PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/runserver.py

https://gitlab.com/tecta/PokemonGo-Map
Python | 165 lines | 144 code | 11 blank | 10 comment | 7 complexity | 523b3a30b80dd5c29f1392b53488b15a MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import shutil
  6. import logging
  7. import time
  8. import re
  9. # Currently supported pgoapi
  10. pgoapi_version = "1.1.6"
  11. # Moved here so logger is configured at load time
  12. logging.basicConfig(format='%(asctime)s [%(threadName)16s][%(module)14s][%(levelname)8s] %(message)s')
  13. log = logging.getLogger()
  14. # Make sure pogom/pgoapi is actually removed if it is an empty directory
  15. # This is a leftover directory from the time pgoapi was embedded in PokemonGo-Map
  16. # The empty directory will cause problems with `import pgoapi` so it needs to go
  17. oldpgoapiPath = os.path.join(os.path.dirname(__file__), "pogom/pgoapi")
  18. if os.path.isdir(oldpgoapiPath):
  19. log.info("I found %s, but its no longer used. Going to remove it...", oldpgoapiPath)
  20. shutil.rmtree(oldpgoapiPath)
  21. log.info("Done!")
  22. # Assert pgoapi is installed
  23. try:
  24. import pgoapi
  25. except ImportError:
  26. log.critical("It seems `pgoapi` is not installed. You must run pip install -r requirements.txt again")
  27. sys.exit(1)
  28. # Assert pgoapi >= 1.1.6 is installed
  29. from distutils.version import StrictVersion
  30. if not hasattr(pgoapi, "__version__") or StrictVersion(pgoapi.__version__) < StrictVersion(pgoapi_version):
  31. log.critical("It seems `pgoapi` is not up-to-date. You must run pip install -r requirements.txt again")
  32. sys.exit(1)
  33. from threading import Thread, Event
  34. from queue import Queue
  35. from flask_cors import CORS
  36. from pogom import config
  37. from pogom.app import Pogom
  38. from pogom.utils import get_args, insert_mock_data, get_encryption_lib_path
  39. from pogom.search import search_overseer_thread, fake_search_loop
  40. from pogom.models import init_database, create_tables, drop_tables, Pokemon, Pokestop, Gym
  41. from pgoapi import utilities as util
  42. if __name__ == '__main__':
  43. # Check if we have the proper encryption library file and get its path
  44. encryption_lib_path = get_encryption_lib_path()
  45. if encryption_lib_path is "":
  46. sys.exit(1)
  47. args = get_args()
  48. if args.debug:
  49. log.setLevel(logging.DEBUG);
  50. else:
  51. log.setLevel(logging.INFO);
  52. # Let's not forget to run Grunt / Only needed when running with webserver
  53. if not args.no_server:
  54. if not os.path.exists(os.path.join(os.path.dirname(__file__), 'static/dist')):
  55. log.critical('Please run "grunt build" before starting the server');
  56. sys.exit();
  57. # These are very noisey, let's shush them up a bit
  58. logging.getLogger('peewee').setLevel(logging.INFO)
  59. logging.getLogger('requests').setLevel(logging.WARNING)
  60. logging.getLogger('pgoapi.pgoapi').setLevel(logging.WARNING)
  61. logging.getLogger('pgoapi.rpc_api').setLevel(logging.INFO)
  62. logging.getLogger('werkzeug').setLevel(logging.ERROR)
  63. config['parse_pokemon'] = not args.no_pokemon
  64. config['parse_pokestops'] = not args.no_pokestops
  65. config['parse_gyms'] = not args.no_gyms
  66. # Turn these back up if debugging
  67. if args.debug:
  68. logging.getLogger('requests').setLevel(logging.DEBUG)
  69. logging.getLogger('pgoapi').setLevel(logging.DEBUG)
  70. logging.getLogger('rpc_api').setLevel(logging.DEBUG)
  71. # use lat/lng directly if matches such a pattern
  72. prog = re.compile("^(\-?\d+\.\d+),?\s?(\-?\d+\.\d+)$")
  73. res = prog.match(args.location)
  74. if res:
  75. log.debug('Using coords from CLI directly')
  76. position = (float(res.group(1)), float(res.group(2)), 0)
  77. else:
  78. log.debug('Lookig up coords in API')
  79. position = util.get_pos_by_name(args.location)
  80. if not any(position):
  81. log.error('Could not get a position by name, aborting')
  82. sys.exit()
  83. log.info('Parsed location is: %.4f/%.4f/%.4f (lat/lng/alt)',
  84. position[0], position[1], position[2])
  85. if args.no_pokemon:
  86. log.info('Parsing of Pokemon disabled')
  87. if args.no_pokestops:
  88. log.info('Parsing of Pokestops disabled')
  89. if args.no_gyms:
  90. log.info('Parsing of Gyms disabled')
  91. config['LOCALE'] = args.locale
  92. config['CHINA'] = args.china
  93. app = Pogom(__name__)
  94. db = init_database(app)
  95. if args.clear_db:
  96. log.info('Clearing database')
  97. if args.db_type == 'mysql':
  98. drop_tables(db)
  99. elif os.path.isfile(args.db):
  100. os.remove(args.db)
  101. create_tables(db)
  102. app.set_current_location(position);
  103. # Control the search status (running or not) across threads
  104. pause_bit = Event()
  105. pause_bit.clear()
  106. # Setup the location tracking queue and push the first location on
  107. new_location_queue = Queue()
  108. new_location_queue.put(position)
  109. if not args.only_server:
  110. # Gather the pokemons!
  111. if not args.mock:
  112. log.debug('Starting a real search thread')
  113. search_thread = Thread(target=search_overseer_thread, args=(args, new_location_queue, pause_bit, encryption_lib_path))
  114. else:
  115. log.debug('Starting a fake search thread')
  116. insert_mock_data(position)
  117. search_thread = Thread(target=fake_search_loop)
  118. search_thread.daemon = True
  119. search_thread.name = 'search_thread'
  120. search_thread.start()
  121. if args.cors:
  122. CORS(app);
  123. app.set_search_control(pause_bit)
  124. app.set_location_queue(new_location_queue)
  125. config['ROOT_PATH'] = app.root_path
  126. config['GMAPS_KEY'] = args.gmaps_key
  127. if args.no_server:
  128. # This loop allows for ctrl-c interupts to work since flask won't be holding the program open
  129. while search_thread.is_alive():
  130. time.sleep(60)
  131. else:
  132. app.run(threaded=True, use_reloader=False, debug=args.debug, host=args.host, port=args.port)