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.

420 lines
14 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. _DOMAINS = r'(?:openload\.(?:co|io|link|pw)|oload\.(?:tv|stream|site|xyz|win|download|cloud|cc|icu|fun|club|info|pw|live|space))'
  212. _VALID_URL = r'''(?x)
  213. https?://
  214. (?P<host>
  215. (?:www\.)?
  216. %s
  217. )/
  218. (?:f|embed)/
  219. (?P<id>[a-zA-Z0-9-_]+)
  220. ''' % _DOMAINS
  221. _TESTS = [{
  222. 'url': 'https://openload.co/f/kUEfGclsU9o',
  223. 'md5': 'bf1c059b004ebc7a256f89408e65c36e',
  224. 'info_dict': {
  225. 'id': 'kUEfGclsU9o',
  226. 'ext': 'mp4',
  227. 'title': 'skyrim_no-audio_1080.mp4',
  228. 'thumbnail': r're:^https?://.*\.jpg$',
  229. },
  230. }, {
  231. 'url': 'https://openload.co/embed/rjC09fkPLYs',
  232. 'info_dict': {
  233. 'id': 'rjC09fkPLYs',
  234. 'ext': 'mp4',
  235. 'title': 'movie.mp4',
  236. 'thumbnail': r're:^https?://.*\.jpg$',
  237. 'subtitles': {
  238. 'en': [{
  239. 'ext': 'vtt',
  240. }],
  241. },
  242. },
  243. 'params': {
  244. 'skip_download': True, # test subtitles only
  245. },
  246. }, {
  247. 'url': 'https://openload.co/embed/kUEfGclsU9o/skyrim_no-audio_1080.mp4',
  248. 'only_matching': True,
  249. }, {
  250. 'url': 'https://openload.io/f/ZAn6oz-VZGE/',
  251. 'only_matching': True,
  252. }, {
  253. 'url': 'https://openload.co/f/_-ztPaZtMhM/',
  254. 'only_matching': True,
  255. }, {
  256. # unavailable via https://openload.co/f/Sxz5sADo82g/, different layout
  257. # for title and ext
  258. 'url': 'https://openload.co/embed/Sxz5sADo82g/',
  259. 'only_matching': True,
  260. }, {
  261. # unavailable via https://openload.co/embed/e-Ixz9ZR5L0/ but available
  262. # via https://openload.co/f/e-Ixz9ZR5L0/
  263. 'url': 'https://openload.co/f/e-Ixz9ZR5L0/',
  264. 'only_matching': True,
  265. }, {
  266. 'url': 'https://oload.tv/embed/KnG-kKZdcfY/',
  267. 'only_matching': True,
  268. }, {
  269. 'url': 'http://www.openload.link/f/KnG-kKZdcfY',
  270. 'only_matching': True,
  271. }, {
  272. 'url': 'https://oload.stream/f/KnG-kKZdcfY',
  273. 'only_matching': True,
  274. }, {
  275. 'url': 'https://oload.xyz/f/WwRBpzW8Wtk',
  276. 'only_matching': True,
  277. }, {
  278. 'url': 'https://oload.win/f/kUEfGclsU9o',
  279. 'only_matching': True,
  280. }, {
  281. 'url': 'https://oload.download/f/kUEfGclsU9o',
  282. 'only_matching': True,
  283. }, {
  284. 'url': 'https://oload.cloud/f/4ZDnBXRWiB8',
  285. 'only_matching': True,
  286. }, {
  287. # Its title has not got its extension but url has it
  288. 'url': 'https://oload.download/f/N4Otkw39VCw/Tomb.Raider.2018.HDRip.XviD.AC3-EVO.avi.mp4',
  289. 'only_matching': True,
  290. }, {
  291. 'url': 'https://oload.cc/embed/5NEAbI2BDSk',
  292. 'only_matching': True,
  293. }, {
  294. 'url': 'https://oload.icu/f/-_i4y_F_Hs8',
  295. 'only_matching': True,
  296. }, {
  297. 'url': 'https://oload.fun/f/gb6G1H4sHXY',
  298. 'only_matching': True,
  299. }, {
  300. 'url': 'https://oload.club/f/Nr1L-aZ2dbQ',
  301. 'only_matching': True,
  302. }, {
  303. 'url': 'https://oload.info/f/5NEAbI2BDSk',
  304. 'only_matching': True,
  305. }, {
  306. 'url': 'https://openload.pw/f/WyKgK8s94N0',
  307. 'only_matching': True,
  308. }, {
  309. 'url': 'https://oload.pw/f/WyKgK8s94N0',
  310. 'only_matching': True,
  311. }, {
  312. 'url': 'https://oload.live/f/-Z58UZ-GR4M',
  313. 'only_matching': True,
  314. }, {
  315. 'url': 'https://oload.space/f/IY4eZSst3u8/',
  316. 'only_matching': True,
  317. }]
  318. _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'
  319. @staticmethod
  320. def _extract_urls(webpage):
  321. return re.findall(
  322. r'<iframe[^>]+src=["\']((?:https?://)?%s/embed/[a-zA-Z0-9-_]+)'
  323. % OpenloadIE._DOMAINS, webpage)
  324. def _real_extract(self, url):
  325. mobj = re.match(self._VALID_URL, url)
  326. host = mobj.group('host')
  327. video_id = mobj.group('id')
  328. url_pattern = 'https://%s/%%s/%s/' % (host, video_id)
  329. headers = {
  330. 'User-Agent': self._USER_AGENT,
  331. }
  332. for path in ('embed', 'f'):
  333. page_url = url_pattern % path
  334. last = path == 'f'
  335. webpage = self._download_webpage(
  336. page_url, video_id, 'Downloading %s webpage' % path,
  337. headers=headers, fatal=last)
  338. if not webpage:
  339. continue
  340. if 'File not found' in webpage or 'deleted by the owner' in webpage:
  341. if not last:
  342. continue
  343. raise ExtractorError('File not found', expected=True, video_id=video_id)
  344. break
  345. phantom = PhantomJSwrapper(self, required_version='2.0')
  346. webpage, _ = phantom.get(page_url, html=webpage, video_id=video_id, headers=headers)
  347. decoded_id = (get_element_by_id('streamurl', webpage) or
  348. get_element_by_id('streamuri', webpage) or
  349. get_element_by_id('streamurj', webpage) or
  350. self._search_regex(
  351. (r'>\s*([\w-]+~\d{10,}~\d+\.\d+\.0\.0~[\w-]+)\s*<',
  352. r'>\s*([\w~-]+~\d+\.\d+\.\d+\.\d+~[\w~-]+)',
  353. r'>\s*([\w-]+~\d{10,}~(?:[a-f\d]+:){2}:~[\w-]+)\s*<',
  354. r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)\s*<',
  355. r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)'), webpage,
  356. 'stream URL'))
  357. video_url = 'https://%s/stream/%s?mime=true' % (host, decoded_id)
  358. title = self._og_search_title(webpage, default=None) or self._search_regex(
  359. r'<span[^>]+class=["\']title["\'][^>]*>([^<]+)', webpage,
  360. 'title', default=None) or self._html_search_meta(
  361. 'description', webpage, 'title', fatal=True)
  362. entries = self._parse_html5_media_entries(page_url, webpage, video_id)
  363. entry = entries[0] if entries else {}
  364. subtitles = entry.get('subtitles')
  365. return {
  366. 'id': video_id,
  367. 'title': title,
  368. 'thumbnail': entry.get('thumbnail') or self._og_search_thumbnail(webpage, default=None),
  369. 'url': video_url,
  370. 'ext': determine_ext(title, None) or determine_ext(url, 'mp4'),
  371. 'subtitles': subtitles,
  372. 'http_headers': headers,
  373. }