示例#1
0
	def request_data(self, request, acc):
		import loader
		l = loader.AsyncLoader()
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirExist(out_dir)
		log.info('requesting user %s info'%(acc['login'],))
		d = os.path.join(util.getTempDir(), 'raw_data') if not out_dir else out_dir
		l.getDcData(self, acc['login'], request, d, out_dir)
		l.start()
示例#2
0
	def onUpdateGeo(self, event):
		'download and process info from server'
		import loader
		l = loader.AsyncLoader()
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		for acc in config.accounts():
			log.info('requesting user %s info'%(acc['login'],))
			d = os.path.join(util.getTempDir(), 'raw_data') if not out_dir else out_dir
			l.getDcData(self, acc['login'], 'known_planets', d)
		l.start()
def bedToFasta(inputBedFile, finalOutputFile, faSequencesDir):
    tempOutputDir = util.getTempDir();
    filePathMinusExtensionFromChromosome = lambda chrom: tempOutputDir + "/" + chrom+"_"+fp.getFileNameParts(inputBedFile).coreFileName;
    pathToInputFaFromChrom = lambda chrom : faSequencesDir+"/"+chrom+".fa";
    bedFilePathFromChromosome = lambda chrom: filePathMinusExtensionFromChromosome(chrom)+".bed"; 
    fastaFilePathFromChromosome = lambda chrom: filePathMinusExtensionFromChromosome(chrom)+".fasta";

    def bedtoolsCommandFromChromosome(chrom): #produces the bedtools command given the chromosome
        return "bedtools getfasta -tab -fi "+pathToInputFaFromChrom(chrom)+" -bed "+bedFilePathFromChromosome(chrom)+ " -fo "+fastaFilePathFromChromosome(chrom);
    
    #step 1: split lines into other files based on 'filter variables' extracted from each line.
    chromosomes = fp.splitLinesIntoOtherFiles(
        fp.getFileHandle(inputBedFile) #the file handle that is the source of the lines
        , util.chainFunctions(fp.trimNewline,fp.splitByTabs) #preprocessing step to be performed on each line
        , fp.lambdaMaker_getAtPosition(0) #filter variable from preprocessed line; in bed files, chromosome is at position 0
        , bedFilePathFromChromosome #function to produce output file path from filter variable
    );

    
    #step 2: kick of parallel threads to run bedtools
    pp.ParalleliserFactory(pp.ParalleliserInfo( #wrapper class - put in place for possible future extensibility.
        #function to execute on each input, in this case each chromosome
        ppko.lambdaProducer_executeAsSystemCall(
            bedtoolsCommandFromChromosome #produces the bedtools command give the chromosome
        ))).getParalleliser([pp.FunctionInputs(args=[chromosome]) for chromosome in chromosomes]).execute();
    
    #concatenate files using cat
    fp.concatenateFiles(finalOutputFile, [fastaFilePathFromChromosome(chrom) for chrom in chromosomes]);
示例#4
0
	def __handleCompressedFile(self, gui, filext, rom, emuParams):

		log.info("__handleCompressedFile")

		# Note: Trying to delete temporary files (from zip or 7z extraction) from last run
		# Do this before launching a new game. Otherwise game could be deleted before launch
		tempDir = os.path.join(util.getTempDir(), 'extracted', self.romCollection.name)
		# check if folder exists
		if not xbmcvfs.exists(tempDir +'\\'):
			log.info("Create temporary folder: " +tempDir)
			xbmcvfs.mkdir(tempDir)

		try:
			if xbmcvfs.exists(tempDir +'\\'):
				log.info("Trying to delete temporary rom files")
				#can't use xbmcvfs.listdir here as it seems to cache the file list and RetroPlayer won't find newly created files anymore
				files = os.listdir(tempDir)
				for f in files:
					#RetroPlayer places savestate files next to the roms. Don't delete these files.
					fname, ext = os.path.splitext(f)
					if(ext not in ('.sav', '.xml', '.png')):
						xbmcvfs.delete(os.path.join(tempDir, f))
		except Exception, (exc):
			log.error("Error deleting files after launch emu: " + str(exc))
			gui.writeMsg(util.localize(32036) + ": " + str(exc))
示例#5
0
    def download_thumb(self, thumburl, destfilename):
        log.info("begin download_thumb using requests module: thumburl = %s" %
                 thumburl)

        # Download file to tmp folder
        tmp = util.joinPath(util.getTempDir(), os.path.basename(destfilename))

        log.info("download_thumb: start downloading to temp file: %s" % tmp)
        response = requests.get(thumburl, stream=True)
        log.info("download_thumb: status code = %s" % response.status_code)
        if response.status_code != 200:
            log.info(
                "download_thumb: invalid response status code. Can't download image."
            )
            return

        with open(tmp, 'wb') as f:
            response.raw.decode_content = True
            shutil.copyfileobj(response.raw, f)

        log.info(
            "download_thumb: copy from temp file to final destination: %s" %
            destfilename)

        # Copy from the tmp folder to the target location
        xbmcvfs.copy(tmp, destfilename)
        xbmcvfs.delete(tmp)
        log.info("end download_thumb")
    def __handleCompressedFile(self, gui, filext, rom, emuParams):

        log.info("__handleCompressedFile")

        # Note: Trying to delete temporary files (from zip or 7z extraction) from last run
        # Do this before launching a new game. Otherwise game could be deleted before launch
        tempDir = os.path.join(util.getTempDir(), 'extracted',
                               self.romCollection.name)
        # check if folder exists
        if not xbmcvfs.exists(tempDir + '\\'):
            log.info("Create temporary folder: " + tempDir)
            xbmcvfs.mkdir(tempDir)

        try:
            if xbmcvfs.exists(tempDir + '\\'):
                log.info("Trying to delete temporary rom files")
                #can't use xbmcvfs.listdir here as it seems to cache the file list and RetroPlayer won't find newly created files anymore
                files = os.listdir(tempDir)
                for f in files:
                    #RetroPlayer places savestate files next to the roms. Don't delete these files.
                    fname, ext = os.path.splitext(f)
                    if (ext not in ('.sav', '.xml', '.png')):
                        xbmcvfs.delete(os.path.join(tempDir, f))
        except Exception, (exc):
            log.error("Error deleting files after launch emu: " + str(exc))
            gui.writeMsg(util.localize(32036) + ": " + str(exc))
示例#7
0
	def cancel_jump(self, evt):

		turn = db.getTurn()
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)

		for acc in config.accounts():
			user_id = int(acc['id'])
			self.pending_actions.user_id = user_id
			
			fleets = []
			fleet_flt = ['owner_id=%s'%(user_id,)]
			
			fleet_name = None #unicode('Fleet')
			# can also filter fleets by names
			#TODO: beware escapes
			if fleet_name:
				fleet_flt.append( 'name="%s"'%(fleet_name,) ) 
			for fleet in db.flyingFleets(turn, fleet_flt):
				#print 'found fleet %s'%(fleet,)
				if fleet['in_transit'] != 0:
					continue
				print 'fleet %s can be stopped'%(fleet,)
			
				self.pending_actions.cancelJump(fleet['id'])
			
			self.perform_actions()
示例#8
0
def processRawData(path):
	log.debug('processing raw data %s'%(path,))
	xml_dir = os.path.join(util.getTempDir(), config.options['data']['raw-xml-dir'])
	util.assureDirExist(xml_dir)
	base = os.path.basename(path)
	xml_path = os.path.join(xml_dir, base[:-3])
	util.unpack(path, xml_path)
	return load_xml(xml_path)
    def __get_temp_dir_path(self, romcollection_name):
        log.info("ArchiveHandler.__get_temp_dir_path")
        temp_dir = os.path.join(util.getTempDir(), 'extracted',
                                romcollection_name)
        # check if folder exists
        if not xbmcvfs.exists(temp_dir + '\\'):
            log.info("Create temporary folder: " + temp_dir)
            xbmcvfs.mkdirs(temp_dir)

        return temp_dir
示例#10
0
	def perform_next_action(self):
		if self.actions_queue==[]:
			return
		login, acts = self.actions_queue[0]
		del self.actions_queue[0]
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)

		l = loader.AsyncLoader()
		l.sendActions(self, login, acts, out_dir)
		l.start()
示例#11
0
	def onUpdate(self, event):
		'download and process info from server'
		import loader
		l = loader.AsyncLoader()
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		for acc in config.accounts():
			if self.command_selected_user and int(acc['id']) != self.map.selected_user_id:
				continue
			log.info('requesting user %s info'%(acc['login'],))
			l.getUserInfo(self, acc['login'], out_dir)
		l.start()
示例#12
0
文件: launcher.py 项目: roeiba/xbmc
def handleCompressedFile(filext, rom, romCollection, emuParams):
	
	#Note: Trying to delete temporary files (from zip or 7z extraction) from last run
	#Do this before launching a new game. Otherwise game could be deleted before launch
	try:
		Logutil.log("Trying to delete temporary rom files", util.LOG_LEVEL_INFO)	
		tempDir = util.getTempDir()
		files = os.listdir(tempDir)
		for file in files:
			os.remove(os.path.join(tempDir, file))
	except Exception, (exc):
		Logutil.log("Error deleting files after launch emu: " +str(exc), util.LOG_LEVEL_ERROR)
		gui.writeMsg(util.localize(35036) +": " +str(exc))
def bedToFastaForAllBedInDirectory(inputDir, finalOutputFile, faSequencesDir):
    inputBedFiles = glob.glob(inputDir+"/*");
    tempDir = util.getTempDir();
    outputFileFromInputFile = lambda inputFile: tempDir + "/" + "fastaExtracted_" + fp.getFileNameParts(inputFile).coreFileName + ".tsv";
    util.executeForAllFilesInDirectory(inputDir, 
        lambda anInput : bedToFasta_function.bedToFasta(anInput, outputFileFromInputFile(anInput), faSequencesDir));

    #concatenate files using cat
    fp.concatenateFiles_preprocess(
        finalOutputFile
        , [outputFileFromInputFile(inputBedFile) for inputBedFile in inputBedFiles]
        , transformation=lambda line,filename: filename+"\t"+line
        , outputTitleFromInputTitle = lambda x : "sourceBed\tchromosomeLocation\tsequence\n");
示例#14
0
	def onUpdate(self, event):
		'download and process info from server'
		l = loader.AsyncLoader()
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		
		for acc in config.accounts():
			if self.command_selected_user and int(acc['id']) != self.map.selected_user_id:
				continue
			log.info('requesting user %s info'%(acc['login'],))
			for msg_type in ['all', 'known_planets', 'fleetsmessages']:
				l.getDcData(self, acc['login'], msg_type, out_dir)
		l.start()
示例#15
0
	def writeNfoElementToFile(self, root, platform, romFile, gameNameFromFile, nfoFile):
		# write file
		try:
			self.indentXml(root)
			tree = ElementTree(root)

			log.info(u"Writing NFO file {0}".format(nfoFile))
			localFile = util.joinPath(util.getTempDir(), os.path.basename(nfoFile))
			tree.write(localFile, encoding="UTF-8", xml_declaration=True)
			xbmcvfs.copy(localFile, nfoFile)
			xbmcvfs.delete(localFile)

		except Exception as exc:
			log.warn(u"Error: Cannot write game nfo for {0}: {1}".format(gameNameFromFile, exc))
示例#16
0
    def writeNfoElementToFile(self, root, platform, romFile, gameNameFromFile,
                              nfoFile):
        # write file
        try:
            self.indentXml(root)
            tree = ElementTree(root)

            log.info(u"Writing NFO file {0}".format(nfoFile))
            localFile = util.joinPath(util.getTempDir(),
                                      os.path.basename(nfoFile))
            tree.write(localFile, encoding="UTF-8", xml_declaration=True)
            xbmcvfs.copy(localFile, nfoFile)
            xbmcvfs.delete(localFile)

        except Exception as exc:
            log.warn(u"Error: Cannot write game nfo for {0}: {1}".format(
                gameNameFromFile, exc))
示例#17
0
def processAllUnpacked():
	xml_dir = os.path.join(util.getTempDir(), config.options['data']['raw-xml-dir'])
	util.assureDirClean(xml_dir)
	log.debug('processing all found data at %s'%(xml_dir,))
	at_least_one = False
	try:
		for file in os.listdir(xml_dir):
			if not file.endswith('.xml'):
				continue
			log.debug('loading %s'%(file,))
			p = os.path.join(xml_dir, file)
			load_xml( p )
			at_least_one = True
		if at_least_one:
			save_load.save()
	except OSError, e:
		log.error('unable to load raw data: %s'%(e,))
示例#18
0
	def update_user(self, user_id):
		l = loader.AsyncLoader()
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		user = store.get_object('user', {'user_id':user_id})
		if not user:
			print 'no user %s found'%(user_id,)
			return
		
		acc = config.users[user['login']]
		if not acc:
			print 'no login/password for user %s specified'%(user['name'],)
			return

		log.info('requesting user %s info'%(acc['login'],))
		l.getUserInfo(self, acc['login'], out_dir)
		l.start()
示例#19
0
def load_sync_data():
	sync_path = config.options['data']['sync_path']
	if not sync_path or sync_path == '':
		print 'sync path not specified, sync not performed'
		return
		
	turns_path = os.path.join(sync_path, 'turns')
	if not os.path.exists(turns_path):
		print 'sync path %s not exist'%(turns_path,)
		return
	available_turns = []
	for f in os.listdir(turns_path):
		available_turns.append(int(f))
	
	if not available_turns:
		print 'no sync data found in %s'%(turns_path,)
		return
	
	load_turn = db.getTurn()
	if not load_turn in available_turns:
		load_turn = max(available_turns)
	
	nick = get_user_nickname()
	
	turn_path = os.path.join(turns_path, str(load_turn))
	for d in os.listdir(turn_path):
		if d == nick:
			continue
		acc_path = os.path.join(turn_path, d)
		print 'load %s turn: %s'%(d, load_turn)
		db.prepareTurn(load_turn)
		
		# do load
		unpack_dir = os.path.join(os.path.join(os.path.join( util.getTempDir(), 'unpack_sync' ), d), str(load_turn))
		util.assureDirClean(unpack_dir)
		for gz_file in os.listdir(acc_path):
			outf = os.path.join(unpack_dir, gz_file)
			if outf.endswith('.gz'):
				outf = outf[:-len('.gz')]
			util.unpack(os.path.join(acc_path, gz_file), outf)
			table_name = os.path.basename(outf)[:-len('.csv')]
			if table_name == db.Db.PROTO or table_name == db.Db.PROTO_ACTION or table_name == db.Db.OPEN_PLANET or table_name == db.Db.USER:
				loadTable(table_name, None, load_turn, None, os.path.dirname(outf))
			else:
				loadTable(table_name, load_turn, None, None, os.path.dirname(outf))
示例#20
0
    def _copylocal(self, romCollection, rom):
        if romCollection.makeLocalCopy:
            localDir = os.path.join(util.getTempDir(), romCollection.name)
            if xbmcvfs.exists(localDir + '\\'):
                log.info("Trying to delete local rom files")
                dirs, files = xbmcvfs.listdir(localDir)
                for f in files:
                    xbmcvfs.delete(os.path.join(localDir, f))
            else:
                log.info("Create temporary folder: " + localDir)
                xbmcvfs.mkdir(localDir)
            localRom = os.path.join(localDir, os.path.basename(str(rom)))
            log.info("Creating local copy: " + str(localRom))
            if xbmcvfs.copy(rom, localRom):
                log.info("Local copy created")
            rom = localRom

        return rom
示例#21
0
文件: action.py 项目: bogolt/dclord
	def do_perform(self):
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		log.debug('preparing directory %s to load action result'%(out_dir,))

		l = loader.AsyncLoader()
		at_leat_one = False
		for user_id, acts in self.stored_actions.iteritems():
			if len(acts) == 0:
				continue
			user = store.get_user(user_id)
			if 'login' in user and user['login']:
				log.debug('Storing actions for user %s'%(user_id,))
				l.sendActions(self, config.get_user_login(user['user_id']), self.prepare_actions_request(user_id), out_dir)
				at_leat_one = True
		
		# clear action list
		self.remove_action_items()
		self.stored_actions = {}
		
		if at_leat_one:
			l.start()
示例#22
0
    def download_thumb(self, thumburl, destfilename):
        log.info("begin download_thumb using requests module: thumburl = %s" % thumburl)

        # Download file to tmp folder
        tmp = util.joinPath(util.getTempDir(), os.path.basename(destfilename))

        log.info("download_thumb: start downloading to temp file: %s" % tmp)
        response = requests.get(thumburl, stream=True)
        log.info("download_thumb: status code = %s" %response.status_code)
        if response.status_code != 200:
            log.info("download_thumb: invalid response status code. Can't download image.")
            return

        with open(tmp, 'wb') as f:
            response.raw.decode_content = True
            shutil.copyfileobj(response.raw, f)

        log.info("download_thumb: copy from temp file to final destination: %s" % destfilename)

        # Copy from the tmp folder to the target location
        xbmcvfs.copy(tmp, destfilename)
        xbmcvfs.delete(tmp)
        log.info("end download_thumb")
示例#23
0
	def getUserInfo(self, cb, login, out_dir = None):
		d = os.path.join(util.getTempDir(), 'raw_data') if not out_dir else out_dir
		self.getDcData(cb, login, 'all', d)
		if 0!=int(config.options['data']['load_known_planets']):
			self.getDcData(cb, login, 'known_planets', d)
示例#24
0
    def __buildCmd(self, gui, filenameRows, gameRow, calledFromSkin):
        log.info("launcher.buildCmd")

        compressedExtensions = ['7z', 'zip']

        cmd = ""
        precmd = ""
        postcmd = ""

        emuCommandLine = self.romCollection.emulatorCmd
        log.info("emuCommandLine: " + emuCommandLine)
        log.info("preCmdLine: " + self.romCollection.preCmd)
        log.info("postCmdLine: " + self.romCollection.postCmd)

        # handle savestates
        stateFile = self.__checkGameHasSaveStates(gameRow, filenameRows)

        if stateFile == '':
            emuParams = self.romCollection.emulatorParams
        else:
            emuParams = self.romCollection.saveStateParams
            if self.escapeCmd:
                stateFile = re.escape(stateFile)
            emuParams = emuParams.replace('%statefile%', stateFile)
            emuParams = emuParams.replace('%STATEFILE%', stateFile)
            emuParams = emuParams.replace('%Statefile%', stateFile)

        # params could be: {-%I% %ROM%}
        # we have to repeat the part inside the brackets and replace the %I% with the current index
        emuParams, partToRepeat = self.__prepareMultiRomCommand(emuParams)

        # ask for disc number if multidisc game
        diskName = ""
        if self.romCollection.diskPrefix != '' and '%I%' not in emuParams:
            log.info("Getting Multiple Disc Parameter")
            options = []
            for disk in filenameRows:
                gamename = os.path.basename(disk[0])
                match = re.search(self.romCollection.diskPrefix.lower(),
                                  str(gamename).lower())
                if match:
                    disk = gamename[match.start():match.end()]
                    options.append(disk)
            if len(options) > 1 and not calledFromSkin:
                diskNum = xbmcgui.Dialog().select(
                    util.localize(32164) + ': ', options)
                if diskNum < 0:
                    # don't launch game
                    log.info("No disc was chosen. Won't launch game")
                    return "", "", "", None
                else:
                    diskName = options[diskNum]
                    log.info("Chosen Disc: %s" % diskName)

        # insert game specific command
        gameCmd = ''
        if gameRow[util.GAME_gameCmd] is not None:
            gameCmd = str(gameRow[util.GAME_gameCmd])
        # be case insensitive with (?i)
        emuParams = re.sub('(?i)%gamecmd%', gameCmd, emuParams)

        log.info("emuParams: " + emuParams)

        fileindex = int(0)
        for fileNameRow in filenameRows:
            rom = fileNameRow[0]
            log.info("rom: " + str(rom))

            if self.romCollection.makeLocalCopy:
                localDir = os.path.join(util.getTempDir(),
                                        self.romCollection.name)
                if xbmcvfs.exists(localDir + '\\'):
                    log.info("Trying to delete local rom files")
                    dirs, files = xbmcvfs.listdir(localDir)
                    for f in files:
                        xbmcvfs.delete(os.path.join(localDir, f))
                localRom = os.path.join(localDir, os.path.basename(str(rom)))
                log.info("Creating local copy: " + str(localRom))
                if xbmcvfs.copy(rom, localRom):
                    log.info("Local copy created")
                rom = localRom

            # If it's a .7z file
            # Don't extract zip files in case of savestate handling and when called From skin
            filext = rom.split('.')[-1]
            roms = [rom]
            if filext in compressedExtensions and not self.romCollection.doNotExtractZipFiles and stateFile == '' and not calledFromSkin:
                roms = self.__handleCompressedFile(gui, filext, rom, emuParams)
                log.debug("roms compressed = " + str(roms))
                if len(roms) == 0:
                    return "", "", "", None

            # no use for complete cmd as we just need the game name
            if self.romCollection.useBuiltinEmulator:
                log.debug("roms = " + str(roms))
                return "", "", "", roms

            del rom

            for rom in roms:
                precmd = ""
                postcmd = ""
                if fileindex == 0:
                    emuParams = self.__replacePlaceholdersInParams(
                        emuParams, rom, gameRow)
                    if self.escapeCmd:
                        emuCommandLine = re.escape(emuCommandLine)

                    if self.romCollection.name in [
                            'Linux', 'Macintosh', 'Windows'
                    ]:
                        cmd = self.__replacePlaceholdersInParams(
                            emuCommandLine, rom, gameRow)
                    else:
                        cmd = '\"' + emuCommandLine + '\" ' + emuParams.replace(
                            '%I%', str(fileindex))
                else:
                    newrepl = partToRepeat
                    newrepl = self.__replacePlaceholdersInParams(
                        newrepl, rom, gameRow)
                    if self.escapeCmd:
                        emuCommandLine = re.escape(emuCommandLine)

                    newrepl = newrepl.replace('%I%', str(fileindex))
                    cmd += ' ' + newrepl

                cmdprefix = ''

                if self.env == "win32":
                    cmdprefix = 'call '

                precmd = cmdprefix + self.__replacePlaceholdersInParams(
                    self.romCollection.preCmd, rom, gameRow)
                postcmd = cmdprefix + self.__replacePlaceholdersInParams(
                    self.romCollection.postCmd, rom, gameRow)

                fileindex += 1

        # A disk was chosen by the user, select it here
        if diskName:
            log.info("Choosing Disk: " + str(diskName))
            match = re.search(self.romCollection.diskPrefix.lower(),
                              cmd.lower())
            replString = cmd[match.start():match.end()]
            cmd = cmd.replace(replString, diskName)

        return cmd, precmd, postcmd, roms
示例#25
0
class NfoWriter:

    Settings = util.getSettings()

    def __init__(self):
        pass

    def exportLibrary(self, gui):
        Logutil.log("Begin exportLibrary", util.LOG_LEVEL_INFO)

        gdb = gui.gdb
        romCollections = gui.config.romCollections

        progressDialog = dialogprogress.ProgressDialogGUI()
        progressDialog.writeMsg(util.localize(32169), "", "")
        continueExport = True
        rccount = 1

        for romCollection in gui.config.romCollections.values():

            progDialogRCHeader = util.localize(32170) + " (%i / %i): %s" % (
                rccount, len(romCollections), romCollection.name)
            rccount = rccount + 1

            Logutil.log("export Rom Collection: " + romCollection.name,
                        util.LOG_LEVEL_INFO)
            gameCount = 1

            #get all games for this Rom Collection
            games = Game(gdb).getFilteredGames(romCollection.id, 0, 0, 0,
                                               False, '0 = 0')
            progressDialog.itemCount = len(games) + 1

            for gameRow in games:

                gamename = self.getGameProperty(gameRow[util.ROW_NAME])

                continueExport = progressDialog.writeMsg(
                    progDialogRCHeader,
                    util.localize(32171) + ": " + str(gamename), "", gameCount)
                if (not continueExport):
                    Logutil.log('Game export canceled by user',
                                util.LOG_LEVEL_INFO)
                    break

                gameCount = gameCount + 1

                plot = self.getGameProperty(gameRow[util.GAME_description])

                publisher = self.getGamePropertyFromCache(
                    gameRow, gui.publisherDict, util.GAME_publisherId,
                    util.ROW_NAME)
                developer = self.getGamePropertyFromCache(
                    gameRow, gui.developerDict, util.GAME_developerId,
                    util.ROW_NAME)
                year = self.getGamePropertyFromCache(gameRow, gui.yearDict,
                                                     util.GAME_yearId,
                                                     util.ROW_NAME)

                genreList = []
                try:
                    cachingOptionStr = self.Settings.getSetting(
                        util.SETTING_RCB_CACHINGOPTION)
                    if (cachingOptionStr == 'CACHEALL'):
                        genre = gui.genreDict[gameRow[util.ROW_ID]]
                    else:
                        genres = Genre(gdb).getGenresByGameId(
                            gameRow[util.ROW_ID])
                        if (genres != None):
                            for i in range(0, len(genres)):
                                genreRow = genres[i]
                                genreList.append(genreRow[util.ROW_NAME])
                except:
                    pass

                players = self.getGameProperty(gameRow[util.GAME_maxPlayers])
                rating = self.getGameProperty(gameRow[util.GAME_rating])
                votes = self.getGameProperty(gameRow[util.GAME_numVotes])
                url = self.getGameProperty(gameRow[util.GAME_url])
                region = self.getGameProperty(gameRow[util.GAME_region])
                media = self.getGameProperty(gameRow[util.GAME_media])
                perspective = self.getGameProperty(
                    gameRow[util.GAME_perspective])
                controller = self.getGameProperty(
                    gameRow[util.GAME_controllerType])
                originalTitle = self.getGameProperty(
                    gameRow[util.GAME_originalTitle])
                alternateTitle = self.getGameProperty(
                    gameRow[util.GAME_alternateTitle])
                version = self.getGameProperty(gameRow[util.GAME_version])

                #user settings
                isFavorite = self.getGameProperty(
                    gameRow[util.GAME_isFavorite])
                launchCount = self.getGameProperty(
                    gameRow[util.GAME_launchCount])

                romFiles = File(gdb).getRomsByGameId(gameRow[util.ROW_ID])
                romFile = ''
                if (romFiles != None and len(romFiles) > 0):
                    romFile = romFiles[0][0]
                gamenameFromFile = helper.getGamenameFromFilename(
                    romFile, romCollection)
                artworkfiles = {}
                artworkurls = []

                self.createNfoFromDesc(
                    gamename, plot, romCollection.name, publisher, developer,
                    year, players, rating, votes, url, region, media,
                    perspective, controller, originalTitle, alternateTitle,
                    version, genreList, isFavorite, launchCount, romFile,
                    gamenameFromFile, artworkfiles, artworkurls)

        progressDialog.writeMsg("", "", "", -1)
        del progressDialog

    def createNfoFromDesc(self, gamename, plot, romCollectionName, publisher,
                          developer, year, players, rating, votes, url, region,
                          media, perspective, controller, originalTitle,
                          alternateTitle, version, genreList, isFavorite,
                          launchCount, romFile, gameNameFromFile, artworkfiles,
                          artworkurls):

        Logutil.log("Begin createNfoFromDesc", util.LOG_LEVEL_INFO)

        root = Element('game')
        SubElement(root, 'title').text = gamename
        SubElement(root, 'originalTitle').text = originalTitle
        SubElement(root, 'alternateTitle').text = alternateTitle
        SubElement(root, 'platform').text = romCollectionName
        SubElement(root, 'plot').text = plot
        SubElement(root, 'publisher').text = publisher
        SubElement(root, 'developer').text = developer
        SubElement(root, 'year').text = year

        for genre in genreList:
            SubElement(root, 'genre').text = str(genre)

        SubElement(root, 'detailUrl').text = url
        SubElement(root, 'maxPlayer').text = players
        SubElement(root, 'region').text = region
        SubElement(root, 'media').text = media
        SubElement(root, 'perspective').text = perspective
        SubElement(root, 'controller').text = controller
        SubElement(root, 'version').text = version
        SubElement(root, 'rating').text = rating
        SubElement(root, 'votes').text = votes

        SubElement(root, 'isFavorite').text = isFavorite
        SubElement(root, 'launchCount').text = launchCount

        for artworktype in artworkfiles.keys():

            local = ''
            online = ''
            try:
                local = artworkfiles[artworktype][0]
                online = str(artworkurls[artworktype.name])
            except:
                pass

            try:
                SubElement(root, 'thumb', {
                    'type': artworktype.name,
                    'local': local
                }).text = online
            except Exception, (exc):
                Logutil.log('Error writing artwork url: ' + str(exc),
                            util.LOG_LEVEL_WARNING)
                pass

        #write file
        try:
            util.indentXml(root)
            tree = ElementTree(root)

            nfoFile = self.getNfoFilePath(romCollectionName, romFile,
                                          gameNameFromFile)

            if (nfoFile != ''):
                if (nfoFile.startswith('smb://')):
                    localFile = util.joinPath(util.getTempDir(),
                                              os.path.basename(nfoFile))
                    tree.write(localFile)
                    xbmcvfs.copy(localFile, nfoFile)
                    xbmcvfs.delete(localFile)
                else:
                    tree.write(nfoFile)

        except Exception, (exc):
            Logutil.log("Error: Cannot write file game.nfo: " + str(exc),
                        util.LOG_LEVEL_WARNING)
示例#26
0
文件: launcher.py 项目: roeiba/xbmc
		match = re.search(romCollection.diskPrefix.lower(), str(names).lower())
	
	if '%I%' in emuParams and match:
		Logutil.log("Loading %d archives" % len(names), util.LOG_LEVEL_INFO)
		
		try:
			archives = getArchives(filext, rom, names)
		except Exception, (exc):
			Logutil.log('Error handling compressed file: ' +str(exc), util.LOG_LEVEL_ERROR)
			return []		
		
		if(archives == None):
			Logutil.log('Error handling compressed file', util.LOG_LEVEL_WARNING)
			return []
		for archive in archives:					
			newPath = os.path.join(util.getTempDir(), archive[0])
			fp = open(newPath, 'wb')
			fp.write(archive[1])
			fp.close()
			roms.append(newPath)
		
	elif len(names) > 1:
		Logutil.log("The Archive has %d files" % len(names), util.LOG_LEVEL_INFO)
		chosenROM = xbmcgui.Dialog().select('Choose a ROM', names)
	elif len(names) == 1:
		Logutil.log("Archive only has one file inside; picking that one", util.LOG_LEVEL_INFO)
		chosenROM = 0
	else:
		Logutil.log("Archive had no files inside!", util.LOG_LEVEL_ERROR)
		return []
示例#27
0
    def __handleCompressedFile(self, gui, filext, rom, emuParams):

        log.info("__handleCompressedFile")

        # Note: Trying to delete temporary files (from zip or 7z extraction) from last run
        # Do this before launching a new game. Otherwise game could be deleted before launch
        tempDir = os.path.join(util.getTempDir(), 'extracted', self.romCollection.name)
        # check if folder exists
        if not xbmcvfs.exists(tempDir + '\\'):
            log.info("Create temporary folder: " + tempDir)
            xbmcvfs.mkdir(tempDir)

        try:
            if xbmcvfs.exists(tempDir + '\\'):
                log.info("Trying to delete temporary rom files")
                #can't use xbmcvfs.listdir here as it seems to cache the file list and RetroPlayer won't find newly created files anymore
                files = os.listdir(tempDir)
                for f in files:
                    #RetroPlayer places savestate files next to the roms. Don't delete these files.
                    fname, ext = os.path.splitext(f)
                    if ext not in ('.sav', '.xml', '.png'):
                        xbmcvfs.delete(os.path.join(tempDir, f))
        except Exception as exc:
            log.error("Error deleting files after launch emu: " + str(exc))
            gui.writeMsg(util.localize(32036) + ": " + str(exc))

        roms = []

        log.info("Treating file as a compressed archive")

        try:
            names = self.__getNames(filext, rom)
        except Exception as exc:
            log.error("Error handling compressed file: " + str(exc))
            return []

        if names is None:
            log.error("Error handling compressed file")
            return []

        chosenROM = -1

        # check if we should handle multiple roms
        match = False
        if self.romCollection.diskPrefix != '':
            match = re.search(self.romCollection.diskPrefix.lower(), str(names).lower())

        if '%I%' in emuParams and match:
            log.info("Loading %d archives" % len(names))

            try:
                archives = self.__getArchives(filext, rom, names)
            except Exception as exc:
                log.error("Error handling compressed file: " + str(exc))
                return []

            if archives is None:
                log.warning("Error handling compressed file")
                return []
            for archive in archives:
                newPath = os.path.join(tempDir, archive[0])
                fp = open(newPath, 'wb')
                fp.write(archive[1])
                fp.close()
                roms.append(newPath)

        elif len(names) > 1:
            log.info("The Archive has %d files" % len(names))
            chosenROM = xbmcgui.Dialog().select('Choose a ROM', names)
        elif len(names) == 1:
            log.info("Archive only has one file inside; picking that one")
            chosenROM = 0
        else:
            log.error("Archive had no files inside!")
            return []

        if chosenROM != -1:
            # Extract all files to %TMP%
            archives = self.__getArchives(filext, rom, names)
            if archives is None:
                log.warn("Error handling compressed file")
                return []
            for archive in archives:
                newPath = os.path.join(tempDir, archive[0])
                log.info("Putting extracted file in %s" % newPath)
                fo = open(str(newPath), 'wb')
                fo.write(archive[1])
                fo.close()

            # Point file name to the chosen file and continue as usual
            roms = [os.path.join(tempDir, names[chosenROM])]

        return roms
示例#28
0
	def onExploreGeoAll(self, _):
		'upload pending events on server'
		
		explore_owned_planets = True
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		for acc in config.accounts():
			if not 'id' in acc:
				continue
			user_id = int(acc['id'])
				
			log.info('requesting user %s info'%(acc['login'],))
			# find if there is any explore-capable fleets over unexplored planets
			# or simply tell explore to every unit =))) game server will do the rest
			
			#1. find all fleets above empty planets
			
			# get fleet position, check if planet geo is unknown
			fleet_planet = {}
			pl = {}
			
			for fleet in store.iter_objects_list('fleet', {'user_id':acc['id']} ):
				#print 'got fleet %s'%(fleet,)
				coord = get_coord(fleet)
				
				if coord in pl:
					pl[coord].add(fleet['fleet_id'])
					continue

				planet = store.get_object('planet', {'x':coord[0], 'y':coord[1]})
				#check holes and stars
				if not planet:
					continue
				
				# check if already explored
				if 'o' in planet and planet['o']:
					continue
				
				if not coord in pl:
					pl[coord] = set()
				pl[ coord ].add(fleet['fleet_id'])
				#print 'Add to exploration list planet %s'%(planet,)
			
			acts = {}
			
			# get all fleet units, check if explore capable
			for coord, planet_fleets in pl.iteritems():
				for fleet_id in planet_fleets:
					for unit in store.get_fleet_units(fleet_id):
						#print '%s %s unit %s'%(coord, fleet_id, unit)
						# ok unit
						bc = unit['proto_id']
						
						#for proto in db.prototypes(['id=%s'%(bc,)]):
						#	print 'proto %s'%(proto,)

						#type 1 probably geo explore
						action_geo_explore = store.get_object('proto_action',{'proto_id':bc, 'proto_action_id':request.RequestMaker.GEO_EXPLORE})
						if action_geo_explore:
							acts[coord] = unit['unit_id']
							break
					# no need to request more then one explore of a single planet
					if coord in acts:
						break

			self.pending_actions.user_id = int(acc['id'])
			#self.pendingActions[int(acc['id'])] = actions
			#hw_planet = db.getUserHw(acc['id'])
			#actions.createNewFleet(hw_planet, 'a_new_shiny_fleet')
			
			at_least_one = False
			for coord, unit_id in acts.iteritems():
				fleet_unit = store.get_object('fleet_unit', {'unit_id':unit_id})
				self.actions.add_action(action.ActionStore(user_id, unit_id, fleet_unit['fleet_id'], coord, action.Action.GEO_EXPLORE))
				#self.pending_actions.explore_planet( coord, unit_id )
				at_least_one = True
			
			if at_least_one:
				self.perform_actions()
示例#29
0
文件: loader.py 项目: bogolt/dclord
	def getKnownPlanets(self, cb, login, out_dir = None):
		d = os.path.join(util.getTempDir(), 'raw_data') if not out_dir else out_dir
		self.getDcData(cb, login, 'known_planets', d)
示例#30
0
				try:
					if(dialogDict != ''):
						progDialogRCHeader = dialogDict["dialogHeaderKey"]
						gamenameFromFile = dialogDict["gameNameKey"]
						scraperSiteName = dialogDict["scraperSiteKey"]
						fileCount = dialogDict["fileCountKey"]
						gui.writeMsg(progDialogRCHeader, util.localize(40023) +": " +gamenameFromFile, str(scraperSiteName[thumbKey]) + " - downloading art", fileCount)
				except:
					pass

				# fetch thumbnail and save to filepath
				try:					
					target = fileName
					if(fileName.startswith('smb://')):
						#download file to local folder and copy it to smb path with xbmcvfs
						target = util.joinPath(util.getTempDir(), os.path.basename(fileName))
											
					req = urllib2.Request(thumbUrl)
					req.add_unredirected_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31')
					f = open(target,'wb')
					f.write(urllib2.urlopen(req).read())
					f.close()
						
					if(fileName.startswith('smb://')):	
						xbmcvfs.copy(target, fileName)
						xbmcvfs.delete(target)
						
				except Exception, (exc):
					# xbmcgui.Dialog().ok(util.localize(35012), util.localize(35011))
					Logutil.log("Could not create file: '%s'. Error message: '%s'" %(str(fileName), str(exc)), util.LOG_LEVEL_ERROR)
					return False, artworkurls
def buildCmd(filenameRows, romCollection, gameRow, escapeCmd, calledFromSkin):		
	Logutil.log('launcher.buildCmd', util.LOG_LEVEL_INFO)
		
	compressedExtensions = ['7z', 'zip']
	
	cmd = ""
	precmd = ""
	postcmd = ""
	
	emuCommandLine = romCollection.emulatorCmd
	Logutil.log('emuCommandLine: ' +emuCommandLine, util.LOG_LEVEL_INFO)
	Logutil.log('preCmdLine: ' +romCollection.preCmd, util.LOG_LEVEL_INFO)
	Logutil.log('postCmdLine: ' +romCollection.postCmd, util.LOG_LEVEL_INFO)

	#handle savestates	
	stateFile = checkGameHasSaveStates(romCollection, gameRow, filenameRows, escapeCmd)
		
	if(stateFile == ''):
		emuParams = romCollection.emulatorParams
	else:		
		emuParams = romCollection.saveStateParams
		if(escapeCmd):
			stateFile = re.escape(stateFile)
		emuParams = emuParams.replace('%statefile%', stateFile)
		emuParams = emuParams.replace('%STATEFILE%', stateFile)
		emuParams = emuParams.replace('%Statefile%', stateFile)
	
	#params could be: {-%I% %ROM%}
	#we have to repeat the part inside the brackets and replace the %I% with the current index
	emuParams, partToRepeat = prepareMultiRomCommand(emuParams)

	#ask for disc number if multidisc game
	diskName = ""
	if(romCollection.diskPrefix != '' and not '%I%' in emuParams):
		Logutil.log("Getting Multiple Disc Parameter", util.LOG_LEVEL_INFO)
		options = []
		for disk in filenameRows:
			gamename = os.path.basename(disk[0])
			match = re.search(romCollection.diskPrefix.lower(), str(gamename).lower())
			if(match):
				disk = gamename[match.start():match.end()]
				options.append(disk)
		if(len(options) > 1 and not calledFromSkin):
			diskNum = xbmcgui.Dialog().select(util.localize(32164) +': ', options)
			if(diskNum < 0):
				#don't launch game
				Logutil.log("No disc was chosen. Won't launch game", util.LOG_LEVEL_INFO)
				return "", "", "", None
			else:
				diskName = options[diskNum]
				Logutil.log('Chosen Disc: %s' % diskName, util.LOG_LEVEL_INFO)

	#insert game specific command
	gameCmd = ''
	if(gameRow[util.GAME_gameCmd] != None):
		gameCmd = str(gameRow[util.GAME_gameCmd])
	#be case insensitive with (?i)
	emuParams = re.sub('(?i)%gamecmd%', gameCmd, emuParams)
	
	Logutil.log('emuParams: ' +emuParams, util.LOG_LEVEL_INFO)
	
	fileindex = int(0)
	for fileNameRow in filenameRows:
		rom = fileNameRow[0]
		Logutil.log('rom: ' +str(rom), util.LOG_LEVEL_INFO)
		
		if romCollection.makeLocalCopy:
			localDir = os.path.join(util.getTempDir(), romCollection.name)
			if os.path.exists(localDir):
				Logutil.log("Trying to delete local rom files", util.LOG_LEVEL_INFO)    
				files = os.listdir(localDir)
				for file in files:
					os.remove(os.path.join(localDir, file))
			localRom = os.path.join(localDir, os.path.basename(str(rom)))
			Logutil.log('Creating local copy: ' + str(localRom), util.LOG_LEVEL_INFO)
			if xbmcvfs.copy(rom, localRom):
				Logutil.log('Local copy created', util.LOG_LEVEL_INFO)
			rom = localRom

		# If it's a .7z file
		# Don't extract zip files in case of savestate handling and when called From skin
		filext = rom.split('.')[-1]
		roms = [rom]
		if filext in compressedExtensions and not romCollection.doNotExtractZipFiles and stateFile == '' and not calledFromSkin:
			roms = handleCompressedFile(filext, rom, romCollection, emuParams)
			print "roms compressed = " +str(roms)
			if len(roms) == 0:
				return "", "", "", None
			
		#no use for complete cmd as we just need the game name
		if (romCollection.useBuiltinEmulator):
			print "roms = " +str(roms)
			return "", "", "", roms
		
		del rom
				
		for rom in roms:
			precmd = ""
			postcmd = ""
			if fileindex == 0:
				emuParams = replacePlaceholdersInParams(emuParams, rom, romCollection, gameRow, escapeCmd)
				if (escapeCmd):
					emuCommandLine = re.escape(emuCommandLine)				
				
				if (os.environ.get( "OS", "xbox" ) == "xbox"):
					cmd = replacePlaceholdersInParams(emuCommandLine, rom, romCollection, gameRow, escapeCmd)
				elif (romCollection.name == 'Linux' or romCollection.name == 'Macintosh' or romCollection.name == 'Windows'):
					cmd = replacePlaceholdersInParams(emuCommandLine, rom, romCollection, gameRow, escapeCmd)
				else:
					cmd = '\"' +emuCommandLine +'\" ' +emuParams.replace('%I%', str(fileindex))
			else:
				newrepl = partToRepeat
				newrepl = replacePlaceholdersInParams(newrepl, rom, romCollection, gameRow, escapeCmd)
				if (escapeCmd):
					emuCommandLine = re.escape(emuCommandLine)

				newrepl = newrepl.replace('%I%', str(fileindex))
				cmd += ' ' +newrepl
				
			cmdprefix = ''
			env = ( os.environ.get( "OS", "win32" ), "win32", )[ os.environ.get( "OS", "win32" ) == "xbox" ]
			if(env == "win32"):
				cmdprefix = 'call '
				
			precmd = cmdprefix + replacePlaceholdersInParams(romCollection.preCmd, rom, romCollection, gameRow, escapeCmd)
			postcmd = cmdprefix + replacePlaceholdersInParams(romCollection.postCmd, rom, romCollection, gameRow, escapeCmd)
						
			fileindex += 1

	#A disk was chosen by the user, select it here
	if (diskName):
		Logutil.log("Choosing Disk: " +str(diskName),util.LOG_LEVEL_INFO)
		match = re.search(romCollection.diskPrefix.lower(), cmd.lower())
		replString = cmd[match.start():match.end()]
		cmd = cmd.replace(replString, diskName)
		
			
	return cmd, precmd, postcmd, roms
def buildCmd(filenameRows, romCollection, gameRow, escapeCmd, calledFromSkin):
    Logutil.log('launcher.buildCmd', util.LOG_LEVEL_INFO)

    compressedExtensions = ['7z', 'zip']

    cmd = ""
    precmd = ""
    postcmd = ""

    emuCommandLine = romCollection.emulatorCmd
    Logutil.log('emuCommandLine: ' + emuCommandLine, util.LOG_LEVEL_INFO)
    Logutil.log('preCmdLine: ' + romCollection.preCmd, util.LOG_LEVEL_INFO)
    Logutil.log('postCmdLine: ' + romCollection.postCmd, util.LOG_LEVEL_INFO)

    #handle savestates
    stateFile = checkGameHasSaveStates(romCollection, gameRow, filenameRows,
                                       escapeCmd)

    if (stateFile == ''):
        emuParams = romCollection.emulatorParams
    else:
        emuParams = romCollection.saveStateParams
        if (escapeCmd):
            stateFile = re.escape(stateFile)
        emuParams = emuParams.replace('%statefile%', stateFile)
        emuParams = emuParams.replace('%STATEFILE%', stateFile)
        emuParams = emuParams.replace('%Statefile%', stateFile)

    #params could be: {-%I% %ROM%}
    #we have to repeat the part inside the brackets and replace the %I% with the current index
    emuParams, partToRepeat = prepareMultiRomCommand(emuParams)

    #ask for disc number if multidisc game
    diskName = ""
    if (romCollection.diskPrefix != '' and not '%I%' in emuParams):
        Logutil.log("Getting Multiple Disc Parameter", util.LOG_LEVEL_INFO)
        options = []
        for disk in filenameRows:
            gamename = os.path.basename(disk[0])
            match = re.search(romCollection.diskPrefix.lower(),
                              str(gamename).lower())
            if (match):
                disk = gamename[match.start():match.end()]
                options.append(disk)
        if (len(options) > 1 and not calledFromSkin):
            diskNum = xbmcgui.Dialog().select(
                util.localize(32164) + ': ', options)
            if (diskNum < 0):
                #don't launch game
                Logutil.log("No disc was chosen. Won't launch game",
                            util.LOG_LEVEL_INFO)
                return "", "", "", None
            else:
                diskName = options[diskNum]
                Logutil.log('Chosen Disc: %s' % diskName, util.LOG_LEVEL_INFO)

    #insert game specific command
    gameCmd = ''
    if (gameRow[util.GAME_gameCmd] != None):
        gameCmd = str(gameRow[util.GAME_gameCmd])
    #be case insensitive with (?i)
    emuParams = re.sub('(?i)%gamecmd%', gameCmd, emuParams)

    Logutil.log('emuParams: ' + emuParams, util.LOG_LEVEL_INFO)

    fileindex = int(0)
    for fileNameRow in filenameRows:
        rom = fileNameRow[0]
        Logutil.log('rom: ' + str(rom), util.LOG_LEVEL_INFO)

        if romCollection.makeLocalCopy:
            localDir = os.path.join(util.getTempDir(), romCollection.name)
            if os.path.exists(localDir):
                Logutil.log("Trying to delete local rom files",
                            util.LOG_LEVEL_INFO)
                files = os.listdir(localDir)
                for file in files:
                    os.remove(os.path.join(localDir, file))
            localRom = os.path.join(localDir, os.path.basename(str(rom)))
            Logutil.log('Creating local copy: ' + str(localRom),
                        util.LOG_LEVEL_INFO)
            if xbmcvfs.copy(rom, localRom):
                Logutil.log('Local copy created', util.LOG_LEVEL_INFO)
            rom = localRom

        # If it's a .7z file
        # Don't extract zip files in case of savestate handling and when called From skin
        filext = rom.split('.')[-1]
        roms = [rom]
        if filext in compressedExtensions and not romCollection.doNotExtractZipFiles and stateFile == '' and not calledFromSkin:
            roms = handleCompressedFile(filext, rom, romCollection, emuParams)
            print "roms compressed = " + str(roms)
            if len(roms) == 0:
                return "", "", "", None

        #no use for complete cmd as we just need the game name
        if (romCollection.useBuiltinEmulator):
            print "roms = " + str(roms)
            return "", "", "", roms

        del rom

        for rom in roms:
            precmd = ""
            postcmd = ""
            if fileindex == 0:
                emuParams = replacePlaceholdersInParams(
                    emuParams, rom, romCollection, gameRow, escapeCmd)
                if (escapeCmd):
                    emuCommandLine = re.escape(emuCommandLine)

                if (os.environ.get("OS", "xbox") == "xbox"):
                    cmd = replacePlaceholdersInParams(emuCommandLine, rom,
                                                      romCollection, gameRow,
                                                      escapeCmd)
                elif (romCollection.name == 'Linux'
                      or romCollection.name == 'Macintosh'
                      or romCollection.name == 'Windows'):
                    cmd = replacePlaceholdersInParams(emuCommandLine, rom,
                                                      romCollection, gameRow,
                                                      escapeCmd)
                else:
                    cmd = '\"' + emuCommandLine + '\" ' + emuParams.replace(
                        '%I%', str(fileindex))
            else:
                newrepl = partToRepeat
                newrepl = replacePlaceholdersInParams(newrepl, rom,
                                                      romCollection, gameRow,
                                                      escapeCmd)
                if (escapeCmd):
                    emuCommandLine = re.escape(emuCommandLine)

                newrepl = newrepl.replace('%I%', str(fileindex))
                cmd += ' ' + newrepl

            cmdprefix = ''
            env = (
                os.environ.get("OS", "win32"),
                "win32",
            )[os.environ.get("OS", "win32") == "xbox"]
            if (env == "win32"):
                cmdprefix = 'call '

            precmd = cmdprefix + replacePlaceholdersInParams(
                romCollection.preCmd, rom, romCollection, gameRow, escapeCmd)
            postcmd = cmdprefix + replacePlaceholdersInParams(
                romCollection.postCmd, rom, romCollection, gameRow, escapeCmd)

            fileindex += 1

    #A disk was chosen by the user, select it here
    if (diskName):
        Logutil.log("Choosing Disk: " + str(diskName), util.LOG_LEVEL_INFO)
        match = re.search(romCollection.diskPrefix.lower(), cmd.lower())
        replString = cmd[match.start():match.end()]
        cmd = cmd.replace(replString, diskName)

    return cmd, precmd, postcmd, roms
示例#33
0
	def onExploreGeoAll(self, _):
		'upload pending events on server'
		
		turn = db.getTurn()
		explore_owned_planets = True
		
		out_dir = os.path.join(util.getTempDir(), config.options['data']['raw-dir'])
		util.assureDirClean(out_dir)
		for acc in config.accounts():
			log.info('requesting user %s info'%(acc['login'],))
			# find if there is any explore-capable fleets over unexplored planets
			# or simply tell explore to every unit =))) game server will do the rest
			
			#1. find all fleets above empty planets
			
			# get fleet position, check if planet geo is unknown
			fleet_planet = {}
			pl = {}
			
			for fleet in db.fleets(turn, ['owner_id=%s'%(acc['id'],)] ):
				print 'got fleet %s'%(fleet,)
				coord = get_coord(fleet)
				cfilter = filter_coord(coord)
				for planet in db.planets(turn, cfilter):
					# skip if occupied
					if planet['owner_id'] and not explore_owned_planets:
						continue
					if planet['o'] and planet['e'] and planet['m'] and planet['t']:
						continue
					#check holes and stars
					if not db.is_planet(coord):
						print '%s not a planet'%(coord,)
						continue
					if not coord in pl:
						pl[coord] = set()
					pl[ coord ].add(fleet['id'])
					print 'planet unexplored %s'%(planet,)
			
			acts = {}
			
			# get all fleet units, check if explore capable
			for coord, planet_fleets in pl.iteritems():
				for fleet_id in planet_fleets:
					for unit in db.units(turn, ['fleet_id=%s'%(fleet_id,)]):
						print '%s %s unit %s'%(coord, fleet_id, unit)
						# ok unit
						bc = unit['class']
						
						#for proto in db.prototypes(['id=%s'%(bc,)]):
						#	print 'proto %s'%(proto,)

						#type 1 probably geo explore
						for act in db.proto_actions(['proto_id=%s'%(bc,), 'type=1']):
							#print 'ACTION: %s %s %s'%(coord, bc, act)
							acts[coord] = unit['id']

			self.pending_actions.user_id = int(acc['id'])
			#self.pendingActions[int(acc['id'])] = actions
			#hw_planet = db.getUserHw(acc['id'])
			#actions.createNewFleet(hw_planet, 'a_new_shiny_fleet')
			
			at_least_one = False
			for coord, unit_id in acts.iteritems():
				print 'explore (%s) %s'%(coord, unit_id)
				self.pending_actions.explore_planet( coord, unit_id )
				at_least_one = True
			
			if at_least_one:
				self.perform_actions()
示例#34
0
	def __buildCmd(self, gui, filenameRows, gameRow, calledFromSkin):
		log.info("launcher.buildCmd")

		compressedExtensions = ['7z', 'zip']

		cmd = ""
		precmd = ""
		postcmd = ""

		emuCommandLine = self.romCollection.emulatorCmd
		log.info("emuCommandLine: " + emuCommandLine)
		log.info("preCmdLine: " + self.romCollection.preCmd)
		log.info("postCmdLine: " + self.romCollection.postCmd)

		# handle savestates
		stateFile = self.__checkGameHasSaveStates(gameRow, filenameRows)

		if stateFile == '':
			emuParams = self.romCollection.emulatorParams
		else:
			emuParams = self.romCollection.saveStateParams
			if self.escapeCmd:
				stateFile = re.escape(stateFile)
			emuParams = emuParams.replace('%statefile%', stateFile)
			emuParams = emuParams.replace('%STATEFILE%', stateFile)
			emuParams = emuParams.replace('%Statefile%', stateFile)

		# params could be: {-%I% %ROM%}
		# we have to repeat the part inside the brackets and replace the %I% with the current index
		emuParams, partToRepeat = self.__prepareMultiRomCommand(emuParams)

		# ask for disc number if multidisc game
		diskName = ""
		if self.romCollection.diskPrefix != '' and '%I%' not in emuParams:
			log.info("Getting Multiple Disc Parameter")
			options = []
			for disk in filenameRows:
				gamename = os.path.basename(disk[0])
				match = re.search(self.romCollection.diskPrefix.lower(), str(gamename).lower())
				if match:
					disk = gamename[match.start():match.end()]
					options.append(disk)
			if len(options) > 1 and not calledFromSkin:
				diskNum = xbmcgui.Dialog().select(util.localize(32164) + ': ', options)
				if diskNum < 0:
					# don't launch game
					log.info("No disc was chosen. Won't launch game")
					return "", "", "", None
				else:
					diskName = options[diskNum]
					log.info("Chosen Disc: %s" % diskName)

		# insert game specific command
		gameCmd = ''
		if gameRow[util.GAME_gameCmd] is not None:
			gameCmd = str(gameRow[util.GAME_gameCmd])
		# be case insensitive with (?i)
		emuParams = re.sub('(?i)%gamecmd%', gameCmd, emuParams)

		log.info("emuParams: " + emuParams)

		fileindex = int(0)
		for fileNameRow in filenameRows:
			rom = fileNameRow[0]
			log.info("rom: " + str(rom))

			if self.romCollection.makeLocalCopy:
				localDir = os.path.join(util.getTempDir(), self.romCollection.name)
				if xbmcvfs.exists(localDir + '\\'):
					log.info("Trying to delete local rom files")
					dirs, files = xbmcvfs.listdir(localDir)
					for f in files:
						xbmcvfs.delete(os.path.join(localDir, f))
				localRom = os.path.join(localDir, os.path.basename(str(rom)))
				log.info("Creating local copy: " + str(localRom))
				if xbmcvfs.copy(rom, localRom):
					log.info("Local copy created")
				rom = localRom

			# If it's a .7z file
			# Don't extract zip files in case of savestate handling and when called From skin
			filext = rom.split('.')[-1]
			roms = [rom]
			if filext in compressedExtensions and not self.romCollection.doNotExtractZipFiles and stateFile == '' and not calledFromSkin:
				roms = self.__handleCompressedFile(gui, filext, rom, emuParams)
				log.debug("roms compressed = " + str(roms))
				if len(roms) == 0:
					return "", "", "", None

			# no use for complete cmd as we just need the game name
			if self.romCollection.useBuiltinEmulator:
				log.debug("roms = " + str(roms))
				return "", "", "", roms

			del rom

			for rom in roms:
				precmd = ""
				postcmd = ""
				if fileindex == 0:
					emuParams = self.__replacePlaceholdersInParams(emuParams, rom, gameRow)
					if self.escapeCmd:
						emuCommandLine = re.escape(emuCommandLine)

					if self.romCollection.name in ['Linux', 'Macintosh', 'Windows']:
						cmd = self.__replacePlaceholdersInParams(emuCommandLine, rom, gameRow)
					else:
						cmd = '\"' + emuCommandLine + '\" ' + emuParams.replace('%I%', str(fileindex))
				else:
					newrepl = partToRepeat
					newrepl = self.__replacePlaceholdersInParams(newrepl, rom, gameRow)
					if self.escapeCmd:
						emuCommandLine = re.escape(emuCommandLine)

					newrepl = newrepl.replace('%I%', str(fileindex))
					cmd += ' ' + newrepl

				cmdprefix = ''

				if self.env == "win32":
					cmdprefix = 'call '

				precmd = cmdprefix + self.__replacePlaceholdersInParams(self.romCollection.preCmd, rom, gameRow)
				postcmd = cmdprefix + self.__replacePlaceholdersInParams(self.romCollection.postCmd, rom, gameRow)

				fileindex += 1

		# A disk was chosen by the user, select it here
		if diskName:
			log.info("Choosing Disk: " + str(diskName))
			match = re.search(self.romCollection.diskPrefix.lower(), cmd.lower())
			replString = cmd[match.start():match.end()]
			cmd = cmd.replace(replString, diskName)

		return cmd, precmd, postcmd, roms
示例#35
0
文件: loader.py 项目: bogolt/dclord
	def getUserInfo(self, cb, login, out_dir = None):
		d = os.path.join(util.getTempDir(), 'raw_data') if not out_dir else out_dir
		self.getDcData(cb, login, 'all', d)