openload.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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')
  42. or cookie.has_nonstandard_attr('httponly')
  43. or 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|biz|stream|site|xyz|win|download|cloud|cc|icu|fun|club|info|press|pw|life|live|space|services|website)|oladblock\.(?:services|xyz|me)|openloed\.co)'
  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. _EMBED_WORD = 'embed'
  222. _STREAM_WORD = 'f'
  223. _REDIR_WORD = 'stream'
  224. _URL_IDS = ('streamurl', 'streamuri', 'streamurj')
  225. _TESTS = [{
  226. 'url': 'https://openload.co/f/kUEfGclsU9o',
  227. 'md5': 'bf1c059b004ebc7a256f89408e65c36e',
  228. 'info_dict': {
  229. 'id': 'kUEfGclsU9o',
  230. 'ext': 'mp4',
  231. 'title': 'skyrim_no-audio_1080.mp4',
  232. 'thumbnail': r're:^https?://.*\.jpg$',
  233. },
  234. }, {
  235. 'url': 'https://openload.co/embed/rjC09fkPLYs',
  236. 'info_dict': {
  237. 'id': 'rjC09fkPLYs',
  238. 'ext': 'mp4',
  239. 'title': 'movie.mp4',
  240. 'thumbnail': r're:^https?://.*\.jpg$',
  241. 'subtitles': {
  242. 'en': [{
  243. 'ext': 'vtt',
  244. }],
  245. },
  246. },
  247. 'params': {
  248. 'skip_download': True, # test subtitles only
  249. },
  250. }, {
  251. 'url': 'https://openload.co/embed/kUEfGclsU9o/skyrim_no-audio_1080.mp4',
  252. 'only_matching': True,
  253. }, {
  254. 'url': 'https://openload.io/f/ZAn6oz-VZGE/',
  255. 'only_matching': True,
  256. }, {
  257. 'url': 'https://openload.co/f/_-ztPaZtMhM/',
  258. 'only_matching': True,
  259. }, {
  260. # unavailable via https://openload.co/f/Sxz5sADo82g/, different layout
  261. # for title and ext
  262. 'url': 'https://openload.co/embed/Sxz5sADo82g/',
  263. 'only_matching': True,
  264. }, {
  265. # unavailable via https://openload.co/embed/e-Ixz9ZR5L0/ but available
  266. # via https://openload.co/f/e-Ixz9ZR5L0/
  267. 'url': 'https://openload.co/f/e-Ixz9ZR5L0/',
  268. 'only_matching': True,
  269. }, {
  270. 'url': 'https://oload.tv/embed/KnG-kKZdcfY/',
  271. 'only_matching': True,
  272. }, {
  273. 'url': 'http://www.openload.link/f/KnG-kKZdcfY',
  274. 'only_matching': True,
  275. }, {
  276. 'url': 'https://oload.stream/f/KnG-kKZdcfY',
  277. 'only_matching': True,
  278. }, {
  279. 'url': 'https://oload.xyz/f/WwRBpzW8Wtk',
  280. 'only_matching': True,
  281. }, {
  282. 'url': 'https://oload.win/f/kUEfGclsU9o',
  283. 'only_matching': True,
  284. }, {
  285. 'url': 'https://oload.download/f/kUEfGclsU9o',
  286. 'only_matching': True,
  287. }, {
  288. 'url': 'https://oload.cloud/f/4ZDnBXRWiB8',
  289. 'only_matching': True,
  290. }, {
  291. # Its title has not got its extension but url has it
  292. 'url': 'https://oload.download/f/N4Otkw39VCw/Tomb.Raider.2018.HDRip.XviD.AC3-EVO.avi.mp4',
  293. 'only_matching': True,
  294. }, {
  295. 'url': 'https://oload.cc/embed/5NEAbI2BDSk',
  296. 'only_matching': True,
  297. }, {
  298. 'url': 'https://oload.icu/f/-_i4y_F_Hs8',
  299. 'only_matching': True,
  300. }, {
  301. 'url': 'https://oload.fun/f/gb6G1H4sHXY',
  302. 'only_matching': True,
  303. }, {
  304. 'url': 'https://oload.club/f/Nr1L-aZ2dbQ',
  305. 'only_matching': True,
  306. }, {
  307. 'url': 'https://oload.info/f/5NEAbI2BDSk',
  308. 'only_matching': True,
  309. }, {
  310. 'url': 'https://openload.pw/f/WyKgK8s94N0',
  311. 'only_matching': True,
  312. }, {
  313. 'url': 'https://oload.pw/f/WyKgK8s94N0',
  314. 'only_matching': True,
  315. }, {
  316. 'url': 'https://oload.live/f/-Z58UZ-GR4M',
  317. 'only_matching': True,
  318. }, {
  319. 'url': 'https://oload.space/f/IY4eZSst3u8/',
  320. 'only_matching': True,
  321. }, {
  322. 'url': 'https://oload.services/embed/bs1NWj1dCag/',
  323. 'only_matching': True,
  324. }, {
  325. 'url': 'https://oload.press/embed/drTBl1aOTvk/',
  326. 'only_matching': True,
  327. }, {
  328. 'url': 'https://oload.website/embed/drTBl1aOTvk/',
  329. 'only_matching': True,
  330. }, {
  331. 'url': 'https://oload.life/embed/oOzZjNPw9Dc/',
  332. 'only_matching': True,
  333. }, {
  334. 'url': 'https://oload.biz/f/bEk3Gp8ARr4/',
  335. 'only_matching': True,
  336. }, {
  337. 'url': 'https://oladblock.services/f/b8NWEgkqNLI/',
  338. 'only_matching': True,
  339. }, {
  340. 'url': 'https://oladblock.xyz/f/b8NWEgkqNLI/',
  341. 'only_matching': True,
  342. }, {
  343. 'url': 'https://oladblock.me/f/b8NWEgkqNLI/',
  344. 'only_matching': True,
  345. }, {
  346. 'url': 'https://openloed.co/f/b8NWEgkqNLI/',
  347. 'only_matching': True,
  348. }]
  349. @classmethod
  350. def _extract_urls(cls, webpage):
  351. return re.findall(
  352. r'<iframe[^>]+src=["\']((?:https?://)?%s/%s/[a-zA-Z0-9-_]+)'
  353. % (cls._DOMAINS, cls._EMBED_WORD), webpage)
  354. def _extract_decrypted_page(self, page_url, webpage, video_id):
  355. phantom = PhantomJSwrapper(self, required_version='2.0')
  356. webpage, _ = phantom.get(page_url, html=webpage, video_id=video_id)
  357. return webpage
  358. def _real_extract(self, url):
  359. mobj = re.match(self._VALID_URL, url)
  360. host = mobj.group('host')
  361. video_id = mobj.group('id')
  362. url_pattern = 'https://%s/%%s/%s/' % (host, video_id)
  363. for path in (self._EMBED_WORD, self._STREAM_WORD):
  364. page_url = url_pattern % path
  365. last = path == self._STREAM_WORD
  366. webpage = self._download_webpage(
  367. page_url, video_id, 'Downloading %s webpage' % path,
  368. fatal=last)
  369. if not webpage:
  370. continue
  371. if 'File not found' in webpage or 'deleted by the owner' in webpage:
  372. if not last:
  373. continue
  374. raise ExtractorError('File not found', expected=True, video_id=video_id)
  375. break
  376. webpage = self._extract_decrypted_page(page_url, webpage, video_id)
  377. for element_id in self._URL_IDS:
  378. decoded_id = get_element_by_id(element_id, webpage)
  379. if decoded_id:
  380. break
  381. if not decoded_id:
  382. decoded_id = self._search_regex(
  383. (r'>\s*([\w-]+~\d{10,}~\d+\.\d+\.0\.0~[\w-]+)\s*<',
  384. r'>\s*([\w~-]+~\d+\.\d+\.\d+\.\d+~[\w~-]+)',
  385. r'>\s*([\w-]+~\d{10,}~(?:[a-f\d]+:){2}:~[\w-]+)\s*<',
  386. r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)\s*<',
  387. r'>\s*([\w~-]+~[a-f0-9:]+~[\w~-]+)'), webpage,
  388. 'stream URL')
  389. video_url = 'https://%s/%s/%s?mime=true' % (host, self._REDIR_WORD, decoded_id)
  390. title = self._og_search_title(webpage, default=None) or self._search_regex(
  391. r'<span[^>]+class=["\']title["\'][^>]*>([^<]+)', webpage,
  392. 'title', default=None) or self._html_search_meta(
  393. 'description', webpage, 'title', fatal=True)
  394. entries = self._parse_html5_media_entries(page_url, webpage, video_id)
  395. entry = entries[0] if entries else {}
  396. subtitles = entry.get('subtitles')
  397. return {
  398. 'id': video_id,
  399. 'title': title,
  400. 'thumbnail': entry.get('thumbnail') or self._og_search_thumbnail(webpage, default=None),
  401. 'url': video_url,
  402. 'ext': determine_ext(title, None) or determine_ext(url, 'mp4'),
  403. 'subtitles': subtitles,
  404. }
  405. class VerystreamIE(OpenloadIE):
  406. IE_NAME = 'verystream'
  407. _DOMAINS = r'(?:verystream\.com)'
  408. _VALID_URL = r'''(?x)
  409. https?://
  410. (?P<host>
  411. (?:www\.)?
  412. %s
  413. )/
  414. (?:stream|e)/
  415. (?P<id>[a-zA-Z0-9-_]+)
  416. ''' % _DOMAINS
  417. _EMBED_WORD = 'e'
  418. _STREAM_WORD = 'stream'
  419. _REDIR_WORD = 'gettoken'
  420. _URL_IDS = ('videolink', )
  421. _TESTS = [{
  422. 'url': 'https://verystream.com/stream/c1GWQ9ngBBx/',
  423. 'md5': 'd3e8c5628ccb9970b65fd65269886795',
  424. 'info_dict': {
  425. 'id': 'c1GWQ9ngBBx',
  426. 'ext': 'mp4',
  427. 'title': 'Big Buck Bunny.mp4',
  428. 'thumbnail': r're:^https?://.*\.jpg$',
  429. },
  430. }, {
  431. 'url': 'https://verystream.com/e/c1GWQ9ngBBx/',
  432. 'only_matching': True,
  433. }]
  434. def _extract_decrypted_page(self, page_url, webpage, video_id):
  435. return webpage # for Verystream, the webpage is already decrypted