cmd_listening-stats.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import asyncio
  2. import json
  3. import logging
  4. import pathlib
  5. from datetime import datetime
  6. import click
  7. from audible_cli.decorators import pass_client
  8. logger = logging.getLogger("audible_cli.cmds.cmd_listening-stats")
  9. current_year = datetime.now().year
  10. def ms_to_hms(milliseconds):
  11. seconds = int((milliseconds / 1000) % 60)
  12. minutes = int(((milliseconds / (1000*60)) % 60))
  13. hours = int(((milliseconds / (1000*60*60)) % 24))
  14. return {"hours": hours, "minutes": minutes, "seconds": seconds}
  15. async def _get_stats_year(client, year):
  16. stats_year = {}
  17. stats = await client.get(
  18. "stats/aggregates",
  19. monthly_listening_interval_duration="12",
  20. monthly_listening_interval_start_date=f"{year}-01",
  21. store="Audible"
  22. )
  23. # iterate over each month
  24. for stat in stats['aggregated_monthly_listening_stats']:
  25. stats_year[stat["interval_identifier"]] = ms_to_hms(stat["aggregated_sum"])
  26. return stats_year
  27. @click.command("listening-stats")
  28. @click.option(
  29. "--output", "-o",
  30. type=click.Path(path_type=pathlib.Path),
  31. default=pathlib.Path().cwd() / "listening-stats.json",
  32. show_default=True,
  33. help="output file"
  34. )
  35. @click.option(
  36. "--signup-year", "-s",
  37. type=click.IntRange(1997, current_year),
  38. default="2010",
  39. show_default=True,
  40. help="start year for collecting listening stats"
  41. )
  42. @pass_client
  43. async def cli(client, output, signup_year):
  44. """get and analyse listening statistics"""
  45. year_range = [y for y in range(signup_year, current_year+1)]
  46. r = await asyncio.gather(
  47. *[_get_stats_year(client, y) for y in year_range]
  48. )
  49. aggregated_stats = {}
  50. for i in r:
  51. for k, v in i.items():
  52. aggregated_stats[k] = v
  53. aggregated_stats = json.dumps(aggregated_stats, indent=4)
  54. output.write_text(aggregated_stats)