Пример #1
0
 def fetch(self, Dir, lvl, whiteFlag, blackFlag):
     limit = getSetting('pagination_limit', asInt=True)
     self.data = None
     query = self.query
     if not query:
         from gui.util import Keyboard
         k = Keyboard('', 'My %s' % self.search_type)
         k.doModal()
         if not k.isConfirmed():
             return False
         query = k.getText()
     query.strip()
     info(self, 'search_type: %s, query: %s' % (self.search_type, query))
     source = self.source
     kwargs = {'query': query,
               'limit': limit,
               }
     if source is not None:
         kwargs['source'] = source
     data = None
     if self.search_type == 'albums':
         data = api.get('/collection/getAlbums', **kwargs)
     elif self.search_type == 'artists':
         data = api.get('/collection/getArtists', **kwargs)
     elif self.search_type == 'tracks':
         data = api.get('/collection/getTracks', **kwargs)
     if data is None:
         return False
     self.data = data
     return True
Пример #2
0
 def _add_tracks(self, playlist_id, nodes):
     if len(nodes) < 1:
         warn(self, 'Empty list...')
         return False
     step = 50
     start = 0
     numtracks = len(nodes)
     if numtracks > 1000:
         notify_error('Qobuz', 'Max tracks per playlist reached (1000)'
                      '\nSkipping %s tracks' % (numtracks - 1000))
         numtracks = 1000
     while start < numtracks:
         if (start + step) > numtracks:
             step = numtracks - start
         str_tracks = ''
         info(self, "Adding tracks start: %s, end: %s" %
              (start, start + step))
         for i in range(start, start + step):
             node = nodes[i]
             if node.nt != Flag.TRACK:
                 warn(self, "Not a Node_track node")
                 continue
             str_tracks += '%s,' % (str(node.nid))
         if not api.playlist_addTracks(
                 playlist_id=playlist_id, track_ids=str_tracks):
             return False
         start += step
     return True
Пример #3
0
 def mkdir(self, path):
     if not os.path.isdir(path):
         try:
             os.makedirs(path)
         except:
             warn("Cannot create directory: " + path)
             exit(2)
         info(self, "Directory created: " + path)
Пример #4
0
 def bootstrap_sys_args(self):
     """Parsing sys arg parameters and store them
     """
     self.MODE = None
     self.params = get_checked_parameters()
     if 'nt' not in self.params:
         self.params['nt'] = Flag.ROOT
         self.MODE = Mode.VIEW
     self.nodeType = int(self.params['nt'])
     try:
         self.MODE = int(self.params['mode'])
     except:
         warn(self, "No 'mode' parameter")
     for name in self.params:
         info(self, "Param: %s = %s (%s)" % (name, str(self.params[name]),
                                             Flag.to_s(self.params['nt'])))
Пример #5
0
 def track_resportStreamingEnd(self, track_id, duration):
     duration = math.floor(int(duration))
     if duration < 5:
         info(self, 'Duration lesser than 5s, abort reporting')
         return None
     # @todo ???
     user_auth_token = ''  # @UnusedVariable
     try:
         user_auth_token = self.user_auth_token  # @UnusedVariable
     except:
         warn(self, 'No authentification token')
         return None
     params = {'user_id': self.user_id,
               'track_id': track_id,
               'duration': duration
               }
     return self._api_request(params, '/track/reportStreamingEnd')
Пример #6
0
 def track_resportStreamingEnd(self, track_id, duration):
     duration = math.floor(int(duration))
     if duration < 5:
         info(self, 'Duration lesser than 5s, abort reporting')
         return None
     # @todo ???
     user_auth_token = ''  # @UnusedVariable
     try:
         user_auth_token = self.user_auth_token  # @UnusedVariable
     except:
         warn(self, 'No authentification token')
         return None
     params = {
         'user_id': self.user_id,
         'track_id': track_id,
         'duration': duration
     }
     return self._api_request(params, '/track/reportStreamingEnd')
Пример #7
0
 def populate(self, xbmc_directory, lvl, whiteFlag, blackFlag):
     username = api.username
     password = api.password
     user_id = api.user_id
     user_data = api.get('/user/login', username=username,
                         password=password)
     if not 'user' in user_data:
         return False
     friend_data = user_data['user']['player_settings']['friends']
     info(self, "Build-down friends list " + repr(self.name))
     if self.name:
         data = api.get('/playlist/getUserPlaylists',
                        username=self.name, limit=0)
     else:
         data = api.get('/playlist/getUserPlaylists',
                        user_id=user_id, limit=0)
     if not data:
         warn(self, "No friend data")
         return False
     # extract all owner names from the list
     friend_list = []
     for item in data['playlists']['items']:
         if item['owner']['name'] == user_data['user']['login']:
             continue
         friend_list.append(item['owner']['name'])
     # add previously stored
     if (not self.name):
         for name in friend_data:
             friend_list.append(str(name))
     # remove duplicates
     keys = {}
     for e in friend_list:
         keys[e] = 1
     friend_list = keys.keys()
     # and add them to the directory
     for name in friend_list:
         node = getNode(Flag.FRIEND, {'query': str(name)})
         if name == self.name:
             continue
         if name in friend_data:
             node.label = 'Friend / %s' % (node.label)
         self.add_child(node)
Пример #8
0
 def gui_remove(self, playlist_id=None):
     if not playlist_id:
         playlist_id = self.nid
     if not playlist_id:
         notify_error(dialogHeading,
                      'Invalid playlist %s' % (str(playlist_id)))
         return False
     login = getSetting('username')
     offset = 0
     limit = getSetting('pagination_limit')
     data = api.get('/playlist/get', playlist_id=playlist_id, limit=limit,
                    offset=offset)
     name = ''
     if 'name' in data:
         name = data['name']
     ok = xbmcgui.Dialog().yesno(lang(30166),
                                 lang(30054),
                                 color('FFFF0000', name))
     if not ok:
         info(self, "Deleting playlist aborted...")
         return False
     res = False
     if data['owner']['name'] == login:
         info(self, "Deleting playlist: " + str(playlist_id))
         res = api.playlist_delete(playlist_id=playlist_id)
     else:
         info(self, 'Unsuscribe playlist' + str(playlist_id))
         res = api.playlist_unsubscribe(playlist_id=playlist_id)
     if not res:
         warn(self, "Cannot delete playlist with id " + str(playlist_id))
         notify_error(lang(30183), lang(30186) + name)
         return False
     self.delete_cache(playlist_id)
     notify_log(lang(30183), (lang(30184) + "%s" + lang(30185)) % (name))
     url = self.make_url(nt=Flag.USERPLAYLISTS, mode=Mode.VIEW, nm='',
                         nid='')
     executeBuiltin(containerUpdate(url, True))
     return False
Пример #9
0
    def _api_request(self, params, uri, **opt):
        '''Qobuz API HTTP get request
            Arguments:
            params:    parameters dictionary
            uri   :    service/method
            opt   :    Optionnal named parameters
                        - noToken=True/False

            Return None if something went wrong
            Return raw data from qobuz on success as dictionary

            * on error you can check error and status_code

            Example:

                ret = api._api_request({'username':'******',
                                  'password':'******'},
                                 'user/login', noToken=True)
                print 'Error: %s [%s]' % (api.error, api.status_code)

            This should produce something like:
            Error: [200]
            Error: Bad Request [400]
        '''
        info(self, 'uri: {}, params: {}', uri, str(params))
        self.statTotalRequest += 1
        self.error = ''
        self.status_code = None
        url = self._baseUrl + uri
        useToken = False if (opt and 'noToken' in opt) else True
        headers = {}
        if useToken and self.user_auth_token:
            headers['x-user-auth-token'] = self.user_auth_token
        headers['x-app-id'] = self.appid
        '''DEBUG'''
        import copy
        _copy_params = copy.deepcopy(params)
        if 'password' in _copy_params:
            _copy_params['password'] = '******'
        '''END / DEBUG'''
        r = None
        try:
            r = self.session.post(url, data=params, headers=headers)
        except:
            self.error = 'Post request fail'
            warn(self, self.error)
            return None
        self.status_code = int(r.status_code)
        if self.status_code != 200:
            self.error = self._api_error_string(r, url, _copy_params)
            warn(self, self.error)
            return None
        if not r.content:
            self.error = 'Request return no content'
            warn(self, self.error)
            return None
        self.statContentSizeTotal += sys.getsizeof(r.content)
        '''Retry get if connexion fail'''
        try:
            response_json = r.json()
        except Exception as e:
            warn(self, 'Json loads failed to load... retrying!\n{}', repr(e))
            try:
                response_json = r.json()
            except:
                self.error = "Failed to load json two times...abort"
                warn(self, self.error)
                return None
        status = None
        try:
            status = response_json['status']
        except:
            pass
        if status == 'error':
            self.error = self._api_error_string(r, url, _copy_params,
                                                response_json)
            warn(self, self.error)
            return None
        return response_json
Пример #10
0
    def _api_request(self, params, uri, **opt):
        '''Qobuz API HTTP get request
            Arguments:
            params:    parameters dictionary
            uri   :    service/method
            opt   :    Optionnal named parameters
                        - noToken=True/False

            Return None if something went wrong
            Return raw data from qobuz on success as dictionary

            * on error you can check error and status_code

            Example:

                ret = api._api_request({'username':'******',
                                  'password':'******'},
                                 'user/login', noToken=True)
                print 'Error: %s [%s]' % (api.error, api.status_code)

            This should produce something like:
            Error: [200]
            Error: Bad Request [400]
        '''
        self.statTotalRequest += 1
        self.error = ''
        self.status_code = None
        url = self._baseUrl + uri
        useToken = False if (opt and 'noToken' in opt) else True
        headers = {}
        if useToken and self.user_auth_token:
            headers['x-user-auth-token'] = self.user_auth_token
        headers['x-app-id'] = self.appid
        '''DEBUG'''
        import copy
        _copy_params = copy.deepcopy(params)
        if 'password' in _copy_params:
            _copy_params['password'] = '******'
        info(self, 'URI {} POST PARAMS: {} HEADERS: {}', uri,
             str(_copy_params), str(headers))
        '''END / DEBUG'''
        r = None
        try:
            r = self.session.post(url, data=params, headers=headers)
        except:
            self.error = 'Post request fail'
            warn(self, self.error)
            return None
        self.status_code = int(r.status_code)
        if self.status_code != 200:
            self.error = self._api_error_string(r, url, _copy_params)
            warn(self, self.error)
            return None
        if not r.content:
            self.error = 'Request return no content'
            warn(self, self.error)
            return None
        self.statContentSizeTotal += sys.getsizeof(r.content)
        '''Retry get if connexion fail'''
        try:
            response_json = r.json()
        except Exception as e:
            warn(self, 'Json loads failed to load... retrying!\n{}', repr(e))
            try:
                response_json = r.json()
            except:
                self.error = "Failed to load json two times...abort"
                warn(self, self.error)
                return None
        status = None
        try:
            status = response_json['status']
        except:
            pass
        if status == 'error':
            self.error = self._api_error_string(r, url, _copy_params,
                                                response_json)
            warn(self, self.error)
            return None
        return response_json