openload.py 17 KB

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