utils.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import gzip
  4. import io
  5. import json
  6. import locale
  7. import os
  8. import re
  9. import sys
  10. import zlib
  11. import email.utils
  12. import json
  13. try:
  14. import urllib.request as compat_urllib_request
  15. except ImportError: # Python 2
  16. import urllib2 as compat_urllib_request
  17. try:
  18. import urllib.error as compat_urllib_error
  19. except ImportError: # Python 2
  20. import urllib2 as compat_urllib_error
  21. try:
  22. import urllib.parse as compat_urllib_parse
  23. except ImportError: # Python 2
  24. import urllib as compat_urllib_parse
  25. try:
  26. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  27. except ImportError: # Python 2
  28. from urlparse import urlparse as compat_urllib_parse_urlparse
  29. try:
  30. import http.cookiejar as compat_cookiejar
  31. except ImportError: # Python 2
  32. import cookielib as compat_cookiejar
  33. try:
  34. import html.entities as compat_html_entities
  35. except ImportError: # Python 2
  36. import htmlentitydefs as compat_html_entities
  37. try:
  38. import html.parser as compat_html_parser
  39. except ImportError: # Python 2
  40. import HTMLParser as compat_html_parser
  41. try:
  42. import http.client as compat_http_client
  43. except ImportError: # Python 2
  44. import httplib as compat_http_client
  45. try:
  46. from subprocess import DEVNULL
  47. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  48. except ImportError:
  49. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  50. try:
  51. from urllib.parse import parse_qs as compat_parse_qs
  52. except ImportError: # Python 2
  53. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  54. # Python 2's version is apparently totally broken
  55. def _unquote(string, encoding='utf-8', errors='replace'):
  56. if string == '':
  57. return string
  58. res = string.split('%')
  59. if len(res) == 1:
  60. return string
  61. if encoding is None:
  62. encoding = 'utf-8'
  63. if errors is None:
  64. errors = 'replace'
  65. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  66. pct_sequence = b''
  67. string = res[0]
  68. for item in res[1:]:
  69. try:
  70. if not item:
  71. raise ValueError
  72. pct_sequence += item[:2].decode('hex')
  73. rest = item[2:]
  74. if not rest:
  75. # This segment was just a single percent-encoded character.
  76. # May be part of a sequence of code units, so delay decoding.
  77. # (Stored in pct_sequence).
  78. continue
  79. except ValueError:
  80. rest = '%' + item
  81. # Encountered non-percent-encoded characters. Flush the current
  82. # pct_sequence.
  83. string += pct_sequence.decode(encoding, errors) + rest
  84. pct_sequence = b''
  85. if pct_sequence:
  86. # Flush the final pct_sequence
  87. string += pct_sequence.decode(encoding, errors)
  88. return string
  89. def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
  90. encoding='utf-8', errors='replace'):
  91. qs, _coerce_result = qs, unicode
  92. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  93. r = []
  94. for name_value in pairs:
  95. if not name_value and not strict_parsing:
  96. continue
  97. nv = name_value.split('=', 1)
  98. if len(nv) != 2:
  99. if strict_parsing:
  100. raise ValueError("bad query field: %r" % (name_value,))
  101. # Handle case of a control-name with no equal sign
  102. if keep_blank_values:
  103. nv.append('')
  104. else:
  105. continue
  106. if len(nv[1]) or keep_blank_values:
  107. name = nv[0].replace('+', ' ')
  108. name = _unquote(name, encoding=encoding, errors=errors)
  109. name = _coerce_result(name)
  110. value = nv[1].replace('+', ' ')
  111. value = _unquote(value, encoding=encoding, errors=errors)
  112. value = _coerce_result(value)
  113. r.append((name, value))
  114. return r
  115. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  116. encoding='utf-8', errors='replace'):
  117. parsed_result = {}
  118. pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
  119. encoding=encoding, errors=errors)
  120. for name, value in pairs:
  121. if name in parsed_result:
  122. parsed_result[name].append(value)
  123. else:
  124. parsed_result[name] = [value]
  125. return parsed_result
  126. try:
  127. compat_str = unicode # Python 2
  128. except NameError:
  129. compat_str = str
  130. try:
  131. compat_chr = unichr # Python 2
  132. except NameError:
  133. compat_chr = chr
  134. std_headers = {
  135. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  136. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  137. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  138. 'Accept-Encoding': 'gzip, deflate',
  139. 'Accept-Language': 'en-us,en;q=0.5',
  140. }
  141. def preferredencoding():
  142. """Get preferred encoding.
  143. Returns the best encoding scheme for the system, based on
  144. locale.getpreferredencoding() and some further tweaks.
  145. """
  146. try:
  147. pref = locale.getpreferredencoding()
  148. u'TEST'.encode(pref)
  149. except:
  150. pref = 'UTF-8'
  151. return pref
  152. if sys.version_info < (3,0):
  153. def compat_print(s):
  154. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  155. else:
  156. def compat_print(s):
  157. assert type(s) == type(u'')
  158. print(s)
  159. # In Python 2.x, json.dump expects a bytestream.
  160. # In Python 3.x, it writes to a character stream
  161. if sys.version_info < (3,0):
  162. def write_json_file(obj, fn):
  163. with open(fn, 'wb') as f:
  164. json.dump(obj, f)
  165. else:
  166. def write_json_file(obj, fn):
  167. with open(fn, 'w', encoding='utf-8') as f:
  168. json.dump(obj, f)
  169. # Some library functions return bytestring on 2.X and unicode on 3.X
  170. def enforce_unicode(s, encoding='utf-8'):
  171. if type(s) != type(u''):
  172. return s.decode(encoding)
  173. return s
  174. def htmlentity_transform(matchobj):
  175. """Transforms an HTML entity to a character.
  176. This function receives a match object and is intended to be used with
  177. the re.sub() function.
  178. """
  179. entity = matchobj.group(1)
  180. # Known non-numeric HTML entity
  181. if entity in compat_html_entities.name2codepoint:
  182. return compat_chr(compat_html_entities.name2codepoint[entity])
  183. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  184. if mobj is not None:
  185. numstr = mobj.group(1)
  186. if numstr.startswith(u'x'):
  187. base = 16
  188. numstr = u'0%s' % numstr
  189. else:
  190. base = 10
  191. return compat_chr(int(numstr, base))
  192. # Unknown entity in name, return its literal representation
  193. return (u'&%s;' % entity)
  194. 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
  195. class AttrParser(compat_html_parser.HTMLParser):
  196. """Modified HTMLParser that isolates a tag with the specified attribute"""
  197. def __init__(self, attribute, value):
  198. self.attribute = attribute
  199. self.value = value
  200. self.result = None
  201. self.started = False
  202. self.depth = {}
  203. self.html = None
  204. self.watch_startpos = False
  205. self.error_count = 0
  206. compat_html_parser.HTMLParser.__init__(self)
  207. def error(self, message):
  208. if self.error_count > 10 or self.started:
  209. raise compat_html_parser.HTMLParseError(message, self.getpos())
  210. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  211. self.error_count += 1
  212. self.goahead(1)
  213. def loads(self, html):
  214. self.html = html
  215. self.feed(html)
  216. self.close()
  217. def handle_starttag(self, tag, attrs):
  218. attrs = dict(attrs)
  219. if self.started:
  220. self.find_startpos(None)
  221. if self.attribute in attrs and attrs[self.attribute] == self.value:
  222. self.result = [tag]
  223. self.started = True
  224. self.watch_startpos = True
  225. if self.started:
  226. if not tag in self.depth: self.depth[tag] = 0
  227. self.depth[tag] += 1
  228. def handle_endtag(self, tag):
  229. if self.started:
  230. if tag in self.depth: self.depth[tag] -= 1
  231. if self.depth[self.result[0]] == 0:
  232. self.started = False
  233. self.result.append(self.getpos())
  234. def find_startpos(self, x):
  235. """Needed to put the start position of the result (self.result[1])
  236. after the opening tag with the requested id"""
  237. if self.watch_startpos:
  238. self.watch_startpos = False
  239. self.result.append(self.getpos())
  240. handle_entityref = handle_charref = handle_data = handle_comment = \
  241. handle_decl = handle_pi = unknown_decl = find_startpos
  242. def get_result(self):
  243. if self.result is None:
  244. return None
  245. if len(self.result) != 3:
  246. return None
  247. lines = self.html.split('\n')
  248. lines = lines[self.result[1][0]-1:self.result[2][0]]
  249. lines[0] = lines[0][self.result[1][1]:]
  250. if len(lines) == 1:
  251. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  252. lines[-1] = lines[-1][:self.result[2][1]]
  253. return '\n'.join(lines).strip()
  254. def get_element_by_id(id, html):
  255. """Return the content of the tag with the specified ID in the passed HTML document"""
  256. return get_element_by_attribute("id", id, html)
  257. def get_element_by_attribute(attribute, value, html):
  258. """Return the content of the tag with the specified attribute in the passed HTML document"""
  259. parser = AttrParser(attribute, value)
  260. try:
  261. parser.loads(html)
  262. except compat_html_parser.HTMLParseError:
  263. pass
  264. return parser.get_result()
  265. def clean_html(html):
  266. """Clean an HTML snippet into a readable string"""
  267. # Newline vs <br />
  268. html = html.replace('\n', ' ')
  269. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  270. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  271. # Strip html tags
  272. html = re.sub('<.*?>', '', html)
  273. # Replace html entities
  274. html = unescapeHTML(html)
  275. return html
  276. def sanitize_open(filename, open_mode):
  277. """Try to open the given filename, and slightly tweak it if this fails.
  278. Attempts to open the given filename. If this fails, it tries to change
  279. the filename slightly, step by step, until it's either able to open it
  280. or it fails and raises a final exception, like the standard open()
  281. function.
  282. It returns the tuple (stream, definitive_file_name).
  283. """
  284. try:
  285. if filename == u'-':
  286. if sys.platform == 'win32':
  287. import msvcrt
  288. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  289. return (sys.stdout, filename)
  290. stream = open(encodeFilename(filename), open_mode)
  291. return (stream, filename)
  292. except (IOError, OSError) as err:
  293. # In case of error, try to remove win32 forbidden chars
  294. filename = re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', filename)
  295. # An exception here should be caught in the caller
  296. stream = open(encodeFilename(filename), open_mode)
  297. return (stream, filename)
  298. def timeconvert(timestr):
  299. """Convert RFC 2822 defined time string into system timestamp"""
  300. timestamp = None
  301. timetuple = email.utils.parsedate_tz(timestr)
  302. if timetuple is not None:
  303. timestamp = email.utils.mktime_tz(timetuple)
  304. return timestamp
  305. def sanitize_filename(s, restricted=False, is_id=False):
  306. """Sanitizes a string so it could be used as part of a filename.
  307. If restricted is set, use a stricter subset of allowed characters.
  308. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  309. """
  310. def replace_insane(char):
  311. if char == '?' or ord(char) < 32 or ord(char) == 127:
  312. return ''
  313. elif char == '"':
  314. return '' if restricted else '\''
  315. elif char == ':':
  316. return '_-' if restricted else ' -'
  317. elif char in '\\/|*<>':
  318. return '_'
  319. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  320. return '_'
  321. if restricted and ord(char) > 127:
  322. return '_'
  323. return char
  324. result = u''.join(map(replace_insane, s))
  325. if not is_id:
  326. while '__' in result:
  327. result = result.replace('__', '_')
  328. result = result.strip('_')
  329. # Common case of "Foreign band name - English song title"
  330. if restricted and result.startswith('-_'):
  331. result = result[2:]
  332. if not result:
  333. result = '_'
  334. return result
  335. def orderedSet(iterable):
  336. """ Remove all duplicates from the input iterable """
  337. res = []
  338. for el in iterable:
  339. if el not in res:
  340. res.append(el)
  341. return res
  342. def unescapeHTML(s):
  343. """
  344. @param s a string
  345. """
  346. assert type(s) == type(u'')
  347. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  348. return result
  349. def encodeFilename(s):
  350. """
  351. @param s The name of the file
  352. """
  353. assert type(s) == type(u'')
  354. # Python 3 has a Unicode API
  355. if sys.version_info >= (3, 0):
  356. return s
  357. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  358. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  359. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  360. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  361. return s
  362. else:
  363. return s.encode(sys.getfilesystemencoding(), 'ignore')
  364. def rsa_verify(message, signature, key):
  365. from struct import pack
  366. from hashlib import sha256
  367. from sys import version_info
  368. def b(x):
  369. if version_info[0] == 2: return x
  370. else: return x.encode('latin1')
  371. assert(type(message) == type(b('')))
  372. block_size = 0
  373. n = key[0]
  374. while n:
  375. block_size += 1
  376. n >>= 8
  377. signature = pow(int(signature, 16), key[1], key[0])
  378. raw_bytes = []
  379. while signature:
  380. raw_bytes.insert(0, pack("B", signature & 0xFF))
  381. signature >>= 8
  382. signature = (block_size - len(raw_bytes)) * b('\x00') + b('').join(raw_bytes)
  383. if signature[0:2] != b('\x00\x01'): return False
  384. signature = signature[2:]
  385. if not b('\x00') in signature: return False
  386. signature = signature[signature.index(b('\x00'))+1:]
  387. if not signature.startswith(b('\x30\x31\x30\x0D\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20')): return False
  388. signature = signature[19:]
  389. if signature != sha256(message).digest(): return False
  390. return True
  391. class DownloadError(Exception):
  392. """Download Error exception.
  393. This exception may be thrown by FileDownloader objects if they are not
  394. configured to continue on errors. They will contain the appropriate
  395. error message.
  396. """
  397. pass
  398. class SameFileError(Exception):
  399. """Same File exception.
  400. This exception will be thrown by FileDownloader objects if they detect
  401. multiple files would have to be downloaded to the same file on disk.
  402. """
  403. pass
  404. class PostProcessingError(Exception):
  405. """Post Processing exception.
  406. This exception may be raised by PostProcessor's .run() method to
  407. indicate an error in the postprocessing task.
  408. """
  409. pass
  410. class MaxDownloadsReached(Exception):
  411. """ --max-downloads limit has been reached. """
  412. pass
  413. class UnavailableVideoError(Exception):
  414. """Unavailable Format exception.
  415. This exception will be thrown when a video is requested
  416. in a format that is not available for that video.
  417. """
  418. pass
  419. class ContentTooShortError(Exception):
  420. """Content Too Short exception.
  421. This exception may be raised by FileDownloader objects when a file they
  422. download is too small for what the server announced first, indicating
  423. the connection was probably interrupted.
  424. """
  425. # Both in bytes
  426. downloaded = None
  427. expected = None
  428. def __init__(self, downloaded, expected):
  429. self.downloaded = downloaded
  430. self.expected = expected
  431. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  432. """Handler for HTTP requests and responses.
  433. This class, when installed with an OpenerDirector, automatically adds
  434. the standard headers to every HTTP request and handles gzipped and
  435. deflated responses from web servers. If compression is to be avoided in
  436. a particular request, the original request in the program code only has
  437. to include the HTTP header "Youtubedl-No-Compression", which will be
  438. removed before making the real request.
  439. Part of this code was copied from:
  440. http://techknack.net/python-urllib2-handlers/
  441. Andrew Rowls, the author of that code, agreed to release it to the
  442. public domain.
  443. """
  444. @staticmethod
  445. def deflate(data):
  446. try:
  447. return zlib.decompress(data, -zlib.MAX_WBITS)
  448. except zlib.error:
  449. return zlib.decompress(data)
  450. @staticmethod
  451. def addinfourl_wrapper(stream, headers, url, code):
  452. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  453. return compat_urllib_request.addinfourl(stream, headers, url, code)
  454. ret = compat_urllib_request.addinfourl(stream, headers, url)
  455. ret.code = code
  456. return ret
  457. def http_request(self, req):
  458. for h in std_headers:
  459. if h in req.headers:
  460. del req.headers[h]
  461. req.add_header(h, std_headers[h])
  462. if 'Youtubedl-no-compression' in req.headers:
  463. if 'Accept-encoding' in req.headers:
  464. del req.headers['Accept-encoding']
  465. del req.headers['Youtubedl-no-compression']
  466. return req
  467. def http_response(self, req, resp):
  468. old_resp = resp
  469. # gzip
  470. if resp.headers.get('Content-encoding', '') == 'gzip':
  471. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  472. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  473. resp.msg = old_resp.msg
  474. # deflate
  475. if resp.headers.get('Content-encoding', '') == 'deflate':
  476. gz = io.BytesIO(self.deflate(resp.read()))
  477. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  478. resp.msg = old_resp.msg
  479. return resp
  480. https_request = http_request
  481. https_response = http_response