hydrus/include/ClientCaches.py

3152 lines
100 KiB
Python
Raw Normal View History

2015-10-07 21:56:22 +00:00
import ClientDefaults
2017-01-18 22:52:39 +00:00
import ClientDownloading
2015-10-21 21:53:10 +00:00
import ClientNetworking
2015-08-05 18:42:35 +00:00
import ClientRendering
2016-06-08 20:27:22 +00:00
import ClientSearch
2017-10-25 21:45:15 +00:00
import ClientServices
2016-06-08 20:27:22 +00:00
import ClientThreading
2015-03-18 21:46:29 +00:00
import HydrusConstants as HC
import HydrusExceptions
import HydrusFileHandling
2015-11-04 22:30:28 +00:00
import HydrusPaths
2017-04-19 20:58:30 +00:00
import HydrusSerialisable
2015-11-18 22:44:07 +00:00
import HydrusSessions
2018-02-14 21:47:18 +00:00
import HydrusThreading
2015-11-25 22:00:57 +00:00
import itertools
2017-01-18 22:52:39 +00:00
import json
2015-03-18 21:46:29 +00:00
import os
import random
2017-01-18 22:52:39 +00:00
import requests
2015-03-18 21:46:29 +00:00
import threading
import time
2015-10-07 21:56:22 +00:00
import urllib
2015-03-18 21:46:29 +00:00
import wx
2015-03-25 22:04:19 +00:00
import HydrusData
import ClientData
2015-06-03 21:05:13 +00:00
import ClientConstants as CC
2017-05-10 21:33:58 +00:00
import HydrusGlobals as HG
2015-08-05 18:42:35 +00:00
import collections
import HydrusTags
2016-06-08 20:27:22 +00:00
import traceback
2015-03-18 21:46:29 +00:00
2015-11-25 22:00:57 +00:00
# important thing here, and reason why it is recursive, is because we want to preserve the parent-grandparent interleaving
def BuildServiceKeysToChildrenToParents( service_keys_to_simple_children_to_parents ):
def AddParents( simple_children_to_parents, children_to_parents, child, parents ):
for parent in parents:
if parent not in children_to_parents[ child ]:
children_to_parents[ child ].append( parent )
if parent in simple_children_to_parents:
grandparents = simple_children_to_parents[ parent ]
AddParents( simple_children_to_parents, children_to_parents, child, grandparents )
service_keys_to_children_to_parents = collections.defaultdict( HydrusData.default_dict_list )
for ( service_key, simple_children_to_parents ) in service_keys_to_simple_children_to_parents.items():
children_to_parents = service_keys_to_children_to_parents[ service_key ]
for ( child, parents ) in simple_children_to_parents.items():
AddParents( simple_children_to_parents, children_to_parents, child, parents )
return service_keys_to_children_to_parents
def BuildServiceKeysToSimpleChildrenToParents( service_keys_to_pairs_flat ):
service_keys_to_simple_children_to_parents = collections.defaultdict( HydrusData.default_dict_set )
for ( service_key, pairs ) in service_keys_to_pairs_flat.items():
service_keys_to_simple_children_to_parents[ service_key ] = BuildSimpleChildrenToParents( pairs )
return service_keys_to_simple_children_to_parents
def BuildSimpleChildrenToParents( pairs ):
simple_children_to_parents = HydrusData.default_dict_set()
for ( child, parent ) in pairs:
2017-05-03 21:33:48 +00:00
if child == parent:
continue
2015-11-25 22:00:57 +00:00
if LoopInSimpleChildrenToParents( simple_children_to_parents, child, parent ): continue
simple_children_to_parents[ child ].add( parent )
return simple_children_to_parents
2017-04-05 21:16:40 +00:00
def CollapseTagSiblingPairs( groups_of_pairs ):
# This now takes 'groups' of pairs in descending order of precedence
# This allows us to mandate that local tags take precedence
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
# a pair is invalid if:
# it causes a loop (a->b, b->c, c->a)
# there is already a relationship for the 'bad' sibling (a->b, a->c)
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
valid_chains = {}
2015-11-25 22:00:57 +00:00
2017-04-05 21:16:40 +00:00
for pairs in groups_of_pairs:
2015-11-25 22:00:57 +00:00
2017-04-05 21:16:40 +00:00
pairs = list( pairs )
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
pairs.sort()
for ( bad, good ) in pairs:
2015-11-25 22:00:57 +00:00
2017-04-05 21:16:40 +00:00
if bad == good:
# a->a is a loop!
continue
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
if bad not in valid_chains:
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
we_have_a_loop = False
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
current_best = good
while current_best in valid_chains:
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
current_best = valid_chains[ current_best ]
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
if current_best == bad:
we_have_a_loop = True
break
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
if not we_have_a_loop:
valid_chains[ bad ] = good
2016-09-14 18:03:59 +00:00
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
# now we collapse the chains, turning:
# a->b, b->c ... e->f
# into
# a->f, b->f ... e->f
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
siblings = {}
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
for ( bad, good ) in valid_chains.items():
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
# given a->b, want to find f
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
if good in siblings:
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
# f already calculated and added
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
best = siblings[ good ]
else:
# we don't know f for this chain, so let's figure it out
current_best = good
while current_best in valid_chains:
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
current_best = valid_chains[ current_best ] # pursue endpoint f
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
best = current_best
# add a->f
siblings[ bad ] = best
2015-11-25 22:00:57 +00:00
2016-09-14 18:03:59 +00:00
return siblings
2015-11-25 22:00:57 +00:00
def LoopInSimpleChildrenToParents( simple_children_to_parents, child, parent ):
potential_loop_paths = { parent }
while len( potential_loop_paths.intersection( simple_children_to_parents.keys() ) ) > 0:
new_potential_loop_paths = set()
for potential_loop_path in potential_loop_paths.intersection( simple_children_to_parents.keys() ):
new_potential_loop_paths.update( simple_children_to_parents[ potential_loop_path ] )
potential_loop_paths = new_potential_loop_paths
if child in potential_loop_paths: return True
return False
class ClientFilesManager( object ):
def __init__( self, controller ):
self._controller = controller
self._lock = threading.Lock()
2015-12-02 22:32:18 +00:00
self._prefixes_to_locations = {}
2015-11-25 22:00:57 +00:00
2016-02-17 22:06:47 +00:00
self._bad_error_occured = False
2017-04-05 21:16:40 +00:00
self._missing_locations = set()
2016-02-17 22:06:47 +00:00
2015-11-25 22:00:57 +00:00
self._Reinit()
2016-07-27 21:53:34 +00:00
def _GenerateExpectedFilePath( self, hash, mime ):
2016-06-08 20:27:22 +00:00
hash_encoded = hash.encode( 'hex' )
2016-07-27 21:53:34 +00:00
prefix = 'f' + hash_encoded[:2]
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
location = self._prefixes_to_locations[ prefix ]
path = os.path.join( location, prefix, hash_encoded + HC.mime_ext_lookup[ mime ] )
return path
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
def _GenerateExpectedFullSizeThumbnailPath( self, hash ):
2016-06-08 20:27:22 +00:00
hash_encoded = hash.encode( 'hex' )
2016-07-27 21:53:34 +00:00
prefix = 't' + hash_encoded[:2]
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
location = self._prefixes_to_locations[ prefix ]
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
path = os.path.join( location, prefix, hash_encoded ) + '.thumbnail'
2016-06-08 20:27:22 +00:00
return path
2016-07-27 21:53:34 +00:00
def _GenerateExpectedResizedThumbnailPath( self, hash ):
2015-11-25 22:00:57 +00:00
2015-12-02 22:32:18 +00:00
hash_encoded = hash.encode( 'hex' )
2016-07-27 21:53:34 +00:00
prefix = 'r' + hash_encoded[:2]
2015-12-02 22:32:18 +00:00
location = self._prefixes_to_locations[ prefix ]
2016-07-27 21:53:34 +00:00
path = os.path.join( location, prefix, hash_encoded ) + '.thumbnail.resized'
return path
2017-11-15 22:35:49 +00:00
def _GenerateFullSizeThumbnail( self, hash, mime = None ):
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
if mime is None:
try:
file_path = self._LookForFilePath( hash )
except HydrusExceptions.FileMissingException:
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was missing. It could not be regenerated because the original file was also missing. This event could indicate hard drive corruption or an unplugged external drive. Please check everything is ok.' )
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
mime = HydrusFileHandling.GetMime( file_path )
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
else:
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
file_path = self._GenerateExpectedFilePath( hash, mime )
2016-07-27 21:53:34 +00:00
try:
2017-11-15 22:35:49 +00:00
thumbnail = HydrusFileHandling.GenerateThumbnail( file_path, mime )
2016-07-27 21:53:34 +00:00
except Exception as e:
HydrusData.ShowException( e )
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was missing. It could not be regenerated from the original file for the above reason. This event could indicate hard drive corruption. Please check everything is ok.' )
full_size_path = self._GenerateExpectedFullSizeThumbnailPath( hash )
try:
with open( full_size_path, 'wb' ) as f:
f.write( thumbnail )
except Exception as e:
HydrusData.ShowException( e )
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was missing. It was regenerated from the original file, but hydrus could not write it to the location ' + full_size_path + ' for the above reason. This event could indicate hard drive corruption, and it also suggests that hydrus does not have permission to write to its thumbnail folder. Please check everything is ok.' )
2017-11-15 22:35:49 +00:00
def _GenerateResizedThumbnail( self, hash, mime ):
2016-07-27 21:53:34 +00:00
full_size_path = self._GenerateExpectedFullSizeThumbnailPath( hash )
2017-12-06 22:06:56 +00:00
thumbnail_dimensions = self._controller.options[ 'thumbnail_dimensions' ]
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
if mime in ( HC.IMAGE_GIF, HC.IMAGE_PNG ):
fullsize_thumbnail_mime = HC.IMAGE_PNG
else:
fullsize_thumbnail_mime = HC.IMAGE_JPEG
2016-07-27 21:53:34 +00:00
try:
2017-11-15 22:35:49 +00:00
thumbnail_resized = HydrusFileHandling.GenerateThumbnailFromStaticImage( full_size_path, thumbnail_dimensions, fullsize_thumbnail_mime )
2016-07-27 21:53:34 +00:00
except:
try:
HydrusPaths.DeletePath( full_size_path )
except:
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was found, but it would not render. An attempt to delete it was made, but that failed as well. This event could indicate hard drive corruption, and it also suggests that hydrus does not have permission to write to its thumbnail folder. Please check everything is ok.' )
2017-11-15 22:35:49 +00:00
self._GenerateFullSizeThumbnail( hash, mime )
2016-07-27 21:53:34 +00:00
2017-11-15 22:35:49 +00:00
thumbnail_resized = HydrusFileHandling.GenerateThumbnailFromStaticImage( full_size_path, thumbnail_dimensions, fullsize_thumbnail_mime )
2016-07-27 21:53:34 +00:00
resized_path = self._GenerateExpectedResizedThumbnailPath( hash )
try:
with open( resized_path, 'wb' ) as f:
f.write( thumbnail_resized )
except Exception as e:
HydrusData.ShowException( e )
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was found, but the resized version would not save to disk. This event suggests that hydrus does not have permission to write to its thumbnail folder. Please check everything is ok.' )
2015-12-02 22:32:18 +00:00
def _GetRecoverTuple( self ):
2016-07-27 21:53:34 +00:00
all_locations = { location for location in self._prefixes_to_locations.values() }
all_prefixes = self._prefixes_to_locations.keys()
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
for possible_location in all_locations:
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
for prefix in all_prefixes:
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
correct_location = self._prefixes_to_locations[ prefix ]
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
if possible_location != correct_location and os.path.exists( os.path.join( possible_location, prefix ) ):
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
recoverable_location = possible_location
return ( prefix, recoverable_location, correct_location )
2015-12-02 22:32:18 +00:00
return None
2015-11-25 22:00:57 +00:00
def _GetRebalanceTuple( self ):
2017-12-06 22:06:56 +00:00
( locations_to_ideal_weights, resized_thumbnail_override, full_size_thumbnail_override ) = self._controller.new_options.GetClientFilesLocationsToIdealWeights()
2016-07-27 21:53:34 +00:00
total_weight = sum( locations_to_ideal_weights.values() )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
ideal_locations_to_normalised_weights = { location : weight / total_weight for ( location, weight ) in locations_to_ideal_weights.items() }
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
current_locations_to_normalised_weights = collections.defaultdict( lambda: 0 )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
file_prefixes = [ prefix for prefix in self._prefixes_to_locations if prefix.startswith( 'f' ) ]
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
for file_prefix in file_prefixes:
location = self._prefixes_to_locations[ file_prefix ]
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
current_locations_to_normalised_weights[ location ] += 1.0 / 256
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
for location in current_locations_to_normalised_weights.keys():
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
if location not in ideal_locations_to_normalised_weights:
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
ideal_locations_to_normalised_weights[ location ] = 0.0
2015-12-02 22:32:18 +00:00
2015-11-25 22:00:57 +00:00
#
2016-07-27 21:53:34 +00:00
overweight_locations = []
underweight_locations = []
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
for ( location, ideal_weight ) in ideal_locations_to_normalised_weights.items():
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
if location in current_locations_to_normalised_weights:
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
current_weight = current_locations_to_normalised_weights[ location ]
2015-11-25 22:00:57 +00:00
if current_weight < ideal_weight:
2016-07-27 21:53:34 +00:00
underweight_locations.append( location )
2015-11-25 22:00:57 +00:00
elif current_weight >= ideal_weight + 1.0 / 256:
2016-07-27 21:53:34 +00:00
overweight_locations.append( location )
2015-11-25 22:00:57 +00:00
else:
2016-07-27 21:53:34 +00:00
underweight_locations.append( location )
2015-11-25 22:00:57 +00:00
#
2016-07-27 21:53:34 +00:00
if len( underweight_locations ) > 0 and len( overweight_locations ) > 0:
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
overweight_location = overweight_locations.pop( 0 )
underweight_location = underweight_locations.pop( 0 )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
random.shuffle( file_prefixes )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
for file_prefix in file_prefixes:
location = self._prefixes_to_locations[ file_prefix ]
if location == overweight_location:
return ( file_prefix, overweight_location, underweight_location )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
else:
2015-12-02 22:32:18 +00:00
2016-08-10 19:04:08 +00:00
if full_size_thumbnail_override is None:
2016-07-27 21:53:34 +00:00
2016-08-10 19:04:08 +00:00
for hex_prefix in HydrusData.IterateHexPrefixes():
full_size_prefix = 't' + hex_prefix
file_prefix = 'f' + hex_prefix
full_size_location = self._prefixes_to_locations[ full_size_prefix ]
file_location = self._prefixes_to_locations[ file_prefix ]
if full_size_location != file_location:
return ( full_size_prefix, full_size_location, file_location )
2016-07-27 21:53:34 +00:00
2016-08-10 19:04:08 +00:00
else:
2016-07-27 21:53:34 +00:00
2016-08-10 19:04:08 +00:00
for hex_prefix in HydrusData.IterateHexPrefixes():
full_size_prefix = 't' + hex_prefix
2016-07-27 21:53:34 +00:00
2016-08-10 19:04:08 +00:00
full_size_location = self._prefixes_to_locations[ full_size_prefix ]
if full_size_location != full_size_thumbnail_override:
return ( full_size_prefix, full_size_location, full_size_thumbnail_override )
2016-07-27 21:53:34 +00:00
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
if resized_thumbnail_override is None:
for hex_prefix in HydrusData.IterateHexPrefixes():
resized_prefix = 'r' + hex_prefix
file_prefix = 'f' + hex_prefix
resized_location = self._prefixes_to_locations[ resized_prefix ]
file_location = self._prefixes_to_locations[ file_prefix ]
if resized_location != file_location:
return ( resized_prefix, resized_location, file_location )
else:
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
for hex_prefix in HydrusData.IterateHexPrefixes():
resized_prefix = 'r' + hex_prefix
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
resized_location = self._prefixes_to_locations[ resized_prefix ]
if resized_location != resized_thumbnail_override:
return ( resized_prefix, resized_location, resized_thumbnail_override )
2015-11-25 22:00:57 +00:00
2016-07-27 21:53:34 +00:00
return None
2015-11-25 22:00:57 +00:00
2015-12-02 22:32:18 +00:00
def _IterateAllFilePaths( self ):
for ( prefix, location ) in self._prefixes_to_locations.items():
2016-07-27 21:53:34 +00:00
if prefix.startswith( 'f' ):
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
dir = os.path.join( location, prefix )
filenames = os.listdir( dir )
for filename in filenames:
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
yield os.path.join( dir, filename )
2016-06-08 20:27:22 +00:00
2015-12-02 22:32:18 +00:00
2016-06-08 20:27:22 +00:00
def _IterateAllThumbnailPaths( self ):
for ( prefix, location ) in self._prefixes_to_locations.items():
2016-07-27 21:53:34 +00:00
if prefix.startswith( 't' ) or prefix.startswith( 'r' ):
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
dir = os.path.join( location, prefix )
filenames = os.listdir( dir )
for filename in filenames:
2016-06-08 20:27:22 +00:00
yield os.path.join( dir, filename )
2016-07-27 21:53:34 +00:00
def _LookForFilePath( self, hash ):
2016-06-08 20:27:22 +00:00
for potential_mime in HC.ALLOWED_MIMES:
2016-07-27 21:53:34 +00:00
potential_path = self._GenerateExpectedFilePath( hash, potential_mime )
2016-06-08 20:27:22 +00:00
if os.path.exists( potential_path ):
return potential_path
2016-07-27 21:53:34 +00:00
raise HydrusExceptions.FileMissingException( 'File for ' + hash.encode( 'hex' ) + ' not found!' )
2016-06-08 20:27:22 +00:00
2015-12-02 22:32:18 +00:00
def _Reinit( self ):
self._prefixes_to_locations = self._controller.Read( 'client_files_locations' )
2017-05-10 21:33:58 +00:00
if HG.client_controller.IsFirstStart():
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
try:
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
for ( prefix, location ) in self._prefixes_to_locations.items():
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
HydrusPaths.MakeSureDirectoryExists( location )
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
subdir = os.path.join( location, prefix )
HydrusPaths.MakeSureDirectoryExists( subdir )
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
except:
text = 'Attempting to create the database\'s client_files folder structure failed!'
2016-02-17 22:06:47 +00:00
2017-04-05 21:16:40 +00:00
wx.MessageBox( text )
raise
2016-06-08 20:27:22 +00:00
2017-04-05 21:16:40 +00:00
else:
2016-06-08 20:27:22 +00:00
2017-04-05 21:16:40 +00:00
self._missing_locations = set()
2016-06-08 20:27:22 +00:00
2017-04-05 21:16:40 +00:00
for ( prefix, location ) in self._prefixes_to_locations.items():
if os.path.exists( location ):
subdir = os.path.join( location, prefix )
if not os.path.exists( subdir ):
self._missing_locations.add( ( location, prefix ) )
else:
self._missing_locations.add( ( location, prefix ) )
2016-06-08 20:27:22 +00:00
2017-04-05 21:16:40 +00:00
if len( self._missing_locations ) > 0:
self._bad_error_occured = True
#
missing_dict = HydrusData.BuildKeyToListDict( self._missing_locations )
missing_locations = list( missing_dict.keys() )
missing_locations.sort()
missing_string = ''
for l in missing_locations:
missing_prefixes = list( missing_dict[ l ] )
missing_prefixes.sort()
missing_prefixes_string = ' ' + os.linesep.join( ( ', '.join( block ) for block in HydrusData.SplitListIntoChunks( missing_prefixes, 32 ) ) )
missing_string += os.linesep
missing_string += l
missing_string += os.linesep
missing_string += missing_prefixes_string
#
if len( self._missing_locations ) > 4:
text = 'When initialising the client files manager, some file locations did not exist! They have all been written to the log!'
text += os.linesep * 2
text += 'If this is happening on client boot, you should now be presented with a dialog to correct this manually!'
wx.MessageBox( text )
HydrusData.DebugPrint( text )
HydrusData.DebugPrint( 'Missing locations follow:' )
HydrusData.DebugPrint( missing_string )
else:
text = 'When initialising the client files manager, these file locations did not exist:'
text += os.linesep * 2
text += missing_string
text += os.linesep * 2
text += 'If this is happening on client boot, you should now be presented with a dialog to correct this manually!'
wx.MessageBox( text )
HydrusData.DebugPrint( text )
2016-06-08 20:27:22 +00:00
2017-04-05 21:16:40 +00:00
def GetMissing( self ):
return self._missing_locations
2017-03-02 02:14:56 +00:00
def LocklessAddFileFromString( self, hash, mime, data ):
dest_path = self._GenerateExpectedFilePath( hash, mime )
with open( dest_path, 'wb' ) as f:
f.write( data )
2016-08-24 18:36:56 +00:00
def LocklessAddFile( self, hash, mime, source_path ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
dest_path = self._GenerateExpectedFilePath( hash, mime )
if not os.path.exists( dest_path ):
2016-02-17 22:06:47 +00:00
2017-05-31 21:50:53 +00:00
successful = HydrusPaths.MirrorFile( source_path, dest_path )
if not successful:
raise Exception( 'There was a problem copying the file from ' + source_path + ' to ' + dest_path + '!' )
2016-06-08 20:27:22 +00:00
2016-02-17 22:06:47 +00:00
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
def AddFullSizeThumbnail( self, hash, thumbnail ):
2015-12-02 22:32:18 +00:00
with self._lock:
2016-08-24 18:36:56 +00:00
self.LocklessAddFullSizeThumbnail( hash, thumbnail )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
def LocklessAddFullSizeThumbnail( self, hash, thumbnail ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
path = self._GenerateExpectedFullSizeThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
with open( path, 'wb' ) as f:
f.write( thumbnail )
2016-06-08 20:27:22 +00:00
2017-12-13 22:33:07 +00:00
resized_path = self._GenerateExpectedResizedThumbnailPath( hash )
if os.path.exists( resized_path ):
HydrusPaths.DeletePath( resized_path )
self._controller.pub( 'clear_thumbnails', { hash } )
2016-08-24 18:36:56 +00:00
self._controller.pub( 'new_thumbnails', { hash } )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
def CheckFileIntegrity( self, *args, **kwargs ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
with self._lock:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
self._controller.WriteSynchronous( 'file_integrity', *args, **kwargs )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
def ClearOrphans( self, move_location = None ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
with self._lock:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
job_key = ClientThreading.JobKey( cancellable = True )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
job_key.SetVariable( 'popup_title', 'clearing orphans' )
job_key.SetVariable( 'popup_text_1', 'preparing' )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
self._controller.pub( 'message', job_key )
orphan_paths = []
orphan_thumbnails = []
for ( i, path ) in enumerate( self._IterateAllFilePaths() ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
( i_paused, should_quit ) = job_key.WaitIfNeeded()
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if should_quit:
return
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if i % 100 == 0:
status = 'reviewed ' + HydrusData.ConvertIntToPrettyString( i ) + ' files, found ' + HydrusData.ConvertIntToPrettyString( len( orphan_paths ) ) + ' orphans'
job_key.SetVariable( 'popup_text_1', status )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
try:
is_an_orphan = False
( directory, filename ) = os.path.split( path )
should_be_a_hex_hash = filename[:64]
hash = should_be_a_hex_hash.decode( 'hex' )
2017-05-10 21:33:58 +00:00
is_an_orphan = HG.client_controller.Read( 'is_an_orphan', 'file', hash )
2016-08-24 18:36:56 +00:00
except:
is_an_orphan = True
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if is_an_orphan:
orphan_paths.append( path )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
time.sleep( 2 )
for ( i, path ) in enumerate( self._IterateAllThumbnailPaths() ):
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
( i_paused, should_quit ) = job_key.WaitIfNeeded()
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if should_quit:
return
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if i % 100 == 0:
status = 'reviewed ' + HydrusData.ConvertIntToPrettyString( i ) + ' thumbnails, found ' + HydrusData.ConvertIntToPrettyString( len( orphan_thumbnails ) ) + ' orphans'
job_key.SetVariable( 'popup_text_1', status )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
try:
is_an_orphan = False
( directory, filename ) = os.path.split( path )
should_be_a_hex_hash = filename[:64]
hash = should_be_a_hex_hash.decode( 'hex' )
2017-05-10 21:33:58 +00:00
is_an_orphan = HG.client_controller.Read( 'is_an_orphan', 'thumbnail', hash )
2016-08-24 18:36:56 +00:00
except:
is_an_orphan = True
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if is_an_orphan:
orphan_thumbnails.append( path )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
time.sleep( 2 )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if len( orphan_paths ) > 0:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if move_location is None:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
status = 'found ' + HydrusData.ConvertIntToPrettyString( len( orphan_paths ) ) + ' orphans, now deleting'
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
job_key.SetVariable( 'popup_text_1', status )
time.sleep( 5 )
for path in orphan_paths:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
return
HydrusData.Print( 'Deleting the orphan ' + path )
status = 'deleting orphan files: ' + HydrusData.ConvertValueRangeToPrettyString( i + 1, len( orphan_paths ) )
job_key.SetVariable( 'popup_text_1', status )
HydrusPaths.DeletePath( path )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
else:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
status = 'found ' + HydrusData.ConvertIntToPrettyString( len( orphan_paths ) ) + ' orphans, now moving to ' + move_location
2016-06-08 20:27:22 +00:00
job_key.SetVariable( 'popup_text_1', status )
2016-08-24 18:36:56 +00:00
time.sleep( 5 )
for path in orphan_paths:
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
return
( source_dir, filename ) = os.path.split( path )
dest = os.path.join( move_location, filename )
dest = HydrusPaths.AppendPathUntilNoConflicts( dest )
HydrusData.Print( 'Moving the orphan ' + path + ' to ' + dest )
status = 'moving orphan files: ' + HydrusData.ConvertValueRangeToPrettyString( i + 1, len( orphan_paths ) )
job_key.SetVariable( 'popup_text_1', status )
HydrusPaths.MergeFile( path, dest )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if len( orphan_thumbnails ) > 0:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
status = 'found ' + HydrusData.ConvertIntToPrettyString( len( orphan_thumbnails ) ) + ' orphan thumbnails, now deleting'
2016-06-08 20:27:22 +00:00
job_key.SetVariable( 'popup_text_1', status )
time.sleep( 5 )
2016-08-24 18:36:56 +00:00
for ( i, path ) in enumerate( orphan_thumbnails ):
2016-06-08 20:27:22 +00:00
( i_paused, should_quit ) = job_key.WaitIfNeeded()
if should_quit:
return
2016-08-24 18:36:56 +00:00
status = 'deleting orphan thumbnails: ' + HydrusData.ConvertValueRangeToPrettyString( i + 1, len( orphan_thumbnails ) )
2016-06-08 20:27:22 +00:00
job_key.SetVariable( 'popup_text_1', status )
2016-08-24 18:36:56 +00:00
HydrusData.Print( 'Deleting the orphan ' + path )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
HydrusPaths.DeletePath( path )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
if len( orphan_paths ) == 0 and len( orphan_thumbnails ) == 0:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
final_text = 'no orphans found!'
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
else:
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
final_text = HydrusData.ConvertIntToPrettyString( len( orphan_paths ) ) + ' orphan files and ' + HydrusData.ConvertIntToPrettyString( len( orphan_thumbnails ) ) + ' orphan thumbnails cleared!'
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
job_key.SetVariable( 'popup_text_1', final_text )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
HydrusData.Print( job_key.ToString() )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
job_key.Finish()
2016-06-08 20:27:22 +00:00
2017-02-08 22:27:00 +00:00
def DelayedDeleteFiles( self, hashes, time_to_delete ):
2016-08-24 18:36:56 +00:00
2017-02-08 22:27:00 +00:00
while not HydrusData.TimeHasPassed( time_to_delete ):
time.sleep( 0.5 )
2016-06-08 20:27:22 +00:00
with self._lock:
for hash in hashes:
try:
2016-07-27 21:53:34 +00:00
path = self._LookForFilePath( hash )
2016-06-08 20:27:22 +00:00
except HydrusExceptions.FileMissingException:
continue
ClientData.DeletePath( path )
2017-02-08 22:27:00 +00:00
def DelayedDeleteThumbnails( self, hashes, time_to_delete ):
2016-08-24 18:36:56 +00:00
2017-02-08 22:27:00 +00:00
while not HydrusData.TimeHasPassed( time_to_delete ):
time.sleep( 0.5 )
2016-06-08 20:27:22 +00:00
with self._lock:
for hash in hashes:
2016-07-27 21:53:34 +00:00
path = self._GenerateExpectedFullSizeThumbnailPath( hash )
resized_path = self._GenerateExpectedResizedThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
HydrusPaths.DeletePath( path )
HydrusPaths.DeletePath( resized_path )
2015-12-02 22:32:18 +00:00
def GetFilePath( self, hash, mime = None ):
with self._lock:
2016-08-24 18:36:56 +00:00
return self.LocklessGetFilePath( hash, mime )
2016-06-08 20:27:22 +00:00
2016-08-24 18:36:56 +00:00
2017-07-19 21:21:41 +00:00
def ImportFile( self, file_import_job ):
2016-08-24 18:36:56 +00:00
2017-07-19 21:21:41 +00:00
file_import_job.GenerateHashAndStatus()
hash = file_import_job.GetHash()
if file_import_job.IsNewToDB():
2016-06-08 20:27:22 +00:00
2017-07-19 21:21:41 +00:00
file_import_job.GenerateInfo()
2016-08-24 18:36:56 +00:00
2018-02-28 22:30:36 +00:00
file_import_job.CheckIsGoodToImport()
2017-07-19 21:21:41 +00:00
2018-02-28 22:30:36 +00:00
with self._lock:
2017-07-19 21:21:41 +00:00
2018-02-28 22:30:36 +00:00
( temp_path, thumbnail ) = file_import_job.GetTempPathAndThumbnail()
mime = file_import_job.GetMime()
self.LocklessAddFile( hash, mime, temp_path )
if thumbnail is not None:
2017-07-19 21:21:41 +00:00
2018-02-28 22:30:36 +00:00
self.LocklessAddFullSizeThumbnail( hash, thumbnail )
2017-07-19 21:21:41 +00:00
2018-02-28 22:30:36 +00:00
import_status = self._controller.WriteSynchronous( 'import_file', file_import_job )
2017-07-19 21:21:41 +00:00
else:
file_import_job.PubsubContentUpdates()
import_status = file_import_job.GetPreImportStatus()
return ( import_status, hash )
2016-08-24 18:36:56 +00:00
def LocklessGetFilePath( self, hash, mime = None ):
if mime is None:
path = self._LookForFilePath( hash )
else:
path = self._GenerateExpectedFilePath( hash, mime )
if not os.path.exists( path ):
raise HydrusExceptions.FileMissingException( 'No file found at path + ' + path + '!' )
2015-12-02 22:32:18 +00:00
2016-08-24 18:36:56 +00:00
return path
2015-12-02 22:32:18 +00:00
2017-11-15 22:35:49 +00:00
def GetFullSizeThumbnailPath( self, hash, mime = None ):
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
with self._lock:
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
path = self._GenerateExpectedFullSizeThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
if not os.path.exists( path ):
2015-12-02 22:32:18 +00:00
2017-11-15 22:35:49 +00:00
self._GenerateFullSizeThumbnail( hash, mime )
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
if not self._bad_error_occured:
self._bad_error_occured = True
2017-06-14 21:19:11 +00:00
HydrusData.ShowText( 'A thumbnail for a file, ' + hash.encode( 'hex' ) + ', was missing. It has been regenerated from the original file, but this event could indicate hard drive corruption. Please check everything is ok. This error may be occuring for many files, but this message will only display once per boot. If you are recovering from a fractured database, you may wish to run \'database->regenerate->all thumbnails\'.' )
2016-07-27 21:53:34 +00:00
2015-12-02 22:32:18 +00:00
2016-07-27 21:53:34 +00:00
return path
2016-06-08 20:27:22 +00:00
2015-12-02 22:32:18 +00:00
2017-11-15 22:35:49 +00:00
def GetResizedThumbnailPath( self, hash, mime ):
2015-12-02 22:32:18 +00:00
with self._lock:
2016-07-27 21:53:34 +00:00
path = self._GenerateExpectedResizedThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
if not os.path.exists( path ):
2015-12-02 22:32:18 +00:00
2017-11-15 22:35:49 +00:00
self._GenerateResizedThumbnail( hash, mime )
2015-12-02 22:32:18 +00:00
2016-06-08 20:27:22 +00:00
return path
2017-03-02 02:14:56 +00:00
def LocklessHasFullSizeThumbnail( self, hash ):
2016-06-08 20:27:22 +00:00
2017-03-02 02:14:56 +00:00
path = self._GenerateExpectedFullSizeThumbnailPath( hash )
return os.path.exists( path )
2015-12-02 22:32:18 +00:00
2017-07-27 00:47:13 +00:00
def Rebalance( self, job_key ):
2015-11-25 22:00:57 +00:00
2017-07-27 00:47:13 +00:00
try:
2015-11-25 22:00:57 +00:00
2017-07-27 00:47:13 +00:00
if self._bad_error_occured:
2015-11-25 22:00:57 +00:00
2017-07-27 00:47:13 +00:00
wx.MessageBox( 'A serious file error has previously occured during this session, so further file moving will not be reattempted. Please restart the client before trying again.' )
2015-12-02 22:32:18 +00:00
2017-07-27 00:47:13 +00:00
return
2015-12-02 22:32:18 +00:00
2017-07-27 00:47:13 +00:00
with self._lock:
2015-11-25 22:00:57 +00:00
2017-07-27 00:47:13 +00:00
rebalance_tuple = self._GetRebalanceTuple()
2015-11-25 22:00:57 +00:00
2017-07-27 00:47:13 +00:00
while rebalance_tuple is not None:
2016-01-13 22:08:19 +00:00
2017-07-27 00:47:13 +00:00
if job_key.IsCancelled():
break
2016-01-13 22:08:19 +00:00
2017-07-27 00:47:13 +00:00
( prefix, overweight_location, underweight_location ) = rebalance_tuple
2016-01-13 22:08:19 +00:00
2017-07-27 00:47:13 +00:00
text = 'Moving \'' + prefix + '\' from ' + overweight_location + ' to ' + underweight_location
HydrusData.Print( text )
job_key.SetVariable( 'popup_text_1', text )
# these two lines can cause a deadlock because the db sometimes calls stuff in here.
self._controller.Write( 'relocate_client_files', prefix, overweight_location, underweight_location )
self._Reinit()
rebalance_tuple = self._GetRebalanceTuple()
2016-01-13 22:08:19 +00:00
2015-12-02 22:32:18 +00:00
recover_tuple = self._GetRecoverTuple()
2017-07-27 00:47:13 +00:00
while recover_tuple is not None:
if job_key.IsCancelled():
break
( prefix, recoverable_location, correct_location ) = recover_tuple
text = 'Recovering \'' + prefix + '\' from ' + recoverable_location + ' to ' + correct_location
HydrusData.Print( text )
job_key.SetVariable( 'popup_text_1', text )
recoverable_path = os.path.join( recoverable_location, prefix )
correct_path = os.path.join( correct_location, prefix )
HydrusPaths.MergeTree( recoverable_path, correct_path )
recover_tuple = self._GetRecoverTuple()
finally:
job_key.SetVariable( 'popup_text_1', 'done!' )
job_key.Finish()
job_key.Delete()
2015-12-02 22:32:18 +00:00
2017-07-19 21:21:41 +00:00
2017-12-13 22:33:07 +00:00
def RebalanceWorkToDo( self ):
2017-07-19 21:21:41 +00:00
with self._lock:
2015-12-02 22:32:18 +00:00
2017-12-13 22:33:07 +00:00
return self._GetRebalanceTuple() is not None
2015-12-02 22:32:18 +00:00
2015-11-25 22:00:57 +00:00
2017-12-13 22:33:07 +00:00
def RegenerateResizedThumbnail( self, hash, mime ):
2016-06-08 20:27:22 +00:00
with self._lock:
2017-12-13 22:33:07 +00:00
self.LocklessRegenerateResizedThumbnail( hash, mime )
2016-06-08 20:27:22 +00:00
2017-12-13 22:33:07 +00:00
def LocklessRegenerateResizedThumbnail( self, hash, mime ):
self._GenerateResizedThumbnail( hash, mime )
2016-06-08 20:27:22 +00:00
def RegenerateThumbnails( self, only_do_missing = False ):
2016-02-03 22:12:53 +00:00
with self._lock:
2016-06-08 20:27:22 +00:00
job_key = ClientThreading.JobKey( cancellable = True )
job_key.SetVariable( 'popup_title', 'regenerating thumbnails' )
job_key.SetVariable( 'popup_text_1', 'creating directories' )
2017-07-27 00:47:13 +00:00
self._controller.pub( 'modal_message', job_key )
2016-02-03 22:12:53 +00:00
2016-06-08 20:27:22 +00:00
num_broken = 0
for ( i, path ) in enumerate( self._IterateAllFilePaths() ):
2016-02-03 22:12:53 +00:00
2016-06-08 20:27:22 +00:00
try:
2016-02-03 22:12:53 +00:00
2016-06-08 20:27:22 +00:00
while job_key.IsPaused() or job_key.IsCancelled():
time.sleep( 0.1 )
if job_key.IsCancelled():
job_key.SetVariable( 'popup_text_1', 'cancelled' )
HydrusData.Print( job_key.ToString() )
return
job_key.SetVariable( 'popup_text_1', HydrusData.ConvertIntToPrettyString( i ) + ' done' )
( base, filename ) = os.path.split( path )
2017-03-29 19:39:34 +00:00
if '.' in filename:
( hash_encoded, ext ) = filename.split( '.', 1 )
else:
continue # it is an update file, so let's save us some ffmpeg lag and logspam
2016-06-08 20:27:22 +00:00
hash = hash_encoded.decode( 'hex' )
2016-07-27 21:53:34 +00:00
full_size_path = self._GenerateExpectedFullSizeThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
if only_do_missing and os.path.exists( full_size_path ):
continue
mime = HydrusFileHandling.GetMime( path )
if mime in HC.MIMES_WITH_THUMBNAILS:
2017-11-15 22:35:49 +00:00
self._GenerateFullSizeThumbnail( hash, mime )
2016-06-08 20:27:22 +00:00
2016-07-27 21:53:34 +00:00
thumbnail_resized_path = self._GenerateExpectedResizedThumbnailPath( hash )
2016-06-08 20:27:22 +00:00
if os.path.exists( thumbnail_resized_path ):
HydrusPaths.DeletePath( thumbnail_resized_path )
except:
HydrusData.Print( path )
HydrusData.Print( traceback.format_exc() )
2016-02-17 22:06:47 +00:00
2016-06-08 20:27:22 +00:00
num_broken += 1
2016-02-03 22:12:53 +00:00
2016-06-08 20:27:22 +00:00
if num_broken > 0:
job_key.SetVariable( 'popup_text_1', 'done! ' + HydrusData.ConvertIntToPrettyString( num_broken ) + ' files caused errors, which have been written to the log.' )
else:
job_key.SetVariable( 'popup_text_1', 'done!' )
HydrusData.Print( job_key.ToString() )
job_key.Finish()
2016-02-03 22:12:53 +00:00
2015-03-18 21:46:29 +00:00
class DataCache( object ):
2017-09-13 20:50:41 +00:00
def __init__( self, controller, cache_size, timeout = 1200 ):
2015-03-18 21:46:29 +00:00
2015-11-25 22:00:57 +00:00
self._controller = controller
2016-08-24 18:36:56 +00:00
self._cache_size = cache_size
2017-09-13 20:50:41 +00:00
self._timeout = timeout
2015-03-18 21:46:29 +00:00
self._keys_to_data = {}
2017-07-05 21:09:28 +00:00
self._keys_fifo = collections.OrderedDict()
2015-03-18 21:46:29 +00:00
self._total_estimated_memory_footprint = 0
self._lock = threading.Lock()
2017-07-05 21:09:28 +00:00
self._controller.sub( self, 'MaintainCache', 'memory_maintenance_pulse' )
2015-03-18 21:46:29 +00:00
2017-12-13 22:33:07 +00:00
def _Delete( self, key ):
2015-06-24 22:10:14 +00:00
2017-12-13 22:33:07 +00:00
if key not in self._keys_to_data:
return
2015-06-24 22:10:14 +00:00
2017-12-13 22:33:07 +00:00
deletee_data = self._keys_to_data[ key ]
2015-06-24 22:10:14 +00:00
2017-12-13 22:33:07 +00:00
del self._keys_to_data[ key ]
2015-06-24 22:10:14 +00:00
2016-04-14 01:54:29 +00:00
self._RecalcMemoryUsage()
2017-12-13 22:33:07 +00:00
def _DeleteItem( self ):
( deletee_key, last_access_time ) = self._keys_fifo.popitem( last = False )
self._Delete( deletee_key )
2016-04-14 01:54:29 +00:00
def _RecalcMemoryUsage( self ):
self._total_estimated_memory_footprint = sum( ( data.GetEstimatedMemoryFootprint() for data in self._keys_to_data.values() ) )
2015-06-24 22:10:14 +00:00
2016-08-03 22:15:54 +00:00
def _TouchKey( self, key ):
2017-07-05 21:09:28 +00:00
# have to delete first, rather than overwriting, so the ordereddict updates its internal order
if key in self._keys_fifo:
2016-08-03 22:15:54 +00:00
2017-07-05 21:09:28 +00:00
del self._keys_fifo[ key ]
2016-08-03 22:15:54 +00:00
2017-07-05 21:09:28 +00:00
self._keys_fifo[ key ] = HydrusData.GetNow()
2016-08-03 22:15:54 +00:00
2015-03-18 21:46:29 +00:00
def Clear( self ):
with self._lock:
self._keys_to_data = {}
2017-07-05 21:09:28 +00:00
self._keys_fifo = collections.OrderedDict()
2015-03-18 21:46:29 +00:00
self._total_estimated_memory_footprint = 0
def AddData( self, key, data ):
with self._lock:
if key not in self._keys_to_data:
2016-08-24 18:36:56 +00:00
while self._total_estimated_memory_footprint > self._cache_size:
2015-03-18 21:46:29 +00:00
2015-06-24 22:10:14 +00:00
self._DeleteItem()
2015-03-18 21:46:29 +00:00
self._keys_to_data[ key ] = data
2017-07-05 21:09:28 +00:00
self._TouchKey( key )
2015-03-18 21:46:29 +00:00
2016-04-14 01:54:29 +00:00
self._RecalcMemoryUsage()
2015-03-18 21:46:29 +00:00
2017-12-13 22:33:07 +00:00
def DeleteData( self, key ):
with self._lock:
self._Delete( key )
2015-03-18 21:46:29 +00:00
def GetData( self, key ):
with self._lock:
2016-04-14 01:54:29 +00:00
if key not in self._keys_to_data:
raise Exception( 'Cache error! Looking for ' + HydrusData.ToUnicode( key ) + ', but it was missing.' )
2015-03-18 21:46:29 +00:00
2016-08-03 22:15:54 +00:00
self._TouchKey( key )
2015-03-18 21:46:29 +00:00
return self._keys_to_data[ key ]
2016-08-03 22:15:54 +00:00
def GetIfHasData( self, key ):
with self._lock:
if key in self._keys_to_data:
self._TouchKey( key )
return self._keys_to_data[ key ]
else:
return None
2015-03-18 21:46:29 +00:00
def HasData( self, key ):
2016-04-14 01:54:29 +00:00
with self._lock:
return key in self._keys_to_data
2015-03-18 21:46:29 +00:00
def MaintainCache( self ):
with self._lock:
while True:
2016-04-14 01:54:29 +00:00
if len( self._keys_fifo ) == 0:
2015-03-18 21:46:29 +00:00
2016-04-14 01:54:29 +00:00
break
2015-03-18 21:46:29 +00:00
2016-04-14 01:54:29 +00:00
else:
2017-07-05 21:09:28 +00:00
( key, last_access_time ) = next( self._keys_fifo.iteritems() )
2015-06-24 22:10:14 +00:00
2017-09-13 20:50:41 +00:00
if HydrusData.TimeHasPassed( last_access_time + self._timeout ):
2015-03-18 21:46:29 +00:00
2016-04-14 01:54:29 +00:00
self._DeleteItem()
else:
break
2015-03-18 21:46:29 +00:00
class LocalBooruCache( object ):
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
self._controller = controller
2015-03-18 21:46:29 +00:00
self._lock = threading.Lock()
self._RefreshShares()
2015-11-25 22:00:57 +00:00
self._controller.sub( self, 'RefreshShares', 'refresh_local_booru_shares' )
self._controller.sub( self, 'RefreshShares', 'restart_booru' )
2015-03-18 21:46:29 +00:00
def _CheckDataUsage( self ):
2017-06-07 22:05:15 +00:00
if not self._local_booru_service.BandwidthOK():
2017-03-02 02:14:56 +00:00
raise HydrusExceptions.ForbiddenException( 'This booru has used all its monthly data. Please try again next month.' )
2015-03-18 21:46:29 +00:00
def _CheckFileAuthorised( self, share_key, hash ):
self._CheckShareAuthorised( share_key )
info = self._GetInfo( share_key )
2017-05-31 21:50:53 +00:00
if hash not in info[ 'hashes_set' ]:
raise HydrusExceptions.NotFoundException( 'That file was not found in that share.' )
2015-03-18 21:46:29 +00:00
def _CheckShareAuthorised( self, share_key ):
self._CheckDataUsage()
info = self._GetInfo( share_key )
timeout = info[ 'timeout' ]
2017-05-31 21:50:53 +00:00
if timeout is not None and HydrusData.TimeHasPassed( timeout ):
raise HydrusExceptions.ForbiddenException( 'This share has expired.' )
2015-03-18 21:46:29 +00:00
def _GetInfo( self, share_key ):
try: info = self._keys_to_infos[ share_key ]
except: raise HydrusExceptions.NotFoundException( 'Did not find that share on this booru.' )
if info is None:
2015-11-25 22:00:57 +00:00
info = self._controller.Read( 'local_booru_share', share_key )
2015-03-18 21:46:29 +00:00
hashes = info[ 'hashes' ]
info[ 'hashes_set' ] = set( hashes )
2016-05-04 21:50:55 +00:00
media_results = self._controller.Read( 'media_results', hashes )
2015-03-18 21:46:29 +00:00
info[ 'media_results' ] = media_results
hashes_to_media_results = { media_result.GetHash() : media_result for media_result in media_results }
info[ 'hashes_to_media_results' ] = hashes_to_media_results
self._keys_to_infos[ share_key ] = info
return info
def _RefreshShares( self ):
2017-06-28 20:23:21 +00:00
self._local_booru_service = self._controller.services_manager.GetService( CC.LOCAL_BOORU_SERVICE_KEY )
2015-03-18 21:46:29 +00:00
self._keys_to_infos = {}
2015-11-25 22:00:57 +00:00
share_keys = self._controller.Read( 'local_booru_share_keys' )
2015-03-18 21:46:29 +00:00
for share_key in share_keys: self._keys_to_infos[ share_key ] = None
def CheckShareAuthorised( self, share_key ):
with self._lock: self._CheckShareAuthorised( share_key )
def CheckFileAuthorised( self, share_key, hash ):
with self._lock: self._CheckFileAuthorised( share_key, hash )
def GetGalleryInfo( self, share_key ):
with self._lock:
self._CheckShareAuthorised( share_key )
info = self._GetInfo( share_key )
name = info[ 'name' ]
text = info[ 'text' ]
timeout = info[ 'timeout' ]
media_results = info[ 'media_results' ]
return ( name, text, timeout, media_results )
def GetMediaResult( self, share_key, hash ):
with self._lock:
info = self._GetInfo( share_key )
media_result = info[ 'hashes_to_media_results' ][ hash ]
return media_result
def GetPageInfo( self, share_key, hash ):
with self._lock:
self._CheckFileAuthorised( share_key, hash )
info = self._GetInfo( share_key )
name = info[ 'name' ]
text = info[ 'text' ]
timeout = info[ 'timeout' ]
media_result = info[ 'hashes_to_media_results' ][ hash ]
return ( name, text, timeout, media_result )
def RefreshShares( self ):
with self._lock:
self._RefreshShares()
class MenuEventIdToActionCache( object ):
def __init__( self ):
self._ids_to_actions = {}
self._actions_to_ids = {}
2015-09-23 21:21:02 +00:00
self._temporary_ids = set()
self._free_temporary_ids = set()
def _ClearTemporaries( self ):
for temporary_id in self._temporary_ids.difference( self._free_temporary_ids ):
temporary_action = self._ids_to_actions[ temporary_id ]
del self._ids_to_actions[ temporary_id ]
del self._actions_to_ids[ temporary_action ]
self._free_temporary_ids = set( self._temporary_ids )
def _GetNewId( self, temporary ):
if temporary:
if len( self._free_temporary_ids ) == 0:
new_id = wx.NewId()
self._temporary_ids.add( new_id )
self._free_temporary_ids.add( new_id )
2016-10-05 20:22:40 +00:00
2015-09-23 21:21:02 +00:00
return self._free_temporary_ids.pop()
else:
return wx.NewId()
2015-03-18 21:46:29 +00:00
def GetAction( self, event_id ):
2015-09-23 21:21:02 +00:00
action = None
if event_id in self._ids_to_actions:
action = self._ids_to_actions[ event_id ]
if event_id in self._temporary_ids:
self._ClearTemporaries()
return action
2015-03-18 21:46:29 +00:00
2015-09-23 21:21:02 +00:00
def GetId( self, command, data = None, temporary = False ):
2015-03-18 21:46:29 +00:00
action = ( command, data )
if action not in self._actions_to_ids:
2015-09-23 21:21:02 +00:00
event_id = self._GetNewId( temporary )
2015-03-18 21:46:29 +00:00
self._ids_to_actions[ event_id ] = action
self._actions_to_ids[ action ] = event_id
return self._actions_to_ids[ action ]
2015-09-23 21:21:02 +00:00
def GetPermanentId( self, command, data = None ):
return self.GetId( command, data, False )
def GetTemporaryId( self, command, data = None ):
temporary = True
if data is None:
temporary = False
return self.GetId( command, data, temporary )
2015-03-18 21:46:29 +00:00
MENU_EVENT_ID_TO_ACTION_CACHE = MenuEventIdToActionCache()
class RenderedImageCache( object ):
2016-08-17 20:07:22 +00:00
def __init__( self, controller ):
2015-03-18 21:46:29 +00:00
2015-11-25 22:00:57 +00:00
self._controller = controller
2015-03-18 21:46:29 +00:00
2017-12-06 22:06:56 +00:00
cache_size = self._controller.options[ 'fullscreen_cache_size' ]
2016-08-24 18:36:56 +00:00
2017-09-13 20:50:41 +00:00
self._data_cache = DataCache( self._controller, cache_size, timeout = 600 )
2015-03-18 21:46:29 +00:00
2017-10-04 17:51:58 +00:00
def Clear( self ):
self._data_cache.Clear()
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
def GetImageRenderer( self, media ):
2015-03-18 21:46:29 +00:00
hash = media.GetHash()
2016-09-21 19:54:04 +00:00
key = hash
2015-03-18 21:46:29 +00:00
2016-08-03 22:15:54 +00:00
result = self._data_cache.GetIfHasData( key )
if result is None:
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
image_renderer = ClientRendering.ImageRenderer( media )
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
self._data_cache.AddData( key, image_renderer )
2015-03-18 21:46:29 +00:00
2016-08-03 22:15:54 +00:00
else:
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
image_renderer = result
2016-08-03 22:15:54 +00:00
2016-09-21 19:54:04 +00:00
return image_renderer
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
def HasImageRenderer( self, hash ):
2015-03-18 21:46:29 +00:00
2016-09-21 19:54:04 +00:00
key = hash
2015-03-18 21:46:29 +00:00
2016-04-14 01:54:29 +00:00
return self._data_cache.HasData( key )
2015-03-18 21:46:29 +00:00
class ThumbnailCache( object ):
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
2015-03-18 21:46:29 +00:00
2015-11-25 22:00:57 +00:00
self._controller = controller
2016-08-24 18:36:56 +00:00
2017-12-06 22:06:56 +00:00
cache_size = self._controller.options[ 'thumbnail_cache_size' ]
2016-08-24 18:36:56 +00:00
2017-09-13 20:50:41 +00:00
self._data_cache = DataCache( self._controller, cache_size, timeout = 86400 )
2015-03-18 21:46:29 +00:00
2015-11-04 22:30:28 +00:00
self._lock = threading.Lock()
self._waterfall_queue_quick = set()
self._waterfall_queue_random = []
self._waterfall_event = threading.Event()
2015-03-18 21:46:29 +00:00
self._special_thumbs = {}
self.Clear()
2017-08-09 21:33:51 +00:00
self._controller.CallToThreadLongRunning( self.DAEMONWaterfall )
2015-03-18 21:46:29 +00:00
2015-11-25 22:00:57 +00:00
self._controller.sub( self, 'Clear', 'thumbnail_resize' )
2017-12-13 22:33:07 +00:00
self._controller.sub( self, 'ClearThumbnails', 'clear_thumbnails' )
2015-03-18 21:46:29 +00:00
2016-06-08 20:27:22 +00:00
def _GetResizedHydrusBitmapFromHardDrive( self, display_media ):
2015-12-23 22:51:04 +00:00
2017-12-06 22:06:56 +00:00
thumbnail_dimensions = self._controller.options[ 'thumbnail_dimensions' ]
2015-12-23 22:51:04 +00:00
2016-06-08 20:27:22 +00:00
if tuple( thumbnail_dimensions ) == HC.UNSCALED_THUMBNAIL_DIMENSIONS:
full_size = True
else:
full_size = False
hash = display_media.GetHash()
2017-11-15 22:35:49 +00:00
mime = display_media.GetMime()
2015-12-23 22:51:04 +00:00
locations_manager = display_media.GetLocationsManager()
2017-09-13 20:50:41 +00:00
try:
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
if full_size:
2015-12-23 22:51:04 +00:00
2017-11-15 22:35:49 +00:00
path = self._controller.client_files_manager.GetFullSizeThumbnailPath( hash, mime )
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
else:
2015-12-23 22:51:04 +00:00
2017-11-15 22:35:49 +00:00
path = self._controller.client_files_manager.GetResizedThumbnailPath( hash, mime )
2016-06-08 20:27:22 +00:00
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
except HydrusExceptions.FileMissingException as e:
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
if locations_manager.IsLocal():
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
HydrusData.ShowException( e )
2015-12-23 22:51:04 +00:00
2017-09-13 20:50:41 +00:00
return self._special_thumbs[ 'hydrus' ]
2015-12-23 22:51:04 +00:00
2017-08-23 21:34:25 +00:00
mime = display_media.GetMime()
2016-06-08 20:27:22 +00:00
try:
2015-12-23 22:51:04 +00:00
2017-08-23 21:34:25 +00:00
hydrus_bitmap = ClientRendering.GenerateHydrusBitmap( path, mime )
2015-12-23 22:51:04 +00:00
2016-06-08 20:27:22 +00:00
except Exception as e:
HydrusData.ShowException( e )
2015-12-23 22:51:04 +00:00
try:
2017-11-15 22:35:49 +00:00
self._controller.client_files_manager.RegenerateResizedThumbnail( hash, mime )
2015-12-23 22:51:04 +00:00
try:
2017-08-23 21:34:25 +00:00
hydrus_bitmap = ClientRendering.GenerateHydrusBitmap( path, mime )
2015-12-23 22:51:04 +00:00
except Exception as e:
HydrusData.ShowException( e )
2016-06-08 20:27:22 +00:00
raise HydrusExceptions.FileMissingException( 'The thumbnail for file ' + hash.encode( 'hex' ) + ' was broken. It was regenerated, but the new file would not render for the above reason. Please inform the hydrus developer what has happened.' )
2015-12-23 22:51:04 +00:00
2016-06-08 20:27:22 +00:00
except Exception as e:
HydrusData.ShowException( e )
return self._special_thumbs[ 'hydrus' ]
( media_x, media_y ) = display_media.GetResolution()
( actual_x, actual_y ) = hydrus_bitmap.GetSize()
2017-12-06 22:06:56 +00:00
( desired_x, desired_y ) = self._controller.options[ 'thumbnail_dimensions' ]
2016-06-08 20:27:22 +00:00
too_large = actual_x > desired_x or actual_y > desired_y
small_original_image = actual_x == media_x and actual_y == media_y
too_small = actual_x < desired_x and actual_y < desired_y
if too_large or ( too_small and not small_original_image ):
2017-11-15 22:35:49 +00:00
self._controller.client_files_manager.RegenerateResizedThumbnail( hash, mime )
2016-06-08 20:27:22 +00:00
2017-08-23 21:34:25 +00:00
hydrus_bitmap = ClientRendering.GenerateHydrusBitmap( path, mime )
2015-12-23 22:51:04 +00:00
return hydrus_bitmap
2015-11-04 22:30:28 +00:00
def _RecalcWaterfallQueueRandom( self ):
2017-09-13 20:50:41 +00:00
# here we sort by the hash since this is both breddy random and more likely to access faster on a well defragged hard drive!
def sort_by_hash_key( ( page_key, media ) ):
return media.GetDisplayMedia().GetHash()
2015-11-04 22:30:28 +00:00
self._waterfall_queue_random = list( self._waterfall_queue_quick )
2017-09-13 20:50:41 +00:00
self._waterfall_queue_random.sort( key = sort_by_hash_key )
2015-11-04 22:30:28 +00:00
def CancelWaterfall( self, page_key, medias ):
with self._lock:
self._waterfall_queue_quick.difference_update( ( ( page_key, media ) for media in medias ) )
self._RecalcWaterfallQueueRandom()
2015-03-18 21:46:29 +00:00
def Clear( self ):
2016-02-03 22:12:53 +00:00
with self._lock:
2015-03-18 21:46:29 +00:00
2016-02-03 22:12:53 +00:00
self._data_cache.Clear()
self._special_thumbs = {}
2017-10-04 17:51:58 +00:00
names = [ 'hydrus', 'flash', 'pdf', 'audio', 'video', 'zip' ]
2016-02-03 22:12:53 +00:00
( os_file_handle, temp_path ) = HydrusPaths.GetTempPath()
try:
2015-05-06 20:26:18 +00:00
2016-02-03 22:12:53 +00:00
for name in names:
path = os.path.join( HC.STATIC_DIR, name + '.png' )
2017-12-06 22:06:56 +00:00
thumbnail_dimensions = self._controller.options[ 'thumbnail_dimensions' ]
2016-02-03 22:12:53 +00:00
2017-12-06 22:06:56 +00:00
thumbnail = HydrusFileHandling.GenerateThumbnailFromStaticImage( path, thumbnail_dimensions, HC.IMAGE_PNG )
2016-02-03 22:12:53 +00:00
2017-05-24 20:28:24 +00:00
with open( temp_path, 'wb' ) as f:
f.write( thumbnail )
2016-02-03 22:12:53 +00:00
2017-08-23 21:34:25 +00:00
hydrus_bitmap = ClientRendering.GenerateHydrusBitmap( temp_path, HC.IMAGE_PNG )
2016-02-03 22:12:53 +00:00
self._special_thumbs[ name ] = hydrus_bitmap
2015-05-06 20:26:18 +00:00
2016-02-03 22:12:53 +00:00
finally:
2015-05-06 20:26:18 +00:00
2016-02-03 22:12:53 +00:00
HydrusPaths.CleanUpTempPath( os_file_handle, temp_path )
2015-05-06 20:26:18 +00:00
2015-03-18 21:46:29 +00:00
2017-12-13 22:33:07 +00:00
def ClearThumbnails( self, hashes ):
with self._lock:
for hash in hashes:
self._data_cache.DeleteData( hash )
2017-10-04 17:51:58 +00:00
def DoingWork( self ):
with self._lock:
return len( self._waterfall_queue_random ) > 0
2015-03-18 21:46:29 +00:00
def GetThumbnail( self, media ):
2018-02-28 22:30:36 +00:00
try:
display_media = media.GetDisplayMedia()
except:
# sometimes media can get switched around during a collect event, and if this happens during waterfall, we have a problem here
# just return for now, we'll see how it goes
return self._special_thumbs[ 'hydrus' ]
2015-11-11 21:20:41 +00:00
2016-04-06 19:52:45 +00:00
if display_media.GetLocationsManager().ShouldHaveThumbnail():
2015-03-18 21:46:29 +00:00
2016-04-06 19:52:45 +00:00
mime = display_media.GetMime()
2015-03-18 21:46:29 +00:00
2016-04-06 19:52:45 +00:00
if mime in HC.MIMES_WITH_THUMBNAILS:
hash = display_media.GetHash()
2015-03-18 21:46:29 +00:00
2016-08-03 22:15:54 +00:00
result = self._data_cache.GetIfHasData( hash )
if result is None:
2016-04-06 19:52:45 +00:00
hydrus_bitmap = self._GetResizedHydrusBitmapFromHardDrive( display_media )
self._data_cache.AddData( hash, hydrus_bitmap )
2016-08-03 22:15:54 +00:00
else:
hydrus_bitmap = result
2015-03-18 21:46:29 +00:00
2016-08-03 22:15:54 +00:00
return hydrus_bitmap
2015-03-18 21:46:29 +00:00
2016-04-06 19:52:45 +00:00
elif mime in HC.AUDIO: return self._special_thumbs[ 'audio' ]
elif mime in HC.VIDEO: return self._special_thumbs[ 'video' ]
elif mime == HC.APPLICATION_FLASH: return self._special_thumbs[ 'flash' ]
elif mime == HC.APPLICATION_PDF: return self._special_thumbs[ 'pdf' ]
2017-10-04 17:51:58 +00:00
elif mime in HC.ARCHIVES: return self._special_thumbs[ 'zip' ]
2016-04-06 19:52:45 +00:00
else: return self._special_thumbs[ 'hydrus' ]
2015-03-18 21:46:29 +00:00
2016-04-06 19:52:45 +00:00
else:
return self._special_thumbs[ 'hydrus' ]
2015-03-18 21:46:29 +00:00
2016-02-03 22:12:53 +00:00
2015-03-18 21:46:29 +00:00
2015-11-11 21:20:41 +00:00
def HasThumbnailCached( self, media ):
display_media = media.GetDisplayMedia()
mime = display_media.GetMime()
if mime in HC.MIMES_WITH_THUMBNAILS:
hash = display_media.GetHash()
return self._data_cache.HasData( hash )
else:
return True
2015-11-04 22:30:28 +00:00
def Waterfall( self, page_key, medias ):
with self._lock:
self._waterfall_queue_quick.update( ( ( page_key, media ) for media in medias ) )
2015-11-25 22:00:57 +00:00
self._RecalcWaterfallQueueRandom()
self._waterfall_event.set()
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
def DAEMONWaterfall( self ):
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
last_paused = HydrusData.GetNowPrecise()
2015-08-05 18:42:35 +00:00
2018-02-14 21:47:18 +00:00
while not HydrusThreading.IsThreadShuttingDown():
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
with self._lock:
do_wait = len( self._waterfall_queue_random ) == 0
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
if do_wait:
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
self._waterfall_event.wait( 1 )
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
self._waterfall_event.clear()
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
last_paused = HydrusData.GetNowPrecise()
2017-06-14 21:19:11 +00:00
start_time = HydrusData.GetNowPrecise()
stop_time = start_time + 0.005 # a bit of a typical frame
page_keys_to_rendered_medias = collections.defaultdict( list )
while not HydrusData.TimeHasPassedPrecise( stop_time ):
2015-11-25 22:00:57 +00:00
2017-06-14 21:19:11 +00:00
with self._lock:
2015-08-05 18:42:35 +00:00
2017-06-14 21:19:11 +00:00
if len( self._waterfall_queue_random ) == 0:
break
2015-11-25 22:00:57 +00:00
result = self._waterfall_queue_random.pop( 0 )
self._waterfall_queue_quick.discard( result )
2015-08-05 18:42:35 +00:00
2017-06-14 21:19:11 +00:00
( page_key, media ) = result
2015-08-05 18:42:35 +00:00
2017-06-14 21:19:11 +00:00
try:
2015-11-25 22:00:57 +00:00
2017-06-14 21:19:11 +00:00
self.GetThumbnail( media ) # to load it
2015-11-25 22:00:57 +00:00
2017-06-14 21:19:11 +00:00
page_keys_to_rendered_medias[ page_key ].append( media )
except Exception as e:
HydrusData.ShowException( e )
2015-11-25 22:00:57 +00:00
2017-06-14 21:19:11 +00:00
for ( page_key, rendered_medias ) in page_keys_to_rendered_medias.items():
2015-11-25 22:00:57 +00:00
2017-06-14 21:19:11 +00:00
self._controller.pub( 'waterfall_thumbnails', page_key, rendered_medias )
2015-08-05 18:42:35 +00:00
2017-06-14 21:19:11 +00:00
time.sleep( 0.00001 )
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
class ServicesManager( object ):
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
self._controller = controller
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
self._lock = threading.Lock()
self._keys_to_services = {}
self._services_sorted = []
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
self.RefreshServices()
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
self._controller.sub( self, 'RefreshServices', 'notify_new_services_data' )
2015-11-18 22:44:07 +00:00
2017-01-04 22:48:23 +00:00
def _GetService( self, service_key ):
try:
return self._keys_to_services[ service_key ]
except KeyError:
raise HydrusExceptions.DataMissing( 'That service was not found!' )
2017-03-02 02:14:56 +00:00
def _SetServices( self, services ):
self._keys_to_services = { service.GetServiceKey() : service for service in services }
2017-10-25 21:45:15 +00:00
self._keys_to_services[ CC.TEST_SERVICE_KEY ] = ClientServices.GenerateService( CC.TEST_SERVICE_KEY, HC.TEST_SERVICE, CC.TEST_SERVICE_KEY )
2017-03-08 23:23:12 +00:00
def compare_function( a, b ):
return cmp( a.GetName(), b.GetName() )
2017-03-02 02:14:56 +00:00
self._services_sorted = list( services )
self._services_sorted.sort( cmp = compare_function )
2017-01-04 22:48:23 +00:00
def Filter( self, service_keys, desired_types ):
with self._lock:
2017-03-08 23:23:12 +00:00
def func( service_key ):
return self._keys_to_services[ service_key ].GetServiceType() in desired_types
filtered_service_keys = filter( func, service_keys )
2017-01-04 22:48:23 +00:00
return filtered_service_keys
2016-03-09 19:37:14 +00:00
def FilterValidServiceKeys( self, service_keys ):
with self._lock:
2017-03-08 23:23:12 +00:00
def func( service_key ):
return service_key in self._keys_to_services
filtered_service_keys = filter( func, service_keys )
2016-03-09 19:37:14 +00:00
return filtered_service_keys
2017-01-04 22:48:23 +00:00
def GetName( self, service_key ):
with self._lock:
service = self._GetService( service_key )
return service.GetName()
2015-11-25 22:00:57 +00:00
def GetService( self, service_key ):
2015-11-18 22:44:07 +00:00
with self._lock:
2017-01-04 22:48:23 +00:00
return self._GetService( service_key )
2017-05-24 20:28:24 +00:00
def GetServiceType( self, service_key ):
with self._lock:
return self._GetService( service_key ).GetServiceType()
2017-01-04 22:48:23 +00:00
def GetServiceKeys( self, desired_types = HC.ALL_SERVICES ):
with self._lock:
filtered_service_keys = [ service_key for ( service_key, service ) in self._keys_to_services.items() if service.GetServiceType() in desired_types ]
return filtered_service_keys
2015-11-18 22:44:07 +00:00
2017-01-04 22:48:23 +00:00
def GetServices( self, desired_types = HC.ALL_SERVICES, randomised = True ):
2015-11-18 22:44:07 +00:00
with self._lock:
2017-03-08 23:23:12 +00:00
def func( service ):
return service.GetServiceType() in desired_types
services = filter( func, self._services_sorted )
2015-11-25 22:00:57 +00:00
if randomised:
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
random.shuffle( services )
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
return services
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
def RefreshServices( self ):
with self._lock:
2015-11-18 22:44:07 +00:00
2015-11-25 22:00:57 +00:00
services = self._controller.Read( 'services' )
2015-11-18 22:44:07 +00:00
2017-03-02 02:14:56 +00:00
self._SetServices( services )
2015-11-18 22:44:07 +00:00
2018-01-31 22:58:15 +00:00
2015-11-18 22:44:07 +00:00
2016-10-19 20:02:56 +00:00
def ServiceExists( self, service_key ):
with self._lock:
return service_key in self._keys_to_services
2017-04-19 20:58:30 +00:00
class ShortcutsManager( object ):
def __init__( self, controller ):
self._controller = controller
self._shortcuts = {}
self.RefreshShortcuts()
self._controller.sub( self, 'RefreshShortcuts', 'new_shortcuts' )
def GetCommand( self, shortcuts_names, shortcut ):
for name in shortcuts_names:
if name in self._shortcuts:
command = self._shortcuts[ name ].GetCommand( shortcut )
if command is not None:
2017-05-10 21:33:58 +00:00
if HG.gui_report_mode:
2017-05-03 21:33:48 +00:00
HydrusData.ShowText( 'command matched: ' + repr( command ) )
2017-04-19 20:58:30 +00:00
return command
return None
def RefreshShortcuts( self ):
self._shortcuts = {}
2017-05-10 21:33:58 +00:00
all_shortcuts = HG.client_controller.Read( 'serialisable_named', HydrusSerialisable.SERIALISABLE_TYPE_SHORTCUTS )
2017-04-19 20:58:30 +00:00
for shortcuts in all_shortcuts:
self._shortcuts[ shortcuts.GetName() ] = shortcuts
2015-08-05 18:42:35 +00:00
class TagCensorshipManager( object ):
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
self._controller = controller
2015-08-05 18:42:35 +00:00
self.RefreshData()
2015-11-25 22:00:57 +00:00
self._controller.sub( self, 'RefreshData', 'notify_new_tag_censorship' )
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
def _CensorshipMatches( self, tag, blacklist, censorships ):
if blacklist:
return not HydrusTags.CensorshipMatch( tag, censorships )
else:
return HydrusTags.CensorshipMatch( tag, censorships )
2015-08-05 18:42:35 +00:00
def GetInfo( self, service_key ):
if service_key in self._service_keys_to_info: return self._service_keys_to_info[ service_key ]
else: return ( True, set() )
def RefreshData( self ):
2016-04-06 19:52:45 +00:00
rows = self._controller.Read( 'tag_censorship' )
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
self._service_keys_to_info = { service_key : ( blacklist, censorships ) for ( service_key, blacklist, censorships ) in rows }
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
2016-10-05 20:22:40 +00:00
def FilterPredicates( self, service_key, predicates ):
for service_key_lookup in ( CC.COMBINED_TAG_SERVICE_KEY, service_key ):
if service_key_lookup in self._service_keys_to_info:
( blacklist, censorships ) = self._service_keys_to_info[ service_key_lookup ]
predicates = [ predicate for predicate in predicates if predicate.GetType() != HC.PREDICATE_TYPE_TAG or self._CensorshipMatches( predicate.GetValue(), blacklist, censorships ) ]
return predicates
2016-04-06 19:52:45 +00:00
def FilterStatusesToPairs( self, service_key, statuses_to_pairs ):
for service_key_lookup in ( CC.COMBINED_TAG_SERVICE_KEY, service_key ):
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
if service_key_lookup in self._service_keys_to_info:
2015-11-18 22:44:07 +00:00
2016-04-06 19:52:45 +00:00
( blacklist, censorships ) = self._service_keys_to_info[ service_key_lookup ]
2015-11-18 22:44:07 +00:00
2016-04-06 19:52:45 +00:00
new_statuses_to_pairs = HydrusData.default_dict_set()
2015-11-18 22:44:07 +00:00
2016-04-06 19:52:45 +00:00
for ( status, pairs ) in statuses_to_pairs.items():
new_statuses_to_pairs[ status ] = { ( one, two ) for ( one, two ) in pairs if self._CensorshipMatches( one, blacklist, censorships ) and self._CensorshipMatches( two, blacklist, censorships ) }
statuses_to_pairs = new_statuses_to_pairs
2015-11-18 22:44:07 +00:00
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
return statuses_to_pairs
2015-08-05 18:42:35 +00:00
def FilterServiceKeysToStatusesToTags( self, service_keys_to_statuses_to_tags ):
2016-04-06 19:52:45 +00:00
if CC.COMBINED_TAG_SERVICE_KEY in self._service_keys_to_info:
( blacklist, censorships ) = self._service_keys_to_info[ CC.COMBINED_TAG_SERVICE_KEY ]
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
service_keys = service_keys_to_statuses_to_tags.keys()
for service_key in service_keys:
statuses_to_tags = service_keys_to_statuses_to_tags[ service_key ]
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
statuses = statuses_to_tags.keys()
for status in statuses:
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
tags = statuses_to_tags[ status ]
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
statuses_to_tags[ status ] = { tag for tag in tags if self._CensorshipMatches( tag, blacklist, censorships ) }
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
for ( service_key, ( blacklist, censorships ) ) in self._service_keys_to_info.items():
if service_key == CC.COMBINED_TAG_SERVICE_KEY:
continue
if service_key in service_keys_to_statuses_to_tags:
statuses_to_tags = service_keys_to_statuses_to_tags[ service_key ]
statuses = statuses_to_tags.keys()
for status in statuses:
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
tags = statuses_to_tags[ status ]
statuses_to_tags[ status ] = { tag for tag in tags if self._CensorshipMatches( tag, blacklist, censorships ) }
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
return service_keys_to_statuses_to_tags
2015-08-05 18:42:35 +00:00
def FilterTags( self, service_key, tags ):
2016-04-06 19:52:45 +00:00
for service_key_lookup in ( CC.COMBINED_TAG_SERVICE_KEY, service_key ):
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
if service_key_lookup in self._service_keys_to_info:
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
( blacklist, censorships ) = self._service_keys_to_info[ service_key_lookup ]
2015-08-05 18:42:35 +00:00
2016-04-06 19:52:45 +00:00
tags = { tag for tag in tags if self._CensorshipMatches( tag, blacklist, censorships ) }
2015-08-05 18:42:35 +00:00
return tags
class TagParentsManager( object ):
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
self._controller = controller
2015-08-05 18:42:35 +00:00
2015-11-11 21:20:41 +00:00
self._service_keys_to_children_to_parents = collections.defaultdict( HydrusData.default_dict_list )
2015-08-05 18:42:35 +00:00
self._RefreshParents()
self._lock = threading.Lock()
2015-11-25 22:00:57 +00:00
self._controller.sub( self, 'RefreshParents', 'notify_new_parents' )
2015-08-05 18:42:35 +00:00
def _RefreshParents( self ):
2015-11-25 22:00:57 +00:00
service_keys_to_statuses_to_pairs = self._controller.Read( 'tag_parents' )
2015-08-05 18:42:35 +00:00
# first collapse siblings
2015-11-25 22:00:57 +00:00
sibling_manager = self._controller.GetManager( 'tag_siblings' )
2015-08-05 18:42:35 +00:00
collapsed_service_keys_to_statuses_to_pairs = collections.defaultdict( HydrusData.default_dict_set )
for ( service_key, statuses_to_pairs ) in service_keys_to_statuses_to_pairs.items():
if service_key == CC.COMBINED_TAG_SERVICE_KEY: continue
for ( status, pairs ) in statuses_to_pairs.items():
2016-09-14 18:03:59 +00:00
pairs = sibling_manager.CollapsePairs( service_key, pairs )
2015-08-05 18:42:35 +00:00
collapsed_service_keys_to_statuses_to_pairs[ service_key ][ status ] = pairs
# now collapse current and pending
service_keys_to_pairs_flat = HydrusData.default_dict_set()
for ( service_key, statuses_to_pairs ) in collapsed_service_keys_to_statuses_to_pairs.items():
2017-03-02 02:14:56 +00:00
pairs_flat = statuses_to_pairs[ HC.CONTENT_STATUS_CURRENT ].union( statuses_to_pairs[ HC.CONTENT_STATUS_PENDING ] )
2015-08-05 18:42:35 +00:00
service_keys_to_pairs_flat[ service_key ] = pairs_flat
# now create the combined tag service
combined_pairs_flat = set()
for pairs_flat in service_keys_to_pairs_flat.values():
combined_pairs_flat.update( pairs_flat )
service_keys_to_pairs_flat[ CC.COMBINED_TAG_SERVICE_KEY ] = combined_pairs_flat
#
service_keys_to_simple_children_to_parents = BuildServiceKeysToSimpleChildrenToParents( service_keys_to_pairs_flat )
self._service_keys_to_children_to_parents = BuildServiceKeysToChildrenToParents( service_keys_to_simple_children_to_parents )
def ExpandPredicates( self, service_key, predicates ):
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_parents_to_all_services' ):
2015-11-18 22:44:07 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
results = []
with self._lock:
for predicate in predicates:
results.append( predicate )
if predicate.GetType() == HC.PREDICATE_TYPE_TAG:
tag = predicate.GetValue()
parents = self._service_keys_to_children_to_parents[ service_key ][ tag ]
for parent in parents:
2015-12-09 23:16:41 +00:00
parent_predicate = ClientSearch.Predicate( HC.PREDICATE_TYPE_PARENT, parent )
2015-08-05 18:42:35 +00:00
results.append( parent_predicate )
return results
def ExpandTags( self, service_key, tags ):
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_parents_to_all_services' ):
2015-11-18 22:44:07 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
tags_results = set( tags )
2015-11-11 21:20:41 +00:00
for tag in tags:
tags_results.update( self._service_keys_to_children_to_parents[ service_key ][ tag ] )
2015-08-05 18:42:35 +00:00
return tags_results
def GetParents( self, service_key, tag ):
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_parents_to_all_services' ):
2015-11-18 22:44:07 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
return self._service_keys_to_children_to_parents[ service_key ][ tag ]
def RefreshParents( self ):
2015-11-11 21:20:41 +00:00
with self._lock:
self._RefreshParents()
2015-08-05 18:42:35 +00:00
class TagSiblingsManager( object ):
2015-11-25 22:00:57 +00:00
def __init__( self, controller ):
self._controller = controller
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
self._service_keys_to_siblings = collections.defaultdict( dict )
self._service_keys_to_reverse_lookup = collections.defaultdict( dict )
2015-08-05 18:42:35 +00:00
self._RefreshSiblings()
self._lock = threading.Lock()
2016-07-13 17:37:44 +00:00
self._controller.sub( self, 'RefreshSiblings', 'notify_new_siblings_data' )
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
def _CollapseTags( self, service_key, tags ):
siblings = self._service_keys_to_siblings[ service_key ]
2015-11-11 21:20:41 +00:00
2016-09-14 18:03:59 +00:00
return { siblings[ tag ] if tag in siblings else tag for tag in tags }
2015-11-11 21:20:41 +00:00
2015-08-05 18:42:35 +00:00
def _RefreshSiblings( self ):
2016-09-14 18:03:59 +00:00
self._service_keys_to_siblings = collections.defaultdict( dict )
self._service_keys_to_reverse_lookup = collections.defaultdict( dict )
2017-04-05 21:16:40 +00:00
local_tags_pairs = set()
tag_repo_pairs = set()
2016-09-14 18:03:59 +00:00
2015-11-25 22:00:57 +00:00
service_keys_to_statuses_to_pairs = self._controller.Read( 'tag_siblings' )
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
for ( service_key, statuses_to_pairs ) in service_keys_to_statuses_to_pairs.items():
2017-03-02 02:14:56 +00:00
all_pairs = statuses_to_pairs[ HC.CONTENT_STATUS_CURRENT ].union( statuses_to_pairs[ HC.CONTENT_STATUS_PENDING ] )
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
if service_key == CC.LOCAL_TAG_SERVICE_KEY:
local_tags_pairs = set( all_pairs )
else:
tag_repo_pairs.update( all_pairs )
2016-09-14 18:03:59 +00:00
2017-04-05 21:16:40 +00:00
siblings = CollapseTagSiblingPairs( [ all_pairs ] )
2016-09-14 18:03:59 +00:00
self._service_keys_to_siblings[ service_key ] = siblings
reverse_lookup = collections.defaultdict( list )
for ( bad, good ) in siblings.items():
reverse_lookup[ good ].append( bad )
self._service_keys_to_reverse_lookup[ service_key ] = reverse_lookup
2017-04-05 21:16:40 +00:00
combined_siblings = CollapseTagSiblingPairs( [ local_tags_pairs, tag_repo_pairs ] )
2016-09-14 18:03:59 +00:00
self._service_keys_to_siblings[ CC.COMBINED_TAG_SERVICE_KEY ] = combined_siblings
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
combined_reverse_lookup = collections.defaultdict( list )
for ( bad, good ) in combined_siblings.items():
combined_reverse_lookup[ good ].append( bad )
self._service_keys_to_reverse_lookup[ CC.COMBINED_TAG_SERVICE_KEY ] = combined_reverse_lookup
2015-08-05 18:42:35 +00:00
2015-11-25 22:00:57 +00:00
self._controller.pub( 'new_siblings_gui' )
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
def GetAutocompleteSiblings( self, service_key, search_text, exact_match = False ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
reverse_lookup = self._service_keys_to_reverse_lookup[ service_key ]
2016-03-09 19:37:14 +00:00
if exact_match:
key_based_matching_values = set()
2016-09-14 18:03:59 +00:00
if search_text in siblings:
2016-03-09 19:37:14 +00:00
2016-09-14 18:03:59 +00:00
key_based_matching_values = { siblings[ search_text ] }
2016-03-09 19:37:14 +00:00
else:
key_based_matching_values = set()
2016-09-14 18:03:59 +00:00
value_based_matching_values = { value for value in siblings.values() if value == search_text }
2016-03-09 19:37:14 +00:00
else:
2017-03-08 23:23:12 +00:00
matching_keys = ClientSearch.FilterTagsBySearchText( service_key, search_text, siblings.keys(), search_siblings = False )
2016-03-09 19:37:14 +00:00
2016-09-14 18:03:59 +00:00
key_based_matching_values = { siblings[ key ] for key in matching_keys }
2016-03-16 22:19:14 +00:00
2017-03-08 23:23:12 +00:00
value_based_matching_values = ClientSearch.FilterTagsBySearchText( service_key, search_text, siblings.values(), search_siblings = False )
2016-03-09 19:37:14 +00:00
2015-08-05 18:42:35 +00:00
matching_values = key_based_matching_values.union( value_based_matching_values )
# all the matching values have a matching sibling somewhere in their network
# so now fetch the networks
2016-09-14 18:03:59 +00:00
lists_of_matching_keys = [ reverse_lookup[ value ] for value in matching_values ]
2015-08-05 18:42:35 +00:00
matching_keys = itertools.chain.from_iterable( lists_of_matching_keys )
matches = matching_values.union( matching_keys )
return matches
2016-09-14 18:03:59 +00:00
def GetSibling( self, service_key, tag ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
if tag in siblings:
return siblings[ tag ]
else:
return None
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
def GetAllSiblings( self, service_key, tag ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
reverse_lookup = self._service_keys_to_reverse_lookup[ service_key ]
if tag in siblings:
best_tag = siblings[ tag ]
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
elif tag in reverse_lookup:
best_tag = tag
else:
return [ tag ]
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
all_siblings = list( reverse_lookup[ best_tag ] )
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
all_siblings.append( best_tag )
2015-08-05 18:42:35 +00:00
return all_siblings
def RefreshSiblings( self ):
with self._lock:
2016-09-14 18:03:59 +00:00
self._RefreshSiblings()
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
def CollapsePredicates( self, service_key, predicates ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
2015-08-05 18:42:35 +00:00
results = [ predicate for predicate in predicates if predicate.GetType() != HC.PREDICATE_TYPE_TAG ]
tag_predicates = [ predicate for predicate in predicates if predicate.GetType() == HC.PREDICATE_TYPE_TAG ]
tags_to_predicates = { predicate.GetValue() : predicate for predicate in predicates if predicate.GetType() == HC.PREDICATE_TYPE_TAG }
tags = tags_to_predicates.keys()
tags_to_include_in_results = set()
for tag in tags:
2016-09-14 18:03:59 +00:00
if tag in siblings:
2015-08-05 18:42:35 +00:00
old_tag = tag
old_predicate = tags_to_predicates[ old_tag ]
2016-09-14 18:03:59 +00:00
new_tag = siblings[ old_tag ]
2015-08-05 18:42:35 +00:00
if new_tag not in tags_to_predicates:
( old_pred_type, old_value, old_inclusive ) = old_predicate.GetInfo()
2016-06-22 20:59:24 +00:00
new_predicate = ClientSearch.Predicate( old_pred_type, new_tag, old_inclusive )
2015-08-05 18:42:35 +00:00
tags_to_predicates[ new_tag ] = new_predicate
tags_to_include_in_results.add( new_tag )
new_predicate = tags_to_predicates[ new_tag ]
2016-08-17 20:07:22 +00:00
new_predicate.AddCounts( old_predicate )
2015-08-05 18:42:35 +00:00
2015-12-02 22:32:18 +00:00
else:
tags_to_include_in_results.add( tag )
2015-08-05 18:42:35 +00:00
results.extend( [ tags_to_predicates[ tag ] for tag in tags_to_include_in_results ] )
return results
2016-09-14 18:03:59 +00:00
def CollapsePairs( self, service_key, pairs ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
2015-08-05 18:42:35 +00:00
result = set()
for ( a, b ) in pairs:
2016-09-14 18:03:59 +00:00
if a in siblings:
a = siblings[ a ]
if b in siblings:
b = siblings[ b ]
2015-08-05 18:42:35 +00:00
result.add( ( a, b ) )
return result
2016-09-14 18:03:59 +00:00
def CollapseStatusesToTags( self, service_key, statuses_to_tags ):
2015-11-11 21:20:41 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-11-11 21:20:41 +00:00
with self._lock:
statuses = statuses_to_tags.keys()
2016-06-22 20:59:24 +00:00
new_statuses_to_tags = HydrusData.default_dict_set()
2015-11-11 21:20:41 +00:00
for status in statuses:
2016-09-14 18:03:59 +00:00
new_statuses_to_tags[ status ] = self._CollapseTags( service_key, statuses_to_tags[ status ] )
2015-11-11 21:20:41 +00:00
2016-06-22 20:59:24 +00:00
return new_statuses_to_tags
2015-11-11 21:20:41 +00:00
2016-09-14 18:03:59 +00:00
def CollapseTag( self, service_key, tag ):
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2016-09-14 18:03:59 +00:00
with self._lock:
siblings = self._service_keys_to_siblings[ service_key ]
if tag in siblings:
return siblings[ tag ]
else:
return tag
def CollapseTags( self, service_key, tags ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-11-11 21:20:41 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
return self._CollapseTags( service_key, tags )
2015-11-11 21:20:41 +00:00
2015-08-05 18:42:35 +00:00
2016-09-14 18:03:59 +00:00
def CollapseTagsToCount( self, service_key, tags_to_count ):
2015-08-05 18:42:35 +00:00
2017-12-06 22:06:56 +00:00
if self._controller.new_options.GetBoolean( 'apply_all_siblings_to_all_services' ):
2017-04-05 21:16:40 +00:00
service_key = CC.COMBINED_TAG_SERVICE_KEY
2015-08-05 18:42:35 +00:00
with self._lock:
2016-09-14 18:03:59 +00:00
siblings = self._service_keys_to_siblings[ service_key ]
2015-08-05 18:42:35 +00:00
results = collections.Counter()
for ( tag, count ) in tags_to_count.items():
2016-09-14 18:03:59 +00:00
if tag in siblings:
tag = siblings[ tag ]
2015-08-05 18:42:35 +00:00
results[ tag ] += count
return results
2015-10-07 21:56:22 +00:00
2015-11-25 22:00:57 +00:00
class UndoManager( object ):
def __init__( self, controller ):
self._controller = controller
self._commands = []
self._inverted_commands = []
self._current_index = 0
self._lock = threading.Lock()
self._controller.sub( self, 'Undo', 'undo' )
self._controller.sub( self, 'Redo', 'redo' )
def _FilterServiceKeysToContentUpdates( self, service_keys_to_content_updates ):
filtered_service_keys_to_content_updates = {}
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
filtered_content_updates = []
for content_update in content_updates:
( data_type, action, row ) = content_update.ToTuple()
if data_type == HC.CONTENT_TYPE_FILES:
2016-12-21 22:30:54 +00:00
if action in ( HC.CONTENT_UPDATE_ADD, HC.CONTENT_UPDATE_DELETE, HC.CONTENT_UPDATE_UNDELETE, HC.CONTENT_UPDATE_RESCIND_PETITION, HC.CONTENT_UPDATE_ADVANCED ):
continue
2015-11-25 22:00:57 +00:00
elif data_type == HC.CONTENT_TYPE_MAPPINGS:
2016-12-21 22:30:54 +00:00
if action in ( HC.CONTENT_UPDATE_RESCIND_PETITION, HC.CONTENT_UPDATE_ADVANCED ):
continue
else:
continue
2015-11-25 22:00:57 +00:00
filtered_content_update = HydrusData.ContentUpdate( data_type, action, row )
filtered_content_updates.append( filtered_content_update )
if len( filtered_content_updates ) > 0:
filtered_service_keys_to_content_updates[ service_key ] = filtered_content_updates
return filtered_service_keys_to_content_updates
def _InvertServiceKeysToContentUpdates( self, service_keys_to_content_updates ):
inverted_service_keys_to_content_updates = {}
for ( service_key, content_updates ) in service_keys_to_content_updates.items():
inverted_content_updates = []
for content_update in content_updates:
( data_type, action, row ) = content_update.ToTuple()
inverted_row = row
if data_type == HC.CONTENT_TYPE_FILES:
if action == HC.CONTENT_UPDATE_ARCHIVE: inverted_action = HC.CONTENT_UPDATE_INBOX
elif action == HC.CONTENT_UPDATE_INBOX: inverted_action = HC.CONTENT_UPDATE_ARCHIVE
elif action == HC.CONTENT_UPDATE_PEND: inverted_action = HC.CONTENT_UPDATE_RESCIND_PEND
elif action == HC.CONTENT_UPDATE_RESCIND_PEND: inverted_action = HC.CONTENT_UPDATE_PEND
elif action == HC.CONTENT_UPDATE_PETITION:
inverted_action = HC.CONTENT_UPDATE_RESCIND_PETITION
( hashes, reason ) = row
inverted_row = hashes
elif data_type == HC.CONTENT_TYPE_MAPPINGS:
if action == HC.CONTENT_UPDATE_ADD: inverted_action = HC.CONTENT_UPDATE_DELETE
elif action == HC.CONTENT_UPDATE_DELETE: inverted_action = HC.CONTENT_UPDATE_ADD
elif action == HC.CONTENT_UPDATE_PEND: inverted_action = HC.CONTENT_UPDATE_RESCIND_PEND
elif action == HC.CONTENT_UPDATE_RESCIND_PEND: inverted_action = HC.CONTENT_UPDATE_PEND
elif action == HC.CONTENT_UPDATE_PETITION:
inverted_action = HC.CONTENT_UPDATE_RESCIND_PETITION
( tag, hashes, reason ) = row
inverted_row = ( tag, hashes )
inverted_content_update = HydrusData.ContentUpdate( data_type, inverted_action, inverted_row )
inverted_content_updates.append( inverted_content_update )
inverted_service_keys_to_content_updates[ service_key ] = inverted_content_updates
return inverted_service_keys_to_content_updates
def AddCommand( self, action, *args, **kwargs ):
with self._lock:
inverted_action = action
inverted_args = args
inverted_kwargs = kwargs
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
service_keys_to_content_updates = self._FilterServiceKeysToContentUpdates( service_keys_to_content_updates )
if len( service_keys_to_content_updates ) == 0: return
inverted_service_keys_to_content_updates = self._InvertServiceKeysToContentUpdates( service_keys_to_content_updates )
if len( inverted_service_keys_to_content_updates ) == 0: return
inverted_args = ( inverted_service_keys_to_content_updates, )
else: return
self._commands = self._commands[ : self._current_index ]
self._inverted_commands = self._inverted_commands[ : self._current_index ]
self._commands.append( ( action, args, kwargs ) )
self._inverted_commands.append( ( inverted_action, inverted_args, inverted_kwargs ) )
self._current_index += 1
self._controller.pub( 'notify_new_undo' )
def GetUndoRedoStrings( self ):
with self._lock:
( undo_string, redo_string ) = ( None, None )
if self._current_index > 0:
undo_index = self._current_index - 1
( action, args, kwargs ) = self._commands[ undo_index ]
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
undo_string = 'undo ' + ClientData.ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates )
if len( self._commands ) > 0 and self._current_index < len( self._commands ):
redo_index = self._current_index
( action, args, kwargs ) = self._commands[ redo_index ]
if action == 'content_updates':
( service_keys_to_content_updates, ) = args
redo_string = 'redo ' + ClientData.ConvertServiceKeysToContentUpdatesToPrettyString( service_keys_to_content_updates )
return ( undo_string, redo_string )
def Undo( self ):
action = None
with self._lock:
if self._current_index > 0:
self._current_index -= 1
( action, args, kwargs ) = self._inverted_commands[ self._current_index ]
if action is not None:
self._controller.WriteSynchronous( action, *args, **kwargs )
self._controller.pub( 'notify_new_undo' )
def Redo( self ):
action = None
with self._lock:
if len( self._commands ) > 0 and self._current_index < len( self._commands ):
( action, args, kwargs ) = self._commands[ self._current_index ]
self._current_index += 1
if action is not None:
self._controller.WriteSynchronous( action, *args, **kwargs )
self._controller.pub( 'notify_new_undo' )