logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

openload.py (8257B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import os
  5. import subprocess
  6. import tempfile
  7. from ..compat import (
  8. compat_open as open,
  9. compat_urlparse,
  10. compat_kwargs,
  11. )
  12. from ..utils import (
  13. check_executable,
  14. encodeArgument,
  15. ExtractorError,
  16. get_exe_version,
  17. is_outdated_version,
  18. process_communicate_or_kill,
  19. std_headers,
  20. )
  21. def cookie_to_dict(cookie):
  22. cookie_dict = {
  23. 'name': cookie.name,
  24. 'value': cookie.value,
  25. }
  26. if cookie.port_specified:
  27. cookie_dict['port'] = cookie.port
  28. if cookie.domain_specified:
  29. cookie_dict['domain'] = cookie.domain
  30. if cookie.path_specified:
  31. cookie_dict['path'] = cookie.path
  32. if cookie.expires is not None:
  33. cookie_dict['expires'] = cookie.expires
  34. if cookie.secure is not None:
  35. cookie_dict['secure'] = cookie.secure
  36. if cookie.discard is not None:
  37. cookie_dict['discard'] = cookie.discard
  38. try:
  39. if (cookie.has_nonstandard_attr('httpOnly')
  40. or cookie.has_nonstandard_attr('httponly')
  41. or cookie.has_nonstandard_attr('HttpOnly')):
  42. cookie_dict['httponly'] = True
  43. except TypeError:
  44. pass
  45. return cookie_dict
  46. def cookie_jar_to_list(cookie_jar):
  47. return [cookie_to_dict(cookie) for cookie in cookie_jar]
  48. class PhantomJSwrapper(object):
  49. """PhantomJS wrapper class
  50. This class is experimental.
  51. """
  52. _TEMPLATE = r'''
  53. phantom.onError = function(msg, trace) {{
  54. var msgStack = ['PHANTOM ERROR: ' + msg];
  55. if(trace && trace.length) {{
  56. msgStack.push('TRACE:');
  57. trace.forEach(function(t) {{
  58. msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
  59. + (t.function ? ' (in function ' + t.function +')' : ''));
  60. }});
  61. }}
  62. console.error(msgStack.join('\n'));
  63. phantom.exit(1);
  64. }};
  65. var page = require('webpage').create();
  66. var fs = require('fs');
  67. var read = {{ mode: 'r', charset: 'utf-8' }};
  68. var write = {{ mode: 'w', charset: 'utf-8' }};
  69. JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
  70. phantom.addCookie(x);
  71. }});
  72. page.settings.resourceTimeout = {timeout};
  73. page.settings.userAgent = "{ua}";
  74. page.onLoadStarted = function() {{
  75. page.evaluate(function() {{
  76. delete window._phantom;
  77. delete window.callPhantom;
  78. }});
  79. }};
  80. var saveAndExit = function() {{
  81. fs.write("{html}", page.content, write);
  82. fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
  83. phantom.exit();
  84. }};
  85. page.onLoadFinished = function(status) {{
  86. if(page.url === "") {{
  87. page.setContent(fs.read("{html}", read), "{url}");
  88. }}
  89. else {{
  90. {jscode}
  91. }}
  92. }};
  93. page.open("");
  94. '''
  95. _TMP_FILE_NAMES = ['script', 'html', 'cookies']
  96. @staticmethod
  97. def _version():
  98. return get_exe_version('phantomjs', version_re=r'([0-9.]+)')
  99. def __init__(self, extractor, required_version=None, timeout=10000):
  100. self._TMP_FILES = {}
  101. self.exe = check_executable('phantomjs', ['-v'])
  102. if not self.exe:
  103. raise ExtractorError('PhantomJS executable not found in PATH, '
  104. 'download it from http://phantomjs.org',
  105. expected=True)
  106. self.extractor = extractor
  107. if required_version:
  108. version = self._version()
  109. if is_outdated_version(version, required_version):
  110. self.extractor._downloader.report_warning(
  111. 'Your copy of PhantomJS is outdated, update it to version '
  112. '%s or newer if you encounter any errors.' % required_version)
  113. self.options = {
  114. 'timeout': timeout,
  115. }
  116. for name in self._TMP_FILE_NAMES:
  117. tmp = tempfile.NamedTemporaryFile(delete=False)
  118. tmp.close()
  119. self._TMP_FILES[name] = tmp
  120. def __del__(self):
  121. for name in self._TMP_FILE_NAMES:
  122. try:
  123. os.remove(self._TMP_FILES[name].name)
  124. except (IOError, OSError, KeyError):
  125. pass
  126. def _save_cookies(self, url):
  127. cookies = cookie_jar_to_list(self.extractor._downloader.cookiejar)
  128. for cookie in cookies:
  129. if 'path' not in cookie:
  130. cookie['path'] = '/'
  131. if 'domain' not in cookie:
  132. cookie['domain'] = compat_urlparse.urlparse(url).netloc
  133. with open(self._TMP_FILES['cookies'].name, 'wb') as f:
  134. f.write(json.dumps(cookies).encode('utf-8'))
  135. def _load_cookies(self):
  136. with open(self._TMP_FILES['cookies'].name, 'rb') as f:
  137. cookies = json.loads(f.read().decode('utf-8'))
  138. for cookie in cookies:
  139. if cookie['httponly'] is True:
  140. cookie['rest'] = {'httpOnly': None}
  141. if 'expiry' in cookie:
  142. cookie['expire_time'] = cookie['expiry']
  143. self.extractor._set_cookie(**compat_kwargs(cookie))
  144. def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
  145. """
  146. Downloads webpage (if needed) and executes JS
  147. Params:
  148. url: website url
  149. html: optional, html code of website
  150. video_id: video id
  151. note: optional, displayed when downloading webpage
  152. note2: optional, displayed when executing JS
  153. headers: custom http headers
  154. jscode: code to be executed when page is loaded
  155. Returns tuple with:
  156. * downloaded website (after JS execution)
  157. * anything you print with `console.log` (but not inside `page.execute`!)
  158. In most cases you don't need to add any `jscode`.
  159. It is executed in `page.onLoadFinished`.
  160. `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
  161. It is possible to wait for some element on the webpage, for example:
  162. var check = function() {
  163. var elementFound = page.evaluate(function() {
  164. return document.querySelector('#b.done') !== null;
  165. });
  166. if(elementFound)
  167. saveAndExit();
  168. else
  169. window.setTimeout(check, 500);
  170. }
  171. page.evaluate(function(){
  172. document.querySelector('#a').click();
  173. });
  174. check();
  175. """
  176. if 'saveAndExit();' not in jscode:
  177. raise ExtractorError('`saveAndExit();` not found in `jscode`')
  178. if not html:
  179. html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
  180. with open(self._TMP_FILES['html'].name, 'wb') as f:
  181. f.write(html.encode('utf-8'))
  182. self._save_cookies(url)
  183. replaces = self.options
  184. replaces['url'] = url
  185. user_agent = headers.get('User-Agent') or std_headers['User-Agent']
  186. replaces['ua'] = user_agent.replace('"', '\\"')
  187. replaces['jscode'] = jscode
  188. for x in self._TMP_FILE_NAMES:
  189. replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
  190. with open(self._TMP_FILES['script'].name, 'wb') as f:
  191. f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
  192. if video_id is None:
  193. self.extractor.to_screen('%s' % (note2,))
  194. else:
  195. self.extractor.to_screen('%s: %s' % (video_id, note2))
  196. p = subprocess.Popen([
  197. self.exe, '--ssl-protocol=any',
  198. self._TMP_FILES['script'].name
  199. ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  200. out, err = process_communicate_or_kill(p)
  201. if p.returncode != 0:
  202. raise ExtractorError(
  203. 'Executing JS failed\n:' + encodeArgument(err))
  204. with open(self._TMP_FILES['html'].name, 'rb') as f:
  205. html = f.read().decode('utf-8')
  206. self._load_cookies()
  207. return (html, encodeArgument(out))