hydrus/hydrus/client/importing/ClientImportFileSeeds.py

2962 lines
104 KiB
Python
Raw Normal View History

2021-11-17 21:22:27 +00:00
import bisect
2020-05-20 21:36:02 +00:00
import collections
2020-09-09 20:59:19 +00:00
import itertools
2020-05-20 21:36:02 +00:00
import os
2020-06-11 12:01:08 +00:00
import random
2021-07-14 20:42:19 +00:00
import re
2020-05-20 21:36:02 +00:00
import threading
import time
import traceback
import typing
import urllib.parse
2020-04-22 21:00:35 +00:00
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusData
from hydrus.core import HydrusExceptions
from hydrus.core import HydrusFileHandling
from hydrus.core import HydrusGlobals as HG
from hydrus.core import HydrusPaths
from hydrus.core import HydrusSerialisable
from hydrus.core import HydrusTags
from hydrus.core import HydrusTemp
2018-06-06 21:27:02 +00:00
2020-07-29 20:52:44 +00:00
from hydrus.client import ClientConstants as CC
from hydrus.client import ClientData
from hydrus.client import ClientParsing
from hydrus.client import ClientTime
2021-06-30 21:27:35 +00:00
from hydrus.client.importing import ClientImportFiles
2020-07-29 20:52:44 +00:00
from hydrus.client.importing import ClientImporting
2021-06-30 21:27:35 +00:00
from hydrus.client.importing.options import FileImportOptions
2022-08-17 20:54:59 +00:00
from hydrus.client.importing.options import NoteImportOptions
2021-11-24 21:59:58 +00:00
from hydrus.client.importing.options import PresentationImportOptions
2021-06-30 21:27:35 +00:00
from hydrus.client.importing.options import TagImportOptions
from hydrus.client.metadata import ClientTags
from hydrus.client.networking import ClientNetworkingFunctions
2020-07-29 20:52:44 +00:00
2018-06-27 19:27:05 +00:00
FILE_SEED_TYPE_HDD = 0
FILE_SEED_TYPE_URL = 1
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
def FileURLMappingHasUntrustworthyNeighbours( hash: bytes, url: str ):
# let's see if the file that has this url has any other interesting urls
# if the file has another url with the same url class, then this is prob an unreliable 'alternate' source url attribution, and untrustworthy
try:
url = HG.client_controller.network_engine.domain_manager.NormaliseURL( url )
except HydrusExceptions.URLClassException:
# this url is so borked it doesn't parse. can't make neighbour inferences about it
return False
url_class = HG.client_controller.network_engine.domain_manager.GetURLClass( url )
# direct file URLs do not care about neighbours, since that can mean tokenised or different CDN URLs
url_is_worried_about_neighbours = url_class is not None and url_class.GetURLType() not in ( HC.URL_TYPE_FILE, HC.URL_TYPE_UNKNOWN )
if url_is_worried_about_neighbours:
media_result = HG.client_controller.Read( 'media_result', hash )
file_urls = media_result.GetLocationsManager().GetURLs()
# normalise to collapse http/https dupes
file_urls = HG.client_controller.network_engine.domain_manager.NormaliseURLs( file_urls )
for file_url in file_urls:
if file_url == url:
# obviously when we find ourselves, that's not a dupe
continue
if ClientNetworkingFunctions.ConvertURLIntoDomain( file_url ) != ClientNetworkingFunctions.ConvertURLIntoDomain( url ):
# checking here for the day when url classes can refer to multiple domains
continue
try:
file_url_class = HG.client_controller.network_engine.domain_manager.GetURLClass( file_url )
except HydrusExceptions.URLClassException:
# this is borked text, not matchable
continue
if file_url_class is None or url_class.GetURLType() in ( HC.URL_TYPE_FILE, HC.URL_TYPE_UNKNOWN ):
# being slightly superfluous here, but this file url can't be an untrustworthy neighbour
continue
if file_url_class == url_class:
# oh no, the file this source url refers to has a different known url in this same domain
# it is more likely that an edit on this site points to the original elsewhere
return True
return False
2018-06-27 19:27:05 +00:00
class FileSeed( HydrusSerialisable.SerialisableBase ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED
2018-06-06 21:27:02 +00:00
SERIALISABLE_NAME = 'File Import'
2022-08-17 20:54:59 +00:00
SERIALISABLE_VERSION = 6
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def __init__( self, file_seed_type: int = None, file_seed_data: str = None ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if file_seed_type is None:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed_type = FILE_SEED_TYPE_URL
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if file_seed_data is None:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed_data = 'https://big-guys.4u/monica_lewinsky_hott.tiff.exe.vbs'
2018-06-06 21:27:02 +00:00
HydrusSerialisable.SerialisableBase.__init__( self )
2018-06-27 19:27:05 +00:00
self.file_seed_type = file_seed_type
self.file_seed_data = file_seed_data
2018-06-06 21:27:02 +00:00
self.created = HydrusData.GetNow()
self.modified = self.created
self.source_time = None
self.status = CC.STATUS_UNKNOWN
self.note = ''
2022-05-18 20:18:25 +00:00
self._cloudflare_last_modified_time = None
2018-06-06 21:27:02 +00:00
self._referral_url = None
2020-09-16 20:46:54 +00:00
self._external_filterable_tags = set()
self._external_additional_service_keys_to_tags = ClientTags.ServiceKeysToTags()
2019-02-27 23:03:30 +00:00
2021-10-13 20:16:57 +00:00
self._primary_urls = set()
self._source_urls = set()
2018-06-06 21:27:02 +00:00
self._tags = set()
2022-08-17 20:54:59 +00:00
self._names_and_notes_dict = dict()
2018-06-06 21:27:02 +00:00
self._hashes = {}
def __eq__( self, other ):
2020-01-22 21:04:43 +00:00
if isinstance( other, FileSeed ):
return self.__hash__() == other.__hash__()
return NotImplemented
2018-06-06 21:27:02 +00:00
def __hash__( self ):
2018-06-27 19:27:05 +00:00
return ( self.file_seed_type, self.file_seed_data ).__hash__()
2018-06-06 21:27:02 +00:00
def __ne__( self, other ):
return self.__hash__() != other.__hash__()
2021-10-13 20:16:57 +00:00
def _AddPrimaryURLs( self, urls ):
2021-12-22 22:31:23 +00:00
if len( urls ) == 0:
return
urls = ClientNetworkingFunctions.NormaliseAndFilterAssociableURLs( urls )
2021-10-13 20:16:57 +00:00
2021-12-22 22:31:23 +00:00
if self.file_seed_type == FILE_SEED_TYPE_URL:
urls.discard( self.file_seed_data )
if self._referral_url is not None:
urls.discard( self._referral_url )
2021-10-13 20:16:57 +00:00
self._primary_urls.update( urls )
self._source_urls.difference_update( urls )
def _AddSourceURLs( self, urls ):
2021-12-22 22:31:23 +00:00
if len( urls ) == 0:
return
urls = ClientNetworkingFunctions.NormaliseAndFilterAssociableURLs( urls )
all_primary_urls = set()
2021-10-13 20:16:57 +00:00
2021-12-22 22:31:23 +00:00
if self.file_seed_type == FILE_SEED_TYPE_URL:
all_primary_urls.add( self.file_seed_data )
2021-12-22 22:31:23 +00:00
if self._referral_url is not None:
all_primary_urls.add( self._referral_url )
2021-12-22 22:31:23 +00:00
all_primary_urls.update( self._primary_urls )
2021-12-22 22:31:23 +00:00
urls.difference_update( all_primary_urls )
2021-12-22 22:31:23 +00:00
primary_url_classes = { HG.client_controller.network_engine.domain_manager.GetURLClass( url ) for url in all_primary_urls }
primary_url_classes.discard( None )
2021-12-22 22:31:23 +00:00
# ok when a booru has a """"""source"""""" url that points to a file alternate on the same booru, that isn't what we call a source url
# so anything that has a source url with the same url class as our primaries, just some same-site loopback, we'll dump
urls = { url for url in urls if HG.client_controller.network_engine.domain_manager.GetURLClass( url ) not in primary_url_classes }
2021-12-22 22:31:23 +00:00
2021-10-13 20:16:57 +00:00
self._source_urls.update( urls )
2021-06-30 21:27:35 +00:00
def _CheckTagsVeto( self, tags, tag_import_options: TagImportOptions.TagImportOptions ):
2018-06-06 21:27:02 +00:00
2021-07-14 20:42:19 +00:00
if len( tags ) > 0:
tags_to_siblings = HG.client_controller.Read( 'tag_siblings_lookup', CC.COMBINED_TAG_SERVICE_KEY, tags )
all_chain_tags = set( itertools.chain.from_iterable( tags_to_siblings.values() ) )
tag_import_options.CheckTagsVeto( tags, all_chain_tags )
2018-06-06 21:27:02 +00:00
def _GetSerialisableInfo( self ):
2020-09-16 20:46:54 +00:00
serialisable_external_filterable_tags = list( self._external_filterable_tags )
serialisable_external_additional_service_keys_to_tags = self._external_additional_service_keys_to_tags.GetSerialisableTuple()
2019-02-27 23:03:30 +00:00
2021-10-13 20:16:57 +00:00
serialisable_primary_urls = list( self._primary_urls )
serialisable_source_urls = list( self._source_urls )
2018-06-06 21:27:02 +00:00
serialisable_tags = list( self._tags )
2022-08-17 20:54:59 +00:00
serialisable_names_and_notes_dict = list( self._names_and_notes_dict.items() )
2019-01-09 22:59:03 +00:00
serialisable_hashes = [ ( hash_type, hash.hex() ) for ( hash_type, hash ) in list(self._hashes.items()) if hash is not None ]
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
return (
self.file_seed_type,
self.file_seed_data,
self.created,
self.modified,
self.source_time,
self.status,
self.note,
self._referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_primary_urls,
serialisable_source_urls,
serialisable_tags,
2022-08-17 20:54:59 +00:00
serialisable_names_and_notes_dict,
2021-10-13 20:16:57 +00:00
serialisable_hashes
)
2018-06-06 21:27:02 +00:00
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
2021-10-13 20:16:57 +00:00
(
self.file_seed_type,
self.file_seed_data,
self.created,
self.modified,
self.source_time,
self.status,
self.note,
self._referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_primary_urls,
serialisable_source_urls,
serialisable_tags,
2022-08-17 20:54:59 +00:00
serialisable_names_and_notes_dict,
2021-10-13 20:16:57 +00:00
serialisable_hashes
) = serialisable_info
2019-02-27 23:03:30 +00:00
2020-09-16 20:46:54 +00:00
self._external_filterable_tags = set( serialisable_external_filterable_tags )
self._external_additional_service_keys_to_tags = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_external_additional_service_keys_to_tags )
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
self._primary_urls = set( serialisable_primary_urls )
self._source_urls = set( serialisable_source_urls )
2018-06-06 21:27:02 +00:00
self._tags = set( serialisable_tags )
2022-08-17 20:54:59 +00:00
self._names_and_notes_dict = dict( serialisable_names_and_notes_dict )
2019-01-09 22:59:03 +00:00
self._hashes = { hash_type : bytes.fromhex( encoded_hash ) for ( hash_type, encoded_hash ) in serialisable_hashes if encoded_hash is not None }
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
def _GetImportOptionsLookupURL( self ) -> str:
2018-07-11 20:23:51 +00:00
2022-08-17 20:54:59 +00:00
if self.IsAPostURL():
2018-07-11 20:23:51 +00:00
2022-08-17 20:54:59 +00:00
lookup_url = self.file_seed_data
else:
if self._referral_url is not None:
2018-07-11 20:23:51 +00:00
2022-08-17 20:54:59 +00:00
lookup_url = self._referral_url
2018-07-11 20:23:51 +00:00
else:
2022-08-17 20:54:59 +00:00
lookup_url = self.file_seed_data
2018-07-11 20:23:51 +00:00
2022-08-17 20:54:59 +00:00
return lookup_url
def _SetupNoteImportOptions( self, given_note_import_options: NoteImportOptions.NoteImportOptions ) -> NoteImportOptions.NoteImportOptions:
if given_note_import_options.IsDefault():
lookup_url = self._GetImportOptionsLookupURL()
note_import_options = HG.client_controller.network_engine.domain_manager.GetDefaultNoteImportOptionsForURL( lookup_url )
else:
note_import_options = given_note_import_options
return note_import_options
def _SetupTagImportOptions( self, given_tag_import_options: TagImportOptions.TagImportOptions ) -> TagImportOptions.TagImportOptions:
if given_tag_import_options.IsDefault():
lookup_url = self._GetImportOptionsLookupURL()
tag_import_options = HG.client_controller.network_engine.domain_manager.GetDefaultTagImportOptionsForURL( lookup_url )
2018-07-11 20:23:51 +00:00
else:
tag_import_options = given_tag_import_options
return tag_import_options
2018-06-06 21:27:02 +00:00
def _UpdateModified( self ):
self.modified = HydrusData.GetNow()
def _UpdateSerialisableInfo( self, version, old_serialisable_info ):
if version == 1:
2018-06-27 19:27:05 +00:00
( file_seed_type, file_seed_data, created, modified, source_time, status, note, serialisable_urls, serialisable_tags, serialisable_hashes ) = old_serialisable_info
2018-06-06 21:27:02 +00:00
referral_url = None
2018-06-27 19:27:05 +00:00
new_serialisable_info = ( file_seed_type, file_seed_data, created, modified, source_time, status, note, referral_url, serialisable_urls, serialisable_tags, serialisable_hashes )
2018-06-06 21:27:02 +00:00
return ( 2, new_serialisable_info )
2019-02-27 23:03:30 +00:00
if version == 2:
( file_seed_type, file_seed_data, created, modified, source_time, status, note, referral_url, serialisable_urls, serialisable_tags, serialisable_hashes ) = old_serialisable_info
2020-09-16 20:46:54 +00:00
external_additional_service_keys_to_tags = ClientTags.ServiceKeysToTags()
2019-02-27 23:03:30 +00:00
2020-09-16 20:46:54 +00:00
serialisable_external_additional_service_keys_to_tags = external_additional_service_keys_to_tags.GetSerialisableTuple()
2019-02-27 23:03:30 +00:00
2020-09-16 20:46:54 +00:00
new_serialisable_info = ( file_seed_type, file_seed_data, created, modified, source_time, status, note, referral_url, serialisable_external_additional_service_keys_to_tags, serialisable_urls, serialisable_tags, serialisable_hashes )
2019-02-27 23:03:30 +00:00
return ( 3, new_serialisable_info )
2020-09-16 20:46:54 +00:00
if version == 3:
( file_seed_type, file_seed_data, created, modified, source_time, status, note, referral_url, serialisable_external_additional_service_keys_to_tags, serialisable_urls, serialisable_tags, serialisable_hashes ) = old_serialisable_info
external_filterable_tags = set()
serialisable_external_filterable_tags = list( external_filterable_tags )
new_serialisable_info = ( file_seed_type, file_seed_data, created, modified, source_time, status, note, referral_url, serialisable_external_filterable_tags, serialisable_external_additional_service_keys_to_tags, serialisable_urls, serialisable_tags, serialisable_hashes )
return ( 4, new_serialisable_info )
2021-10-13 20:16:57 +00:00
if version == 4:
(
file_seed_type,
file_seed_data,
created,
modified,
source_time,
status,
note,
referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_urls,
serialisable_tags,
serialisable_hashes
) = old_serialisable_info
serialisable_primary_urls = serialisable_urls
serialisable_source_urls = []
new_serialisable_info = (
file_seed_type,
file_seed_data,
created,
modified,
source_time,
status,
note,
referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_primary_urls,
serialisable_source_urls,
serialisable_tags,
serialisable_hashes
)
return ( 5, new_serialisable_info )
2022-08-17 20:54:59 +00:00
if version == 5:
(
file_seed_type,
file_seed_data,
created,
modified,
source_time,
status,
note,
referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_primary_urls,
serialisable_source_urls,
serialisable_tags,
serialisable_hashes
) = old_serialisable_info
names_and_notes = []
new_serialisable_info = (
file_seed_type,
file_seed_data,
created,
modified,
source_time,
status,
note,
referral_url,
serialisable_external_filterable_tags,
serialisable_external_additional_service_keys_to_tags,
serialisable_primary_urls,
serialisable_source_urls,
serialisable_tags,
names_and_notes,
serialisable_hashes
)
return ( 6, new_serialisable_info )
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
def AddParseResults( self, parse_results, file_import_options: FileImportOptions.FileImportOptions ):
2018-06-06 21:27:02 +00:00
for ( hash_type, hash ) in ClientParsing.GetHashesFromParseResults( parse_results ):
if hash_type not in self._hashes:
self._hashes[ hash_type ] = hash
2021-10-13 20:16:57 +00:00
source_urls = ClientParsing.GetURLsFromParseResults( parse_results, ( HC.URL_TYPE_SOURCE, ) )
self._AddSourceURLs( source_urls )
2018-06-06 21:27:02 +00:00
tags = ClientParsing.GetTagsFromParseResults( parse_results )
self._tags.update( tags )
2022-08-17 20:54:59 +00:00
names_and_notes = ClientParsing.GetNamesAndNotesFromParseResults( parse_results )
self._names_and_notes_dict.update( names_and_notes )
2018-06-06 21:27:02 +00:00
source_timestamp = ClientParsing.GetTimestampFromParseResults( parse_results, HC.TIMESTAMP_TYPE_SOURCE )
if source_timestamp is not None:
2019-01-09 22:59:03 +00:00
source_timestamp = min( HydrusData.GetNow() - 30, source_timestamp )
2022-06-22 20:43:12 +00:00
self.source_time = ClientTime.MergeModifiedTimes( self.source_time, source_timestamp )
2018-06-06 21:27:02 +00:00
self._UpdateModified()
def AddTags( self, tags ):
tags = HydrusTags.CleanTags( tags )
self._tags.update( tags )
self._UpdateModified()
2022-08-17 20:54:59 +00:00
def AddNamesAndNotes( self, names_and_notes ):
self._names_and_notes_dict.update( names_and_notes )
self._UpdateModified()
2021-10-13 20:16:57 +00:00
def AddPrimaryURLs( self, urls ):
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
self._AddPrimaryURLs( urls )
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
self._UpdateModified()
2021-10-13 20:16:57 +00:00
def AddSourceURLs( self, urls ):
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
self._AddSourceURLs( urls )
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
self._UpdateModified()
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
def CheckPreFetchMetadata( self, tag_import_options: TagImportOptions.TagImportOptions ):
2018-06-06 21:27:02 +00:00
self._CheckTagsVeto( self._tags, tag_import_options )
2018-06-06 21:27:02 +00:00
2022-08-03 20:59:51 +00:00
def DownloadAndImportRawFile( self, file_url: str, file_import_options, loud_or_quiet: int, network_job_factory, network_job_presentation_context_factory, status_hook, override_bandwidth = False, forced_referral_url = None, file_seed_cache = None ):
2022-08-10 21:32:27 +00:00
file_import_options = FileImportOptions.GetRealFileImportOptions( file_import_options, loud_or_quiet )
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
self.AddPrimaryURLs( ( file_url, ) )
2018-06-06 21:27:02 +00:00
( os_file_handle, temp_path ) = HydrusTemp.GetTempPath()
2018-06-06 21:27:02 +00:00
try:
2021-11-17 21:22:27 +00:00
if forced_referral_url is not None:
referral_url = forced_referral_url
elif self.file_seed_data != file_url:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
referral_url = self.file_seed_data
2018-06-06 21:27:02 +00:00
else:
referral_url = self._referral_url
2019-02-06 22:41:35 +00:00
status_hook( 'downloading file' )
2018-06-06 21:27:02 +00:00
network_job = network_job_factory( 'GET', file_url, temp_path = temp_path, referral_url = referral_url )
2018-07-18 21:07:15 +00:00
if override_bandwidth:
2019-06-19 22:08:48 +00:00
network_job.OverrideBandwidth( 3 )
2018-07-18 21:07:15 +00:00
2018-06-06 21:27:02 +00:00
network_job.SetFileImportOptions( file_import_options )
HG.client_controller.network_engine.AddJob( network_job )
with network_job_presentation_context_factory( network_job ) as njpc:
network_job.WaitUntilDone()
2021-11-17 21:22:27 +00:00
actual_fetched_url = network_job.GetActualFetchedURL()
if actual_fetched_url != file_url:
self._AddPrimaryURLs( ( actual_fetched_url, ) )
( actual_url_type, actual_match_name, actual_can_parse, actual_cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( actual_fetched_url )
if actual_url_type == HC.URL_TYPE_POST and actual_can_parse:
# we just had a 3XX redirect to a Post URL!
if file_seed_cache is None:
raise Exception( 'The downloader thought it had a raw file url with "{}", but that redirected to the apparent Post URL "{}", but then there was no file log in which to queue that download!'.format( file_url, actual_fetched_url ) )
else:
( original_url_type, original_match_name, original_can_parse, original_cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self.file_seed_data )
if original_url_type == actual_url_type and original_match_name == actual_match_name:
raise Exception( 'The downloader thought it had a raw file url with "{}", but that redirected to the apparent Post URL "{}". As that URL has the same class as this import job\'s original URL, we are stopping here in case this is a looping redirect!'.format( file_url, actual_fetched_url ) )
file_seed = FileSeed( FILE_SEED_TYPE_URL, actual_fetched_url )
file_seed.SetReferralURL( file_url )
file_seeds = [ file_seed ]
file_seed_cache.AddFileSeeds( file_seeds )
status = CC.STATUS_SUCCESSFUL_AND_CHILD_FILES
2021-11-17 21:22:27 +00:00
note = 'was redirected on file download to a post url, which has been queued in the parent file log'
self.SetStatus( status, note = note )
return
last_modified_time = network_job.GetLastModifiedTime()
2022-05-18 20:18:25 +00:00
if self.source_time is not None and last_modified_time is not None:
# even with timezone weirdness, does the current source time have something reasonable?
current_source_time_looks_good = HydrusData.TimeHasPassed( self.source_time - 86400 )
# if CF is delivering a timestamp from 17 days before source time, this is probably some unusual CDN situation or delayed post
# we don't _really_ want this CF timestamp since it throws the domain-based timestamp ordering out
# in future maybe we'll save it as a misc 'cloudflare' domain or something, but for now we'll discard
if network_job.IsCloudFlareCache() and abs( self.source_time - last_modified_time ) > 86400 * 2:
self._cloudflare_last_modified_time = last_modified_time
last_modified_time = None
self.source_time = ClientTime.MergeModifiedTimes( self.source_time, last_modified_time )
2019-02-06 22:41:35 +00:00
status_hook( 'importing file' )
2020-02-19 21:48:36 +00:00
self.Import( temp_path, file_import_options, status_hook = status_hook )
2018-06-06 21:27:02 +00:00
finally:
HydrusTemp.CleanUpTempPath( os_file_handle, temp_path )
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
def FetchPageMetadata( self, tag_import_options: TagImportOptions.TagImportOptions ):
2018-06-06 21:27:02 +00:00
pass
2020-04-29 21:44:12 +00:00
def GetAPIInfoDict( self, simple: bool ):
2019-08-21 21:34:01 +00:00
d = {}
d[ 'import_data' ] = self.file_seed_data
d[ 'created' ] = self.created
d[ 'modified' ] = self.modified
d[ 'source_time' ] = self.source_time
d[ 'status' ] = self.status
d[ 'note' ] = self.note
return d
2018-10-31 21:41:14 +00:00
def GetExampleNetworkJob( self, network_job_factory ):
if self.IsAPostURL():
post_url = self.file_seed_data
2020-06-17 21:31:54 +00:00
try:
( url_to_check, parser ) = HG.client_controller.network_engine.domain_manager.GetURLToFetchAndParser( post_url )
except HydrusExceptions.URLClassException:
url_to_check = post_url
2018-10-31 21:41:14 +00:00
else:
url_to_check = self.file_seed_data
network_job = network_job_factory( 'GET', url_to_check )
return network_job
2018-06-27 19:27:05 +00:00
def GetHash( self ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if 'sha256' in self._hashes:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
return self._hashes[ 'sha256' ]
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
return None
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
def GetHashTypesToHashes( self ):
return dict( self._hashes )
2022-12-21 22:00:27 +00:00
def GetPreImportStatusPredictionHash( self, file_import_options: FileImportOptions.FileImportOptions ) -> typing.Tuple[ bool, bool, ClientImportFiles.FileImportStatus ]:
# TODO: a user raised the spectre of multiple hash parses on some site that actually provides somehow the pre- and post- optimised versions of a file
# some I guess support multiple hashes at some point, maybe, or figure out a different solution, or draw a harder line in parsing about one-hash-per-parse
preimport_hash_check_type = file_import_options.GetPreImportHashCheckType()
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
match_found = False
matches_are_dispositive = preimport_hash_check_type == FileImportOptions.DO_CHECK_AND_MATCHES_ARE_DISPOSITIVE
2021-07-28 21:12:00 +00:00
2022-12-21 22:00:27 +00:00
if len( self._hashes ) == 0 or preimport_hash_check_type == FileImportOptions.DO_NOT_CHECK:
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
return ( match_found, matches_are_dispositive, ClientImportFiles.FileImportStatus.STATICGetUnknownStatus() )
2018-06-06 21:27:02 +00:00
# hashes
2021-06-30 21:27:35 +00:00
jobs = []
if 'sha256' in self._hashes:
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
jobs.append( ( 'sha256', self._hashes[ 'sha256' ] ) )
for ( hash_type, found_hash ) in self._hashes.items():
if hash_type == 'sha256':
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
continue
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
jobs.append( ( hash_type, found_hash ) )
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
for ( hash_type, found_hash ) in jobs:
file_import_status = HG.client_controller.Read( 'hash_status', hash_type, found_hash, prefix = '{} hash recognised'.format( hash_type ) )
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
# there's some subtle gubbins going on here
# an sha256 'haven't seen this before' result will not set the hash here and so will not count as a match
# this is the same as if we do an md5 lookup and get no sha256 result back. we just aren't trusting a novel sha256 as a 'match'
# this is _useful_ to reduce the dispositivity of this lad in this specific case
2021-06-30 21:27:35 +00:00
2022-12-21 22:00:27 +00:00
if file_import_status.hash is None:
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
continue
2018-06-27 19:27:05 +00:00
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
match_found = True
2021-06-30 21:27:35 +00:00
2022-12-21 22:00:27 +00:00
file_import_status = ClientImportFiles.CheckFileImportStatus( file_import_status )
2021-06-30 21:27:35 +00:00
2022-12-21 22:00:27 +00:00
return ( match_found, matches_are_dispositive, file_import_status )
2021-06-30 21:27:35 +00:00
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
return ( match_found, matches_are_dispositive, ClientImportFiles.FileImportStatus.STATICGetUnknownStatus() )
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
def GetPreImportStatusPredictionURL( self, file_import_options: FileImportOptions.FileImportOptions, file_url = None ) -> typing.Tuple[ bool, bool, ClientImportFiles.FileImportStatus ]:
preimport_url_check_type = file_import_options.GetPreImportURLCheckType()
preimport_url_check_looks_for_neighbours = file_import_options.PreImportURLCheckLooksForNeighbours()
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
match_found = False
matches_are_dispositive = preimport_url_check_type == FileImportOptions.DO_CHECK_AND_MATCHES_ARE_DISPOSITIVE
if preimport_url_check_type == FileImportOptions.DO_NOT_CHECK:
2018-10-03 21:00:15 +00:00
2022-12-21 22:00:27 +00:00
return ( match_found, matches_are_dispositive, ClientImportFiles.FileImportStatus.STATICGetUnknownStatus() )
2018-10-03 21:00:15 +00:00
2018-06-27 19:27:05 +00:00
# urls
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
urls = []
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
if self.file_seed_type == FILE_SEED_TYPE_URL:
2018-06-27 19:27:05 +00:00
2021-06-30 21:27:35 +00:00
urls.append( self.file_seed_data )
2018-06-27 19:27:05 +00:00
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
if file_url is not None:
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
urls.append( file_url )
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
urls.extend( self._primary_urls )
2021-06-30 21:27:35 +00:00
2021-10-13 20:16:57 +00:00
# now that we store primary and source urls separately, we'll trust any primary but be careful about source
# trusting classless source urls was too much of a hassle with too many boorus providing bad source urls like user account pages
2021-06-30 21:27:35 +00:00
2021-10-13 20:16:57 +00:00
urls.extend( ( url for url in self._source_urls if HG.client_controller.network_engine.domain_manager.URLDefinitelyRefersToOneFile( url ) ) )
# now discard gallery pages or post urls that can hold multiple files
2021-06-30 21:27:35 +00:00
urls = [ url for url in urls if not HG.client_controller.network_engine.domain_manager.URLCanReferToMultipleFiles( url ) ]
2022-12-21 22:00:27 +00:00
lookup_urls = HG.client_controller.network_engine.domain_manager.NormaliseURLs( urls )
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
untrustworthy_domains = set()
2021-06-30 21:27:35 +00:00
2022-12-21 22:00:27 +00:00
for lookup_url in lookup_urls:
if ClientNetworkingFunctions.ConvertURLIntoDomain( lookup_url ) in untrustworthy_domains:
continue
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
results = HG.client_controller.Read( 'url_statuses', lookup_url )
2021-06-30 21:27:35 +00:00
2022-12-21 22:00:27 +00:00
if len( results ) == 0: # if no match found, this is a new URL, no useful data discovered
2018-06-27 19:27:05 +00:00
continue
2021-06-30 21:27:35 +00:00
elif len( results ) > 1: # if more than one file claims this url, it cannot be relied on to guess the file
2018-06-06 21:27:02 +00:00
2021-06-30 21:27:35 +00:00
continue
2022-12-21 22:00:27 +00:00
else: # this url is matched to one known file--sounds good!
2021-06-30 21:27:35 +00:00
file_import_status = results[0]
file_import_status = ClientImportFiles.CheckFileImportStatus( file_import_status )
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
if preimport_url_check_looks_for_neighbours and FileURLMappingHasUntrustworthyNeighbours( file_import_status.hash, lookup_url ):
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
untrustworthy_domains.add( ClientNetworkingFunctions.ConvertURLIntoDomain( lookup_url ) )
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
continue
2018-06-27 19:27:05 +00:00
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
match_found = True
# we have discovered a single-file match with a hash and no controversial urls; we have a result
# this may be a 'needs to be imported' result, but that's fine. probably a record of a previously deleted file that is now ok to import
return ( match_found, matches_are_dispositive, file_import_status )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
2022-12-21 22:00:27 +00:00
# no good matches found
return ( match_found, matches_are_dispositive, ClientImportFiles.FileImportStatus.STATICGetUnknownStatus() )
2018-10-03 21:00:15 +00:00
def GetSearchFileSeeds( self ):
if self.file_seed_type == FILE_SEED_TYPE_URL:
search_urls = ClientNetworkingFunctions.GetSearchURLs( self.file_seed_data )
2018-10-03 21:00:15 +00:00
search_file_seeds = [ FileSeed( FILE_SEED_TYPE_URL, search_url ) for search_url in search_urls ]
else:
search_file_seeds = [ self ]
return search_file_seeds
def GetExternalTags( self ):
t = set( self._tags )
t.update( self._external_filterable_tags )
return t
2021-10-13 20:16:57 +00:00
def GetPrimaryURLs( self ):
2021-10-13 20:16:57 +00:00
return set( self._primary_urls )
def GetReferralURL( self ):
return self._referral_url
def GetSourceURLs( self ):
return set( self._source_urls )
2018-10-03 21:00:15 +00:00
def HasHash( self ):
return self.GetHash() is not None
2021-06-30 21:27:35 +00:00
def Import( self, temp_path: str, file_import_options: FileImportOptions.FileImportOptions, status_hook = None ):
2018-10-03 21:00:15 +00:00
2021-06-30 21:27:35 +00:00
file_import_job = ClientImportFiles.FileImportJob( temp_path, file_import_options )
2018-10-03 21:00:15 +00:00
2021-06-30 21:27:35 +00:00
file_import_status = file_import_job.DoWork( status_hook = status_hook )
2018-10-03 21:00:15 +00:00
2021-06-30 21:27:35 +00:00
self.SetStatus( file_import_status.status, note = file_import_status.note )
self.SetHash( file_import_status.hash )
2018-10-03 21:00:15 +00:00
2022-08-03 20:59:51 +00:00
def ImportPath( self, file_seed_cache: "FileSeedCache", file_import_options: FileImportOptions.FileImportOptions, loud_or_quiet: int, status_hook = None ):
2018-10-03 21:00:15 +00:00
try:
2022-08-10 21:32:27 +00:00
file_import_options = FileImportOptions.GetRealFileImportOptions( file_import_options, loud_or_quiet )
2022-08-03 20:59:51 +00:00
2018-10-03 21:00:15 +00:00
if self.file_seed_type != FILE_SEED_TYPE_HDD:
raise HydrusExceptions.VetoException( 'Attempted to import as a path, but I do not think I am a path!' )
path = self.file_seed_data
if not os.path.exists( path ):
raise HydrusExceptions.VetoException( 'Source file does not exist!' )
( os_file_handle, temp_path ) = HydrusTemp.GetTempPath()
2018-10-03 21:00:15 +00:00
try:
2021-08-18 21:10:01 +00:00
if status_hook is not None:
status_hook( 'copying file to temp location' )
2018-10-03 21:00:15 +00:00
copied = HydrusPaths.MirrorFile( path, temp_path )
if not copied:
raise Exception( 'File failed to copy to temp path--see log for error.' )
2020-02-19 21:48:36 +00:00
self.Import( temp_path, file_import_options, status_hook = status_hook )
2018-10-03 21:00:15 +00:00
finally:
HydrusTemp.CleanUpTempPath( os_file_handle, temp_path )
2018-10-03 21:00:15 +00:00
2021-10-13 20:16:57 +00:00
self.WriteContentUpdates( file_import_options = file_import_options )
2019-02-27 23:03:30 +00:00
2018-10-03 21:00:15 +00:00
except HydrusExceptions.VetoException as e:
2019-01-09 22:59:03 +00:00
self.SetStatus( CC.STATUS_VETOED, note = str( e ) )
2018-10-03 21:00:15 +00:00
except HydrusExceptions.UnsupportedFileException as e:
self.SetStatus( CC.STATUS_ERROR, note = str( e ) )
2018-10-03 21:00:15 +00:00
except Exception as e:
self.SetStatus( CC.STATUS_ERROR, exception = e )
file_seed_cache.NotifyFileSeedsUpdated( ( self, ) )
def IsAPostURL( self ):
if self.file_seed_type == FILE_SEED_TYPE_URL:
2021-11-17 21:22:27 +00:00
try:
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self.file_seed_data )
except HydrusExceptions.URLClassException:
return False
2018-10-03 21:00:15 +00:00
if url_type == HC.URL_TYPE_POST:
2018-06-27 19:27:05 +00:00
2018-10-03 21:00:15 +00:00
return True
return False
def IsDeleted( self ):
return self.status == CC.STATUS_DELETED
def IsLocalFileImport( self ):
return self.file_seed_type == FILE_SEED_TYPE_HDD
2021-06-09 20:28:09 +00:00
def IsProbablyMasterPostURL( self ):
if self.file_seed_type == FILE_SEED_TYPE_URL:
if self._referral_url is not None:
try:
# if our given referral is a post url, we are most probably a multi-file url
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self._referral_url )
2021-06-09 20:28:09 +00:00
if url_type == HC.URL_TYPE_POST:
return False
except:
# screw it
return True
return True
def IsURLFileImport( self ):
return self.file_seed_type == FILE_SEED_TYPE_URL
2018-10-03 21:00:15 +00:00
def Normalise( self ):
if self.file_seed_type == FILE_SEED_TYPE_URL:
2020-04-01 21:51:42 +00:00
try:
self.file_seed_data = HG.client_controller.network_engine.domain_manager.NormaliseURL( self.file_seed_data )
except HydrusExceptions.URLClassException:
pass
2018-10-03 21:00:15 +00:00
2022-08-17 20:54:59 +00:00
def PredictPreImportStatus( self, file_import_options: FileImportOptions.FileImportOptions, tag_import_options: TagImportOptions.TagImportOptions, note_import_options: NoteImportOptions.NoteImportOptions, file_url = None ):
2018-10-03 21:00:15 +00:00
2022-12-21 22:00:27 +00:00
( hash_match_found, hash_matches_are_dispositive, hash_file_import_status ) = self.GetPreImportStatusPredictionHash( file_import_options )
( url_match_found, url_matches_are_dispositive, url_file_import_status ) = self.GetPreImportStatusPredictionURL( file_import_options, file_url = file_url )
2018-10-03 21:00:15 +00:00
# now let's set the prediction
2022-12-21 22:00:27 +00:00
if hash_match_found and hash_matches_are_dispositive:
2018-10-03 21:00:15 +00:00
2021-06-30 21:27:35 +00:00
file_import_status = hash_file_import_status
2018-10-03 21:00:15 +00:00
2022-12-21 22:00:27 +00:00
elif url_match_found and url_matches_are_dispositive:
2021-07-28 21:12:00 +00:00
2021-06-30 21:27:35 +00:00
file_import_status = url_file_import_status
2018-06-06 21:27:02 +00:00
2022-12-21 22:00:27 +00:00
else:
# prefer the one that says already in db/previously deleted
if hash_file_import_status.ShouldImport( file_import_options ):
file_import_status = url_file_import_status
else:
file_import_status = hash_file_import_status
2018-06-06 21:27:02 +00:00
2018-10-03 21:00:15 +00:00
# and make some recommendations
2021-06-30 21:27:35 +00:00
should_download_file = file_import_status.ShouldImport( file_import_options )
2018-10-03 21:00:15 +00:00
should_download_metadata = should_download_file # if we want the file, we need the metadata to get the file_url!
# but if we otherwise still want to force some tags, let's do it
if not should_download_metadata and tag_import_options.WorthFetchingTags():
2022-12-21 22:00:27 +00:00
url_override = url_file_import_status.AlreadyInDB() and tag_import_options.ShouldFetchTagsEvenIfURLKnownAndFileAlreadyInDB()
2021-06-30 21:27:35 +00:00
hash_override = hash_file_import_status.AlreadyInDB() and tag_import_options.ShouldFetchTagsEvenIfHashKnownAndFileAlreadyInDB()
2018-10-03 21:00:15 +00:00
if url_override or hash_override:
should_download_metadata = True
2022-08-17 20:54:59 +00:00
if not should_download_metadata and note_import_options.GetGetNotes():
# here we could have a 'fetch notes even if url known and file already in db' option
pass
2021-06-30 21:27:35 +00:00
# update private status store if predictions are useful
if self.status == CC.STATUS_UNKNOWN and not should_download_file:
self.status = file_import_status.status
if file_import_status.hash is not None:
self._hashes[ 'sha256' ] = file_import_status.hash
self.note = file_import_status.note
self._UpdateModified()
2018-10-03 21:00:15 +00:00
return ( should_download_metadata, should_download_file )
2018-06-27 19:27:05 +00:00
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def PresentToPage( self, page_key: bytes ):
2018-06-06 21:27:02 +00:00
hash = self.GetHash()
if hash is not None:
2020-04-29 21:44:12 +00:00
media_result = HG.client_controller.Read( 'media_result', hash )
2018-06-06 21:27:02 +00:00
HG.client_controller.pub( 'add_media_results', page_key, ( media_result, ) )
2020-09-16 20:46:54 +00:00
def SetExternalAdditionalServiceKeysToTags( self, service_keys_to_tags ):
self._external_additional_service_keys_to_tags = ClientTags.ServiceKeysToTags( service_keys_to_tags )
def SetExternalFilterableTags( self, tags ):
2019-02-27 23:03:30 +00:00
2020-09-16 20:46:54 +00:00
self._external_filterable_tags = set( tags )
2019-02-27 23:03:30 +00:00
2018-06-06 21:27:02 +00:00
def SetHash( self, hash ):
if hash is not None:
self._hashes[ 'sha256' ] = hash
2020-04-29 21:44:12 +00:00
def SetReferralURL( self, referral_url: str ):
2018-06-06 21:27:02 +00:00
self._referral_url = referral_url
2020-04-29 21:44:12 +00:00
def SetStatus( self, status: int, note: str = '', exception = None ):
2018-06-06 21:27:02 +00:00
if exception is not None:
2019-01-09 22:59:03 +00:00
first_line = str( exception ).split( os.linesep )[0]
2018-06-06 21:27:02 +00:00
2019-01-09 22:59:03 +00:00
note = first_line + '\u2026 (Copy note to see full error)'
2018-06-06 21:27:02 +00:00
note += os.linesep
2019-01-09 22:59:03 +00:00
note += traceback.format_exc()
2018-06-06 21:27:02 +00:00
2020-11-11 22:20:16 +00:00
HydrusData.Print( 'Error when processing {}!'.format( self.file_seed_data ) )
2018-06-06 21:27:02 +00:00
HydrusData.Print( traceback.format_exc() )
self.status = status
self.note = note
self._UpdateModified()
2021-11-24 21:59:58 +00:00
def ShouldPresent( self, presentation_import_options: PresentationImportOptions.PresentationImportOptions ):
2018-06-06 21:27:02 +00:00
2021-11-24 21:59:58 +00:00
if not self.HasHash():
2018-06-06 21:27:02 +00:00
2021-11-24 21:59:58 +00:00
return False
2018-06-06 21:27:02 +00:00
2021-11-24 21:59:58 +00:00
was_just_imported = not HydrusData.TimeHasPassed( self.modified + 5 )
should_check_location = not was_just_imported
return presentation_import_options.ShouldPresentHashAndStatus( self.GetHash(), self.status, should_check_location = should_check_location )
2018-06-06 21:27:02 +00:00
def WorksInNewSystem( self ):
2018-06-27 19:27:05 +00:00
if self.file_seed_type == FILE_SEED_TYPE_URL:
2018-06-06 21:27:02 +00:00
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self.file_seed_data )
2018-06-06 21:27:02 +00:00
if url_type == HC.URL_TYPE_FILE:
return True
if url_type == HC.URL_TYPE_POST and can_parse:
return True
2018-06-27 19:27:05 +00:00
if url_type == HC.URL_TYPE_UNKNOWN and self._referral_url is not None: # this is likely be a multi-file child of a post url file_seed
2018-06-06 21:27:02 +00:00
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self._referral_url )
2018-06-06 21:27:02 +00:00
if url_type == HC.URL_TYPE_POST: # we must have got here through parsing that m8, so let's assume this is an unrecognised file url
return True
return False
2022-08-17 20:54:59 +00:00
def WorkOnURL( self, file_seed_cache: "FileSeedCache", status_hook, network_job_factory, network_job_presentation_context_factory, file_import_options: FileImportOptions.FileImportOptions, loud_or_quiet: int, tag_import_options: TagImportOptions.TagImportOptions, note_import_options: NoteImportOptions.NoteImportOptions ):
2018-06-06 21:27:02 +00:00
did_substantial_work = False
try:
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( self.file_seed_data )
2018-08-01 20:44:57 +00:00
if url_type not in ( HC.URL_TYPE_POST, HC.URL_TYPE_FILE, HC.URL_TYPE_UNKNOWN ):
2019-01-30 22:14:54 +00:00
raise HydrusExceptions.VetoException( 'This URL appeared to be a "{}", which is not a File or Post URL!'.format( match_name ) )
2018-08-01 20:44:57 +00:00
if url_type == HC.URL_TYPE_POST and not can_parse:
raise HydrusExceptions.VetoException( 'Cannot parse {}: {}'.format( match_name, cannot_parse_reason ) )
2018-08-01 20:44:57 +00:00
2022-08-10 21:32:27 +00:00
file_import_options = FileImportOptions.GetRealFileImportOptions( file_import_options, loud_or_quiet )
2018-07-11 20:23:51 +00:00
tag_import_options = self._SetupTagImportOptions( tag_import_options )
2022-08-17 20:54:59 +00:00
note_import_options = self._SetupNoteImportOptions( note_import_options )
2018-07-11 20:23:51 +00:00
2018-06-06 21:27:02 +00:00
status_hook( 'checking url status' )
2022-08-17 20:54:59 +00:00
( should_download_metadata, should_download_file ) = self.PredictPreImportStatus( file_import_options, tag_import_options, note_import_options )
2018-06-06 21:27:02 +00:00
if self.IsAPostURL():
2018-06-27 19:27:05 +00:00
if should_download_metadata:
2018-06-06 21:27:02 +00:00
did_substantial_work = True
2018-06-27 19:27:05 +00:00
post_url = self.file_seed_data
2018-06-06 21:27:02 +00:00
2021-11-17 21:22:27 +00:00
url_for_child_referral = post_url
2018-06-06 21:27:02 +00:00
( url_to_check, parser ) = HG.client_controller.network_engine.domain_manager.GetURLToFetchAndParser( post_url )
2019-03-06 23:06:22 +00:00
status_hook( 'downloading file page' )
2018-06-06 21:27:02 +00:00
2021-02-24 22:35:18 +00:00
if self._referral_url is not None and self._referral_url != url_to_check:
2018-06-06 21:27:02 +00:00
referral_url = self._referral_url
2021-02-24 22:35:18 +00:00
elif url_to_check != post_url:
referral_url = post_url
2018-06-06 21:27:02 +00:00
else:
referral_url = None
network_job = network_job_factory( 'GET', url_to_check, referral_url = referral_url )
HG.client_controller.network_engine.AddJob( network_job )
with network_job_presentation_context_factory( network_job ) as njpc:
network_job.WaitUntilDone()
2019-01-09 22:59:03 +00:00
parsing_text = network_job.GetContentText()
2018-06-06 21:27:02 +00:00
2020-12-16 22:29:51 +00:00
actual_fetched_url = network_job.GetActualFetchedURL()
if actual_fetched_url != url_to_check:
2021-11-17 21:22:27 +00:00
# we have redirected, a 3XX response
2020-12-16 22:29:51 +00:00
2021-11-17 21:22:27 +00:00
( actual_url_type, actual_match_name, actual_can_parse, actual_cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( actual_fetched_url )
if actual_url_type == HC.URL_TYPE_POST and actual_can_parse:
self._AddPrimaryURLs( ( actual_fetched_url, ) )
2020-12-16 22:29:51 +00:00
post_url = actual_fetched_url
2021-11-17 21:22:27 +00:00
url_for_child_referral = post_url
2020-12-16 22:29:51 +00:00
( url_to_check, parser ) = HG.client_controller.network_engine.domain_manager.GetURLToFetchAndParser( post_url )
2018-06-06 21:27:02 +00:00
parsing_context = {}
parsing_context[ 'post_url' ] = post_url
parsing_context[ 'url' ] = url_to_check
2019-01-09 22:59:03 +00:00
all_parse_results = parser.Parse( parsing_context, parsing_text )
2018-06-06 21:27:02 +00:00
if len( all_parse_results ) == 0:
2020-04-16 00:09:42 +00:00
it_was_a_real_file = False
( os_file_handle, temp_path ) = HydrusTemp.GetTempPath()
2020-04-16 00:09:42 +00:00
try:
with open( temp_path, 'wb' ) as f:
f.write( network_job.GetContentBytes() )
mime = HydrusFileHandling.GetMime( temp_path )
if mime in HC.ALLOWED_MIMES:
it_was_a_real_file = True
status_hook( 'page was actually a file, trying to import' )
self.Import( temp_path, file_import_options, status_hook = status_hook )
except:
pass # in this special occasion, we will swallow the error
finally:
HydrusTemp.CleanUpTempPath( os_file_handle, temp_path )
2020-04-16 00:09:42 +00:00
if not it_was_a_real_file:
raise HydrusExceptions.VetoException( 'The parser found nothing in the document, nor did it seem to be an importable file!' )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
elif len( all_parse_results ) > 1:
2018-06-06 21:27:02 +00:00
2018-10-24 21:34:02 +00:00
# multiple child urls generated by a subsidiary page parser
2021-11-17 21:22:27 +00:00
file_seeds = ClientImporting.ConvertAllParseResultsToFileSeeds( all_parse_results, url_for_child_referral, file_import_options )
2018-08-22 21:10:59 +00:00
2019-04-03 22:45:57 +00:00
for file_seed in file_seeds:
2020-09-16 20:46:54 +00:00
file_seed.SetExternalFilterableTags( self._external_filterable_tags )
file_seed.SetExternalAdditionalServiceKeysToTags( self._external_additional_service_keys_to_tags )
2019-04-03 22:45:57 +00:00
2021-10-13 20:16:57 +00:00
file_seed.AddPrimaryURLs( set( self._primary_urls ) )
file_seed.AddSourceURLs( set( self._source_urls ) )
file_seed.AddTags( set( self._tags ) )
2019-07-03 22:49:27 +00:00
2022-08-17 20:54:59 +00:00
file_seed.AddNamesAndNotes( sorted( self._names_and_notes_dict.items() ) )
2019-04-03 22:45:57 +00:00
2018-10-24 21:34:02 +00:00
try:
my_index = file_seed_cache.GetFileSeedIndex( self )
insertion_index = my_index + 1
except:
insertion_index = len( file_seed_cache )
num_urls_added = file_seed_cache.InsertFileSeeds( insertion_index, file_seeds )
2018-06-06 21:27:02 +00:00
status = CC.STATUS_SUCCESSFUL_AND_CHILD_FILES
2020-11-11 22:20:16 +00:00
note = 'Found {} new URLs.'.format( HydrusData.ToHumanInt( num_urls_added ) )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
self.SetStatus( status, note = note )
else:
2018-10-24 21:34:02 +00:00
# no subsidiary page parser results, just one
2018-08-08 20:29:54 +00:00
parse_results = all_parse_results[0]
2018-06-06 21:27:02 +00:00
2018-10-03 21:00:15 +00:00
self.AddParseResults( parse_results, file_import_options )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
self.CheckPreFetchMetadata( tag_import_options )
desired_urls = ClientParsing.GetURLsFromParseResults( parse_results, ( HC.URL_TYPE_DESIRED, ), only_get_top_priority = True )
child_urls = []
if len( desired_urls ) == 0:
raise HydrusExceptions.VetoException( 'Could not find a file or post URL to download!' )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
elif len( desired_urls ) == 1:
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
desired_url = desired_urls[0]
2018-06-06 21:27:02 +00:00
( url_type, match_name, can_parse, cannot_parse_reason ) = HG.client_controller.network_engine.domain_manager.GetURLParseCapability( desired_url )
2018-08-08 20:29:54 +00:00
if url_type in ( HC.URL_TYPE_FILE, HC.URL_TYPE_UNKNOWN ):
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
file_url = desired_url
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
( should_download_metadata, should_download_file ) = self.PredictPreImportStatus( file_import_options, tag_import_options, note_import_options, file_url )
2018-08-08 20:29:54 +00:00
if should_download_file:
2022-08-03 20:59:51 +00:00
self.DownloadAndImportRawFile( file_url, file_import_options, loud_or_quiet, network_job_factory, network_job_presentation_context_factory, status_hook, override_bandwidth = True, forced_referral_url = url_for_child_referral, file_seed_cache = file_seed_cache )
2018-08-08 20:29:54 +00:00
elif url_type == HC.URL_TYPE_POST and can_parse:
# a pixiv mode=medium page has spawned a mode=manga page, so we need a new file_seed to go pursue that
child_urls = [ desired_url ]
else:
if can_parse:
raise HydrusExceptions.VetoException( 'Found a URL--{}--but could not understand it!'.format( desired_url ) )
else:
raise HydrusExceptions.VetoException( 'Found a URL--{}--but could not parse it: {}'.format( desired_url, cannot_parse_reason ) )
2018-06-06 21:27:02 +00:00
else:
2018-08-08 20:29:54 +00:00
child_urls = desired_urls
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
if len( child_urls ) > 0:
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
child_file_seeds = []
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
for child_url in child_urls:
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
duplicate_file_seed = self.Duplicate() # inherits all urls and tags from here
duplicate_file_seed.file_seed_data = child_url
2021-11-17 21:22:27 +00:00
duplicate_file_seed.SetReferralURL( url_for_child_referral )
2018-08-08 20:29:54 +00:00
if self._referral_url is not None:
2021-10-13 20:16:57 +00:00
duplicate_file_seed.AddSourceURLs( ( self._referral_url, ) )
2018-08-08 20:29:54 +00:00
child_file_seeds.append( duplicate_file_seed )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
try:
my_index = file_seed_cache.GetFileSeedIndex( self )
insertion_index = my_index + 1
except:
insertion_index = len( file_seed_cache )
2018-06-06 21:27:02 +00:00
2018-10-24 21:34:02 +00:00
num_urls_added = file_seed_cache.InsertFileSeeds( insertion_index, child_file_seeds )
2018-06-06 21:27:02 +00:00
status = CC.STATUS_SUCCESSFUL_AND_CHILD_FILES
2020-11-11 22:20:16 +00:00
note = 'Found {} new URLs.'.format( HydrusData.ToHumanInt( num_urls_added ) )
2018-06-06 21:27:02 +00:00
2018-08-08 20:29:54 +00:00
self.SetStatus( status, note = note )
2018-06-06 21:27:02 +00:00
else:
2018-06-27 19:27:05 +00:00
if should_download_file:
2018-06-06 21:27:02 +00:00
2020-01-22 21:04:43 +00:00
self.CheckPreFetchMetadata( tag_import_options )
2018-06-06 21:27:02 +00:00
did_substantial_work = True
2018-06-27 19:27:05 +00:00
file_url = self.file_seed_data
2018-06-06 21:27:02 +00:00
2022-08-03 20:59:51 +00:00
self.DownloadAndImportRawFile( file_url, file_import_options, loud_or_quiet, network_job_factory, network_job_presentation_context_factory, status_hook, file_seed_cache = file_seed_cache )
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
did_substantial_work |= self.WriteContentUpdates( file_import_options = file_import_options, tag_import_options = tag_import_options, note_import_options = note_import_options )
2018-06-06 21:27:02 +00:00
except HydrusExceptions.ShutdownException:
return False
except HydrusExceptions.VetoException as e:
status = CC.STATUS_VETOED
2019-01-09 22:59:03 +00:00
note = str( e )
2018-06-06 21:27:02 +00:00
self.SetStatus( status, note = note )
if isinstance( e, HydrusExceptions.CancelledException ):
status_hook( 'cancelled!' )
time.sleep( 2 )
2019-02-06 22:41:35 +00:00
except HydrusExceptions.InsufficientCredentialsException:
2018-07-18 21:07:15 +00:00
status = CC.STATUS_VETOED
note = '403'
self.SetStatus( status, note = note )
status_hook( '403' )
time.sleep( 2 )
2018-06-06 21:27:02 +00:00
except HydrusExceptions.NotFoundException:
status = CC.STATUS_VETOED
note = '404'
self.SetStatus( status, note = note )
status_hook( '404' )
time.sleep( 2 )
except HydrusExceptions.UnsupportedFileException as e:
status = CC.STATUS_ERROR
note = str( e )
self.SetStatus( status, note = note )
2018-06-06 21:27:02 +00:00
except Exception as e:
status = CC.STATUS_ERROR
self.SetStatus( status, exception = e )
status_hook( 'error!' )
time.sleep( 3 )
finally:
file_seed_cache.NotifyFileSeedsUpdated( ( self, ) )
2018-07-11 20:23:51 +00:00
2018-06-06 21:27:02 +00:00
return did_substantial_work
2022-08-17 20:54:59 +00:00
def WriteContentUpdates( self, file_import_options: typing.Optional[ FileImportOptions.FileImportOptions ] = None, tag_import_options: typing.Optional[ TagImportOptions.TagImportOptions ] = None, note_import_options: typing.Optional[ NoteImportOptions.NoteImportOptions ] = None ):
2018-06-06 21:27:02 +00:00
did_work = False
if self.status == CC.STATUS_ERROR:
return did_work
hash = self.GetHash()
if hash is None:
return did_work
2019-02-27 23:03:30 +00:00
# changed this to say that urls alone are not 'did work' since all url results are doing this, and when they have no tags, they are usually superfast db hits anyway
# better to scream through an 'already in db' import list that flicker
2018-06-06 21:27:02 +00:00
service_keys_to_content_updates = collections.defaultdict( list )
2021-10-13 20:16:57 +00:00
potentially_associable_urls = set()
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
if file_import_options is not None:
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
if file_import_options.ShouldAssociatePrimaryURLs():
potentially_associable_urls.update( self._primary_urls )
if self.file_seed_type == FILE_SEED_TYPE_URL:
potentially_associable_urls.add( self.file_seed_data )
2022-03-09 22:18:23 +00:00
domain = ClientNetworkingFunctions.ConvertURLIntoDomain( self.file_seed_data )
if self.source_time is None:
domain_modified_timestamp = self.created
else:
domain_modified_timestamp = self.source_time
content_update = HydrusData.ContentUpdate( HC.CONTENT_TYPE_TIMESTAMP, HC.CONTENT_UPDATE_ADD, ( 'domain', hash, ( domain, domain_modified_timestamp ) ) )
service_keys_to_content_updates[ CC.COMBINED_LOCAL_FILE_SERVICE_KEY ].append( content_update )
2022-05-18 20:18:25 +00:00
if self._cloudflare_last_modified_time is not None:
content_update = HydrusData.ContentUpdate( HC.CONTENT_TYPE_TIMESTAMP, HC.CONTENT_UPDATE_ADD, ( 'domain', hash, ( 'cloudflare.com', self._cloudflare_last_modified_time ) ) )
service_keys_to_content_updates[ CC.COMBINED_LOCAL_FILE_SERVICE_KEY ].append( content_update )
2021-10-13 20:16:57 +00:00
if self._referral_url is not None:
potentially_associable_urls.add( self._referral_url )
2018-06-06 21:27:02 +00:00
2021-10-13 20:16:57 +00:00
if file_import_options.ShouldAssociateSourceURLs():
potentially_associable_urls.update( self._source_urls )
2018-06-06 21:27:02 +00:00
associable_urls = ClientNetworkingFunctions.NormaliseAndFilterAssociableURLs( potentially_associable_urls )
2018-06-06 21:27:02 +00:00
if len( associable_urls ) > 0:
content_update = HydrusData.ContentUpdate( HC.CONTENT_TYPE_URLS, HC.CONTENT_UPDATE_ADD, ( associable_urls, ( hash, ) ) )
service_keys_to_content_updates[ CC.COMBINED_LOCAL_FILE_SERVICE_KEY ].append( content_update )
2022-08-17 20:54:59 +00:00
media_result = None
2020-04-29 21:44:12 +00:00
if tag_import_options is None:
2018-06-27 19:27:05 +00:00
2020-09-16 20:46:54 +00:00
for ( service_key, content_updates ) in ClientData.ConvertServiceKeysToTagsToServiceKeysToContentUpdates( ( hash, ), self._external_additional_service_keys_to_tags ).items():
2018-06-06 21:27:02 +00:00
service_keys_to_content_updates[ service_key ].extend( content_updates )
2019-02-27 23:03:30 +00:00
did_work = True
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
else:
2018-06-06 21:27:02 +00:00
2022-08-17 20:54:59 +00:00
if media_result is None:
media_result = HG.client_controller.Read( 'media_result', hash )
2018-06-06 21:27:02 +00:00
2020-09-16 20:46:54 +00:00
for ( service_key, content_updates ) in tag_import_options.GetServiceKeysToContentUpdates( self.status, media_result, set( self._tags ), external_filterable_tags = self._external_filterable_tags, external_additional_service_keys_to_tags = self._external_additional_service_keys_to_tags ).items():
2020-04-29 21:44:12 +00:00
service_keys_to_content_updates[ service_key ].extend( content_updates )
2022-08-17 20:54:59 +00:00
did_work = True
if note_import_options is not None:
if media_result is None:
media_result = HG.client_controller.Read( 'media_result', hash )
names_and_notes = sorted( self._names_and_notes_dict.items() )
for ( service_key, content_updates ) in note_import_options.GetServiceKeysToContentUpdates( media_result, names_and_notes ).items():
service_keys_to_content_updates[ service_key ].extend( content_updates )
2020-04-29 21:44:12 +00:00
did_work = True
2018-06-06 21:27:02 +00:00
2019-02-27 23:03:30 +00:00
if len( service_keys_to_content_updates ) > 0:
HG.client_controller.WriteSynchronous( 'content_updates', service_keys_to_content_updates )
2018-06-06 21:27:02 +00:00
return did_work
2018-06-27 19:27:05 +00:00
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED ] = FileSeed
2018-06-06 21:27:02 +00:00
2020-06-11 12:01:08 +00:00
class FileSeedCacheStatus( HydrusSerialisable.SerialisableBase ):
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED_CACHE_STATUS
SERIALISABLE_NAME = 'Import File Status Cache Status'
SERIALISABLE_VERSION = 1
def __init__( self ):
self._generation_time = HydrusData.GetNow()
self._statuses_to_counts = collections.Counter()
self._latest_added_time = 0
def _GetSerialisableInfo( self ):
serialisable_statuses_to_counts = list( self._statuses_to_counts.items() )
return ( self._generation_time, serialisable_statuses_to_counts, self._latest_added_time )
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
( self._generation_time, serialisable_statuses_to_counts, self._latest_added_time ) = serialisable_info
self._statuses_to_counts = collections.Counter()
self._statuses_to_counts.update( dict( serialisable_statuses_to_counts ) )
def GetFileSeedCount( self, status: typing.Optional[ int ] = None ) -> int:
if status is None:
return sum( self._statuses_to_counts.values() )
else:
return self._statuses_to_counts[ status ]
def GetGenerationTime( self ) -> int:
return self._generation_time
def GetLatestAddedTime( self ) -> int:
return self._latest_added_time
def GetStatusText( self, simple = False ) -> str:
num_successful_and_new = self._statuses_to_counts[ CC.STATUS_SUCCESSFUL_AND_NEW ]
num_successful_but_redundant = self._statuses_to_counts[ CC.STATUS_SUCCESSFUL_BUT_REDUNDANT ]
num_ignored = self._statuses_to_counts[ CC.STATUS_VETOED ]
num_deleted = self._statuses_to_counts[ CC.STATUS_DELETED ]
num_failed = self._statuses_to_counts[ CC.STATUS_ERROR ]
num_skipped = self._statuses_to_counts[ CC.STATUS_SKIPPED ]
num_unknown = self._statuses_to_counts[ CC.STATUS_UNKNOWN ]
if simple:
total = sum( self._statuses_to_counts.values() )
total_processed = total - num_unknown
#
status_text = ''
if total > 0:
if num_unknown > 0:
status_text += HydrusData.ConvertValueRangeToPrettyString( total_processed, total )
else:
status_text += HydrusData.ToHumanInt( total_processed )
show_new_on_file_seed_short_summary = HG.client_controller.new_options.GetBoolean( 'show_new_on_file_seed_short_summary' )
if show_new_on_file_seed_short_summary and num_successful_and_new:
status_text += ' - {}N'.format( HydrusData.ToHumanInt( num_successful_and_new ) )
simple_status_strings = []
if num_ignored > 0:
simple_status_strings.append( '{}Ig'.format( HydrusData.ToHumanInt( num_ignored ) ) )
show_deleted_on_file_seed_short_summary = HG.client_controller.new_options.GetBoolean( 'show_deleted_on_file_seed_short_summary' )
if show_deleted_on_file_seed_short_summary and num_deleted > 0:
simple_status_strings.append( '{}D'.format( HydrusData.ToHumanInt( num_deleted ) ) )
if num_failed > 0:
simple_status_strings.append( '{}F'.format( HydrusData.ToHumanInt( num_failed ) ) )
if num_skipped > 0:
simple_status_strings.append( '{}S'.format( HydrusData.ToHumanInt( num_skipped ) ) )
if len( simple_status_strings ) > 0:
status_text += ' - {}'.format( ''.join( simple_status_strings ) )
else:
status_strings = []
num_successful = num_successful_and_new + num_successful_but_redundant
if num_successful > 0:
s = '{} successful'.format( HydrusData.ToHumanInt( num_successful ) )
if num_successful_and_new > 0:
if num_successful_but_redundant > 0:
s += ' ({} already in db)'.format( HydrusData.ToHumanInt( num_successful_but_redundant ) )
else:
s += ' (all already in db)'
status_strings.append( s )
if num_ignored > 0:
status_strings.append( '{} ignored'.format( HydrusData.ToHumanInt( num_ignored ) ) )
if num_deleted > 0:
status_strings.append( '{} previously deleted'.format( HydrusData.ToHumanInt( num_deleted ) ) )
if num_failed > 0:
status_strings.append( '{} failed'.format( HydrusData.ToHumanInt( num_failed ) ) )
if num_skipped > 0:
status_strings.append( '{} skipped'.format( HydrusData.ToHumanInt( num_skipped ) ) )
status_text = ', '.join( status_strings )
return status_text
def GetStatusesToCounts( self ) -> typing.Mapping[ int, int ]:
return self._statuses_to_counts
def GetValueRange( self ) -> typing.Tuple[ int, int ]:
total = sum( self._statuses_to_counts.values() )
num_unknown = self._statuses_to_counts[ CC.STATUS_UNKNOWN ]
total_processed = total - num_unknown
return ( total_processed, total )
def HasWorkToDo( self ):
( num_done, num_total ) = self.GetValueRange()
return num_done < num_total
def Merge( self, file_seed_cache_status: "FileSeedCacheStatus" ):
self._latest_added_time = max( self._latest_added_time, file_seed_cache_status.GetLatestAddedTime() )
self._statuses_to_counts.update( file_seed_cache_status.GetStatusesToCounts() )
def SetStatusesToCounts( self, statuses_to_counts: typing.Mapping[ int, int ] ):
self._statuses_to_counts = collections.Counter()
self._statuses_to_counts.update( statuses_to_counts )
def SetLatestAddedTime( self, latest_added_time: int ):
self._latest_added_time = latest_added_time
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED_CACHE_STATUS ] = FileSeedCacheStatus
2018-06-27 19:27:05 +00:00
class FileSeedCache( HydrusSerialisable.SerialisableBase ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
SERIALISABLE_TYPE = HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED_CACHE
2018-06-06 21:27:02 +00:00
SERIALISABLE_NAME = 'Import File Status Cache'
SERIALISABLE_VERSION = 8
2018-10-24 21:34:02 +00:00
COMPACT_NUMBER = 250
2018-08-22 21:10:59 +00:00
2018-06-06 21:27:02 +00:00
def __init__( self ):
HydrusSerialisable.SerialisableBase.__init__( self )
2018-06-27 19:27:05 +00:00
self._file_seeds = HydrusSerialisable.SerialisableList()
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds_to_indices = {}
2018-06-06 21:27:02 +00:00
2021-11-17 21:22:27 +00:00
self._statuses_to_indexed_file_seeds = collections.defaultdict( list )
2018-06-27 19:27:05 +00:00
self._file_seed_cache_key = HydrusData.GenerateKey()
2018-06-06 21:27:02 +00:00
2020-06-11 12:01:08 +00:00
self._status_cache = FileSeedCacheStatus()
2018-06-06 21:27:02 +00:00
self._status_dirty = True
2021-11-17 21:22:27 +00:00
self._statuses_to_indexed_file_seeds_dirty = True
2018-06-06 21:27:02 +00:00
self._lock = threading.Lock()
def __len__( self ):
2018-06-27 19:27:05 +00:00
return len( self._file_seeds )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
def _FileSeedIndicesJustChanged( self ):
self._file_seeds_to_indices = { file_seed : index for ( index, file_seed ) in enumerate( self._file_seeds ) }
self._SetStatusesToFileSeedsDirty()
2021-11-17 21:22:27 +00:00
def _FixFileSeedsStatusPosition( self, file_seeds ):
indices_and_file_seeds_affected = []
for file_seed in file_seeds:
if file_seed in self._file_seeds_to_indices:
indices_and_file_seeds_affected.append( ( self._file_seeds_to_indices[ file_seed ], file_seed ) )
else:
self._SetStatusesToFileSeedsDirty()
return
for row in indices_and_file_seeds_affected:
correct_status = row[1].status
if row in self._statuses_to_indexed_file_seeds[ correct_status ]:
continue
for ( status, indices_and_file_seeds ) in self._statuses_to_indexed_file_seeds.items():
if status == correct_status:
continue
if row in indices_and_file_seeds:
indices_and_file_seeds.remove( row )
bisect.insort( self._statuses_to_indexed_file_seeds[ correct_status ], row )
break
2018-06-06 21:27:02 +00:00
def _GenerateStatus( self ):
2020-06-11 12:01:08 +00:00
fscs = FileSeedCacheStatus()
fscs.SetLatestAddedTime( self._GetLatestAddedTime() )
fscs.SetStatusesToCounts( self._GetStatusesToCounts() )
self._status_cache = fscs
2018-06-06 21:27:02 +00:00
self._status_dirty = False
2020-04-29 21:44:12 +00:00
def _GetFileSeeds( self, status: int = None ):
2018-06-06 21:27:02 +00:00
if status is None:
2018-06-27 19:27:05 +00:00
return list( self._file_seeds )
2018-06-06 21:27:02 +00:00
else:
2021-11-17 21:22:27 +00:00
if self._statuses_to_indexed_file_seeds_dirty:
self._RegenerateStatusesToFileSeeds()
return [ file_seed for ( index, file_seed ) in self._statuses_to_indexed_file_seeds[ status ] ]
2018-06-06 21:27:02 +00:00
2020-06-11 12:01:08 +00:00
def _GetLatestAddedTime( self ):
if len( self._file_seeds ) == 0:
latest_timestamp = 0
else:
latest_timestamp = max( ( file_seed.created for file_seed in self._file_seeds ) )
return latest_timestamp
2022-06-08 19:46:00 +00:00
def _GetMyFileSeed( self, file_seed: FileSeed ) -> typing.Optional[ FileSeed ]:
search_file_seeds = file_seed.GetSearchFileSeeds()
for f_s in self._file_seeds:
if f_s in search_file_seeds:
return f_s
return None
2020-06-11 12:01:08 +00:00
def _GetNextFileSeed( self, status: int ) -> typing.Optional[ FileSeed ]:
2021-11-17 21:22:27 +00:00
# the problem with this is if a file seed recently changed but 'notifyupdated' hasn't had a chance to go yet
# there could be a FS in a list other than the one we are looking at that has the status we want
# _however_, it seems like I do not do any async calls to notifyupdated in the actual FSC, only from notifyupdated to GUI elements, so we _seem_ to be good
if self._statuses_to_indexed_file_seeds_dirty:
self._RegenerateStatusesToFileSeeds()
indexed_file_seeds = self._statuses_to_indexed_file_seeds[ status ]
while len( indexed_file_seeds ) > 0:
row = indexed_file_seeds[ 0 ]
file_seed = row[1]
2020-06-11 12:01:08 +00:00
if file_seed.status == status:
return file_seed
2021-11-17 21:22:27 +00:00
else:
self._FixFileSeedsStatusPosition( ( file_seed, ) )
indexed_file_seeds = self._statuses_to_indexed_file_seeds[ status ]
2020-06-11 12:01:08 +00:00
return None
2018-06-06 21:27:02 +00:00
def _GetSerialisableInfo( self ):
2019-02-06 22:41:35 +00:00
return self._file_seeds.GetSerialisableTuple()
2018-06-06 21:27:02 +00:00
2022-03-09 22:18:23 +00:00
def _GetSourceTimestampForVelocityCalculations( self, file_seed: FileSeed ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
source_timestamp = file_seed.source_time
2018-06-06 21:27:02 +00:00
if source_timestamp is None:
# decent fallback compromise
# -30 since added and 'last check' timestamps are often the same, and this messes up calculations
2018-06-27 19:27:05 +00:00
source_timestamp = file_seed.created - 30
2018-06-06 21:27:02 +00:00
return source_timestamp
2018-07-04 20:48:28 +00:00
def _GetStatusesToCounts( self ):
statuses_to_counts = collections.Counter()
2021-11-17 21:22:27 +00:00
if self._statuses_to_indexed_file_seeds_dirty:
self._RegenerateStatusesToFileSeeds()
for ( status, indexed_file_seeds ) in self._statuses_to_indexed_file_seeds.items():
2018-07-04 20:48:28 +00:00
2021-11-17 21:22:27 +00:00
count = len( indexed_file_seeds )
if count > 0:
statuses_to_counts[ status ] = count
2018-07-04 20:48:28 +00:00
return statuses_to_counts
2020-04-29 21:44:12 +00:00
def _HasFileSeed( self, file_seed: FileSeed ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
search_file_seeds = file_seed.GetSearchFileSeeds()
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
has_file_seed = True in ( search_file_seed in self._file_seeds_to_indices for search_file_seed in search_file_seeds )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
return has_file_seed
2018-06-06 21:27:02 +00:00
def _InitialiseFromSerialisableInfo( self, serialisable_info ):
with self._lock:
2018-06-27 19:27:05 +00:00
self._file_seeds = HydrusSerialisable.CreateFromSerialisableTuple( serialisable_info )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
def _RegenerateStatusesToFileSeeds( self ):
self._statuses_to_indexed_file_seeds = collections.defaultdict( list )
for ( file_seed, index ) in self._file_seeds_to_indices.items():
self._statuses_to_indexed_file_seeds[ file_seed.status ].append( ( index, file_seed ) )
for indexed_file_seeds in self._statuses_to_indexed_file_seeds.values():
indexed_file_seeds.sort()
self._statuses_to_indexed_file_seeds_dirty = False
def _SetStatusesToFileSeedsDirty( self ):
self._statuses_to_indexed_file_seeds_dirty = True
2018-06-06 21:27:02 +00:00
def _SetStatusDirty( self ):
self._status_dirty = True
def _UpdateSerialisableInfo( self, version, old_serialisable_info ):
if version == 1:
new_serialisable_info = []
2018-06-27 19:27:05 +00:00
for ( file_seed, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if 'note' in file_seed_info:
2018-06-06 21:27:02 +00:00
2019-01-09 22:59:03 +00:00
file_seed_info[ 'note' ] = str( file_seed_info[ 'note' ] )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
new_serialisable_info.append( ( file_seed, file_seed_info ) )
2018-06-06 21:27:02 +00:00
return ( 2, new_serialisable_info )
if version in ( 2, 3 ):
# gelbooru replaced their thumbnail links with this redirect spam
# 'https://gelbooru.com/redirect.php?s=Ly9nZWxib29ydS5jb20vaW5kZXgucGhwP3BhZ2U9cG9zdCZzPXZpZXcmaWQ9MzY4ODA1OA=='
# I missed some http ones here, so I've broadened the test and rescheduled it
new_serialisable_info = []
2018-06-27 19:27:05 +00:00
for ( file_seed, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if 'gelbooru.com/redirect.php' in file_seed:
2018-06-06 21:27:02 +00:00
continue
2018-06-27 19:27:05 +00:00
new_serialisable_info.append( ( file_seed, file_seed_info ) )
2018-06-06 21:27:02 +00:00
return ( 4, new_serialisable_info )
if version == 4:
def ConvertRegularToRawURL( regular_url ):
# convert this:
# http://68.media.tumblr.com/5af0d991f26ef9fdad5a0c743fb1eca2/tumblr_opl012ZBOu1tiyj7vo1_500.jpg
# to this:
# http://68.media.tumblr.com/5af0d991f26ef9fdad5a0c743fb1eca2/tumblr_opl012ZBOu1tiyj7vo1_raw.jpg
# the 500 part can be a bunch of stuff, including letters
url_components = regular_url.split( '_' )
last_component = url_components[ -1 ]
( number_gubbins, file_ext ) = last_component.split( '.' )
2020-11-11 22:20:16 +00:00
raw_last_component = 'raw.{}'.format( file_ext )
2018-06-06 21:27:02 +00:00
url_components[ -1 ] = raw_last_component
raw_url = '_'.join( url_components )
return raw_url
def Remove68Subdomain( long_url ):
# sometimes the 68 subdomain gives a 404 on the raw url, so:
# convert this:
# http://68.media.tumblr.com/5af0d991f26ef9fdad5a0c743fb1eca2/tumblr_opl012ZBOu1tiyj7vo1_raw.jpg
# to this:
# http://media.tumblr.com/5af0d991f26ef9fdad5a0c743fb1eca2/tumblr_opl012ZBOu1tiyj7vo1_raw.jpg
# I am not sure if it is always 68, but let's not assume
( scheme, rest ) = long_url.split( '://', 1 )
if rest.startswith( 'media.tumblr.com' ):
return long_url
( gumpf, shorter_rest ) = rest.split( '.', 1 )
2020-11-11 22:20:16 +00:00
shorter_url = '{}://{}'.format( scheme, shorter_rest )
2018-06-06 21:27:02 +00:00
return shorter_url
new_serialisable_info = []
2018-06-27 19:27:05 +00:00
good_file_seeds = set()
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
for ( file_seed, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
try:
2019-01-09 22:59:03 +00:00
parse = urllib.parse.urlparse( file_seed )
2018-06-06 21:27:02 +00:00
if 'media.tumblr.com' in parse.netloc:
2018-06-27 19:27:05 +00:00
file_seed = Remove68Subdomain( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed = ConvertRegularToRawURL( file_seed )
2018-06-06 21:27:02 +00:00
file_seed = ClientNetworkingFunctions.ConvertHTTPToHTTPS( file_seed )
2018-06-06 21:27:02 +00:00
if 'pixiv.net' in parse.netloc:
file_seed = ClientNetworkingFunctions.ConvertHTTPToHTTPS( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if file_seed in good_file_seeds: # we hit a dupe, so skip it
2018-06-06 21:27:02 +00:00
continue
except:
pass
2018-06-27 19:27:05 +00:00
good_file_seeds.add( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
new_serialisable_info.append( ( file_seed, file_seed_info ) )
2018-06-06 21:27:02 +00:00
return ( 5, new_serialisable_info )
if version == 5:
new_serialisable_info = []
2018-06-27 19:27:05 +00:00
for ( file_seed, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed_info[ 'source_timestamp' ] = None
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
new_serialisable_info.append( ( file_seed, file_seed_info ) )
2018-06-06 21:27:02 +00:00
return ( 6, new_serialisable_info )
if version == 6:
new_serialisable_info = []
2018-06-27 19:27:05 +00:00
for ( file_seed, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
try:
magic_phrase = '//media.tumblr.com'
replacement = '//data.tumblr.com'
2018-06-27 19:27:05 +00:00
if magic_phrase in file_seed:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed = file_seed.replace( magic_phrase, replacement )
2018-06-06 21:27:02 +00:00
except:
pass
2018-06-27 19:27:05 +00:00
new_serialisable_info.append( ( file_seed, file_seed_info ) )
2018-06-06 21:27:02 +00:00
return ( 7, new_serialisable_info )
if version == 7:
2018-06-27 19:27:05 +00:00
file_seeds = HydrusSerialisable.SerialisableList()
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
for ( file_seed_text, file_seed_info ) in old_serialisable_info:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if file_seed_text.startswith( 'http' ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed_type = FILE_SEED_TYPE_URL
2018-06-06 21:27:02 +00:00
else:
2018-06-27 19:27:05 +00:00
file_seed_type = FILE_SEED_TYPE_HDD
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed = FileSeed( file_seed_type, file_seed_text )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seed.status = file_seed_info[ 'status' ]
file_seed.created = file_seed_info[ 'added_timestamp' ]
file_seed.modified = file_seed_info[ 'last_modified_timestamp' ]
file_seed.source_time = file_seed_info[ 'source_timestamp' ]
file_seed.note = file_seed_info[ 'note' ]
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
file_seeds.append( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
new_serialisable_info = file_seeds.GetSerialisableTuple()
2018-06-06 21:27:02 +00:00
return ( 8, new_serialisable_info )
def AddFileSeeds( self, file_seeds: typing.Collection[ FileSeed ], dupe_try_again = False ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if len( file_seeds ) == 0:
2018-06-06 21:27:02 +00:00
return 0
2022-06-08 19:46:00 +00:00
updated_or_new_file_seeds = []
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
for file_seed in file_seeds:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if self._HasFileSeed( file_seed ):
2018-06-06 21:27:02 +00:00
2022-06-08 19:46:00 +00:00
if dupe_try_again:
f_s = self._GetMyFileSeed( file_seed )
if f_s is not None:
if f_s.status == CC.STATUS_ERROR:
f_s.SetStatus( CC.STATUS_UNKNOWN )
updated_or_new_file_seeds.append( f_s )
2018-06-06 21:27:02 +00:00
continue
2019-10-09 22:03:03 +00:00
try:
file_seed.Normalise()
except HydrusExceptions.URLClassException:
# this is some borked 'https://' url that makes no sense
continue
2018-06-06 21:27:02 +00:00
2022-06-08 19:46:00 +00:00
updated_or_new_file_seeds.append( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds.append( file_seed )
2018-06-06 21:27:02 +00:00
2021-11-17 21:22:27 +00:00
index = len( self._file_seeds ) - 1
self._file_seeds_to_indices[ file_seed ] = index
if not self._statuses_to_indexed_file_seeds_dirty:
self._statuses_to_indexed_file_seeds[ file_seed.status ].append( ( index, file_seed ) )
2018-06-06 21:27:02 +00:00
self._SetStatusDirty()
2022-06-08 19:46:00 +00:00
self.NotifyFileSeedsUpdated( updated_or_new_file_seeds )
2018-06-06 21:27:02 +00:00
2022-06-08 19:46:00 +00:00
return len( updated_or_new_file_seeds )
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def AdvanceFileSeed( self, file_seed: FileSeed ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
if file_seed in self._file_seeds_to_indices:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
index = self._file_seeds_to_indices[ file_seed ]
2018-06-06 21:27:02 +00:00
if index > 0:
2018-06-27 19:27:05 +00:00
self._file_seeds.remove( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds.insert( index - 1, file_seed )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self.NotifyFileSeedsUpdated( ( file_seed, ) )
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def CanCompact( self, compact_before_this_source_time: int ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-08-22 21:10:59 +00:00
if len( self._file_seeds ) <= self.COMPACT_NUMBER:
2018-06-06 21:27:02 +00:00
return False
2018-08-22 21:10:59 +00:00
for file_seed in self._file_seeds[:-self.COMPACT_NUMBER]:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if file_seed.status == CC.STATUS_UNKNOWN:
2018-06-06 21:27:02 +00:00
continue
2022-03-09 22:18:23 +00:00
if self._GetSourceTimestampForVelocityCalculations( file_seed ) < compact_before_this_source_time:
2018-06-06 21:27:02 +00:00
return True
return False
2020-04-29 21:44:12 +00:00
def Compact( self, compact_before_this_source_time: int ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-08-22 21:10:59 +00:00
if len( self._file_seeds ) <= self.COMPACT_NUMBER:
2018-06-06 21:27:02 +00:00
return
2018-06-27 19:27:05 +00:00
new_file_seeds = HydrusSerialisable.SerialisableList()
2018-06-06 21:27:02 +00:00
2018-08-22 21:10:59 +00:00
for file_seed in self._file_seeds[:-self.COMPACT_NUMBER]:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
still_to_do = file_seed.status == CC.STATUS_UNKNOWN
2022-03-09 22:18:23 +00:00
still_relevant = self._GetSourceTimestampForVelocityCalculations( file_seed ) > compact_before_this_source_time
2018-06-06 21:27:02 +00:00
if still_to_do or still_relevant:
2018-06-27 19:27:05 +00:00
new_file_seeds.append( file_seed )
2018-06-06 21:27:02 +00:00
2018-08-22 21:10:59 +00:00
new_file_seeds.extend( self._file_seeds[-self.COMPACT_NUMBER:] )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds = new_file_seeds
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
2018-06-06 21:27:02 +00:00
self._SetStatusDirty()
2020-04-29 21:44:12 +00:00
def DelayFileSeed( self, file_seed: FileSeed ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
if file_seed in self._file_seeds_to_indices:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
index = self._file_seeds_to_indices[ file_seed ]
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if index < len( self._file_seeds ) - 1:
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds.remove( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds.insert( index + 1, file_seed )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self.NotifyFileSeedsUpdated( ( file_seed, ) )
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def GetAPIInfoDict( self, simple: bool ):
2019-08-21 21:34:01 +00:00
with self._lock:
d = {}
if self._status_dirty:
self._GenerateStatus()
2020-06-11 12:01:08 +00:00
d[ 'status' ] = self._status_cache.GetStatusText()
d[ 'simple_status' ] = self._status_cache.GetStatusText( simple = True )
2019-08-21 21:34:01 +00:00
2020-06-11 12:01:08 +00:00
( num_done, num_total ) = self._status_cache.GetValueRange()
d[ 'total_processed' ] = num_done
d[ 'total_to_process' ] = num_total
2019-08-21 21:34:01 +00:00
if not simple:
d[ 'import_items' ] = [ file_seed.GetAPIInfoDict( simple ) for file_seed in self._file_seeds ]
return d
2021-06-09 20:28:09 +00:00
def GetApproxNumMasterFileSeeds( self ):
return len( [ file_seed for file_seed in self._file_seeds if file_seed.IsProbablyMasterPostURL() ] )
2018-06-06 21:27:02 +00:00
def GetEarliestSourceTime( self ):
with self._lock:
2018-06-27 19:27:05 +00:00
if len( self._file_seeds ) == 0:
2018-06-06 21:27:02 +00:00
return None
2022-03-09 22:18:23 +00:00
earliest_timestamp = min( ( self._GetSourceTimestampForVelocityCalculations( file_seed ) for file_seed in self._file_seeds ) )
2018-06-06 21:27:02 +00:00
return earliest_timestamp
2020-06-11 12:01:08 +00:00
def GetExampleFileSeed( self ):
with self._lock:
if len( self._file_seeds ) == 0:
return None
else:
2021-11-17 21:22:27 +00:00
good_file_seeds = [ file_seed for file_seed in self._file_seeds[-30:] if file_seed.status in CC.SUCCESSFUL_IMPORT_STATES ]
if len( good_file_seeds ) > 0:
example_seed = random.choice( good_file_seeds )
else:
example_seed = self._GetNextFileSeed( CC.STATUS_UNKNOWN )
2020-06-11 12:01:08 +00:00
if example_seed is None:
example_seed = random.choice( self._file_seeds[-10:] )
if example_seed.file_seed_type == FILE_SEED_TYPE_HDD:
return None
else:
return example_seed
2018-06-27 19:27:05 +00:00
def GetFileSeedCacheKey( self ):
return self._file_seed_cache_key
2020-04-29 21:44:12 +00:00
def GetFileSeedCount( self, status: int = None ):
2018-06-27 19:27:05 +00:00
result = 0
with self._lock:
if status is None:
result = len( self._file_seeds )
else:
2021-11-17 21:22:27 +00:00
if self._statuses_to_indexed_file_seeds_dirty:
2018-06-27 19:27:05 +00:00
2021-11-17 21:22:27 +00:00
self._RegenerateStatusesToFileSeeds()
2018-06-27 19:27:05 +00:00
2021-11-17 21:22:27 +00:00
return len( self._statuses_to_indexed_file_seeds[ status ] )
2018-06-27 19:27:05 +00:00
return result
2020-04-29 21:44:12 +00:00
def GetFileSeeds( self, status: int = None ):
2018-06-27 19:27:05 +00:00
with self._lock:
return self._GetFileSeeds( status )
2020-04-29 21:44:12 +00:00
def GetFileSeedIndex( self, file_seed: FileSeed ):
2018-06-27 19:27:05 +00:00
with self._lock:
return self._file_seeds_to_indices[ file_seed ]
2018-10-03 21:00:15 +00:00
def GetHashes( self ):
with self._lock:
hashes = [ file_seed.GetHash() for file_seed in self._file_seeds if file_seed.HasHash() ]
return hashes
2018-06-06 21:27:02 +00:00
def GetLatestSourceTime( self ):
with self._lock:
2018-06-27 19:27:05 +00:00
if len( self._file_seeds ) == 0:
2018-06-06 21:27:02 +00:00
return 0
2022-03-09 22:18:23 +00:00
latest_timestamp = max( ( self._GetSourceTimestampForVelocityCalculations( file_seed ) for file_seed in self._file_seeds ) )
2018-06-06 21:27:02 +00:00
return latest_timestamp
2021-11-24 21:59:58 +00:00
def GetNextFileSeed( self, status: int ) -> typing.Optional[ FileSeed ]:
2018-06-06 21:27:02 +00:00
with self._lock:
2020-06-11 12:01:08 +00:00
return self._GetNextFileSeed( status )
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def GetNumNewFilesSince( self, since: int ):
2018-06-06 21:27:02 +00:00
num_files = 0
with self._lock:
2018-06-27 19:27:05 +00:00
for file_seed in self._file_seeds:
2018-06-06 21:27:02 +00:00
2022-03-09 22:18:23 +00:00
source_timestamp = self._GetSourceTimestampForVelocityCalculations( file_seed )
2018-06-06 21:27:02 +00:00
if source_timestamp >= since:
num_files += 1
return num_files
2021-11-24 21:59:58 +00:00
def GetPresentedHashes( self, presentation_import_options: PresentationImportOptions.PresentationImportOptions ):
2018-06-06 21:27:02 +00:00
with self._lock:
2021-11-24 21:59:58 +00:00
hashes_and_statuses = [ ( file_seed.GetHash(), file_seed.status ) for file_seed in self._file_seeds if file_seed.HasHash() ]
2018-08-08 20:29:54 +00:00
2020-07-29 20:52:44 +00:00
2021-11-24 21:59:58 +00:00
return presentation_import_options.GetPresentedHashes( hashes_and_statuses )
2018-06-06 21:27:02 +00:00
def GetStatus( self ):
with self._lock:
if self._status_dirty:
self._GenerateStatus()
return self._status_cache
def GetValueRange( self ):
with self._lock:
if self._status_dirty:
self._GenerateStatus()
2020-06-11 12:01:08 +00:00
return self._status_cache.GetValueRange()
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def HasFileSeed( self, file_seed: FileSeed ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
return self._HasFileSeed( file_seed )
2018-06-06 21:27:02 +00:00
def InsertFileSeeds( self, index: int, file_seeds: typing.Collection[ FileSeed ] ):
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
if len( file_seeds ) == 0:
2018-06-06 21:27:02 +00:00
return 0
2018-10-24 21:34:02 +00:00
new_file_seeds = set()
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
index = min( index, len( self._file_seeds ) )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
for file_seed in file_seeds:
2018-06-06 21:27:02 +00:00
2018-10-24 21:34:02 +00:00
if self._HasFileSeed( file_seed ) or file_seed in new_file_seeds:
2018-06-06 21:27:02 +00:00
continue
2018-06-27 19:27:05 +00:00
file_seed.Normalise()
2018-06-06 21:27:02 +00:00
2018-10-24 21:34:02 +00:00
new_file_seeds.add( file_seed )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds.insert( index, file_seed )
2018-06-06 21:27:02 +00:00
index += 1
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
2018-06-06 21:27:02 +00:00
self._SetStatusDirty()
2018-06-27 19:27:05 +00:00
self.NotifyFileSeedsUpdated( new_file_seeds )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
return len( new_file_seeds )
2018-06-06 21:27:02 +00:00
def NotifyFileSeedsUpdated( self, file_seeds: typing.Collection[ FileSeed ] ):
2018-06-06 21:27:02 +00:00
with self._lock:
2021-11-17 21:22:27 +00:00
if not self._statuses_to_indexed_file_seeds_dirty:
self._FixFileSeedsStatusPosition( file_seeds )
#
2018-06-06 21:27:02 +00:00
self._SetStatusDirty()
2018-06-27 19:27:05 +00:00
HG.client_controller.pub( 'file_seed_cache_file_seeds_updated', self._file_seed_cache_key, file_seeds )
2018-06-06 21:27:02 +00:00
2020-04-29 21:44:12 +00:00
def RemoveFileSeeds( self, file_seeds: typing.Iterable[ FileSeed ] ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
file_seeds_to_delete = set( file_seeds )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self._file_seeds = HydrusSerialisable.SerialisableList( [ file_seed for file_seed in self._file_seeds if file_seed not in file_seeds_to_delete ] )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
self._FileSeedIndicesJustChanged()
2021-11-17 21:22:27 +00:00
2018-06-06 21:27:02 +00:00
self._SetStatusDirty()
2018-06-27 19:27:05 +00:00
self.NotifyFileSeedsUpdated( file_seeds_to_delete )
2018-06-06 21:27:02 +00:00
def RemoveFileSeedsByStatus( self, statuses_to_remove: typing.Collection[ int ] ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
file_seeds_to_delete = [ file_seed for file_seed in self._file_seeds if file_seed.status in statuses_to_remove ]
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self.RemoveFileSeeds( file_seeds_to_delete )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
def RemoveAllButUnknownFileSeeds( self ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
file_seeds_to_delete = [ file_seed for file_seed in self._file_seeds if file_seed.status != CC.STATUS_UNKNOWN ]
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self.RemoveFileSeeds( file_seeds_to_delete )
2018-06-06 21:27:02 +00:00
2020-06-11 12:01:08 +00:00
def RetryFailed( self ):
2018-06-06 21:27:02 +00:00
with self._lock:
2018-06-27 19:27:05 +00:00
failed_file_seeds = self._GetFileSeeds( CC.STATUS_ERROR )
for file_seed in failed_file_seeds:
file_seed.SetStatus( CC.STATUS_UNKNOWN )
self.NotifyFileSeedsUpdated( failed_file_seeds )
2021-07-14 20:42:19 +00:00
def RetryIgnored( self, ignored_regex = None ):
2018-06-27 19:27:05 +00:00
with self._lock:
ignored_file_seeds = self._GetFileSeeds( CC.STATUS_VETOED )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
for file_seed in ignored_file_seeds:
2018-06-06 21:27:02 +00:00
2021-07-14 20:42:19 +00:00
if ignored_regex is not None:
if re.search( ignored_regex, file_seed.note ) is None:
continue
2018-06-27 19:27:05 +00:00
file_seed.SetStatus( CC.STATUS_UNKNOWN )
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
self.NotifyFileSeedsUpdated( ignored_file_seeds )
2018-06-06 21:27:02 +00:00
2022-12-14 22:22:11 +00:00
def Reverse( self ):
with self._lock:
self._file_seeds.reverse()
self._FileSeedIndicesJustChanged()
self.NotifyFileSeedsUpdated( list( self._file_seeds ) )
2018-06-06 21:27:02 +00:00
def WorkToDo( self ):
with self._lock:
if self._status_dirty:
self._GenerateStatus()
2020-06-11 12:01:08 +00:00
return self._status_cache.HasWorkToDo()
2018-06-06 21:27:02 +00:00
2018-06-27 19:27:05 +00:00
HydrusSerialisable.SERIALISABLE_TYPES_TO_OBJECT_TYPES[ HydrusSerialisable.SERIALISABLE_TYPE_FILE_SEED_CACHE ] = FileSeedCache
2020-04-29 21:44:12 +00:00
def GenerateFileSeedCachesStatus( file_seed_caches: typing.Iterable[ FileSeedCache ] ):
2020-06-11 12:01:08 +00:00
fscs = FileSeedCacheStatus()
2020-04-29 21:44:12 +00:00
for file_seed_cache in file_seed_caches:
2020-06-11 12:01:08 +00:00
fscs.Merge( file_seed_cache.GetStatus() )
2020-04-29 21:44:12 +00:00
2020-06-11 12:01:08 +00:00
return fscs
2020-04-29 21:44:12 +00:00