utils.py 11 KB

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