openload.py 8.4 KB

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