__init__.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. import os
  2. import subprocess
  3. import sys
  4. import time
  5. from ..utils import (
  6. compat_subprocess_get_DEVNULL,
  7. encodeFilename,
  8. hyphenate_date,
  9. PostProcessingError,
  10. prepend_extension,
  11. shell_quote,
  12. subtitles_filename,
  13. )
  14. class PostProcessor(object):
  15. """Post Processor class.
  16. PostProcessor objects can be added to downloaders with their
  17. add_post_processor() method. When the downloader has finished a
  18. successful download, it will take its internal chain of PostProcessors
  19. and start calling the run() method on each one of them, first with
  20. an initial argument and then with the returned value of the previous
  21. PostProcessor.
  22. The chain will be stopped if one of them ever returns None or the end
  23. of the chain is reached.
  24. PostProcessor objects follow a "mutual registration" process similar
  25. to InfoExtractor objects.
  26. """
  27. _downloader = None
  28. def __init__(self, downloader=None):
  29. self._downloader = downloader
  30. def set_downloader(self, downloader):
  31. """Sets the downloader for this PP."""
  32. self._downloader = downloader
  33. def run(self, information):
  34. """Run the PostProcessor.
  35. The "information" argument is a dictionary like the ones
  36. composed by InfoExtractors. The only difference is that this
  37. one has an extra field called "filepath" that points to the
  38. downloaded file.
  39. This method returns a tuple, the first element of which describes
  40. whether the original file should be kept (i.e. not deleted - None for
  41. no preference), and the second of which is the updated information.
  42. In addition, this method may raise a PostProcessingError
  43. exception if post processing fails.
  44. """
  45. return None, information # by default, keep file and do nothing
  46. class FFmpegPostProcessorError(PostProcessingError):
  47. pass
  48. class AudioConversionError(PostProcessingError):
  49. pass
  50. class FFmpegPostProcessor(PostProcessor):
  51. def __init__(self,downloader=None):
  52. PostProcessor.__init__(self, downloader)
  53. self._exes = self.detect_executables()
  54. @staticmethod
  55. def detect_executables():
  56. def executable(exe):
  57. try:
  58. subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  59. except OSError:
  60. return False
  61. return exe
  62. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  63. return dict((program, executable(program)) for program in programs)
  64. def run_ffmpeg_multiple_files(self, input_paths, out_path, opts):
  65. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  66. raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
  67. files_cmd = []
  68. for path in input_paths:
  69. files_cmd.extend(['-i', encodeFilename(path, True)])
  70. cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y'] + files_cmd
  71. + opts +
  72. [encodeFilename(self._ffmpeg_filename_argument(out_path), True)])
  73. if self._downloader.params.get('verbose', False):
  74. self._downloader.to_screen(u'[debug] ffmpeg command line: %s' % shell_quote(cmd))
  75. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  76. stdout,stderr = p.communicate()
  77. if p.returncode != 0:
  78. stderr = stderr.decode('utf-8', 'replace')
  79. msg = stderr.strip().split('\n')[-1]
  80. raise FFmpegPostProcessorError(msg)
  81. def run_ffmpeg(self, path, out_path, opts):
  82. self.run_ffmpeg_multiple_files([path], out_path, opts)
  83. def _ffmpeg_filename_argument(self, fn):
  84. # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
  85. if fn.startswith(u'-'):
  86. return u'./' + fn
  87. return fn
  88. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  89. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  90. FFmpegPostProcessor.__init__(self, downloader)
  91. if preferredcodec is None:
  92. preferredcodec = 'best'
  93. self._preferredcodec = preferredcodec
  94. self._preferredquality = preferredquality
  95. self._nopostoverwrites = nopostoverwrites
  96. def get_audio_codec(self, path):
  97. if not self._exes['ffprobe'] and not self._exes['avprobe']:
  98. raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
  99. try:
  100. cmd = [
  101. self._exes['avprobe'] or self._exes['ffprobe'],
  102. '-show_streams',
  103. encodeFilename(self._ffmpeg_filename_argument(path), True)]
  104. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  105. output = handle.communicate()[0]
  106. if handle.wait() != 0:
  107. return None
  108. except (IOError, OSError):
  109. return None
  110. audio_codec = None
  111. for line in output.decode('ascii', 'ignore').split('\n'):
  112. if line.startswith('codec_name='):
  113. audio_codec = line.split('=')[1].strip()
  114. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  115. return audio_codec
  116. return None
  117. def run_ffmpeg(self, path, out_path, codec, more_opts):
  118. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  119. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  120. if codec is None:
  121. acodec_opts = []
  122. else:
  123. acodec_opts = ['-acodec', codec]
  124. opts = ['-vn'] + acodec_opts + more_opts
  125. try:
  126. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  127. except FFmpegPostProcessorError as err:
  128. raise AudioConversionError(err.msg)
  129. def run(self, information):
  130. path = information['filepath']
  131. filecodec = self.get_audio_codec(path)
  132. if filecodec is None:
  133. raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
  134. more_opts = []
  135. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  136. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  137. # Lossless, but in another container
  138. acodec = 'copy'
  139. extension = 'm4a'
  140. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  141. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  142. # Lossless if possible
  143. acodec = 'copy'
  144. extension = filecodec
  145. if filecodec == 'aac':
  146. more_opts = ['-f', 'adts']
  147. if filecodec == 'vorbis':
  148. extension = 'ogg'
  149. else:
  150. # MP3 otherwise.
  151. acodec = 'libmp3lame'
  152. extension = 'mp3'
  153. more_opts = []
  154. if self._preferredquality is not None:
  155. if int(self._preferredquality) < 10:
  156. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  157. else:
  158. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  159. else:
  160. # We convert the audio (lossy)
  161. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  162. extension = self._preferredcodec
  163. more_opts = []
  164. if self._preferredquality is not None:
  165. # The opus codec doesn't support the -aq option
  166. if int(self._preferredquality) < 10 and extension != 'opus':
  167. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  168. else:
  169. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  170. if self._preferredcodec == 'aac':
  171. more_opts += ['-f', 'adts']
  172. if self._preferredcodec == 'm4a':
  173. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  174. if self._preferredcodec == 'vorbis':
  175. extension = 'ogg'
  176. if self._preferredcodec == 'wav':
  177. extension = 'wav'
  178. more_opts += ['-f', 'wav']
  179. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  180. new_path = prefix + sep + extension
  181. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  182. if new_path == path:
  183. self._nopostoverwrites = True
  184. try:
  185. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  186. self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
  187. else:
  188. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  189. self.run_ffmpeg(path, new_path, acodec, more_opts)
  190. except:
  191. etype,e,tb = sys.exc_info()
  192. if isinstance(e, AudioConversionError):
  193. msg = u'audio conversion failed: ' + e.msg
  194. else:
  195. msg = u'error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg')
  196. raise PostProcessingError(msg)
  197. # Try to update the date time for extracted audio file.
  198. if information.get('filetime') is not None:
  199. try:
  200. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  201. except:
  202. self._downloader.report_warning(u'Cannot update utime of audio file')
  203. information['filepath'] = new_path
  204. return self._nopostoverwrites,information
  205. class FFmpegVideoConvertor(FFmpegPostProcessor):
  206. def __init__(self, downloader=None,preferedformat=None):
  207. super(FFmpegVideoConvertor, self).__init__(downloader)
  208. self._preferedformat=preferedformat
  209. def run(self, information):
  210. path = information['filepath']
  211. prefix, sep, ext = path.rpartition(u'.')
  212. outpath = prefix + sep + self._preferedformat
  213. if information['ext'] == self._preferedformat:
  214. self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  215. return True,information
  216. self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
  217. self.run_ffmpeg(path, outpath, [])
  218. information['filepath'] = outpath
  219. information['format'] = self._preferedformat
  220. information['ext'] = self._preferedformat
  221. return False,information
  222. class FFmpegEmbedSubtitlePP(FFmpegPostProcessor):
  223. # See http://www.loc.gov/standards/iso639-2/ISO-639-2_utf-8.txt
  224. _lang_map = {
  225. 'aa': 'aar',
  226. 'ab': 'abk',
  227. 'ae': 'ave',
  228. 'af': 'afr',
  229. 'ak': 'aka',
  230. 'am': 'amh',
  231. 'an': 'arg',
  232. 'ar': 'ara',
  233. 'as': 'asm',
  234. 'av': 'ava',
  235. 'ay': 'aym',
  236. 'az': 'aze',
  237. 'ba': 'bak',
  238. 'be': 'bel',
  239. 'bg': 'bul',
  240. 'bh': 'bih',
  241. 'bi': 'bis',
  242. 'bm': 'bam',
  243. 'bn': 'ben',
  244. 'bo': 'bod',
  245. 'br': 'bre',
  246. 'bs': 'bos',
  247. 'ca': 'cat',
  248. 'ce': 'che',
  249. 'ch': 'cha',
  250. 'co': 'cos',
  251. 'cr': 'cre',
  252. 'cs': 'ces',
  253. 'cu': 'chu',
  254. 'cv': 'chv',
  255. 'cy': 'cym',
  256. 'da': 'dan',
  257. 'de': 'deu',
  258. 'dv': 'div',
  259. 'dz': 'dzo',
  260. 'ee': 'ewe',
  261. 'el': 'ell',
  262. 'en': 'eng',
  263. 'eo': 'epo',
  264. 'es': 'spa',
  265. 'et': 'est',
  266. 'eu': 'eus',
  267. 'fa': 'fas',
  268. 'ff': 'ful',
  269. 'fi': 'fin',
  270. 'fj': 'fij',
  271. 'fo': 'fao',
  272. 'fr': 'fra',
  273. 'fy': 'fry',
  274. 'ga': 'gle',
  275. 'gd': 'gla',
  276. 'gl': 'glg',
  277. 'gn': 'grn',
  278. 'gu': 'guj',
  279. 'gv': 'glv',
  280. 'ha': 'hau',
  281. 'he': 'heb',
  282. 'hi': 'hin',
  283. 'ho': 'hmo',
  284. 'hr': 'hrv',
  285. 'ht': 'hat',
  286. 'hu': 'hun',
  287. 'hy': 'hye',
  288. 'hz': 'her',
  289. 'ia': 'ina',
  290. 'id': 'ind',
  291. 'ie': 'ile',
  292. 'ig': 'ibo',
  293. 'ii': 'iii',
  294. 'ik': 'ipk',
  295. 'io': 'ido',
  296. 'is': 'isl',
  297. 'it': 'ita',
  298. 'iu': 'iku',
  299. 'ja': 'jpn',
  300. 'jv': 'jav',
  301. 'ka': 'kat',
  302. 'kg': 'kon',
  303. 'ki': 'kik',
  304. 'kj': 'kua',
  305. 'kk': 'kaz',
  306. 'kl': 'kal',
  307. 'km': 'khm',
  308. 'kn': 'kan',
  309. 'ko': 'kor',
  310. 'kr': 'kau',
  311. 'ks': 'kas',
  312. 'ku': 'kur',
  313. 'kv': 'kom',
  314. 'kw': 'cor',
  315. 'ky': 'kir',
  316. 'la': 'lat',
  317. 'lb': 'ltz',
  318. 'lg': 'lug',
  319. 'li': 'lim',
  320. 'ln': 'lin',
  321. 'lo': 'lao',
  322. 'lt': 'lit',
  323. 'lu': 'lub',
  324. 'lv': 'lav',
  325. 'mg': 'mlg',
  326. 'mh': 'mah',
  327. 'mi': 'mri',
  328. 'mk': 'mkd',
  329. 'ml': 'mal',
  330. 'mn': 'mon',
  331. 'mr': 'mar',
  332. 'ms': 'msa',
  333. 'mt': 'mlt',
  334. 'my': 'mya',
  335. 'na': 'nau',
  336. 'nb': 'nob',
  337. 'nd': 'nde',
  338. 'ne': 'nep',
  339. 'ng': 'ndo',
  340. 'nl': 'nld',
  341. 'nn': 'nno',
  342. 'no': 'nor',
  343. 'nr': 'nbl',
  344. 'nv': 'nav',
  345. 'ny': 'nya',
  346. 'oc': 'oci',
  347. 'oj': 'oji',
  348. 'om': 'orm',
  349. 'or': 'ori',
  350. 'os': 'oss',
  351. 'pa': 'pan',
  352. 'pi': 'pli',
  353. 'pl': 'pol',
  354. 'ps': 'pus',
  355. 'pt': 'por',
  356. 'qu': 'que',
  357. 'rm': 'roh',
  358. 'rn': 'run',
  359. 'ro': 'ron',
  360. 'ru': 'rus',
  361. 'rw': 'kin',
  362. 'sa': 'san',
  363. 'sc': 'srd',
  364. 'sd': 'snd',
  365. 'se': 'sme',
  366. 'sg': 'sag',
  367. 'si': 'sin',
  368. 'sk': 'slk',
  369. 'sl': 'slv',
  370. 'sm': 'smo',
  371. 'sn': 'sna',
  372. 'so': 'som',
  373. 'sq': 'sqi',
  374. 'sr': 'srp',
  375. 'ss': 'ssw',
  376. 'st': 'sot',
  377. 'su': 'sun',
  378. 'sv': 'swe',
  379. 'sw': 'swa',
  380. 'ta': 'tam',
  381. 'te': 'tel',
  382. 'tg': 'tgk',
  383. 'th': 'tha',
  384. 'ti': 'tir',
  385. 'tk': 'tuk',
  386. 'tl': 'tgl',
  387. 'tn': 'tsn',
  388. 'to': 'ton',
  389. 'tr': 'tur',
  390. 'ts': 'tso',
  391. 'tt': 'tat',
  392. 'tw': 'twi',
  393. 'ty': 'tah',
  394. 'ug': 'uig',
  395. 'uk': 'ukr',
  396. 'ur': 'urd',
  397. 'uz': 'uzb',
  398. 've': 'ven',
  399. 'vi': 'vie',
  400. 'vo': 'vol',
  401. 'wa': 'wln',
  402. 'wo': 'wol',
  403. 'xh': 'xho',
  404. 'yi': 'yid',
  405. 'yo': 'yor',
  406. 'za': 'zha',
  407. 'zh': 'zho',
  408. 'zu': 'zul',
  409. }
  410. def __init__(self, downloader=None, subtitlesformat='srt'):
  411. super(FFmpegEmbedSubtitlePP, self).__init__(downloader)
  412. self._subformat = subtitlesformat
  413. @classmethod
  414. def _conver_lang_code(cls, code):
  415. """Convert language code from ISO 639-1 to ISO 639-2/T"""
  416. return cls._lang_map.get(code[:2])
  417. def run(self, information):
  418. if information['ext'] != u'mp4':
  419. self._downloader.to_screen(u'[ffmpeg] Subtitles can only be embedded in mp4 files')
  420. return True, information
  421. if not information.get('subtitles'):
  422. self._downloader.to_screen(u'[ffmpeg] There aren\'t any subtitles to embed')
  423. return True, information
  424. sub_langs = [key for key in information['subtitles']]
  425. filename = information['filepath']
  426. input_files = [filename] + [subtitles_filename(filename, lang, self._subformat) for lang in sub_langs]
  427. opts = ['-map', '0:0', '-map', '0:1', '-c:v', 'copy', '-c:a', 'copy']
  428. for (i, lang) in enumerate(sub_langs):
  429. opts.extend(['-map', '%d:0' % (i+1), '-c:s:%d' % i, 'mov_text'])
  430. lang_code = self._conver_lang_code(lang)
  431. if lang_code is not None:
  432. opts.extend(['-metadata:s:s:%d' % i, 'language=%s' % lang_code])
  433. opts.extend(['-f', 'mp4'])
  434. temp_filename = filename + u'.temp'
  435. self._downloader.to_screen(u'[ffmpeg] Embedding subtitles in \'%s\'' % filename)
  436. self.run_ffmpeg_multiple_files(input_files, temp_filename, opts)
  437. os.remove(encodeFilename(filename))
  438. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  439. return True, information
  440. class FFmpegMetadataPP(FFmpegPostProcessor):
  441. def run(self, info):
  442. metadata = {}
  443. if info.get('title') is not None:
  444. metadata['title'] = info['title']
  445. if info.get('upload_date') is not None:
  446. metadata['date'] = info['upload_date']
  447. if info.get('uploader') is not None:
  448. metadata['artist'] = info['uploader']
  449. elif info.get('uploader_id') is not None:
  450. metadata['artist'] = info['uploader_id']
  451. if not metadata:
  452. self._downloader.to_screen(u'[ffmpeg] There isn\'t any metadata to add')
  453. return True, info
  454. filename = info['filepath']
  455. temp_filename = prepend_extension(filename, 'temp')
  456. options = ['-c', 'copy']
  457. for (name, value) in metadata.items():
  458. options.extend(['-metadata', '%s=%s' % (name, value)])
  459. self._downloader.to_screen(u'[ffmpeg] Adding metadata to \'%s\'' % filename)
  460. self.run_ffmpeg(filename, temp_filename, options)
  461. os.remove(encodeFilename(filename))
  462. os.rename(encodeFilename(temp_filename), encodeFilename(filename))
  463. return True, info
  464. class FFmpegMergerPP(FFmpegPostProcessor):
  465. def run(self, info):
  466. filename = info['filepath']
  467. args = ['-c', 'copy']
  468. self.run_ffmpeg_multiple_files(info['__files_to_merge'], filename, args)
  469. return True, info
  470. class XAttrMetadataPP(PostProcessor):
  471. #
  472. # More info about extended attributes for media:
  473. # http://freedesktop.org/wiki/CommonExtendedAttributes/
  474. # http://www.freedesktop.org/wiki/PhreedomDraft/
  475. # http://dublincore.org/documents/usageguide/elements.shtml
  476. #
  477. # TODO:
  478. # * capture youtube keywords and put them in 'user.dublincore.subject' (comma-separated)
  479. # * figure out which xattrs can be used for 'duration', 'thumbnail', 'resolution'
  480. #
  481. def run(self, info):
  482. """ Set extended attributes on downloaded file (if xattr support is found). """
  483. # This mess below finds the best xattr tool for the job and creates a
  484. # "write_xattr" function.
  485. try:
  486. # try the pyxattr module...
  487. import xattr
  488. def write_xattr(path, key, value):
  489. return xattr.setxattr(path, key, value)
  490. except ImportError:
  491. if os.name == 'posix':
  492. def which(bin):
  493. for dir in os.environ["PATH"].split(":"):
  494. path = os.path.join(dir, bin)
  495. if os.path.exists(path):
  496. return path
  497. user_has_setfattr = which("setfattr")
  498. user_has_xattr = which("xattr")
  499. if user_has_setfattr or user_has_xattr:
  500. def write_xattr(path, key, value):
  501. import errno
  502. potential_errors = {
  503. # setfattr: /tmp/blah: Operation not supported
  504. "Operation not supported": errno.EOPNOTSUPP,
  505. # setfattr: ~/blah: No such file or directory
  506. # xattr: No such file: ~/blah
  507. "No such file": errno.ENOENT,
  508. }
  509. if user_has_setfattr:
  510. cmd = ['setfattr', '-n', key, '-v', value, path]
  511. elif user_has_xattr:
  512. cmd = ['xattr', '-w', key, value, path]
  513. try:
  514. output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
  515. except subprocess.CalledProcessError as e:
  516. errorstr = e.output.strip().decode()
  517. for potential_errorstr, potential_errno in potential_errors.items():
  518. if errorstr.find(potential_errorstr) > -1:
  519. e = OSError(potential_errno, potential_errorstr)
  520. e.__cause__ = None
  521. raise e
  522. raise # Reraise unhandled error
  523. else:
  524. # On Unix, and can't find pyxattr, setfattr, or xattr.
  525. if sys.platform.startswith('linux'):
  526. self._downloader.report_error("Couldn't find a tool to set the xattrs. Install either the python 'pyxattr' or 'xattr' modules, or the GNU 'attr' package (which contains the 'setfattr' tool).")
  527. elif sys.platform == 'darwin':
  528. self._downloader.report_error("Couldn't find a tool to set the xattrs. Install either the python 'xattr' module, or the 'xattr' binary.")
  529. else:
  530. # Write xattrs to NTFS Alternate Data Streams: http://en.wikipedia.org/wiki/NTFS#Alternate_data_streams_.28ADS.29
  531. def write_xattr(path, key, value):
  532. assert(key.find(":") < 0)
  533. assert(path.find(":") < 0)
  534. assert(os.path.exists(path))
  535. ads_fn = path + ":" + key
  536. with open(ads_fn, "w") as f:
  537. f.write(value)
  538. # Write the metadata to the file's xattrs
  539. self._downloader.to_screen('[metadata] Writing metadata to file\'s xattrs...')
  540. filename = info['filepath']
  541. try:
  542. xattr_mapping = {
  543. 'user.xdg.referrer.url': 'webpage_url',
  544. # 'user.xdg.comment': 'description',
  545. 'user.dublincore.title': 'title',
  546. 'user.dublincore.date': 'upload_date',
  547. 'user.dublincore.description': 'description',
  548. 'user.dublincore.contributor': 'uploader',
  549. 'user.dublincore.format': 'format',
  550. }
  551. for xattrname, infoname in xattr_mapping.items():
  552. value = info.get(infoname)
  553. if value:
  554. if infoname == "upload_date":
  555. value = hyphenate_date(value)
  556. write_xattr(filename, xattrname, value)
  557. return True, info
  558. except OSError:
  559. self._downloader.report_error("This filesystem doesn't support extended attributes. (You may have to enable them in your /etc/fstab)")
  560. return False, info