itunes_xml.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import argparse
  2. import os
  3. import re
  4. import sys
  5. import symuid
  6. import symuid.library.itunes
  7. # TODO rename module to itunes.py
  8. # after ImportMismatchError on `pytest --doctest-modules` was fixed
  9. def import_itunes_xml_library(xml_library_path, path_regex_sub):
  10. lib = symuid.library.itunes.XmlLibrary(xml_library_path)
  11. for itunes_track in lib.tracks:
  12. # TODO create tag if last_play_dt is None
  13. if itunes_track.last_play_dt and itunes_track.local:
  14. track_path = itunes_track.local_path
  15. for pattern, repl in path_regex_sub:
  16. track_path = re.sub(pattern, repl, track_path)
  17. if not os.path.exists(track_path):
  18. sys.stderr.write("{!r}: not found\n".format(track_path))
  19. else:
  20. symuid_track = symuid.Track(path=track_path)
  21. # TODO dt=dt.datetime.now()
  22. symuid_track.register_play_count(
  23. symuid.PlayCount(
  24. player="itunes",
  25. library_id=lib.library_id,
  26. register_dt=itunes_track.last_play_dt,
  27. count=itunes_track.play_count,
  28. ),
  29. tag_set_cb=lambda tr, tag: print(
  30. "{!r}: set tag {!r}".format(tr.path, tag)
  31. ),
  32. )
  33. def _main():
  34. argparser = argparse.ArgumentParser(
  35. description="Import play counts from iTunes XML Library"
  36. )
  37. argparser.add_argument("xml_library_path")
  38. argparser.add_argument(
  39. "--path-regex-sub",
  40. nargs=2,
  41. action="append",
  42. metavar=("regex", "replacement"),
  43. default=[],
  44. help="(default: no substitution)",
  45. )
  46. args = argparser.parse_args()
  47. import_itunes_xml_library(**vars(args))