def get_now_showing_json(self): # Get list of available films args = "?client=android&country=%s&token=%s&udid=%s&client_version=3.05" % (self._country, self._token, self._udid) r = requests.get(self._mubi_urls['films'] + args) if r.status_code != 200: xbmc.log("Invalid status code %s getting list of films", 4) return r.text
def category(catname, url): if url is None: url = caturl.format(catname) url = urllib.unquote_plus(url).replace(' ', '+') itemslist = parseVideosUrl(url) xbmc.log("Parsed Vids list {0} {1}".format(len(itemslist), repr(itemslist))) litems = makeVideoItems(itemslist) xbmc.log("List Items {0} {1}".format(len(litems), repr(litems))) return litems
def set_reel(self, film_id, reel_id): # this calls tells the api that the user wants to select a reel other than the default reel (i.e. # they want to see another dub) payload = {'reel_id': reel_id} r = self._session.put((self._mubi_urls['set_reel'] % str(film_id)), data=payload) result = (''.join(r.text)).encode('utf-8') xbmc.log("Set reel response: %s" % result, 2) return r.status_code == 200
def get_film_id_by_web_url(self, mubi_url): r = requests.get(mubi_url) result = (''.join(r.text)).encode('utf-8') import re m = re.search('"film_id":([0-9]+)', result) film_id = m.group(1) xbmc.log("Got film id: %s" % film_id, 3) return film_id
def play(url): if url.find('linkOut') != -1: urlout = url.split('?id=')[-1] url = base64.b64decode(urlout) plugin.notify(msg=urlout, title=url) resolved = '' stream_url = '' item = None try: import urlresolver resolved = urlresolver.HostedMediaFile(url).resolve() if not resolved or resolved == False or len(resolved) < 1: resolved = urlresolver.resolve(url) if resolved is None or len(resolved) < 1: resolved = urlresolver.resolve(urllib.unquote(url)) if len(resolved) > 1: plugin.notify(msg="PLAY {0}".format(resolved.partition('.')[-1]), title="URLRESOLVER", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) plugin.play_video(item) return None except: resolved = '' plugin.notify(msg="FAILED {0}".format(url.partition('.')[-1]), title="URLRESOLVER", delay=1000) try: import YDStreamExtractor info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True) resolved = info.streamURL() for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8', 'ignore') xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format(stream_url)) except: pass if len(stream_url) > 1: resolved = stream_url if len(resolved) > 1: plugin.notify(msg="Playing: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) plugin.play_video(item) return None except: plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) if len(resolved) > 1: plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) plugin.play_video(item) return None else: plugin.set_resolved_url(url) plugin.play_video(url) return None
def set_watching(self, film_id): # this call tells the api that the user wants to watch a certain movie and returns the default reel id payload = {'last_time_code': 0} r = self._session.put((self._mubi_urls['set_watching'] % str(film_id)), data=payload) result = (''.join(r.text)).encode('utf-8') if r.status_code == 200: return json.loads(result)['reel_id'] else: xbmc.log("Failed to obtain the reel id with result: %s" % result, 4) return -1
def get_film_page(self, film_id): cached = self._simplecache.get(self._cache_id % film_id) if cached: return json.loads(cached) args = "?client=android&country=%s&token=%s&udid=%s&client_version=3.05" % (self._country, self._token, self._udid) r = requests.get((self._mubi_urls['film'] % str(film_id)) + args) if r.status_code != 200: xbmc.log("Invalid status code %s getting film info for %s" % (r.status_code, film_id), 4) self._simplecache.set(self._cache_id % film_id, r.text, expiration=datetime.timedelta(days=32)) return json.loads(r.text)
def app_startup(self): payload = {'udid': self._udid, 'token': self._token, 'client': 'android', 'client_version': '3.05'} r = requests.post(self._mubi_urls['startup'] + "?client=android", data=payload) if r.status_code == 200: self._country = json.loads(r.text)['country'] xbmc.log("Successfully got country as %s" % self._country, 2) else: xbmc.log("Failed to get country: %s" % r.text, 4) return
def play(url): resolved = '' stream_url = '' item = None try: import urlresolver resolved = urlresolver.HostedMediaFile(url).resolve() if not resolved or resolved == False or len(resolved) < 1: resolved = urlresolver.resolve(url) if resolved is None or len(resolved) < 1: resolved = urlresolver.resolve(urllib.unquote(url)) if len(resolved) > 1: plugin.notify(msg="PLAY {0}".format(resolved.partition('.')[-1]), title="URLRESOLVER", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) return item except: resolved = '' plugin.notify(msg="FAILED {0}".format(url.partition('.')[-1]), title="URLRESOLVER", delay=1000) try: import YDStreamExtractor info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True) resolved = info.streamURL() for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8', 'ignore') xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format(stream_url)) except: pass if len(stream_url) > 1: resolved = stream_url if len(resolved) > 1: plugin.notify(msg="Playing: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) return item except: plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) if len(resolved) > 1: plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) return item else: plugin.set_resolved_url(url) # url) # plugurl = 'plugin://plugin.video.live.streamspro/?url={0}'.format(urllib.quote_plus(url)) # item = ListItem.from_dict(path=plugurl) # item.add_stream_info('video', stream_values={}) # item.set_is_playable(True) # plugin.notify(msg="RESOLVE FAIL: {0}".format(url.split('.', 1)[-1]),title="Trying {0}".format(item.path.split('.', 1)[-1]), delay=2000) return None
def get_default_reel_id_is_drm(self, film_id): reel_id = [(f['default_reel']['id'], f['default_reel']['drm']) for f in json.loads(self.get_now_showing_json()) if str(f['id']) == str(film_id)] if len(reel_id) == 1: return reel_id[0] elif reel_id: xbmc.log("Multiple default_reel's returned for film %s: %s" % (film_id, ', '.join(reel_id)), 3) return reel_id[0] else: xbmc.log("Could not find default reel id for film %s" % film_id, 4) return None
def findahost(linklist=[], prefhost=""): for fitem in linklist: lb, vu = fitem xbmc.log("Lookin for host: {0} in {1}".format(prefhost, vu)) vu = vu.lower() if vu.find(prefhost) != -1: return ( lb, vu, ) return None
def play(url): if plugin.get_setting('debugon', converter=bool): web_pdb.set_trace() resolved = '' stream_url = '' item = None try: import urlresolver resolved = urlresolver.HostedMediaFile(url).resolve() if not resolved or resolved == False or len(resolved) < 1: resolved = urlresolver.resolve(url) if resolved is None or len(resolved) < 1: resolved = urlresolver.resolve(WebUtils.unescape(url)) if len(resolved) > 1: plugin.notify(msg="PLAY {0}".format(resolved.partition('.')[-1]), title="URLRESOLVER", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) return item except: resolved = '' plugin.notify(msg="FAILED {0}".format(url.partition('.')[-1]), title="URLRESOLVER", delay=1000) try: import YDStreamExtractor info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True) resolved = info.streamURL() for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8', 'ignore') xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format(stream_url)) except: pass if len(stream_url) > 1: resolved = stream_url if len(resolved) > 1: plugin.notify(msg="Playing: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) return item except: plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) if len(resolved) > 1: plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) return item else: plugin.set_resolved_url(url) # url) return None
def play(url): if url.find('linkOut') != -1: urlout = url.split('?id=')[-1] url = base64.b64decode(urlout) resolved = '' stream_url = '' item = None try: if urlresolver is not None: stream_url = urlresolver.resolve(url) if len(stream_url) > 1: resolved = stream_url except: plugin.notify(msg="{0}".format(url), title="URLResolver FAILED", delay=1000) if len(resolved) < 1: plugin.notify(msg="{0}".format(url), title="Trying YouTube-DL", delay=1000) try: import YDStreamExtractor info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True) stream_url = info.streamURL() if len(stream_url) < 1 or stream_url.find('http') == -1: for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8', 'ignore') xbmc.log(msg="**YOUTUBE-DL Stream found: {0}".format( stream_url)) except: pass if len(stream_url) > 1: resolved = stream_url else: resolved = stream_url except: plugin.notify(msg="{0}".format(url), title="YOUTUBE-DL Failed", delay=1000) if len(resolved) < 1: plugin.notify(msg="{0}".format(url), title="FAILED TO RESOLVE", delay=1000) return None else: vidurl = resolved.encode('utf-8', 'ignore') item = ListItem.from_dict(path=vidurl) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) plugin.set_resolved_url(item) return plugin.play_video(item)
def get_film_page(self, film_id): cached = self._simplecache.get(self._cache_id % film_id) if cached: return json.loads(cached) args = "?country=%s" % self._country r = self._session.get((self._mubi_urls['film'] % str(film_id)) + args) if r.status_code != 200: xbmc.log("Invalid status code %s getting film info for %s" % (r.status_code, film_id), 4) self._simplecache.set(self._cache_id % film_id, r.text, expiration=datetime.timedelta(days=32)) return json.loads(r.text)
def play_film(identifier): mubi_resolved_info = mubi.get_play_url(identifier) mubi_film = ListItem(path=mubi_resolved_info['url']) if mubi_resolved_info['is_mpd']: mubi_film.set_property('inputstreamaddon', 'inputstream.adaptive') mubi_film.set_property('inputstream.adaptive.manifest_type', 'mpd') if mubi_resolved_info['is_drm']: xbmc.log("Playing DRM films is not currently supported", 4) return None # drm = mubi_resolved_info['drm_item'] # mubi_film.set_property('inputstream.adaptive.license_key', drm['lurl']+'|'+drm['header']+ # '|B{SSM}|'+drm['license_field']) # mubi_film.set_property('inputstream.adaptive.license_type', "com.widevine.alpha") return plugin.set_resolved_url(mubi_film)
def play_film(identifier): mubi_resolved_info = mubi.get_play_url(identifier) mubi_film = xbmcgui.ListItem(path=mubi_resolved_info['url']) if mubi_resolved_info['is_mpd']: mubi_film.setProperty('inputstreamaddon', 'inputstream.adaptive') mubi_film.setProperty('inputstream.adaptive.manifest_type', 'mpd') if mubi_resolved_info['drm_header'] is not None: xbmc.log('DRM Header: %s' %mubi_resolved_info['drm_header'], 2) mubi_film.setProperty('inputstream.adaptive.license_type', "com.widevine.alpha") mubi_film.setProperty('inputstream.adaptive.license_key', LICENSE_URL + '|' + LICENSE_URL_HEADERS + '&dt-custom-data=' + mubi_resolved_info['drm_header'] + '|R{SSM}|JBlicense') mubi_film.setMimeType('application/dash+xml') mubi_film.setContentLookup(False) return xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=mubi_film)
def app_startup(self): payload = { 'udid': self._udid, 'token': self._token, 'client': 'android', 'client_version': APP_VERSION_CODE } r = self._session.post(self._mubi_urls['startup'] + "?client=android", data=payload) result = (''.join(r.text)).encode('utf-8') if r.status_code == 200: self._country = json.loads(result)['country'] xbmc.log("Successfully got country as %s" % self._country, 2) else: xbmc.log("Failed to get country: %s" % result, 4) return
def get_film_metadata(self, film_overview): film_id = film_overview['id'] available_at = dateutil.parser.parse(film_overview['available_at']) expires_at = dateutil.parser.parse(film_overview['expires_at']) # Check film is valid, has not expired and is not preview now = datetime.datetime.now(available_at.tzinfo) if available_at > now: xbmc.log("Film %s is not yet available" % film_id, 2) return None elif expires_at < now: xbmc.log("Film %s has expired" % film_id, 2) return None hd = film_overview['hd'] drm = film_overview['reels'][0]['drm'] audio_lang = film_overview['reels'][0]['audio_language'] subtitle_lang = film_overview['reels'][0]['subtitle_language'] # Build plot field. Place lang info in here since there is nowhere else for it to go drm_string = "" #"Protected by DRM\n" if drm else "" lang_string = ("Language: %s" % audio_lang) + ( (", Subtitles: %s\n" % subtitle_lang) if subtitle_lang else "\n") plot_string = "Synopsis: %s\n\nOur take: %s" % ( film_overview['excerpt'], film_overview['editorial']) # Get detailed look at film to get cast info film_page = self.get_film_page(film_id) cast = [(m['name'], m['credits']) for m in film_page['cast']] # Build film metadata object metadata = Metadata( title=film_overview['title'], director=film_overview['directors'], year=film_overview['year'], duration=film_overview['duration'] * 60, # This is in seconds country=film_overview['country'], plot=drm_string + lang_string + plot_string, overlay=6 if hd else 0, genre=', '.join(film_overview['genres']), originaltitle=film_overview['original_title'], # Out of 5, kodi uses 10 rating=film_overview['average_rating'] * 2 if film_overview['average_rating'] is not None else None, votes=film_overview['number_of_ratings'], castandrole=cast, trailer=film_overview['trailer_url']) listview_title = film_overview['title'] + (" [HD]" if hd else "") return Film(listview_title, film_id, film_overview['stills']['standard'], metadata)
def get_film_id_by_web_url(self, mubi_url): import re r = self._session.get( mubi_url, headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.123 Safari/537.36' } ) result = (''.join(r.text)).encode('utf-8') m = re.search('"film_id":([0-9]+)', result) film_id = m.group(1) reels = [] # try: # m = re.search('data-available-reels=\'([^\']+)\'', result) # reels = json.loads(html.unescape(m.group(1))) # except: pass xbmc.log("Got film id: %s" % film_id, 3) return {"film_id": film_id, "reels": reels}
def get_play_url(self, film_id): (reel_id, is_drm) = self.get_default_reel_id_is_drm(film_id) args = "?client=android&country=%s&token=%s&udid=%s&client_version=3.05&film_id=%s&reel_id=%s&download=false" \ % (self._country, self._token, self._udid, film_id, reel_id) r = requests.get((self._mubi_urls['viewing'] % str(film_id)) + args) if r.status_code != 200: xbmc.log("Could not get secure URL for film %s" % film_id, 4) url = json.loads(r.text)["url"] # For DRM you will have to find the following info: # {"userId": long(result['username']), "sessionId": result['transaction'], "merchant": result['accountCode']} # This might need optdata in header however looking in requests during browser negotiation I don't see it # https://stackoverflow.com/questions/35792897/http-request-header-field-optdata # The best conversation for this is: # https://github.com/emilsvennesson/kodi-viaplay/issues/9 # You can pick this conversation up using Android Packet Capture item_result = {'url': url, 'is_mpd': "mpd" in url, 'is_drm': is_drm} xbmc.log("Got video info as: '%s'" % json.dumps(item_result), 2) return item_result
def play(title, video, url): resolved = None mediaurl = None vidhtml = urllib2.urlopen(url).read() vidurl = '' try: matches = re.compile('(http://[^"<]+?.mp4[^"<]+?)"', re.I + re.M + re.S + re.U).findall(vidhtml)[0] if matches is not None: vidurl = matches xbmc.log("MATCH MP4 = {0}".format(vidurl)) vli = ListItem(label=title, label2=url, icon=video, thumbnail=video, path=vidurl) vli.playable = True #plugin.set_resolved_url(plugin.url_for(play, title=title, video=video, url=url)) #xbmc.Player().play(vidurl) #plugin.play_video(vli) #return plugin.play_video(vli) #return xbmc.Player().play(vidurl) except: pass try: if vidurl == '': matches2 = re.compile('(http://[^"<]+?.flv[^"<]+?)"', re.I + re.M + re.S + re.U).findall(vidhtml)[0] if matches2 is not None: vidurl = matches2 xbmc.log("MATCH MP4 = {0}".format(vidurl)) vli = ListItem(label=title, label2=url, icon=video, thumbnail=video, path=vidurl) vli.playable = True #plugin.set_resolved_url(plugin.url_for(play, title=title, video=video, url=url)) #xbmc.Player().play(vidurl) #plugin.set_resolved_url(vli) #plugin.play_video(vli) #plugin.set_resolved_url(plugin.url_for(play, title=title, video=video, url=url)) #return plugin.play_video(vli) except: pass #plugin.set_resolved_url(plugin.url_for(play, title=title, video=video, url=url)) try: if vli is not None: plugin.set_resolved_url(vli) return plugin.play_video(vli) except: pass
def filter(self, record): """Returns True for all records if running in the CLI, else returns True. When running inside Kodi it calls the xbmc.log() method and prevents the message from being double printed to STDOUT. """ # When running in Kodi, any logged statements will be double printed # since we are calling xbmc.log() explicitly. Therefore we return False # so every log message is filtered out and not printed again. if CLI_MODE: return True else: # Must not be imported until here because of import order issues # when running in CLI from kodiswift import xbmc xbmc_level = XBMCFilter.xbmc_levels.get( XBMCFilter.python_to_xbmc.get(record.levelname)) xbmc.log('%s%s' % (self.prefix, record.getMessage()), xbmc_level) return False
def play(title, video, url): """ Play attempts to scrape the video's page and find the actual video file to play. This is still buggy but seems to work on a lot of the sites but not all the time so any help on this function working better would be appreciated. I pass in the title of the movie and the video tags the Thumbnail which I use to create a proper ListItem with the scrapped MP4 url :param title: Video Title to play passed to XBMC in a new ListItem object with resolved URL of video scraped from url :param video: Thumbnail URL of the video used as the icon and thumbnail for ListItem to play :param url: URL of the embed/video page to scrape for the real playable video file :return: ListItem of video with path = scraped url of the MP4/Video file hopefully """ resolved = None mediaurl = None vidhtml = urllib2.urlopen(url).read() vidurl = '' vli = None try: matches = re.compile('(http://[^"<]+?.mp4[^"<]+?)"', re.I + re.M + re.S + re.U).findall(vidhtml)[0] if matches is not None: vidurl = matches xbmc.log("MATCH MP4 = {0}".format(vidurl)) vli = ListItem(label=title, label2=url, icon=video, thumbnail=video, path=vidurl) vli.playable = True else: matches = re.compile('(http://[^"<]+?.flv[^"<]+?)"', re.I + re.M + re.S + re.U).findall(vidhtml)[0] if matches is not None: vidurl = matches xbmc.log("MATCH FLV = {0}".format(vidurl)) vli = ListItem(label=title, label2=url, icon=video, thumbnail=video, path=vidurl) vli.playable = True except: pass try: if vli is not None: plugin.set_resolved_url(vli) plugin.play_video(vli) # return plugin.play_video(vli) except: pass
def get_play_url(self, film_id): (reel_id, is_drm) = self.get_default_reel_id_is_drm(film_id) # set reel payload = {'reel_id': reel_id, 'sidecar_subtitle_language_id': 20} r = requests.put((self._mubi_urls['set_reel'] % str(film_id)), data=payload, headers=self._headers) result = (''.join(r.text)).encode('utf-8') xbmc.log("Set reel response: %s" % result, 2) # get film url args = "?country=%s&download=false" % (self._country) r = requests.get( (self._mubi_urls['get_url'] % (str(film_id), str(reel_id))) + args, headers=self._headers) result = (''.join(r.text)).encode('utf-8') if r.status_code != 200: xbmc.log( "Could not get secure URL for film %s with reel_id=%s" % (film_id, reel_id), 4) xbmc.log("Response was: %s" % result, 2) url = json.loads(result)["url"] # For DRM you will have to find the following info: # {"userId": long(result['username']), "sessionId": result['transaction'], "merchant": result['accountCode']} # This might need optdata in header however looking in requests during browser negotiation I don't see it # https://stackoverflow.com/questions/35792897/http-request-header-field-optdata # The best conversation for this is: # https://github.com/emilsvennesson/kodi-viaplay/issues/9 # You can pick this conversation up using Android Packet Capture item_result = { 'url': url, 'is_mpd': "mpd" in url, 'is_drm': is_drm, 'drm_header': base64.b64encode('{"userId":' + str(self._userid) + ',"sessionId":"' + self._token + '","merchant":"mubi"}') } xbmc.log("Got video info as: '%s'" % json.dumps(item_result), 2) return item_result
def get_play_url(self, film_id): # reels probably refer to different streams of the same movie (usually when the movie is available in two dub versions) # it is necessary to tell the API that one wants to watch a film before requesting the movie URL from the API, otherwise # the URL will not be delivered. # this can be done by either calling # [1] api/v1/{film_id}/viewing/set_reel, or # [2] api/v1/{film_id}/viewing/watching # the old behavior of the addon was calling [1], as the reel id could be known from loading the film list. # however, with the new feature of playing a movie by entering the MUBI web url, the reel id is not always known (i.e. # if the film is taken from the library, rather than from the "now showing" section). # by calling [2], the default reel id for a film (which is usually the original dub version of the movie) is returned. # <old> # (reel_id, is_drm) = self.get_default_reel_id_is_drm(film_id) # set the current reel before playing the movie (if the reel was never set, the movie URL will not be delivered) # payload = {'reel_id': reel_id, 'sidecar_subtitle_language_id': 20} # r = requests.put((self._mubi_urls['set_reel'] % str(film_id)), data=payload, headers=self._headers) # result = (''.join(r.text)).encode('utf-8') # xbmc.log("Set reel response: %s" % result, 2) # </old> # new: get the default reel id by calling api/v1/{film_id}/viewing/watching reel_id = self.set_watching(film_id) is_drm = True # let's just assume, that is_drm is always true # get the movie URL args = "?country=%s&download=false" % (self._country) r = requests.get( (self._mubi_urls['get_url'] % (str(film_id), str(reel_id))) + args, headers=self._headers) result = (''.join(r.text)).encode('utf-8') if r.status_code != 200: xbmc.log( "Could not get secure URL for film %s with reel_id=%s" % (film_id, reel_id), 4) xbmc.log("Response was: %s" % result, 2) url = json.loads(result)["url"] # return the video info item_result = { 'url': url, 'is_mpd': "mpd" in url, 'drm_header': base64.b64encode('{"userId":' + str(self._userid) + ',"sessionId":"' + self._token + '","merchant":"mubi"}') if is_drm else None } xbmc.log("Got video info as: '%s'" % json.dumps(item_result), 2) return item_result
def login(self): payload = {'udid': self._udid, 'token': '', 'client': 'android', 'client_version': '3.05', 'email': self._username, 'password': self._password} xbmc.log("Logging in with username: %s and udid: %s" % (self._username, self._udid), 2) r = requests.post(self._mubi_urls["login"] + "?client=android", data=payload) if r.status_code == 200: self._token = json.loads(r.text)['token'] xbmc.log("Login Successful and got token %s" % self._token, 2) else: xbmc.log("Login Failed", 4) self.app_startup() return r.status_code
def login(self): payload = { 'email': self._username, 'password': self._password } xbmc.log("Logging in with username: %s and udid: %s" % (self._username, self._udid), 2) r = self._session.post(self._mubi_urls["login"], data=payload) result = (''.join(r.text)).encode('utf-8') if r.status_code == 200: self._token = json.loads(result)['token'] self._userid = json.loads(result)['user']['id'] self._session.headers.update({'authorization': "Bearer %s" % self._token}) xbmc.log("Login Successful with token=%s and userid=%s" % (self._token, self._userid), 2) xbmc.log("Headers=%s" % self._session.headers, 2) else: xbmc.log("Login Failed with result: %s" % result, 4) # self.app_startup() return r.status_code
def site(sitename, section, url): """ Main working function for the addon and handles Site specific calls to Search a site, Next Page, and Index. Index and Search sections call back into this section for Next Page support A shortcut helper SITEROOT simply calls this function for each site but looks up the correct URL to pass to section=Index :param sitename: Name of site to perform section actions on :param section: Index, Search, Next :param url: API URL for the section :return: Listitems for results plus a Search Site Item and Next Page Item """ # siteapiurls = getAPIURLS() # siteurl = siteapiurls.get(sitename) litems = [] itemslist = [] DOSTR8 = plugin.get_setting(key='dostr8') __imgnext__ = __imgsearch__.replace('search.png', 'next.png') siteurl = getAPIURLS(sitename=sitename) if siteurl.find('search=gay&') != -1: surl = siteurl.replace('search=gay&', 'search={0}+gay&') else: surl = siteurl.replace('search=', 'search={0}') itemsearch = {'label': 'Search {0}'.format(sitename.title()), 'path': plugin.url_for(site, sitename=sitename, section='search', url=surl), 'icon': __imgsearch__, 'thumb': __imgsearch__} itemsearch.setdefault(itemsearch.keys()[0]) pagenum = 2 if url.find('page=') != -1: pagestr = str(url.split('page=', 1)[1]).split('&', 1)[0] if pagestr is not None: pagenum = int(pagestr) + 1 else: pagenum = 2 pagenumcur = pagenum - 1 if url.find('page=1') != -1: nurl = url.replace('page=1&', 'page=2&') elif url.find('page=') != -1: nurl = url.replace('page={0}&'.format(pagenumcur), 'page={0}&'.format(pagenum)) else: nurl = url + '&page={0}'.format(pagenum) itemnext = {'label': 'Next --> {0}'.format(pagenum), 'path': plugin.url_for(site, sitename=sitename, section='next', url=nurl), 'icon': __imgnext__, 'thumb': __imgnext__} itemnext.setdefault(itemnext.keys()[0]) if section.lower() == "index": # Index was called so get the first page of a specific site and return items with a Search and Next added vitems = list() itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems: litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) itemslist.append(itemnext) litems = itemslist elif section.lower() == "next": # Provides support for viewing Next set of results/page and accessed from the itemnext ListItem added to Index/Search vitems = list() itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems: litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) itemslist.append(itemnext) litems = itemslist elif section.lower() == "category": if sitename.lower() == 'spankwire': txt = file(path.join(__addondir__, 'spankwire.json')).read() allitems = json.loads(txt) itemlist = allitems.get(allitems.keys()[0]) allitems = sorted(itemlist, key=lambda itemlist: itemlist['label']) for li in allitems: assert isinstance(li, dict) # catpath = plugin.url_for(category, catname=li.get('label'), url=li.get('path')) catpath = plugin.url_for(site, sitename='spankwire', section='index', url=li.get('path')) li.update(path=catpath) li.setdefault(li.keys()[0]) litems.append(li) elif sitename.lower() == 'gaytube': litems = catlist_gaytube() elif sitename.lower() == 'tube8': if not (DOSTR8 == True or DOSTR8 == 'true'): litems = catlist_tube8(isGay=True) else: litems = catlist_tube8(isGay=False) elif section.lower() == "search": # Perform a search of the specific site and return results and a next page item - NOT a global multisite search searchtxt = '' try: searchtxt = plugin.get_setting('lastsearch') except: searchtxt = '' searchtxt = plugin.keyboard(searchtxt, 'Search {0}'.format(sitename.title()), False) searchquery = searchtxt.replace(' ', '+') plugin.set_setting(key='lastsearch', val=searchtxt) surl = surl.format(searchquery) itemslist = parseVideosUrl(surl) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems: litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) nurl = surl.replace('page=1&', 'page=2&') itemnext = {'label': 'Next {0} --> {1}'.format(searchtxt, pagenum), 'path': plugin.url_for(site, sitename=sitename, section='next', url=nurl), 'icon': __imgnext__, 'thumb': __imgnext__} itemnext.setdefault(itemnext.keys()[0]) itemslist.append(itemnext) litems = itemslist else: itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) litems.append(itemnext) return litems
def makeVideoItems(itemlist): """ Takes a list of dict's returned from the API and looks for the specific fields to build XBMC ListItem for each item :param itemlist: :return: List of dict(Label, Label2, Icon, Thumb, Path) items created for each dict returned from the API """ litems = [] vitem = dict() vid = dict() item = dict() getsrc = itemgetter('src') try: for vitem in itemlist: assert isinstance(vitem, dict) if vitem.has_key('video'): vid = vitem.get('video') else: vid = vitem if vid is not None: assert isinstance(vid, dict) thumb = '' length = '' vidid = '' vurl = '' vtitle = '' pubdate = '' if vid.has_key('url'): vurl = vid.get('url') elif vid.has_key('embed'): vurl = vid.get('embed') if vid.has_key('default_thumb'): thumb = vid.get('default_thumb') elif vid.has_key('thumbnail'): thumb = vid.get('thumbnail') elif vid.has_key('thumb'): thumb = vid.get('thumb') if vid.has_key('duration'): length = vid.get('duration') if vid.has_key('id'): vidid = vid.get('id') elif vid.has_key('video_id'): vidid = vid.get('video_id') else: vidid = vurl.rsplit('-', 1)[0] if vid.has_key('title'): vtitle = vid.get('title').title() elif vitem.has_key('title'): vtitle = vitem.get('title').title() if vid.has_key('publish_date'): pubdate = vid.get('publish_date') elif vitem.has_key('publish_date'): pubdate = vitem.get('publish_date') vtitle = vtitle.replace('"', '') vtitle = vtitle.replace("'", '') lbl = vtitle lbl2 = "{0} {1}".format(pubdate, vidid) if length != "00:00:00" and length != '': if length.find(':') == -1: lenint = 0 seconds = int(length) m, s = divmod(seconds, 60) h, m = divmod(m, 60) length = "%02d:%02d" % (m, s) if h > 0: length = "%d:%02d:%02d" % (h, m, s) else: length = length.replace("00:", "").lstrip("0") lbl += '|[COLOR green]{0}[/COLOR]'.format(length) vpath = plugin.url_for(play, title=vtitle, video=thumb, url=vurl) item = dict(label=lbl, label2=lbl2, icon=thumb, thumb=thumb, path=vpath, is_playable=True) item.setdefault(item.keys()[0]) xbmc.log("Item {0} - {1} - {2} - {3}\n".format(vtitle, lbl2, thumb, vpath)) litems.append(item) else: xbmc.log("Item has no video key: {0}\n".format(repr(vitem))) except: xbmc.log("ERROR MAKINGVIDEOITEMS: {0}\n".format(repr(vitem))) allitems = sorted(litems, key=lambda litems: litems['label']) xbmc.log("\nFINISHED MakeVidItems: #{0} {1}\n".format(len(allitems), repr(allitems))) return allitems
def site(sitename, section, url): litems = [] itemslist = [] siteurl = APIURLS.get(sitename) __imgnext__ = __imgsearch__.replace('search.png', 'next.png') if siteurl.find('search=gay') != -1: surl = siteurl.replace('search=gay&', 'search=gay+{0}&') else: surl = siteurl.replace('search=&', 'search={0}&') itemsearch = {'label': 'Search {0}'.format(sitename.title()), 'path': plugin.url_for(site, sitename=sitename, section='search', url=surl), 'icon': __imgsearch__, 'thumb': __imgsearch__} itemsearch.setdefault(itemsearch.keys()[0]) pagenum = 2 if url.find('page=') != -1: pagestr = str(url.split('page=',1)[1]).split('&',1)[0] if pagestr is not None: pagenum = int(pagestr)+1 pagenumcur = pagenum - 1 #tempu = url[url.find('page=')] if url.find('page=1') != -1: nurl = url.replace('page=1', 'page=2') elif url.find('page=') != -1: nurl = url.replace('page={0}'.format(pagenumcur), 'page={0}'.format(pagenum)) else: nurl = url + '&page={0}'.format(pagenum) itemnext = {'label': 'Next --> {0}'.format(pagenum), 'path': plugin.url_for(site, sitename=sitename, section='next', url=nurl), 'icon': __imgnext__, 'thumb': __imgnext__} itemnext.setdefault(itemnext.keys()[0]) if section.lower() == "index": vitems = list() itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems:litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) itemslist.append(itemnext) litems = itemslist elif section.lower() == "next": vitems = list() itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems:litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) itemslist.append(itemnext) litems = itemslist elif section.lower() == "search": searchtxt = '' searchtxt = plugin.get_setting('lastsearch') searchtxt = plugin.keyboard(searchtxt, 'Search {0}'.format(sitename.title()), False) searchquery = searchtxt.replace(' ', '+') plugin.set_setting(key='lastsearch', val=searchtxt) surl = surl.format(searchquery) xbmc.log('SEARCH - {0} - URL {1}'.format(searchquery, surl)) itemslist = parseVideosUrl(surl) litems = makeVideoItems(itemslist) try: itemslist = sorted(litems, key=lambda litems:litems['label']) except: xbmc.log('\nERROR SORTING ITEMS #{0}'.format(len(litems))) itemslist = litems itemslist.insert(0, itemsearch) nurl = surl.replace('page=1', 'page=2') itemnext = {'label': 'Next {0} --> {1}'.format(searchtxt, pagenum), 'path': plugin.url_for(site, sitename=sitename, section='next', url=nurl), 'icon': __imgnext__, 'thumb': __imgnext__} itemnext.setdefault(itemnext.keys()[0]) itemslist.append(itemnext) litems = itemslist else: itemslist = parseVideosUrl(url) litems = makeVideoItems(itemslist) litems.append(itemnext) return litems
def log(txt, level=xbmc.LOGWARNING): message = '%s: %s' % ('SiTo.tv', str(txt).encode('ascii', 'ignore')) xbmc.log(msg=message, level=level)
def playfirst(url=''): idx = 0 if len(url) < 1: return None html = DL(url) prefhost = '' sourceslist = [] blockedlist = [] stext = plugin.get_setting('topSources') btext = plugin.get_setting('blockedSources') if len(stext) < 1: prefhost = 'vidoza' else: stext = stext.lower() stext = stext.strip(',') if stext.find(',') == -1: sourceslist.append(stext) else: sourceslist = stext.split(',') prefhost = sourceslist[0].lower() btext = plugin.get_setting('blockedSources') if len(btext) < 1: blockedlist.append('vshare') else: btext = btext.lower() btext = btext.strip(',') if btext.find(',') == -1: blockedlist.append(btext) else: blockedlist = btext.split(',') litems = [] name = '' link = '' linklistall = [] linklistall = findvidlinks(html, findhosts=sourceslist) if len(linklistall) > 0: for fitem in linklistall: lname, purl = fitem for source in blockedlist: lbl, hurl = source if purl.find(hurl) == -1: linklist.append(fitem) if len(linklist) < 1: linklist = linklistall for fitem in linklist: vname, vurl = fitem for source in sourceslist: if vurl.find(source) != -1: name = vname link = vurl break #foundhost = findahost(linklist, source) #if foundhost is not None: # name, link = foundhost # break if len(link) > 0: break if len(link) < 1: name, link = linklist[0] xbmc.log("Source {0} {1}".format(name, link)) plugin.notify(msg="#{0} {1}".format(str(len(linklist)), sourceslist[:]), title=link) #if link.find('linkOut') != -1: # urlout = link.split('?id=')[-1] # link = base64.b64decode(urlout) return play(url=link.encode('utf-8', 'ignore')) '''
def playold(url): if url.find('linkOut') != -1: urlout = url.split('?id=')[-1] url = base64.b64decode(urlout) resolved = '' stream_url = '' item = None try: if urlresolver is not None: resolved = urlresolver.resolve(url) if len(resolved) > 1: plugin.notify(msg="PLAY {0}".format(resolved.split('://', 1)[-1]), title="URLRESOLVER", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) plugin.play_video(item) return None except: resolved = '' plugin.notify(msg="FAILED {0}".format(url), title="URLResolver", delay=1000) try: import YDStreamExtractor info = YDStreamExtractor.getVideoInfo(url, resolve_redirects=True) resolved = info.streamURL() for s in info.streams(): try: stream_url = s['xbmc_url'].encode('utf-8', 'ignore') xbmc.log( msg="**YOUTUBE-DL Stream found: {0}".format(stream_url)) except: pass if len(stream_url) > 1: resolved = stream_url if len(resolved) > 1: plugin.notify(msg="PLAY: {0}".format(resolved.split('://', 1)[-1]), title="YOUTUBE-DL", delay=1000) plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) item.add_stream_info('video', stream_values={}) item.set_is_playable(True) plugin.play_video(item) return None except: plugin.notify(msg="Failed: {0}".format(resolved.partition('.')[-1]), title="YOUTUBE-DL", delay=1000) if len(resolved) > 1: plugin.set_resolved_url(resolved) item = ListItem.from_dict(path=resolved) plugin.play_video(item) return None else: plugin.set_resolved_url(url) plugin.play_video(url) return None
def makeVideoItems(itemlist, aslistitem=False): litems = [] vitem = dict() vid = dict() item = dict() getsrc = itemgetter('src') try: for vitem in itemlist: assert isinstance(vitem, dict) if vitem.has_key('video'): vid = vitem.get('video') else: vid = vitem if vid is not None: assert isinstance(vid, dict) thumb = '' length = '' vidid = '' vurl = '' vtitle = '' pubdate = '' if vid.has_key('url'): vurl = vid.get('url') elif vid.has_key('embed'): vurl = vid.get('embed') if vid.has_key('default_thumb'): thumb = vid.get('default_thumb') elif vid.has_key('thumbnail'): thumb = vid.get('thumbnail') elif vid.has_key('thumb'): thumb = vid.get('thumb') if vid.has_key('duration'): length = vid.get('duration') if vid.has_key('id'): vidid = vid.get('id') elif vid.has_key('video_id'): vidid = vid.get('video_id') else: vidid = vurl.rsplit('-', 1)[0] if vid.has_key('title'): vtitle = vid.get('title').title() elif vitem.has_key('title'): vtitle = vitem.get('title').title() if vid.has_key('publish_date'): pubdate = vid.get('publish_date') elif vitem.has_key('publish_date'): pubdate = vitem.get('publish_date') vtitle = vtitle.replace('"', '') vtitle = vtitle.replace("'", '') lbl = vtitle lbl2 = "{0} {1}".format(pubdate, vidid) if length != "00:00:00" and length != '': if length.find(':') == -1: lenint = 0 seconds = int(length) m, s = divmod(seconds, 60) h, m = divmod(m, 60) length = "%02d:%02d" % (m, s) if h > 0: length = "%d:%02d:%02d" % (h, m, s) else: length = length.replace("00:","").lstrip("0") lbl += '|[COLOR green]{0}[/COLOR]'.format(length) vpath = plugin.url_for(play, title=vtitle, video=thumb, url=vurl) item = dict(label=lbl, label2=lbl2, icon=thumb, thumb=thumb, path=vpath, is_playable=True) item.setdefault(item.keys()[0]) xbmc.log("Item {0} - {1} - {2} - {3}\n".format(vtitle, lbl2, thumb, vpath)) if aslistitem: litems.append(makeItemExtraThumbs(item, vid)) else: litems.append(item) else: xbmc.log("Item has no video key: {0}\n".format(repr(vitem))) except: xbmc.log("ERROR MAKINGVIDEOITEMS: {0}\n".format(repr(vitem))) allitems = sorted(litems, key=lambda litems: litems['label']) xbmc.log("\nFINISHED MakeVidItems: #{0} {1}\n".format(len(allitems), repr(allitems))) return allitems
def oldplay(title, video, url): try: if vidurl is None: m1 = re.compile('href="(https?.+mp4[^"]*)".', re.I + re.M + re.S + re.U).findall(vidhtml) m2 = re.compile('flv_url=(http[^"]+?)&', re.I+re.M).findall(vidhtml) m3 = re.compile("videoUrl: '([^']+)", re.I+re.M).findall(vidhtml) m4 = re.compile("480: '([^']+)", re.I+re.M).findall(vidhtml) m5 = re.compile('source src="([^"]+)"', re.I+re.M).findall(vidhtml) m6 = re.compile("var player_quality_480p = '([^\"]+.mp4[^']*)';", re.I+re.M).findall(vidhtml) if m1 is not None: vidurl = m1.pop() xbmc.log("MATCH 1 = {0}".format(vidurl)) if m2 is not None: vidurl = m2.pop() xbmc.log("MATCH 2 = {0}".format(vidurl)) if m3 is not None: vidurl = m3.pop() xbmc.log("MATCH 3 = {0}".format(vidurl)) if m4 is not None: vidurl = m4.pop() xbmc.log("MATCH 4 = {0}".format(vidurl)) if m5 is not None: vidurl = m5.pop() xbmc.log("MATCH 5 = {0}".format(vidurl)) if m6 is not None: vidurl = m6.pop() xbmc.log("MATCH 6 = {0}".format(vidurl)) #matches = re.compile("videoUrl: '([^']*)',", re.I + re.M + re.S + re.U).findall(vidhtml)[0] #vidurl = matches #vidurl = matches.split(' ', 1)[0].strip('"') #xbmc.Player().play(vidurl) if vidurl is not None: xbmc.log("PLAY matches vidpage: \n{0}".format(vidurl)) vli = ListItem(label=title, label2=url, icon=video, thumbnail=video, path=vidurl) vli.playable = True plugin.set_resolved_url(vli) plugin.play_video(vli) # return plugin.play_video(vli) else: xbmc.log("FAILED to resolve url to movie file. {0}".format(url)) except: xbmc.log("failed to resolve url to movie file.")