media.py 4.1 KB

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