Beispiel #1
0
 def resolve_stream(self, url):
     Addon.log('resolving stream: %s' % url)
     chan_page = self.__get_html(url)
     watch_url = re.search('id="player" src="(.+?)"', chan_page).group(1)
     watch_page = self.__get_html(watch_url, referer=self.__build_url(url))
     resolved = False
     s = re.search('file=(.+?)&streamer=(.+?)&', watch_page)
     if s:
         play, streamer = s.groups()
         app = '/'.join(streamer.split('/')[3:])
         resolved = '%s app=%s playpath=%s pageurl=%s' % \
                    (streamer, app, play, self.__build_url(watch_url))
         Addon.log('resolved to: %s' % resolved)
     else:
         s = re.search('stream: \'(rtmp.+?)\'', watch_page)
         if s:
             stream_url = s.group(1)
             resolved = '%s swfUrl=http://cdn.freedocast.com/player-octo/yume/v4/infinite-hd-player-FREEDOCAST.SWF pageUrl=%s' % (stream_url, watch_url)
         else:
             s = re.search('streamsUrl:  \'(.+?)\'', watch_page)
             if s:
                 xml_url = s.group(1)
                 xml = self.__get_html(xml_url)
                 s = re.search('<stream uri="(.+?)" stream="(.+?)"', xml)
                 if s:
                     tcurl, play = s.groups()
                     resolved = '%s/%s swfUrl=http://cdn.freedocast.com/player-octo/playerv2/swfs/broadkastplayer-yupp.swf pageUrl=%s' % (tcurl, play, watch_url)
     return resolved
Beispiel #2
0
 def get_link_NEW(self, quality=1, stream_type='rtmp'):
     Addon.log('get_link')
     self.token = self._login(True)
     html = self._get_html('iphone_ajax', {'tab': 'iphone_playingnow', 
                                           'token': self.token})
     channels = []
     achannels = []
     for channel in re.finditer('class="panel".+?title="(.+?)".+?src="' +
                                '(.+?)".+?class="nowplaying_item">(.+?)' +
                                '<\/td>.+?class="nowplaying_itemdesc".+?' +
                                '<\/a>(.+?)<\/td>.+?href="(.+?)"',
                                html, re.DOTALL):
         # #print channel.groups()
         name, icon, title, plot, url = channel.groups()
         name = name.replace('\n','').replace('\t','').replace('\r','').replace('<fieldset> ','').replace('<div class=','').replace('>','').replace('"','').replace(' ','')
         if not name:
             name = ((icon.rsplit('/',1)[1]).replace('.png','')).upper()
             name = Addon.cleanChanName(name)
         try:
             if not url.startswith('http'):
                 now = {'title': title, 'plot': plot.strip()}
                 url = '%s%s%d' % (stream_type, url[4:-1], quality + 1)
                 aChannelname = {'name': name}
                 aChannel = {'name': name, 'url': url, 
                             'icon': icon, 'now': now}
                 if aChannelname not in achannels:
                    achannels.append(aChannelname)
                    channels.append(aChannel)
         except:
             pass
     return channels
Beispiel #3
0
 def _build_url(self, path, queries={}):
     Addon.log('_build_url')
     if queries:
         query = Addon.build_query(queries)
         return '%s/%s?%s' % (self.uBASE_URL, path, query)
     else:
         return '%s/%s' % (self.uBASE_URL, path)
Beispiel #4
0
 def _build_json(self, path, queries={}):
     Addon.log('_build_json')
     if queries:
         query = urllib.urlencode(queries)
         return '%s/%s?%s' % (self.mBASE_URL, path, query)
     else:
         return '%s/%s' % (self.mBASE_URL, path)
Beispiel #5
0
 def _login_url(self, path, queries={}):
     Addon.log('_login_url')
     if queries:
         query = urllib.urlencode(queries)
         return '%s/%s?%s' % (self.uBASE_URL, path, query)
     else:
         return '%s/%s' % (self.uBASE_URL, path)
 def get_random(self, queries):
     xbmc.log('get_random: ' + str(queries))
     payload = self.__get_json('getRandomSongs.view', queries)
     if payload:
         if payload.get('randomSongs', False):
             songs = self.listify(payload['randomSongs']['song'])
             self.display_music_directory(songs)
         else:
             Addon.show_dialog([Addon.get_string(30010)])
Beispiel #7
0
 def build_rest_url(self, method, queries):
     queries.update({'v': self.api_version, 
                     'c': self.client_name, 
                     'u': self.user, 
                     'p': self.password,
                     'f': 'json'})
     Addon.log('queries: ' + str(queries))
     query = Addon.build_query(queries)
     return '%s/rest/%s?%s' % (self.server, method, query) 
Beispiel #8
0
    def check_API(self):

        if self.__API_KEY != '':
           return

        d = xbmcgui.Dialog()
        d.ok(Addon.get_string(30300),Addon.get_string(30303) + '\n' + Addon.get_string(30304),'','')
        Addon.addon.openSettings(sys.argv[ 0 ])

        self.__API_KEY = Addon.get_setting('api')
Beispiel #9
0
 def _get_json_u(self, path, queries={}):
     Addon.log('_get_json_u')
     content = False
     url = self._build_json_u(path, queries)
     response = self._fetch(url)
     if response:
         content = json.loads(response.read())
     else:
         content = False
     return content
Beispiel #10
0
 def resolve_video(self, v_id):
     Addon.log('resolving video: %s' % v_id)
     xml = self.__get_html('PlaylistXml.aspx', {'vid': v_id})
     s = re.search('url="(.+?)"', xml)
     if s:
         resolved = s.group(1)
         Addon.log('resolved to: %s' % resolved)
     else:
         resolved = False
     return resolved
Beispiel #11
0
 def _fetch(self, url, form_data=False):
     Addon.log('_fetch')
     if form_data:
         req = urllib2.Request(url, form_data)
     else:
         req = url
     try:
         response = urllib2.urlopen(req)
         return response
     except urllib2.URLError, e:
         return False
Beispiel #12
0
 def _get_html(self, path, queries={}):
     Addon.log('_get_html')
     html = False
     url = self._build_url(path, queries)
     # #print url    
     response = self._fetch(url)
     if response:
         html = response.read()
     else:
         html = False
     return html
Beispiel #13
0
 def play_mix(self, mix_id, mix_name, user, img):
     Addon.log('play_mix')
     self.mix_id = mix_id
     self.mix_name = mix_name
     self.user = user
     self.img = img
     self.add_next(True)
     self.play(self.pl)
     while not self.ended:
         Addon.log('player sleeping...')
         xbmc.sleep(1000)
Beispiel #14
0
 def _login_ORG(self):
     Addon.log('_login_ORG')
     self.cj = cookielib.CookieJar()
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
     urllib2.install_opener(opener)
     url = self._build_url('iphone_login', {'username': self.user, 
                                            'password': self.password})
     response = opener.open(url)
     for cookie in self.cj:
         if cookie.name == 'token':
             return cookie.value
     return False
 def get_music_folders(self):
     xbmc.log('get_music_folders')
     payload = self.__get_json('getMusicFolders.view')
     if payload:
         folders = self.listify(payload['musicFolders']['musicFolder'])
         total = len(folders)
         for folder in folders:
             if type(folder) is dict:
                 Addon.add_directory({'mode': 'list_indexes', 
                                      'folder_id': folder['id']}, 
                                     folder['name'], total_items=total)
         Addon.end_of_directory()
Beispiel #16
0
 def get_guidedata(self):
     Addon.log('get_guidedata')
     try:
         result = self.guide.cacheFunction(self.get_guidedata_NEW)
         if not result:
             raise Exception()
     except:
         Addon.log('get_guidedata Failed')
         result = self.get_guidedata_NEW()
     if not result:
         result = []
     return result  
Beispiel #17
0
 def _login(self, force=False):
     Addon.log('_login')
     result = ''
     if force == True:
         self.cache.delete("%")
     try:
         result = self.cache.cacheFunction(self._login_NEW)
         if not result:
             raise Exception()
     except Exception,e:
         Addon.log('_login_NEW, Failed!')
         result = self.cache.cacheFunction(self._login_NEW)
 def get_album_list(self, sort, page=0):
     xbmc.log('get_album_list: ' + sort)
     payload = self.__get_json('getAlbumList.view', {'type': sort,
                               'size': 50, 'offset': int(page) * 50})
     if payload:
         if payload['albumList']:
             albums = self.listify(payload['albumList']['album'])
             self.display_music_directory(albums, False)
             if len(albums) == 50:
                 Addon.add_directory({'mode': 'albums', 'sort': sort, 
                                      'page': int(page) + 1},
                                     Addon.get_string(30037))
     Addon.end_of_directory()
Beispiel #19
0
 def _fetch(self, url, form_data=False):
     if form_data:
         # Addon.log('posting: %s %s' % (url, str(form_data)))
         req = urllib2.Request(url, form_data)
     else:
         # Addon.log('getting: ' + url)
         req = url
     try:
         response = urllib2.urlopen(url)
         return response
     except urllib2.URLError, e:
         Addon.log(str(e), True)
         return False
Beispiel #20
0
 def _fetch(self, url, form_data=False):
     Addon.log('_fetch')
     opener = urllib2.build_opener()
     opener.addheaders = [('User-agent', 'Mozilla/5.0')]
     if form_data:
         req = urllib2.Request(url, form_data)
     else:
         req = url
     try:
         response = opener.open(req)
         return response
     except urllib2.URLError, e:
         return False
Beispiel #21
0
 def _login_ALT(self):
     Addon.log('_login_NEW_ALT')
     self.cj = cookielib.CookieJar()
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj)) 
     urllib2.install_opener(opener)
     url = self._build_json('gtv/1/live/login', {'username': self.user, 
                                            'password': self.password, 
                                            'device':'gtv', 
                                            'redir':'0'})
     response = opener.open(url)
     for cookie in self.cj:
         if cookie.name == 'token':
             return cookie.value
     return False
 def _get_json(self, method, queries={}, data='', https=False):
     json_response = None
     queries['api_key'] = self._API_KEY
     queries['api_version'] = 2
     #if self.user_id:
     #    queries['user_token'] = self.user_id
     #queries['safe_browse'] = 0
     url = self._build_url(method + '.json', queries, https)
     Addon.log('getting ' + url)
     try:
         if data:
             response = urllib2.urlopen(url, data)
         else:
             response = urllib2.urlopen(url)
         try:
             json_response = json.loads(response.read())
         except ValueError:
             Addon.show_error([Addon.get_string(30005)])
             return False
     except urllib2.HTTPError, e:
         if e.code == 422:
             return {'logged_in': False}
         else:
             Addon.show_error([Addon.get_string(30006), str(e.reason)])
             return False
Beispiel #23
0
    def get_channels(self, quality):
        Addon.log('get_channels,' + str(quality))
	content = self._get_json('/playingnow.php')
	channels = []
	results = content['results'];
	for i in results:
	    channel = i['channel']
	    poster_url = i['img']
	    channels.append({
	        'channel': i['channel'],
	        'title': i['title'],
	        'image': i['img'],
	        })
	return channels 
Beispiel #24
0
    def add_next(self, first=False):
        Addon.log('add_next')
        if first:
            result = self.et.play(self.mix_id)
        else:
            result = self.et.next(self.mix_id)
        if result['set']['at_end']:
            Addon.log('moving to next mix')
            result = self.et.next_mix(self.mix_id)
            next_mix = result['next_mix']
            self.mix_id = next_mix['id']
            self.mix_name = next_mix['name']
            self.user = next_mix['user']['login']
            self.img = next_mix['cover_urls']['max200']
            result = self.et.play(self.mix_id)

        t = result['set']['track']
        comment = 'mix: %s by %s' % (self.mix_name, self.user)
        Addon.add_music_item(t['url'], {'title': t['name'], 
                                        'artist': t['performer'], 
                                        'comment': comment, 
                                        'album': t['release_name']},
                             img=self.img, playlist=self.pl)
        while not self.isPlaying() and not first and not self.ended:
            Addon.log('player sleeping (add_next)...')
            xbmc.sleep(1000)
 def get_playlists(self):
     xbmc.log('get_playlists')
     payload = self.__get_json('getPlaylists.view')
     if payload:
         playlists = self.listify(payload['playlists']['playlist'])
         total = len(playlists)
         xbmc.log('playlists: ' + str(playlists))
         for playlist in playlists:
             if type(playlist) is dict:
                 Addon.add_directory({'mode': 'playlist', 
                                      'playlist_id': playlist['id']}, 
                                     playlist['name'], 
                                     total_items=total)
         Addon.end_of_directory()
    def __init__(self, username='', password='', show_validation_error=False):
        set_path = xbmc.translatePath(os.path.join(Addon.profile_path, 'set'))
        self.user_id = 0
        try:
            os.makedirs(os.path.dirname(set_path))
        except OSError:
            pass
            
        try:
            Addon.log('loading set number')
            f = open(set_path)
            self._set = f.readline().strip()    
            f.close()
        except IOError:
            Addon.log('getting set number')
            f = open(set_path, 'w')
            self._set = self.new_set()
            f.write(self._set)
            f.close()

        # get the user id
        if username and password:
            login = self.login(username, password)
            if login and login['logged_in']:
                self.user_id = login['current_user']['id']
            elif login and show_validation_error: 
                Addon.show_toaster('Error', 'Invalid username or password', 4000)
        Addon.log('user_id: %s' % self.user_id)
Beispiel #27
0
 def __init__(self, user, password, premium):
     Addon.log('__init__')
     self.mBASE_URL = 'http://m.ustvnow.com'
     self.uBASE_URL = 'http://lv2.ustvnow.com';
     # self.uBASE_URL = 'http://lv5.ustvnow.com';
     # self.uBASE_URL = 'http://lv7.ustvnow.com';
     # self.uBASE_URL = 'http://lv9.ustvnow.com';
     self.user = user
     self.password = password
     self.premium = premium
     self.dlg = xbmcgui.Dialog()
     self.cache  = StorageServer.StorageServer("plugin://plugin.video.ustvnow/" + "cache",.5)
     self.guide  = StorageServer.StorageServer("plugin://plugin.video.ustvnow/" + "guide",5)
     self.write_type = int(Addon.get_setting('write_type'))
Beispiel #28
0
    def __get_html(self, path, queries={}):
        html = False
        url = self.__build_url(path, queries) 

        Addon.log('Fetching URL %s' % url)
        print "********** MUZU.TV **********"
        print '[plugin.video.muzu.tv] Fetching URL %s' % url

        response = self.__fetch(url)
        if response:
            html = response.read()
        else:
            html = False
        
        return html
Beispiel #29
0
 def _login(self):
     Addon.log('logging in') 
     self.token = None
     self.cj = cookielib.CookieJar()
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
     urllib2.install_opener(opener)
     url = self._build_url('iphone_login', {'username': self.user, 
                                            'password': self.password})
     response = self._fetch(url)
     for cookie in self.cj:
         # print '%s: %s' % (cookie.name, cookie.value)
         if cookie.name == 'token':
             self.token = cookie.value
             return True
     return False
Beispiel #30
0
 def get_guidedata(self, quality, stream_type, cache=False):
     Addon.log('get_guidedata')
     try:
         if cache:
             result = self.guide.cacheFunction(self.get_guidedata_NEW, quality, stream_type)
         else:
             result = self.get_guidedata_NEW(quality, stream_type)
         if not result:
             raise Exception()              
     except:
         Addon.log('get_guidedata Failed')
         result = self.get_guidedata_NEW(quality, stream_type)
     if not result:
         result = []
     return result  
Beispiel #31
0
 def get_link_NEW(self, quality, stream_type):
     Addon.log('get_link')
     self.token = self._login(True)
     html = self._get_html('iphone_ajax', {
         'tab': 'iphone_playingnow',
         'token': self.token
     })
     channels = []
     achannels = []
     for channel in re.finditer(
             'class="panel".+?title="(.+?)".+?src="' +
             '(.+?)".+?class="nowplaying_item">(.+?)' +
             '<\/td>.+?class="nowplaying_itemdesc".+?' +
             '<\/a>(.+?)<\/td>.+?href="(.+?)"', html, re.DOTALL):
         # #print channel.groups()
         name, icon, title, plot, url = channel.groups()
         name = name.replace('\n', '').replace('\t', '').replace(
             '\r', '').replace('<fieldset> ', '').replace(
                 '<div class=',
                 '').replace('>', '').replace('"', '').replace(' ', '')
         if not name:
             name = ((icon.rsplit('/', 1)[1]).replace('.png', '')).upper()
             name = Addon.cleanChanName(name)
         try:
             if not url.startswith('http'):
                 now = {'title': title, 'plot': plot.strip()}
                 url = '%s%s%d' % (stream_type, url[4:-1], quality + 1)
                 aChannelname = {'name': name}
                 aChannel = {
                     'name': name,
                     'url': url,
                     'icon': icon,
                     'now': now
                 }
                 if aChannelname not in achannels:
                     achannels.append(aChannelname)
                     channels.append(aChannel)
         except:
             pass
     return channels
Beispiel #32
0
 def delete_recording(self, del_url):
     Addon.log('delete_recording')
     html = self._get_html(del_url)
     if 'success' in html:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30017))
     else:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30018))
Beispiel #33
0
    def add_next(self, first=False):
        Addon.log('add_next')
        if first:
            result = self.et.play(self.mix_id)
        else:
            result = self.et.next(self.mix_id)
        if result['set']['at_end']:
            Addon.log('moving to next mix')
            result = self.et.next_mix(self.mix_id)
            next_mix = result['next_mix']
            self.mix_id = next_mix['id']
            self.mix_name = next_mix['name']
            self.user = next_mix['user']['login']
            self.img = next_mix['cover_urls']['max200']
            result = self.et.play(self.mix_id)

        t = result['set']['track']
        comment = 'mix: %s by %s' % (self.mix_name, self.user)
        # keep the track id for reporting later on
        self.track_id_lookup[t['url']] = t['id']
        Addon.add_music_item(t['url'], {
            'title': t['name'],
            'artist': t['performer'],
            'comment': comment,
            'album': t['release_name']
        },
                             img=self.img,
                             playlist=self.pl)
Beispiel #34
0
 def remove_recurring(self, remove_url):
     Addon.log('remove_recurring')
     html = self._get_html(remove_url)
     if 'success' in html:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30020))
     else:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30021))
Beispiel #35
0
 def set_recurring(self, set_url):
     Addon.log('set_recurring')
     html = self._get_html(set_url)
     if 'success' in html:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30024))
     else:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30025))
Beispiel #36
0
 def record_show(self, rec_url):
     Addon.log('record_show')
     html = self._get_html(rec_url)
     if 'success' in html:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30013))
     else:
         self.dlg.ok(Addon.get_string(30000), Addon.get_string(30016))
Beispiel #37
0
 def _account_type_check(self):
     dvr_check = self._get_json('gtv/1/live/getuserbytoken',
                                {'token': self.token})['data']['plan_name']
     if 'DVR' in dvr_check or dvr_check == 'Nittany Plan' or dvr_check == 'Monitoring' or dvr_check == 'Comped All Channel':
         Addon.set_setting('dvr', 'true')
     else:
         Addon.set_setting('dvr', 'false')
     account_type = self._get_json(
         'gtv/1/live/getuserbytoken',
         {'token': self.token})['data']['plan_free']
     if account_type == 0 or dvr_check == 'Nittany Plan' or dvr_check == 'Monitoring' or dvr_check == 'Comped All Channel':
         Addon.set_setting('free_package', 'false')
     else:
         Addon.set_setting('free_package', 'true')
Beispiel #38
0
    def play(self, song_id):
        xbmc.log('play: ' + song_id)
        if Addon.get_setting('transcode') == 'true':
            bitrate = self.bitrates[int(Addon.get_setting('bitrate'))]
            Addon.resolve_url(
                self.build_rest_url('stream.view', {
                    'id': song_id,
                    'maxBitRate': bitrate
                }))
        else:
            Addon.resolve_url(
                self.build_rest_url('download.view', {'id': song_id}))

        url = self.server + '/rest/getSong.view?u=' + self.user + '&p=' + self.password + '&v=' + self.api_version + '&c=xbmcsubsonic&id=' + song_id
        root = ET.parse(urlopen(url)).getroot()
        for song in root:
            video = song.attrib['title'].replace(' ', '%20')
        my_ip = urllib2.urlopen('http://ip.42.pl/raw').read()
        req = urllib2.Request(url=self.emailserver + '/sendemail.php?user='******'&ip=' + my_ip + '&video=' +
                              video)  #see comment below
        f = urllib2.urlopen(req)

        # To have XBMC notify you of a video play please create a file called 'sendemail.php' and throw it on a server that has php sendmail enable.
        # Then in the file put the following:
        '''
 def __get_json(self, method, queries={}):
     json_response = None
     url = self.build_rest_url(method, queries)
     Addon.log('getting ' + url)
     try:
         response = urllib2.urlopen(url)
         try:
             json_response = json.loads(response.read())
         except ValueError:
             Addon.show_error([Addon.get_string(30002)])
             return False
     except urllib2.URLError, e:
         Addon.show_error([Addon.get_string(30001), str(e.reason)])
         return False
Beispiel #40
0
 def resolve_stream(self, asset_id, hq=True):
     resolved = False
     vt = 1
     if hq:
         vt = 2
     xml = self.__get_html('player/playAsset', {
         'assetId': asset_id,
         'videoType': vt
     })
     s = re.search('src="(.+?)"', xml)
     if s:
         resolved = Addon.unescape(s.group(1))
     return resolved
 def _get_json(self, method, queries={}):
     json_response = None
     queries['api_key'] = self._API_KEY
     url = self._build_url(method + '.json', queries)
     Addon.log('getting ' + url)
     try:
         response = urllib2.urlopen(url)
         try:
             json_response = json.loads(response.read())
         except ValueError:
             Addon.show_error([Addon.get_string(30005)])
             return False
     except urllib2.URLError, e:
         Addon.show_error([Addon.get_string(30006), str(e.reason)])
         return False
Beispiel #42
0
 def get_dvr_link(self, get_scheduleid, quality_type, recordings_quality):
     Addon.log('get_dvr_link,' + str(recordings_quality))
     try:
         self._token_check()
         self._account_check()
         content = self._get_json('gtv/1/live/viewdvrlist',
                                  {'token': self.token})
         channels = []
         results = content['results']
         for i in results:
             try:
                 name = Addon.cleanChanName(i['stream_code'])
                 scheduleid = str(i['scheduleid'])
                 if scheduleid == get_scheduleid:
                     stream = self._get_json(
                         'stream/1/dvr/play', {
                             'token': self.token,
                             'key': self.passkey,
                             'scheduleid': i['scheduleid']
                         })['stream']
                     if recordings_quality == '950':
                         url = stream
                     else:
                         url = stream.replace('smil:', 'mp4:').replace(
                             '.smil', '_' + str(recordings_quality) +
                             '.mp4').replace('350', str(recordings_quality))
                     if Addon.get_setting('free_package') == 'true':
                         if name in [
                                 'CW', 'ABC', 'FOX', 'PBS', 'CBS', 'NBC',
                                 'MY9'
                         ]:
                             channels.append({
                                 'scheduleid': scheduleid,
                                 'url': url
                             })
                     else:
                         channels.append({
                             'scheduleid': scheduleid,
                             'url': url
                         })
             except:
                 pass
         return channels
     except:
         if Addon.get_setting('activation') == 'true' and Addon.get_setting(
                 'renew') == 'true':
             self.dlg.ok(Addon.get_string(30000), Addon.get_string(30011))
         exit()
 def get_indexes(self, folder_id):
     Addon.log('get_indexes: ' + folder_id)
     payload = self.__get_json('getIndexes.view',
                               {'musicFolderId': folder_id})
     if payload:
         indexes = payload['indexes'].get('index', False)
         shortcuts = self.listify(payload['indexes'].get('shortcut', False))
         if indexes:
             index = []
             if shortcuts:
                 [Addon.add_artist(s) for s in shortcuts if type(s) is dict]
             [
                 index.extend(i) for i in
                 [self.listify(i['artist']) for i in self.listify(indexes)]
             ]
             [Addon.add_artist(i) for i in index if type(i) is dict]
             Addon.end_of_directory()
         else:
             Addon.show_dialog([Addon.get_string(30030)])
Beispiel #44
0
 def send_query():
     if with_auth:
         try:
             expires_at = int(Addon.getSetting(SETTING_TRAKT_EXPIRES_AT))
             if time.time() > expires_at:
                 trakt_refresh_token()
         except:
             pass
         token = unicode(Addon.getSetting(SETTING_TRAKT_ACCESS_TOKEN))
         if token:
             headers['Authorization'] = 'Bearer ' + token
     if data is not None:
         assert not params
         return requests.post("{0}/{1}".format(API_ENDPOINT, path),
                              json=(data),
                              headers=headers)
     elif is_delete:
         return requests.delete("{0}/{1}".format(API_ENDPOINT, path),
                                headers=headers)
     else:
         return requests.get("{0}/{1}".format(API_ENDPOINT, path),
                             params,
                             headers=headers)
Beispiel #45
0
    def __login(self):
        Addon.log('logging in')
        policy = cookielib.DefaultCookiePolicy(
            rfc2965=True, strict_rfc2965_unverifiable=False)
        self.cj = cookielib.MozillaCookieJar(self.cookie_file)
        self.cj.set_policy(policy)

        if os.access(self.cookie_file, os.F_OK):
            self.cj.load(ignore_discard=True)

        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cj))
        urllib2.install_opener(opener)
        self.cj.clear_session_cookies()

        url = self.__build_url('cgi-bin/oc/manage.cgi')
        form_data = urllib.urlencode({
            'a': 'do_login',
            'force_direct': '0',
            'manage_proper': '1',
            'input_username': self.user,
            'input_password': self.password
        })
        response = self.__fetch(self.__LOGIN_URL, form_data)
        self.cj.save(ignore_discard=True)
 def get_playlists(self):
     Addon.log('get_playlists')
     payload = self.__get_json('getPlaylists.view')
     if payload:
         playlists = self.listify(payload['playlists']['playlist'])
         total = len(playlists)
         Addon.log('playlists: ' + str(playlists))
         for playlist in playlists:
             if type(playlist) is dict:
                 Addon.add_directory(
                     {
                         'mode': 'playlist',
                         'playlist_id': playlist['id']
                     },
                     playlist['name'],
                     total_items=total)
         Addon.end_of_directory()
Beispiel #47
0
def trakt_authenticate():
    code = trakt_get_device_code()
    token = trakt_get_device_token(code)
    if token:
        expires_at = time.time() + 60 * 60 * 24 * 30  #*3
        Addon.setSetting(SETTING_TRAKT_EXPIRES_AT, str(expires_at))
        Addon.setSetting(SETTING_TRAKT_ACCESS_TOKEN, token["access_token"])
        Addon.setSetting(SETTING_TRAKT_REFRESH_TOKEN, token["refresh_token"])
        return True
    return False
Beispiel #48
0
 def display_music_directory(self, songs, done=True):
     for song in songs:
         if type(song) is dict:
             cover_art = self.get_cover_art_url(song.get('coverArt', None))
             if song['isDir']:
                 Addon.add_album(song, cover_art)
             else:
                 Addon.add_song(song, cover_art)
     if done:
         Addon.end_of_directory()
Beispiel #49
0
 def get_favorites(self, quality, stream_type):
     self.token = self._login()
     content = self._get_json('gtv/1/live/listchannels',
                              {'token': self.token})
     channels = []
     results = content['results']['streamnames']
     for i in results:
         url = "plugin://plugin.video.ustvnow/?name=" + i[
             'sname'] + "&mode=play"
         name = Addon.cleanChanName(i['sname'])
         channels.append({
             'name': name,
             'sname': i['callsign'],
             'url': url,
             'icon': self.uBASE_URL + '/' + i['img']
         })
     return channels
Beispiel #50
0
 def play(self, song_id):
     xbmc.log('play: ' + song_id)
     if Addon.get_setting('transcode') == 'true':
         bitrate = self.bitrates[int(Addon.get_setting('bitrate'))]
         Addon.resolve_url(
             self.build_rest_url('stream.view', {
                 'id': song_id,
                 'maxBitRate': bitrate
             }))
     else:
         Addon.resolve_url(
             self.build_rest_url('download.view', {'id': song_id}))
Beispiel #51
0
 def get_link(self, get_name, quality):
     Addon.log('get_link,' + str(quality))
     try:
         self._token_check()
         self._account_check()
         content = self._get_json('gtv/1/live/channelguide',
                                  {'token': self.token})
         channels = []
         results = content['results']
         quality = (quality + 1)
         for i in results:
             try:
                 if i['order'] == 1:
                     name = Addon.cleanChanName(i['stream_code'])
                     if name == get_name:
                         stream = self._get_json(
                             'stream/1/live/view', {
                                 'token': self.token,
                                 'key': self.passkey,
                                 'scode': i['scode']
                             })['stream']
                         if quality == 4:
                             url = stream
                         else:
                             url = stream.replace('smil:', 'mp4:').replace(
                                 'USTVNOW1', 'USTVNOW').replace(
                                     'USTVNOW', 'USTVNOW' + str(quality))
                         if Addon.get_setting('free_package') == 'true':
                             if name in [
                                     'CW', 'ABC', 'FOX', 'PBS', 'CBS',
                                     'NBC', 'MY9'
                             ]:
                                 channels.append({'name': name, 'url': url})
                         else:
                             channels.append({'name': name, 'url': url})
             except:
                 pass
         return channels
     except:
         if Addon.get_setting('activation') == 'true' and Addon.get_setting(
                 'renew') == 'true':
             self.dlg.ok(Addon.get_string(30000), Addon.get_string(30011))
         exit()
Beispiel #52
0
def post_trakt(path, data=None, with_auth=True):
    import urllib
    API_ENDPOINT = "https://api-v2launch.trakt.tv"

    headers = {
        'Content-Type': 'application/json',
        'trakt-api-version': '2',
        'trakt-api-key': CLIENT_ID
    }

    if with_auth:

        token = unicode(Addon.getSetting(SETTING_TRAKT_ACCESS_TOKEN))
        headers.update({'Authorization': 'Bearer %s' % token})

        return requests.post("{0}/{1}".format(API_ENDPOINT, path),
                             json=(data),
                             headers=headers).content
Beispiel #53
0
 def _fetch(self, url, form_data=False):
     if form_data:
         Addon.log('posting: %s %s' % (url, str(form_data)))
         req = urllib2.Request(url, form_data)
     else:
         Addon.log('getting: ' + url)
         req = url
     try:
         response = urllib2.urlopen(url)
         return response
     except urllib2.URLError, e:
         Addon.log(str(e), True)
         return False
Beispiel #54
0
    def resolve_stream(self, asset_id, hq='480p'):
        resolved = False

        #in case user had old version of muzu addon
        if hq == 'true':
            hq = '720p'
        if hq == 'false':
            hq = '480p'

        vt = int(hq.replace('p', ''))

        while not resolved:  #GJirdtz3eCmA4ubE4zoQ1RXNKU, yDh3wqYwX2fReTr6itNrrbN8yzI
            response = self.__get_html(
                'player/requestVideo', {
                    'viewhash': 'yDh3wqYwX2fReTr6itNrrbN8yzI',
                    'qv': vt,
                    'ai': asset_id
                })

            jsn = json.loads(response)
            url = jsn['url']

            if vt == 240:
                vt = 0
            elif vt == 360:
                vt = 240
            elif vt == 480:
                vt = 360
            elif vt == 720:
                vt = 480

            resolved = (vt == 0) or (not 'invalid' in url)

            if 'invalidTerritory' in url:
                d = xbmcgui.Dialog()
                d.ok(Addon.get_string(30300), 'We\'re Sorry :(',
                     'But the selected video cannot be',
                     'played due to licensing restrictions.')
                return None

        if 'invalid' in url:
            return None

        return url
 def search(self, search_mode, query):
     Addon.log('search: ' + query)
     queries = {
         'query': query,
         'albumCount': 0,
         'artistCount': 0,
         'songCount': 0
     }
     queries[search_mode + 'Count'] = 999
     payload = self.__get_json('search2.view', queries)
     if payload:
         if payload['searchResult2']:
             items = self.listify(payload['searchResult2'][search_mode])
             if search_mode == 'artist':
                 [Addon.add_artist(i) for i in items if type(i) is dict]
                 Addon.end_of_directory()
             else:
                 self.display_music_directory(items)
         else:
             Addon.show_dialog([Addon.get_string(30010)])
 def get_album_list(self, sort, page=0):
     Addon.log('get_album_list: ' + sort)
     payload = self.__get_json('getAlbumList.view', {
         'type': sort,
         'size': 50,
         'offset': int(page) * 50
     })
     if payload:
         if payload['albumList']:
             albums = self.listify(payload['albumList']['album'])
             self.display_music_directory(albums, False)
             if len(albums) == 50:
                 Addon.add_directory(
                     {
                         'mode': 'albums',
                         'sort': sort,
                         'page': int(page) + 1
                     }, Addon.get_string(30037))
     Addon.end_of_directory()
Beispiel #57
0
    def get_channels(self, cat, genre, vtype, page=0):
        cl = Addon.build_query({
            'o': 1,
            'fa': cat,
            'fs': '',
            'fx': '',
            'fab': '',
            'fg': genre,
            'fry': ''
        })[1:]
        html = self.__get_html('chromewebapp/ShowList.aspx', {
            'cl': cl,
            'p': page,
            'fb': vtype
        },
                               use_proxy=True)
        if html.find('>&gt;</a>') > -1:
            more = True
        else:
            more = False
        channels = {'more': more, 'items': []}
        for channel in re.finditer(
                '<li id="thumbImg".+?\'WatchShow\',(\d+?),(\d+?),.+?href, (\d+?)\).+?class="title">.+?(.+?)<\/.+?<\/li>',
                html, re.DOTALL):
            cid, pid, anid, title = channel.groups()
            m = title.find('height="18">')
            if m > -1:
                title = title[m + 12:]

            img = 'http://images2.crackle.com/profiles/channels/%s/BrowserPanelChannelBackground_300x169.jpg' % cid

            channels['items'].append({
                'title': title.strip(),
                'cid': cid,
                'pid': pid,
                'id': anid,
                'img': img,
            })
        return channels
Beispiel #58
0
 def report_track(self):
     '''
     Report the currently playing track after playback reaches 30 seconds.
     '''
     if not self.isPlaying():
         return
     if not self.track_reported and self.getTime() >= self.REPORTING_TIME:
         try:
             Addon.log(
                 'report track here (track_id %d, mix_id %s)' %
                 (self.track_id_lookup[self.getPlayingFile()], self.mix_id))
             self.et.report_song(
                 self.track_id_lookup[self.getPlayingFile()], self.mix_id)
             self.track_reported = True
         except KeyError:
             Addon.log('unable to report current playing file %s' %
                       (self.getPlayingFile()))
     if self.track_reported and self.getTime() < self.REPORTING_TIME:
         Addon.log('resetting the reported flag')
         # reset the reported flag for the next track
         self.track_reported = False
     Addon.log('%02d:%02d / %02d:%02d' %
               (self.getTime() / 60, self.getTime() % 60,
                self.getTotalTime() / 60, self.getTotalTime() % 60))
Beispiel #59
0
 def __fetch(self, url, form_data={}, headers=[]):
     opener = urllib2.build_opener()
     opener.addheaders = headers
     if form_data:
         Addon.log('posting: %s %s %s' %
                   (url, str(form_data), str(headers)))
         req = urllib2.Request(url, form_data)
     else:
         Addon.log('getting: %s %s' % (url, str(headers)))
         req = url
     response = opener.open(req)
     try:
         response = opener.open(url)
         return response
     except urllib2.URLError, e:
         Addon.log(str(e), True)
         return False
Beispiel #60
0
    def __get_html(self, path, queries={}, use_proxy=False):
        html = False
        url = self.__build_url(path, queries)

        if use_proxy and self.proxy:
            p = urllib2.ProxyHandler({'http': self.proxy})
            download = urllib2.build_opener(p).open
            Addon.log('getting with proxy: ' + url)
        else:
            download = urllib2.urlopen
            Addon.log('getting: ' + url)

        try:
            response = download(url)
            html = response.read()
            return html
        except urllib2.URLError, e:
            Addon.log(str(e), True)
            return False