__init__.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import datetime as dt
  2. import os
  3. import re
  4. import mutagen
  5. from symuid import _tag_interface
  6. from symuid._datetime import datetime_utc_now
  7. def _timestamp_to_utc_dt(ts_sec):
  8. return dt.datetime.utcfromtimestamp(ts_sec) \
  9. .replace(tzinfo=dt.timezone.utc)
  10. class PlayCount:
  11. def __init__(self, player, library_id, register_dt, count):
  12. self.player = player
  13. self.library_id = library_id
  14. assert isinstance(register_dt, dt.datetime), register_dt
  15. assert register_dt.tzinfo is not None, register_dt
  16. self.register_dt = register_dt
  17. assert isinstance(count, int) and count >= 0, count
  18. self.count = count
  19. def __eq__(self, other):
  20. # pylint: disable=unidiomatic-typecheck
  21. return type(self) == type(other) and vars(self) == vars(other)
  22. def __hash__(self):
  23. attrs_sorted = sorted(vars(self).items(), key=lambda p: p[0])
  24. return hash(tuple(v for k, v in attrs_sorted))
  25. def __repr__(self):
  26. return 'PlayCount({})'.format(', '.join(
  27. '{}={!r}'.format(k, v) for k, v in vars(self).items()
  28. ))
  29. class Track:
  30. PATH_DEFAULT_IGNORE_REGEX = r'\.(itdb|itc2|itl|jpg|midi?|plist|xml|zip)$'
  31. def __init__(self, path):
  32. self._iface = self._select_tag_interface(path)
  33. @staticmethod
  34. def _select_tag_interface(track_path) -> _tag_interface.TagInterface:
  35. mutagen_file = mutagen.File(track_path)
  36. if mutagen_file is None:
  37. raise NotImplementedError(track_path)
  38. if isinstance(mutagen_file.tags, mutagen.id3.ID3):
  39. return _tag_interface.ID3(mutagen_file)
  40. if isinstance(mutagen_file.tags, mutagen.mp4.MP4Tags):
  41. return _tag_interface.MP4(mutagen_file)
  42. if isinstance(mutagen_file, (mutagen.oggopus.OggOpus,
  43. mutagen.oggvorbis.OggVorbis)):
  44. return _tag_interface.Ogg(mutagen_file)
  45. raise NotImplementedError((track_path, type(mutagen_file)))
  46. @property
  47. def path(self):
  48. return self._iface.track_path
  49. @property
  50. def comment(self):
  51. return self._iface.get_comment()
  52. @comment.setter
  53. def comment(self, comment):
  54. self._iface.set_comment(comment)
  55. self._iface.save()
  56. def get_uuid(self):
  57. return self._iface.get_track_uuid()
  58. def assign_uuid(self, uuid):
  59. if self.get_uuid():
  60. raise Exception("{!r} already has an uuid".format(self.path))
  61. self._iface.set_track_uuid(uuid)
  62. self._iface.save()
  63. def _get_play_counts(self, player=None, library_id=None):
  64. label = 'symuid:pcnt'
  65. assert library_id is None or player is not None
  66. if player:
  67. label += ':' + player
  68. if library_id:
  69. label += ':' + library_id
  70. elif library_id:
  71. raise Exception((player, library_id))
  72. for k, count in self._iface.get_free_ints(label):
  73. player, library_id, register_ts_dec = k.split(':')[2:]
  74. yield PlayCount(
  75. player=player,
  76. library_id=library_id,
  77. register_dt=_timestamp_to_utc_dt(int(register_ts_dec)),
  78. count=count,
  79. )
  80. def _get_latest_play_counts(self, player=None, library_id=None):
  81. latest = {}
  82. for count in self._get_play_counts(player, library_id):
  83. if not count.player in latest:
  84. latest[count.player] = {}
  85. if not count.library_id in latest[count.player] \
  86. or latest[count.player][count.library_id].register_dt < count.register_dt:
  87. latest[count.player][count.library_id] = count
  88. return [c for p in latest.values() for c in p.values()]
  89. def get_latest_play_count(self, player, library_id):
  90. assert player is not None, player
  91. assert library_id is not None, library_id
  92. counts = self._get_latest_play_counts(player, library_id)
  93. if len(counts) == 0:
  94. return None
  95. assert len(counts) == 1, counts
  96. return counts[0]
  97. def get_play_count_sum(self, player=None, library_id=None):
  98. return sum(c.count for c in self._get_latest_play_counts(player, library_id))
  99. def register_play_count(self, play_count, tag_set_cb=None):
  100. assert isinstance(play_count, PlayCount), play_count
  101. tag_label = 'symuid:pcnt:{}:{}:{:.0f}'.format(
  102. play_count.player, play_count.library_id,
  103. play_count.register_dt.timestamp(),
  104. )
  105. current_count = self._iface.get_free_int(tag_label)
  106. if current_count is None:
  107. new_tag = self._iface.set_free_int(tag_label, play_count.count)
  108. self._iface.save()
  109. if tag_set_cb:
  110. tag_set_cb(self, new_tag)
  111. elif current_count != play_count.count:
  112. raise Exception((current_count, play_count.count))
  113. def increase_play_count(self, player, library_id, tag_set_cb=None):
  114. current_pc = self.get_latest_play_count(player, library_id)
  115. self.register_play_count(
  116. PlayCount(
  117. player=player,
  118. library_id=library_id,
  119. register_dt=datetime_utc_now(),
  120. count=current_pc.count + 1 if current_pc else 1,
  121. ),
  122. tag_set_cb=tag_set_cb,
  123. )
  124. @classmethod
  125. def walk(cls, root_path, path_ignore_regex, ignored_cb=None, unsupported_cb=None):
  126. for dirpath, _, filenames in os.walk(root_path):
  127. for filename in filenames:
  128. track_path = os.path.join(dirpath, filename)
  129. if path_ignore_regex.search(track_path):
  130. if ignored_cb is not None:
  131. ignored_cb(track_path)
  132. else:
  133. try:
  134. yield cls(track_path)
  135. except NotImplementedError as exc:
  136. if unsupported_cb is not None:
  137. unsupported_cb(track_path, exc)