2
0

utils.py 49 KB

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