utils.py 11 KB

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