You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

539 lines
17 KiB

  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. def htmlentity_transform(matchobj):
  170. """Transforms an HTML entity to a character.
  171. This function receives a match object and is intended to be used with
  172. the re.sub() function.
  173. """
  174. entity = matchobj.group(1)
  175. # Known non-numeric HTML entity
  176. if entity in compat_html_entities.name2codepoint:
  177. return compat_chr(compat_html_entities.name2codepoint[entity])
  178. mobj = re.match(u'(?u)#(x?\\d+)', entity)
  179. if mobj is not None:
  180. numstr = mobj.group(1)
  181. if numstr.startswith(u'x'):
  182. base = 16
  183. numstr = u'0%s' % numstr
  184. else:
  185. base = 10
  186. return compat_chr(int(numstr, base))
  187. # Unknown entity in name, return its literal representation
  188. return (u'&%s;' % entity)
  189. 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
  190. class AttrParser(compat_html_parser.HTMLParser):
  191. """Modified HTMLParser that isolates a tag with the specified attribute"""
  192. def __init__(self, attribute, value):
  193. self.attribute = attribute
  194. self.value = value
  195. self.result = None
  196. self.started = False
  197. self.depth = {}
  198. self.html = None
  199. self.watch_startpos = False
  200. self.error_count = 0
  201. compat_html_parser.HTMLParser.__init__(self)
  202. def error(self, message):
  203. if self.error_count > 10 or self.started:
  204. raise compat_html_parser.HTMLParseError(message, self.getpos())
  205. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  206. self.error_count += 1
  207. self.goahead(1)
  208. def loads(self, html):
  209. self.html = html
  210. self.feed(html)
  211. self.close()
  212. def handle_starttag(self, tag, attrs):
  213. attrs = dict(attrs)
  214. if self.started:
  215. self.find_startpos(None)
  216. if self.attribute in attrs and attrs[self.attribute] == self.value:
  217. self.result = [tag]
  218. self.started = True
  219. self.watch_startpos = True
  220. if self.started:
  221. if not tag in self.depth: self.depth[tag] = 0
  222. self.depth[tag] += 1
  223. def handle_endtag(self, tag):
  224. if self.started:
  225. if tag in self.depth: self.depth[tag] -= 1
  226. if self.depth[self.result[0]] == 0:
  227. self.started = False
  228. self.result.append(self.getpos())
  229. def find_startpos(self, x):
  230. """Needed to put the start position of the result (self.result[1])
  231. after the opening tag with the requested id"""
  232. if self.watch_startpos:
  233. self.watch_startpos = False
  234. self.result.append(self.getpos())
  235. handle_entityref = handle_charref = handle_data = handle_comment = \
  236. handle_decl = handle_pi = unknown_decl = find_startpos
  237. def get_result(self):
  238. if self.result is None:
  239. return None
  240. if len(self.result) != 3:
  241. return None
  242. lines = self.html.split('\n')
  243. lines = lines[self.result[1][0]-1:self.result[2][0]]
  244. lines[0] = lines[0][self.result[1][1]:]
  245. if len(lines) == 1:
  246. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  247. lines[-1] = lines[-1][:self.result[2][1]]
  248. return '\n'.join(lines).strip()
  249. def get_element_by_id(id, html):
  250. """Return the content of the tag with the specified ID in the passed HTML document"""
  251. return get_element_by_attribute("id", id, html)
  252. def get_element_by_attribute(attribute, value, html):
  253. """Return the content of the tag with the specified attribute in the passed HTML document"""
  254. parser = AttrParser(attribute, value)
  255. try:
  256. parser.loads(html)
  257. except compat_html_parser.HTMLParseError:
  258. pass
  259. return parser.get_result()
  260. def clean_html(html):
  261. """Clean an HTML snippet into a readable string"""
  262. # Newline vs <br />
  263. html = html.replace('\n', ' ')
  264. html = re.sub(r'\s*<\s*br\s*/?\s*>\s*', '\n', html)
  265. html = re.sub(r'<\s*/\s*p\s*>\s*<\s*p[^>]*>', '\n', html)
  266. # Strip html tags
  267. html = re.sub('<.*?>', '', html)
  268. # Replace html entities
  269. html = unescapeHTML(html)
  270. return html
  271. def sanitize_open(filename, open_mode):
  272. """Try to open the given filename, and slightly tweak it if this fails.
  273. Attempts to open the given filename. If this fails, it tries to change
  274. the filename slightly, step by step, until it's either able to open it
  275. or it fails and raises a final exception, like the standard open()
  276. function.
  277. It returns the tuple (stream, definitive_file_name).
  278. """
  279. try:
  280. if filename == u'-':
  281. if sys.platform == 'win32':
  282. import msvcrt
  283. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  284. return (sys.stdout, filename)
  285. stream = open(encodeFilename(filename), open_mode)
  286. return (stream, filename)
  287. except (IOError, OSError) as err:
  288. # In case of error, try to remove win32 forbidden chars
  289. filename = re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', filename)
  290. # An exception here should be caught in the caller
  291. stream = open(encodeFilename(filename), open_mode)
  292. return (stream, filename)
  293. def timeconvert(timestr):
  294. """Convert RFC 2822 defined time string into system timestamp"""
  295. timestamp = None
  296. timetuple = email.utils.parsedate_tz(timestr)
  297. if timetuple is not None:
  298. timestamp = email.utils.mktime_tz(timetuple)
  299. return timestamp
  300. def sanitize_filename(s, restricted=False, is_id=False):
  301. """Sanitizes a string so it could be used as part of a filename.
  302. If restricted is set, use a stricter subset of allowed characters.
  303. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  304. """
  305. def replace_insane(char):
  306. if char == '?' or ord(char) < 32 or ord(char) == 127:
  307. return ''
  308. elif char == '"':
  309. return '' if restricted else '\''
  310. elif char == ':':
  311. return '_-' if restricted else ' -'
  312. elif char in '\\/|*<>':
  313. return '_'
  314. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  315. return '_'
  316. if restricted and ord(char) > 127:
  317. return '_'
  318. return char
  319. result = u''.join(map(replace_insane, s))
  320. if not is_id:
  321. while '__' in result:
  322. result = result.replace('__', '_')
  323. result = result.strip('_')
  324. # Common case of "Foreign band name - English song title"
  325. if restricted and result.startswith('-_'):
  326. result = result[2:]
  327. if not result:
  328. result = '_'
  329. return result
  330. def orderedSet(iterable):
  331. """ Remove all duplicates from the input iterable """
  332. res = []
  333. for el in iterable:
  334. if el not in res:
  335. res.append(el)
  336. return res
  337. def unescapeHTML(s):
  338. """
  339. @param s a string
  340. """
  341. assert type(s) == type(u'')
  342. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  343. return result
  344. def encodeFilename(s):
  345. """
  346. @param s The name of the file
  347. """
  348. assert type(s) == type(u'')
  349. # Python 3 has a Unicode API
  350. if sys.version_info >= (3, 0):
  351. return s
  352. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  353. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  354. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  355. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  356. return s
  357. else:
  358. return s.encode(sys.getfilesystemencoding(), 'ignore')
  359. class ExtractorError(Exception):
  360. """Error during info extraction."""
  361. def __init__(self, msg, tb=None):
  362. """ tb is the original traceback (so that it can be printed out) """
  363. super(ExtractorError, self).__init__(msg)
  364. if tb is None:
  365. tb = sys.exc_info()[2]
  366. self.traceback = tb
  367. class DownloadError(Exception):
  368. """Download Error exception.
  369. This exception may be thrown by FileDownloader objects if they are not
  370. configured to continue on errors. They will contain the appropriate
  371. error message.
  372. """
  373. pass
  374. class SameFileError(Exception):
  375. """Same File exception.
  376. This exception will be thrown by FileDownloader objects if they detect
  377. multiple files would have to be downloaded to the same file on disk.
  378. """
  379. pass
  380. class PostProcessingError(Exception):
  381. """Post Processing exception.
  382. This exception may be raised by PostProcessor's .run() method to
  383. indicate an error in the postprocessing task.
  384. """
  385. pass
  386. class MaxDownloadsReached(Exception):
  387. """ --max-downloads limit has been reached. """
  388. pass
  389. class UnavailableVideoError(Exception):
  390. """Unavailable Format exception.
  391. This exception will be thrown when a video is requested
  392. in a format that is not available for that video.
  393. """
  394. pass
  395. class ContentTooShortError(Exception):
  396. """Content Too Short exception.
  397. This exception may be raised by FileDownloader objects when a file they
  398. download is too small for what the server announced first, indicating
  399. the connection was probably interrupted.
  400. """
  401. # Both in bytes
  402. downloaded = None
  403. expected = None
  404. def __init__(self, downloaded, expected):
  405. self.downloaded = downloaded
  406. self.expected = expected
  407. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  408. """Handler for HTTP requests and responses.
  409. This class, when installed with an OpenerDirector, automatically adds
  410. the standard headers to every HTTP request and handles gzipped and
  411. deflated responses from web servers. If compression is to be avoided in
  412. a particular request, the original request in the program code only has
  413. to include the HTTP header "Youtubedl-No-Compression", which will be
  414. removed before making the real request.
  415. Part of this code was copied from:
  416. http://techknack.net/python-urllib2-handlers/
  417. Andrew Rowls, the author of that code, agreed to release it to the
  418. public domain.
  419. """
  420. @staticmethod
  421. def deflate(data):
  422. try:
  423. return zlib.decompress(data, -zlib.MAX_WBITS)
  424. except zlib.error:
  425. return zlib.decompress(data)
  426. @staticmethod
  427. def addinfourl_wrapper(stream, headers, url, code):
  428. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  429. return compat_urllib_request.addinfourl(stream, headers, url, code)
  430. ret = compat_urllib_request.addinfourl(stream, headers, url)
  431. ret.code = code
  432. return ret
  433. def http_request(self, req):
  434. for h in std_headers:
  435. if h in req.headers:
  436. del req.headers[h]
  437. req.add_header(h, std_headers[h])
  438. if 'Youtubedl-no-compression' in req.headers:
  439. if 'Accept-encoding' in req.headers:
  440. del req.headers['Accept-encoding']
  441. del req.headers['Youtubedl-no-compression']
  442. return req
  443. def http_response(self, req, resp):
  444. old_resp = resp
  445. # gzip
  446. if resp.headers.get('Content-encoding', '') == 'gzip':
  447. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  448. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  449. resp.msg = old_resp.msg
  450. # deflate
  451. if resp.headers.get('Content-encoding', '') == 'deflate':
  452. gz = io.BytesIO(self.deflate(resp.read()))
  453. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  454. resp.msg = old_resp.msg
  455. return resp
  456. https_request = http_request
  457. https_response = http_response