__init__.py 6.1 KB

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