update_companies.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from __future__ import annotations
  2. import json
  3. import tomllib
  4. import typing
  5. import httpx
  6. def main() -> None:
  7. with open('config.toml', 'rb') as f:
  8. config = tomllib.load(f)
  9. fio_api_key = config['fio_api_key']
  10. with open('www/data/knownCompanies.json', 'r') as f:
  11. companies: dict = json.load(f)
  12. usernames = {co['Username'].casefold(): co_id for co_id, co in companies.items() if co['Username'] is not None}
  13. all_companies: list[FIOCompany] = httpx.get('https://rest.fnar.net/company/all',
  14. headers={'Authorization': fio_api_key}).raise_for_status().json()
  15. all_companies.sort(key=lambda co: co['Timestamp']) # duplicate usernames appear due to COLIQs
  16. try:
  17. for company in all_companies:
  18. username = company['UserName']
  19. if username is None:
  20. print(company['CompanyId'], 'has no username:', company)
  21. continue
  22. old_co_id = usernames.get(username.casefold())
  23. if old_co_id is not None and old_co_id != company['CompanyId']:
  24. print(username, 'previously known as', old_co_id)
  25. companies.pop(old_co_id, None)
  26. known_company = {'Username': username}
  27. if corp := company.get('CorporationCode'):
  28. known_company['Corporation'] = corp
  29. if known_company == companies.get(company['CompanyId']):
  30. print(username, 'had no change')
  31. else:
  32. print(known_company)
  33. companies[company['CompanyId']] = known_company
  34. finally:
  35. with open('www/data/knownCompanies.json', 'w') as f:
  36. json.dump(companies, f)
  37. class FIOCompany(typing.TypedDict):
  38. CompanyId: str
  39. UserName: str | None
  40. CorporationCode: str | None
  41. Timestamp: str
  42. if __name__ == '__main__':
  43. main()