def Do(self): pyfalog.debug('Doing change of local module states at position {}/{} to click {} on fit {}'.format(self.mainPosition, self.positions, self.click, self.fitID)) sFit = Fit.getInstance() fit = sFit.getFit(self.fitID) mainMod = fit.modules[self.mainPosition] if mainMod.isEmpty: return False positions = [pos for pos in self.positions if not fit.modules[pos].isEmpty] if self.mainPosition not in positions: positions.append(self.mainPosition) self.savedStates = {pos: fit.modules[pos].state for pos in positions} changed = False mainProposedState = Module.getProposedState(mainMod, self.click) pyfalog.debug('Attempting to change modules to {}'.format(mainProposedState)) if mainProposedState != mainMod.state: pyfalog.debug('Toggle {} state: {} for fit ID: {}'.format(mainMod, mainProposedState, self.fitID)) mainMod.state = mainProposedState changed = True for position in [pos for pos in positions if pos != self.mainPosition]: mod = fit.modules[position] proposedState = Module.getProposedState(mod, self.click, mainProposedState) if proposedState != mod.state: pyfalog.debug('Toggle {} state: {} for fit ID: {}'.format(mod, proposedState, self.fitID)) mod.state = proposedState changed = True if not changed: return False sFit.recalc(fit) self.savedStateCheckChanges = sFit.checkStates(fit, mainMod) return True
def __makeModule(self, itemSpec): # Mutate item if needed m = None if itemSpec.mutationIdx in self.mutations: mutaItem, mutaAttrs = self.mutations[itemSpec.mutationIdx] mutaplasmid = getDynamicItem(mutaItem.ID) if mutaplasmid: try: m = Module(mutaplasmid.resultingItem, itemSpec.item, mutaplasmid) except ValueError: pass else: for attrID, mutator in m.mutators.items(): if attrID in mutaAttrs: mutator.value = mutaAttrs[attrID] # If we still don't have item (item is not mutated or we # failed to construct mutated item), try to make regular item if m is None: try: m = Module(itemSpec.item) except ValueError: return None if itemSpec.charge is not None and m.isValidCharge(itemSpec.charge): m.charge = itemSpec.charge if itemSpec.offline and m.isValidState(FittingModuleState.OFFLINE): m.state = FittingModuleState.OFFLINE elif m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) return m
def __init__(self, fitID, mainItem, items, click): wx.Command.__init__(self, True, 'Change Projected Item States') self.internalHistory = InternalCommandHistory() self.fitID = fitID self.pModPositions = [] self.pDroneItemIDs = [] self.pFighterPositions = [] self.pFitIDs = [] fit = Fit.getInstance().getFit(fitID) for item in items: if isinstance(item, EosModule): if item in fit.projectedModules: self.pModPositions.append(fit.projectedModules.index(item)) elif isinstance(item, EosDrone): self.pDroneItemIDs.append(item.itemID) elif isinstance(item, EosFighter): if item in fit.projectedFighters: self.pFighterPositions.append(fit.projectedFighters.index(item)) elif isinstance(item, EosFit): self.pFitIDs.append(item.ID) self.proposedState = None if click == 'right' and isinstance(mainItem, EosModule): self.proposedState = 'overheat' elif click == 'left': if isinstance(mainItem, EosModule): modProposedState = EosModule.getProposedState(mainItem, click) self.proposedState = 'inactive' if modProposedState == FittingModuleState.OFFLINE else 'active' elif isinstance(mainItem, EosDrone): self.proposedState = 'active' if mainItem.amountActive == 0 else 'inactive' elif isinstance(mainItem, EosFighter): self.proposedState = 'inactive' if mainItem.active else 'active' elif isinstance(mainItem, EosFit): projectionInfo = mainItem.getProjectionInfo(self.fitID) if projectionInfo is not None: self.proposedState = 'inactive' if projectionInfo.active else 'active'
def Do(self): pyfalog.debug("Projecting fit ({0}) onto: {1}", self.fitID, self.itemID) fit = eos.db.getFit(self.fitID) item = eos.db.getItem(self.itemID, eager=("attributes", "group.category")) try: module = Module(item) except ValueError: return False # todo: thing to check for existing environmental effects self.old_item = fit.projectedModules.makeRoom(module) module.state = State.ONLINE fit.projectedModules.append(module) eos.db.commit() self.new_index = fit.projectedModules.index(module) return True
def Do(self): pyfalog.debug("Projecting fit ({0}) onto: {1}", self.fitID, self.itemID) fit = eos.db.getFit(self.fitID) item = eos.db.getItem(self.itemID, eager=("attributes", "group.category")) try: module = Module(item) if not module.item.isType("projected"): return False except ValueError: return False module.state = State.ACTIVE if not module.canHaveState(module.state, fit): module.state = State.OFFLINE fit.projectedModules.append(module) eos.db.commit() self.new_index = fit.projectedModules.index(module) return True
def Do(self): pyfalog.debug("Projecting fit ({0}) onto: {1}", self.fitID, self.itemID) fit = eos.db.getFit(self.fitID) item = eos.db.getItem(self.itemID, eager=("attributes", "group.category")) try: module = Module(item) except ValueError: return False # todo: thing to check for existing environmental effects module.state = FittingModuleState.ONLINE if module.isExclusiveSystemEffect: # if this is an exclusive system effect, we need to cache the old one. We make room for the new one here, which returns the old one self.old_item = fit.projectedModules.makeRoom(module) fit.projectedModules.append(module) eos.db.commit() self.new_index = fit.projectedModules.index(module) return True
def Do(self): sFit = Fit.getInstance() fitID = self.fitID fit = eos.db.getFit(fitID) if self.baseItem is None: pyfalog.warning("Unable to build non-mutated module: no base item to build from") return False try: mutaTypeID = self.mutaItem.ID except AttributeError: mutaplasmid = None else: mutaplasmid = getDynamicItem(mutaTypeID) # Try to build simple item even though no mutaplasmid found if mutaplasmid is None: try: module = Module(self.baseItem) except ValueError: pyfalog.warning("Unable to build non-mutated module: {}", self.baseItem) return False # Build mutated module otherwise else: try: module = Module(mutaplasmid.resultingItem, self.baseItem, mutaplasmid) except ValueError: pyfalog.warning("Unable to build mutated module: {} {}", self.baseItem, self.mutaItem) return False else: for attrID, mutator in module.mutators.items(): if attrID in self.attrMap: mutator.value = self.attrMap[attrID] # this is essentially the same as the FitAddModule command. possibly look into centralizing this functionality somewhere? if module.fits(fit): pyfalog.debug("Adding {} as module for fit {}", module, fit) module.owner = fit numSlots = len(fit.modules) fit.modules.append(module) if module.isValidState(FittingModuleState.ACTIVE): module.state = FittingModuleState.ACTIVE # todo: fix these # As some items may affect state-limiting attributes of the ship, calculate new attributes first # self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed sFit.checkStates(fit, module) # fit.fill() eos.db.commit() self.change = numSlots != len(fit.modules) self.new_position = module.modPosition else: return False return True
def toggleModulesState(self, fitID, base, modules, click): pyfalog.debug("Toggle module state for fit ID: {0}", fitID) changed = False proposedState = es_Module.getProposedState(base, click) if proposedState != base.state: changed = True base.state = proposedState for mod in modules: if mod != base: p = es_Module.getProposedState(mod, click, proposedState) mod.state = p if p != mod.state: changed = True if changed: eos.db.commit() fit = eos.db.getFit(fitID) # As some items may affect state-limiting attributes of the ship, calculate new attributes first self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed self.checkStates(fit, base)
def change_module(self, fitID, position, itemID): fit = eos.db.getFit(fitID) # We're trying to add a charge to a slot, which won't work. Instead, try to add the charge to the module in that slot. # todo: evaluate if this is still a thing # actually, this seems like it should be handled higher up... # # if self.isAmmo(itemID): # module = fit.modules[self.position] # if not module.isEmpty: # self.setAmmo(fitID, itemID, [module]) # return True pyfalog.debug("Changing position of module from position ({0}) for fit ID: {1}", self.position, fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) mod = fit.modules[self.position] try: self.module = Module(item) except ValueError: pyfalog.warning("Invalid item: {0}", itemID) return False if self.module.slot != mod.slot: return False # Dummy it out in case the next bit fails fit.modules.toDummy(self.position) if not self.module.fits(fit): self.Undo() return False self.module.owner = fit fit.modules.toModule(self.position, self.module) if self.module.isValidState(FittingModuleState.ACTIVE): self.module.state = FittingModuleState.ACTIVE if self.old_module and self.old_module.charge and self.module.isValidCharge(self.old_module.charge): self.module.charge = self.old_module.charge # Then, check states of all modules and change where needed. This will recalc if needed # self.checkStates(fit, m) # fit.fill() eos.db.commit() return True
def Do(self): sFit = Fit.getInstance() fitID = self.fitID itemID = self.itemID fit = eos.db.getFit(fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) bItem = eos.db.getItem(self.baseID) if self.baseID else None mItem = next((x for x in bItem.mutaplasmids if x.ID == self.mutaplasmidID)) if self.mutaplasmidID else None try: self.module = Module(item, bItem, mItem) except ValueError: pyfalog.warning("Invalid module: {}", item) return False # If subsystem and we need to replace, run the replace command instead and bypass the rest of this command if self.module.item.category.name == "Subsystem": for mod in fit.modules: if mod.getModifiedItemAttr("subSystemSlot") == self.module.getModifiedItemAttr("subSystemSlot"): from .fitReplaceModule import FitReplaceModuleCommand self.replace_cmd = FitReplaceModuleCommand(self.fitID, mod.modPosition, itemID) return self.replace_cmd.Do() if self.module.fits(fit): pyfalog.debug("Adding {} as module for fit {}", self.module, fit) self.module.owner = fit numSlots = len(fit.modules) fit.modules.append(self.module) if self.module.isValidState(State.ACTIVE): self.module.state = State.ACTIVE # todo: fix these # As some items may affect state-limiting attributes of the ship, calculate new attributes first # self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed sFit.checkStates(fit, self.module) # fit.fill() eos.db.commit() self.change = numSlots != len(fit.modules) self.new_position = self.module.modPosition else: return False return True
def Do(self): pyfalog.debug('Doing change of projected module state at positions {} to state {} on fit {}'.format( self.positions, self.proposedState, self.fitID)) sFit = Fit.getInstance() fit = sFit.getFit(self.fitID) self.savedStates = {pos: fit.projectedModules[pos].state for pos in self.positions} changed = False for position in self.positions: mod = fit.projectedModules[position] proposedState = Module.getProposedState(mod, None, self.proposedState) if proposedState != mod.state: pyfalog.debug('Toggle projected {} state: {} for fit ID: {}'.format(mod, proposedState, self.fitID)) mod.state = proposedState changed = True if not changed: return False sFit.recalc(fit) self.savedStateCheckChanges = sFit.checkStates(fit, None) return True
def toggleProjected(self, fitID, thing, click): pyfalog.debug("Toggling projected on fit ({0}) for: {1}", fitID, thing) fit = eos.db.getFit(fitID) if isinstance(thing, es_Drone): if thing.amountActive == 0 and thing.canBeApplied(fit): thing.amountActive = thing.amount else: thing.amountActive = 0 elif isinstance(thing, es_Fighter): thing.active = not thing.active elif isinstance(thing, es_Module): thing.state = es_Module.getProposedState(thing, click) if not thing.canHaveState(thing.state, fit): thing.state = State.OFFLINE elif isinstance(thing, FitType): projectionInfo = thing.getProjectionInfo(fitID) if projectionInfo: projectionInfo.active = not projectionInfo.active eos.db.commit() self.recalc(fit)
def importDna(string): sMkt = Market.getInstance() ids = list(map(int, re.findall(r'\d+', string))) for id_ in ids: try: try: try: Ship(sMkt.getItem(sMkt.getItem(id_))) except ValueError: Citadel(sMkt.getItem(sMkt.getItem(id_))) except ValueError: Citadel(sMkt.getItem(id_)) string = string[string.index(str(id_)):] break except: pyfalog.warning("Exception caught in importDna") pass string = string[:string.index("::") + 2] info = string.split(":") f = Fit() try: try: f.ship = Ship(sMkt.getItem(int(info[0]))) except ValueError: f.ship = Citadel(sMkt.getItem(int(info[0]))) f.name = "{0} - DNA Imported".format(f.ship.item.name) except UnicodeEncodeError: def logtransform(s_): if len(s_) > 10: return s_[:10] + "..." return s_ pyfalog.exception("Couldn't import ship data {0}", [logtransform(s) for s in info]) return None moduleList = [] for itemInfo in info[1:]: if itemInfo: itemID, amount = itemInfo.split(";") item = sMkt.getItem(int(itemID), eager="group.category") if item.category.name == "Drone": d = Drone(item) d.amount = int(amount) f.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int(amount) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize if ft.fits(f): f.fighters.append(ft) elif item.category.name == "Charge": c = Cargo(item) c.amount = int(amount) f.cargo.append(c) else: for i in range(int(amount)): try: m = Module(item) except: pyfalog.warning("Exception caught in importDna") continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(f) for module in moduleList: if module.fits(f): module.owner = f if module.isValidState(State.ACTIVE): module.state = State.ACTIVE f.modules.append(module) return f
def Do(self): sFit = Fit.getInstance() fitID = self.fitID if fitID is None: return False fit = eos.db.getFit(fitID) if self.baseItem is None: pyfalog.warning( "Unable to build non-mutated module: no base item to build from" ) return False try: mutaTypeID = self.mutaItem.ID except AttributeError: mutaplasmid = None else: mutaplasmid = getDynamicItem(mutaTypeID) # Try to build simple item even though no mutaplasmid found if mutaplasmid is None: try: module = Module(self.baseItem) except ValueError: pyfalog.warning("Unable to build non-mutated module: {}", self.baseItem) return False # Build mutated module otherwise else: try: module = Module(mutaplasmid.resultingItem, self.baseItem, mutaplasmid) except ValueError: pyfalog.warning("Unable to build mutated module: {} {}", self.baseItem, self.mutaItem) return False else: for attrID, mutator in module.mutators.items(): if attrID in self.attrMap: mutator.value = self.attrMap[attrID] # this is essentially the same as the FitAddModule command. possibly look into centralizing this functionality somewhere? if module.fits(fit): pyfalog.debug("Adding {} as module for fit {}", module, fit) module.owner = fit numSlots = len(fit.modules) fit.modules.append(module) if module.isValidState(FittingModuleState.ACTIVE): module.state = FittingModuleState.ACTIVE # todo: fix these # As some items may affect state-limiting attributes of the ship, calculate new attributes first # self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed sFit.checkStates(fit, module) # fit.fill() eos.db.commit() self.change = numSlots != len(fit.modules) self.new_position = module.modPosition else: return False return True
def importDna(string): sMkt = Market.getInstance() ids = list(map(int, re.findall(r'\d+', string))) for id_ in ids: try: try: try: Ship(sMkt.getItem(sMkt.getItem(id_))) except ValueError: Citadel(sMkt.getItem(sMkt.getItem(id_))) except ValueError: Citadel(sMkt.getItem(id_)) string = string[string.index(str(id_)):] break except: pyfalog.warning("Exception caught in importDna") pass string = string[:string.index("::") + 2] info = string.split(":") f = Fit() try: try: f.ship = Ship(sMkt.getItem(int(info[0]))) except ValueError: f.ship = Citadel(sMkt.getItem(int(info[0]))) f.name = "{0} - DNA Imported".format(f.ship.item.name) except UnicodeEncodeError: def logtransform(s_): if len(s_) > 10: return s_[:10] + "..." return s_ pyfalog.exception("Couldn't import ship data {0}", [logtransform(s) for s in info]) return None moduleList = [] for itemInfo in info[1:]: if itemInfo: itemID, amount = itemInfo.split(";") item = sMkt.getItem(int(itemID), eager="group.category") if item.category.name == "Drone": d = Drone(item) d.amount = int(amount) f.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int( amount ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize if ft.fits(f): f.fighters.append(ft) elif item.category.name == "Charge": c = Cargo(item) c.amount = int(amount) f.cargo.append(c) else: for i in range(int(amount)): try: m = Module(item) except: pyfalog.warning("Exception caught in importDna") continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f if m.isValidState(FittingModuleState.ACTIVE): m.state = FittingModuleState.ACTIVE moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(f) for module in moduleList: if module.fits(f): module.owner = f if module.isValidState(FittingModuleState.ACTIVE): module.state = FittingModuleState.ACTIVE f.modules.append(module) return f
def importEft(lines): lines = _importPrepare(lines) try: fit = _importCreateFit(lines) except EftImportError: return aFit = AbstractFit() aFit.mutations = _importGetMutationData(lines) nameChars = '[^,/\[\]]' # Characters which are allowed to be used in name stubPattern = '^\[.+?\]$' modulePattern = '^(?P<typeName>{0}+?)(,\s*(?P<chargeName>{0}+?))?(?P<offline>\s*{1})?(\s*\[(?P<mutation>\d+?)\])?$'.format( nameChars, OFFLINE_SUFFIX) droneCargoPattern = '^(?P<typeName>{}+?) x(?P<amount>\d+?)$'.format( nameChars) sections = [] for section in _importSectionIter(lines): for line in section.lines: # Stub line if re.match(stubPattern, line): section.itemSpecs.append(None) continue # Items with quantity specifier m = re.match(droneCargoPattern, line) if m: try: itemSpec = MultiItemSpec(m.group('typeName')) # Items which cannot be fetched are considered as stubs except EftImportError: section.itemSpecs.append(None) else: itemSpec.amount = int(m.group('amount')) section.itemSpecs.append(itemSpec) continue # All other items m = re.match(modulePattern, line) if m: try: itemSpec = RegularItemSpec( m.group('typeName'), chargeName=m.group('chargeName')) # Items which cannot be fetched are considered as stubs except EftImportError: section.itemSpecs.append(None) else: if m.group('offline'): itemSpec.offline = True if m.group('mutation'): itemSpec.mutationIdx = int(m.group('mutation')) section.itemSpecs.append(itemSpec) continue _clearTail(section.itemSpecs) sections.append(section) hasDroneBay = any(s.isDroneBay for s in sections) hasFighterBay = any(s.isFighterBay for s in sections) for section in sections: if section.isModuleRack: aFit.addModules(section.itemSpecs) elif section.isImplantRack: for itemSpec in section.itemSpecs: aFit.addImplant(itemSpec) elif section.isDroneBay: for itemSpec in section.itemSpecs: aFit.addDrone(itemSpec) elif section.isFighterBay: for itemSpec in section.itemSpecs: aFit.addFighter(itemSpec) elif section.isCargoHold: for itemSpec in section.itemSpecs: aFit.addCargo(itemSpec) # Mix between different kinds of item specs (can happen when some # blank lines are removed) else: for itemSpec in section.itemSpecs: if itemSpec is None: continue if itemSpec.isModule: aFit.addModule(itemSpec) elif itemSpec.isImplant: aFit.addImplant(itemSpec) elif itemSpec.isDrone and not hasDroneBay: aFit.addDrone(itemSpec) elif itemSpec.isFighter and not hasFighterBay: aFit.addFighter(itemSpec) elif itemSpec.isCargo: aFit.addCargo(itemSpec) # Subsystems first because they modify slot amount for i, m in enumerate(aFit.subsystems): if m is None: dummy = Module.buildEmpty(aFit.getSlotByContainer(aFit.subsystems)) dummy.owner = fit fit.modules.replaceRackPosition(i, dummy) elif m.fits(fit): m.owner = fit fit.modules.replaceRackPosition(i, m) sFit = svcFit.getInstance() sFit.recalc(fit) sFit.fill(fit) # Other stuff for modRack in ( aFit.rigs, aFit.services, aFit.modulesHigh, aFit.modulesMed, aFit.modulesLow, ): for i, m in enumerate(modRack): if m is None: dummy = Module.buildEmpty(aFit.getSlotByContainer(modRack)) dummy.owner = fit fit.modules.replaceRackPosition(i, dummy) elif m.fits(fit): m.owner = fit if not m.isValidState(m.state): pyfalog.warning( 'service.port.eft.importEft: module {} cannot have state {}', m, m.state) fit.modules.replaceRackPosition(i, m) for implant in aFit.implants: fit.implants.append(implant) for booster in aFit.boosters: fit.boosters.append(booster) for drone in aFit.drones.values(): fit.drones.append(drone) for fighter in aFit.fighters: fit.fighters.append(fighter) for cargo in aFit.cargo.values(): fit.cargo.append(cargo) return fit
def toModule(self, fallbackState=None): mkt = Market.getInstance() item = mkt.getItem(self.itemID, eager=('attributes', 'group.category')) if self.baseItemID and self.mutaplasmidID: baseItem = mkt.getItem(self.baseItemID, eager=('attributes', 'group.category')) mutaplasmid = eos.db.getDynamicItem(self.mutaplasmidID) else: baseItem = None mutaplasmid = None try: mod = Module(item, baseItem=baseItem, mutaplasmid=mutaplasmid) except ValueError: pyfalog.warning('Invalid item: {}'.format(self.itemID)) return None if self.mutations is not None: for attrID, mutator in mod.mutators.items(): if attrID in self.mutations: mutator.value = self.mutations[attrID] if self.spoolType is not None and self.spoolAmount is not None: mod.spoolType = self.spoolType mod.spoolAmount = self.spoolAmount if self.state is not None: if mod.isValidState(self.state): mod.state = self.state else: mod.state = mod.getMaxState(proposedState=self.state) elif fallbackState is not None: if mod.isValidState(fallbackState): mod.state = fallbackState if self.chargeID is not None: charge = mkt.getItem(self.chargeID, eager=('attributes', )) if charge is None: pyfalog.warning('Cannot set charge {}'.format(self.chargeID)) return None mod.charge = charge return mod
def importEftCfg(shipname, contents, callback=None): """Handle import from EFT config store file""" # Check if we have such ship in database, bail if we don't sMkt = Market.getInstance() try: sMkt.getItem(shipname) except: return [] # empty list is expected # If client didn't take care of encoding file contents into Unicode, # do it using fallback encoding ourselves if isinstance(contents, str): contents = unicode(contents, "cp1252") fits = [] # List for fits fitIndices = [] # List for starting line numbers for each fit lines = re.split('[\n\r]+', contents) # Separate string into lines for line in lines: # Detect fit header if line[:1] == "[" and line[-1:] == "]": # Line index where current fit starts startPos = lines.index(line) fitIndices.append(startPos) for i, startPos in enumerate(fitIndices): # End position is last file line if we're trying to get it for last fit, # or start position of next fit minus 1 endPos = len(lines) if i == len(fitIndices) - 1 else fitIndices[i + 1] # Finally, get lines for current fitting fitLines = lines[startPos:endPos] try: # Create fit object f = Fit() # Strip square brackets and pull out a fit name f.name = fitLines[0][1:-1] # Assign ship to fitting try: f.ship = Ship(sMkt.getItem(shipname)) except ValueError: f.ship = Citadel(sMkt.getItem(shipname)) moduleList = [] for x in range(1, len(fitLines)): line = fitLines[x] if not line: continue # Parse line into some data we will need misc = re.match( "(Drones|Implant|Booster)_(Active|Inactive)=(.+)", line) cargo = re.match("Cargohold=(.+)", line) if misc: entityType = misc.group(1) entityState = misc.group(2) entityData = misc.group(3) if entityType == "Drones": droneData = re.match("(.+),([0-9]+)", entityData) # Get drone name and attempt to detect drone number droneName = droneData.group( 1) if droneData else entityData droneAmount = int( droneData.group(2)) if droneData else 1 # Bail if we can't get item or it's not from drone category try: droneItem = sMkt.getItem( droneName, eager="group.category") except: pyfalog.warning("Cannot get item.") continue if droneItem.category.name == "Drone": # Add drone to the fitting d = Drone(droneItem) d.amount = droneAmount if entityState == "Active": d.amountActive = droneAmount elif entityState == "Inactive": d.amountActive = 0 f.drones.append(d) elif droneItem.category.name == "Fighter": # EFT saves fighter as drones ft = Fighter(droneItem) ft.amount = int( droneAmount ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize f.fighters.append(ft) else: continue elif entityType == "Implant": # Bail if we can't get item or it's not from implant category try: implantItem = sMkt.getItem( entityData, eager="group.category") except: pyfalog.warning("Cannot get item.") continue if implantItem.category.name != "Implant": continue # Add implant to the fitting imp = Implant(implantItem) if entityState == "Active": imp.active = True elif entityState == "Inactive": imp.active = False f.implants.append(imp) elif entityType == "Booster": # Bail if we can't get item or it's not from implant category try: boosterItem = sMkt.getItem( entityData, eager="group.category") except: pyfalog.warning("Cannot get item.") continue # All boosters have implant category if boosterItem.category.name != "Implant": continue # Add booster to the fitting b = Booster(boosterItem) if entityState == "Active": b.active = True elif entityState == "Inactive": b.active = False f.boosters.append(b) # If we don't have any prefixes, then it's a module elif cargo: cargoData = re.match("(.+),([0-9]+)", cargo.group(1)) cargoName = cargoData.group( 1) if cargoData else cargo.group(1) cargoAmount = int( cargoData.group(2)) if cargoData else 1 # Bail if we can't get item try: item = sMkt.getItem(cargoName) except: pyfalog.warning("Cannot get item.") continue # Add Cargo to the fitting c = Cargo(item) c.amount = cargoAmount f.cargo.append(c) else: withCharge = re.match("(.+),(.+)", line) modName = withCharge.group(1) if withCharge else line chargeName = withCharge.group( 2) if withCharge else None # If we can't get module item, skip it try: modItem = sMkt.getItem(modName) except: pyfalog.warning("Cannot get item.") continue # Create module m = Module(modItem) # Add subsystems before modules to make sure T3 cruisers have subsystems installed if modItem.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f # Activate mod if it is activable if m.isValidState(State.ACTIVE): m.state = State.ACTIVE # Add charge to mod if applicable, on any errors just don't add anything if chargeName: try: chargeItem = sMkt.getItem( chargeName, eager="group.category") if chargeItem.category.name == "Charge": m.charge = chargeItem except: pyfalog.warning("Cannot get item.") pass # Append module to fit moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(f) for module in moduleList: if module.fits(f): f.modules.append(module) # Append fit to list of fits fits.append(f) if callback: wx.CallAfter(callback, None) # Skip fit silently if we get an exception except Exception as e: pyfalog.error("Caught exception on fit.") pyfalog.error(e) pass return fits
def importEftCfg(shipname, lines, iportuser): """Handle import from EFT config store file""" # Check if we have such ship in database, bail if we don't sMkt = Market.getInstance() try: sMkt.getItem(shipname) except: return [] # empty list is expected fits = [] # List for fits fitIndices = [] # List for starting line numbers for each fit for line in lines: # Detect fit header if line[:1] == "[" and line[-1:] == "]": # Line index where current fit starts startPos = lines.index(line) fitIndices.append(startPos) for i, startPos in enumerate(fitIndices): # End position is last file line if we're trying to get it for last fit, # or start position of next fit minus 1 endPos = len(lines) if i == len(fitIndices) - 1 else fitIndices[i + 1] # Finally, get lines for current fitting fitLines = lines[startPos:endPos] try: # Create fit object fitobj = Fit() # Strip square brackets and pull out a fit name fitobj.name = fitLines[0][1:-1] # Assign ship to fitting try: fitobj.ship = Ship(sMkt.getItem(shipname)) except ValueError: fitobj.ship = Citadel(sMkt.getItem(shipname)) moduleList = [] for x in range(1, len(fitLines)): line = fitLines[x] if not line: continue # Parse line into some data we will need misc = re.match("(Drones|Implant|Booster)_(Active|Inactive)=(.+)", line) cargo = re.match("Cargohold=(.+)", line) # 2017/03/27 NOTE: store description from EFT description = re.match("Description=(.+)", line) if misc: entityType = misc.group(1) entityState = misc.group(2) entityData = misc.group(3) if entityType == "Drones": droneData = re.match("(.+),([0-9]+)", entityData) # Get drone name and attempt to detect drone number droneName = droneData.group(1) if droneData else entityData droneAmount = int(droneData.group(2)) if droneData else 1 # Bail if we can't get item or it's not from drone category try: droneItem = sMkt.getItem(droneName, eager="group.category") except: pyfalog.warning("Cannot get item.") continue if droneItem.category.name == "Drone": # Add drone to the fitting d = Drone(droneItem) d.amount = droneAmount if entityState == "Active": d.amountActive = droneAmount elif entityState == "Inactive": d.amountActive = 0 fitobj.drones.append(d) elif droneItem.category.name == "Fighter": # EFT saves fighter as drones ft = Fighter(droneItem) ft.amount = int(droneAmount) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize fitobj.fighters.append(ft) else: continue elif entityType == "Implant": # Bail if we can't get item or it's not from implant category try: implantItem = sMkt.getItem(entityData, eager="group.category") except: pyfalog.warning("Cannot get item.") continue if implantItem.category.name != "Implant": continue # Add implant to the fitting imp = Implant(implantItem) if entityState == "Active": imp.active = True elif entityState == "Inactive": imp.active = False fitobj.implants.append(imp) elif entityType == "Booster": # Bail if we can't get item or it's not from implant category try: boosterItem = sMkt.getItem(entityData, eager="group.category") except: pyfalog.warning("Cannot get item.") continue # All boosters have implant category if boosterItem.category.name != "Implant": continue # Add booster to the fitting b = Booster(boosterItem) if entityState == "Active": b.active = True elif entityState == "Inactive": b.active = False fitobj.boosters.append(b) # If we don't have any prefixes, then it's a module elif cargo: cargoData = re.match("(.+),([0-9]+)", cargo.group(1)) cargoName = cargoData.group(1) if cargoData else cargo.group(1) cargoAmount = int(cargoData.group(2)) if cargoData else 1 # Bail if we can't get item try: item = sMkt.getItem(cargoName) except: pyfalog.warning("Cannot get item.") continue # Add Cargo to the fitting c = Cargo(item) c.amount = cargoAmount fitobj.cargo.append(c) # 2017/03/27 NOTE: store description from EFT elif description: fitobj.notes = description.group(1).replace("|", "\n") else: withCharge = re.match("(.+),(.+)", line) modName = withCharge.group(1) if withCharge else line chargeName = withCharge.group(2) if withCharge else None # If we can't get module item, skip it try: modItem = sMkt.getItem(modName) except: pyfalog.warning("Cannot get item.") continue # Create module m = Module(modItem) # Add subsystems before modules to make sure T3 cruisers have subsystems installed if modItem.category.name == "Subsystem": if m.fits(fitobj): fitobj.modules.append(m) else: m.owner = fitobj # Activate mod if it is activable if m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) # Add charge to mod if applicable, on any errors just don't add anything if chargeName: try: chargeItem = sMkt.getItem(chargeName, eager="group.category") if chargeItem.category.name == "Charge": m.charge = chargeItem except: pyfalog.warning("Cannot get item.") pass # Append module to fit moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers sFit = svcFit.getInstance() sFit.recalc(fitobj) sFit.fill(fitobj) for module in moduleList: if module.fits(fitobj): fitobj.modules.append(module) # Append fit to list of fits fits.append(fitobj) if iportuser: # NOTE: Send current processing status processing_notify( iportuser, IPortUser.PROCESS_IMPORT | IPortUser.ID_UPDATE, "%s:\n%s" % (fitobj.ship.name, fitobj.name) ) # Skip fit silently if we get an exception except Exception as e: pyfalog.error("Caught exception on fit.") pyfalog.error(e) pass return fits
def restoreRemovedDummies(fit, dummyInfo): # Need this to properly undo the case when removal of subsystems removes dummy slots for position in sorted(dummyInfo): slot = dummyInfo[position] fit.modules.insert(position, Module.buildEmpty(slot))
class FitReplaceModuleCommand(wx.Command): """" Fitting command that changes an existing module into another. from sFit.changeModule """ def __init__(self, fitID, position, itemID): wx.Command.__init__(self, True, "Change Module") self.fitID = fitID self.itemID = itemID self.position = position self.module = None # the module version of itemID self.old_module = None def Do(self): return self.change_module(self.fitID, self.position, self.itemID) def Undo(self): if self.old_module is None: fit = eos.db.getFit(self.fitID) fit.modules.toDummy(self.position) return True self.change_module(self.fitID, self.position, self.old_module.itemID) self.module.state = self.old_module.state self.module.charge = self.old_module.charge return True def change_module(self, fitID, position, itemID): fit = eos.db.getFit(fitID) # We're trying to add a charge to a slot, which won't work. Instead, try to add the charge to the module in that slot. # todo: evaluate if this is still a thing # actually, this seems like it should be handled higher up... # # if self.isAmmo(itemID): # module = fit.modules[self.position] # if not module.isEmpty: # self.setAmmo(fitID, itemID, [module]) # return True pyfalog.debug( "Changing position of module from position ({0}) for fit ID: {1}", self.position, fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) mod = fit.modules[self.position] if not mod.isEmpty: self.old_module = ModuleInfoCache(mod.modPosition, mod.item.ID, mod.state, mod.charge, mod.baseItemID, mod.mutaplasmidID) try: self.module = Module(item) except ValueError: pyfalog.warning("Invalid item: {0}", itemID) return False if self.module.slot != mod.slot: return False # Dummy it out in case the next bit fails fit.modules.toDummy(self.position) if self.module.fits(fit): self.module.owner = fit fit.modules.toModule(self.position, self.module) if self.module.isValidState(State.ACTIVE): self.module.state = State.ACTIVE # Then, check states of all modules and change where needed. This will recalc if needed # self.checkStates(fit, m) # fit.fill() eos.db.commit() return True return False
class FitReplaceModuleCommand(wx.Command): """" Fitting command that changes an existing module into another. from sFit.changeModule """ def __init__(self, fitID, position, itemID): wx.Command.__init__(self, True, "Change Module") self.fitID = fitID self.itemID = itemID self.position = position self.module = None # the module version of itemID self.old_module = None def Do(self): fit = eos.db.getFit(self.fitID) mod = fit.modules[self.position] if not mod.isEmpty: self.old_module = ModuleInfoCache(mod.modPosition, mod.item.ID, mod.state, mod.charge, mod.baseItemID, mod.mutaplasmidID) return self.change_module(self.fitID, self.position, self.itemID) def Undo(self): if self.old_module is None: fit = eos.db.getFit(self.fitID) fit.modules.toDummy(self.position) return True self.change_module(self.fitID, self.position, self.old_module.itemID) self.module.state = self.old_module.state self.module.charge = self.old_module.charge return True def change_module(self, fitID, position, itemID): fit = eos.db.getFit(fitID) # We're trying to add a charge to a slot, which won't work. Instead, try to add the charge to the module in that slot. # todo: evaluate if this is still a thing # actually, this seems like it should be handled higher up... # # if self.isAmmo(itemID): # module = fit.modules[self.position] # if not module.isEmpty: # self.setAmmo(fitID, itemID, [module]) # return True pyfalog.debug("Changing position of module from position ({0}) for fit ID: {1}", self.position, fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) mod = fit.modules[self.position] try: self.module = Module(item) except ValueError: pyfalog.warning("Invalid item: {0}", itemID) return False if self.module.slot != mod.slot: return False # Dummy it out in case the next bit fails fit.modules.toDummy(self.position) if self.module.fits(fit): self.module.owner = fit fit.modules.toModule(self.position, self.module) if self.module.isValidState(State.ACTIVE): self.module.state = State.ACTIVE if self.old_module and self.old_module.charge and self.module.isValidCharge(self.old_module.charge): self.module.charge = self.old_module.charge # Then, check states of all modules and change where needed. This will recalc if needed # self.checkStates(fit, m) # fit.fill() eos.db.commit() return True return False
def importXml(text, iportuser): from .port import Port # type: (str, IPortUser) -> list[eos.saveddata.fit.Fit] sMkt = Market.getInstance() doc = xml.dom.minidom.parseString(text) # NOTE: # When L_MARK is included at this point, # Decided to be localized data b_localized = L_MARK in text fittings = doc.getElementsByTagName("fittings").item(0) fittings = fittings.getElementsByTagName("fitting") fit_list = [] failed = 0 for fitting in fittings: try: fitobj = _resolve_ship(fitting, sMkt, b_localized) except: failed += 1 continue # -- 170327 Ignored description -- # read description from exported xml. (EVE client, EFT) description = fitting.getElementsByTagName("description").item(0).getAttribute("value") if description is None: description = "" elif len(description): # convert <br> to "\n" and remove html tags. if Port.is_tag_replace(): description = replace_ltgt( sequential_rep(description, r"<(br|BR)>", "\n", r"<[^<>]+>", "") ) fitobj.notes = description hardwares = fitting.getElementsByTagName("hardware") moduleList = [] for hardware in hardwares: try: item = _resolve_module(hardware, sMkt, b_localized) if not item or not item.published: continue if item.category.name == "Drone": d = Drone(item) d.amount = int(hardware.getAttribute("qty")) fitobj.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int(hardware.getAttribute("qty")) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize fitobj.fighters.append(ft) elif hardware.getAttribute("slot").lower() == "cargo": # although the eve client only support charges in cargo, third-party programs # may support items or "refits" in cargo. Support these by blindly adding all # cargo, not just charges c = Cargo(item) c.amount = int(hardware.getAttribute("qty")) fitobj.cargo.append(c) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.warning("item can't be added to any slot (unknown item or just charge), ignore it") continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fitobj): m.owner = fitobj fitobj.modules.append(m) else: if m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) moduleList.append(m) except KeyboardInterrupt: pyfalog.warning("Keyboard Interrupt") continue # Recalc to get slot numbers correct for T3 cruisers sFit = svcFit.getInstance() sFit.recalc(fitobj) sFit.fill(fitobj) for module in moduleList: if module.fits(fitobj): module.owner = fitobj fitobj.modules.append(module) fit_list.append(fitobj) if iportuser: # NOTE: Send current processing status processing_notify( iportuser, IPortUser.PROCESS_IMPORT | IPortUser.ID_UPDATE, "Processing %s\n%s" % (fitobj.ship.name, fitobj.name) ) return fit_list
def importEftCfg(shipname, lines, iportuser): """Handle import from EFT config store file""" # Check if we have such ship in database, bail if we don't sMkt = Market.getInstance() try: sMkt.getItem(shipname) except (KeyboardInterrupt, SystemExit): raise except: return [] # empty list is expected fits = [] # List for fits fitIndices = [] # List for starting line numbers for each fit for line in lines: # Detect fit header if line[:1] == "[" and line[-1:] == "]": # Line index where current fit starts startPos = lines.index(line) fitIndices.append(startPos) for i, startPos in enumerate(fitIndices): # End position is last file line if we're trying to get it for last fit, # or start position of next fit minus 1 endPos = len(lines) if i == len(fitIndices) - 1 else fitIndices[i + 1] # Finally, get lines for current fitting fitLines = lines[startPos:endPos] try: # Create fit object fitobj = Fit() # Strip square brackets and pull out a fit name fitobj.name = fitLines[0][1:-1] # Assign ship to fitting try: fitobj.ship = Ship(sMkt.getItem(shipname)) except ValueError: fitobj.ship = Citadel(sMkt.getItem(shipname)) moduleList = [] for x in range(1, len(fitLines)): line = fitLines[x] if not line: continue # Parse line into some data we will need misc = re.match( "(Drones|Implant|Booster)_(Active|Inactive)=(.+)", line) cargo = re.match("Cargohold=(.+)", line) # 2017/03/27 NOTE: store description from EFT description = re.match("Description=(.+)", line) if misc: entityType = misc.group(1) entityState = misc.group(2) entityData = misc.group(3) if entityType == "Drones": droneData = re.match("(.+),([0-9]+)", entityData) # Get drone name and attempt to detect drone number droneName = droneData.group( 1) if droneData else entityData droneAmount = int( droneData.group(2)) if droneData else 1 # Bail if we can't get item or it's not from drone category try: droneItem = sMkt.getItem(droneName, eager="group.category") except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") continue if droneItem.category.name == "Drone": # Add drone to the fitting d = Drone(droneItem) d.amount = droneAmount if entityState == "Active": d.amountActive = droneAmount elif entityState == "Inactive": d.amountActive = 0 fitobj.drones.append(d) elif droneItem.category.name == "Fighter": # EFT saves fighter as drones ft = Fighter(droneItem) ft.amount = int( droneAmount ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize fitobj.fighters.append(ft) else: continue elif entityType == "Implant": # Bail if we can't get item or it's not from implant category try: implantItem = sMkt.getItem(entityData, eager="group.category") except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") continue if implantItem.category.name != "Implant": continue # Add implant to the fitting imp = Implant(implantItem) if entityState == "Active": imp.active = True elif entityState == "Inactive": imp.active = False fitobj.implants.append(imp) elif entityType == "Booster": # Bail if we can't get item or it's not from implant category try: boosterItem = sMkt.getItem(entityData, eager="group.category") except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") continue # All boosters have implant category if boosterItem.category.name != "Implant": continue # Add booster to the fitting b = Booster(boosterItem) if entityState == "Active": b.active = True elif entityState == "Inactive": b.active = False fitobj.boosters.append(b) # If we don't have any prefixes, then it's a module elif cargo: cargoData = re.match("(.+),([0-9]+)", cargo.group(1)) cargoName = cargoData.group( 1) if cargoData else cargo.group(1) cargoAmount = int(cargoData.group(2)) if cargoData else 1 # Bail if we can't get item try: item = sMkt.getItem(cargoName) except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") continue # Add Cargo to the fitting c = Cargo(item) c.amount = cargoAmount fitobj.cargo.append(c) # 2017/03/27 NOTE: store description from EFT elif description: fitobj.notes = description.group(1).replace("|", "\n") else: withCharge = re.match("(.+),(.+)", line) modName = withCharge.group(1) if withCharge else line chargeName = withCharge.group(2) if withCharge else None # If we can't get module item, skip it try: modItem = sMkt.getItem(modName) except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") continue # Create module m = Module(modItem) # Add subsystems before modules to make sure T3 cruisers have subsystems installed if modItem.category.name == "Subsystem": if m.fits(fitobj): fitobj.modules.append(m) else: m.owner = fitobj # Activate mod if it is activable if m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) # Add charge to mod if applicable, on any errors just don't add anything if chargeName: try: chargeItem = sMkt.getItem( chargeName, eager="group.category") if chargeItem.category.name == "Charge": m.charge = chargeItem except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Cannot get item.") pass # Append module to fit moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers sFit = svcFit.getInstance() sFit.recalc(fitobj) sFit.fill(fitobj) for module in moduleList: if module.fits(fitobj): fitobj.modules.append(module) # Append fit to list of fits fits.append(fitobj) if iportuser: # NOTE: Send current processing status processing_notify( iportuser, IPortUser.PROCESS_IMPORT | IPortUser.ID_UPDATE, "%s:\n%s" % (fitobj.ship.name, fitobj.name)) except (KeyboardInterrupt, SystemExit): raise # Skip fit silently if we get an exception except Exception as e: pyfalog.error("Caught exception on fit.") pyfalog.error(e) pass return fits
def processImportInfo(info, fitName, amountSeparator): sMkt = Market.getInstance() f = Fit() try: try: f.ship = Ship(sMkt.getItem(int(info[0]))) except ValueError: f.ship = Citadel(sMkt.getItem(int(info[0]))) if fitName is None: f.name = "{0} - DNA Imported".format(f.ship.item.name) else: f.name = fitName except UnicodeEncodeError: def logtransform(s_): if len(s_) > 10: return s_[:10] + "..." return s_ pyfalog.exception("Couldn't import ship data {0}", [logtransform(s) for s in info]) return None moduleList = [] for itemInfo in info[1:]: if itemInfo: if amountSeparator in itemInfo: itemID, amount = itemInfo.split(amountSeparator) else: itemID = itemInfo amount = 1 item = sMkt.getItem(int(itemID), eager="group.category") if item.category.name == "Drone": d = Drone(item) d.amount = int(amount) f.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int( amount ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize if ft.fits(f): f.fighters.append(ft) elif item.category.name == "Charge": c = Cargo(item) c.amount = int(amount) f.cargo.append(c) else: for i in range(int(amount)): try: m = Module(item) except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Exception caught in importDna") continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: m.owner = f if m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers sFit = svcFit.getInstance() sFit.recalc(f) sFit.fill(f) for module in moduleList: if module.fits(f): module.owner = f if module.isValidState(FittingModuleState.ACTIVE): module.state = activeStateLimit(module.item) f.modules.append(module) return f
def columnBackground(self, colItem, item): if self.sFit.serviceFittingOptions["colorFitBySlot"]: return slotColourMap.get(Module.calculateSlot(item)) or self.GetBackgroundColour() else: return self.GetBackgroundColour()
def importKillmail( killmail, fitNameFunction=lambda killmail, fit: fit.ship.item.name ) -> Fit or None: """Parses a single killmail from the ESI API. The argument is an already parsed JSON""" sMkt = Market.getInstance() fit = Fit() victim = killmail["victim"] items = victim["items"] try: ship = victim["ship_type_id"] try: fit.ship = Ship(sMkt.getItem(ship)) except ValueError: fit.ship = Citadel(sMkt.getItem(ship)) except: pyfalog.warning("Caught exception in importZKillboard") return None fit.name = fitNameFunction(killmail, fit) items.sort(key=lambda k: k["flag"]) moduleList = [] moduleByFlag = {} chargeByFlag = {} for module in items: try: item = sMkt.getItem(module["item_type_id"], eager="group.category") if not item.published: continue flag = module["flag"] if flag == INV_FLAG_DRONEBAY: d = Drone(item) d.amount = module.get("quantity_destroyed", 0) + module.get( "quantity_dropped", 0) fit.drones.append(d) elif flag == INV_FLAG_CARGOBAY: c = fit.cargo.findFirst(item) if c is None: c = Cargo(item) fit.cargo.append(c) c.amount += module.get("quantity_destroyed", 0) + module.get( "quantity_dropped", 0) elif flag == INV_FLAG_FIGHTER: fighter = Fighter(item) fit.fighters.append(fighter) else: try: m = Module(item) moduleByFlag[flag] = m # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: chargeByFlag[flag] = item pyfalog.debug( "Item can't be added to any slot (unknown item or just charge)" ) continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fit): fit.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except: pyfalog.warning("Could not process module.") continue # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(fit) for flag in moduleByFlag.keys(): module = moduleByFlag[flag] charge = chargeByFlag.get(flag, None) if (not charge is None ) and module.isValidCharge(charge) and module.charge is None: module.charge = charge for module in moduleList: if module.fits(fit): fit.modules.append(module) km_time = datetime.strptime(killmail["killmail_time"], "%Y-%m-%dT%H:%M:%SZ") fit.timestamp = time.mktime(km_time.timetuple()) fit.modified = fit.created = km_time return saveImportedFit(fit)
def importXml(text, callback=None, encoding="utf-8"): sMkt = Market.getInstance() doc = xml.dom.minidom.parseString(text.encode(encoding)) fittings = doc.getElementsByTagName("fittings").item(0) fittings = fittings.getElementsByTagName("fitting") fits = [] for i, fitting in enumerate(fittings): f = Fit() f.name = fitting.getAttribute("name") # <localized hint="Maelstrom">Maelstrom</localized> shipType = fitting.getElementsByTagName("shipType").item( 0).getAttribute("value") try: try: f.ship = Ship(sMkt.getItem(shipType)) except ValueError: f.ship = Citadel(sMkt.getItem(shipType)) except Exception as e: pyfalog.warning("Caught exception on importXml") pyfalog.error(e) continue hardwares = fitting.getElementsByTagName("hardware") moduleList = [] for hardware in hardwares: try: moduleName = hardware.getAttribute("type") try: item = sMkt.getItem(moduleName, eager="group.category") except Exception as e: pyfalog.warning("Caught exception on importXml") pyfalog.error(e) continue if item: if item.category.name == "Drone": d = Drone(item) d.amount = int(hardware.getAttribute("qty")) f.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int( hardware.getAttribute("qty") ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize f.fighters.append(ft) elif hardware.getAttribute("slot").lower() == "cargo": # although the eve client only support charges in cargo, third-party programs # may support items or "refits" in cargo. Support these by blindly adding all # cargo, not just charges c = Cargo(item) c.amount = int(hardware.getAttribute("qty")) f.cargo.append(c) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.warning( "item can't be added to any slot (unknown item or just charge), ignore it" ) continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): m.owner = f f.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except KeyboardInterrupt: pyfalog.warning("Keyboard Interrupt") continue # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(f) for module in moduleList: if module.fits(f): module.owner = f f.modules.append(module) fits.append(f) if callback: wx.CallAfter(callback, None) return fits
class FitAddModuleCommand(wx.Command): """" Fitting command that appends a module to a fit using the first available slot. In the case of a Subsystem, it checks if there is already a subsystem with the same slot, and runs the replace command instead. from sFit.appendModule """ def __init__(self, fitID, itemID, mutaplasmidID=None, baseID=None): wx.Command.__init__(self, True) self.fitID = fitID self.itemID = itemID self.mutaplasmidID = mutaplasmidID self.baseID = baseID self.new_position = None self.change = None self.replace_cmd = None def Do(self): sFit = Fit.getInstance() fitID = self.fitID itemID = self.itemID fit = eos.db.getFit(fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) bItem = eos.db.getItem(self.baseID) if self.baseID else None mItem = next( (x for x in bItem.mutaplasmids if x.ID == self.mutaplasmidID)) if self.mutaplasmidID else None try: self.module = Module(item, bItem, mItem) except ValueError: pyfalog.warning("Invalid module: {}", item) return False # If subsystem and we need to replace, run the replace command instead and bypass the rest of this command if self.module.item.category.name == "Subsystem": for mod in fit.modules: if mod.getModifiedItemAttr( "subSystemSlot") == self.module.getModifiedItemAttr( "subSystemSlot"): from .fitReplaceModule import FitReplaceModuleCommand self.replace_cmd = FitReplaceModuleCommand( self.fitID, mod.modPosition, itemID) return self.replace_cmd.Do() if self.module.fits(fit): pyfalog.debug("Adding {} as module for fit {}", self.module, fit) self.module.owner = fit numSlots = len(fit.modules) fit.modules.append(self.module) if self.module.isValidState(State.ACTIVE): self.module.state = State.ACTIVE # todo: fix these # As some items may affect state-limiting attributes of the ship, calculate new attributes first # self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed sFit.checkStates(fit, self.module) # fit.fill() eos.db.commit() self.change = numSlots != len(fit.modules) self.new_position = self.module.modPosition else: return False return True def Undo(self): # We added a subsystem module, which actually ran the replace command. Run the undo for that guy instead if self.replace_cmd: return self.replace_cmd.Undo() from .fitRemoveModule import FitRemoveModuleCommand # Avoid circular import if self.new_position: cmd = FitRemoveModuleCommand(self.fitID, [self.new_position]) cmd.Do() return True
def importEft(lines): lines = _importPrepare(lines) try: fit = _importCreateFit(lines) except EftImportError: return aFit = AbstractFit() aFit.mutations = _importGetMutationData(lines) nameChars = '[^,/\[\]]' # Characters which are allowed to be used in name stubPattern = '^\[.+?\]$' modulePattern = '^(?P<typeName>{0}+?)(,\s*(?P<chargeName>{0}+?))?(?P<offline>\s*{1})?(\s*\[(?P<mutation>\d+?)\])?$'.format(nameChars, OFFLINE_SUFFIX) droneCargoPattern = '^(?P<typeName>{}+?) x(?P<amount>\d+?)$'.format(nameChars) sections = [] for section in _importSectionIter(lines): for line in section.lines: # Stub line if re.match(stubPattern, line): section.itemSpecs.append(None) continue # Items with quantity specifier m = re.match(droneCargoPattern, line) if m: try: itemSpec = MultiItemSpec(m.group('typeName')) # Items which cannot be fetched are considered as stubs except EftImportError: section.itemSpecs.append(None) else: itemSpec.amount = int(m.group('amount')) section.itemSpecs.append(itemSpec) continue # All other items m = re.match(modulePattern, line) if m: try: itemSpec = RegularItemSpec(m.group('typeName'), chargeName=m.group('chargeName')) # Items which cannot be fetched are considered as stubs except EftImportError: section.itemSpecs.append(None) else: if m.group('offline'): itemSpec.offline = True if m.group('mutation'): itemSpec.mutationIdx = int(m.group('mutation')) section.itemSpecs.append(itemSpec) continue _clearTail(section.itemSpecs) sections.append(section) hasDroneBay = any(s.isDroneBay for s in sections) hasFighterBay = any(s.isFighterBay for s in sections) for section in sections: if section.isModuleRack: aFit.addModules(section.itemSpecs) elif section.isImplantRack: for itemSpec in section.itemSpecs: aFit.addImplant(itemSpec) elif section.isDroneBay: for itemSpec in section.itemSpecs: aFit.addDrone(itemSpec) elif section.isFighterBay: for itemSpec in section.itemSpecs: aFit.addFighter(itemSpec) elif section.isCargoHold: for itemSpec in section.itemSpecs: aFit.addCargo(itemSpec) # Mix between different kinds of item specs (can happen when some # blank lines are removed) else: for itemSpec in section.itemSpecs: if itemSpec is None: continue if itemSpec.isModule: aFit.addModule(itemSpec) elif itemSpec.isImplant: aFit.addImplant(itemSpec) elif itemSpec.isDrone and not hasDroneBay: aFit.addDrone(itemSpec) elif itemSpec.isFighter and not hasFighterBay: aFit.addFighter(itemSpec) elif itemSpec.isCargo: aFit.addCargo(itemSpec) # Subsystems first because they modify slot amount for i, m in enumerate(aFit.subsystems): if m is None: dummy = Module.buildEmpty(aFit.getSlotByContainer(aFit.subsystems)) dummy.owner = fit fit.modules.replaceRackPosition(i, dummy) elif m.fits(fit): m.owner = fit fit.modules.replaceRackPosition(i, m) sFit = svcFit.getInstance() sFit.recalc(fit) sFit.fill(fit) # Other stuff for modRack in ( aFit.rigs, aFit.services, aFit.modulesHigh, aFit.modulesMed, aFit.modulesLow, ): for i, m in enumerate(modRack): if m is None: dummy = Module.buildEmpty(aFit.getSlotByContainer(modRack)) dummy.owner = fit fit.modules.replaceRackPosition(i, dummy) elif m.fits(fit): m.owner = fit if not m.isValidState(m.state): pyfalog.warning('service.port.eft.importEft: module {} cannot have state {}', m, m.state) fit.modules.replaceRackPosition(i, m) for implant in aFit.implants: fit.implants.append(implant) for booster in aFit.boosters: fit.boosters.append(booster) for drone in aFit.drones.values(): fit.drones.append(drone) for fighter in aFit.fighters: fit.fighters.append(fighter) for cargo in aFit.cargo.values(): fit.cargo.append(cargo) return fit
def importEft(eftString): sMkt = Market.getInstance() offineSuffix = " /OFFLINE" fit = Fit() eftString = eftString.strip() lines = re.split('[\n\r]+', eftString) info = lines[0][1:-1].split(",", 1) if len(info) == 2: shipType = info[0].strip() fitName = info[1].strip() else: shipType = info[0].strip() fitName = "Imported %s" % shipType try: ship = sMkt.getItem(shipType) try: fit.ship = Ship(ship) except ValueError: fit.ship = Citadel(ship) fit.name = fitName except: pyfalog.warning("Exception caught in importEft") return # maintain map of drones and their quantities droneMap = {} cargoMap = {} moduleList = [] for i in range(1, len(lines)): ammoName = None extraAmount = None line = lines[i].strip() if not line: continue setOffline = line.endswith(offineSuffix) if setOffline is True: # remove offline suffix from line line = line[:len(line) - len(offineSuffix)] modAmmo = line.split(",") # matches drone and cargo with x{qty} modExtra = modAmmo[0].split(" x") if len(modAmmo) == 2: # line with a module and ammo ammoName = modAmmo[1].strip() modName = modAmmo[0].strip() elif len(modExtra) == 2: # line with drone/cargo and qty extraAmount = modExtra[1].strip() modName = modExtra[0].strip() else: # line with just module modName = modExtra[0].strip() try: # get item information. If we are on a Drone/Cargo line, throw out cargo item = sMkt.getItem(modName, eager="group.category") except: # if no data can be found (old names) pyfalog.warning("no data can be found (old names)") continue if item.category.name == "Drone": extraAmount = int( extraAmount) if extraAmount is not None else 1 if modName not in droneMap: droneMap[modName] = 0 droneMap[modName] += extraAmount elif item.category.name == "Fighter": extraAmount = int( extraAmount) if extraAmount is not None else 1 fighterItem = Fighter(item) if extraAmount > fighterItem.fighterSquadronMaxSize: # Amount bigger then max fightergroup size extraAmount = fighterItem.fighterSquadronMaxSize if fighterItem.fits(fit): fit.fighters.append(fighterItem) if len( modExtra ) == 2 and item.category.name != "Drone" and item.category.name != "Fighter": extraAmount = int( extraAmount) if extraAmount is not None else 1 if modName not in cargoMap: cargoMap[modName] = 0 cargoMap[modName] += extraAmount elif item.category.name == "Implant": if "implantness" in item.attributes: fit.implants.append(Implant(item)) elif "boosterness" in item.attributes: fit.boosters.append(Booster(item)) else: pyfalog.error("Failed to import implant: {0}", line) # elif item.category.name == "Subsystem": # try: # subsystem = Module(item) # except ValueError: # continue # # if subsystem.fits(fit): # fit.modules.append(subsystem) else: try: m = Module(item) except ValueError: continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fit): fit.modules.append(m) else: if ammoName: try: ammo = sMkt.getItem(ammoName) if m.isValidCharge(ammo) and m.charge is None: m.charge = ammo except: pass if setOffline is True and m.isValidState(State.OFFLINE): m.state = State.OFFLINE elif m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(fit) for m in moduleList: if m.fits(fit): m.owner = fit if not m.isValidState(m.state): pyfalog.warning("Error: Module {0} cannot have state {1}", m, m.state) fit.modules.append(m) for droneName in droneMap: d = Drone(sMkt.getItem(droneName)) d.amount = droneMap[droneName] fit.drones.append(d) for cargoName in cargoMap: c = Cargo(sMkt.getItem(cargoName)) c.amount = cargoMap[cargoName] fit.cargo.append(c) return fit
def columnBackground(self, colItem, item): if self.sFit.serviceFittingOptions["colorFitBySlot"]: return slotColourMap.get( Module.calculateSlot(item)) or self.GetBackgroundColour() else: return self.GetBackgroundColour()
class FitAddModuleCommand(wx.Command): """" Fitting command that appends a module to a fit using the first available slot. In the case of a Subsystem, it checks if there is already a subsystem with the same slot, and runs the replace command instead. from sFit.appendModule """ def __init__(self, fitID, itemID, mutaplasmidID=None, baseID=None): wx.Command.__init__(self, True) self.fitID = fitID self.itemID = itemID self.mutaplasmidID = mutaplasmidID self.baseID = baseID self.new_position = None self.change = None self.replace_cmd = None def Do(self): sFit = Fit.getInstance() fitID = self.fitID itemID = self.itemID fit = eos.db.getFit(fitID) item = eos.db.getItem(itemID, eager=("attributes", "group.category")) bItem = eos.db.getItem(self.baseID) if self.baseID else None mItem = next((x for x in bItem.mutaplasmids if x.ID == self.mutaplasmidID)) if self.mutaplasmidID else None try: self.module = Module(item, bItem, mItem) except ValueError: pyfalog.warning("Invalid module: {}", item) return False # If subsystem and we need to replace, run the replace command instead and bypass the rest of this command if self.module.item.category.name == "Subsystem": for mod in fit.modules: if mod.getModifiedItemAttr("subSystemSlot") == self.module.getModifiedItemAttr("subSystemSlot"): from .fitReplaceModule import FitReplaceModuleCommand self.replace_cmd = FitReplaceModuleCommand(self.fitID, mod.modPosition, itemID) return self.replace_cmd.Do() if self.module.fits(fit): pyfalog.debug("Adding {} as module for fit {}", self.module, fit) self.module.owner = fit numSlots = len(fit.modules) fit.modules.append(self.module) if self.module.isValidState(State.ACTIVE): self.module.state = State.ACTIVE # todo: fix these # As some items may affect state-limiting attributes of the ship, calculate new attributes first # self.recalc(fit) # Then, check states of all modules and change where needed. This will recalc if needed sFit.checkStates(fit, self.module) # fit.fill() eos.db.commit() self.change = numSlots != len(fit.modules) self.new_position = self.module.modPosition else: return False return True def Undo(self): # We added a subsystem module, which actually ran the replace command. Run the undo for that guy instead if self.replace_cmd: return self.replace_cmd.Undo() from .fitRemoveModule import FitRemoveModuleCommand # Avoid circular import if self.new_position: cmd = FitRemoveModuleCommand(self.fitID, [self.new_position]) cmd.Do() return True
def importESI(str_): sMkt = Market.getInstance() fitobj = Fit() refobj = json.loads(str_) items = refobj['items'] # "<" and ">" is replace to "<", ">" by EVE client fitobj.name = refobj['name'] # 2017/03/29: read description fitobj.notes = refobj['description'] try: ship = refobj['ship_type_id'] try: fitobj.ship = Ship(sMkt.getItem(ship)) except ValueError: fitobj.ship = Citadel(sMkt.getItem(ship)) except: pyfalog.warning("Caught exception in importESI") return None items.sort(key=lambda k: k['flag']) moduleList = [] for module in items: try: item = sMkt.getItem(module['type_id'], eager="group.category") if not item.published: continue if module['flag'] == INV_FLAG_DRONEBAY: d = Drone(item) d.amount = module['quantity'] fitobj.drones.append(d) elif module['flag'] == INV_FLAG_CARGOBAY: c = Cargo(item) c.amount = module['quantity'] fitobj.cargo.append(c) elif module['flag'] == INV_FLAG_FIGHTER: fighter = Fighter(item) fitobj.fighters.append(fighter) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.debug("Item can't be added to any slot (unknown item or just charge)") continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fitobj): fitobj.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except: pyfalog.warning("Could not process module.") continue # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(fitobj) for module in moduleList: if module.fits(fitobj): fitobj.modules.append(module) return fitobj
def getTestSet(setType): def getT2ItemsWhere(additionalFilter, mustBeOffensive=False, category="Module"): # Used to obtain a smaller subset of items while still containing examples of each group. T2_META_LEVEL = 5 metaLevelAttrID = getAttributeInfo("metaLevel").attributeID categoryID = getCategory(category).categoryID result = gamedata_session.query(Item).join(ItemEffect, Group, Attribute).\ filter( additionalFilter, Attribute.attributeID == metaLevelAttrID, Attribute.value == T2_META_LEVEL, Group.categoryID == categoryID, ).all() if mustBeOffensive: result = filter(lambda t: t.offensive is True, result) return list(result) def getChargeType(item, setType): if setType == "turret": return str(item.attributes["chargeGroup1"].value) + "-" + str(item.attributes["chargeSize"].value) return str(item.attributes["chargeGroup1"].value) if setType in EfsPort.wepTestSet.keys(): return EfsPort.wepTestSet[setType] else: EfsPort.wepTestSet[setType] = [] modSet = EfsPort.wepTestSet[setType] if setType == "drone": ilist = getT2ItemsWhere(True, True, "Drone") for item in ilist: drone = Drone(item) drone.amount = 1 drone.amountActive = 1 drone.itemModifiedAttributes.parent = drone modSet.append(drone) return modSet turretFittedEffectID = gamedata_session.query(Effect).filter(Effect.name == "turretFitted").first().effectID launcherFittedEffectID = gamedata_session.query(Effect).filter(Effect.name == "launcherFitted").first().effectID if setType == "launcher": effectFilter = ItemEffect.effectID == launcherFittedEffectID reqOff = False else: effectFilter = ItemEffect.effectID == turretFittedEffectID reqOff = True ilist = getT2ItemsWhere(effectFilter, reqOff) previousChargeTypes = [] # Get modules from item list for item in ilist: chargeType = getChargeType(item, setType) # Only add turrets if we don"t already have one with the same size and ammo type. if setType == "launcher" or chargeType not in previousChargeTypes: previousChargeTypes.append(chargeType) mod = Module(item) modSet.append(mod) sMkt = Market.getInstance() # Due to typed missile damage bonuses we"ll need to add extra launchers to cover all four types. additionalLaunchers = [] for mod in modSet: clist = list(gamedata_session.query(Item).options(). filter(Item.groupID == mod.getModifiedItemAttr("chargeGroup1")).all()) mods = [mod] charges = [clist[0]] if setType == "launcher": # We don"t want variations of missiles we already have prevCharges = list(sMkt.getVariationsByItems(charges)) testCharges = [] for charge in clist: if charge not in prevCharges: testCharges.append(charge) prevCharges += sMkt.getVariationsByItems([charge]) for c in testCharges: charges.append(c) additionalLauncher = Module(mod.item) mods.append(additionalLauncher) for i in range(len(mods)): mods[i].charge = charges[i] mods[i].reloadForce = True mods[i].state = 2 if setType == "launcher" and i > 0: additionalLaunchers.append(mods[i]) modSet += additionalLaunchers return modSet
def importESI(string): sMkt = Market.getInstance() fitobj = Fit() refobj = json.loads(string) items = refobj['items'] # "<" and ">" is replace to "<", ">" by EVE client fitobj.name = refobj['name'] # 2017/03/29: read description fitobj.notes = refobj['description'] try: ship = refobj['ship_type_id'] try: fitobj.ship = Ship(sMkt.getItem(ship)) except ValueError: fitobj.ship = Citadel(sMkt.getItem(ship)) except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Caught exception in importESI") return None items.sort(key=lambda k: k['flag']) moduleList = [] for module in items: try: item = sMkt.getItem(module['type_id'], eager="group.category") if not item.published: continue if module['flag'] == INV_FLAG_DRONEBAY: d = Drone(item) d.amount = module['quantity'] fitobj.drones.append(d) elif module['flag'] == INV_FLAG_CARGOBAY: c = Cargo(item) c.amount = module['quantity'] fitobj.cargo.append(c) elif module['flag'] == INV_FLAG_FIGHTER: fighter = Fighter(item) fitobj.fighters.append(fighter) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.debug( "Item can't be added to any slot (unknown item or just charge)" ) continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fitobj): fitobj.modules.append(m) else: if m.isValidState(FittingModuleState.ACTIVE): m.state = activeStateLimit(m.item) moduleList.append(m) except (KeyboardInterrupt, SystemExit): raise except: pyfalog.warning("Could not process module.") continue # Recalc to get slot numbers correct for T3 cruisers sFit = svcFit.getInstance() sFit.recalc(fitobj) sFit.fill(fitobj) for module in moduleList: if module.fits(fitobj): fitobj.modules.append(module) return fitobj
def importXml(text, iportuser): from .port import Port # type: (str, IPortUser) -> list[eos.saveddata.fit.Fit] sMkt = Market.getInstance() doc = xml.dom.minidom.parseString(text) # NOTE: # When L_MARK is included at this point, # Decided to be localized data b_localized = L_MARK in text fittings = doc.getElementsByTagName("fittings").item(0) fittings = fittings.getElementsByTagName("fitting") fit_list = [] failed = 0 for fitting in fittings: try: fitobj = _resolve_ship(fitting, sMkt, b_localized) except: failed += 1 continue # -- 170327 Ignored description -- # read description from exported xml. (EVE client, EFT) description = fitting.getElementsByTagName("description").item( 0).getAttribute("value") if description is None: description = "" elif len(description): # convert <br> to "\n" and remove html tags. if Port.is_tag_replace(): description = replace_ltgt( sequential_rep(description, r"<(br|BR)>", "\n", r"<[^<>]+>", "")) fitobj.notes = description hardwares = fitting.getElementsByTagName("hardware") moduleList = [] for hardware in hardwares: try: item = _resolve_module(hardware, sMkt, b_localized) if not item or not item.published: continue if item.category.name == "Drone": d = Drone(item) d.amount = int(hardware.getAttribute("qty")) fitobj.drones.append(d) elif item.category.name == "Fighter": ft = Fighter(item) ft.amount = int( hardware.getAttribute("qty") ) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize fitobj.fighters.append(ft) elif hardware.getAttribute("slot").lower() == "cargo": # although the eve client only support charges in cargo, third-party programs # may support items or "refits" in cargo. Support these by blindly adding all # cargo, not just charges c = Cargo(item) c.amount = int(hardware.getAttribute("qty")) fitobj.cargo.append(c) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.warning( "item can't be added to any slot (unknown item or just charge), ignore it" ) continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(fitobj): m.owner = fitobj fitobj.modules.append(m) else: if m.isValidState(FittingModuleState.ACTIVE): m.state = FittingModuleState.ACTIVE moduleList.append(m) except KeyboardInterrupt: pyfalog.warning("Keyboard Interrupt") continue # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(fitobj) for module in moduleList: if module.fits(fitobj): module.owner = fitobj fitobj.modules.append(module) fit_list.append(fitobj) if iportuser: # NOTE: Send current processing status processing_notify( iportuser, IPortUser.PROCESS_IMPORT | IPortUser.ID_UPDATE, "Processing %s\n%s" % (fitobj.ship.name, fitobj.name)) return fit_list
def importCrest(str_): fit = json.loads(str_) sMkt = Market.getInstance() f = Fit() f.name = fit['name'] try: try: f.ship = Ship(sMkt.getItem(fit['ship']['id'])) except ValueError: f.ship = Citadel(sMkt.getItem(fit['ship']['id'])) except: pyfalog.warning("Caught exception in importCrest") return None items = fit['items'] items.sort(key=lambda k: k['flag']) moduleList = [] for module in items: try: item = sMkt.getItem(module['type']['id'], eager="group.category") if module['flag'] == INV_FLAG_DRONEBAY: d = Drone(item) d.amount = module['quantity'] f.drones.append(d) elif module['flag'] == INV_FLAG_CARGOBAY: c = Cargo(item) c.amount = module['quantity'] f.cargo.append(c) elif module['flag'] == INV_FLAG_FIGHTER: fighter = Fighter(item) f.fighters.append(fighter) else: try: m = Module(item) # When item can't be added to any slot (unknown item or just charge), ignore it except ValueError: pyfalog.debug( "Item can't be added to any slot (unknown item or just charge)" ) continue # Add subsystems before modules to make sure T3 cruisers have subsystems installed if item.category.name == "Subsystem": if m.fits(f): f.modules.append(m) else: if m.isValidState(State.ACTIVE): m.state = State.ACTIVE moduleList.append(m) except: pyfalog.warning("Could not process module.") continue # Recalc to get slot numbers correct for T3 cruisers svcFit.getInstance().recalc(f) for module in moduleList: if module.fits(f): f.modules.append(module) return f