Beispiel #1
0
  def __init__(self):
    # Set up caching.
    cache_file = os.path.join(tempfile.gettempdir(), 'koscheck')
    self.cache = SqliteCache(cache_file)

    self.api = api.API(cache=self.cache)
    self.eve = eve.EVE(api=self.api)
Beispiel #2
0
def class_test():
    if not os.path.exists('config.yml'):
        print("config.yml not found")
        print("please edit config_example.yml and rename it to config.yml")
        sys.exit(1)

    import yaml
    config = yaml.load(file('config.yml'))

    print "Config loaded"

    apikey = (config['key'], config['verification'])

    from evelink.cache.sqlite import SqliteCache
    evelink_cache = SqliteCache('db/evelink_cache.db')

    # API with cache and correct api key
    api = evelink.api.API(api_key=apikey, cache=evelink_cache)

    print "API connected"

    # account data
    a = evelink.account.Account(api)

    # loop through character id's in api
    for char_id in a.characters().result:
        print "Creating character", char_id
        c = CharacterFactory.create_character(api, char_id)
        print c.name
        print c.get_skill_queue_items()
        print c.get_active_jobs_items()
Beispiel #3
0
def main(apikey):
    from evelink.cache.sqlite import SqliteCache
    evelink_cache = SqliteCache('db/evelink_cache.db')

    api = evelink.api.API(api_key=apikey, cache=evelink_cache)

    a = evelink.account.Account(api)

    try:
        for char_id in a.characters().result:
            print("-" * 30)
            char = evelink.char.Char(char_id, api)
            print_charactersheet(char, api)
            print_industry_jobs(char, api)
            print_orders(char, api)
    except evelink.api.APIError, e:
        print("Api Error:", e)
Beispiel #4
0
    def onStart(self):
        if not os.path.exists('config.yml'):
            print("config.yml not found")
            print("please edit config_example.yml and rename it to config.yml")
            sys.exit(1)

        import yaml
        config = yaml.load(file('config.yml'))

        apikey = (config['key'], config['verification'])

        from evelink.cache.sqlite import SqliteCache
        evelink_cache = SqliteCache('db/evelink_cache.db')

        # API with cache and correct api key
        self.api = evelink.api.API(api_key=apikey, cache=evelink_cache)

        self.addForm("MAIN", CharacterSummary, name="MAIN")
        self.addForm("Detailed", CharacterSummary, name="Detailed")
Beispiel #5
0
def main(apikey):
    from evelink.cache.sqlite import SqliteCache
    evelink_cache = SqliteCache('db/evelink_cache.db')

    api = evelink.api.API(api_key=apikey, cache=evelink_cache)

    a = evelink.account.Account(api)

    # clear the table, makes easier to keep it up to date
    # updating would work, but removing items that no longer exists is a pain
    db['assets'].drop()

    try:
        for char_id in a.characters().result:
            print("-" * 30)
            char = evelink.char.Char(char_id, api)
            grand_total = print_assets(char, api)

            print("*" * 30)
            print(grand_total, "ISK")
            print("*" * 30)
    except evelink.api.APIError, e:
        print("Api Error:", e)
Beispiel #6
0
 def setUp(self):
     self.cache_dir = tempfile.mkdtemp()
     self.cache_path = os.path.join(self.cache_dir, 'sqlite')
     self.cache = SqliteCache(self.cache_path)
Beispiel #7
0
class SqliteCacheTestCase(unittest.TestCase):

    def setUp(self):
        self.cache_dir = tempfile.mkdtemp()
        self.cache_path = os.path.join(self.cache_dir, 'sqlite')
        self.cache = SqliteCache(self.cache_path)

    def tearDown(self):
        self.cache.connection.close()
        try:
          os.remove(self.cache_path)
        except OSError:
          pass
        try:
          os.rmdir(self.cache_dir)
        except OSError:
          pass

    def test_cache(self):
        self.cache.put('foo', 'bar', 3600)
        self.cache.put('bar', 1, 3600)
        self.cache.put('baz', True, 3600)
        self.assertEqual(self.cache.get('foo'), 'bar')
        self.assertEqual(self.cache.get('bar'), 1)
        self.assertEqual(self.cache.get('baz'), True)

    def test_expire(self):
        self.cache.put('baz', 'qux', -1)
        self.assertEqual(self.cache.get('baz'), None)
Beispiel #8
0
def get_api_key(key):
    if isinstance(key, API):
        return key
    key_id, v_code, entity_id = get_key_config(key)
    return API(api_key=(key_id, v_code),
               cache=SqliteCache(_config.get_option('cache_location')))
Beispiel #9
0
class KosChecker:
  """Maintains API state and performs KOS checks."""

  def __init__(self):
    # Set up caching.
    cache_file = os.path.join(tempfile.gettempdir(), 'koscheck')
    self.cache = SqliteCache(cache_file)

    self.api = api.API(cache=self.cache)
    self.eve = eve.EVE(api=self.api)

  def koscheck(self, player):
    """Checks a given player against the KOS list, including esoteric rules."""
    kos = self.koscheck_internal(player)
    if kos == None or kos == NPC:
      # We were unable to find the player. Use employment history to
      # get their current corp and look that up. If it's an NPC corp,
      # we'll get bounced again.
      history = self.employment_history(player)

      kos = self.koscheck_internal(history[0])
      in_npc_corp = (kos == NPC)

      idx = 0
      while kos == NPC and (idx + 1) < len(history):
        idx = idx + 1
        kos = self.koscheck_internal(history[idx])

      if in_npc_corp and kos != None and kos != NPC and kos != False:
        kos = '%s: %s' % (LASTCORP, history[idx])

    if kos == None or kos == NPC:
      kos = False

    return kos

  def koscheck_internal(self, entity):
    """Looks up KOS entries by directly calling the CVA KOS API."""
    cache_key = self.api._cache_key(KOS_CHECKER_URL, {'entity': entity})

    result = self.cache.get(cache_key)
    if not result:
      result = json.load(urllib2.urlopen(
          KOS_CHECKER_URL % urllib.urlencode({'q' : entity})))
      self.cache.put(cache_key, result, 60*60)

    kos = None
    for value in result['results']:
      # Require exact match (case-insensitively).
      if value['label'].lower() != entity.lower():
        continue
      if value['type'] == 'alliance' and value['ticker'] == None:
        # Bogus alliance created instead of NPC corp.
        continue
      kos = False
      while True:
        if value['kos']:
          kos = '%s: %s' % (value['type'], value['label'])
        if 'npc' in value and value['npc'] and not kos:
          # Signal that further lookup is needed of player's last corp
          return NPC
        if 'corp' in value:
          value = value['corp']
        elif 'alliance' in value:
          value = value['alliance']
        else:
          return kos
      break
    return kos

  def employment_history(self, character):
    """Retrieves a player's most recent corporations via EVE api."""
    cid = self.eve.character_id_from_name(character)
    cdata = self.eve.character_info_from_id(cid)
    corps = cdata['history']
    unique_corps = []
    for corp in corps:
      if corp['corp_id'] not in unique_corps:
        unique_corps.append(corp['corp_id'])
    mapping = self.eve.character_names_from_ids(unique_corps)
    return [mapping[cid] for cid in unique_corps]

  def loop(self, filename, handler):
    """Performs KOS processing on each line read from the log file.

    handler is a function of 3 args: (kos, notkos, error) that is called
    every time there is a new KOS result.
    """
    tailer = FileTailer(filename)
    while True:
      entry, comment = tailer.poll()
      if not entry:
        time.sleep(1.0)
        continue
      kos, not_kos, error = self.koscheck_logentry(entry)
      handler(comment, kos, not_kos, error)

  def koscheck_logentry(self, entry):
    kos = []
    notkos = []
    error = []
    for person in entry:
      if person.isspace() or len(person) == 0:
        continue
      person = person.strip(' .')
      try:
        result = self.koscheck(person)
        if result != False:
          kos.append((person, result))
        else:
          notkos.append(person)
      except:
        error.append(person)
    return (kos, notkos, error)
Beispiel #10
0
 def setUp(self):
     self.cache_dir = tempfile.mkdtemp()
     self.cache_path = os.path.join(self.cache_dir, 'sqlite')
     self.cache = SqliteCache(self.cache_path)
Beispiel #11
0
class SqliteCacheTestCase(unittest.TestCase):
    def setUp(self):
        self.cache_dir = tempfile.mkdtemp()
        self.cache_path = os.path.join(self.cache_dir, 'sqlite')
        self.cache = SqliteCache(self.cache_path)

    def tearDown(self):
        self.cache.connection.close()
        try:
            os.remove(self.cache_path)
        except OSError:
            pass
        try:
            os.rmdir(self.cache_dir)
        except OSError:
            pass

    def test_cache(self):
        self.cache.put('foo', 'bar', 3600)
        self.cache.put('bar', 1, 3600)
        self.cache.put('baz', True, 3600)
        self.assertEqual(self.cache.get('foo'), 'bar')
        self.assertEqual(self.cache.get('bar'), 1)
        self.assertEqual(self.cache.get('baz'), True)

    def test_expire(self):
        self.cache.put('baz', 'qux', -1)
        self.assertEqual(self.cache.get('baz'), None)
Beispiel #12
0
def keys_from_args(args):
    return [(int(args[i]), args[i + 1]) for i in range(1, len(args) - 1, 2)]


def keys_from_config(config):
    return [(config.getint(section, 'keyID'), config.get(section, 'vCode'))
            for section in config.sections() if section.startswith('key:')]


if __name__ == "__main__":
    logging.basicConfig(format='%(levelname)s:%(message)s',
                        level=logging.DEBUG)

    config = ConfigParser.RawConfigParser()
    config.read('posmon.ini')

    print config.get('posmon', 'sde_db_uri')
    sde_initialize(config.get('posmon', 'sde_db_uri'))

    if len(sys.argv) > 1:
        keys = keys_from_args(sys.argv)
    else:
        keys = keys_from_config(config)
    for key_id, vcode in keys:
        api_key = API(api_key=(key_id, vcode),
                      cache=SqliteCache(config.get('posmon', 'cache')))
        if len(sys.argv) > 1:
            process(api_key, format=sys.argv[1], config=config)
        else:
            process(api_key, config=config)
Beispiel #13
0
cache_path = config.get('posmon', 'cache')
sde_db_uri = config.get('posmon', 'sde_db_uri')
try:
    sentry_uri = config.get('posmon', 'sentry.uri')
except ConfigParser.NoOptionError:
    sentry_uri = None

# Set up logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
if sentry_uri:
    from raven.handlers.logging import SentryHandler
    sentry_handler = SentryHandler(sentry_uri)
    sentry_handler.setLevel(logging.WARNING)
    logging.getLogger().addHandler(sentry_handler)

sde.initialize(sde_db_uri)

# Run!
cache=SqliteCache(cache_path)
fmt = sys.argv[1] if len(sys.argv) > 1 else 'text'
for key_id, vcode in keys:
    api_key = API(api_key=(key_id, vcode), cache=cache)
    try:
        process(api_key, format=fmt, config=config)
    except Exception as e:
        if fmt == 'text':
            print "error processing key: %s" % (str(e),)
        else:
            print json.dumps({'error': str(e)})
        logging.exception(str(e))