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.

527 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('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  265. # Strip html tags
  266. html = re.sub('<.*?>', '', html)
  267. # Replace html entities
  268. html = unescapeHTML(html)
  269. return html
  270. def sanitize_open(filename, open_mode):
  271. """Try to open the given filename, and slightly tweak it if this fails.
  272. Attempts to open the given filename. If this fails, it tries to change
  273. the filename slightly, step by step, until it's either able to open it
  274. or it fails and raises a final exception, like the standard open()
  275. function.
  276. It returns the tuple (stream, definitive_file_name).
  277. """
  278. try:
  279. if filename == u'-':
  280. if sys.platform == 'win32':
  281. import msvcrt
  282. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  283. return (sys.stdout, filename)
  284. stream = open(encodeFilename(filename), open_mode)
  285. return (stream, filename)
  286. except (IOError, OSError) as err:
  287. # In case of error, try to remove win32 forbidden chars
  288. filename = re.sub(u'[/<>:"\\|\\\\?\\*]', u'#', filename)
  289. # An exception here should be caught in the caller
  290. stream = open(encodeFilename(filename), open_mode)
  291. return (stream, filename)
  292. def timeconvert(timestr):
  293. """Convert RFC 2822 defined time string into system timestamp"""
  294. timestamp = None
  295. timetuple = email.utils.parsedate_tz(timestr)
  296. if timetuple is not None:
  297. timestamp = email.utils.mktime_tz(timetuple)
  298. return timestamp
  299. def sanitize_filename(s, restricted=False, is_id=False):
  300. """Sanitizes a string so it could be used as part of a filename.
  301. If restricted is set, use a stricter subset of allowed characters.
  302. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible
  303. """
  304. def replace_insane(char):
  305. if char == '?' or ord(char) < 32 or ord(char) == 127:
  306. return ''
  307. elif char == '"':
  308. return '' if restricted else '\''
  309. elif char == ':':
  310. return '_-' if restricted else ' -'
  311. elif char in '\\/|*<>':
  312. return '_'
  313. if restricted and (char in '!&\'()[]{}$;`^,#' or char.isspace()):
  314. return '_'
  315. if restricted and ord(char) > 127:
  316. return '_'
  317. return char
  318. result = u''.join(map(replace_insane, s))
  319. if not is_id:
  320. while '__' in result:
  321. result = result.replace('__', '_')
  322. result = result.strip('_')
  323. # Common case of "Foreign band name - English song title"
  324. if restricted and result.startswith('-_'):
  325. result = result[2:]
  326. if not result:
  327. result = '_'
  328. return result
  329. def orderedSet(iterable):
  330. """ Remove all duplicates from the input iterable """
  331. res = []
  332. for el in iterable:
  333. if el not in res:
  334. res.append(el)
  335. return res
  336. def unescapeHTML(s):
  337. """
  338. @param s a string
  339. """
  340. assert type(s) == type(u'')
  341. result = re.sub(u'(?u)&(.+?);', htmlentity_transform, s)
  342. return result
  343. def encodeFilename(s):
  344. """
  345. @param s The name of the file
  346. """
  347. assert type(s) == type(u'')
  348. # Python 3 has a Unicode API
  349. if sys.version_info >= (3, 0):
  350. return s
  351. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  352. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  353. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  354. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  355. return s
  356. else:
  357. return s.encode(sys.getfilesystemencoding(), 'ignore')
  358. class DownloadError(Exception):
  359. """Download Error exception.
  360. This exception may be thrown by FileDownloader objects if they are not
  361. configured to continue on errors. They will contain the appropriate
  362. error message.
  363. """
  364. pass
  365. class SameFileError(Exception):
  366. """Same File exception.
  367. This exception will be thrown by FileDownloader objects if they detect
  368. multiple files would have to be downloaded to the same file on disk.
  369. """
  370. pass
  371. class PostProcessingError(Exception):
  372. """Post Processing exception.
  373. This exception may be raised by PostProcessor's .run() method to
  374. indicate an error in the postprocessing task.
  375. """
  376. pass
  377. class MaxDownloadsReached(Exception):
  378. """ --max-downloads limit has been reached. """
  379. pass
  380. class UnavailableVideoError(Exception):
  381. """Unavailable Format exception.
  382. This exception will be thrown when a video is requested
  383. in a format that is not available for that video.
  384. """
  385. pass
  386. class ContentTooShortError(Exception):
  387. """Content Too Short exception.
  388. This exception may be raised by FileDownloader objects when a file they
  389. download is too small for what the server announced first, indicating
  390. the connection was probably interrupted.
  391. """
  392. # Both in bytes
  393. downloaded = None
  394. expected = None
  395. def __init__(self, downloaded, expected):
  396. self.downloaded = downloaded
  397. self.expected = expected
  398. class YoutubeDLHandler(compat_urllib_request.HTTPHandler):
  399. """Handler for HTTP requests and responses.
  400. This class, when installed with an OpenerDirector, automatically adds
  401. the standard headers to every HTTP request and handles gzipped and
  402. deflated responses from web servers. If compression is to be avoided in
  403. a particular request, the original request in the program code only has
  404. to include the HTTP header "Youtubedl-No-Compression", which will be
  405. removed before making the real request.
  406. Part of this code was copied from:
  407. http://techknack.net/python-urllib2-handlers/
  408. Andrew Rowls, the author of that code, agreed to release it to the
  409. public domain.
  410. """
  411. @staticmethod
  412. def deflate(data):
  413. try:
  414. return zlib.decompress(data, -zlib.MAX_WBITS)
  415. except zlib.error:
  416. return zlib.decompress(data)
  417. @staticmethod
  418. def addinfourl_wrapper(stream, headers, url, code):
  419. if hasattr(compat_urllib_request.addinfourl, 'getcode'):
  420. return compat_urllib_request.addinfourl(stream, headers, url, code)
  421. ret = compat_urllib_request.addinfourl(stream, headers, url)
  422. ret.code = code
  423. return ret
  424. def http_request(self, req):
  425. for h in std_headers:
  426. if h in req.headers:
  427. del req.headers[h]
  428. req.add_header(h, std_headers[h])
  429. if 'Youtubedl-no-compression' in req.headers:
  430. if 'Accept-encoding' in req.headers:
  431. del req.headers['Accept-encoding']
  432. del req.headers['Youtubedl-no-compression']
  433. return req
  434. def http_response(self, req, resp):
  435. old_resp = resp
  436. # gzip
  437. if resp.headers.get('Content-encoding', '') == 'gzip':
  438. gz = gzip.GzipFile(fileobj=io.BytesIO(resp.read()), mode='r')
  439. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  440. resp.msg = old_resp.msg
  441. # deflate
  442. if resp.headers.get('Content-encoding', '') == 'deflate':
  443. gz = io.BytesIO(self.deflate(resp.read()))
  444. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  445. resp.msg = old_resp.msg
  446. return resp
  447. https_request = http_request
  448. https_response = http_response