utils.py 49 KB

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