def authenticate(): try: content = mc.Http().Get( 'http://app.boxee.tv/api/get_application_data?id=mlb') if content: return status_error else: auth_dom = parseString(content) email = auth_dom.getElementsByTagName('email')[0].firstChild.data account = auth_dom.getElementsByTagName( 'rand_account')[0].firstChild.data post_data = request({ 'func': '_login', 'email': email, 'pass': account }) if ((not post_data) or (post_data['data'] == '0')): Exception('post request return false') cf = mc.GetApp().GetLocalConfig() response = getJson(data=post_data['data']) response = response.get('identity') code = str(response.get('code')) if ((code != '1') and info('authenticate.code', code)): cf.Reset('fprt') cf.Reset('ipid') cf.Reset('username') cf.Reset('password') info('login', 'stored/entered credentials invalid') return status_invalid mc.HideDialogWait() except Exception, e: updateArchiveSpoiler() return status_invalid
def request(data): try: info('request', 'processing post request to boxee.tv') if ((not data) or (str(type(data)) != "<type 'dict'>")): return raiseError( log='request', error='data passed is not usable. contact [email protected]') try: params = urllib.urlencode(data) except: return raiseError( log='request', error='data passed is not usable. contact [email protected]') http = mc.Http() result = http.Post('http://dir.boxee.tv/apps/mlb/mlb.php', params) code = http.GetHttpResponseCode() http.Reset() if ((code != 200) and debug('request', ('post returned response code ' + str(code)))): pass if (result or debug('request', 'post return zero bytes')): pass if ((code == 200) and result): info('request', 'post was successfull') response = {'data': result, 'code': code} return response except Exception, e: return raiseError(log='request', error=e)
def CreateHTMLListItem(url): #mc.ShowDialogOk("Debug", "Creating HTMLListItem") uri = urlparse.urlparse(url) if not uri[0]: url = "http://" + urlparse.urlunparse(uri) uri = urlparse.urlparse(url) domain = uri[1] domain = domain.split('.') if len(domain) > 2: domain = domain[-2:] domain = ".".join(domain) badUrl = False http = mc.Http() if not http.Get(url): badUrl = True if not badUrl: item = mc.ListItem() item.SetLabel("Navi-X Browser") item.SetAddToHistory(False) item.SetReportToServer(False) item.SetContentType("text/html") item.SetPath(url) #return item return {"code":0,"data":item} else: #mc.ShowDialogOk("Error: html", "The address does not exist or cannot be displayed through the browser.") return {"code":1,"data":"The address does not exist or cannot be displayed through the browser."}
def callService(func, values={}, authenticated=True, content=False): try: info('callservice', ('calling the boxee_mlb service w/%s, authentication/%s' % (func, str(authenticated).lower()))) params = {} http_service = mc.Http() url_base = 'http://dir.boxee.tv/apps/mlb/mlb.php?func=%s&%s' if authenticated: app = mc.GetApp() cf = app.GetLocalConfig() params['nsfp'] = cf.GetValue('fprt') params['nsid'] = cf.GetValue('ipid') if values: for i in values: params[i] = values[i] url_base = underscore((url_base % (func, urllib.urlencode(params)))) query_result = http_service.Get(url_base) if (content == 'json'): query_result = re.sub('//.*?\n|/\\*.*?\\*/', '', query_result, re.S) query_result = json.loads(query_result) return query_result except Exception, e: return raiseError(log='callservice', error=e)
def updateToken(self): http = mc.Http() http.SetHttpHeader("X-Plex-Platform", "Boxee") http.SetHttpHeader("X-Plex-Platform-Version", mc.GetInfoString("System.BuildVersion")) http.SetHttpHeader("X-Plex-Provides", "player") http.SetHttpHeader("X-Plex-Product", "Plexee") http.SetHttpHeader("X-Plex-Version", "1.0") try: http.SetHttpHeader("X-Plex-Device", mc.GetPlatform()) except: http.SetHttpHeader("X-Plex-Device", "Boxee") try: http.SetHttpHeader("X-Plex-Client-Identifier", mc.GetDeviceId()) except: http.SetHttpHeader("X-Plex-Client-Identifier", str(uuid.getnode())) base64String = base64.encodestring( "%s:%s" % (self.username, self.password)).replace('\n', '') http.SetHttpHeader("Authorization", "Basic %s" % base64String) postData = "username=%s&password=%s" % (self.username, self.password) data = http.Post(MyPlexService.AUTH_URL, postData) http.Reset() if data: tree = ElementTree.fromstring(data) self.authenticationToken = tree.findtext("authentication-token", None)
def loadTVEpg(update=False): global epg_list, config, ipaddress if epg_list is not None and update == False: return epg_list # get the current epg list epg_url = "http://" + ipaddress + "/web/epgnow?bRef=1:7:1:0:0:0:0:0:0:0:(type%20==%201)%20||%20(type%20==%2017)%20||%20(type%20==%20195)%20||%20(type%20==%2025)%20ORDER%20BY%20name" epg_data = mc.Http().Get(epg_url) epg_events = BeautifulStoneSoup(epg_data) epg_list = [] for event in epg_events.findAll('e2event'): epg_list.append({ 'reference': event.e2eventservicereference.renderContents(), 'id': event.e2eventid.renderContents(), 'start': event.e2eventstart.renderContents(), 'duration': event.e2eventcurrenttime.renderContents(), 'currenttime': event.e2eventservicereference.renderContents(), 'title': event.e2eventtitle.renderContents(), 'description': event.e2eventdescription.renderContents(), 'descriptionextended': event.e2eventdescriptionextended.renderContents(), 'servicename': event.e2eventservicename.renderContents() }) epg_list.sort(compareEpgList) return epg_list
def getServers(self): localServers = dict() remoteServers = dict() foundServer = False if self.isAuthenticated(): data = mc.Http().Get(self.getLibraryUrl()) if data: tree = ElementTree.fromstring(data) for child in tree: host = child.attrib.get("address", "") port = child.attrib.get("port", "") accessToken = child.attrib.get("accessToken", "") machineIdentifier = child.attrib.get("machineIdentifier", "") local = child.attrib.get("owned", "0") util.logInfo("MyPlex found %s:%s" % (host,port)) foundServer = True server = PlexServer(host, port, accessToken) if not server.isAuthenticated(): continue if local == "1": localServers[machineIdentifier] = server else: remoteServers[machineIdentifier] = server return localServers, remoteServers, foundServer
def request(self, path): myHttp = mc.Http() myHttp.SetUserAgent( 'Boxee App (%s; U; %s; en-us; Boxee %s %s)' % (self.os, self.platform, self.deviceid, self.boxeeid)) data = myHttp.Get(path) return data
def getPhotoList(self, listItem): #photoUrl = self.getUrl(self.getRootUrl(), fullUrl) url = self.getUrl(self.getRootUrl(), listItem.GetProperty('parentKey')) data = mc.Http().Get(url+'/children') if data: list = mc.ListItems() tree = ElementTree.fromstring(data) for photoNode in tree.findall("Photo"): title = photoNode.attrib.get("title", "Plex Photo") key = photoNode.attrib.get('key') for part in photoNode.findall("Media/Part"): li = mc.ListItem(mc.ListItem.MEDIA_PICTURE) li.SetProperty('key',key) li.SetTitle(title) li.SetLabel(title) li.SetPath(self.getUrl(self.getRootUrl(), key)) li.SetProperty('rotation','') li.SetProperty('zoom','') #Resize images li.SetImage(0, self.getThumbUrl(part.attrib.get('key'),1280,1280)) #li.SetImage(0, self.getUrl(self.getRootUrl(), part.attrib.get('key'))) list.append(li) return list else: return None
def getJson(url=False, data=False): try: if url: data = mc.Http().Get(url) data = re.sub('//.*?\n|/\\*.*?\\*/', '', data, re.S) data = json.loads(data) return data except Exception, e: return raiseError(log='getjson', error=e)
def request(self, path): # Instatiate HTTP object myHttp = mc.Http() # Set User Agent myHttp.SetUserAgent("Boxee App (boxee/beta " + self.version + " tracker)") # Get data data = myHttp.Get(path) # Make request return data
def _updateSettings(self): data = mc.Http().Get(self.getRootUrl()) if data: tree = ElementTree.fromstring(data) self.friendlyName = tree.attrib.get("friendlyName", None) self.machineIdentifier = tree.attrib.get("machineIdentifier", None) self.platform = tree.attrib.get("platform", None) self.platformVersion = tree.attrib.get("platformVersion", None) self.transcoderVideoBitrates = tree.attrib.get("transcoderVideoBitrates", None) self.transcoderVideoQualities = tree.attrib.get("transcoderVideoQualities", None) self.transcoderVideoResolutions = tree.attrib.get("transcoderVideoResolutions", None) self.version = tree.attrib.get("version", None)
def urlopen(url, **kwargs): """ Action a http request # url - reqest url # params - dict, extra http parameters (optional) # xhr - boolean, make a xhr ajax request # post - dict, parameters to POST if empty a GET request is executed # cookie - string, send cookie data with request # useragent - string, send custom useragent with request # cache - instance, possible to feed a cache instance # age - int, maximum age in seconds of cached item """ http = mc.Http() http.SetUserAgent( "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.10 (maverick) Firefox/3.6.13" ) http.SetHttpHeader( 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*') if kwargs.get('cache', False): cache = kwargs['cache'] if kwargs.get('age', False): data = cache.get(url, kwargs['age']) else: data = cache.get(url) if data: return data params = {} if kwargs.get('params', False): params = kwargs['params'] if params.get('xhr', False): http.SetHttpHeader('X-Requested-With', 'XMLHttpRequest') if params.get('cookie', False): http.SetHttpHeader('Cookie', params['cookie']) if params.get('useragent', False): http.SetUserAgent(params['useragent']) if params.get('post', False): data = http.Post(url, params['post']) else: data = http.Get(url) if kwargs.get('cache', False): cache.set(url, data) return data
def getListItems(self, fullUrl): data = mc.Http().Get(fullUrl) if data: tree = ElementTree.fromstring(data) titleListItem = self._createListItem(tree, fullUrl) titleListItem.SetProperty("plexeeview", "grid") titleListItems = mc.ListItems() titleListItems.append(titleListItem) childListItems = mc.ListItems() for child in tree: childListItem = self._createListItem(child, fullUrl) childListItems.append(childListItem) return WindowInformation(titleListItems, childListItems) else: return None
def getSubtitles(self, fullUrl): """ Return list of subtitles Jinxo: Only the default - and any SRT files are supported at present """ subItems = mc.ListItems() subItem = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN) subItem.SetLabel("None") subItem.SetPath("") subItems.append(subItem) videoUrl = self.getUrl(self.getRootUrl(), fullUrl) data = mc.Http().Get(videoUrl) if data: tree = ElementTree.fromstring(data) videoNode = tree[0] foundDefault = False for stream in videoNode.findall("Media/Part/Stream"): if stream.attrib.get("streamType","0") != "3": continue subItem = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN) language = stream.attrib.get("language","Unknown") format = stream.attrib.get("format","?") path = stream.attrib.get("key","") source = "File" if path != "": subItem.SetPath(self.getUrl(self.getRootUrl(), path)) else: #Jinxo: Only default supported at the moment, as I haven't been able to switch to another.... source = "Embedded" default = stream.attrib.get("default","") if default == "": continue if foundDefault: continue foundDefault = True #Jinxo: The value doesn't matter - just enter something subItem.SetPath("1"); label = language + " (" + format.upper() + ":" + source + ")" subItem.SetLabel(label.encode('utf-8')) subItems.append(subItem) return subItems;
def loadRadioList(): global current_navigation, config, radio_services, ipaddress current_navigation = 'radio' if radio_services is None: radio_url = "http://" + ipaddress + "/web/getservices?sRef=1:7:2:0:0:0:0:0:0:0:(type%20==%202)%20ORDER%20BY%20name" radio_data = mc.Http().Get(radio_url) radio_services = BeautifulStoneSoup(radio_data) # create new list itemList = mc.ListItems() for service in radio_services.findAll('e2service'): item = mc.ListItem(mc.ListItem.MEDIA_AUDIO_RADIO) reference = service.e2servicereference.renderContents() item.SetPath("http://" + ipaddress + "/web/stream.m3u?ref=" + reference) item.SetLabel(service.e2servicename.renderContents()) itemList.append(item) mc.GetActiveWindow().GetList(120).SetItems(itemList)
def playMusicUrl(self, fullUrl): trackUrl = self.getUrl(self.getRootUrl(), fullUrl) data = mc.Http().Get(trackUrl) if data: tree = ElementTree.fromstring(data) trackNode = tree[0] title = trackNode.attrib.get("title", "Plex Track") playlist = mc.PlayList(mc.PlayList.PLAYLIST_MUSIC) playlist.Clear() for part in trackNode.findall("Media/Part"): li = mc.ListItem(mc.ListItem.MEDIA_AUDIO_MUSIC) li.SetTitle(title) li.SetLabel(title) li.SetPath(self.getUrl(self.getRootUrl(), part.attrib.get('key'))) playlist.Add(li) playlist.Play(0) else: return None
def playVideoUrl(self, fullUrl): videoUrl = self.getUrl(self.getRootUrl(), fullUrl) data = mc.Http().Get(videoUrl) if data: tree = ElementTree.fromstring(data) videoNode = tree[0] title = videoNode.attrib.get("title", "Plex Video") playlist = mc.PlayList(mc.PlayList.PLAYLIST_VIDEO) playlist.Clear() for part in videoNode.findall("Media/Part"): li = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN) li.SetTitle(title) li.SetLabel(title) li.SetPath( self.getUrl(self.getRootUrl(), part.attrib.get('key'))) playlist.Add(li) playlist.Play(0) else: return None
def getListItems(self, fullUrl): data = mc.Http().Get(fullUrl) if data: tree = ElementTree.fromstring(data) titleListItem = self._createListItem(tree, fullUrl) titleListItem.SetProperty("plexeeview", "grid") #Set title item art/thumb to display if needed titleListItem.SetProperty("art", tree.attrib.get("art","")) titleListItem.SetProperty("thumb", tree.attrib.get("thumb","")) titleListItems = mc.ListItems() titleListItems.append(titleListItem) childListItems = mc.ListItems() for child in tree: childListItem = self._createListItem(child, fullUrl) childListItems.append(childListItem) return WindowInformation(titleListItems, childListItems) else: return None
def getServers(self): localServers = dict() remoteServers = dict() if self.isAuthenticated(): data = mc.Http().Get(self.getLibraryUrl()) if data: tree = ElementTree.fromstring(data) for child in tree: host = child.attrib.get("address", "") port = child.attrib.get("port", "") accessToken = child.attrib.get("accessToken", "") machineIdentifier = child.attrib.get( "machineIdentifier", "") local = child.attrib.get("owned", "0") if local == "1": localServers[machineIdentifier] = PlexServer( host, port, accessToken) else: remoteServers[machineIdentifier] = PlexServer( host, port, accessToken) return localServers, remoteServers
# LICENSE Bartsidee Framework - CC BY-NC-ND #=============================================================================== # This work is licenced under the Creative Commons # Attribution-Non-Commercial-No Derivative Works 3.0 Unported License. To view a # copy of this licence, visit http://creativecommons.org/licenses/by-nc-nd/3.0/ # or send a letter to Creative Commons, 171 Second Street, Suite 300, # San Francisco, California 94105, USA. #=============================================================================== import mc, bz2, binascii, os from time import time from urllib import FancyURLopener #=============================================================================== # Global Variables #=============================================================================== http = mc.Http() http.SetUserAgent( "Mozilla/5.0 (Windows; U; Windows NT 6.1; nl; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13" ) http.SetHttpHeader( 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*') config = mc.GetApp().GetLocalConfig() #=============================================================================== # Function to Retrieve and Cache a Http request # Input: # url - reqest url # cacheTime - amount of time to keep the http result in the cache (seconds) # xhr - make a xhr ajax request (boolean) # params - parameters to POST if empty a GET request is executed
def playItem(mlbList, forceAudioCheck=False, playFromListItem=False): if mc.ShowDialogWait(): play_audio = False if playFromListItem: window = mc.GetActiveWindow() list = window.GetList(mlbList) index = list.GetFocusedItem() item = list.GetItem(index) else: item = playFromListItem session_id = 'null' cf = mc.GetApp().GetLocalConfig() if cf.GetValue('sessionid'): session_id = cf.GetValue('sessionid') if isLoggedIn(): return raiseError( 'You must first log in before you can watch this game.') video_request_type = 'HTTP_CLOUD_WIRED' audio_request_type = 'AUDIO_SHOUTCAST_32K' audio_set_shout_protocol = False simulate_blackout = False simulate_not_authorized = False mr_url = 'https://secure.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.1?%s' params = { 'subject': 'LIVE_EVENT_COVERAGE', 'playbackScenario': video_request_type, 'eventId': item.GetProperty('event-id'), 'contentId': item.GetProperty('content-id'), 'sessionKey': session_id, 'fingerprint': cf.GetValue('fprt'), 'identityPointId': cf.GetValue('ipid'), 'platform': 'BOXEE' } web_url = ( 'http://mlb.mlb.com/media/player/entry.jsp?calendar_event_id=%s&source=boxeeRef' % item.GetProperty('event-id')) media_request = underscore((mr_url % urllib.urlencode(params))) if simulate_blackout: playlist_url = -1 elif simulate_not_authorized: playlist_url = -2 else: media_data = queryMediaService(media_request) playlist_url = media_data['playlist_url'] update_media_state = media_data['media_state'] if (bool(update_media_state) and (str(update_media_state).lower() != item.GetProperty('media-state').lower())): info( 'playitem', ('updating media_state (%s)' % update_media_state.lower())) item.SetProperty('media-state', update_media_state.lower()) if (playlist_url == -3000): check_auth = authenticate() if (check_auth == status_valid): media_data = queryMediaService(media_request) playlist_url = media_data['playlist_url'] update_media_state = media_data['media_state'] if (bool(update_media_state) and (str(update_media_state).lower() != item.GetProperty('media-state').lower())): info('playitem', ('updating media_state (%s)' % update_media_state.lower())) item.SetProperty('media-state', update_media_state.lower()) else: raiseError( 'Unable to validate your account. Please make sure your mlb.tv account is linked with Boxee! See boxee.tv/services.', 'playitem', 'lost users login credentials') mc.HideDialogWait() return False if ((playlist_url == -1) and ((not item.GetProperty('audio-string')) and (item.GetProperty('media-state') != 'media_on'))): return raiseError( 'No available audio streams found for this game. We apologize for the inconvenience.' ) confirm = mc.ShowDialogConfirm( 'MLB.TV', 'Video is not currently available for this game. Would you like to listen to the live audio broadcast?', 'No', 'Yes') if confirm: play_audio = parseAudioStreams(item) if play_audio: return False params = { 'subject': 'LIVE_EVENT_COVERAGE', 'playbackScenario': audio_request_type, 'eventId': item.GetProperty('event-id'), 'contentId': play_audio[1], 'sessionKey': session_id, 'fingerprint': cf.GetValue('fprt'), 'identityPointId': cf.GetValue('ipid'), 'platform': 'BOXEE' } del params['platform'] media_request = underscore((mr_url % urllib.urlencode(params))) media_data = queryMediaService(media_request) playlist_url = media_data['playlist_url'] update_media_state = media_data['media_state'] if (bool(update_media_state) and (str(update_media_state).lower() != item.GetProperty('media-state').lower())): info( 'playitem', ('updating media_state (%s)' % update_media_state.lower())) item.SetProperty('media-state', update_media_state.lower()) else: mc.HideDialogWait() return False if ((playlist_url == -2) and mc.GetActiveWindow().ClearStateStack()): return raiseError( 'You must own MLB.TV to watch live baseball. Please go to mlb.com/boxee to sign up.' ) if play_audio: content_type = 'audio/mpeg' stream_type = mc.ListItem.MEDIA_AUDIO_OTHER playlist_url = playlist_url.replace('http://', 'shout://') else: live = 0 playlist_url = (playlist_url + ('&quality=%s' % promptQuality())) if (item.GetProperty('media-state') == 'media_on'): confirm = mc.ShowDialogConfirm( 'MLB.TV', 'Would you like to watch this game from the start or jump into the live broadcast?', 'Start', 'Live') live = int(confirm) playlist_url = ((playlist_url + '&live=') + str(live)) content_type = 'application/vnd.apple.mpegurl' stream_type = mc.ListItem.MEDIA_VIDEO_OTHER alt_label = item.GetProperty('alt-label') title = alt_label.replace('#', '').replace('@mlbtv', '') title = (title.replace(' v ', ' @ ') + ' on MLB.TV') playlist_url = ((playlist_url + '&bx-ourl=') + urllib.quote_plus(web_url)) ext = mc.ListItem(stream_type) ext.SetTitle(alt_label) ext.SetLabel(title) ext.SetDescription(item.GetDescription(), False) ext.SetContentType(content_type) ext.SetThumbnail(item.GetThumbnail()) ext.SetProviderSource('MLB.TV') params = { 'title': title, 'alt-label': alt_label, 'event-id': item.GetProperty('event-id'), 'content-id': item.GetProperty('content-id'), 'description': item.GetDescription(), 'bx-ourl': web_url, 'thumbnail': item.GetThumbnail(), 'audio-stream': play_audio, 'media-state': item.GetProperty('media-state') } if play_audio: params['audio-string'] = item.GetProperty('audio-string') rand_number = str(random.randint(10000, 100000000)) tracking_url = ((( ((('http://mlbglobal08.112.2o7.net/b/ss/mlbglobal08/1/G.5--NS/' + rand_number) + '?ch=Media&pageName=BOXEE%20Media%20Return&c25=') + str(play_audio[2])) + '%7C') + underscore(audio_request_type)) + '&c27=Media%20Player&c43=BOXEE') notify = mc.Http().Get(tracking_url) del notify ext.SetPath(('app://mlb/launch?%s' % urllib.urlencode(params))) new_item = mc.ListItem(stream_type) new_item.SetLabel(title) new_item.SetTitle(alt_label) new_item.SetDescription(item.GetDescription(), False) new_item.SetPath(playlist_url) new_item.SetProviderSource('MLB.TV') new_item.SetContentType(content_type) new_item.SetThumbnail(item.GetThumbnail()) if (play_audio and new_item.SetAddToHistory(False)): new_item.SetReportToServer(False) new_item.SetExternalItem(ext) mc.GetActiveWindow().ClearStateStack() try: track_label = generateTrackerGameString(item) if (track_label and myTracker.trackEvent('Video', 'Play', track_label)): pass except: myTracker.trackEvent('Video', 'Play', title) mc.HideDialogWait() mc.GetPlayer().Play(new_item)
def setMediaUnwatched(self, mediaKey): url = self.getRootUrl() + ":/unscrobble?key="+mediaKey+"&identifier=com.plexapp.plugins.library" util.logDebug("Setting media key=[%s] as unwatched" % mediaKey) mc.Http().Get(url)
def playVideoUrl(self, fullUrl, subitem = None, offset=0): videoUrl = self.getUrl(self.getRootUrl(), fullUrl) data = mc.Http().Get(videoUrl) if data: tree = ElementTree.fromstring(data) videoNode = tree[0] playlist = mc.PlayList(mc.PlayList.PLAYLIST_VIDEO) playlist.Clear() thumbnailUrl = self.getThumbUrl(videoNode.attrib.get("thumb"), 100, 100) description = util.cleanString(videoNode.attrib.get("summary","")) title = util.cleanString(videoNode.attrib.get("title", "Plex Video")) contentRating = util.cleanString(videoNode.attrib.get("contentRating","")) for part in videoNode.findall("Media/Part"): li = mc.ListItem(mc.ListItem.MEDIA_VIDEO_CLIP) li.SetTitle(title) li.SetLabel(title) li.SetPath(self.getUrl(self.getRootUrl(), part.attrib.get("key"))) li.SetThumbnail(thumbnailUrl) li.SetDescription(description, False) li.SetContentRating(contentRating) #TV Episode extras mediaType = videoNode.attrib.get("type","movie") if mediaType == 'episode': li.SetTVShowTitle(util.cleanString(videoNode.attrib.get("grandparentTitle",""))) li.SetEpisode(int(videoNode.attrib.get('index'))) li.SetSeason(int(videoNode.attrib.get('parentIndex'))) playlist.Add(li) playlist.Play(0) #ok wait for player to start loop = 0 util.logDebug("Waiting on player") while not xbmc.Player().isPlaying(): xbmc.sleep(1000) loop = loop + 1 if loop > 10: break util.logDebug("Player started...") #set any offset if offset != 0: xbmc.Player().seekTime(offset/1000) #Set subtitles subtitleKey = "" if subitem != None: subtitleKey = subitem.GetPath() if subtitleKey == "": import os noSubPath = os.path.join(mc.GetApp().GetAppMediaDir(), "media", "no_subs.srt") xbmc.Player().setSubtitles(noSubPath) else: util.logInfo("Setting subtitles to: " + subtitleKey) xbmc.Player().setSubtitles(subtitleKey) #Monitor playback and update progress to plex key = videoNode.attrib.get('ratingKey') self.monitorPlayback(key, offset) else: return None
def setMediaPlayedPosition(self, mediaKey, positionMsec): url = self.getRootUrl() + ":/progress?key="+mediaKey+"&identifier=com.plexapp.plugins.library&time="+str(positionMsec) util.logDebug("Setting media key=[%s] to position=[%s]" % (mediaKey,str(positionMsec))) mc.Http().Get(url)
REGEX_PAGE_ITEM = r"""<a class="title" href="/index.php/serie(\?serID=\d+&md5=[^\"]+)">([^<]+)</a>""" REGEX_PAGE_PAGES = r"""class="populair_top_pagina_nr">(\d+)</(a|strong)>""" REGEX_PAGE_ITEM2 = r"""<a href="http://player.omroep.nl/(\?aflID=\d+)"[^>]+><img .*? alt="bekijk uitzending: ([^\"]+)" />""" REGEX_ITEM_SECURITY = r"""var securityCode = '([0-9a-f]+)'""" REGEX_ITEM_INFO = r"""<b class="btitle">[^<]+</b>\s+<p style="margin-top:5px;">(.*?)(\s+<)""" REGEX_ITEM_THUMB = r"""<td height="100"[^>]+>\s+<img src="(.*?)" .*? style="float:left;margin:0px 5px 0px 0px;" />""" REGEX_STREAM_URI = r"""<stream[^>]+compressie_kwaliteit=.bb.[^>]+compressie_formaat=.wmv.[^>]*>([^<]*)</stream>""" REGEX_STREAM_DIRECT = r"""<Ref href[^"]+"([^"]+)\"""" REGEX_SEARCH_ITEM = r"""<a class="title" href="/index.php/search(\?serID=\d+&md5=[^&]+)&sq=[^\"]+">([^<]+)</a>""" #MEDIA_PATH = mc.GetApp().GetAppMediaDir() #print MEDIA_PATH # ? doesn't work? # Create HTTP for stream fetching HTTP2 = mc.Http() # Set user-agent (Windows Media Player) HTTP2.SetUserAgent("Windows-Media-Player/10.00.00.3646") # get App Config config = mc.GetApp().GetLocalConfig() # load index on app start def doLoad(): if config.GetValue("wantindex") != "no": data = uzgf.GetCached(ROOT_URI, 1) doAction("feed://index/0", "") config.SetValue("wantindex", "yes") # do an Action based on path
# -*- coding: utf-8 -*- import sys import string import mc import codecs from elementsoup import ElementSoup BASE_URL = "http://www.playkanalerna.se" HTTP = mc.Http() HTTP.SetUserAgent("Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)") cache = {} def getPageElements(url): print 'FETCHING: ' + url if url in cache: print 'Cache found' page = cache[url] else: print 'No cache, fetching page' page = ElementSoup.parse(HTTP.Get(url)) cache[url] = page return page def getCategories(): page = getPageElements(BASE_URL) elements = page.findall(".//ul[@class='categories']//a")
def getVideoItem(self, listItem): li = mc.ListItem(mc.ListItem.MEDIA_UNKNOWN) copyAttribs = ["type","viewGroup","itemtype","machineidentifier","thumb","art","key"] #Copy key attributes for a in copyAttribs: li.SetProperty(a, listItem.GetProperty(a)) li.SetPath(listItem.GetPath()) #Get video detail from plex data = mc.Http().Get(listItem.GetPath()) if not data: return listItem tree = ElementTree.fromstring(data)[0] #Set video specific generalAttribs = ['title','audioChannels','thumb','art','contentRating','year','summary','viewOffset','duration','rating','tagline'] episodeAttribs = ['grandparentTitle','index','parentIndex','leafCount','viewedLeafCount'] for a in (generalAttribs + episodeAttribs): if tree.attrib.has_key(a): li.SetProperty(a.lower(), util.cleanString(tree.attrib[a])) #Set episode titles if li.GetProperty('type') == 'episode': epTitle = util.formatEpisodeTitle(season=li.GetProperty('parentindex'), episode=li.GetProperty('index'), title=li.GetProperty('title')) #Set tagline to episode title li.SetProperty('tagline',epTitle) #set showtitle li.SetProperty('title',li.GetProperty('grandparenttitle')) #Set images art = li.GetProperty("art") thumb = li.GetProperty("thumb") if thumb != "": li.SetImage(0, self.getThumbUrl(thumb, 450, 500)) if art != "": li.SetImage(1, self.getThumbUrl(art, 980, 580)) #Resolution mediaNode = tree.find("Media") if mediaNode: resolution = mediaNode.attrib.get("videoResolution","") if resolution.isdigit(): resolution = resolution + "p" else: resolution = resolution.upper() li.SetProperty("resolution",util.cleanString(resolution)) channels = mediaNode.attrib.get("audioChannels","") if channels.isdigit(): channels = int(channels) if channels > 2: channels = str(channels - 1) + ".1 channels" else: channels = str(channels) + " channels" li.SetProperty("channels",util.cleanString(channels)) #Genre li.SetProperty("genre", util.cleanString(self._getTags(tree, "Genre", "tag", 2))) #Director li.SetProperty("director", util.cleanString(self._getTags(tree, "Director", "tag"))) #Writer li.SetProperty("writer", util.cleanString(self._getTags(tree, "Writer", "tag"))) #Actors li.SetProperty("actors", util.cleanString(self._getTags(tree, "Role", "tag"))) #Duration duration = "" if tree.attrib.has_key("duration") and tree.attrib["duration"].isdigit(): #Format millisecond duration duration = util.msToFormattedDuration(int(tree.attrib["duration"])) li.SetProperty("durationformatted", duration) if tree.attrib.has_key("rating"): li.SetProperty("roundedrating", str(int(round(float(tree.attrib["rating"]))))) return li
def queryMediaService(media_request, isAudio=False): try: http = mc.Http() cf = mc.GetApp().GetLocalConfig() rand_number = str(random.randint(10000, 100000000)) http.Get( (('http://mlbglobal08.112.2o7.net/b/ss/mlbglobal08/1/H.19--NS/' + rand_number) + '?ch=Media&pageName=BOXEE%20Request&c1=BOXEE')) http.Reset() media_service = http.Get(media_request) status_code = '' if ('status-code' in media_service): status_code = int( re.compile('<status-code>(.*?)<').findall(media_service)[0]) if ('notAuthorizedStatus' in media_service): return {'playlist_url': -2, 'media_state': ''} if (media_service and ('<url>' in media_service)): base_encoded_string = re.compile('<url>(.*?)<').findall( media_service)[0] media_state = '' if (media_service and ('<state>' in media_service)): media_state = re.compile('<state>(.*?)<').findall(media_service)[0] content_id = '' if (media_service and ('<content-id>' in media_service)): content_id = re.compile('<content-id>(.*?)<').findall( media_service)[0] event_id = '' if (media_service and ('<event-id>' in media_service)): event_id = re.compile('<event-id>(.*?)<').findall(media_service)[0] startDate = '0' innings_index = '' if (media_service and ('<innings-index>' in media_service)): innings_index = re.compile('<innings-index>(.*?)<').findall( media_service)[0] info('innings_index', innings_index) if innings_index.startswith('http'): http = mc.Http().Get(innings_index) if http: startDate = '0' elif ('start_timecode' in http): startDate = re.compile('start_timecode="(.*?)">').findall( http)[0] else: startDate = '0' if (media_service and ('<session-key>' in media_service)): old_session = cf.GetValue('sessionid') session_key = re.compile('<session-key>(.*?)<').findall( media_service)[0] cf.SetValue('sessionid', session_key) if ((not isAudio) and ((not base_encoded_string.startswith('http://')) and (not base_encoded_string.startswith('rtmp://')))): request_params = base64.b64decode(base_encoded_string).split('|') ( stream_url, stream_fingerprint, stream_params, ) = request_params rand_number = str(random.randint(10000, 100000000)) bx_ourl = ( 'http://mlb.mlb.com/media/player/entry.jsp?calendar_event_id=%s&source=boxeeRef' % event_id) tracking_url = ( ((('http://mlbglobal08.112.2o7.net/b/ss/mlbglobal08/1/G.5--NS/' + rand_number) + '?ch=Media&pageName=BOXEE%20Media%20Return&c25=') + content_id) + '%7CHTTP%5FCLOUD%5FWIRED&c27=Media%20Player&c43=BOXEE') params = { 'stream-fingerprint': stream_fingerprint, 'tracking-url': tracking_url, 'startDate': startDate, 'stream-params': stream_params } playlist_url = ( 'playlist://%s?%s' % (urllib.quote_plus(stream_url), urllib.urlencode(params))) data = {'playlist_url': playlist_url, 'media_state': media_state} return data except Exception, e: raiseError(log='querymediaservice', error=e) return {'playlist_url': False, 'media_state': ''}