app.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """General function module"""
  2. import random
  3. from datetime import datetime, timedelta
  4. from app import LOGGER, SCHEDULER, RESOURCE_IDS, RESOURCE_MAX, jobs, api
  5. def check_resources(resource_id):
  6. """Check resources and refill if necessary"""
  7. regions = api.download_resources(resource_id)
  8. LOGGER.info('Check resource %s', RESOURCE_IDS[resource_id])
  9. print_resources(regions, resource_id)
  10. refill_percentage = 25
  11. if need_refill(regions, refill_percentage):
  12. max_seconds = max_refill_seconds(regions, refill_percentage, 900)
  13. random_seconds = random.randint(0, max_seconds)
  14. random_time_delta = timedelta(seconds=random_seconds)
  15. scheduled_date = datetime.now() + random_time_delta
  16. job_id = 'refill_{}'.format(resource_id)
  17. LOGGER.info(
  18. 'Refill resource %s at %s (%s minutes)', RESOURCE_IDS[resource_id],
  19. scheduled_date, round(random_time_delta.seconds / 60)
  20. )
  21. SCHEDULER.add_job(
  22. jobs.refill_resource,
  23. 'date',
  24. args=[resource_id],
  25. id=job_id,
  26. run_date=scheduled_date,
  27. replace_existing=True
  28. )
  29. def print_resources(regions, resource_id):
  30. """print resources"""
  31. if regions:
  32. LOGGER.info('----- %s region(s)', len(regions))
  33. LOGGER.info('region expl max D left c % t %')
  34. for region in regions.values():
  35. region['explored_percentage'] = 100 / region['maximum'] * region['explored']
  36. region['total_left'] = region['explored'] + region['limit_left']
  37. region['total_percentage'] = 100 / RESOURCE_MAX[resource_id] * region['total_left']
  38. row = '{:25}: {:7.2f}{:4}{:4}{:5}{:7.2f}{:7.2f}'.format(
  39. region['region_name'], region['explored'], region['maximum'],
  40. region['deep_exploration'], region['limit_left'],
  41. region['explored_percentage'], region['total_percentage']
  42. )
  43. LOGGER.info(row)
  44. LOGGER.info('-----')
  45. else:
  46. LOGGER.error('no region to print data')
  47. def need_refill(regions, limit):
  48. """Check if refill is needed"""
  49. for region in regions.values():
  50. percentage = 100 / region['maximum'] * region['explored']
  51. if percentage < limit and region['limit_left']:
  52. return True
  53. return False
  54. def max_refill_seconds(regions, limit, max_time):
  55. """Give random seconds for next refill"""
  56. lowest_percentage = limit
  57. for region in regions.values():
  58. percentage = 100 / region['maximum'] * region['explored']
  59. if percentage < lowest_percentage:
  60. lowest_percentage = percentage
  61. return int(max_time / limit * lowest_percentage)