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.

372 lines
10 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import gzip
  4. import htmlentitydefs
  5. import HTMLParser
  6. import locale
  7. import os
  8. import re
  9. import sys
  10. import zlib
  11. import urllib2
  12. import email.utils
  13. import json
  14. try:
  15. import cStringIO as StringIO
  16. except ImportError:
  17. import StringIO
  18. std_headers = {
  19. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:10.0) Gecko/20100101 Firefox/10.0',
  20. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  21. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  22. 'Accept-Encoding': 'gzip, deflate',
  23. 'Accept-Language': 'en-us,en;q=0.5',
  24. }
  25. try:
  26. compat_str = unicode # Python 2
  27. except NameError:
  28. compat_str = str
  29. def preferredencoding():
  30. """Get preferred encoding.
  31. Returns the best encoding scheme for the system, based on
  32. locale.getpreferredencoding() and some further tweaks.
  33. """
  34. def yield_preferredencoding():
  35. try:
  36. pref = locale.getpreferredencoding()
  37. u'TEST'.encode(pref)
  38. except:
  39. pref = 'UTF-8'
  40. while True:
  41. yield pref
  42. return yield_preferredencoding().next()
  43. def htmlentity_transform(matchobj):
  44. """Transforms an HTML entity to a Unicode character.
  45. This function receives a match object and is intended to be used with
  46. the re.sub() function.
  47. """
  48. entity = matchobj.group(1)
  49. # Known non-numeric HTML entity
  50. if entity in htmlentitydefs.name2codepoint:
  51. return unichr(htmlentitydefs.name2codepoint[entity])
  52. # Unicode character
  53. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  54. if mobj is not None:
  55. numstr = mobj.group(1)
  56. if numstr.startswith(u'x'):
  57. base = 16
  58. numstr = u'0%s' % numstr
  59. else:
  60. base = 10
  61. return unichr(long(numstr, base))
  62. # Unknown entity in name, return its literal representation
  63. return (u'&%s;' % entity)
  64. HTMLParser.locatestarttagend = re.compile(r"""<[a-zA-Z][-.a-zA-Z0-9:_]*(?:\s+(?:(?<=['"\s])[^\s/>][^\s/=>]*(?:\s*=+\s*(?:'[^']*'|"[^"]*"|(?!['"])[^>\s]*))?\s*)*)?\s*""", re.VERBOSE) # backport bugfix
  65. class IDParser(HTMLParser.HTMLParser):
  66. """Modified HTMLParser that isolates a tag with the specified id"""
  67. def __init__(self, id):
  68. self.id = id
  69. self.result = None
  70. self.started = False
  71. self.depth = {}
  72. self.html = None
  73. self.watch_startpos = False
  74. self.error_count = 0
  75. HTMLParser.HTMLParser.__init__(self)
  76. def error(self, message):
  77. if self.error_count > 10 or self.started:
  78. raise HTMLParser.HTMLParseError(message, self.getpos())
  79. self.rawdata = '\n'.join(self.html.split('\n')[self.getpos()[0]:]) # skip one line
  80. self.error_count += 1
  81. self.goahead(1)
  82. def loads(self, html):
  83. self.html = html
  84. self.feed(html)
  85. self.close()
  86. def handle_starttag(self, tag, attrs):
  87. attrs = dict(attrs)
  88. if self.started:
  89. self.find_startpos(None)
  90. if 'id' in attrs and attrs['id'] == self.id:
  91. self.result = [tag]
  92. self.started = True
  93. self.watch_startpos = True
  94. if self.started:
  95. if not tag in self.depth: self.depth[tag] = 0
  96. self.depth[tag] += 1
  97. def handle_endtag(self, tag):
  98. if self.started:
  99. if tag in self.depth: self.depth[tag] -= 1
  100. if self.depth[self.result[0]] == 0:
  101. self.started = False
  102. self.result.append(self.getpos())
  103. def find_startpos(self, x):
  104. """Needed to put the start position of the result (self.result[1])
  105. after the opening tag with the requested id"""
  106. if self.watch_startpos:
  107. self.watch_startpos = False
  108. self.result.append(self.getpos())
  109. handle_entityref = handle_charref = handle_data = handle_comment = \
  110. handle_decl = handle_pi = unknown_decl = find_startpos
  111. def get_result(self):
  112. if self.result == None: return None
  113. if len(self.result) != 3: return None
  114. lines = self.html.split('\n')
  115. lines = lines[self.result[1][0]-1:self.result[2][0]]
  116. lines[0] = lines[0][self.result[1][1]:]
  117. if len(lines) == 1:
  118. lines[-1] = lines[-1][:self.result[2][1]-self.result[1][1]]
  119. lines[-1] = lines[-1][:self.result[2][1]]
  120. return '\n'.join(lines).strip()
  121. def get_element_by_id(id, html):
  122. """Return the content of the tag with the specified id in the passed HTML document"""
  123. parser = IDParser(id)
  124. try:
  125. parser.loads(html)
  126. except HTMLParser.HTMLParseError:
  127. pass
  128. return parser.get_result()
  129. def clean_html(html):
  130. """Clean an HTML snippet into a readable string"""
  131. # Newline vs <br />
  132. html = html.replace('\n', ' ')
  133. html = re.sub('\s*<\s*br\s*/?\s*>\s*', '\n', html)
  134. # Strip html tags
  135. html = re.sub('<.*?>', '', html)
  136. # Replace html entities
  137. html = unescapeHTML(html)
  138. return html
  139. def sanitize_open(filename, open_mode):
  140. """Try to open the given filename, and slightly tweak it if this fails.
  141. Attempts to open the given filename. If this fails, it tries to change
  142. the filename slightly, step by step, until it's either able to open it
  143. or it fails and raises a final exception, like the standard open()
  144. function.
  145. It returns the tuple (stream, definitive_file_name).
  146. """
  147. try:
  148. if filename == u'-':
  149. if sys.platform == 'win32':
  150. import msvcrt
  151. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  152. return (sys.stdout, filename)
  153. stream = open(encodeFilename(filename), open_mode)
  154. return (stream, filename)
  155. except (IOError, OSError), err:
  156. # In case of error, try to remove win32 forbidden chars
  157. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  158. # An exception here should be caught in the caller
  159. stream = open(encodeFilename(filename), open_mode)
  160. return (stream, filename)
  161. def timeconvert(timestr):
  162. """Convert RFC 2822 defined time string into system timestamp"""
  163. timestamp = None
  164. timetuple = email.utils.parsedate_tz(timestr)
  165. if timetuple is not None:
  166. timestamp = email.utils.mktime_tz(timetuple)
  167. return timestamp
  168. def sanitize_filename(s, restricted=False):
  169. """Sanitizes a string so it could be used as part of a filename.
  170. If restricted is set, use a stricter subset of allowed characters.
  171. """
  172. def replace_insane(char):
  173. if char == '?' or ord(char) < 32 or ord(char) == 127:
  174. return ''
  175. elif char == '"':
  176. return '' if restricted else '\''
  177. elif char == ':':
  178. return '_-' if restricted else ' -'
  179. elif char in '\\/|*<>':
  180. return '-'
  181. if restricted and (char in '&\'' or char.isspace()):
  182. return '_'
  183. return char
  184. result = u''.join(map(replace_insane, s))
  185. while '--' in result:
  186. result = result.replace('--', '-')
  187. return result.strip('-')
  188. def orderedSet(iterable):
  189. """ Remove all duplicates from the input iterable """
  190. res = []
  191. for el in iterable:
  192. if el not in res:
  193. res.append(el)
  194. return res
  195. def unescapeHTML(s):
  196. """
  197. @param s a string (of type unicode)
  198. """
  199. assert type(s) == type(u'')
  200. result = re.sub(ur'(?u)&(.+?);', htmlentity_transform, s)
  201. return result
  202. def encodeFilename(s):
  203. """
  204. @param s The name of the file (of type unicode)
  205. """
  206. assert type(s) == type(u'')
  207. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  208. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  209. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  210. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  211. return s
  212. else:
  213. return s.encode(sys.getfilesystemencoding(), 'ignore')
  214. class DownloadError(Exception):
  215. """Download Error exception.
  216. This exception may be thrown by FileDownloader objects if they are not
  217. configured to continue on errors. They will contain the appropriate
  218. error message.
  219. """
  220. pass
  221. class SameFileError(Exception):
  222. """Same File exception.
  223. This exception will be thrown by FileDownloader objects if they detect
  224. multiple files would have to be downloaded to the same file on disk.
  225. """
  226. pass
  227. class PostProcessingError(Exception):
  228. """Post Processing exception.
  229. This exception may be raised by PostProcessor's .run() method to
  230. indicate an error in the postprocessing task.
  231. """
  232. pass
  233. class MaxDownloadsReached(Exception):
  234. """ --max-downloads limit has been reached. """
  235. pass
  236. class UnavailableVideoError(Exception):
  237. """Unavailable Format exception.
  238. This exception will be thrown when a video is requested
  239. in a format that is not available for that video.
  240. """
  241. pass
  242. class ContentTooShortError(Exception):
  243. """Content Too Short exception.
  244. This exception may be raised by FileDownloader objects when a file they
  245. download is too small for what the server announced first, indicating
  246. the connection was probably interrupted.
  247. """
  248. # Both in bytes
  249. downloaded = None
  250. expected = None
  251. def __init__(self, downloaded, expected):
  252. self.downloaded = downloaded
  253. self.expected = expected
  254. class Trouble(Exception):
  255. """Trouble helper exception
  256. This is an exception to be handled with
  257. FileDownloader.trouble
  258. """
  259. class YoutubeDLHandler(urllib2.HTTPHandler):
  260. """Handler for HTTP requests and responses.
  261. This class, when installed with an OpenerDirector, automatically adds
  262. the standard headers to every HTTP request and handles gzipped and
  263. deflated responses from web servers. If compression is to be avoided in
  264. a particular request, the original request in the program code only has
  265. to include the HTTP header "Youtubedl-No-Compression", which will be
  266. removed before making the real request.
  267. Part of this code was copied from:
  268. http://techknack.net/python-urllib2-handlers/
  269. Andrew Rowls, the author of that code, agreed to release it to the
  270. public domain.
  271. """
  272. @staticmethod
  273. def deflate(data):
  274. try:
  275. return zlib.decompress(data, -zlib.MAX_WBITS)
  276. except zlib.error:
  277. return zlib.decompress(data)
  278. @staticmethod
  279. def addinfourl_wrapper(stream, headers, url, code):
  280. if hasattr(urllib2.addinfourl, 'getcode'):
  281. return urllib2.addinfourl(stream, headers, url, code)
  282. ret = urllib2.addinfourl(stream, headers, url)
  283. ret.code = code
  284. return ret
  285. def http_request(self, req):
  286. for h in std_headers:
  287. if h in req.headers:
  288. del req.headers[h]
  289. req.add_header(h, std_headers[h])
  290. if 'Youtubedl-no-compression' in req.headers:
  291. if 'Accept-encoding' in req.headers:
  292. del req.headers['Accept-encoding']
  293. del req.headers['Youtubedl-no-compression']
  294. return req
  295. def http_response(self, req, resp):
  296. old_resp = resp
  297. # gzip
  298. if resp.headers.get('Content-encoding', '') == 'gzip':
  299. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  300. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  301. resp.msg = old_resp.msg
  302. # deflate
  303. if resp.headers.get('Content-encoding', '') == 'deflate':
  304. gz = StringIO.StringIO(self.deflate(resp.read()))
  305. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  306. resp.msg = old_resp.msg
  307. return resp