utils.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. try:
  14. import cStringIO as StringIO
  15. except ImportError:
  16. import StringIO
  17. try:
  18. import json
  19. except ImportError: # Python <2.6, use trivialjson (https://github.com/phihag/trivialjson):
  20. import trivialjson as json
  21. std_headers = {
  22. 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:5.0.1) Gecko/20100101 Firefox/5.0.1',
  23. 'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  24. 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  25. 'Accept-Encoding': 'gzip, deflate',
  26. 'Accept-Language': 'en-us,en;q=0.5',
  27. }
  28. def preferredencoding():
  29. """Get preferred encoding.
  30. Returns the best encoding scheme for the system, based on
  31. locale.getpreferredencoding() and some further tweaks.
  32. """
  33. def yield_preferredencoding():
  34. try:
  35. pref = locale.getpreferredencoding()
  36. u'TEST'.encode(pref)
  37. except:
  38. pref = 'UTF-8'
  39. while True:
  40. yield pref
  41. return yield_preferredencoding().next()
  42. def htmlentity_transform(matchobj):
  43. """Transforms an HTML entity to a Unicode character.
  44. This function receives a match object and is intended to be used with
  45. the re.sub() function.
  46. """
  47. entity = matchobj.group(1)
  48. # Known non-numeric HTML entity
  49. if entity in htmlentitydefs.name2codepoint:
  50. return unichr(htmlentitydefs.name2codepoint[entity])
  51. # Unicode character
  52. mobj = re.match(ur'(?u)#(x?\d+)', entity)
  53. if mobj is not None:
  54. numstr = mobj.group(1)
  55. if numstr.startswith(u'x'):
  56. base = 16
  57. numstr = u'0%s' % numstr
  58. else:
  59. base = 10
  60. return unichr(long(numstr, base))
  61. # Unknown entity in name, return its literal representation
  62. return (u'&%s;' % entity)
  63. 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
  64. class IDParser(HTMLParser.HTMLParser):
  65. """Modified HTMLParser that isolates a tag with the specified id"""
  66. def __init__(self, id):
  67. self.id = id
  68. self.result = None
  69. self.started = False
  70. self.depth = {}
  71. self.html = None
  72. self.watch_startpos = False
  73. self.error_count = 0
  74. HTMLParser.HTMLParser.__init__(self)
  75. def error(self, message):
  76. print self.getpos()
  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_title(utitle):
  140. """Sanitizes a video title so it could be used as part of a filename."""
  141. utitle = unescapeHTML(utitle)
  142. return utitle.replace(unicode(os.sep), u'%')
  143. def sanitize_open(filename, open_mode):
  144. """Try to open the given filename, and slightly tweak it if this fails.
  145. Attempts to open the given filename. If this fails, it tries to change
  146. the filename slightly, step by step, until it's either able to open it
  147. or it fails and raises a final exception, like the standard open()
  148. function.
  149. It returns the tuple (stream, definitive_file_name).
  150. """
  151. try:
  152. if filename == u'-':
  153. if sys.platform == 'win32':
  154. import msvcrt
  155. msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
  156. return (sys.stdout, filename)
  157. stream = open(encodeFilename(filename), open_mode)
  158. return (stream, filename)
  159. except (IOError, OSError), err:
  160. # In case of error, try to remove win32 forbidden chars
  161. filename = re.sub(ur'[/<>:"\|\?\*]', u'#', filename)
  162. # An exception here should be caught in the caller
  163. stream = open(encodeFilename(filename), open_mode)
  164. return (stream, filename)
  165. def timeconvert(timestr):
  166. """Convert RFC 2822 defined time string into system timestamp"""
  167. timestamp = None
  168. timetuple = email.utils.parsedate_tz(timestr)
  169. if timetuple is not None:
  170. timestamp = email.utils.mktime_tz(timetuple)
  171. return timestamp
  172. def simplify_title(title):
  173. expr = re.compile(ur'[^\w\d_\-]+', flags=re.UNICODE)
  174. return expr.sub(u'_', title).strip(u'_')
  175. def orderedSet(iterable):
  176. """ Remove all duplicates from the input iterable """
  177. res = []
  178. for el in iterable:
  179. if el not in res:
  180. res.append(el)
  181. return res
  182. def unescapeHTML(s):
  183. """
  184. @param s a string (of type unicode)
  185. """
  186. assert type(s) == type(u'')
  187. result = re.sub(ur'(?u)&(.+?);', htmlentity_transform, s)
  188. return result
  189. def encodeFilename(s):
  190. """
  191. @param s The name of the file (of type unicode)
  192. """
  193. assert type(s) == type(u'')
  194. if sys.platform == 'win32' and sys.getwindowsversion().major >= 5:
  195. # Pass u'' directly to use Unicode APIs on Windows 2000 and up
  196. # (Detecting Windows NT 4 is tricky because 'major >= 4' would
  197. # match Windows 9x series as well. Besides, NT 4 is obsolete.)
  198. return s
  199. else:
  200. return s.encode(sys.getfilesystemencoding(), 'ignore')
  201. class DownloadError(Exception):
  202. """Download Error exception.
  203. This exception may be thrown by FileDownloader objects if they are not
  204. configured to continue on errors. They will contain the appropriate
  205. error message.
  206. """
  207. pass
  208. class SameFileError(Exception):
  209. """Same File exception.
  210. This exception will be thrown by FileDownloader objects if they detect
  211. multiple files would have to be downloaded to the same file on disk.
  212. """
  213. pass
  214. class PostProcessingError(Exception):
  215. """Post Processing exception.
  216. This exception may be raised by PostProcessor's .run() method to
  217. indicate an error in the postprocessing task.
  218. """
  219. pass
  220. class MaxDownloadsReached(Exception):
  221. """ --max-downloads limit has been reached. """
  222. pass
  223. class UnavailableVideoError(Exception):
  224. """Unavailable Format exception.
  225. This exception will be thrown when a video is requested
  226. in a format that is not available for that video.
  227. """
  228. pass
  229. class ContentTooShortError(Exception):
  230. """Content Too Short exception.
  231. This exception may be raised by FileDownloader objects when a file they
  232. download is too small for what the server announced first, indicating
  233. the connection was probably interrupted.
  234. """
  235. # Both in bytes
  236. downloaded = None
  237. expected = None
  238. def __init__(self, downloaded, expected):
  239. self.downloaded = downloaded
  240. self.expected = expected
  241. class YoutubeDLHandler(urllib2.HTTPHandler):
  242. """Handler for HTTP requests and responses.
  243. This class, when installed with an OpenerDirector, automatically adds
  244. the standard headers to every HTTP request and handles gzipped and
  245. deflated responses from web servers. If compression is to be avoided in
  246. a particular request, the original request in the program code only has
  247. to include the HTTP header "Youtubedl-No-Compression", which will be
  248. removed before making the real request.
  249. Part of this code was copied from:
  250. http://techknack.net/python-urllib2-handlers/
  251. Andrew Rowls, the author of that code, agreed to release it to the
  252. public domain.
  253. """
  254. @staticmethod
  255. def deflate(data):
  256. try:
  257. return zlib.decompress(data, -zlib.MAX_WBITS)
  258. except zlib.error:
  259. return zlib.decompress(data)
  260. @staticmethod
  261. def addinfourl_wrapper(stream, headers, url, code):
  262. if hasattr(urllib2.addinfourl, 'getcode'):
  263. return urllib2.addinfourl(stream, headers, url, code)
  264. ret = urllib2.addinfourl(stream, headers, url)
  265. ret.code = code
  266. return ret
  267. def http_request(self, req):
  268. for h in std_headers:
  269. if h in req.headers:
  270. del req.headers[h]
  271. req.add_header(h, std_headers[h])
  272. if 'Youtubedl-no-compression' in req.headers:
  273. if 'Accept-encoding' in req.headers:
  274. del req.headers['Accept-encoding']
  275. del req.headers['Youtubedl-no-compression']
  276. return req
  277. def http_response(self, req, resp):
  278. old_resp = resp
  279. # gzip
  280. if resp.headers.get('Content-encoding', '') == 'gzip':
  281. gz = gzip.GzipFile(fileobj=StringIO.StringIO(resp.read()), mode='r')
  282. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  283. resp.msg = old_resp.msg
  284. # deflate
  285. if resp.headers.get('Content-encoding', '') == 'deflate':
  286. gz = StringIO.StringIO(self.deflate(resp.read()))
  287. resp = self.addinfourl_wrapper(gz, old_resp.headers, old_resp.url, old_resp.code)
  288. resp.msg = old_resp.msg
  289. return resp