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.

501 lines
14 KiB

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