def get_item_by_path(self, path, include_download_info=False):
     parameters = self.prepare_parameters()
     if path[-1:] == '/':
         path = path[:-1]
     Logger.debug(path + ' <- Target')
     key = '%s%s' % (self._driveid, path,)
     Logger.debug('Testing item from cache: %s' % key)
     item = self._items_cache.get(key)
     if not item:
         parameters['fields'] = 'files(%s)' % self._get_field_parameters()
         index = path.rfind('/')
         filename = urllib.unquote(path[index+1:])
         parent = path[0:index]
         if not parent:
             parent = 'root'
         else:
             parent = self.get_item_by_path(parent, include_download_info)['id']
         item = None
         parameters['q'] = '\'%s\' in parents and name = \'%s\'' % (Utils.str(parent), Utils.str(filename).replace("'","\\'"))
         files = self.get('/files', parameters = parameters)
         if (len(files['files']) > 0):
             for f in files['files']:
                 item = self._extract_item(f, include_download_info)
                 break
     else:
         Logger.debug('Found in cache.')
     if not item:
         raise RequestException('Not found by path', HTTPError(path, 404, 'Not found', None, None), 'Request URL: %s' % path, None)
     
     else:
         self._items_cache.set(key, item)
     return item
 def _validate_access_tokens(self, access_tokens, url, data,
                             request_headers):
     if not access_tokens or not 'access_token' in access_tokens or not 'refresh_token' in access_tokens or not 'expires_in' in access_tokens or not 'date' in access_tokens:
         raise RequestException(
             'Access tokens provided are not valid: ' +
             Utils.str(access_tokens), None, 'Request URL: ' +
             Utils.str(url) + '\nRequest data: ' + Utils.str(data) +
             '\nRequest headers: ' + Utils.str(request_headers), None)
 def is_path_possible(self, driveid, path):
     index = path.rfind('/')
     while index >= 0:
         filename = path[index+1:]
         path = path[0:index]
         key = '%s%s:children' % (driveid, path,)
         Logger.debug('testing possible path key: ' + key)
         children = self._children_cache.get(key)
         if children or type(children) is list:
             if filename and not filename in children:
                 Logger.debug('Not found. From cache.') 
                 raise RequestException('Not found. From cache.', HTTPError(self.path, 404, 'Not found.', None, None), 'Request URL: %s' % self.path, None)
             return True
         index = path.rfind('/')
     return True
    def request(self):
        self.response_text = self._DEFAULT_RESPONSE
        if not self.exceptions:
            self.exceptions = Exception
        if not self.wait:
            self.wait = time.sleep
        if not self.headers:
            self.headers = {}

        for i in xrange(self.tries):
            self.current_tries = i + 1
            if self.before_request:
                self.before_request(self)
            if self.cancel_operation and self.cancel_operation():
                break
            request_report = 'Request URL: ' + self.get_url_for_report(
                self.url)
            request_report += '\nRequest data: ' + Utils.str(self.data)
            request_report += '\nRequest headers: ' + Utils.str(
                self.get_headers_for_report(self.headers))
            response_report = '<response_not_set>'
            response = None
            try:
                Logger.debug(request_report)
                req = urllib2.Request(self.url, self.data, self.headers)
                response = urllib2.urlopen(req)
                self.response_code = response.getcode()
                self.response_info = response.info()
                self.response_url = response.geturl()
                cookiejar = CookieJar()
                cookiejar._policy._now = cookiejar._now = int(time.time())
                self.response_cookies = cookiejar.make_cookies(response, req)
                self.response_text = response.read()
                content_length = self.response_info.getheader(
                    'content-length', -1)
                response_report = '\nResponse Headers:\n%s' % Utils.str(
                    self.response_info)
                response_report += '\nResponse (%d) content-length=%s, len=<%s>:\n%s' % (
                    self.response_code, content_length, len(
                        self.response_text), self.response_text)
                self.success = True
                break
            except self.exceptions as e:
                root_exception = e
                response_report = '\nResponse <Exception>: '
                if isinstance(e, urllib2.HTTPError):
                    response_report += Utils.str(e.read())
                else:
                    response_report += Utils.str(e)
                rex = RequestException(Utils.str(e), root_exception,
                                       request_report, response_report)
                if self.on_exception:
                    self.on_exception(self, rex)
                if self.cancel_operation and self.cancel_operation():
                    break
                if self.current_tries == self.tries:
                    if self.on_failure:
                        self.on_failure(self)
                    if self.on_complete:
                        self.on_complete(self)
                    Logger.debug('Raising exception...')
                    raise rex
                current_time = time.time()
                max_waiting_time = current_time + self.current_delay
                while (not self.cancel_operation
                       or not self.cancel_operation()
                       ) and max_waiting_time > current_time:
                    remaining = round(max_waiting_time - current_time)
                    if self.waiting_retry:
                        self.waiting_retry(self, remaining)
                    self.wait(1)
                    current_time = time.time()
                self.current_delay *= self.backoff
            finally:
                Logger.debug(response_report)
                if response:
                    response.close()
        if self.success and self.on_success:
            self.on_success(self)
        if self.on_complete:
            self.on_complete(self)
        return self.response_text
    def request(self):
        self.response_text = self._DEFAULT_RESPONSE
        if not self.exceptions:
            self.exceptions = Exception
        if not self.wait:
            self.wait = time.sleep
        if not self.headers:
            self.headers = {}

        for i in xrange(self.tries):
            self.current_tries = i + 1
            if self.before_request:
                self.before_request(self)
            if self.cancel_operation and self.cancel_operation():
                break
            request_report = 'Request URL: ' + self.get_url_for_report(
                self.url)
            request_report += '\nRequest data: ' + Utils.str(self.data)
            request_report += '\nRequest headers: ' + Utils.str(
                self.get_headers_for_report(self.headers))
            response_report = '<response_not_set>'
            response = None
            rex = None
            download_file = None
            try:
                Logger.debug(request_report)
                req = urllib2.Request(self.url, self.data, self.headers)
                response = urllib2.urlopen(req)
                self.response_code = response.getcode()
                self.response_info = response.info()
                self.response_url = response.geturl()
                cookiejar = CookieJar()
                cookiejar._policy._now = cookiejar._now = int(time.time())
                self.response_cookies = cookiejar.make_cookies(response, req)
                if self.read_content:
                    if self.download_path:
                        self.response_text = 'Downloading to: ' + self.download_path + '... '
                        download_file = KodiUtils.file(self.download_path,
                                                       'wb')
                        self.download_progress = 0
                        while True:
                            chunk = response.read(self.DOWNLOAD_CHUNK_SIZE)
                            if not chunk:
                                break
                            download_file.write(chunk)
                            self.download_progress += self.DOWNLOAD_CHUNK_SIZE
                            if self.on_update_download:
                                self.on_update_download(self)
                        self.response_text += ' OK.'
                    else:
                        self.response_text = response.read()
                content_length = self.response_info.getheader(
                    'content-length', -1)
                response_report = '\nResponse Headers:\n%s' % Utils.str(
                    self.response_info)
                response_report += '\nResponse (%d) content-length=%s, len=<%s>:\n' % (
                    self.response_code,
                    content_length,
                    len(self.response_text),
                )
                try:
                    response_report += Utils.str(self.response_text)
                except:
                    response_report += '<possible binary content>'
                self.success = True
                break
            except self.exceptions as e:
                Logger.debug('Exception...')
                root_exception = e
                response_report = '\nResponse <Exception>: '
                if isinstance(e, urllib2.HTTPError):
                    self.response_code = e.code
                    self.response_text = Utils.str(e.read())
                    response_report += self.response_text
                else:
                    response_report += Utils.str(e)
                rex = RequestException(Utils.str(e), root_exception,
                                       request_report, response_report)
            finally:
                try:
                    if download_file:
                        download_file.close()
                    Logger.debug(response_report)
                except:
                    Logger.debug('unable to print response_report')
                if response:
                    response.close()
            if rex:
                if self.on_exception:
                    Logger.debug('calling self.on_exception...')
                    self.on_exception(self, rex)
                if self.cancel_operation and self.cancel_operation():
                    break
                Logger.debug('current_tries: ' + str(self.current_tries) +
                             ' maximum tries: ' + str(self.tries) + ' i: ' +
                             str(i))
                if self.current_tries == self.tries:
                    Logger.debug('max retries reached')
                    if self.on_failure:
                        self.on_failure(self)
                    if self.on_complete:
                        self.on_complete(self)
                    Logger.debug('Raising exception...')
                    raise rex
                current_time = time.time()
                max_waiting_time = current_time + self.current_delay
                Logger.debug('current_delay: ' + str(self.current_delay) +
                             ' seconds. Waiting...')
                while (not self.cancel_operation
                       or not self.cancel_operation()
                       ) and max_waiting_time > current_time:
                    remaining = round(max_waiting_time - current_time)
                    if self.waiting_retry:
                        Logger.debug('calling self.waiting_retry...')
                        self.waiting_retry(self, remaining)
                    self.wait(1)
                    current_time = time.time()
                Logger.debug('Done waiting.')
                self.current_delay *= self.backoff

        if self.success and self.on_success:
            self.on_success(self)
        if self.on_complete:
            self.on_complete(self)
        return self.response_text