unused.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. '''
  2. This component will look for files to be removed. There are some assumptions:
  3. * Only files in $TMPDIR are removed. Please remember that larigira has its
  4. own specific TMPDIR
  5. * MPD URIs are parsed, and only file:/// is supported
  6. '''
  7. import os
  8. from os.path import commonpath, normpath
  9. import logging
  10. import mpd
  11. class UnusedCleaner:
  12. def __init__(self, conf):
  13. self.conf = conf
  14. self.waiting_removal_files = set()
  15. self.log = logging.getLogger(self.__class__.__name__)
  16. def _get_mpd(self):
  17. mpd_client = mpd.MPDClient(use_unicode=True)
  18. mpd_client.connect(self.conf['MPD_HOST'], self.conf['MPD_PORT'])
  19. return mpd_client
  20. def watch(self, uri):
  21. '''
  22. adds fpath to the list of "watched" file
  23. as soon as it leaves the mpc playlist, it is removed
  24. '''
  25. if not uri.startswith('file:///'):
  26. return # not a file URI
  27. fpath = uri[len('file://'):]
  28. if 'TMPDIR' in self.conf and self.conf['TMPDIR'] \
  29. and commonpath([self.conf['TMPDIR'], fpath]) != \
  30. normpath(self.conf['TMPDIR']):
  31. self.log.info('Not watching file {}: not in TMPDIR'.format(fpath))
  32. return
  33. if not os.path.exists(fpath):
  34. self.log.warning('a path that does not exist is being monitored')
  35. self.waiting_removal_files.add(fpath)
  36. def check_playlist(self):
  37. '''check playlist + internal watchlist to see what can be removed'''
  38. mpd = self._get_mpd()
  39. files_in_playlist = {song['file'] for song in mpd.playlistid()
  40. if song['file'].startswith('/')}
  41. for fpath in self.waiting_removal_files - files_in_playlist:
  42. # we can remove it!
  43. self.log.debug('removing unused: {}'.format(fpath))
  44. self.waiting_removal_files.remove(fpath)
  45. if os.path.exists(fpath):
  46. os.unlink(fpath)