Пример #1
0
def _resolve_ship(fitting, sMkt, b_localized):
    # type: (xml.dom.minidom.Element, service.market.Market, bool) -> eos.saveddata.fit.Fit
    """ NOTE: Since it is meaningless unless a correct ship object can be constructed,
        process flow changed
    """
    # ------ Confirm ship
    # <localized hint="Maelstrom">Maelstrom</localized>
    shipType = fitting.getElementsByTagName("shipType").item(0).getAttribute("value")
    anything = None
    if b_localized:
        try:
            # expect an official name, emergency cache
            shipType, anything = _extract_match(shipType)
        except ExtractingError:
            pass

    limit = 2
    ship = None
    while True:
        must_retry = False
        try:
            try:
                ship = Ship(sMkt.getItem(shipType))
            except ValueError:
                ship = Citadel(sMkt.getItem(shipType))
        except Exception as e:
            pyfalog.warning("Caught exception on _resolve_ship")
            pyfalog.error(e)
            limit -= 1
            if limit is 0:
                break
            shipType = anything
            must_retry = True
        if not must_retry:
            break

    if ship is None:
        raise Exception("cannot resolve ship type.")

    fitobj = Fit(ship=ship)
    # ------ Confirm fit name
    anything = fitting.getAttribute("name")
    # 2017/03/29 NOTE:
    #    if fit name contained "<" or ">" then reprace to named html entity by EVE client
    # if re.search(RE_LTGT, anything):
    if "&lt;" in anything or "&gt;" in anything:
        anything = replace_ltgt(anything)
    fitobj.name = anything

    return fitobj
Пример #2
0
def _importCreateFit(lines):
    """Create fit and set top-level entity (ship or citadel)."""
    fit = Fit()
    header = lines.pop(0)
    m = re.match('\[(?P<shipType>[\w\s]+),\s*(?P<fitName>.+)\]', header)
    if not m:
        pyfalog.warning('service.port.eft.importEft: corrupted fit header')
        raise EftImportError
    shipType = m.group('shipType').strip()
    fitName = m.group('fitName').strip()
    try:
        ship = fetchItem(shipType)
        try:
            fit.ship = Ship(ship)
        except ValueError:
            fit.ship = Citadel(ship)
        fit.name = fitName
    except:
        pyfalog.warning('service.port.eft.importEft: exception caught when parsing header')
        raise EftImportError
    return fit
Пример #3
0
 def newFit(self, shipID, name=None):
     pyfalog.debug("Creating new fit for ID: {0}", shipID)
     try:
         ship = es_Ship(eos.db.getItem(shipID))
     except ValueError:
         ship = es_Citadel(eos.db.getItem(shipID))
     fit = FitType(ship)
     fit.name = name if name is not None else "New %s" % fit.ship.item.name
     fit.damagePattern = self.pattern
     fit.targetResists = self.targetResists
     fit.character = self.character
     fit.booster = self.booster
     useCharImplants = self.serviceFittingOptions["useCharacterImplantsByDefault"]
     fit.implantLocation = ImplantLocation.CHARACTER if useCharImplants else ImplantLocation.FIT
     eos.db.save(fit)
     self.recalc(fit)
     return fit.ID
Пример #4
0
 def newFit(self, shipID, name=None):
     pyfalog.debug("Creating new fit for ID: {0}", shipID)
     try:
         ship = es_Ship(eos.db.getItem(shipID))
     except ValueError:
         ship = es_Citadel(eos.db.getItem(shipID))
     fit = FitType(ship)
     fit.name = name if name is not None else "New %s" % fit.ship.item.name
     fit.damagePattern = self.pattern
     fit.targetResists = self.targetResists
     fit.character = self.character
     fit.booster = self.booster
     eos.db.save(fit)
     self.recalc(fit)
     return fit.ID
Пример #5
0
def importESI(str_):

    sMkt = Market.getInstance()
    fitobj = Fit()
    refobj = json.loads(str_)
    items = refobj['items']
    # "<" and ">" is replace to "&lt;", "&gt;" 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
Пример #6
0
def importESI(string):

    sMkt = Market.getInstance()
    fitobj = Fit()
    refobj = json.loads(string)
    items = refobj['items']
    # "<" and ">" is replace to "&lt;", "&gt;" 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
Пример #7
0
Файл: eft.py Проект: poklj/Pyfa
def importEftCfg(shipname, contents, 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
    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
            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(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(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
Пример #8
0
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
Пример #9
0
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
Пример #10
0
def importDna(string, fitName=None):
    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])))
        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:
            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 = 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
Пример #11
0
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)
Пример #12
0
    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
Пример #13
0
    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
Пример #14
0
    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