media.py 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. __package__ = 'archivebox.extractors'
  2. from pathlib import Path
  3. from typing import Optional
  4. from ..index.schema import Link, ArchiveResult, ArchiveOutput, ArchiveError
  5. from ..system import run, chmod_file
  6. from ..util import (
  7. enforce_types,
  8. is_static_file,
  9. dedupe,
  10. )
  11. from ..config import (
  12. MEDIA_TIMEOUT,
  13. SAVE_MEDIA,
  14. YOUTUBEDL_ARGS,
  15. YOUTUBEDL_EXTRA_ARGS,
  16. YOUTUBEDL_BINARY,
  17. YOUTUBEDL_VERSION,
  18. CHECK_SSL_VALIDITY
  19. )
  20. from ..logging_util import TimedProgress
  21. @enforce_types
  22. def should_save_media(link: Link, out_dir: Optional[Path]=None, overwrite: Optional[bool]=False) -> bool:
  23. if is_static_file(link.url):
  24. return False
  25. out_dir = out_dir or Path(link.link_dir)
  26. if not overwrite and (out_dir / 'media').exists():
  27. return False
  28. return SAVE_MEDIA
  29. @enforce_types
  30. def save_media(link: Link, out_dir: Optional[Path]=None, timeout: int=MEDIA_TIMEOUT) -> ArchiveResult:
  31. """Download playlists or individual video, audio, and subtitles using youtube-dl or yt-dlp"""
  32. out_dir = out_dir or Path(link.link_dir)
  33. output: ArchiveOutput = 'media'
  34. output_path = out_dir / output
  35. output_path.mkdir(exist_ok=True)
  36. # later options take precedence
  37. options = [
  38. *YOUTUBEDL_ARGS,
  39. *YOUTUBEDL_EXTRA_ARGS,
  40. *([] if CHECK_SSL_VALIDITY else ['--no-check-certificate']),
  41. # TODO: add --cookies-from-browser={CHROME_USER_DATA_DIR}
  42. ]
  43. cmd = [
  44. YOUTUBEDL_BINARY,
  45. *dedupe(options),
  46. link.url,
  47. ]
  48. status = 'succeeded'
  49. timer = TimedProgress(timeout, prefix=' ')
  50. try:
  51. result = run(cmd, cwd=str(output_path), timeout=timeout + 1)
  52. chmod_file(output, cwd=str(out_dir))
  53. if result.returncode:
  54. if (b'ERROR: Unsupported URL' in result.stderr
  55. or b'HTTP Error 404' in result.stderr
  56. or b'HTTP Error 403' in result.stderr
  57. or b'URL could be a direct video link' in result.stderr
  58. or b'Unable to extract container ID' in result.stderr):
  59. # These happen too frequently on non-media pages to warrant printing to console
  60. pass
  61. else:
  62. hints = (
  63. 'Got youtube-dl (or yt-dlp) response code: {}.'.format(result.returncode),
  64. *result.stderr.decode().split('\n'),
  65. )
  66. raise ArchiveError('Failed to save media', hints)
  67. except Exception as err:
  68. status = 'failed'
  69. output = err
  70. finally:
  71. timer.end()
  72. # add video description and subtitles to full-text index
  73. # Let's try a few different
  74. index_texts = [
  75. # errors:
  76. # * 'strict' to raise a ValueError exception if there is an
  77. # encoding error. The default value of None has the same effect.
  78. # * 'ignore' ignores errors. Note that ignoring encoding errors
  79. # can lead to data loss.
  80. # * 'xmlcharrefreplace' is only supported when writing to a
  81. # file. Characters not supported by the encoding are replaced with
  82. # the appropriate XML character reference &#nnn;.
  83. # There are a few more options described in https://docs.python.org/3/library/functions.html#open
  84. text_file.read_text(encoding='utf-8', errors='xmlcharrefreplace').strip()
  85. for text_file in (
  86. *output_path.glob('*.description'),
  87. *output_path.glob('*.srt'),
  88. *output_path.glob('*.vtt'),
  89. *output_path.glob('*.lrc'),
  90. *output_path.glob('*.lrc'),
  91. )
  92. ]
  93. return ArchiveResult(
  94. cmd=cmd,
  95. pwd=str(out_dir),
  96. cmd_version=YOUTUBEDL_VERSION,
  97. output=output,
  98. status=status,
  99. index_texts=index_texts,
  100. **timer.stats,
  101. )