PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/pogom/utils.py

https://gitlab.com/yenny.prathivi/PokemonGo-Map
Python | 210 lines | 174 code | 32 blank | 4 comment | 23 complexity | 2f0e55412475d555e60d8181d842799e MD5 | raw file
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import sys
  4. import getpass
  5. import configargparse
  6. import uuid
  7. import os
  8. import json
  9. from datetime import datetime, timedelta
  10. import logging
  11. import shutil
  12. import requests
  13. from . import config
  14. log = logging.getLogger(__name__)
  15. def parse_unicode(bytestring):
  16. decoded_string = bytestring.decode(sys.getfilesystemencoding())
  17. return decoded_string
  18. def verify_config_file_exists(filename):
  19. fullpath = os.path.join(os.path.dirname(__file__), filename)
  20. if not os.path.exists(fullpath):
  21. log.info("Could not find " + filename + ", copying default")
  22. shutil.copy2(fullpath + '.example', fullpath)
  23. def get_args():
  24. # fuck PEP8
  25. configpath = os.path.join(os.path.dirname(__file__), '../config/config.ini')
  26. parser = configargparse.ArgParser(default_config_files=[configpath])
  27. parser.add_argument('-a', '--auth-service', type=str.lower,
  28. help='Auth Service', default='ptc')
  29. parser.add_argument('-u', '--username', help='Username')
  30. parser.add_argument('-p', '--password', help='Password')
  31. parser.add_argument('-l', '--location', type=parse_unicode,
  32. help='Location, can be an address or coordinates')
  33. parser.add_argument('-st', '--step-limit', help='Steps', type=int,
  34. default=12)
  35. parser.add_argument('-sd', '--scan-delay',
  36. help='Time delay between requests in scan threads',
  37. type=float, default=5)
  38. parser.add_argument('-td', '--thread-delay',
  39. help='Time delay between each scan thread loop',
  40. type=float, default=5)
  41. parser.add_argument('-ld', '--login-delay',
  42. help='Time delay between each login attempt',
  43. type=float, default=5)
  44. parser.add_argument('-dc', '--display-in-console',
  45. help='Display Found Pokemon in Console',
  46. action='store_true', default=False)
  47. parser.add_argument('-H', '--host', help='Set web server listening host',
  48. default='127.0.0.1')
  49. parser.add_argument('-P', '--port', type=int,
  50. help='Set web server listening port', default=5000)
  51. parser.add_argument('-L', '--locale',
  52. help='Locale for Pokemon names (default: {},\
  53. check {} for more)'.
  54. format(config['LOCALE'], config['LOCALES_DIR']), default='en')
  55. parser.add_argument('-c', '--china',
  56. help='Coordinates transformer for China',
  57. action='store_true')
  58. parser.add_argument('-d', '--debug', help='Debug Mode', action='store_true')
  59. parser.add_argument('-m', '--mock',
  60. help='Mock mode. Starts the web server but not the background thread.',
  61. action='store_true', default=False)
  62. parser.add_argument('-ns', '--no-server',
  63. help='No-Server Mode. Starts the searcher but not the Webserver.',
  64. action='store_true', default=False)
  65. parser.add_argument('-os', '--only-server',
  66. help='Server-Only Mode. Starts only the Webserver without the searcher.',
  67. action='store_true', default=False)
  68. parser.add_argument('-fl', '--fixed-location',
  69. help='Hides the search bar for use in shared maps.',
  70. action='store_true', default=False)
  71. parser.add_argument('-k', '--gmaps-key',
  72. help='Google Maps Javascript API Key',
  73. required=True)
  74. parser.add_argument('-C', '--cors', help='Enable CORS on web server',
  75. action='store_true', default=False)
  76. parser.add_argument('-D', '--db', help='Database filename',
  77. default='pogom.db')
  78. parser.add_argument('-t', '--num-threads', help='Number of search threads', type=int, default=1)
  79. parser.add_argument('-np', '--no-pokemon',
  80. help='Disables Pokemon from the map (including parsing them into local db)',
  81. action='store_true', default=False)
  82. parser.add_argument('-ng', '--no-gyms',
  83. help='Disables Gyms from the map (including parsing them into local db)',
  84. action='store_true', default=False)
  85. parser.add_argument('-nk', '--no-pokestops',
  86. help='Disables PokeStops from the map (including parsing them into local db)',
  87. action='store_true', default=False)
  88. parser.add_argument('--db-type', help='Type of database to be used (default: sqlite)',
  89. default='sqlite')
  90. parser.add_argument('--db-name', help='Name of the database to be used')
  91. parser.add_argument('--db-user', help='Username for the database')
  92. parser.add_argument('--db-pass', help='Password for the database')
  93. parser.add_argument('--db-host', help='IP or hostname for the database')
  94. parser.add_argument('-wh', '--webhook', help='Define URL(s) to POST webhook information to',
  95. nargs='*', default=False, dest='webhooks')
  96. parser.set_defaults(DEBUG=False)
  97. args = parser.parse_args()
  98. if args.only_server:
  99. if args.location is None:
  100. parser.print_usage()
  101. print sys.argv[0] + ': error: arguments -l/--location is required'
  102. sys.exit(1)
  103. else:
  104. if (args.username is None or args.location is None or args.step_limit is None):
  105. parser.print_usage()
  106. print sys.argv[0] + ': error: arguments -u/--username, -l/--location, -st/--step-limit are required'
  107. sys.exit(1)
  108. if config["PASSWORD"] is None and args.password is None:
  109. config["PASSWORD"] = args.password = getpass.getpass()
  110. elif args.password is None:
  111. args.password = config["PASSWORD"]
  112. return args
  113. def insert_mock_data():
  114. num_pokemon = 6
  115. num_pokestop = 6
  116. num_gym = 6
  117. log.info('Creating fake: {} pokemon, {} pokestops, {} gyms'.format(
  118. num_pokemon, num_pokestop, num_gym))
  119. from .models import Pokemon, Pokestop, Gym
  120. from .search import generate_location_steps
  121. latitude, longitude = float(config['ORIGINAL_LATITUDE']),\
  122. float(config['ORIGINAL_LONGITUDE'])
  123. locations = [l for l in generate_location_steps((latitude, longitude),
  124. num_pokemon)]
  125. disappear_time = datetime.now() + timedelta(hours=1)
  126. detect_time = datetime.now()
  127. for i in range(num_pokemon):
  128. Pokemon.create(encounter_id=uuid.uuid4(),
  129. spawnpoint_id='sp{}'.format(i),
  130. pokemon_id=(i+1) % 150,
  131. latitude=locations[i][0],
  132. longitude=locations[i][1],
  133. disappear_time=disappear_time,
  134. detect_time=detect_time)
  135. for i in range(num_pokestop):
  136. Pokestop.create(pokestop_id=uuid.uuid4(),
  137. enabled=True,
  138. latitude=locations[i+num_pokemon][0],
  139. longitude=locations[i+num_pokemon][1],
  140. last_modified=datetime.now(),
  141. # Every other pokestop be lured
  142. lure_expiration=disappear_time if (i % 2 == 0) else None,
  143. active_pokemon_id=i
  144. )
  145. for i in range(num_gym):
  146. Gym.create(gym_id=uuid.uuid4(),
  147. team_id=i % 3,
  148. guard_pokemon_id=(i+1) % 150,
  149. latitude=locations[i + num_pokemon + num_pokestop][0],
  150. longitude=locations[i + num_pokemon + num_pokestop][1],
  151. last_modified=datetime.now(),
  152. enabled=True,
  153. gym_points=1000
  154. )
  155. def get_pokemon_name(pokemon_id):
  156. if not hasattr(get_pokemon_name, 'names'):
  157. file_path = os.path.join(
  158. config['ROOT_PATH'],
  159. config['LOCALES_DIR'],
  160. 'pokemon.{}.json'.format(config['LOCALE']))
  161. with open(file_path, 'r') as f:
  162. get_pokemon_name.names = json.loads(f.read())
  163. return get_pokemon_name.names[str(pokemon_id)]
  164. def send_to_webhook(message_type, message):
  165. args = get_args()
  166. data = {
  167. 'type': message_type,
  168. 'message': message
  169. }
  170. if args.webhooks:
  171. webhooks = args.webhooks
  172. for w in webhooks:
  173. try:
  174. requests.post(w, json=data, timeout=(None, 1))
  175. except requests.exceptions.ReadTimeout:
  176. log.debug('Could not receive response from webhook')
  177. except requests.exceptions.RequestException as e:
  178. log.debug(e)