def __init__(self, key_id=None, vcode=None, cache=True): if cache: self.client = self.public_client = eveapi.EVEAPIConnection( cacheHandler=RedisEveAPICacheHandler( debug=app.config['DEBUG'])) else: self.client = self.public_client = eveapi.EVEAPIConnection() if key_id and vcode: self.auth(key_id, vcode)
def update_system_stats(): """ Updates the System Statistics (jumps, kills) from the API. """ api = eveapi.EVEAPIConnection(cacheHandler=handler) jumpapi = api.map.Jumps() killapi = api.map.Kills() System.objects.all().update(shipkills=0, podkills=0, npckills=0) KSystem.objects.all().update(jumps=0) # Update jumps from Jumps API for K-space systems for entry in jumpapi.solarSystems: try: KSystem.objects.filter(pk=entry.solarSystemID).update( jumps=entry.shipJumps) except Exception: pass # Update kills from Kills API for entry in killapi.solarSystems: try: System.objects.filter(pk=entry.solarSystemID).update( shipkills = entry.shipKills, podkills = entry.podKills, npckills = entry.factionKills) except Exception: pass
def create_related(self): api = eveapi.EVEAPIConnection() auth = api.auth(keyID=self.key, vCode=self.vcode) keyinfo = auth.account.APIKeyInfo().key.type characters = auth.account.Characters().characters if not keyinfo == u'Corporation': for character in characters: try: models.get_model("characters", "Character").objects.create( user = self.user, api = self, characterID = character.characterID, name = character.name, corporationID = character.corporationID, corporationName = character.corporationName, ) except IntegrityError: pass #create corporation else: for character in characters: try: models.get_model("corporations", "Corporation").objects.create( user = self.user, api = self, corporationID = character.corporationID, corporationName = character.corporationName, ) except IntegrityError: pass
def main(self): """Program Main flow""" global LOGGER if not self.debug: self._log_builder.configure_discord_logger() LOGGER = self._log_builder.logger LOGGER.info('Getting Map info') eveapi.set_user_agent("eveapi.py/1.3") api = eveapi.EVEAPIConnection() kills = api.map.kills() jumps = api.map.Jumps() facWarSystems = api.map.FacWarSystems() sovereignty = api.map.Sovereignty() killsDataframe = convert_to_panda(kills, KILLS_FIELDS.split(',')) jumpsDataframe = convert_to_panda(jumps, JUMPS_FIELDS.split(',')) facWarSystemsDataframe = convert_to_panda(facWarSystems, FAC_FIELDS.split(',')) sovereigntyDataframe = convert_to_panda(sovereignty, SOV_FIELDS.split(',')) LOGGER.info('Saving to CSV File') killsDataframe.to_csv("kills.csv") jumpsDataframe.to_csv("jumps.csv") facWarSystemsDataframe.to_csv("facWarSystems.csv") sovereigntyDataframe.to_csv("sovereignty.csv")
def run(self, character_id): api = eveapi.EVEAPIConnection() character = Character.objects.get(id=character_id) # Try to fetch a valid key from DB try: apikey = APIKey.objects.get(id=character.apikey_id, is_valid=True) except APIKey.DoesNotExist: # End execution for this character return logger.debug("Updating research agents for %s..." % character.name) # Try to authenticate and handle exceptions properly try: auth = api.auth(keyID=apikey.keyid, vCode=apikey.vcode) me = auth.character(character.id) # Get newest page - use maximum row count to minimize amount of requests sheet = me.Research() except eveapi.Error, e: handle_api_exception(e, apikey) return
def run(self, character_id): #define variables i_stats = {} implant = {} attributes = ['memory', 'intelligence', 'perception', 'willpower', 'charisma'] #grab an api object api = eveapi.EVEAPIConnection() character = Character.objects.get(id=character_id) # Try to fetch a valid key from DB try: apikey = APIKey.objects.get(id=character.apikey_id, is_valid=True) except APIKey.DoesNotExist: # End execution for this character return logger.debug("Updating character sheet for %s" % character.name) # Try to authenticate and handle exceptions properly try: auth = api.auth(keyID=apikey.keyid, vCode=apikey.vcode) me = auth.character(character.id) sheet = me.CharacterSheet() i_stats['name'] = "" i_stats['value'] = 0 except eveapi.Error, e: handle_api_exception(e, apikey) return
def run(self, **kwargs): logger.debug('Updating conquerable stations...') api = eveapi.EVEAPIConnection() stations = api.eve.ConquerableStationList() for station in stations.outposts: # Try to find mapping in DB. If found -> update. If not found -> create try: station_object = StaStation.objects.get(id=station.stationID) station_object.name = station.stationName station_object.save() except StaStation.DoesNotExist: # Add station / catch race condition with other workers try: station_object = StaStation(id=station.stationID, name=station.stationName, solar_system_id=station.solarSystemID, type_id=station.stationTypeID, constellation=MapSolarSystem.objects.get(id=station.solarSystemID).constellation, region=MapSolarSystem.objects.get(id=station.solarSystemID).region) station_object.save() except IntegrityError: logger.warning('Station was already processed by another concurrently running worker.') logger.info('Updated %d conquerable stations.' % len(stations.outposts))
def apiHandler(apiType, call, keyID=0, vCode=0, ids=0): """ Wrapper for the API to deal with API errors :param apiType: The API level (eve/character/etc.) :type apiType: int. :param call: The specific API call :type call: Str. :param keyID: apiKey for authentication :type keyID: Int. :param vCode: vCode for the provided API key :type vCode: Str. :param ids: Ids that needs to be passed :type ids: Int. :return: keyType and keyMask in a dict :raises: None """ api = eveapi.EVEAPIConnection() apiaccess = getattr(api, apiType + "/" + call) try: if call == 'CharacterName': result = apiaccess(ids=ids) elif call == 'CorporationSheet': result = apiaccess(corporationID=ids) elif apiType == 'char': result = apiaccess(keyID=keyID, vCode=vCode, userID=ids) elif call == 'AllianceList': result = apiaccess() else: result = apiaccess(keyID=keyID, vCode=vCode) return result except eveapi.Error, e: print "Oops! eveapi returned the following error:" print "code:", e.code print "message:", e.message
def validateKey(keyID, vCode): try: key = ApiKey.objects.get(keyID=keyID, deleted=False) return None, "The Key you provided is already in the database." except: pass api = eveapi.EVEAPIConnection() auth = api.auth(keyID=keyID, vCode=vCode) try: result = auth.account.APIKeyInfo() except: return None, "The Key you provided is invalid." if (result.key.expires != ""): return None, "The Key you provided has an expiration date set." if not result.key.accessMask in [268435455, 1073741823, 4294967295]: return None, "The Key you provided is not a full access key." if result.key.type != "Account": return None, "The Key you provided is not a full Account key." charlist = [] storedChars = Character.objects.all() for character in result.key.characters: try: storedChars.get(charID=character.characterID) if not char.apikey.deleted: return None, "The character " + character.characterName + " is already in the database." except: charlist.append({ "charID": character.characterID, "charName": character.characterName }) return charlist, None
def add_status_info(poses): """Accepts a list of corp poses and returns a list of POSes with status information attached. A posstatus object has the following attributes: itemid: the POS item id pos: POS object processed status: Status retrieved """ class statusentry: def __init__(self, pos, status): self.itemid = pos.apiitemid self.pos = pos self.status = status api = eveapi.EVEAPIConnection(cacheHandler=handler) #Now that we have a corp authenticated API, let's play with some POSes statuslist = [] for pos in poses: auth = api.auth(keyID=pos.apikey.keyid, vCode=pos.apikey.vcode) result = auth.corp.StarbaseDetail(itemID=pos.apiitemid) status = statusentry(pos, result) statuslist.append(status) return statuslist
def getdetailshash(name): api = eveapi.EVEAPIConnection() r = api.eve.CharacterID(names=name).characters assert (len(r) > 0) id = r[0].characterID r = api.eve.CharacterInfo(characterID=id) return (id, r)
def __init__(self, KEYID='', VCODE="", CHARACTERID=''): #создаем экземпляр интерфейса self.api = eveapi.EVEAPIConnection() #авторизуемся на сервере. необходимы только эти параметры, дополнительные передаются в соответствующие функции. self.auth = self.api.auth(keyID=KEYID, vCode=VCODE)
def get_authenticated_api(self, cache_handler=handler): """ Returns an eveapi api object with the proper auth context for this key. Uses the built-in cacheHandler by default. """ api = eveapi.EVEAPIConnection(cacheHandler=cache_handler) auth = api.auth(keyID=self.keyid, vCode=self.vcode) return auth
def edit_pos(request, sysID, posID): """ GET gets the edit POS dialog, POST processes it. """ if not request.is_ajax(): raise PermissionDenied system = get_object_or_404(System, pk=sysID) pos = get_object_or_404(POS, pk=posID) if request.method == 'POST': tower = get_object_or_404(Type, name=request.POST['tower']) try: corp = Corporation.objects.get(name=request.POST['corp']) except: # Corp isn't in our DB, get its ID and add it try: api = eveapi.EVEAPIConnection(cacheHandler=handler) corpID = api.eve.CharacterID( names=request.POST['corp']).characters[0].characterID corp = core_tasks.update_corporation(corpID) except: # The corp doesn't exist return HttpResponse('Corp does not exist!', status=404) pos.corporation = corp pos.towertype = tower pos.posname = request.POST['name'] pos.planet = int(request.POST['planet']) pos.moon = int(request.POST['moon']) pos.status = int(request.POST['status']) pos.fitting = request.POST['fitting'] # Have the async worker update the corp just so that it is up to date core_tasks.update_corporation.delay(corp.id) if pos.status == 3: if request.POST['rfdays'] == '': rf_days = 0 else: rf_days = int(request.POST['rfdays']) if request.POST['rfhours'] == '': rf_hours = 0 else: rf_hours = int(request.POST['rfhours']) if request.POST['rfminutes'] == '': rf_minutes = 0 else: rf_minutes = int(request.POST['rfminutes']) delta = timedelta(days=rf_days, hours=rf_hours, minutes=rf_minutes) pos.rftime = datetime.now(pytz.utc) + delta pos.save() if request.POST.get('dscan', None) == "1": pos.fit_from_dscan(request.POST['fitting'].encode('utf-8')) return HttpResponse() else: fitting = pos.fitting.replace("<br />", "\n") return TemplateResponse(request, 'edit_pos.html', { 'system': system, 'pos': pos, 'fitting': fitting })
def update_all_alliances(): """ Updates all corps in all alliances. This task will take a long time to run. """ api = eveapi.EVEAPIConnection(cacheHandler=handler) alliancelist = api.eve.AllianceList() for alliance in alliancelist.alliances: update_alliance(alliance.allianceID)
def get_character_id(character_name=None): if character_name is None: raise Exception('No character name provided') character_id = r.get('eve:name_id:{}'.format(character_name)) if character_id is None: client = eveapi.EVEAPIConnection(cacheHandler=RedisEveAPICacheHandler( debug=app.config['DEBUG'])) character_id = client.eve.CharacterID( names=[character_name]).characters[0]['characterID'] r.set('eve:name_id:{}'.format(character_name), character_id) return character_id
def add_ref_types(): api = eveapi.EVEAPIConnection() reftypes = api.eve.RefTypes().refTypes for ref in reftypes: try: WalletRefTypes.objects.create( refTypeID=ref.refTypeID, refTypeName=ref.refTypeName, ) except: print "ooeps"
def skill_groups(): api = eveapi.EVEAPIConnection() skilltree = api.eve.SkillTree() for g in skilltree.skillGroups: try: SkillGroup.objects.create( groupid=g.groupID, groupname=g.groupName, ) except: pass
def attributes(): api = eveapi.EVEAPIConnection() skilltree = api.eve.SkillTree() for g in skilltree.skillGroups: for skill in g.skills: try: Attribute.objects.create( name=skill.requiredAttributes.secondaryAttribute, ) except: pass
def main(args): eveapi.set_user_agent("eveapi.py/1.3") api = eveapi.EVEAPIConnection() auth = api.auth(keyID=YOUR_KEYID, vCode=YOUR_VCODE) result = auth.account.Characters() charnum = choosen(result.characters) ret = auth.character(result.characters[charnum].characterID) sheet = ret.CharacterSheet() print(sheet.name)
def api_connect(): timestamp = int(time.time()) if api_connect.timestamp == timestamp: api_connect.counter += 1 if api_connect.counter == settings.EVE_API_REQUESTS: #if api_connect.counter == 10: time.sleep(1) api_connect.counter = 0 api_connect.timestamp = timestamp else: api_connect.timestamp = timestamp api_connect.counter = 0 return eveapi.EVEAPIConnection()
def clean(self): key = self.cleaned_data['key_ID'] vcode = self.cleaned_data['verification_code'] if Api.objects.filter(key=key, vcode=vcode).exists(): raise forms.ValidationError("This key has already been entered") #connect with api and validate key api = eveapi.EVEAPIConnection() auth = api.auth(keyID=key, vCode=vcode) try: keyinfo = auth.account.APIKeyInfo() except RuntimeError: raise forms.ValidationError("Invallid data, cannot connect to api")
def check_server_status(): """ Checks the server status, if it detects the server is down, set updated=False on all signatures. """ api = eveapi.EVEAPIConnection(cacheHandler=handler) try: statusapi = api.server.ServerStatus() except: # API is down, assume the server is down as well Signature.objects.all().update(updated=False) return if statusapi.serverOpen == u'True': return Signature.objects.all().update(updated=False)
def update_corporation(corpID, sync=False): """ Updates a corporation from the API. If it's alliance doesn't exist, update that as well. """ api = eveapi.EVEAPIConnection(cacheHandler=handler) # Encapsulate this in a try block because one corp has a f****d # up character that chokes eveapi try: corpapi = api.corp.CorporationSheet(corporationID=corpID) except: raise AttributeError("Invalid Corp ID or Corp has malformed data.") if corpapi.allianceID: try: alliance = Alliance.objects.get(id=corpapi.allianceID) except: # If the alliance doesn't exist, we start a task to add it # and terminate this task since the alliance task will call # it after creating the alliance object if not sync: update_alliance.delay(corpapi.allianceID) return else: # Something is waiting and requires the corp object # We set alliance to None and kick off the # update_alliance task to fix it later alliance = None update_alliance.delay(corpapi.allianceID) else: alliance = None if Corporation.objects.filter(id=corpID).count(): # Corp exists, update it corp = Corporation.objects.get(id=corpID) corp.member_count = corpapi.memberCount corp.ticker = corpapi.ticker corp.name = corpapi.corporationName corp.alliance = alliance corp.save() else: # Corp doesn't exist, create it corp = Corporation(id=corpID, member_count=corpapi.memberCount, name=corpapi.corporationName, alliance=alliance) corp.save() return corp
def evetime(self, irc, msg, args): """ Get current time on Tranquility """ api = eveapi.EVEAPIConnection() status = api.server.ServerStatus() tq_time = datetime.datetime.utcfromtimestamp(status._meta.currentTime) SERVER_STATUS = { 'True': ircutils.mircColor('online', fg='green'), 'False': ircutils.mircColor('offline', fg='red'), } irc.reply( '{0}, Tranquility is {1} with {2:,d} players logged in'.format( ircutils.bold(tq_time.time()), SERVER_STATUS[status.serverOpen], status.onlinePlayers), prefixNick=False)
def probe(keys, endpoints): output = {} for namespace in ('Corp', 'Char'): api = eveapi.EVEAPIConnection(cacheHandler=MyCacheHandler(debug=False)) auth = api.auth(keyID=keys[namespace]['keyID'], vCode=keys[namespace]['vCode']) characterID = keys[namespace]['characterID'] output[namespace] = {} for endpoint in endpoints[namespace]: sys.stderr.write('Probing %s %s\n' % (namespace, endpoint)) if len(endpoints[namespace][endpoint]['keys']) > 1: continue output[namespace][endpoint] = {} try: #FIXME: should use keys from endpoints to determine what parameters to pass res = getattr(getattr(auth, namespace), endpoint)(characterID=characterID) except Exception, e: sys.stderr.write('%s: %s\n' % (endpoint, e)) output[namespace][endpoint] = '#FIXME' continue attributes = filter(lambda l: not l.startswith('_'), dir(res)) for attribute in attributes: attribute_type = type(getattr(res, attribute)).__name__ if not attribute_type == 'IndexRowset': output[namespace][endpoint][attribute] = attribute_type else: rowset = getattr(res, attribute) columns = rowset.columns.split(',') subtable = {} try: sample_row = rowset[0] for column in columns: column = column.strip() subtable[str(column)] = str( type(getattr(sample_row, column)).__name__) except IndexError: for column in columns: subtable[str(column)] = '#FIXME' except AttributeError: sys.stderr.write( 'Error parsing "%s", columns: "%s"\n' % (attribute, columns)) output[namespace][endpoint][attribute] = subtable output[namespace][endpoint]['_fk'] = endpoints[namespace][ endpoint]['keys']
def update_from_import_list(cls, system, import_list): """ Imports starbases from YAML importer. """ for pos in import_list: planet = pos['planet'] moon = pos['moon'] warpin = pos['warpin'] status = pos['status'] rftime = pos['rftime'] name = pos['name'] tower = Type.objects.get(name=pos['tower']) try: owner = Corporation.objects.get(name=pos['owner']) except Corporation.DoesNotExist: from core import tasks api = eveapi.EVEAPIConnection(cacheHandler=handler) corp_id = api.eve.CharacterID( names=pos['owner']).characters[0].characterID owner = tasks.update_corporation(corp_id, True) if POS.objects.filter(system=system, planet=planet, moon=moon, corporation=owner).exists(): # Update first existing record starbase = POS.objects.filter(system=system, planet=planet, moon=moon, corporation=owner).all()[0] starbase.status = status starbase.name = name starbase.towertype = tower if status == 3: starbase.rftime = rftime starbase.warpin_notice = warpin else: new_pos = POS(system=system, planet=planet, moon=moon, corporation=owner, towertype=tower, warpin_notice=warpin, status=status) if status == 3: new_pos.rftime = rftime new_pos.save()
def add_stations(): api = eveapi.EVEAPIConnection() outposts = api.eve.ConquerableStationList().outposts for o in outposts: try: ConquerableStation.objects.create( stationID = o.stationID, stationName = o.stationName, stationTypeID = o.stationTypeID, solarSystemID = o.solarSystemID, corporationID = o.corporationID, corporationName = o.corporationName, ) except: print "aaapje faalhaas"
def set_acces_fields(self): api = eveapi.EVEAPIConnection() auth = api.auth(keyID=self.key, vCode=self.vcode) if self.category == u'Corporation': #Will come fields = Api.corporation_acces_fields() for field in fields: acces = getattr(self, "corp_" + field + "_acces")(auth, self.corporation.corporationID) setattr(self, field, acces) else: fields = Api.character_acces_fields() character = self.character_set.all()[0] for field in fields: acces = getattr(self, field + "_acces")(auth, character.characterID) setattr(self, field, acces) self.save()
def update_alliance(allianceID): """ Updates an alliance and it's corporations from the API. """ api = eveapi.EVEAPIConnection(cacheHandler=handler) allianceapi = api.eve.AllianceList().alliances.Get(allianceID) if Alliance.objects.filter(id=allianceID).count(): # Alliance exists, update it for corp in allianceapi.memberCorporations: try: update_corporation(corp.corporationID) except AttributeError: # Pass on this exception because one Russian corp has an # unavoidable bad character in their description pass alliance = Alliance.objects.get(id=allianceID) alliance.name = allianceapi.name alliance.shortname = allianceapi.shortName # Check to see if we have a record for the executor if Corporation.objects.filter(id=allianceapi.executorCorpID).count(): alliance.executor = Corporation.objects.get( id=allianceapi.executorCorpID) else: # Alliance doesn't exists, add it without executor, update corps # and then update the executor alliance = Alliance(id=allianceapi.allianceID, name=allianceapi.name, shortname=allianceapi.shortName, executor=None) alliance.save() for corp in allianceapi.memberCorporations: try: update_corporation(corp.corporationID) except AttributeError: # F**k you, xCAPITALSx pass try: # If an alliance's executor can't be processed for some reason, # set it to None alliance.executor = Corporation.objects.get( id=allianceapi.executorCorpID) except: alliance.executor = None alliance.save()