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.

380 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. if restricted and ord(char) > 127:
  184. return '_'
  185. return char
  186. result = u''.join(map(replace_insane, s))
  187. while '__' in result:
  188. result = result.replace('__', '_')
  189. result = result.strip('_')
  190. # Common case of "Foreign band name - English song title"
  191. if restricted and result.startswith('-_'):
  192. result = result[2:]
  193. if not result:
  194. result = '_'
  195. return result
  196. def orderedSet(iterable):
  197. """ Remove all duplicates from the input iterable """
  198. res = []
  199. for el in iterable:
  200. if el not in res:
  201. res.append(el)
  202. return res
  203. def unescapeHTML(s):
  204. """
  205. @param s a string (of type unicode)
  206. """
  207. assert type(s) == type(u'')
  208. result = re.sub(ur'(?u)&(.+?);', htmlentity_transform, s)
  209. return result
  210. def encodeFilename(s):
  211. """
  212. @param s The name of the file (of type unicode)
  213. """
  214. assert type(s) == type(u'')
  215. if sys.platform == 'win32' and sys.getwindowsversion()[0] >= 5:
  216. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  217. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  218. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  219. return s
  220. else:
  221. return s.encode(sys.getfilesystemencoding(), 'ignore')
  222. class DownloadError(Exception):
  223. """Download Error exception.
  224. This exception may be thrown by FileDownloader objects if they are not
  225. configured to continue on errors. They will contain the appropriate
  226. error message.
  227. """
  228. pass
  229. class SameFileError(Exception):
  230. """Same File exception.
  231. This exception will be thrown by FileDownloader objects if they detect
  232. multiple files would have to be downloaded to the same file on disk.
  233. """
  234. pass
  235. class PostProcessingError(Exception):
  236. """Post Processing exception.
  237. This exception may be raised by PostProcessor's .run() method to
  238. indicate an error in the postprocessing task.
  239. """
  240. pass
  241. class MaxDownloadsReached(Exception):
  242. """ --max-downloads limit has been reached. """
  243. pass
  244. class UnavailableVideoError(Exception):
  245. """Unavailable Format exception.
  246. This exception will be thrown when a video is requested
  247. in a format that is not available for that video.
  248. """
  249. pass
  250. class ContentTooShortError(Exception):
  251. """Content Too Short exception.
  252. This exception may be raised by FileDownloader objects when a file they
  253. download is too small for what the server announced first, indicating
  254. the connection was probably interrupted.
  255. """
  256. # Both in bytes
  257. downloaded = None
  258. expected = None
  259. def __init__(self, downloaded, expected):
  260. self.downloaded = downloaded
  261. self.expected = expected
  262. class Trouble(Exception):
  263. """Trouble helper exception
  264. This is an exception to be handled with
  265. FileDownloader.trouble
  266. """
  267. class YoutubeDLHandler(urllib2.HTTPHandler):
  268. """Handler for HTTP requests and responses.
  269. This class, when installed with an OpenerDirector, automatically adds
  270. the standard headers to every HTTP request and handles gzipped and
  271. deflated responses from web servers. If compression is to be avoided in
  272. a particular request, the original request in the program code only has
  273. to include the HTTP header "Youtubedl-No-Compression", which will be
  274. removed before making the real request.
  275. Part of this code was copied from:
  276. http://techknack.net/python-urllib2-handlers/
  277. Andrew Rowls, the author of that code, agreed to release it to the
  278. public domain.
  279. """
  280. @staticmethod
  281. def deflate(data):
  282. try:
  283. return zlib.decompress(data, -zlib.MAX_WBITS)
  284. except zlib.error:
  285. return zlib.decompress(data)
  286. @staticmethod
  287. def addinfourl_wrapper(stream, headers, url, code):
  288. if hasattr(urllib2.addinfourl, 'getcode'):
  289. return urllib2.addinfourl(stream, headers, url, code)
  290. ret = urllib2.addinfourl(stream, headers, url)
  291. ret.code = code
  292. return ret
  293. def http_request(self, req):
  294. for h in std_headers:
  295. if h in req.headers:
  296. del req.headers[h]
  297. req.add_header(h, std_headers[h])
  298. if 'Youtubedl-no-compression' in req.headers:
  299. if 'Accept-encoding' in req.headers:
  300. del req.headers['Accept-encoding']
  301. del req.headers['Youtubedl-no-compression']
  302. return req
  303. def http_response(self, req, resp):
  304. old_resp = resp
  305. # gzip
  306. if resp.headers.get('Content-encoding', '') == 'gzip':
  307. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  308. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  309. resp.msg = old_resp.msg
  310. # deflate
  311. if resp.headers.get('Content-encoding', '') == 'deflate':
  312. gz = StringIO.StringIO(self.deflate(resp.read()))
  313. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  314. resp.msg = old_resp.msg
  315. return resp