utils.py 46 KB

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