itunes_xml.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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:
  30. print('{!r}: set tag {!r}'.format(tr.path, tag)),
  31. )
  32. def _main():
  33. argparser = argparse.ArgumentParser(description='Import play counts from iTunes XML Library')
  34. argparser.add_argument('xml_library_path')
  35. argparser.add_argument(
  36. '--path-regex-sub',
  37. nargs=2,
  38. action='append',
  39. metavar=('regex', 'replacement'),
  40. default=[],
  41. help='(default: no substitution)',
  42. )
  43. args = argparser.parse_args()
  44. import_itunes_xml_library(**vars(args))