xattrpp.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os
  2. from .common import PostProcessor
  3. from ..utils import (
  4. PostProcessingError,
  5. XAttrMetadataError,
  6. XAttrUnavailableError,
  7. hyphenate_date,
  8. write_xattr,
  9. )
  10. class XAttrMetadataPP(PostProcessor):
  11. """Set extended attributes on downloaded file (if xattr support is found)
  12. More info about extended attributes for media:
  13. http://freedesktop.org/wiki/CommonExtendedAttributes/
  14. http://www.freedesktop.org/wiki/PhreedomDraft/
  15. http://dublincore.org/documents/usageguide/elements.shtml
  16. TODO:
  17. * capture youtube keywords and put them in 'user.dublincore.subject' (comma-separated)
  18. * figure out which xattrs can be used for 'duration', 'thumbnail', 'resolution'
  19. """
  20. XATTR_MAPPING = {
  21. 'user.xdg.referrer.url': 'webpage_url',
  22. 'user.dublincore.title': 'title',
  23. 'user.dublincore.date': 'upload_date',
  24. 'user.dublincore.contributor': 'uploader',
  25. 'user.dublincore.format': 'format',
  26. # We do this last because it may get us close to the xattr limits
  27. # (e.g., 4kB on ext4), and we don't want to have the other ones fail
  28. 'user.dublincore.description': 'description',
  29. # 'user.xdg.comment': 'description',
  30. }
  31. def run(self, info):
  32. mtime = os.stat(info['filepath']).st_mtime
  33. self.to_screen('Writing metadata to file\'s xattrs')
  34. for xattrname, infoname in self.XATTR_MAPPING.items():
  35. try:
  36. value = info.get(infoname)
  37. if value:
  38. if infoname == 'upload_date':
  39. value = hyphenate_date(value)
  40. write_xattr(info['filepath'], xattrname, value.encode())
  41. except XAttrUnavailableError as e:
  42. raise PostProcessingError(str(e))
  43. except XAttrMetadataError as e:
  44. if e.reason == 'NO_SPACE':
  45. self.report_warning(
  46. 'There\'s no disk space left, disk quota exceeded or filesystem xattr limit exceeded. '
  47. f'Extended attribute "{xattrname}" was not written.')
  48. elif e.reason == 'VALUE_TOO_LONG':
  49. self.report_warning(f'Unable to write extended attribute "{xattrname}" due to too long values.')
  50. else:
  51. tip = ('You need to use NTFS' if os.name == 'nt'
  52. else 'You may have to enable them in your "/etc/fstab"')
  53. raise PostProcessingError(f'This filesystem doesn\'t support extended attributes. {tip}')
  54. self.try_utime(info['filepath'], mtime, mtime)
  55. return [], info