def CallBlockingToWx( self, func, *args, **kwargs ): def wx_code( job_key ): try: result = func( *args, **kwargs ) job_key.SetVariable( 'result', result ) except HydrusExceptions.PermissionException as e: job_key.SetVariable( 'error', e ) except Exception as e: job_key.SetVariable( 'error', e ) HydrusData.Print( 'CallBlockingToWx just caught this error:' ) HydrusData.DebugPrint( traceback.format_exc() ) finally: job_key.Finish() job_key = ClientThreading.JobKey() job_key.Begin() wx.CallAfter( wx_code, job_key ) while not job_key.IsDone(): if self._model_shutdown: raise HydrusExceptions.ShutdownException( 'Application is shutting down!' ) time.sleep( 0.05 ) if job_key.HasVariable( 'result' ): # result can be None, for wx_code that has no return variable result = job_key.GetIfHasVariable( 'result' ) return result error = job_key.GetIfHasVariable( 'error' ) if error is not None: raise error raise HydrusExceptions.ShutdownException()
def _GetResponse( self, method_string, path_and_query, request_headers, body, attempt_number = 1 ): try: self._connection.request( method_string, path_and_query, headers = request_headers, body = body ) return self._connection.getresponse() except ( httplib.CannotSendRequest, httplib.BadStatusLine ): # for some reason, we can't send a request on the current connection, so let's make a new one and try again! time.sleep( 1 ) if attempt_number <= 3: self._RefreshConnection() return self._GetResponse( method_string, path_and_query, request_headers, body, attempt_number = attempt_number + 1 ) else: raise except socket.error as e: if e.errno == errno.WSAEACCES: text = 'The hydrus client did not have permission to make a connection to ' + HydrusData.ToUnicode( self._host ) if self._port is not None: text += ' on port ' + HydrusData.ToUnicode( self._port ) text += '. This is usually due to a firewall stopping it.' raise HydrusExceptions.FirewallException( text ) elif e.errno == errno.WSAECONNRESET: time.sleep( 5 ) if attempt_number <= 3: self._RefreshConnection() return self._GetResponse( method_string, path_and_query, request_headers, body, attempt_number = attempt_number + 1 ) else: text = 'The hydrus client\'s connection to ' + HydrusData.ToUnicode( self._host ) + ' kept on being reset by the remote host, so the attempt was abandoned.' raise HydrusExceptions.NetworkException( text ) else: raise
def CheckHydrusVersion(service_key, service_type, response_headers): service_string = HC.service_string_lookup[service_type] if 'server' not in response_headers or service_string not in response_headers[ 'server']: HC.app.Write( 'service_updates', { service_key: [ HC.ServiceUpdate(HC.SERVICE_UPDATE_ACCOUNT, HC.GetUnknownAccount()) ] }) raise HydrusExceptions.WrongServiceTypeException('Target was not a ' + service_string + '!') server_header = response_headers['server'] (service_string_gumpf, network_version) = server_header.split('/') network_version = int(network_version) if network_version != HC.NETWORK_VERSION: if network_version > HC.NETWORK_VERSION: message = 'Your client is out of date; please download the latest release.' else: message = 'The server is out of date; please ask its admin to update to the latest release.' raise HydrusExceptions.NetworkVersionException( 'Network version mismatch! The server\'s network version was ' + u(network_version) + ', whereas your client\'s is ' + u(HC.NETWORK_VERSION) + '! ' + message)
def _threadDoGETJob( self, request ): self._checkBandwidth( request ) # no permission check as any functional account can get thumbnails hash = request.hydrus_args[ 'hash' ] ( valid, mime ) = HG.server_controller.Read( 'service_has_file', self._service_key, hash ) if not valid: raise HydrusExceptions.NotFoundException( 'Thumbnail not found on this service!' ) if mime not in HC.MIMES_WITH_THUMBNAILS: raise HydrusExceptions.NotFoundException( 'That mime should not have a thumbnail!' ) path = ServerFiles.GetThumbnailPath( hash ) response_context = HydrusServerResources.ResponseContext( 200, mime = HC.APPLICATION_OCTET_STREAM, path = path ) return response_context
def _CheckHydrusVersion(self, service_type, response): service_string = HC.service_string_lookup[service_type] headers = response.headers if 'server' not in headers or service_string not in headers['server']: raise HydrusExceptions.WrongServiceTypeException( 'Target was not a ' + service_string + '!') server_header = headers['server'] (service_string_gumpf, network_version) = server_header.split('/') network_version = int(network_version) if network_version != HC.NETWORK_VERSION: if network_version > HC.NETWORK_VERSION: message = 'Your client is out of date; please download the latest release.' else: message = 'The server is out of date; please ask its admin to update to the latest release.' raise HydrusExceptions.NetworkVersionException( 'Network version mismatch! The server\'s network version was ' + str(network_version) + ', whereas your client\'s is ' + str(HC.NETWORK_VERSION) + '! ' + message)
def AddUPnPMapping( internal_client, internal_port, external_port, protocol, description, duration = 3600 ): cmd = '"' + upnpc_path + '" -e "' + description + '" -a ' + internal_client + ' ' + str( internal_port ) + ' ' + str( external_port ) + ' ' + protocol + ' ' + str( duration ) p = subprocess.Popen( shlex.split( cmd ), stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, startupinfo = HydrusData.GetHideTerminalSubprocessStartupInfo() ) HydrusData.WaitForProcessToFinish( p, 30 ) ( output, error ) = p.communicate() if 'x.x.x.x:' + str( external_port ) + ' TCP is redirected to internal ' + internal_client + ':' + str( internal_port ) in output: raise HydrusExceptions.FirewallException( 'The UPnP mapping of ' + internal_client + ':' + internal_port + '->external:' + external_port + ' already exists as a port forward. If this UPnP mapping is automatic, please disable it.' ) if output is not None and 'failed with code' in output: if 'UnknownError' in output: raise HydrusExceptions.FirewallException( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode( output ) ) else: raise Exception( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode( output ) ) if error is not None and len( error ) > 0: raise Exception( 'Problem while trying to add UPnP mapping:' + os.linesep * 2 + HydrusData.ToUnicode( error ) )
def GetFileInfo(path, mime=None): size = os.path.getsize(path) if size == 0: raise HydrusExceptions.SizeException('File is of zero length!') if mime is None: mime = GetMime(path) if mime not in HC.ALLOWED_MIMES: raise HydrusExceptions.MimeException('Filetype is not permitted!') width = None height = None duration = None num_frames = None num_words = None if mime in (HC.IMAGE_JPEG, HC.IMAGE_PNG, HC.IMAGE_GIF): ((width, height), duration, num_frames) = HydrusImageHandling.GetImageProperties(path) elif mime == HC.APPLICATION_FLASH: ((width, height), duration, num_frames) = HydrusFlashHandling.GetFlashProperties(path) elif mime in (HC.IMAGE_APNG, HC.VIDEO_AVI, HC.VIDEO_FLV, HC.VIDEO_WMV, HC.VIDEO_MOV, HC.VIDEO_MP4, HC.VIDEO_MKV, HC.VIDEO_WEBM, HC.VIDEO_MPEG): ((width, height), duration, num_frames) = HydrusVideoHandling.GetFFMPEGVideoProperties(path) elif mime == HC.APPLICATION_PDF: num_words = HydrusDocumentHandling.GetPDFNumWords(path) elif mime == HC.AUDIO_MP3: duration = HydrusAudioHandling.GetMP3Duration(path) elif mime == HC.AUDIO_OGG: duration = HydrusAudioHandling.GetOGGVorbisDuration(path) elif mime == HC.AUDIO_FLAC: duration = HydrusAudioHandling.GetFLACDuration(path) elif mime == HC.AUDIO_WMA: duration = HydrusAudioHandling.GetWMADuration(path) return (size, mime, width, height, duration, num_frames, num_words)
def TryToClose( self ): if self._job_key.IsDone(): self._ReleaseMessage() else: if self._job_key.IsCancellable(): with ClientGUIDialogs.DialogYesNo( self, 'Cancel/stop job?' ) as dlg: if dlg.ShowModal() == wx.ID_YES: self._job_key.Cancel() self._ReleaseMessage() else: raise HydrusExceptions.VetoException() else: raise HydrusExceptions.VetoException( 'Unfortunately, this job cannot be cancelled. If it really is taking too long, please kill the client through task manager.' )
def GetFilePath(location, hash, mime=None): if mime is None: path = None for potential_mime in HC.ALLOWED_MIMES: potential_path = GetExpectedFilePath(location, hash, potential_mime) if os.path.exists(potential_path): path = potential_path break else: path = GetExpectedFilePath(location, hash, mime) if path is None: raise HydrusExceptions.FileMissingException( 'File not found in directory ' + location + '!') elif not os.path.exists(path): raise HydrusExceptions.FileMissingException( 'File not found in path + ' + path + '!') return path
def ParseFileArguments( path ): HydrusImageHandling.ConvertToPngIfBmp( path ) hash = HydrusFileHandling.GetHashFromPath( path ) try: mime = HydrusFileHandling.GetMime( path ) if mime in HC.IMAGES and HydrusImageHandling.IsDecompressionBomb( path ): raise HydrusExceptions.ForbiddenException( 'File seemed to be a Decompression Bomb!' ) ( size, mime, width, height, duration, num_frames, num_words ) = HydrusFileHandling.GetFileInfo( path, mime ) except HydrusExceptions.SizeException: raise HydrusExceptions.ForbiddenException( 'File is of zero length!' ) except HydrusExceptions.MimeException: raise HydrusExceptions.ForbiddenException( 'Filetype is not permitted!' ) except Exception as e: raise HydrusExceptions.ForbiddenException( HydrusData.ToUnicode( e ) ) args = {} args[ 'path' ] = path args[ 'hash' ] = hash args[ 'size' ] = size args[ 'mime' ] = mime if width is not None: args[ 'width' ] = width if height is not None: args[ 'height' ] = height if duration is not None: args[ 'duration' ] = duration if num_frames is not None: args[ 'num_frames' ] = num_frames if num_words is not None: args[ 'num_words' ] = num_words if mime in HC.MIMES_WITH_THUMBNAILS: try: thumbnail = HydrusFileHandling.GenerateThumbnail( path, mime ) except Exception as e: tb = traceback.format_exc() raise HydrusExceptions.ForbiddenException( 'Could not generate thumbnail from that file:' + os.linesep + tb ) args[ 'thumbnail' ] = thumbnail return args
def Test( self, text ): text_len = len( text ) presentation_text = '"' + text + '"' if self._min_chars is not None and text_len < self._min_chars: raise HydrusExceptions.StringMatchException( presentation_text + ' had fewer than ' + HydrusData.ConvertIntToPrettyString( self._min_chars ) + ' characters' ) if self._max_chars is not None and text_len > self._max_chars: raise HydrusExceptions.StringMatchException( presentation_text + ' had more than ' + HydrusData.ConvertIntToPrettyString( self._max_chars ) + ' characters' ) if self._match_type == STRING_MATCH_FIXED: if text != self._match_value: raise HydrusExceptions.StringMatchException( presentation_text + ' did not exactly match "' + self._match_value + '"' ) elif self._match_type in ( STRING_MATCH_FLEXIBLE, STRING_MATCH_REGEX ): if self._match_type == STRING_MATCH_FLEXIBLE: if self._match_value == ALPHA: r = '^[a-zA-Z]+$' fail_reason = ' had non-alpha characters' elif self._match_value == ALPHANUMERIC: r = '^[a-zA-Z\d]+$' fail_reason = ' had non-alphanumeric characters' elif self._match_value == NUMERIC: r = '^\d+$' fail_reason = ' had non-numeric characters' elif self._match_type == STRING_MATCH_REGEX: r = self._match_value fail_reason = ' did not match "' + r + '"' if re.search( r, text, flags = re.UNICODE ) is None: raise HydrusExceptions.StringMatchException( presentation_text + fail_reason ) elif self._match_type == STRING_MATCH_ANY: pass
def Test(self, url): # split the url into parts according to urlparse p = urlparse.urlparse(url) # test p.netloc with netloc, taking subdomain_is_important into account url_path = p.path while url_path.startswith('/'): url_path = url_path[1:] url_path_components = p.path.split('/') if len(url_path_components) < len(self._path_components): raise HydrusExceptions.URLMatchException( p.path + ' did not have ' + str(len(self._path_components)) + ' components') for (url_path_component, expected_path_component) in zip(url_path_components, self._path_components): try: expected_path_component.Test(url_path_component) except HydrusExceptions.StringMatchException as e: raise HydrusExceptions.URLMatchException(unicode(e)) url_parameters_list = urlparse.parse_qsl(p.query) if len(url_parameters_list) < len(self._parameters): raise HydrusExceptions.URLMatchException( p.query + ' did not have ' + str(len(self._parameters)) + ' value pairs') for (key, url_value) in url_parameters_list: if key not in self._parameters: raise HydrusExceptions.URLMatchException(key + ' not found in ' + p.query) expected_value = self._parameters[key] try: expected_value.Test(url_value) except HydrusExceptions.StringMatchException as e: raise HydrusExceptions.URLMatchException(unicode(e))
def _checkBandwidth( self, request ): if not self._service.BandwidthOK(): raise HydrusExceptions.BandwidthException( 'This service has run out of bandwidth. Please try again later.' ) if not HG.server_controller.ServerBandwidthOK(): raise HydrusExceptions.BandwidthException( 'This server has run out of bandwidth. Please try again later.' )
def Start( self, engine, domain, credentials, temp_variables ): # e.g. converting 'website.com' to 'login.website.com' url_base = self._domain_string_converter.Convert( domain ) arguments = {} arguments.update( self._statics ) self._TestCredentials( credentials ) for ( credential_type, pretty_name, arg_name, string_match ) in self._required_credentials: arguments[ arg_name ] = credentials.GetCredential( arg_name ) for name in self._required_temps: if name not in temp_variables: raise HydrusExceptions.ValidationException( 'The temporary variable \'' + name + '\' was not found!' ) arguments[ name ] = temp_variables[ name ] if self._method == 'POST': pass # make it into body elif self._method == 'GET': pass # make it into query # construct the url, failing if creds or temps missing # hit the url, failing on connection fault or whatever for parsing_node in self._content_parsing_nodes: try: parsing_node.Vetoes() except HydrusExceptions.VetoException as e: raise HydrusExceptions.ValidationException( unicode( e ) ) # if content type is a temp variable: # get it and add to temp_variables pass
def CheckPermission( self, permission ): if self._IsBanned(): raise HydrusExceptions.PermissionException( 'This account is banned!' ) if self._IsExpired(): raise HydrusExceptions.PermissionException( 'This account is expired.' ) if self._IsBytesExceeded(): raise HydrusExceptions.PermissionException( 'You have hit your data transfer limit, and cannot make any more requests for the month.' ) if self._IsRequestsExceeded(): raise HydrusExceptions.PermissionException( 'You have hit your requests limit, and cannot make any more requests for the month.' ) if not self._info[ 'account_type' ].HasPermission( permission ): raise HydrusExceptions.PermissionException( 'You do not have permission to do that.' )
def _parseAccessKey( self, request ): if not request.requestHeaders.hasHeader( 'Hydrus-Key' ): raise HydrusExceptions.PermissionException( 'No hydrus key header found!' ) hex_keys = request.requestHeaders.getRawHeaders( 'Hydrus-Key' ) hex_key = hex_keys[0] try: access_key = hex_key.decode( 'hex' ) except: raise HydrusExceptions.ForbiddenException( 'Could not parse the hydrus key!' ) return access_key
def ProcessStartingAction( db_dir, action ): already_running = HydrusData.IsAlreadyRunning( db_dir, 'server' ) if action == 'start': if already_running: HydrusData.Print( 'The server is already running. Would you like to [s]top it, [r]estart it, or e[x]it?' ) answer = raw_input() if len( answer ) > 0: answer = answer[0] if answer == 's': return 'stop' elif answer == 'r': return 'restart' raise HydrusExceptions.PermissionException( 'Exiting!' ) else: return action elif action == 'stop': if already_running: return action else: raise HydrusExceptions.PermissionException( 'The server is not running, so it cannot be stopped!' ) elif action == 'restart': if already_running: return action else: return 'start'
def _ParseImagePage(self, html, page_url): if 'member_illust.php?mode=manga' in html: manga_url = page_url.replace('medium', 'manga') raise HydrusExceptions.MimeException( page_url + ' was manga, not a single image, so could not be downloaded.') if 'member_illust.php?mode=ugoira_view' in html: raise HydrusExceptions.MimeException( page_url + ' was ugoira, not a single image, so could not be downloaded.') soup = ClientParsing.GetSoup(html) # original_image = soup.find(class_='original-image') image_url = original_image[ 'data-src'] # http://i3.pixiv.net/img-original/img/2014/01/25/19/21/56/41171994_p0.jpg # tags_parent = soup.find('section', class_='work-tags') # <a href="/search.php?s_mode=s_tag_full&word=%E3%83%8F%E3%83%B3%E3%83%89%E3%83%A1%E3%82%A4%E3%83%89" class="text">[unicode tag here]</a> tags = [ link.string for link in tags_parent.find_all('a', class_='text') ] user = soup.find('h1', class_='user') if user is not None: tags.append('creator:' + user.string) title_parent = soup.find('section', class_=re.compile('work-info')) if title_parent is not None: title = title_parent.find('h1', class_='title') if title is not None: tags.append('title:' + title.string) return (image_url, tags)
def WaitUntilDone( self ): while True: self._is_done_event.wait( 5 ) with self._lock: if not self._is_started and self._death_time is not None and HydrusData.TimeHasPassed( self._death_time ): raise Exception( 'Network job death time reached--not sure what the error was. Maybe a paused service?' ) if self.IsDone(): break with self._lock: if self.engine.controller.ModelIsShutdown(): raise HydrusExceptions.ShutdownException() elif self._error_exception is not None: if isinstance( self._error_exception, Exception ): raise self._error_exception else: raise Exception( 'Problem in network error handling.' ) elif self._IsCancelled(): if self._method == 'POST': message = 'Upload cancelled: ' + self._status_text else: message = 'Download cancelled: ' + self._status_text raise HydrusExceptions.CancelledException( message )
def CheckFFMPEGError( lines ): if len( lines ) == 0: raise HydrusExceptions.MimeException( 'Could not parse that file--no FFMPEG output given.' ) if "No such file or directory" in lines[-1]: raise IOError( "File not found!" ) if 'Invalid data' in lines[-1]: raise HydrusExceptions.MimeException( 'FFMPEG could not parse.' )
def GetValue(self): name = self._name.GetValue() path = HydrusData.ToUnicode(self._path.GetPath()) export_type = self._type.GetChoice() delete_from_client_after_export = self._delete_from_client_after_export.GetValue( ) file_search_context = self._searchbox.GetFileSearchContext() predicates = self._predicates_box.GetPredicates() file_search_context.SetPredicates(predicates) period = self._period.GetValue() phrase = self._pattern.GetValue() if self._path.GetPath() in ('', None): raise HydrusExceptions.VetoException( 'You must enter a folder path to export to!') phrase = self._pattern.GetValue() try: ClientExporting.ParseExportPhrase(phrase) except Exception as e: raise HydrusExceptions.VetoException( 'Could not parse that export phrase! ' + HydrusData.ToUnicode(e)) export_folder = ClientExporting.ExportFolder( name, path=path, export_type=export_type, delete_from_client_after_export=delete_from_client_after_export, file_search_context=file_search_context, period=period, phrase=phrase) return export_folder
def CheckTagNotEmpty(tag): (namespace, subtag) = SplitTag(tag) if subtag == '': raise HydrusExceptions.SizeException('Received a zero-length tag!')
def _threadDoPOSTJob(self, request): services = request.hydrus_args['services'] unique_ports = {service.GetPort() for service in services} if len(unique_ports) < len(services): raise HydrusExceptions.PermissionException( 'It looks like some of those services share ports! Please give them unique ports!' ) if len(unique_ports) < services: pass with HG.dirty_object_lock: service_keys_to_access_keys = HG.server_controller.WriteSynchronous( 'services', request.hydrus_account, services) HG.server_controller.SetServices(services) body = HydrusNetwork.DumpToBodyString( {'service_keys_to_access_keys': service_keys_to_access_keys}) response_context = HydrusServerResources.ResponseContext(200, body=body) return response_context
def wait_for_free_slot( controller, subs_jobs, max_simultaneous_subscriptions ): time.sleep( 0.1 ) while True: p1 = controller.options[ 'pause_subs_sync' ] p2 = HydrusThreading.IsThreadShuttingDown() if p1 or p2: if HG.subscription_report_mode: HydrusData.ShowText( 'Subscriptions cancelling. Global sub pause is ' + str( p1 ) + ' and sub daemon thread shutdown status is ' + str( p2 ) + '.' ) if p2: for ( thread, job ) in subs_jobs: HydrusThreading.ShutdownThread( thread ) raise HydrusExceptions.CancelledException( 'subs cancelling or thread shutting down' ) filter_finished_jobs( subs_jobs ) if len( subs_jobs ) < max_simultaneous_subscriptions: return time.sleep( 1.0 )
def InitClientFilesManager(self): self.client_files_manager = ClientCaches.ClientFilesManager(self) missing_locations = self.client_files_manager.GetMissing() while len(missing_locations) > 0: with ClientGUITopLevelWindows.DialogManage( None, 'repair file system') as dlg: panel = ClientGUIScrolledPanelsManagement.RepairFileSystemPanel( dlg, missing_locations) dlg.SetPanel(panel) if dlg.ShowModal() == wx.ID_OK: self.client_files_manager = ClientCaches.ClientFilesManager( self) missing_locations = self.client_files_manager.GetMissing() else: raise HydrusExceptions.PermissionException( 'File system failed, user chose to quit.')
def _callbackParsePOSTArgs( self, request ): request.content.seek( 0 ) if not request.requestHeaders.hasHeader( 'Content-Type' ): hydrus_args = {} else: content_types = request.requestHeaders.getRawHeaders( 'Content-Type' ) content_type = content_types[0] try: mime = HC.mime_enum_lookup[ content_type ] except: raise HydrusExceptions.ForbiddenException( 'Did not recognise Content-Type header!' ) total_bytes_read = 0 if mime == HC.APPLICATION_JSON: json_string = request.content.read() total_bytes_read += len( json_string ) hydrus_args = HydrusNetwork.ParseBodyString( json_string ) else: ( os_file_handle, temp_path ) = HydrusPaths.GetTempPath() request.temp_file_info = ( os_file_handle, temp_path ) with open( temp_path, 'wb' ) as f: for block in HydrusPaths.ReadFileLikeAsBlocks( request.content ): f.write( block ) total_bytes_read += len( block ) decompression_bombs_ok = self._DecompressionBombsOK( request ) hydrus_args = ParseFileArguments( temp_path, decompression_bombs_ok ) self._reportDataUsed( request, total_bytes_read ) request.hydrus_args = hydrus_args return request
def _checkUserAgent( self, request ): request.is_hydrus_user_agent = False if request.requestHeaders.hasHeader( 'User-Agent' ): user_agent_texts = request.requestHeaders.getRawHeaders( 'User-Agent' ) user_agent_text = user_agent_texts[0] try: user_agents = user_agent_text.split( ' ' ) except: return # crazy user agent string, so just assume not a hydrus client for user_agent in user_agents: if '/' in user_agent: ( client, network_version ) = user_agent.split( '/', 1 ) if client == 'hydrus': request.is_hydrus_user_agent = True network_version = int( network_version ) if network_version == HC.NETWORK_VERSION: return else: if network_version < HC.NETWORK_VERSION: message = 'Your client is out of date; please download the latest release.' else: message = 'This server is out of date; please ask its admin to update to the latest release.' raise HydrusExceptions.NetworkVersionException( 'Network version mismatch! This server\'s network version is ' + str( HC.NETWORK_VERSION ) + ', whereas your client\'s is ' + str( network_version ) + '! ' + message )
def CheckCanLogin(self, credentials): if self._validity == VALIDITY_INVALID: raise HydrusExceptions.LoginException( 'Login script is not valid: ' + self._error_reason) for step in self._login_steps: try: step.TestCredentials(credentials) except HydrusExceptions.ValidationException as e: raise HydrusExceptions.LoginException(str(e))
def GenerateLoginProcess(self, network_context): with self._lock: if network_context.context_type == CC.NETWORK_CONTEXT_DOMAIN: login_network_context = self._GetLoginNetworkContext( network_context) if login_network_context is None: raise HydrusExceptions.DataMissing() (login_script, credentials) = self._domains_to_login_scripts_and_credentials[ login_network_context.context_data] login_process = LoginProcessDomain(self.engine, login_network_context, login_script, credentials) elif network_context.context_type == CC.NETWORK_CONTEXT_HYDRUS: login_process = LoginProcessHydrus(self.engine, network_context, self._hydrus_login_script) return login_process
def _checkSession( self, request ): if not request.requestHeaders.hasHeader( 'Cookie' ): raise HydrusExceptions.PermissionException( 'No cookies found!' ) cookie_texts = request.requestHeaders.getRawHeaders( 'Cookie' ) cookie_text = cookie_texts[0] try: cookies = Cookie.SimpleCookie( cookie_text ) if 'session_key' not in cookies: session_key = None else: session_key = cookies[ 'session_key' ].value.decode( 'hex' ) except: raise Exception( 'Problem parsing cookies!' ) account = HG.server_controller.server_session_manager.GetAccount( self._service_key, session_key ) request.hydrus_account = account return request