def _on_exception(self, request, e, original_on_exception):
     ex = ExceptionUtils.extract_exception(e, urllib2.HTTPError)
     if ex and ex.code >= 400 and ex.code <= 599 and ex.code != 503:
         request.tries = request.current_tries
     if original_on_exception and not (original_on_exception is
                                       self._on_exception):
         original_on_exception(request, e)
 def get_drives(self, request_params=None, access_tokens=None):
     drives = [{
         'id' : self._user['permissionId'],
         'name' : '',
         'type' : ''
     }]
     try:
         all_teamdrives_fetch = False
         page_token = None
         parameters = {'pageSize': 100}
         while not all_teamdrives_fetch:
             if page_token:
                 parameters['nextPageToken'] = page_token
             response = self.get('/teamdrives', parameters=parameters, request_params=request_params, access_tokens=access_tokens)
             if response and 'teamDrives' in response:
                 for drive in response['teamDrives']:
                     drives.append({
                         'id' : drive['id'],
                         'name' : Utils.get_safe_value(drive, 'name', drive['id']),
                         'type' : drive['kind']
                     })
             if response and 'nextPageToken' in response:
                 page_token = response['nextPageToken']
             else:
                 all_teamdrives_fetch = True
     except RequestException as ex:
         httpex = ExceptionUtils.extract_exception(ex, HTTPError)
         if not httpex or httpex.code != 403:
             raise ex
     return drives
    def do_GET(self):
        Logger.debug(self.path)
        data = self.path.split('/')
        code = 307
        headers = {}
        content = Utils.get_file_buffer()
        if len(data) > 4 and data[1] == self.server.service.name:
            try:
                driveid = data[2]
                provider = self.server.data()
                account_manager = AccountManager(
                    self.server.service.profile_path)
                provider.configure(account_manager, driveid)
                item = provider.get_item(item_driveid=data[3],
                                         item_id=data[4],
                                         include_download_info=True)
                headers['location'] = item['download_info']['url']
            except Exception as e:
                httpex = ExceptionUtils.extract_exception(e, HTTPError)
                if httpex:
                    code = httpex.code
                else:
                    code = 500

                ErrorReport.handle_exception(e)
                content.write(ExceptionUtils.full_stacktrace(e))
        else:
            code = 404
        self.write_response(code, content=content, headers=headers)
Esempio n. 4
0
 def do_POST(self):
     content = Utils.get_file_buffer()
     data = self.path.split('/')
     if len(data) > 1 and data[1] == self.server.service.name:
         try:
             size = int(self.headers.getheader('content-length', 0))
             cmd = eval(self.rfile.read(size))
             method = Utils.get_safe_value(cmd, 'method')
             if method:
                 code = 200
                 args = Utils.get_safe_value(cmd, 'args', [])
                 kwargs = Utils.get_safe_value(cmd, 'kwargs', {})
                 Logger.debug('Command received:\n%s' % cmd)
                 content.write(
                     repr(self.server.data.rpc(method, args, kwargs)))
             else:
                 code = 400
                 content.write('Method required')
         except Exception as e:
             httpex = ExceptionUtils.extract_exception(e, HTTPError)
             if httpex:
                 code = httpex.code
             else:
                 code = 500
             content.write(ExceptionUtils.full_stacktrace(e))
     else:
         code = 404
     self.write_response(code, content=content)
 def do_GET(self):
     Logger.debug(self.path)
     data = self.path.split('/')
     code = 307
     headers = {}
     content = Utils.get_file_buffer()
     if len(data) > 5 and data[1] == self.server.service.name:
         try:
             item = RpcUtil.rpc(data[2], 'get_item', kwargs = {
                 'driveid' : data[3],
                 'item_driveid' : data[4],
                 'item_id' : data[5],
                 'include_download_info' : True
             })
             headers['location'] = item['download_info']['url']
         except Exception as e:
             httpex = ExceptionUtils.extract_exception(e, HTTPError)
             if httpex:
                 code = httpex.code
             else:
                 code = 500
             content.write(ExceptionUtils.full_stacktrace(e))
     else:
         code = 404
     self.write_response(code, content=content, headers=headers)
Esempio n. 6
0
    def get_drives(self, request_params=None, access_tokens=None):
        drives = []
        drives_id_list = []
        try:
            response = self.get('/drives',
                                request_params=request_params,
                                access_tokens=access_tokens)
            for drive in response['value']:
                drives_id_list.append(drive['id'])
                drives.append({
                    'id': drive['id'],
                    'name': Utils.get_safe_value(drive, 'name', ''),
                    'type': drive['driveType']
                })
        except RequestException as ex:
            httpex = ExceptionUtils.extract_exception(ex, HTTPError)
            if not httpex or httpex.code != 403:
                raise ex

        response = self.get('/me/drives',
                            request_params=request_params,
                            access_tokens=access_tokens)
        for drive in response['value']:
            if not drive['id'] in drives_id_list:
                drives_id_list.append(drive['id'])
                drives.append({
                    'id': drive['id'],
                    'name': Utils.get_safe_value(drive, 'name', ''),
                    'type': drive['driveType']
                })
        return drives
 def do_GET(self):
     data = self.path.split('/')
     size = len(data)
     if size > 1 and data[1] == self.server.service.name:
         try:
             if size == 2:
                 self.write_response(303, headers={'location': self.path + '/'})
             elif size > 2 and data[2]:
                 addon_name = data[2]
                 if size == 3:
                     self.write_response(303, headers={'location': self.path + '/'})
                 elif size == 4 and not data[3]:
                     self.show_drives(addon_name)
                 else:
                     drive_name = data[3]
                     path = self.path[len(self.server.service.name)+len(addon_name)+len(drive_name)+3:]
                     self.process_path(addon_name, drive_name, path)
             else:
                 self.show_addon_list()
         except Exception as e:
             httpex = ExceptionUtils.extract_exception(e, HTTPError)
             if httpex:
                 response_code = httpex.code
             else:
                 response_code = 500
             content = Utils.get_file_buffer()
             content.write(ExceptionUtils.full_stacktrace(e))
             self.write_response(response_code, content=content)
     else:
         self.write_response(404)
Esempio n. 8
0
    def handle_exception(ex):
        stacktrace = ExceptionUtils.full_stacktrace(ex)
        rex = ExceptionUtils.extract_exception(ex, RequestException)
        httpex = ExceptionUtils.extract_exception(ex, HTTPError)
        dnf = ExceptionUtils.extract_exception(ex, DriveNotFoundException)

        line1 = ''
        line2 = Utils.unicode(ex)

        send_report = True
        log_report = True
        if rex and rex.response:
            line1 = Utils.unicode(rex)
            line2 = ExceptionUtils.extract_error_message(rex.response)

        if httpex:
            if httpex.code == 401:
                send_report = False
            elif httpex.code == 404:
                send_report = False
                log_report = False
        if dnf:
            send_report = False
            log_report = False

        addonid = KodiUtils.get_addon_info('id')
        addon_version = KodiUtils.get_addon_info('version')
        common_addon_version = KodiUtils.get_addon_info(
            'version', 'script.module.clouddrive.common')
        report = '[%s] [%s]/[%s]\n\n%s\n%s\n%s\n\n%s' % (
            addonid, addon_version, common_addon_version, line1, line2, '',
            stacktrace)
        if rex:
            report += '\n\n%s\nResponse:\n%s' % (rex.request, rex.response)
        if log_report:
            Logger.debug(report)
        else:
            Logger.debug(ex)
        if send_report:
            Logger.notice(report)
            Logger.notice('Report sent')
            ErrorReport.send_report(report)
Esempio n. 9
0
 def rpc(self, method, args=None, kwargs=None):
     args = Utils.default(args, [])
     kwargs = Utils.default(kwargs, {})
     method = getattr(self, method)
     fkwargs = {}
     for name in inspect.getargspec(method)[0]:
         if name in kwargs:
             fkwargs[name] = kwargs[name]
     try:
         return method(*args, **fkwargs)
     except Exception as ex:
         handle = True
         httpex = ExceptionUtils.extract_exception(ex, HTTPError)
         if httpex:
             handle = httpex.code != 404
         if handle:
             self._handle_exception(ex, False)
         raise ex
Esempio n. 10
0
 def get_drives(self, request_params=None, access_tokens=None):
     drives = [{
         'id' : self._user['permissionId'],
         'name' : '',
         'type' : ''
     }]
     try:
         response = self.get('/teamdrives', request_params=request_params, access_tokens=access_tokens)
         if response and 'teamDrives' in response:
             for drive in response['teamDrives']:
                 drives.append({
                     'id' : drive['id'],
                     'name' : Utils.get_safe_value(drive, 'name', drive['id']),
                     'type' : drive['kind']
                 })
     except RequestException as ex:
         httpex = ExceptionUtils.extract_exception(ex, HTTPError)
         if not httpex or httpex.code != 403:
             raise ex
     return drives
Esempio n. 11
0
 def _handle_exception(self, ex, show_error_dialog = True):
     stacktrace = ExceptionUtils.full_stacktrace(ex)
     rex = ExceptionUtils.extract_exception(ex, RequestException)
     uiex = ExceptionUtils.extract_exception(ex, UIException)
     httpex = ExceptionUtils.extract_exception(ex, HTTPError)
     urlex = ExceptionUtils.extract_exception(ex, URLError)
     line1 = self._common_addon.getLocalizedString(32027)
     line2 = Utils.unicode(ex)
     line3 = self._common_addon.getLocalizedString(32016)
     
     if uiex:
         line1 = self._common_addon.getLocalizedString(int(Utils.str(uiex)))
         line2 = Utils.unicode(uiex.root_exception)
     elif rex and rex.response:
         line1 += ' ' + Utils.unicode(rex)
         line2 = ExceptionUtils.extract_error_message(rex.response)
     send_report = True
     add_account_cmd = 'RunPlugin('+self._addon_url + '?' + urllib.urlencode({'action':'_add_account', 'content_type': self._content_type})+')'
     if isinstance(ex, AccountNotFoundException) or isinstance(ex, DriveNotFoundException):
         show_error_dialog = False
         if self._dialog.yesno(self._addon_name, self._common_addon.getLocalizedString(32063) % '\n'):
             KodiUtils.executebuiltin(add_account_cmd)
     elif rex and httpex:
         if httpex.code >= 500:
             line1 = self._common_addon.getLocalizedString(32035)
             line2 = None
             line3 = self._common_addon.getLocalizedString(32038)
         elif httpex.code >= 400:
             driveid = Utils.get_safe_value(self._addon_params, 'driveid')
             if driveid:
                 self._account_manager.load()
                 account = self._account_manager.get_account_by_driveid(driveid)
                 drive = self._account_manager.get_drive_by_driveid(driveid)
                 if KodiUtils.get_signin_server() in rex.request or httpex.code == 401:
                     send_report = False
                     show_error_dialog = False
                     if self._dialog.yesno(self._addon_name, self._common_addon.getLocalizedString(32046) % (self._get_display_name(account, drive, True), '\n')):
                         KodiUtils.executebuiltin(add_account_cmd)
                 elif httpex.code == 403:
                     line1 = self._common_addon.getLocalizedString(32019)
                     line2 = line3 = None
                 elif httpex.code == 404:
                     send_report = False
                     line1 = self._common_addon.getLocalizedString(32037)
                     line2 = line2 = None
                 else:
                     line1 = self._common_addon.getLocalizedString(32036)
                     line3 = self._common_addon.getLocalizedString(32038)
             else:
                 if KodiUtils.get_signin_server()+'/pin/' in rex.request and httpex.code == 404 and self._ip_before_pin:
                     ip_after_pin = Request(KodiUtils.get_signin_server() + '/ip', None).request()
                     if self._ip_before_pin != ip_after_pin:
                         send_report = False
                         line1 = self._common_addon.getLocalizedString(32072)
                         line2 = self._common_addon.getLocalizedString(32073) % (self._ip_before_pin, ip_after_pin,)
     elif urlex:
         reason = Utils.str(urlex.reason)
         line3 = self._common_addon.getLocalizedString(32074)
         if '[Errno 101]' in reason:
             line1 = self._common_addon.getLocalizedString(32076)
         elif '[Errno 11001]' in reason:
             line1 = self._common_addon.getLocalizedString(32077)
         elif 'CERTIFICATE_VERIFY_FAILED' in reason:
             line1 = self._common_addon.getLocalizedString(32078)
         else:
             line1 = self._common_addon.getLocalizedString(32075)
         
     report = '[%s] [%s]/[%s]\n\n%s\n%s\n%s\n\n%s' % (self._addonid, self._addon_version, self._common_addon_version, line1, line2, line3, stacktrace)
     if rex:
         report += '\n\n%s\nResponse:\n%s' % (rex.request, rex.response)
     report += '\n\nshow_error_dialog: %s' % show_error_dialog
     Logger.error(report)
     if show_error_dialog:
         self._dialog.ok(self._addon_name, line1, line2, line3)
     if send_report:
         report_error = KodiUtils.get_addon_setting('report_error', self._common_addon_id) == 'true'
         report_error_invite = KodiUtils.get_addon_setting('report_error_invite', self._common_addon_id) == 'true'
         if not report_error and not report_error_invite:
             if not self._dialog.yesno(self._addon_name, self._common_addon.getLocalizedString(32050), None, None, self._common_addon.getLocalizedString(32012), self._common_addon.getLocalizedString(32013)):
                 KodiUtils.set_addon_setting('report_error', 'true', self._common_addon_id)
             KodiUtils.set_addon_setting('report_error_invite', 'true', self._common_addon_id)
         ErrorReport.send_report(report)
    def do_GET(self):
        Logger.debug(self.path + ': Requested')
        if self._system_monitor.abortRequested():
            Logger.debug(self.path + ': abort requested')
            return
        data = self.path.split('/')
        size = len(data)
        cached_page = self._page_cache.get(self.path)
        if cached_page:
            if cached_page['pending']:
                Logger.debug(self.path + ': Already requested. Waiting for original request...')
                max_waiting_time = time.time() + 30
                while not self._system_monitor.abortRequested() and max_waiting_time > time.time() and cached_page['pending']:
                    if self._system_monitor.waitForAbort(1):
                        break
                    cached_page = self._page_cache.get(self.path)

            if not self._system_monitor.abortRequested():
                if cached_page['pending']:
                    self.write_response(504)
                    Logger.debug(self.path + ': 504 - Gateway timeout')
                    self._page_cache.remove(self.path)
                else:
                    if 'content' in cached_page and cached_page['content']:
                        content = Utils.get_file_buffer()
                        content.write(cached_page['content'])
                        cached_page['content'] = content
                    self.write_response(cached_page['response_code'], content=Utils.get_safe_value(cached_page, 'content'), headers=Utils.get_safe_value(cached_page, 'headers', {}))
                    Logger.debug(self.path + ': %d - Served from cache' % cached_page['response_code'])
        else:
            cached_page = {'pending': True}
            self._page_cache.set(self.path, cached_page)
            if size > 1 and data[1] == self.server.service.name:
                try:
                    if size == 2:
                        cached_page['response_code'] = 303
                        cached_page['headers'] = {'location': self.path + '/'}
                    elif size > 2 and data[2]:
                        cached_page = self.handle_resource_request(data)
                    else:
                        cached_page = self.show_addon_list()
                except Exception as e:
                    httpex = ExceptionUtils.extract_exception(e, HTTPError)
                    if httpex:
                        cached_page['response_code'] = httpex.code
                    else:
                        cached_page['response_code'] = 500
                    
                    ErrorReport.handle_exception(e)
                    content = Utils.get_file_buffer()
                    content.write(ExceptionUtils.full_stacktrace(e))
                    
                    cached_page['content'] = content
            else:
                cached_page['response_code'] = 404
            cached_page['pending'] = False
            content_value = None
            if 'content' in cached_page:
                content_value = cached_page['content'].getvalue()
            self.write_response(cached_page['response_code'], content=Utils.get_safe_value(cached_page, 'content'), headers=Utils.get_safe_value(cached_page, 'headers', {}))
            cached_page['content'] = content_value
            if Utils.get_safe_value(cached_page, 'response_code', 0) >= 500:
                self._page_cache.remove(self.path)
            else:
                self._page_cache.set(self.path, cached_page)
            Logger.debug(self.path + ': Response code ' + Utils.str(cached_page['response_code']))
Esempio n. 13
0
 def on_exception(self, request, e):
     ex = ExceptionUtils.extract_exception(e, urllib2.HTTPError)
     if ex and ex.code == 404:
         self.persist_change_token(None)