utils.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import unicode_literals
  4. import calendar
  5. import codecs
  6. import contextlib
  7. import ctypes
  8. import datetime
  9. import email.utils
  10. import errno
  11. import functools
  12. import gzip
  13. import itertools
  14. import io
  15. import json
  16. import locale
  17. import math
  18. import operator
  19. import os
  20. import pipes
  21. import platform
  22. import re
  23. import ssl
  24. import socket
  25. import struct
  26. import subprocess
  27. import sys
  28. import tempfile
  29. import traceback
  30. import xml.etree.ElementTree
  31. import zlib
  32. from .compat import (
  33. compat_basestring,
  34. compat_chr,
  35. compat_html_entities,
  36. compat_http_client,
  37. compat_parse_qs,
  38. compat_socket_create_connection,
  39. compat_str,
  40. compat_urllib_error,
  41. compat_urllib_parse,
  42. compat_urllib_parse_urlparse,
  43. compat_urllib_request,
  44. compat_urlparse,
  45. shlex_quote,
  46. )
  47. # This is not clearly defined otherwise
  48. compiled_regex_type = type(re.compile(''))
  49. std_headers = {
  50. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20150101 Firefox/20.0 (Chrome)',
  51. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  52. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  53. 'Accept-Encoding': 'gzip, deflate',
  54. 'Accept-Language': 'en-us,en;q=0.5',
  55. }
  56. ENGLISH_MONTH_NAMES = [
  57. 'January', 'February', 'March', 'April', 'May', 'June',
  58. 'July', 'August', 'September', 'October', 'November', 'December']
  59. def preferredencoding():
  60. """Get preferred encoding.
  61. Returns the best encoding scheme for the system, based on
  62. locale.getpreferredencoding() and some further tweaks.
  63. """
  64. try:
  65. pref = locale.getpreferredencoding()
  66. 'TEST'.encode(pref)
  67. except:
  68. pref = 'UTF-8'
  69. return pref
  70. def write_json_file(obj, fn):
  71. """ Encode obj as JSON and write it to fn, atomically if possible """
  72. fn = encodeFilename(fn)
  73. if sys.version_info < (3, 0) and sys.platform != 'win32':
  74. encoding = get_filesystem_encoding()
  75. # os.path.basename returns a bytes object, but NamedTemporaryFile
  76. # will fail if the filename contains non ascii characters unless we
  77. # use a unicode object
  78. path_basename = lambda f: os.path.basename(fn).decode(encoding)
  79. # the same for os.path.dirname
  80. path_dirname = lambda f: os.path.dirname(fn).decode(encoding)
  81. else:
  82. path_basename = os.path.basename
  83. path_dirname = os.path.dirname
  84. args = {
  85. 'suffix': '.tmp',
  86. 'prefix': path_basename(fn) + '.',
  87. 'dir': path_dirname(fn),
  88. 'delete': False,
  89. }
  90. # In Python 2.x, json.dump expects a bytestream.
  91. # In Python 3.x, it writes to a character stream
  92. if sys.version_info < (3, 0):
  93. args['mode'] = 'wb'
  94. else:
  95. args.update({
  96. 'mode': 'w',
  97. 'encoding': 'utf-8',
  98. })
  99. tf = tempfile.NamedTemporaryFile(**args)
  100. try:
  101. with tf:
  102. json.dump(obj, tf)
  103. if sys.platform == 'win32':
  104. # Need to remove existing file on Windows, else os.rename raises
  105. # WindowsError or FileExistsError.
  106. try:
  107. os.unlink(fn)
  108. except OSError:
  109. pass
  110. os.rename(tf.name, fn)
  111. except:
  112. try:
  113. os.remove(tf.name)
  114. except OSError:
  115. pass
  116. raise
  117. if sys.version_info >= (2, 7):
  118. def find_xpath_attr(node, xpath, key, val):
  119. """ Find the xpath xpath[@key=val] """
  120. assert re.match(r'^[a-zA-Z-]+$', key)
  121. assert re.match(r'^[a-zA-Z0-9@\s:._-]*$', val)
  122. expr = xpath + "[@%s='%s']" % (key, val)
  123. return node.find(expr)
  124. else:
  125. def find_xpath_attr(node, xpath, key, val):
  126. # Here comes the crazy part: In 2.6, if the xpath is a unicode,
  127. # .//node does not match if a node is a direct child of . !
  128. if isinstance(xpath, compat_str):
  129. xpath = xpath.encode('ascii')
  130. for f in node.findall(xpath):
  131. if f.attrib.get(key) == val:
  132. return f
  133. return None
  134. # On python2.6 the xml.etree.ElementTree.Element methods don't support
  135. # the namespace parameter
  136. def xpath_with_ns(path, ns_map):
  137. components = [c.split(':') for c in path.split('/')]
  138. replaced = []
  139. for c in components:
  140. if len(c) == 1:
  141. replaced.append(c[0])
  142. else:
  143. ns, tag = c
  144. replaced.append('{%s}%s' % (ns_map[ns], tag))
  145. return '/'.join(replaced)
  146. def xpath_text(node, xpath, name=None, fatal=False):
  147. if sys.version_info < (2, 7): # Crazy 2.6
  148. xpath = xpath.encode('ascii')
  149. n = node.find(xpath)
  150. if n is None or n.text is None:
  151. if fatal:
  152. name = xpath if name is None else name
  153. raise ExtractorError('Could not find XML element %s' % name)
  154. else:
  155. return None
  156. return n.text
  157. def get_element_by_id(id, html):
  158. """Return the content of the tag with the specified ID in the passed HTML document"""
  159. return get_element_by_attribute("id", id, html)
  160. def get_element_by_attribute(attribute, value, html):
  161. """Return the content of the tag with the specified attribute in the passed HTML document"""
  162. m = re.search(r'''(?xs)
  163. <([a-zA-Z0-9:._-]+)
  164. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  165. \s+%s=['"]?%s['"]?
  166. (?:\s+[a-zA-Z0-9:._-]+(?:=[a-zA-Z0-9:._-]+|="[^"]+"|='[^']+'))*?
  167. \s*>
  168. (?P<content>.*?)
  169. </\1>
  170. ''' % (re.escape(attribute), re.escape(value)), html)
  171. if not m:
  172. return None
  173. res = m.group('content')
  174. if res.startswith('"') or res.startswith("'"):
  175. res = res[1:-1]
  176. return unescapeHTML(res)
  177. def clean_html(html):
  178. """Clean an HTML snippet into a readable string"""
  179. if html is None: # Convenience for sanitizing descriptions etc.
  180. return html
  181. # Newline vs <br />
  182. html = html.replace('\n', ' ')
  183. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  184. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  185. # Strip html tags
  186. html = re.sub('<.*?>', '', html)
  187. # Replace html entities
  188. html = unescapeHTML(html)
  189. return html.strip()
  190. def sanitize_open(filename, open_mode):
  191. """Try to open the given filename, and slightly tweak it if this fails.
  192. Attempts to open the given filename. If this fails, it tries to change
  193. the filename slightly, step by step, until it's either able to open it
  194. or it fails and raises a final exception, like the standard open()
  195. function.
  196. It returns the tuple (stream, definitive_file_name).
  197. """
  198. try:
  199. if filename == '-':
  200. if sys.platform == 'win32':
  201. import msvcrt
  202. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  203. return (sys.stdout.buffer if hasattr(sys.stdout, 'buffer') else sys.stdout, filename)
  204. stream = open(encodeFilename(filename), open_mode)
  205. return (stream, filename)
  206. except (IOError, OSError) as err:
  207. if err.errno in (errno.EACCES,):
  208. raise
  209. # In case of error, try to remove win32 forbidden chars
  210. alt_filename = os.path.join(
  211. re.sub('[/<>:"\\|\\\\?\\*]', '#', path_part)
  212. for path_part in os.path.split(filename)
  213. )
  214. if alt_filename == filename:
  215. raise
  216. else:
  217. # An exception here should be caught in the caller
  218. stream = open(encodeFilename(filename), open_mode)
  219. return (stream, alt_filename)
  220. def timeconvert(timestr):
  221. """Convert RFC 2822 defined time string into system timestamp"""
  222. timestamp = None
  223. timetuple = email.utils.parsedate_tz(timestr)
  224. if timetuple is not None:
  225. timestamp = email.utils.mktime_tz(timetuple)
  226. return timestamp
  227. def sanitize_filename(s, restricted=False, is_id=False):
  228. """Sanitizes a string so it could be used as part of a filename.
  229. If restricted is set, use a stricter subset of allowed characters.
  230. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  231. """
  232. def replace_insane(char):
  233. if char == '?' or ord(char) < 32 or ord(char) == 127:
  234. return ''
  235. elif char == '"':
  236. return '' if restricted else '\''
  237. elif char == ':':
  238. return '_-' if restricted else ' -'
  239. elif char in '\\/|*<>':
  240. return '_'
  241. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  242. return '_'
  243. if restricted and ord(char) > 127:
  244. return '_'
  245. return char
  246. # Handle timestamps
  247. s = re.sub(r'[0-9]+(?::[0-9]+)+', lambda m: m.group(0).replace(':', '_'), s)
  248. result = ''.join(map(replace_insane, s))
  249. if not is_id:
  250. while '__' in result:
  251. result = result.replace('__', '_')
  252. result = result.strip('_')
  253. # Common case of "Foreign band name - English song title"
  254. if restricted and result.startswith('-_'):
  255. result = result[2:]
  256. if result.startswith('-'):
  257. result = '_' + result[len('-'):]
  258. result = result.lstrip('.')
  259. if not result:
  260. result = '_'
  261. return result
  262. def sanitize_path(s):
  263. """Sanitizes and normalizes path on Windows"""
  264. if sys.platform != 'win32':
  265. return s
  266. drive, _ = os.path.splitdrive(s)
  267. unc, _ = os.path.splitunc(s)
  268. unc_or_drive = unc or drive
  269. norm_path = os.path.normpath(remove_start(s, unc_or_drive)).split(os.path.sep)
  270. if unc_or_drive:
  271. norm_path.pop(0)
  272. sanitized_path = [
  273. re.sub('[/<>:"\\|\\\\?\\*]', '#', path_part)
  274. for path_part in norm_path]
  275. if unc_or_drive:
  276. sanitized_path.insert(0, unc_or_drive + os.path.sep)
  277. return os.path.join(*sanitized_path)
  278. def orderedSet(iterable):
  279. """ Remove all duplicates from the input iterable """
  280. res = []
  281. for el in iterable:
  282. if el not in res:
  283. res.append(el)
  284. return res
  285. def _htmlentity_transform(entity):
  286. """Transforms an HTML entity to a character."""
  287. # Known non-numeric HTML entity
  288. if entity in compat_html_entities.name2codepoint:
  289. return compat_chr(compat_html_entities.name2codepoint[entity])
  290. mobj = re.match(r'#(x?[0-9]+)', entity)
  291. if mobj is not None:
  292. numstr = mobj.group(1)
  293. if numstr.startswith('x'):
  294. base = 16
  295. numstr = '0%s' % numstr
  296. else:
  297. base = 10
  298. return compat_chr(int(numstr, base))
  299. # Unknown entity in name, return its literal representation
  300. return ('&%s;' % entity)
  301. def unescapeHTML(s):
  302. if s is None:
  303. return None
  304. assert type(s) == compat_str
  305. return re.sub(
  306. r'&([^;]+);', lambda m: _htmlentity_transform(m.group(1)), s)
  307. def encodeFilename(s, for_subprocess=False):
  308. """
  309. @param s The name of the file
  310. """
  311. assert type(s) == compat_str
  312. # Python 3 has a Unicode API
  313. if sys.version_info >= (3, 0):
  314. return s
  315. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  316. # Pass '' directly to use Unicode APIs on Windows 2000 and up
  317. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  318. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  319. if not for_subprocess:
  320. return s
  321. else:
  322. # For subprocess calls, encode with locale encoding
  323. # Refer to http://stackoverflow.com/a/9951851/35070
  324. encoding = preferredencoding()
  325. else:
  326. encoding = sys.getfilesystemencoding()
  327. if encoding is None:
  328. encoding = 'utf-8'
  329. return s.encode(encoding, 'ignore')
  330. def encodeArgument(s):
  331. if not isinstance(s, compat_str):
  332. # Legacy code that uses byte strings
  333. # Uncomment the following line after fixing all post processors
  334. # assert False, 'Internal error: %r should be of type %r, is %r' % (s, compat_str, type(s))
  335. s = s.decode('ascii')
  336. return encodeFilename(s, True)
  337. def decodeOption(optval):
  338. if optval is None:
  339. return optval
  340. if isinstance(optval, bytes):
  341. optval = optval.decode(preferredencoding())
  342. assert isinstance(optval, compat_str)
  343. return optval
  344. def formatSeconds(secs):
  345. if secs > 3600:
  346. return '%d:%02d:%02d' % (secs // 3600, (secs % 3600) // 60, secs % 60)
  347. elif secs > 60:
  348. return '%d:%02d' % (secs // 60, secs % 60)
  349. else:
  350. return '%d' % secs
  351. def make_HTTPS_handler(params, **kwargs):
  352. opts_no_check_certificate = params.get('nocheckcertificate', False)
  353. if hasattr(ssl, 'create_default_context'): # Python >= 3.4 or 2.7.9
  354. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  355. if opts_no_check_certificate:
  356. context.check_hostname = False
  357. context.verify_mode = ssl.CERT_NONE
  358. try:
  359. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  360. except TypeError:
  361. # Python 2.7.8
  362. # (create_default_context present but HTTPSHandler has no context=)
  363. pass
  364. if sys.version_info < (3, 2):
  365. return YoutubeDLHTTPSHandler(params, **kwargs)
  366. else: # Python < 3.4
  367. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  368. context.verify_mode = (ssl.CERT_NONE
  369. if opts_no_check_certificate
  370. else ssl.CERT_REQUIRED)
  371. context.set_default_verify_paths()
  372. return YoutubeDLHTTPSHandler(params, context=context, **kwargs)
  373. class ExtractorError(Exception):
  374. """Error during info extraction."""
  375. def __init__(self, msg, tb=None, expected=False, cause=None, video_id=None):
  376. """ tb, if given, is the original traceback (so that it can be printed out).
  377. If expected is set, this is a normal error message and most likely not a bug in youtube-dl.
  378. """
  379. if sys.exc_info()[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  380. expected = True
  381. if video_id is not None:
  382. msg = video_id + ': ' + msg
  383. if cause:
  384. msg += ' (caused by %r)' % cause
  385. if not expected:
  386. if ytdl_is_updateable():
  387. update_cmd = 'type youtube-dl -U to update'
  388. else:
  389. update_cmd = 'see https://yt-dl.org/update on how to update'
  390. msg += '; please report this issue on https://yt-dl.org/bug .'
  391. msg += ' Make sure you are using the latest version; %s.' % update_cmd
  392. msg += ' Be sure to call youtube-dl with the --verbose flag and include its complete output.'
  393. super(ExtractorError, self).__init__(msg)
  394. self.traceback = tb
  395. self.exc_info = sys.exc_info() # preserve original exception
  396. self.cause = cause
  397. self.video_id = video_id
  398. def format_traceback(self):
  399. if self.traceback is None:
  400. return None
  401. return ''.join(traceback.format_tb(self.traceback))
  402. class UnsupportedError(ExtractorError):
  403. def __init__(self, url):
  404. super(UnsupportedError, self).__init__(
  405. 'Unsupported URL: %s' % url, expected=True)
  406. self.url = url
  407. class RegexNotFoundError(ExtractorError):
  408. """Error when a regex didn't match"""
  409. pass
  410. class DownloadError(Exception):
  411. """Download Error exception.
  412. This exception may be thrown by FileDownloader objects if they are not
  413. configured to continue on errors. They will contain the appropriate
  414. error message.
  415. """
  416. def __init__(self, msg, exc_info=None):
  417. """ exc_info, if given, is the original exception that caused the trouble (as returned by sys.exc_info()). """
  418. super(DownloadError, self).__init__(msg)
  419. self.exc_info = exc_info
  420. class SameFileError(Exception):
  421. """Same File exception.
  422. This exception will be thrown by FileDownloader objects if they detect
  423. multiple files would have to be downloaded to the same file on disk.
  424. """
  425. pass
  426. class PostProcessingError(Exception):
  427. """Post Processing exception.
  428. This exception may be raised by PostProcessor's .run() method to
  429. indicate an error in the postprocessing task.
  430. """
  431. def __init__(self, msg):
  432. self.msg = msg
  433. class MaxDownloadsReached(Exception):
  434. """ --max-downloads limit has been reached. """
  435. pass
  436. class UnavailableVideoError(Exception):
  437. """Unavailable Format exception.
  438. This exception will be thrown when a video is requested
  439. in a format that is not available for that video.
  440. """
  441. pass
  442. class ContentTooShortError(Exception):
  443. """Content Too Short exception.
  444. This exception may be raised by FileDownloader objects when a file they
  445. download is too small for what the server announced first, indicating
  446. the connection was probably interrupted.
  447. """
  448. # Both in bytes
  449. downloaded = None
  450. expected = None
  451. def __init__(self, downloaded, expected):
  452. self.downloaded = downloaded
  453. self.expected = expected
  454. def _create_http_connection(ydl_handler, http_class, is_https, *args, **kwargs):
  455. hc = http_class(*args, **kwargs)
  456. source_address = ydl_handler._params.get('source_address')
  457. if source_address is not None:
  458. sa = (source_address, 0)
  459. if hasattr(hc, 'source_address'): # Python 2.7+
  460. hc.source_address = sa
  461. else: # Python 2.6
  462. def _hc_connect(self, *args, **kwargs):
  463. sock = compat_socket_create_connection(
  464. (self.host, self.port), self.timeout, sa)
  465. if is_https:
  466. self.sock = ssl.wrap_socket(
  467. sock, self.key_file, self.cert_file,
  468. ssl_version=ssl.PROTOCOL_TLSv1)
  469. else:
  470. self.sock = sock
  471. hc.connect = functools.partial(_hc_connect, hc)
  472. return hc
  473. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  474. """Handler for HTTP requests and responses.
  475. This class, when installed with an OpenerDirector, automatically adds
  476. the standard headers to every HTTP request and handles gzipped and
  477. deflated responses from web servers. If compression is to be avoided in
  478. a particular request, the original request in the program code only has
  479. to include the HTTP header "Youtubedl-No-Compression", which will be
  480. removed before making the real request.
  481. Part of this code was copied from:
  482. http://techknack.net/python-urllib2-handlers/
  483. Andrew Rowls, the author of that code, agreed to release it to the
  484. public domain.
  485. """
  486. def __init__(self, params, *args, **kwargs):
  487. compat_urllib_request.HTTPHandler.__init__(self, *args, **kwargs)
  488. self._params = params
  489. def http_open(self, req):
  490. return self.do_open(functools.partial(
  491. _create_http_connection, self, compat_http_client.HTTPConnection, False),
  492. req)
  493. @staticmethod
  494. def deflate(data):
  495. try:
  496. return zlib.decompress(data, -zlib.MAX_WBITS)
  497. except zlib.error:
  498. return zlib.decompress(data)
  499. @staticmethod
  500. def addinfourl_wrapper(stream, headers, url, code):
  501. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  502. return compat_urllib_request.addinfourl(stream, headers, url, code)
  503. ret = compat_urllib_request.addinfourl(stream, headers, url)
  504. ret.code = code
  505. return ret
  506. def http_request(self, req):
  507. for h, v in std_headers.items():
  508. # Capitalize is needed because of Python bug 2275: http://bugs.python.org/issue2275
  509. # The dict keys are capitalized because of this bug by urllib
  510. if h.capitalize() not in req.headers:
  511. req.add_header(h, v)
  512. if 'Youtubedl-no-compression' in req.headers:
  513. if 'Accept-encoding' in req.headers:
  514. del req.headers['Accept-encoding']
  515. del req.headers['Youtubedl-no-compression']
  516. if sys.version_info < (2, 7) and '#' in req.get_full_url():
  517. # Python 2.6 is brain-dead when it comes to fragments
  518. req._Request__original = req._Request__original.partition('#')[0]
  519. req._Request__r_type = req._Request__r_type.partition('#')[0]
  520. return req
  521. def http_response(self, req, resp):
  522. old_resp = resp
  523. # gzip
  524. if resp.headers.get('Content-encoding', '') == 'gzip':
  525. content = resp.read()
  526. gz = gzip.GzipFile(fileobj=io.BytesIO(content), mode='rb')
  527. try:
  528. uncompressed = io.BytesIO(gz.read())
  529. except IOError as original_ioerror:
  530. # There may be junk add the end of the file
  531. # See http://stackoverflow.com/q/4928560/35070 for details
  532. for i in range(1, 1024):
  533. try:
  534. gz = gzip.GzipFile(fileobj=io.BytesIO(content[:-i]), mode='rb')
  535. uncompressed = io.BytesIO(gz.read())
  536. except IOError:
  537. continue
  538. break
  539. else:
  540. raise original_ioerror
  541. resp = self.addinfourl_wrapper(uncompressed, old_resp.headers, old_resp.url, old_resp.code)
  542. resp.msg = old_resp.msg
  543. # deflate
  544. if resp.headers.get('Content-encoding', '') == 'deflate':
  545. gz = io.BytesIO(self.deflate(resp.read()))
  546. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  547. resp.msg = old_resp.msg
  548. return resp
  549. https_request = http_request
  550. https_response = http_response
  551. class YoutubeDLHTTPSHandler(compat_urllib_request.HTTPSHandler):
  552. def __init__(self, params, https_conn_class=None, *args, **kwargs):
  553. compat_urllib_request.HTTPSHandler.__init__(self, *args, **kwargs)
  554. self._https_conn_class = https_conn_class or compat_http_client.HTTPSConnection
  555. self._params = params
  556. def https_open(self, req):
  557. kwargs = {}
  558. if hasattr(self, '_context'): # python > 2.6
  559. kwargs['context'] = self._context
  560. if hasattr(self, '_check_hostname'): # python 3.x
  561. kwargs['check_hostname'] = self._check_hostname
  562. return self.do_open(functools.partial(
  563. _create_http_connection, self, self._https_conn_class, True),
  564. req, **kwargs)
  565. def parse_iso8601(date_str, delimiter='T', timezone=None):
  566. """ Return a UNIX timestamp from the given date """
  567. if date_str is None:
  568. return None
  569. if timezone is None:
  570. m = re.search(
  571. r'(\.[0-9]+)?(?:Z$| ?(?P<sign>\+|-)(?P<hours>[0-9]{2}):?(?P<minutes>[0-9]{2})$)',
  572. date_str)
  573. if not m:
  574. timezone = datetime.timedelta()
  575. else:
  576. date_str = date_str[:-len(m.group(0))]
  577. if not m.group('sign'):
  578. timezone = datetime.timedelta()
  579. else:
  580. sign = 1 if m.group('sign') == '+' else -1
  581. timezone = datetime.timedelta(
  582. hours=sign * int(m.group('hours')),
  583. minutes=sign * int(m.group('minutes')))
  584. date_format = '%Y-%m-%d{0}%H:%M:%S'.format(delimiter)
  585. dt = datetime.datetime.strptime(date_str, date_format) - timezone
  586. return calendar.timegm(dt.timetuple())
  587. def unified_strdate(date_str, day_first=True):
  588. """Return a string with the date in the format YYYYMMDD"""
  589. if date_str is None:
  590. return None
  591. upload_date = None
  592. # Replace commas
  593. date_str = date_str.replace(',', ' ')
  594. # %z (UTC offset) is only supported in python>=3.2
  595. date_str = re.sub(r' ?(\+|-)[0-9]{2}:?[0-9]{2}$', '', date_str)
  596. # Remove AM/PM + timezone
  597. date_str = re.sub(r'(?i)\s*(?:AM|PM)(?:\s+[A-Z]+)?', '', date_str)
  598. format_expressions = [
  599. '%d %B %Y',
  600. '%d %b %Y',
  601. '%B %d %Y',
  602. '%b %d %Y',
  603. '%b %dst %Y %I:%M%p',
  604. '%b %dnd %Y %I:%M%p',
  605. '%b %dth %Y %I:%M%p',
  606. '%Y %m %d',
  607. '%Y-%m-%d',
  608. '%Y/%m/%d',
  609. '%Y/%m/%d %H:%M:%S',
  610. '%Y-%m-%d %H:%M:%S',
  611. '%Y-%m-%d %H:%M:%S.%f',
  612. '%d.%m.%Y %H:%M',
  613. '%d.%m.%Y %H.%M',
  614. '%Y-%m-%dT%H:%M:%SZ',
  615. '%Y-%m-%dT%H:%M:%S.%fZ',
  616. '%Y-%m-%dT%H:%M:%S.%f0Z',
  617. '%Y-%m-%dT%H:%M:%S',
  618. '%Y-%m-%dT%H:%M:%S.%f',
  619. '%Y-%m-%dT%H:%M',
  620. ]
  621. if day_first:
  622. format_expressions.extend([
  623. '%d.%m.%Y',
  624. '%d/%m/%Y',
  625. '%d/%m/%y',
  626. '%d/%m/%Y %H:%M:%S',
  627. ])
  628. else:
  629. format_expressions.extend([
  630. '%m.%d.%Y',
  631. '%m/%d/%Y',
  632. '%m/%d/%y',
  633. '%m/%d/%Y %H:%M:%S',
  634. ])
  635. for expression in format_expressions:
  636. try:
  637. upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
  638. except ValueError:
  639. pass
  640. if upload_date is None:
  641. timetuple = email.utils.parsedate_tz(date_str)
  642. if timetuple:
  643. upload_date = datetime.datetime(*timetuple[:6]).strftime('%Y%m%d')
  644. return upload_date
  645. def determine_ext(url, default_ext='unknown_video'):
  646. if url is None:
  647. return default_ext
  648. guess = url.partition('?')[0].rpartition('.')[2]
  649. if re.match(r'^[A-Za-z0-9]+$', guess):
  650. return guess
  651. else:
  652. return default_ext
  653. def subtitles_filename(filename, sub_lang, sub_format):
  654. return filename.rsplit('.', 1)[0] + '.' + sub_lang + '.' + sub_format
  655. def date_from_str(date_str):
  656. """
  657. Return a datetime object from a string in the format YYYYMMDD or
  658. (now|today)[+-][0-9](day|week|month|year)(s)?"""
  659. today = datetime.date.today()
  660. if date_str in ('now', 'today'):
  661. return today
  662. if date_str == 'yesterday':
  663. return today - datetime.timedelta(days=1)
  664. match = re.match('(now|today)(?P<sign>[+-])(?P<time>\d+)(?P<unit>day|week|month|year)(s)?', date_str)
  665. if match is not None:
  666. sign = match.group('sign')
  667. time = int(match.group('time'))
  668. if sign == '-':
  669. time = -time
  670. unit = match.group('unit')
  671. # A bad aproximation?
  672. if unit == 'month':
  673. unit = 'day'
  674. time *= 30
  675. elif unit == 'year':
  676. unit = 'day'
  677. time *= 365
  678. unit += 's'
  679. delta = datetime.timedelta(**{unit: time})
  680. return today + delta
  681. return datetime.datetime.strptime(date_str, "%Y%m%d").date()
  682. def hyphenate_date(date_str):
  683. """
  684. Convert a date in 'YYYYMMDD' format to 'YYYY-MM-DD' format"""
  685. match = re.match(r'^(\d\d\d\d)(\d\d)(\d\d)$', date_str)
  686. if match is not None:
  687. return '-'.join(match.groups())
  688. else:
  689. return date_str
  690. class DateRange(object):
  691. """Represents a time interval between two dates"""
  692. def __init__(self, start=None, end=None):
  693. """start and end must be strings in the format accepted by date"""
  694. if start is not None:
  695. self.start = date_from_str(start)
  696. else:
  697. self.start = datetime.datetime.min.date()
  698. if end is not None:
  699. self.end = date_from_str(end)
  700. else:
  701. self.end = datetime.datetime.max.date()
  702. if self.start > self.end:
  703. raise ValueError('Date range: "%s" , the start date must be before the end date' % self)
  704. @classmethod
  705. def day(cls, day):
  706. """Returns a range that only contains the given day"""
  707. return cls(day, day)
  708. def __contains__(self, date):
  709. """Check if the date is in the range"""
  710. if not isinstance(date, datetime.date):
  711. date = date_from_str(date)
  712. return self.start <= date <= self.end
  713. def __str__(self):
  714. return '%s - %s' % (self.start.isoformat(), self.end.isoformat())
  715. def platform_name():
  716. """ Returns the platform name as a compat_str """
  717. res = platform.platform()
  718. if isinstance(res, bytes):
  719. res = res.decode(preferredencoding())
  720. assert isinstance(res, compat_str)
  721. return res
  722. def _windows_write_string(s, out):
  723. """ Returns True if the string was written using special methods,
  724. False if it has yet to be written out."""
  725. # Adapted from http://stackoverflow.com/a/3259271/35070
  726. import ctypes
  727. import ctypes.wintypes
  728. WIN_OUTPUT_IDS = {
  729. 1: -11,
  730. 2: -12,
  731. }
  732. try:
  733. fileno = out.fileno()
  734. except AttributeError:
  735. # If the output stream doesn't have a fileno, it's virtual
  736. return False
  737. except io.UnsupportedOperation:
  738. # Some strange Windows pseudo files?
  739. return False
  740. if fileno not in WIN_OUTPUT_IDS:
  741. return False
  742. GetStdHandle = ctypes.WINFUNCTYPE(
  743. ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD)(
  744. (b"GetStdHandle", ctypes.windll.kernel32))
  745. h = GetStdHandle(WIN_OUTPUT_IDS[fileno])
  746. WriteConsoleW = ctypes.WINFUNCTYPE(
  747. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE, ctypes.wintypes.LPWSTR,
  748. ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.DWORD),
  749. ctypes.wintypes.LPVOID)((b"WriteConsoleW", ctypes.windll.kernel32))
  750. written = ctypes.wintypes.DWORD(0)
  751. GetFileType = ctypes.WINFUNCTYPE(ctypes.wintypes.DWORD, ctypes.wintypes.DWORD)((b"GetFileType", ctypes.windll.kernel32))
  752. FILE_TYPE_CHAR = 0x0002
  753. FILE_TYPE_REMOTE = 0x8000
  754. GetConsoleMode = ctypes.WINFUNCTYPE(
  755. ctypes.wintypes.BOOL, ctypes.wintypes.HANDLE,
  756. ctypes.POINTER(ctypes.wintypes.DWORD))(
  757. (b"GetConsoleMode", ctypes.windll.kernel32))
  758. INVALID_HANDLE_VALUE = ctypes.wintypes.DWORD(-1).value
  759. def not_a_console(handle):
  760. if handle == INVALID_HANDLE_VALUE or handle is None:
  761. return True
  762. return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR or
  763. GetConsoleMode(handle, ctypes.byref(ctypes.wintypes.DWORD())) == 0)
  764. if not_a_console(h):
  765. return False
  766. def next_nonbmp_pos(s):
  767. try:
  768. return next(i for i, c in enumerate(s) if ord(c) > 0xffff)
  769. except StopIteration:
  770. return len(s)
  771. while s:
  772. count = min(next_nonbmp_pos(s), 1024)
  773. ret = WriteConsoleW(
  774. h, s, count if count else 2, ctypes.byref(written), None)
  775. if ret == 0:
  776. raise OSError('Failed to write string')
  777. if not count: # We just wrote a non-BMP character
  778. assert written.value == 2
  779. s = s[1:]
  780. else:
  781. assert written.value > 0
  782. s = s[written.value:]
  783. return True
  784. def write_string(s, out=None, encoding=None):
  785. if out is None:
  786. out = sys.stderr
  787. assert type(s) == compat_str
  788. if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'):
  789. if _windows_write_string(s, out):
  790. return
  791. if ('b' in getattr(out, 'mode', '') or
  792. sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr
  793. byt = s.encode(encoding or preferredencoding(), 'ignore')
  794. out.write(byt)
  795. elif hasattr(out, 'buffer'):
  796. enc = encoding or getattr(out, 'encoding', None) or preferredencoding()
  797. byt = s.encode(enc, 'ignore')
  798. out.buffer.write(byt)
  799. else:
  800. out.write(s)
  801. out.flush()
  802. def bytes_to_intlist(bs):
  803. if not bs:
  804. return []
  805. if isinstance(bs[0], int): # Python 3
  806. return list(bs)
  807. else:
  808. return [ord(c) for c in bs]
  809. def intlist_to_bytes(xs):
  810. if not xs:
  811. return b''
  812. return struct_pack('%dB' % len(xs), *xs)
  813. # Cross-platform file locking
  814. if sys.platform == 'win32':
  815. import ctypes.wintypes
  816. import msvcrt
  817. class OVERLAPPED(ctypes.Structure):
  818. _fields_ = [
  819. ('Internal', ctypes.wintypes.LPVOID),
  820. ('InternalHigh', ctypes.wintypes.LPVOID),
  821. ('Offset', ctypes.wintypes.DWORD),
  822. ('OffsetHigh', ctypes.wintypes.DWORD),
  823. ('hEvent', ctypes.wintypes.HANDLE),
  824. ]
  825. kernel32 = ctypes.windll.kernel32
  826. LockFileEx = kernel32.LockFileEx
  827. LockFileEx.argtypes = [
  828. ctypes.wintypes.HANDLE, # hFile
  829. ctypes.wintypes.DWORD, # dwFlags
  830. ctypes.wintypes.DWORD, # dwReserved
  831. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  832. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  833. ctypes.POINTER(OVERLAPPED) # Overlapped
  834. ]
  835. LockFileEx.restype = ctypes.wintypes.BOOL
  836. UnlockFileEx = kernel32.UnlockFileEx
  837. UnlockFileEx.argtypes = [
  838. ctypes.wintypes.HANDLE, # hFile
  839. ctypes.wintypes.DWORD, # dwReserved
  840. ctypes.wintypes.DWORD, # nNumberOfBytesToLockLow
  841. ctypes.wintypes.DWORD, # nNumberOfBytesToLockHigh
  842. ctypes.POINTER(OVERLAPPED) # Overlapped
  843. ]
  844. UnlockFileEx.restype = ctypes.wintypes.BOOL
  845. whole_low = 0xffffffff
  846. whole_high = 0x7fffffff
  847. def _lock_file(f, exclusive):
  848. overlapped = OVERLAPPED()
  849. overlapped.Offset = 0
  850. overlapped.OffsetHigh = 0
  851. overlapped.hEvent = 0
  852. f._lock_file_overlapped_p = ctypes.pointer(overlapped)
  853. handle = msvcrt.get_osfhandle(f.fileno())
  854. if not LockFileEx(handle, 0x2 if exclusive else 0x0, 0,
  855. whole_low, whole_high, f._lock_file_overlapped_p):
  856. raise OSError('Locking file failed: %r' % ctypes.FormatError())
  857. def _unlock_file(f):
  858. assert f._lock_file_overlapped_p
  859. handle = msvcrt.get_osfhandle(f.fileno())
  860. if not UnlockFileEx(handle, 0,
  861. whole_low, whole_high, f._lock_file_overlapped_p):
  862. raise OSError('Unlocking file failed: %r' % ctypes.FormatError())
  863. else:
  864. import fcntl
  865. def _lock_file(f, exclusive):
  866. fcntl.flock(f, fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH)
  867. def _unlock_file(f):
  868. fcntl.flock(f, fcntl.LOCK_UN)
  869. class locked_file(object):
  870. def __init__(self, filename, mode, encoding=None):
  871. assert mode in ['r', 'a', 'w']
  872. self.f = io.open(filename, mode, encoding=encoding)
  873. self.mode = mode
  874. def __enter__(self):
  875. exclusive = self.mode != 'r'
  876. try:
  877. _lock_file(self.f, exclusive)
  878. except IOError:
  879. self.f.close()
  880. raise
  881. return self
  882. def __exit__(self, etype, value, traceback):
  883. try:
  884. _unlock_file(self.f)
  885. finally:
  886. self.f.close()
  887. def __iter__(self):
  888. return iter(self.f)
  889. def write(self, *args):
  890. return self.f.write(*args)
  891. def read(self, *args):
  892. return self.f.read(*args)
  893. def get_filesystem_encoding():
  894. encoding = sys.getfilesystemencoding()
  895. return encoding if encoding is not None else 'utf-8'
  896. def shell_quote(args):
  897. quoted_args = []
  898. encoding = get_filesystem_encoding()
  899. for a in args:
  900. if isinstance(a, bytes):
  901. # We may get a filename encoded with 'encodeFilename'
  902. a = a.decode(encoding)
  903. quoted_args.append(pipes.quote(a))
  904. return ' '.join(quoted_args)
  905. def takewhile_inclusive(pred, seq):
  906. """ Like itertools.takewhile, but include the latest evaluated element
  907. (the first element so that Not pred(e)) """
  908. for e in seq:
  909. yield e
  910. if not pred(e):
  911. return
  912. def smuggle_url(url, data):
  913. """ Pass additional data in a URL for internal use. """
  914. sdata = compat_urllib_parse.urlencode(
  915. {'__youtubedl_smuggle': json.dumps(data)})
  916. return url + '#' + sdata
  917. def unsmuggle_url(smug_url, default=None):
  918. if '#__youtubedl_smuggle' not in smug_url:
  919. return smug_url, default
  920. url, _, sdata = smug_url.rpartition('#')
  921. jsond = compat_parse_qs(sdata)['__youtubedl_smuggle'][0]
  922. data = json.loads(jsond)
  923. return url, data
  924. def format_bytes(bytes):
  925. if bytes is None:
  926. return 'N/A'
  927. if type(bytes) is str:
  928. bytes = float(bytes)
  929. if bytes == 0.0:
  930. exponent = 0
  931. else:
  932. exponent = int(math.log(bytes, 1024.0))
  933. suffix = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'][exponent]
  934. converted = float(bytes) / float(1024 ** exponent)
  935. return '%.2f%s' % (converted, suffix)
  936. def parse_filesize(s):
  937. if s is None:
  938. return None
  939. # The lower-case forms are of course incorrect and inofficial,
  940. # but we support those too
  941. _UNIT_TABLE = {
  942. 'B': 1,
  943. 'b': 1,
  944. 'KiB': 1024,
  945. 'KB': 1000,
  946. 'kB': 1024,
  947. 'Kb': 1000,
  948. 'MiB': 1024 ** 2,
  949. 'MB': 1000 ** 2,
  950. 'mB': 1024 ** 2,
  951. 'Mb': 1000 ** 2,
  952. 'GiB': 1024 ** 3,
  953. 'GB': 1000 ** 3,
  954. 'gB': 1024 ** 3,
  955. 'Gb': 1000 ** 3,
  956. 'TiB': 1024 ** 4,
  957. 'TB': 1000 ** 4,
  958. 'tB': 1024 ** 4,
  959. 'Tb': 1000 ** 4,
  960. 'PiB': 1024 ** 5,
  961. 'PB': 1000 ** 5,
  962. 'pB': 1024 ** 5,
  963. 'Pb': 1000 ** 5,
  964. 'EiB': 1024 ** 6,
  965. 'EB': 1000 ** 6,
  966. 'eB': 1024 ** 6,
  967. 'Eb': 1000 ** 6,
  968. 'ZiB': 1024 ** 7,
  969. 'ZB': 1000 ** 7,
  970. 'zB': 1024 ** 7,
  971. 'Zb': 1000 ** 7,
  972. 'YiB': 1024 ** 8,
  973. 'YB': 1000 ** 8,
  974. 'yB': 1024 ** 8,
  975. 'Yb': 1000 ** 8,
  976. }
  977. units_re = '|'.join(re.escape(u) for u in _UNIT_TABLE)
  978. m = re.match(
  979. r'(?P<num>[0-9]+(?:[,.][0-9]*)?)\s*(?P<unit>%s)' % units_re, s)
  980. if not m:
  981. return None
  982. num_str = m.group('num').replace(',', '.')
  983. mult = _UNIT_TABLE[m.group('unit')]
  984. return int(float(num_str) * mult)
  985. def month_by_name(name):
  986. """ Return the number of a month by (locale-independently) English name """
  987. try:
  988. return ENGLISH_MONTH_NAMES.index(name) + 1
  989. except ValueError:
  990. return None
  991. def month_by_abbreviation(abbrev):
  992. """ Return the number of a month by (locale-independently) English
  993. abbreviations """
  994. try:
  995. return [s[:3] for s in ENGLISH_MONTH_NAMES].index(abbrev) + 1
  996. except ValueError:
  997. return None
  998. def fix_xml_ampersands(xml_str):
  999. """Replace all the '&' by '&amp;' in XML"""
  1000. return re.sub(
  1001. r'&(?!amp;|lt;|gt;|apos;|quot;|#x[0-9a-fA-F]{,4};|#[0-9]{,4};)',
  1002. '&amp;',
  1003. xml_str)
  1004. def setproctitle(title):
  1005. assert isinstance(title, compat_str)
  1006. try:
  1007. libc = ctypes.cdll.LoadLibrary("libc.so.6")
  1008. except OSError:
  1009. return
  1010. title_bytes = title.encode('utf-8')
  1011. buf = ctypes.create_string_buffer(len(title_bytes))
  1012. buf.value = title_bytes
  1013. try:
  1014. libc.prctl(15, buf, 0, 0, 0)
  1015. except AttributeError:
  1016. return # Strange libc, just skip this
  1017. def remove_start(s, start):
  1018. if s.startswith(start):
  1019. return s[len(start):]
  1020. return s
  1021. def remove_end(s, end):
  1022. if s.endswith(end):
  1023. return s[:-len(end)]
  1024. return s
  1025. def url_basename(url):
  1026. path = compat_urlparse.urlparse(url).path
  1027. return path.strip('/').split('/')[-1]
  1028. class HEADRequest(compat_urllib_request.Request):
  1029. def get_method(self):
  1030. return "HEAD"
  1031. def int_or_none(v, scale=1, default=None, get_attr=None, invscale=1):
  1032. if get_attr:
  1033. if v is not None:
  1034. v = getattr(v, get_attr, None)
  1035. if v == '':
  1036. v = None
  1037. return default if v is None else (int(v) * invscale // scale)
  1038. def str_or_none(v, default=None):
  1039. return default if v is None else compat_str(v)
  1040. def str_to_int(int_str):
  1041. """ A more relaxed version of int_or_none """
  1042. if int_str is None:
  1043. return None
  1044. int_str = re.sub(r'[,\.\+]', '', int_str)
  1045. return int(int_str)
  1046. def float_or_none(v, scale=1, invscale=1, default=None):
  1047. return default if v is None else (float(v) * invscale / scale)
  1048. def parse_duration(s):
  1049. if not isinstance(s, compat_basestring):
  1050. return None
  1051. s = s.strip()
  1052. m = re.match(
  1053. r'''(?ix)(?:P?T)?
  1054. (?:
  1055. (?P<only_mins>[0-9.]+)\s*(?:mins?|minutes?)\s*|
  1056. (?P<only_hours>[0-9.]+)\s*(?:hours?)|
  1057. \s*(?P<hours_reversed>[0-9]+)\s*(?:[:h]|hours?)\s*(?P<mins_reversed>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*|
  1058. (?:
  1059. (?:
  1060. (?:(?P<days>[0-9]+)\s*(?:[:d]|days?)\s*)?
  1061. (?P<hours>[0-9]+)\s*(?:[:h]|hours?)\s*
  1062. )?
  1063. (?P<mins>[0-9]+)\s*(?:[:m]|mins?|minutes?)\s*
  1064. )?
  1065. (?P<secs>[0-9]+)(?P<ms>\.[0-9]+)?\s*(?:s|secs?|seconds?)?
  1066. )$''', s)
  1067. if not m:
  1068. return None
  1069. res = 0
  1070. if m.group('only_mins'):
  1071. return float_or_none(m.group('only_mins'), invscale=60)
  1072. if m.group('only_hours'):
  1073. return float_or_none(m.group('only_hours'), invscale=60 * 60)
  1074. if m.group('secs'):
  1075. res += int(m.group('secs'))
  1076. if m.group('mins_reversed'):
  1077. res += int(m.group('mins_reversed')) * 60
  1078. if m.group('mins'):
  1079. res += int(m.group('mins')) * 60
  1080. if m.group('hours'):
  1081. res += int(m.group('hours')) * 60 * 60
  1082. if m.group('hours_reversed'):
  1083. res += int(m.group('hours_reversed')) * 60 * 60
  1084. if m.group('days'):
  1085. res += int(m.group('days')) * 24 * 60 * 60
  1086. if m.group('ms'):
  1087. res += float(m.group('ms'))
  1088. return res
  1089. def prepend_extension(filename, ext):
  1090. name, real_ext = os.path.splitext(filename)
  1091. return '{0}.{1}{2}'.format(name, ext, real_ext)
  1092. def check_executable(exe, args=[]):
  1093. """ Checks if the given binary is installed somewhere in PATH, and returns its name.
  1094. args can be a list of arguments for a short output (like -version) """
  1095. try:
  1096. subprocess.Popen([exe] + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  1097. except OSError:
  1098. return False
  1099. return exe
  1100. def get_exe_version(exe, args=['--version'],
  1101. version_re=None, unrecognized='present'):
  1102. """ Returns the version of the specified executable,
  1103. or False if the executable is not present """
  1104. try:
  1105. out, _ = subprocess.Popen(
  1106. [exe] + args,
  1107. stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
  1108. except OSError:
  1109. return False
  1110. if isinstance(out, bytes): # Python 2.x
  1111. out = out.decode('ascii', 'ignore')
  1112. return detect_exe_version(out, version_re, unrecognized)
  1113. def detect_exe_version(output, version_re=None, unrecognized='present'):
  1114. assert isinstance(output, compat_str)
  1115. if version_re is None:
  1116. version_re = r'version\s+([-0-9._a-zA-Z]+)'
  1117. m = re.search(version_re, output)
  1118. if m:
  1119. return m.group(1)
  1120. else:
  1121. return unrecognized
  1122. class PagedList(object):
  1123. def __len__(self):
  1124. # This is only useful for tests
  1125. return len(self.getslice())
  1126. class OnDemandPagedList(PagedList):
  1127. def __init__(self, pagefunc, pagesize):
  1128. self._pagefunc = pagefunc
  1129. self._pagesize = pagesize
  1130. def getslice(self, start=0, end=None):
  1131. res = []
  1132. for pagenum in itertools.count(start // self._pagesize):
  1133. firstid = pagenum * self._pagesize
  1134. nextfirstid = pagenum * self._pagesize + self._pagesize
  1135. if start >= nextfirstid:
  1136. continue
  1137. page_results = list(self._pagefunc(pagenum))
  1138. startv = (
  1139. start % self._pagesize
  1140. if firstid <= start < nextfirstid
  1141. else 0)
  1142. endv = (
  1143. ((end - 1) % self._pagesize) + 1
  1144. if (end is not None and firstid <= end <= nextfirstid)
  1145. else None)
  1146. if startv != 0 or endv is not None:
  1147. page_results = page_results[startv:endv]
  1148. res.extend(page_results)
  1149. # A little optimization - if current page is not "full", ie. does
  1150. # not contain page_size videos then we can assume that this page
  1151. # is the last one - there are no more ids on further pages -
  1152. # i.e. no need to query again.
  1153. if len(page_results) + startv < self._pagesize:
  1154. break
  1155. # If we got the whole page, but the next page is not interesting,
  1156. # break out early as well
  1157. if end == nextfirstid:
  1158. break
  1159. return res
  1160. class InAdvancePagedList(PagedList):
  1161. def __init__(self, pagefunc, pagecount, pagesize):
  1162. self._pagefunc = pagefunc
  1163. self._pagecount = pagecount
  1164. self._pagesize = pagesize
  1165. def getslice(self, start=0, end=None):
  1166. res = []
  1167. start_page = start // self._pagesize
  1168. end_page = (
  1169. self._pagecount if end is None else (end // self._pagesize + 1))
  1170. skip_elems = start - start_page * self._pagesize
  1171. only_more = None if end is None else end - start
  1172. for pagenum in range(start_page, end_page):
  1173. page = list(self._pagefunc(pagenum))
  1174. if skip_elems:
  1175. page = page[skip_elems:]
  1176. skip_elems = None
  1177. if only_more is not None:
  1178. if len(page) < only_more:
  1179. only_more -= len(page)
  1180. else:
  1181. page = page[:only_more]
  1182. res.extend(page)
  1183. break
  1184. res.extend(page)
  1185. return res
  1186. def uppercase_escape(s):
  1187. unicode_escape = codecs.getdecoder('unicode_escape')
  1188. return re.sub(
  1189. r'\\U[0-9a-fA-F]{8}',
  1190. lambda m: unicode_escape(m.group(0))[0],
  1191. s)
  1192. def escape_rfc3986(s):
  1193. """Escape non-ASCII characters as suggested by RFC 3986"""
  1194. if sys.version_info < (3, 0) and isinstance(s, compat_str):
  1195. s = s.encode('utf-8')
  1196. return compat_urllib_parse.quote(s, b"%/;:@&=+$,!~*'()?#[]")
  1197. def escape_url(url):
  1198. """Escape URL as suggested by RFC 3986"""
  1199. url_parsed = compat_urllib_parse_urlparse(url)
  1200. return url_parsed._replace(
  1201. path=escape_rfc3986(url_parsed.path),
  1202. params=escape_rfc3986(url_parsed.params),
  1203. query=escape_rfc3986(url_parsed.query),
  1204. fragment=escape_rfc3986(url_parsed.fragment)
  1205. ).geturl()
  1206. try:
  1207. struct.pack('!I', 0)
  1208. except TypeError:
  1209. # In Python 2.6 (and some 2.7 versions), struct requires a bytes argument
  1210. def struct_pack(spec, *args):
  1211. if isinstance(spec, compat_str):
  1212. spec = spec.encode('ascii')
  1213. return struct.pack(spec, *args)
  1214. def struct_unpack(spec, *args):
  1215. if isinstance(spec, compat_str):
  1216. spec = spec.encode('ascii')
  1217. return struct.unpack(spec, *args)
  1218. else:
  1219. struct_pack = struct.pack
  1220. struct_unpack = struct.unpack
  1221. def read_batch_urls(batch_fd):
  1222. def fixup(url):
  1223. if not isinstance(url, compat_str):
  1224. url = url.decode('utf-8', 'replace')
  1225. BOM_UTF8 = '\xef\xbb\xbf'
  1226. if url.startswith(BOM_UTF8):
  1227. url = url[len(BOM_UTF8):]
  1228. url = url.strip()
  1229. if url.startswith(('#', ';', ']')):
  1230. return False
  1231. return url
  1232. with contextlib.closing(batch_fd) as fd:
  1233. return [url for url in map(fixup, fd) if url]
  1234. def urlencode_postdata(*args, **kargs):
  1235. return compat_urllib_parse.urlencode(*args, **kargs).encode('ascii')
  1236. try:
  1237. etree_iter = xml.etree.ElementTree.Element.iter
  1238. except AttributeError: # Python <=2.6
  1239. etree_iter = lambda n: n.findall('.//*')
  1240. def parse_xml(s):
  1241. class TreeBuilder(xml.etree.ElementTree.TreeBuilder):
  1242. def doctype(self, name, pubid, system):
  1243. pass # Ignore doctypes
  1244. parser = xml.etree.ElementTree.XMLParser(target=TreeBuilder())
  1245. kwargs = {'parser': parser} if sys.version_info >= (2, 7) else {}
  1246. tree = xml.etree.ElementTree.XML(s.encode('utf-8'), **kwargs)
  1247. # Fix up XML parser in Python 2.x
  1248. if sys.version_info < (3, 0):
  1249. for n in etree_iter(tree):
  1250. if n.text is not None:
  1251. if not isinstance(n.text, compat_str):
  1252. n.text = n.text.decode('utf-8')
  1253. return tree
  1254. US_RATINGS = {
  1255. 'G': 0,
  1256. 'PG': 10,
  1257. 'PG-13': 13,
  1258. 'R': 16,
  1259. 'NC': 18,
  1260. }
  1261. def parse_age_limit(s):
  1262. if s is None:
  1263. return None
  1264. m = re.match(r'^(?P<age>\d{1,2})\+?$', s)
  1265. return int(m.group('age')) if m else US_RATINGS.get(s, None)
  1266. def strip_jsonp(code):
  1267. return re.sub(
  1268. r'(?s)^[a-zA-Z0-9_]+\s*\(\s*(.*)\);?\s*?(?://[^\n]*)*$', r'\1', code)
  1269. def js_to_json(code):
  1270. def fix_kv(m):
  1271. v = m.group(0)
  1272. if v in ('true', 'false', 'null'):
  1273. return v
  1274. if v.startswith('"'):
  1275. return v
  1276. if v.startswith("'"):
  1277. v = v[1:-1]
  1278. v = re.sub(r"\\\\|\\'|\"", lambda m: {
  1279. '\\\\': '\\\\',
  1280. "\\'": "'",
  1281. '"': '\\"',
  1282. }[m.group(0)], v)
  1283. return '"%s"' % v
  1284. res = re.sub(r'''(?x)
  1285. "(?:[^"\\]*(?:\\\\|\\['"nu]))*[^"\\]*"|
  1286. '(?:[^'\\]*(?:\\\\|\\['"nu]))*[^'\\]*'|
  1287. [a-zA-Z_][.a-zA-Z_0-9]*
  1288. ''', fix_kv, code)
  1289. res = re.sub(r',(\s*\])', lambda m: m.group(1), res)
  1290. return res
  1291. def qualities(quality_ids):
  1292. """ Get a numeric quality value out of a list of possible values """
  1293. def q(qid):
  1294. try:
  1295. return quality_ids.index(qid)
  1296. except ValueError:
  1297. return -1
  1298. return q
  1299. DEFAULT_OUTTMPL = '%(title)s-%(id)s.%(ext)s'
  1300. def limit_length(s, length):
  1301. """ Add ellipses to overly long strings """
  1302. if s is None:
  1303. return None
  1304. ELLIPSES = '...'
  1305. if len(s) > length:
  1306. return s[:length - len(ELLIPSES)] + ELLIPSES
  1307. return s
  1308. def version_tuple(v):
  1309. return tuple(int(e) for e in re.split(r'[-.]', v))
  1310. def is_outdated_version(version, limit, assume_new=True):
  1311. if not version:
  1312. return not assume_new
  1313. try:
  1314. return version_tuple(version) < version_tuple(limit)
  1315. except ValueError:
  1316. return not assume_new
  1317. def ytdl_is_updateable():
  1318. """ Returns if youtube-dl can be updated with -U """
  1319. from zipimport import zipimporter
  1320. return isinstance(globals().get('__loader__'), zipimporter) or hasattr(sys, 'frozen')
  1321. def args_to_str(args):
  1322. # Get a short string representation for a subprocess command
  1323. return ' '.join(shlex_quote(a) for a in args)
  1324. def mimetype2ext(mt):
  1325. _, _, res = mt.rpartition('/')
  1326. return {
  1327. 'x-ms-wmv': 'wmv',
  1328. 'x-mp4-fragmented': 'mp4',
  1329. }.get(res, res)
  1330. def urlhandle_detect_ext(url_handle):
  1331. try:
  1332. url_handle.headers
  1333. getheader = lambda h: url_handle.headers[h]
  1334. except AttributeError: # Python < 3
  1335. getheader = url_handle.info().getheader
  1336. cd = getheader('Content-Disposition')
  1337. if cd:
  1338. m = re.match(r'attachment;\s*filename="(?P<filename>[^"]+)"', cd)
  1339. if m:
  1340. e = determine_ext(m.group('filename'), default_ext=None)
  1341. if e:
  1342. return e
  1343. return mimetype2ext(getheader('Content-Type'))
  1344. def age_restricted(content_limit, age_limit):
  1345. """ Returns True iff the content should be blocked """
  1346. if age_limit is None: # No limit set
  1347. return False
  1348. if content_limit is None:
  1349. return False # Content available for everyone
  1350. return age_limit < content_limit
  1351. def is_html(first_bytes):
  1352. """ Detect whether a file contains HTML by examining its first bytes. """
  1353. BOMS = [
  1354. (b'\xef\xbb\xbf', 'utf-8'),
  1355. (b'\x00\x00\xfe\xff', 'utf-32-be'),
  1356. (b'\xff\xfe\x00\x00', 'utf-32-le'),
  1357. (b'\xff\xfe', 'utf-16-le'),
  1358. (b'\xfe\xff', 'utf-16-be'),
  1359. ]
  1360. for bom, enc in BOMS:
  1361. if first_bytes.startswith(bom):
  1362. s = first_bytes[len(bom):].decode(enc, 'replace')
  1363. break
  1364. else:
  1365. s = first_bytes.decode('utf-8', 'replace')
  1366. return re.match(r'^\s*<', s)
  1367. def determine_protocol(info_dict):
  1368. protocol = info_dict.get('protocol')
  1369. if protocol is not None:
  1370. return protocol
  1371. url = info_dict['url']
  1372. if url.startswith('rtmp'):
  1373. return 'rtmp'
  1374. elif url.startswith('mms'):
  1375. return 'mms'
  1376. elif url.startswith('rtsp'):
  1377. return 'rtsp'
  1378. ext = determine_ext(url)
  1379. if ext == 'm3u8':
  1380. return 'm3u8'
  1381. elif ext == 'f4m':
  1382. return 'f4m'
  1383. return compat_urllib_parse_urlparse(url).scheme
  1384. def render_table(header_row, data):
  1385. """ Render a list of rows, each as a list of values """
  1386. table = [header_row] + data
  1387. max_lens = [max(len(compat_str(v)) for v in col) for col in zip(*table)]
  1388. format_str = ' '.join('%-' + compat_str(ml + 1) + 's' for ml in max_lens[:-1]) + '%s'
  1389. return '\n'.join(format_str % tuple(row) for row in table)
  1390. def _match_one(filter_part, dct):
  1391. COMPARISON_OPERATORS = {
  1392. '<': operator.lt,
  1393. '<=': operator.le,
  1394. '>': operator.gt,
  1395. '>=': operator.ge,
  1396. '=': operator.eq,
  1397. '!=': operator.ne,
  1398. }
  1399. operator_rex = re.compile(r'''(?x)\s*
  1400. (?P<key>[a-z_]+)
  1401. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  1402. (?:
  1403. (?P<intval>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)|
  1404. (?P<strval>(?![0-9.])[a-z0-9A-Z]*)
  1405. )
  1406. \s*$
  1407. ''' % '|'.join(map(re.escape, COMPARISON_OPERATORS.keys())))
  1408. m = operator_rex.search(filter_part)
  1409. if m:
  1410. op = COMPARISON_OPERATORS[m.group('op')]
  1411. if m.group('strval') is not None:
  1412. if m.group('op') not in ('=', '!='):
  1413. raise ValueError(
  1414. 'Operator %s does not support string values!' % m.group('op'))
  1415. comparison_value = m.group('strval')
  1416. else:
  1417. try:
  1418. comparison_value = int(m.group('intval'))
  1419. except ValueError:
  1420. comparison_value = parse_filesize(m.group('intval'))
  1421. if comparison_value is None:
  1422. comparison_value = parse_filesize(m.group('intval') + 'B')
  1423. if comparison_value is None:
  1424. raise ValueError(
  1425. 'Invalid integer value %r in filter part %r' % (
  1426. m.group('intval'), filter_part))
  1427. actual_value = dct.get(m.group('key'))
  1428. if actual_value is None:
  1429. return m.group('none_inclusive')
  1430. return op(actual_value, comparison_value)
  1431. UNARY_OPERATORS = {
  1432. '': lambda v: v is not None,
  1433. '!': lambda v: v is None,
  1434. }
  1435. operator_rex = re.compile(r'''(?x)\s*
  1436. (?P<op>%s)\s*(?P<key>[a-z_]+)
  1437. \s*$
  1438. ''' % '|'.join(map(re.escape, UNARY_OPERATORS.keys())))
  1439. m = operator_rex.search(filter_part)
  1440. if m:
  1441. op = UNARY_OPERATORS[m.group('op')]
  1442. actual_value = dct.get(m.group('key'))
  1443. return op(actual_value)
  1444. raise ValueError('Invalid filter part %r' % filter_part)
  1445. def match_str(filter_str, dct):
  1446. """ Filter a dictionary with a simple string syntax. Returns True (=passes filter) or false """
  1447. return all(
  1448. _match_one(filter_part, dct) for filter_part in filter_str.split('&'))
  1449. def match_filter_func(filter_str):
  1450. def _match_func(info_dict):
  1451. if match_str(filter_str, info_dict):
  1452. return None
  1453. else:
  1454. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  1455. return '%s does not pass filter %s, skipping ..' % (video_title, filter_str)
  1456. return _match_func
  1457. class PerRequestProxyHandler(compat_urllib_request.ProxyHandler):
  1458. def __init__(self, proxies=None):
  1459. # Set default handlers
  1460. for type in ('http', 'https'):
  1461. setattr(self, '%s_open' % type,
  1462. lambda r, proxy='__noproxy__', type=type, meth=self.proxy_open:
  1463. meth(r, proxy, type))
  1464. return compat_urllib_request.ProxyHandler.__init__(self, proxies)
  1465. def proxy_open(self, req, proxy, type):
  1466. req_proxy = req.headers.get('Ytdl-request-proxy')
  1467. if req_proxy is not None:
  1468. proxy = req_proxy
  1469. del req.headers['Ytdl-request-proxy']
  1470. if proxy == '__noproxy__':
  1471. return None # No Proxy
  1472. return compat_urllib_request.ProxyHandler.proxy_open(
  1473. self, req, proxy, type)