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.

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