Пример #1
0
    def system(self, data, cl=False):
        util.debug("[SC] SYSYEM CL: %s" % str(cl));
        if cl is False and "setContent" in data:
            xbmcplugin.setContent(int(sys.argv[1]), data["setContent"])
            '''
            view_mode=data["setContent"].lower()
            skin_name=xbmc.getSkinDir() # nacitame meno skinu
            util.debug("[SC] skin_name='"+skin_name+"'")
            try:
                util.debug("[SC] view mode is "+view_mode)
                view_codes=sctop.ALL_VIEW_CODES.get(view_mode)
                view_code=view_codes.get(skin_name)
                util.debug("[SC] view code for "+view_mode+" in "+skin_name+" is "+str(view_code))
                xbmc.executebuiltin("Container.SetViewMode("+str(view_code)+")")
                #xbmc.executebuiltin("Container.Refresh")
            except:
                util.debug("[SC] Unable to find view code for view mode "+str(view_mode)+" and skin "+skin_name)
            '''
                
        if cl is False and "setPluginCategory" in data:
            xbmcplugin.setPluginCategory(int(sys.argv[1]), data["setPluginCategory"])
        
        if cl is False and "addSortMethod" in data:
            xbmcplugin.addSortMethod(int(sys.argv[1]), sctop.sortmethod[int(data["addSortMethod"])])

        if cl is False and data.get('addSortMethods'):
            for m in data.get("addSortMethods"):
                xbmcplugin.addSortMethod(int(sys.argv[1]), sctop.sortmethod[int(m)])
        
        if cl is False and "setPluginFanart" in data:
            xbmcplugin.setPluginFanart(int(sys.argv[1]), data["setPluginFanart"])
        
        if cl is False and "version" in data:
            util.info("[SC] kontrola verzie: %s %s" % (str(sctop.addonInfo('version')), data["version"]))
            if sctop.addonInfo('version') != data["version"] and sctop.getSetting('ver') != data['version']:
                try:
                    sctop.dialog.ok(sctop.getString(30954), sctop.getString(30955) % str(data['version']))
                except:
                    pass
                xbmc.executebuiltin('UpdateAddonRepos')
                sctop.setSetting('ver', data['version'])
            if sctop.getSettingAsBool('cachemigrate') == '' or sctop.getSettingAsBool('cachemigrate') is False:
                self.parent.cacheMigrate()
                pass
            pass
        
        if cl is False and "focus" in data:
            self.parent.system = {"focus": data['focus']}
            
        if cl is True and "focus" in data:
            try:
                self.parent.endOfDirectory()
                util.debug("[SC] nastavujem focus na: %d" % int(data['focus']))
                xel = xbmcgui.Window(xbmcgui.getCurrentWindowId())
                ctr = xel.getControl(xel.getFocusId())
                ctr.selectItem(int(data['focus']))
            except Exception as e:
                util.debug("[SC] error focus :-( %s" % str(traceback.format_exc()))
                pass
Пример #2
0
 def _url(self, url):
     if url.startswith('plugin://'):
         return url
     
     if url.startswith('cmd://'):
         if '__self__' in url:
             url.replace('__self__', sctop.__scriptid__)
         return url
     
     if url.startswith('/'):
         url = sctop.BASE_URL + url
     
     if not url.startswith('http'):
         util.debug('[SC] nemame http v URL %s' % url)
         o = urlparse(self.base_url)
     else:
         o = urlparse(url)
     q = parse_qs(o.query)
     q.update({'uid': self.uid, 'ver': sctop.API_VERSION, 'lang': sctop.KODI_LANG})
     if sctop.getSettingAsBool('filter_audio'):
         q.update({'l' : sctop.getSetting('filter_lang.1')})
     if not url.startswith('http'):
         n = [str(o[0]),str(o[1]),str(o[2]).rstrip('./') + '/' + url.lstrip('./'),str(o[3]), '']
     else:
         n = [str(o[0]),str(o[1]),str(o[2]),str(o[3]), '']
     n[3] = urllib.urlencode(q, True)
     nurl = urlunsplit(n)
     return nurl
Пример #3
0
 def get_data_cached(self, url, post=False):
     try:
         url.index('/json/')
         self._oldapi()
     except Exception:
         pass
     headers = {
         'X-UID': self.uid,
         'X-LANG': self.tr['language'],
         'X-VER': sctop.API_VERSION,
         'Accept' : 'application/vnd.bbaron.kodi-plugin-v%s+json' % (sctop.API_VERSION),
     }
     url = self._url(url)
     code = None
     try:
         if post != False:
             util.debug("POST URL: %s %s" % (url, str(post)))
             (ret, code) = sctop.post(url, post, headers, "extend")
             self.handleHttpError(code)
             return ret
         util.info("GET x URL: %s" % url)
         ret = False
         if sctop.getSettingAsBool('usecache') is not False:
             util.debug("[SC] skusam cache")
             ret = self.cache.get(str(url))
         if not ret:
             util.debug("[SC] url BEZ cache %s" % str(url))
             (ret, code, info) = sctop.request(url, headers, "info")
             util.debug("[SC] code: %s %s" % (str(code), str(info)))
             self.handleHttpError(code, data=ret, i=info)
             if code == 200:
                 ttl = datetime.timedelta(hours=2)
                 try:
                     util.debug("[SC] info: %s " % str(info) )
                     if 'x-ttl' in info:
                         ttl = datetime.timedelta(seconds=int(info.get('x-ttl')))
                         util.debug("[SC] mame TTL: %s" % str(ttl))
                 except:
                     pass
                 try:
                     self.cache.cache.set(str(url), ret, expiration=ttl)
                 except:
                     self.cache.set(str(url), ret)
         else:
             util.debug("[SC] url z cache %s" % str(url))
         util.debug("[SC] return data")
         return ret
     except Exception as e:
         inet = sctop.getCondVisibility('System.InternetState')
         util.debug("[SC] inet scinema status: %s | %s" % (str(inet), str(e)))
         if inet is False or inet == 0:
             HANDLE = int(sys.argv[1])
             xbmcplugin.endOfDirectory(HANDLE, succeeded=False)
             sctop.dialog.ok("internet", 'Skontrolujte pripojenie na internet')
             return False
         util.error('[SC] ERROR URL: --------- %s --------' % str(traceback.format_exc()) )
         if code is None:
             sctop.dialog.ok("error", url)
         return False
Пример #4
0
 def get_data_cached(self, url, post=False):
     try:
         url.index('/json/')
         self._oldapi()
     except Exception:
         pass
     headers = {
         'X-UID':
         self.uid,
         'X-LANG':
         self.tr['language'],
         'X-VER':
         sctop.API_VERSION,
         'Accept':
         'application/vnd.bbaron.kodi-plugin-v%s+json' %
         (sctop.API_VERSION),
     }
     url = self._url(url)
     code = None
     try:
         if post != False:
             util.debug("POST URL: %s %s" % (url, str(post)))
             (ret, code) = sctop.post(url, post, headers, "extend")
             self.handleHttpError(code)
             return ret
         util.info("GET x URL: %s" % url)
         ret = False
         if sctop.getSettingAsBool('usecache') is not False:
             util.debug("[SC] skusam cache")
             ret = self.cache.get(str(url))
         if not ret:
             util.debug("[SC] url BEZ cache %s" % str(url))
             (ret, code, info) = sctop.request(url, headers, "info")
             util.debug("[SC] code: %s %s" % (str(code), str(info)))
             self.handleHttpError(code, data=ret, i=info)
             if code == 200:
                 ttl = datetime.timedelta(hours=2)
                 try:
                     util.debug("[SC] info: %s " % str(info))
                     if 'x-ttl' in info:
                         ttl = datetime.timedelta(
                             seconds=int(info.get('x-ttl')))
                         util.debug("[SC] mame TTL: %s" % str(ttl))
                 except:
                     pass
                 try:
                     self.cache.cache.set(str(url), ret, expiration=ttl)
                 except:
                     self.cache.set(str(url), ret)
         else:
             util.debug("[SC] url z cache %s" % str(url))
         util.debug("[SC] return data")
         return ret
     except Exception, e:
         util.error('[SC] ERROR URL: ' + str(e))
         if code is None:
             sctop.dialog.ok("error", url)
         return False
    def _url(self, url):
        if url.startswith('plugin://'):
            return url

        if url.startswith('cmd://'):
            if '__self__' in url:
                url.replace('__self__', sctop.__scriptid__)
            return url

        if url.startswith('/'):
            url = sctop.BASE_URL + url

        if not url.startswith('http'):
            util.debug('[SC] nemame http v URL %s' % url)
            o = urlparse(self.base_url)
        else:
            o = urlparse(url)
        q = parse_qs(o.query)
        q.update({
            'uid': self.uid,
            'ver': sctop.API_VERSION,
            'lang': sctop.KODI_LANG,
            'v': sctop.addonInfo('version')
        })

        util.debug(
            '[SC] providers [%s] [%s]' %
            (str(sctop.getSetting('kruser')), str(sctop.getSetting('wsuser'))))
        if sctop.getSetting('kruser') != '' and sctop.getSetting(
                'wsuser') != '':
            q.update({'pro': 'kraska,webshare'})
        elif sctop.getSetting('kruser') != '':
            q.update({'pro': 'kraska'})
        elif sctop.getSetting('wsuser') != '':
            q.update({'pro': 'webshare'})

        if sctop.getSettingAsBool('filter_audio'):
            q.update({'l': sctop.getSetting('filter_lang.1')})
        if not url.startswith('http'):
            n = [
                str(o[0]),
                str(o[1]),
                str(o[2]).rstrip('./') + '/' + url.lstrip('./'),
                str(o[3]), ''
            ]
        else:
            n = [str(o[0]), str(o[1]), str(o[2]), str(o[3]), '']
        n[3] = urllib.urlencode(q, True)
        nurl = urlunsplit(n)
        return nurl
    def onPlayBackStarted(self):
        if self.scid is not None:
            self.onPlayBackStopped()
        self.upNextEnable = True
        self.se = None
        self.ep = None
        self.libItem = None
        self.watchedTime = 0
        self.log("[SC] Zacalo sa prehravat")
        mojPlugin = self.win.getProperty(sctop.__scriptid__)
        if sctop.__scriptid__ not in mojPlugin:
            util.debug("[SC] Nieje to moj plugin ... ")
            return
        util.debug("[SC] JE to moj plugin ... %s" % str(mojPlugin))
        self.scid = self.win.getProperty('scid')
        try:
            self.ids = json.loads(
                self.win.getProperty('%s.ids' % sctop.__scriptid__))
        except:
            self.ids = {}
            pass
        try:
            stream = json.loads(
                self.win.getProperty('%s.stream' % sctop.__scriptid__))
            util.debug("[SC] stream %s" % str(stream))
        except:
            stream = {}
            pass
        self.stream = stream
        self.win.clearProperty(sctop.__scriptid__)
        self.win.clearProperty('%s.ids' % sctop.__scriptid__)
        self.win.clearProperty('%s.stream' % sctop.__scriptid__)
        self.win.clearProperty('scid')
        self.win.clearProperty('scresume')
        try:
            if sctop.getSettingAsBool('filter_audio'):
                util.debug("[SC] skusam vybrat spravne audio")
                self.selectAudio()
            else:
                util.debug("[SC] nemame filter pre audio")
        except:
            util.debug(
                "[SC] XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
            )
            pass
        try:
            if not self.isPlayingVideo():
                return

            self.itemDuration = self.getTotalTime()
            # plánovaný čas dokončení 100 % přehrání
            self.estimateFinishTime = xbmc.getInfoLabel(
                'Player.FinishTime(hh:mm:ss)')
            if 'originaltitle' in stream:
                season = stream.get('season')
                episode = stream.get('episode')
                if episode is not None and season is not None:
                    showtitle = stream.get('originaltitle')
                else:
                    showtitle = None
                year = stream.get('year')
                title = stream.get('originaltitle')
                try:
                    imdb = 'tt%07d' % int(stream.get('imdb')) if stream.get(
                        'imdb').isdigit() else None
                except:
                    imdb = None
                    util.debug("[SC] imdb %s" % str(traceback.format_exc()))
                self.se = season
                self.ep = episode
            else:
                season = xbmc.getInfoLabel('VideoPlayer.Season')
                episode = xbmc.getInfoLabel('VideoPlayer.Episode')
                self.se = season
                self.ep = episode
                showtitle = xbmc.getInfoLabel('VideoPlayer.TVShowTitle')
                year = xbmc.getInfoLabel('VideoPlayer.Year')
                title = xbmc.getInfoLabel('VideoPlayer.Title')
                imdb = xbmc.getInfoLabel(
                    "VideoPlayer.IMDBNumber")  #"ListItem.IMDBNumber")

            if episode is not None:
                util.debug("[SC] Serial")
                self.itemType = 'episode'
            else:
                util.debug("[SC] Film")
                self.itemType = 'movie'

            try:
                if self.itemType == 'movie':
                    method = 'VideoLibrary.GetMovies'
                    try:
                        if self.ids is not None and trakt.getTraktCredentialsInfo(
                        ) == True:
                            #trakt.addTraktCollection({'movies':[{'ids':self.ids}]})
                            pass
                    except:
                        self.log(
                            "[SC] trakt.tv error - nepodarilo sa pridat film do kolekcie: %s"
                            % str(traceback.format_exc()))
                        pass
                    value = "%s (%s).strm" % (self.parent.normalize_filename(
                        str(title)), str(year))
                    field = 'filename'
                    res = self.executeJSON({
                        'jsonrpc': '2.0',
                        'method': method,
                        'params': {
                            'filter': {
                                'operator': 'contains',
                                'field': field,
                                'value': value
                            },
                            'properties': ['file', 'resume'],
                        },
                        'id': 1
                    })

                    if 'result' in res and 'movies' in res['result']:
                        for m in res['result']['movies']:
                            util.debug("[SC] m: %s" % str(m))
                            if 'movieid' in m:
                                self.libItem = m
                                self.itemDBID = m['movieid']
                                break
                else:
                    if self.ids is not None and trakt.getTraktCredentialsInfo(
                    ) == True:
                        #trakt.addTraktCollection({'shows':[{'ids':self.ids}]})
                        pass
                    if self.parent is not None:
                        try:
                            self.parent.addLast(self.scid)
                        except Exception, e:
                            util.error(e)
                            pass

                    method = 'VideoLibrary.GetTVShows'
                    value = self.parent.normalize_filename(
                        str(showtitle)
                    )  #/Season %s/%sx%s.strm" % (showtitle, season, season, episode)
                    field = 'path'
                    res = self.executeJSON({
                        'jsonrpc': '2.0',
                        'method': method,
                        'params': {
                            'filter': {
                                'operator': 'contains',
                                'field': field,
                                'value': value
                            }
                        },
                        'id': 1
                    })

                    if 'result' in res:
                        for m in res['result']['tvshows']:
                            if 'tvshowid' in m:
                                self.itemDBID = int(m['tvshowid'])
                                res = self.executeJSON({
                                    'jsonrpc': '2.0',
                                    'method': 'VideoLibrary.GetEpisodes',
                                    'params': {
                                        'tvshowid': int(m['tvshowid']),
                                        'season': int(season),
                                        'properties':
                                        ['episode', 'file', 'resume'],
                                        'sort': {
                                            'method': 'episode'
                                        }
                                    },
                                    'id': 1
                                })
                                util.info("[SC] tvshow json: %s" % str(res))
                                for e in res['result']['episodes']:
                                    if int(e['episode']) == int(episode):
                                        self.libItem = e
                                        self.itemDBID = e['episodeid']
                                        break
                                break

            except Exception:
                self.log("[SC] Chyba JSONRPC: %s" %
                         str(traceback.format_exc()))
                pass

            res = self.executeJSON({
                'jsonrpc': '2.0',
                'method': 'Player.GetItem',
                'params': {
                    'playerid': 1
                },
                'id': 1
            })
            if res:
                _filename = None
                try:
                    _filename = os.path.basename(self.getPlayingFile())
                except:
                    util.debug(
                        "[SC] onPlayBackStarted() - Exception trying to get playing filename, player suddenly stopped."
                    )
                    return
                util.debug(
                    "[SC] Zacalo sa prehravat: DBID: [%s], SCID: [%s] imdb: %s dur: %s est: %s fi: [%s] | %sx%s - title: %s (year: %s) showtitle: %s"
                    % (str(self.itemDBID), str(
                        self.scid), str(imdb), str(self.itemDuration),
                       self.estimateFinishTime, _filename, str(season),
                       str(episode), str(title), str(year), str(showtitle)))
                data = {
                    'scid': self.scid,
                    'action': 'start',
                    'ep': episode,
                    'se': season
                }
                util.debug("[SC] prehravanie %s" % str(res))

                self.action(data)
                if 'item' in res and 'id' not in res['item']:
                    util.debug("[SC] prehravanie mimo kniznice")
        except Exception:
            self.log("[SC] Chyba MyPlayer: %s" % str(traceback.format_exc()))
            pass

        try:
            if 'resume' in self.libItem:
                util.debug("[SC] resume! %s" % str(self.libItem))
                pos = self.libItem['resume'].get('position', 0)
                maxPos = self.getTotalTime() * .75
                if pos > 3 * 60 and pos < maxPos:
                    self.seekTime(pos)
        except:
            pass
Пример #7
0
def getTrakt(url, post=None, output='content', method=None):
    try:
        use_ssl = sctop.getSettingAsBool('UseSSL')
        url = urlparse.urljoin(
            'http%s://api.trakt.tv' % ('s' if use_ssl else ''), url)

        headers = {'trakt-api-key': sctop.trCL, 'trakt-api-version': '2'}

        if getTraktCredentialsInfo() == False:
            util.debug("[SC] gt 1 data: %s %s" % (str(url), str(post)))
            if post is not None:
                result = util.post_json(url, post, headers)
            else:
                result = util.request(url, headers)
            util.debug("[SC] gt 1 result: %s" % str(result))
            return result

        headers['Authorization'] = 'Bearer %s' % sctop.getSetting(
            'trakt.token')
        #util.debug('[SC] token %s' % sctop.getSetting('trakt.token'))

        if post is not None:
            result, code = sctop.post_json(url, post, headers, "extend")
            info = None
        else:
            result, code, info = sctop.request(url,
                                               headers,
                                               "info",
                                               method=method)
        #util.debug("[SC] trakt gt result: %s %s" % (str(result), str(code)))
        if not (code == 401 or code == 405):
            if output == "content":
                return result
            else:
                return (result, code, info)

        oauth = 'http%s://api.trakt.tv/oauth/token' % ('s' if use_ssl else '')
        opost = {
            'client_id': sctop.trCL,
            'client_secret': sctop.trSC,
            'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
            'grant_type': 'refresh_token',
            'refresh_token': sctop.getSetting('trakt.refresh')
        }

        result, code = sctop.post_json(oauth, opost, headers, "extend")
        if code == 401:
            authTrakt()
            result, code = sctop.post_json(oauth, opost, headers, "extend")
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        sctop.setSetting(setting='trakt.token', value=token)
        sctop.setSetting(setting='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        util.debug('[SC] token: %s' % token)

        result = sctop.post_json(url, post, headers)
        return result
    except Exception as e:
        util.error(e)
        pass
Пример #8
0
def manager(name, trakt, content):
    try:
        icon = sctop.infoLabel('ListItem.Icon')
        message = sctop.getString(30941).encode('utf-8')
        content = "movies" if content == 'movie' else "shows"
        post = {content: [{"ids": {"trakt": trakt}}]}

        items = []
        if sctop.getSettingAsBool('trakt.collections'):
            items = [(sctop.getString(30934).encode('utf-8'),
                      '/sync/collection')]
            items += [(sctop.getString(30935).encode('utf-8'),
                       '/sync/collection/remove')]
        if sctop.getSettingAsBool('trakt.watchlist'):
            items += [(sctop.getString(30936).encode('utf-8'),
                       '/sync/watchlist')]
            items += [(sctop.getString(30937).encode('utf-8'),
                       '/sync/watchlist/remove')]
        items += [(sctop.getString(30989), 'rating')]
        items += [(sctop.getString(30938).encode('utf-8'),
                   '/users/me/lists/%s/items')]

        result = getTrakt('/users/me/lists')
        result = json.loads(result)
        lists = [(i['name'], i['ids']['slug']) for i in result]
        lists = [lists[i // 2] for i in range(len(lists) * 2)]
        util.debug("[SC] string %s" % sctop.getString(30939))
        for i in range(0, len(lists), 2):
            lists[i] = ((sctop.getString(30939) % lists[i][0]).encode('utf-8'),
                        '/users/me/lists/%s/items' % lists[i][1])
        for i in range(1, len(lists), 2):
            lists[i] = ((sctop.getString(30940) % lists[i][0]).encode('utf-8'),
                        '/users/me/lists/%s/items/remove' % lists[i][1])
        items += lists

        select = sctop.selectDialog([i[0] for i in items],
                                    sctop.getString(30941).encode('utf-8'))

        if select == -1:
            return
        elif items[select][1] == 'rating':
            ratings = [(sctop.getString(i + 30990).encode('utf-8'), i)
                       for i in range(10, -1, -1)]
            select = sctop.selectDialog([i[0] for i in ratings], str(name))
            url = "/sync/ratings/remove"
            if select == -1:
                return
            elif ratings[select][1] != 0:
                url = "/sync/ratings"
                post[content][0]['rating'] = ratings[select][1]
            try:
                result = getTrakt(url, post=post)
                result = json.loads(result)
            except:
                return sctop.infoDialog(sctop.getString(30941).encode('utf-8'),
                                        heading=str(name),
                                        sound=True,
                                        icon='ERROR')

            if 'added' in result:
                if result['added'][content]:
                    message = sctop.getString(30987).encode(
                        'utf-8') % ratings[select][1]
                else:
                    return

            if 'deleted' in result:
                if result['deleted'][content]:
                    message = sctop.getString(30988).encode('utf-8')
                else:
                    return

        elif items[select][1] == '/users/me/lists/%s/items':
            t = sctop.getString(30938).encode('utf-8')
            k = sctop.keyboard('', t)
            k.doModal()
            new = k.getText() if k.isConfirmed() else None
            if (new == None or new == ''): return
            result = getTrakt('/users/me/lists',
                              post={
                                  "name": new,
                                  "privacy": "private"
                              })

            try:
                slug = json.loads(result)['ids']['slug']
            except:
                return sctop.infoDialog(sctop.getString(30941).encode('utf-8'),
                                        heading=str(name),
                                        sound=True,
                                        icon='ERROR')
            result = getTrakt(items[select][1] % slug, post=post)
        else:
            result = getTrakt(items[select][1], post=post)

        icon = icon if not result == None else 'ERROR'

        sctop.infoDialog(message, heading=str(name), sound=True, icon=icon)
    except Exception as e:
        util.debug("[SC] trakt error: %s" % str(traceback.format_exc()))
        return
Пример #9
0
def getLists(user='******'):
    result = getTrakt('/users/%s/lists' % user)

    if not result:
        return []
    result = json.loads(result)

    items = []
    items_below = []
    if sctop.getSettingAsBool('trakt.watchlist') or user != 'me':
        items += [{
            'type': 'dir',
            'title': '[B]$30944[/B]',
            'action': 'traktShowList',
            'id': 'watchlist',
            'tl': 'watchlist',
            'tu': user
        }]

    items += [{
        'type': 'dir',
        'title': '[B]$30958[/B]',
        'action': 'traktHistory',
        'id': 'history',
        'tu': user
    }]
    #,
    #{
    #    'type': 'dir',
    #    'title': 'Nedokoncene',
    #    'url': 'cmd://Container.Update("%s")' % \
    #        (xbmcutil._create_plugin_url({'action':'traktShowList', 'id':'progress'}))
    #}

    if user == "me":
        if sctop.getSettingAsBool('trakt.following'):
            below = sctop.getSettingAsBool('trakt.following-below')
            (items_below if below else items).append({
                'action': 'traktFollowing',
                'title': '[B]$30963[/B]',
                'id': 'following',
                'type': 'dir'
            })

        for l, t in (('liked', '$30964'), ('popular', '$30965'), ('trending',
                                                                  '$30966')):
            if sctop.getSettingAsBool('trakt.%s' % l):
                (items_below if sctop.getSettingAsBool('trakt.%s-below' %
                                                       l) else items).append({
                                                           'action':
                                                           'traktSpecialLists',
                                                           'title':
                                                           '[B]%s[/B]' % t,
                                                           'id':
                                                           '%s_lists' % l,
                                                           'type':
                                                           'dir',
                                                           'page':
                                                           '1'
                                                       })

    lists = [{
        'action': 'traktShowList',
        'title': i['name'],
        'id': i['ids']['slug'],
        'type': 'dir',
        'tl': i['ids']['slug'],
        'tu': user,
        'list': 'user'
    } for i in result]

    items += lists

    return items + items_below
Пример #10
0
def manager(name, trakt, content):
    try:
        icon = sctop.infoLabel('ListItem.Icon')
        message = sctop.getString(30941).encode('utf-8')
        content = "movies" if content == 'movie' else "shows"
        post = {content: [{"ids": {"trakt": trakt}}]}
        trakt = int(trakt)
        relevant = sctop.getSettingAsBool('trakt.relevant_menu')

        items = []
        if sctop.getSettingAsBool('trakt.collections'):
            key = 'trakt.collection.%s.ids' % content
            if relevant:
                ids = _get_cached_ids(key, '/users/me/collection/%s' % content)

            if not relevant or trakt not in ids:
                items = [(sctop.getString(30934).encode('utf-8'),
                          '/sync/collection', key)]
            if not relevant or trakt in ids:
                items += [(sctop.getString(30935).encode('utf-8'),
                           '/sync/collection/remove', key)]

        if sctop.getSettingAsBool('trakt.watchlist'):
            key = 'trakt.watchlist.%s.ids' % content
            if relevant:
                ids = _get_cached_ids(key, '/users/me/watchlist/%s' % content)

            if not relevant or trakt not in ids:
                items += [(sctop.getString(30936).encode('utf-8'),
                           '/sync/watchlist', key)]
            if not relevant or trakt in ids:
                items += [(sctop.getString(30937).encode('utf-8'),
                           '/sync/watchlist/remove', key)]

        items += [(sctop.getString(30989), 'rating')]

        lists = sctop.cache.get('trakt.lists')
        if not relevant or not lists:
            result = getTrakt('/users/me/lists')
            lists = json.loads(result)
            sctop.cache.set('trakt.lists', lists)

        util.debug("[SC] string %s" % sctop.getString(30939))

        for lst in lists:
            key = 'trakt.lists.%s.%s.ids' % (lst['ids']['trakt'], content)
            if relevant:
                ids = _get_cached_ids(
                    key, '/users/me/lists/%s/items/%s' %
                    (lst['ids']['slug'], content))
            if not relevant or trakt not in ids:
                items.append(
                    ((sctop.getString(30939) % lst['name']).encode('utf-8'),
                     '/users/me/lists/%s/items' % lst['ids']['slug'], key))

            if not relevant or trakt in ids:
                items.append(
                    ((sctop.getString(30940) % lst['name']).encode('utf-8'),
                     '/users/me/lists/%s/items/remove' % lst['ids']['slug'],
                     key))

        items += [(sctop.getString(30938).encode('utf-8'),
                   '/users/me/lists/%s/items')]

        if relevant:
            items.append(
                (sctop.getString(30811).encode('utf-8'), 'clear_cache'))

        select = sctop.selectDialog([i[0] for i in items],
                                    sctop.getString(30941).encode('utf-8'))

        if select == -1:
            return
        elif items[select][1] == 'rating':
            ratings = [(sctop.getString(i + 30990).encode('utf-8'), i)
                       for i in range(10, -1, -1)]
            select = sctop.selectDialog([i[0] for i in ratings], str(name))
            url = "/sync/ratings/remove"
            if select == -1:
                return
            elif ratings[select][1] != 0:
                url = "/sync/ratings"
                post[content][0]['rating'] = ratings[select][1]
            try:
                result = getTrakt(url, post=post)
                result = json.loads(result)
            except:
                return sctop.infoDialog(sctop.getString(30941).encode('utf-8'),
                                        heading=str(name),
                                        sound=True,
                                        icon='ERROR')

            if 'added' in result:
                if result['added'][content]:
                    message = sctop.getString(30987).encode(
                        'utf-8') % ratings[select][1]
                else:
                    return

            if 'deleted' in result:
                if result['deleted'][content]:
                    message = sctop.getString(30988).encode('utf-8')
                else:
                    return

        elif items[select][1] == '/users/me/lists/%s/items':
            t = sctop.getString(30938).encode('utf-8')
            k = sctop.keyboard('', t)
            k.doModal()
            new = k.getText() if k.isConfirmed() else None
            if (new == None or new == ''): return
            result = getTrakt('/users/me/lists',
                              post={
                                  "name": new,
                                  "privacy": "private"
                              })
            sctop.cache.set('trakt.lists', None, expiration=timedelta())
            try:
                slug = json.loads(result)['ids']['slug']
            except:
                return sctop.infoDialog(sctop.getString(30941).encode('utf-8'),
                                        heading=str(name),
                                        sound=True,
                                        icon='ERROR')
            result = getTrakt(items[select][1] % slug, post=post)
        elif items[select][1] == 'clear_cache':
            ttl = timedelta()
            sctop.cache.set('trakt.lists', None, expiration=ttl)

            contents = ['shows', 'movies']
            for l in ['watchlist', 'collection']:
                for c in contents:
                    key = 'trakt.%s.%s.ids' % (l, c)
                    sctop.cache.set(key, None, expiration=ttl)

            result = getTrakt('/users/me/lists')
            lists = json.loads(result)
            for l in lists:
                for c in contents:
                    key = 'trakt.lists.%s.%s.ids' % (l['ids']['trakt'], c)
                    sctop.cache.set(key, None, expiration=ttl)

            message = sctop.getString(30812).encode('utf-8')
            name = sctop.getString(30941).encode('utf-8')
        else:
            result = getTrakt(items[select][1], post=post)
            key = items[select][2]
            if result and relevant:
                ids = sctop.cache.get(key)
                if type(ids) is list:
                    if items[select][1][-7:] == '/remove':
                        ids = [i for i in ids if i != trakt]
                    else:
                        ids.append(trakt)
                    sctop.cache.set(key, ids)

        icon = icon if not result == None else 'ERROR'

        sctop.infoDialog(message, heading=str(name), sound=True, icon=icon)
    except Exception as e:
        util.debug("[SC] trakt error: %s" % str(traceback.format_exc()))
        return
Пример #11
0
def manager(name, trakt, content):
    try:
        icon = sctop.infoLabel('ListItem.Icon')
        message = sctop.getString(30941).encode('utf-8')
        content = "movies" if content == 'movie' else "shows"
        post = {content: [{"ids": {"trakt": trakt}}]}
        trakt = int(trakt)
        relevant = sctop.getSettingAsBool('trakt.relevant_menu')

        items = []
        if sctop.getSettingAsBool('trakt.collections'):
            key = 'trakt.collection.%s.ids' % content
            if relevant:
                ids = _get_cached_ids(key, '/uses/me/collection/%s' % content)

            if not relevant or trakt not in ids:
                items = [(sctop.getString(30934).encode('utf-8'),
                          '/sync/collection', key)]
            if not relevant or trakt in ids:
                items += [(sctop.getString(30935).encode('utf-8'),
                           '/sync/collection/remove', key)]

        if sctop.getSettingAsBool('trakt.watchlist'):
            key = 'trakt.watchlist.%s.ids' % content
            if relevant:
                ids = _get_cached_ids(key, '/users/me/watchlist/%s' % content)

            if not relevant or trakt not in ids:
                items += [(sctop.getString(30936).encode('utf-8'),
                           '/sync/watchlist', key)]
            if not relevant or trakt in ids:
                items += [(sctop.getString(30937).encode('utf-8'),
                           '/sync/watchlist/remove', key)]

        items += [(sctop.getString(30989), 'rating')]

        lists = sctop.cache.get('trakt.lists')
        if not relevant or not lists:
            result = getTrakt('/users/me/lists')
            lists = json.loads(result)
            sctop.cache.set('trakt.lists', lists)

        util.debug("[SC] string %s" % sctop.getString(30939))

        for lst in lists:
            key = 'trakt.lists.%s.%s.ids' % (lst['ids']['trakt'], content)
            if relevant:
                ids = _get_cached_ids(
                    key, '/users/me/lists/%s/items/%s' % (lst['ids']['slug'],
                                                          content))
            if not relevant or trakt not in ids:
                items.append(
                    ((sctop.getString(30939) % lst['name']).encode('utf-8'),
                     '/users/me/lists/%s/items' % lst['ids']['slug'], key))

            if not relevant or trakt in ids:
                items.append(
                    ((sctop.getString(30940) % lst['name']).encode('utf-8'),
                     '/users/me/lists/%s/items/remove' % lst['ids']['slug'],
                     key))

        items += [(sctop.getString(30938).encode('utf-8'),
                   '/users/me/lists/%s/items')]

        if relevant:
            items.append((sctop.getString(30811).encode('utf-8'),
                          'clear_cache'))

        select = sctop.selectDialog([i[0] for i in items],
                                    sctop.getString(30941).encode('utf-8'))

        if select == -1:
            return
        elif items[select][1] == 'rating':
            ratings = [(sctop.getString(i + 30990).encode('utf-8'), i)
                       for i in range(10, -1, -1)]
            select = sctop.selectDialog([i[0] for i in ratings], str(name))
            url = "/sync/ratings/remove"
            if select == -1:
                return
            elif ratings[select][1] != 0:
                url = "/sync/ratings"
                post[content][0]['rating'] = ratings[select][1]
            try:
                result = getTrakt(url, post=post)
                result = json.loads(result)
            except:
                return sctop.infoDialog(
                    sctop.getString(30941).encode('utf-8'),
                    heading=str(name),
                    sound=True,
                    icon='ERROR')

            if 'added' in result:
                if result['added'][content]:
                    message = sctop.getString(30987).encode(
                        'utf-8') % ratings[select][1]
                else:
                    return

            if 'deleted' in result:
                if result['deleted'][content]:
                    message = sctop.getString(30988).encode('utf-8')
                else:
                    return

        elif items[select][1] == '/users/me/lists/%s/items':
            t = sctop.getString(30938).encode('utf-8')
            k = sctop.keyboard('', t)
            k.doModal()
            new = k.getText() if k.isConfirmed() else None
            if (new == None or new == ''): return
            result = getTrakt(
                '/users/me/lists', post={
                    "name": new,
                    "privacy": "private"
                })
            sctop.cache.set('trakt.lists', None, expiration=timedelta())
            try:
                slug = json.loads(result)['ids']['slug']
            except:
                return sctop.infoDialog(
                    sctop.getString(30941).encode('utf-8'),
                    heading=str(name),
                    sound=True,
                    icon='ERROR')
            result = getTrakt(items[select][1] % slug, post=post)
        elif items[select][1] == 'clear_cache':
            ttl = timedelta()
            sctop.cache.set('trakt.lists', None, expiration=ttl)

            contents = ['shows', 'movies']
            for l in ['watchlist', 'collection']:
                for c in contents:
                    key = 'trakt.%s.%s.ids' % (l, c)
                    sctop.cache.set(key, None, expiration=ttl)

            result = getTrakt('/users/me/lists')
            lists = json.loads(result)
            for l in lists:
                for c in contents:
                    key = 'trakt.lists.%s.%s.ids' % (l['ids']['trakt'], c)
                    sctop.cache.set(key, None, expiration=ttl)

            message = sctop.getString(30812).encode('utf-8')
            name = sctop.getString(30941).encode('utf-8')
        else:
            result = getTrakt(items[select][1], post=post)
            key = items[select][2]
            if result and relevant:
                ids = sctop.cache.get(key)
                if type(ids) is list:
                    if items[select][1][-7:] == '/remove':
                        ids = [i for i in ids if i != trakt]
                    else:
                        ids.append(trakt)
                    sctop.cache.set(key, ids)

        icon = icon if not result == None else 'ERROR'

        sctop.infoDialog(message, heading=str(name), sound=True, icon=icon)
    except Exception as e:
        util.debug("[SC] trakt error: %s" % str(traceback.format_exc()))
        return
Пример #12
0
def getTrakt(url, post=None, output='content', method=None):
    try:
        use_ssl = sctop.getSettingAsBool('UseSSL')
        url = urlparse.urljoin(
            'http%s://api.trakt.tv' % ('s' if use_ssl else ''), url)

        headers = {'trakt-api-key': sctop.trCL, 'trakt-api-version': '2'}

        if getTraktCredentialsInfo() == False:
            util.debug("[SC] gt 1 data: %s %s" % (str(url), str(post)))
            if post is not None:
                result = util.post_json(url, post, headers)
            else:
                result = util.request(url, headers)
            util.debug("[SC] gt 1 result: %s" % str(result))
            return result

        headers[
            'Authorization'] = 'Bearer %s' % sctop.getSetting('trakt.token')
        #util.debug('[SC] token %s' % sctop.getSetting('trakt.token'))

        if post is not None:
            result, code = sctop.post_json(url, post, headers, "extend")
            info = None
        else:
            result, code, info = sctop.request(
                url, headers, "info", method=method)
        #util.debug("[SC] trakt gt result: %s %s" % (str(result), str(code)))
        if not (code == 401 or code == 405):
            if output == "content":
                return result
            else:
                return (result, code, info)

        oauth = 'http%s://api.trakt.tv/oauth/token' % ('s' if use_ssl else '')
        opost = {
            'client_id': sctop.trCL,
            'client_secret': sctop.trSC,
            'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
            'grant_type': 'refresh_token',
            'refresh_token': sctop.getSetting('trakt.refresh')
        }

        result, code = sctop.post_json(oauth, opost, headers, "extend")
        if code == 401:
            authTrakt()
            result, code = sctop.post_json(oauth, opost, headers, "extend")
        result = json.loads(result)

        token, refresh = result['access_token'], result['refresh_token']

        sctop.setSetting(setting='trakt.token', value=token)
        sctop.setSetting(setting='trakt.refresh', value=refresh)

        headers['Authorization'] = 'Bearer %s' % token

        util.debug('[SC] token: %s' % token)

        result = sctop.post_json(url, post, headers)
        return result
    except Exception as e:
        util.error(e)
        pass
Пример #13
0
def getLists(user='******'):
    result = getTrakt('/users/%s/lists' % user)

    if not result:
        return []
    result = json.loads(result)

    items = []
    items_below = []
    if sctop.getSettingAsBool('trakt.watchlist') or user != 'me':
        items += [{
            'type': 'dir',
            'title': '[B]$30944[/B]',
            'action': 'traktShowList',
            'id': 'watchlist',
            'tl': 'watchlist',
            'tu': user
        }]

    items += [{
        'type': 'dir',
        'title': '[B]$30958[/B]',
        'action': 'traktHistory',
        'id': 'history',
        'tu': user
    }]
    #,
    #{
    #    'type': 'dir',
    #    'title': 'Nedokoncene',
    #    'url': 'cmd://Container.Update("%s")' % \
    #        (xbmcutil._create_plugin_url({'action':'traktShowList', 'id':'progress'}))
    #}

    if user == "me":
        if sctop.getSettingAsBool('trakt.following'):
            below = sctop.getSettingAsBool('trakt.following-below')
            (items_below if below else items).append({
                'action':
                'traktFollowing',
                'title':
                '[B]$30963[/B]',
                'id':
                'following',
                'type':
                'dir'
            })

        for l, t in (('liked', '$30964'), ('popular', '$30965'), ('trending',
                                                                  '$30966')):
            if sctop.getSettingAsBool('trakt.%s' % l):
                (items_below if sctop.getSettingAsBool('trakt.%s-below' % l)
                 else items).append({
                     'action': 'traktSpecialLists',
                     'title': '[B]%s[/B]' % t,
                     'id': '%s_lists' % l,
                     'type': 'dir',
                     'page': '1'
                 })

    lists = [{
        'action': 'traktShowList',
        'title': i['name'],
        'id': i['ids']['slug'],
        'type': 'dir',
        'tl': i['ids']['slug'],
        'tu': user,
        'list': 'user'
    } for i in result]

    items += lists

    return items + items_below