utils.py 46 KB

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