update_companies.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. from __future__ import annotations
  2. import time
  3. import json
  4. import tomllib
  5. import typing
  6. import httpx
  7. def main() -> None:
  8. with open('config.toml', 'rb') as f:
  9. config = tomllib.load(f)
  10. fio_api_key = config['fio_api_key']
  11. with open('www/data/knownCompanies.json', 'r') as f:
  12. companies = json.load(f)
  13. now = int(time.time())
  14. cached: set[str] = set()
  15. for co in companies.values():
  16. co_last_update = co.get('LastUpdated')
  17. if co_last_update is not None and now - co_last_update < 24 * 60 * 60:
  18. cached.add(co['Username'].casefold())
  19. print(len(cached), 'cached companies')
  20. all_users: typing.Collection[str] = httpx.get('https://rest.fnar.net/user/allusers',
  21. headers={'Authorization': fio_api_key}).raise_for_status().json()
  22. try:
  23. for username in all_users:
  24. if username.casefold() in cached:
  25. continue
  26. response = get_with_retry('https://rest.fnar.net/user/' + username)
  27. if response.status_code in (204, 404):
  28. print(username, 'not found')
  29. continue
  30. fio_user = response.json()
  31. assert username.casefold() == fio_user['UserName'].casefold(), f'{username} != {fio_user["UserName"]}'
  32. known_user = {'Username': username, 'LastUpdated': now}
  33. if corp := fio_user.get('CorporationCode'):
  34. known_user['Corporation'] = corp
  35. if known_user == companies.get(fio_user['CompanyId']):
  36. print(username, 'had no change')
  37. else:
  38. print(known_user)
  39. companies[fio_user['CompanyId']] = known_user
  40. finally:
  41. with open('www/data/knownCompanies.json', 'w') as f:
  42. json.dump(companies, f)
  43. def get_with_retry(url) -> httpx.Response:
  44. for attempt in range(10):
  45. try:
  46. response = httpx.get(url)
  47. except httpx.TransportError as e:
  48. print(e, 'retrying in', attempt)
  49. time.sleep(attempt)
  50. continue
  51. if response.status_code in (204, 404) or response.is_success:
  52. return response
  53. elif attempt == 9:
  54. response.raise_for_status()
  55. print(response.status_code, 'retrying in', attempt)
  56. time.sleep(attempt)
  57. raise AssertionError
  58. if __name__ == '__main__':
  59. main()