logo

youtube-dl

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

openload.py (8232B)


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