You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

358 lines
12 KiB

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import json
  4. import os
  5. import re
  6. import subprocess
  7. import tempfile
  8. from .common import InfoExtractor
  9. from ..compat import (
  10. compat_urlparse,
  11. compat_kwargs,
  12. )
  13. from ..utils import (
  14. check_executable,
  15. determine_ext,
  16. encodeArgument,
  17. ExtractorError,
  18. get_element_by_id,
  19. get_exe_version,
  20. is_outdated_version,
  21. std_headers,
  22. )
  23. def cookie_to_dict(cookie):
  24. cookie_dict = {
  25. 'name': cookie.name,
  26. 'value': cookie.value,
  27. }
  28. if cookie.port_specified:
  29. cookie_dict['port'] = cookie.port
  30. if cookie.domain_specified:
  31. cookie_dict['domain'] = cookie.domain
  32. if cookie.path_specified:
  33. cookie_dict['path'] = cookie.path
  34. if cookie.expires is not None:
  35. cookie_dict['expires'] = cookie.expires
  36. if cookie.secure is not None:
  37. cookie_dict['secure'] = cookie.secure
  38. if cookie.discard is not None:
  39. cookie_dict['discard'] = cookie.discard
  40. try:
  41. if (cookie.has_nonstandard_attr('httpOnly') or
  42. cookie.has_nonstandard_attr('httponly') or
  43. cookie.has_nonstandard_attr('HttpOnly')):
  44. cookie_dict['httponly'] = True
  45. except TypeError:
  46. pass
  47. return cookie_dict
  48. def cookie_jar_to_list(cookie_jar):
  49. return [cookie_to_dict(cookie) for cookie in cookie_jar]
  50. class PhantomJSwrapper(object):
  51. """PhantomJS wrapper class
  52. This class is experimental.
  53. """
  54. _TEMPLATE = r'''
  55. phantom.onError = function(msg, trace) {{
  56. var msgStack = ['PHANTOM ERROR: ' + msg];
  57. if(trace && trace.length) {{
  58. msgStack.push('TRACE:');
  59. trace.forEach(function(t) {{
  60. msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line
  61. + (t.function ? ' (in function ' + t.function +')' : ''));
  62. }});
  63. }}
  64. console.error(msgStack.join('\n'));
  65. phantom.exit(1);
  66. }};
  67. var page = require('webpage').create();
  68. var fs = require('fs');
  69. var read = {{ mode: 'r', charset: 'utf-8' }};
  70. var write = {{ mode: 'w', charset: 'utf-8' }};
  71. JSON.parse(fs.read("{cookies}", read)).forEach(function(x) {{
  72. phantom.addCookie(x);
  73. }});
  74. page.settings.resourceTimeout = {timeout};
  75. page.settings.userAgent = "{ua}";
  76. page.onLoadStarted = function() {{
  77. page.evaluate(function() {{
  78. delete window._phantom;
  79. delete window.callPhantom;
  80. }});
  81. }};
  82. var saveAndExit = function() {{
  83. fs.write("{html}", page.content, write);
  84. fs.write("{cookies}", JSON.stringify(phantom.cookies), write);
  85. phantom.exit();
  86. }};
  87. page.onLoadFinished = function(status) {{
  88. if(page.url === "") {{
  89. page.setContent(fs.read("{html}", read), "{url}");
  90. }}
  91. else {{
  92. {jscode}
  93. }}
  94. }};
  95. page.open("");
  96. '''
  97. _TMP_FILE_NAMES = ['script', 'html', 'cookies']
  98. @staticmethod
  99. def _version():
  100. return get_exe_version('phantomjs', version_re=r'([0-9.]+)')
  101. def __init__(self, extractor, required_version=None, timeout=10000):
  102. self._TMP_FILES = {}
  103. self.exe = check_executable('phantomjs', ['-v'])
  104. if not self.exe:
  105. raise ExtractorError('PhantomJS executable not found in PATH, '
  106. 'download it from http://phantomjs.org',
  107. expected=True)
  108. self.extractor = extractor
  109. if required_version:
  110. version = self._version()
  111. if is_outdated_version(version, required_version):
  112. self.extractor._downloader.report_warning(
  113. 'Your copy of PhantomJS is outdated, update it to version '
  114. '%s or newer if you encounter any errors.' % required_version)
  115. self.options = {
  116. 'timeout': timeout,
  117. }
  118. for name in self._TMP_FILE_NAMES:
  119. tmp = tempfile.NamedTemporaryFile(delete=False)
  120. tmp.close()
  121. self._TMP_FILES[name] = tmp
  122. def __del__(self):
  123. for name in self._TMP_FILE_NAMES:
  124. try:
  125. os.remove(self._TMP_FILES[name].name)
  126. except (IOError, OSError, KeyError):
  127. pass
  128. def _save_cookies(self, url):
  129. cookies = cookie_jar_to_list(self.extractor._downloader.cookiejar)
  130. for cookie in cookies:
  131. if 'path' not in cookie:
  132. cookie['path'] = '/'
  133. if 'domain' not in cookie:
  134. cookie['domain'] = compat_urlparse.urlparse(url).netloc
  135. with open(self._TMP_FILES['cookies'].name, 'wb') as f:
  136. f.write(json.dumps(cookies).encode('utf-8'))
  137. def _load_cookies(self):
  138. with open(self._TMP_FILES['cookies'].name, 'rb') as f:
  139. cookies = json.loads(f.read().decode('utf-8'))
  140. for cookie in cookies:
  141. if cookie['httponly'] is True:
  142. cookie['rest'] = {'httpOnly': None}
  143. if 'expiry' in cookie:
  144. cookie['expire_time'] = cookie['expiry']
  145. self.extractor._set_cookie(**compat_kwargs(cookie))
  146. def get(self, url, html=None, video_id=None, note=None, note2='Executing JS on webpage', headers={}, jscode='saveAndExit();'):
  147. """
  148. Downloads webpage (if needed) and executes JS
  149. Params:
  150. url: website url
  151. html: optional, html code of website
  152. video_id: video id
  153. note: optional, displayed when downloading webpage
  154. note2: optional, displayed when executing JS
  155. headers: custom http headers
  156. jscode: code to be executed when page is loaded
  157. Returns tuple with:
  158. * downloaded website (after JS execution)
  159. * anything you print with `console.log` (but not inside `page.execute`!)
  160. In most cases you don't need to add any `jscode`.
  161. It is executed in `page.onLoadFinished`.
  162. `saveAndExit();` is mandatory, use it instead of `phantom.exit()`
  163. It is possible to wait for some element on the webpage, for example:
  164. var check = function() {
  165. var elementFound = page.evaluate(function() {
  166. return document.querySelector('#b.done') !== null;
  167. });
  168. if(elementFound)
  169. saveAndExit();
  170. else
  171. window.setTimeout(check, 500);
  172. }
  173. page.evaluate(function(){
  174. document.querySelector('#a').click();
  175. });
  176. check();
  177. """
  178. if 'saveAndExit();' not in jscode:
  179. raise ExtractorError('`saveAndExit();` not found in `jscode`')
  180. if not html:
  181. html = self.extractor._download_webpage(url, video_id, note=note, headers=headers)
  182. with open(self._TMP_FILES['html'].name, 'wb') as f:
  183. f.write(html.encode('utf-8'))
  184. self._save_cookies(url)
  185. replaces = self.options
  186. replaces['url'] = url
  187. user_agent = headers.get('User-Agent') or std_headers['User-Agent']
  188. replaces['ua'] = user_agent.replace('"', '\\"')
  189. replaces['jscode'] = jscode
  190. for x in self._TMP_FILE_NAMES:
  191. replaces[x] = self._TMP_FILES[x].name.replace('\\', '\\\\').replace('"', '\\"')
  192. with open(self._TMP_FILES['script'].name, 'wb') as f:
  193. f.write(self._TEMPLATE.format(**replaces).encode('utf-8'))
  194. if video_id is None:
  195. self.extractor.to_screen('%s' % (note2,))
  196. else:
  197. self.extractor.to_screen('%s: %s' % (video_id, note2))
  198. p = subprocess.Popen([
  199. self.exe, '--ssl-protocol=any',
  200. self._TMP_FILES['script'].name
  201. ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  202. out, err = p.communicate()
  203. if p.returncode != 0:
  204. raise ExtractorError(
  205. 'Executing JS failed\n:' + encodeArgument(err))
  206. with open(self._TMP_FILES['html'].name, 'rb') as f:
  207. html = f.read().decode('utf-8')
  208. self._load_cookies()
  209. return (html, encodeArgument(out))
  210. class OpenloadIE(InfoExtractor):
  211. _VALID_URL = r'https?://(?:www\.)?(?:openload\.(?:co|io|link)|oload\.(?:tv|stream))/(?:f|embed)/(?P<id>[a-zA-Z0-9-_]+)'
  212. _TESTS = [{
  213. 'url': 'https://openload.co/f/kUEfGclsU9o',
  214. 'md5': 'bf1c059b004ebc7a256f89408e65c36e',
  215. 'info_dict': {
  216. 'id': 'kUEfGclsU9o',
  217. 'ext': 'mp4',
  218. 'title': 'skyrim_no-audio_1080.mp4',
  219. 'thumbnail': r're:^https?://.*\.jpg$',
  220. },
  221. }, {
  222. 'url': 'https://openload.co/embed/rjC09fkPLYs',
  223. 'info_dict': {
  224. 'id': 'rjC09fkPLYs',
  225. 'ext': 'mp4',
  226. 'title': 'movie.mp4',
  227. 'thumbnail': r're:^https?://.*\.jpg$',
  228. 'subtitles': {
  229. 'en': [{
  230. 'ext': 'vtt',
  231. }],
  232. },
  233. },
  234. 'params': {
  235. 'skip_download': True, # test subtitles only
  236. },
  237. }, {
  238. 'url': 'https://openload.co/embed/kUEfGclsU9o/skyrim_no-audio_1080.mp4',
  239. 'only_matching': True,
  240. }, {
  241. 'url': 'https://openload.io/f/ZAn6oz-VZGE/',
  242. 'only_matching': True,
  243. }, {
  244. 'url': 'https://openload.co/f/_-ztPaZtMhM/',
  245. 'only_matching': True,
  246. }, {
  247. # unavailable via https://openload.co/f/Sxz5sADo82g/, different layout
  248. # for title and ext
  249. 'url': 'https://openload.co/embed/Sxz5sADo82g/',
  250. 'only_matching': True,
  251. }, {
  252. # unavailable via https://openload.co/embed/e-Ixz9ZR5L0/ but available
  253. # via https://openload.co/f/e-Ixz9ZR5L0/
  254. 'url': 'https://openload.co/f/e-Ixz9ZR5L0/',
  255. 'only_matching': True,
  256. }, {
  257. 'url': 'https://oload.tv/embed/KnG-kKZdcfY/',
  258. 'only_matching': True,
  259. }, {
  260. 'url': 'http://www.openload.link/f/KnG-kKZdcfY',
  261. 'only_matching': True,
  262. }, {
  263. 'url': 'https://oload.stream/f/KnG-kKZdcfY',
  264. 'only_matching': True,
  265. }]
  266. _USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
  267. @staticmethod
  268. def _extract_urls(webpage):
  269. return re.findall(
  270. r'<iframe[^>]+src=["\']((?:https?://)?(?:openload\.(?:co|io)|oload\.tv)/embed/[a-zA-Z0-9-_]+)',
  271. webpage)
  272. def _real_extract(self, url):
  273. video_id = self._match_id(url)
  274. url_pattern = 'https://openload.co/%%s/%s/' % video_id
  275. headers = {
  276. 'User-Agent': self._USER_AGENT,
  277. }
  278. for path in ('embed', 'f'):
  279. page_url = url_pattern % path
  280. last = path == 'f'
  281. webpage = self._download_webpage(
  282. page_url, video_id, 'Downloading %s webpage' % path,
  283. headers=headers, fatal=last)
  284. if not webpage:
  285. continue
  286. if 'File not found' in webpage or 'deleted by the owner' in webpage:
  287. if not last:
  288. continue
  289. raise ExtractorError('File not found', expected=True, video_id=video_id)
  290. break
  291. phantom = PhantomJSwrapper(self, required_version='2.0')
  292. webpage, _ = phantom.get(page_url, html=webpage, video_id=video_id, headers=headers)
  293. decoded_id = get_element_by_id('streamurl', webpage)
  294. video_url = 'https://openload.co/stream/%s?mime=true' % decoded_id
  295. title = self._og_search_title(webpage, default=None) or self._search_regex(
  296. r'<span[^>]+class=["\']title["\'][^>]*>([^<]+)', webpage,
  297. 'title', default=None) or self._html_search_meta(
  298. 'description', webpage, 'title', fatal=True)
  299. entries = self._parse_html5_media_entries(page_url, webpage, video_id)
  300. entry = entries[0] if entries else {}
  301. subtitles = entry.get('subtitles')
  302. info_dict = {
  303. 'id': video_id,
  304. 'title': title,
  305. 'thumbnail': entry.get('thumbnail') or self._og_search_thumbnail(webpage, default=None),
  306. 'url': video_url,
  307. # Seems all videos have extensions in their titles
  308. 'ext': determine_ext(title, 'mp4'),
  309. 'subtitles': subtitles,
  310. 'http_headers': headers,
  311. }
  312. return info_dict