1
0
mirror of https://github.com/janeczku/calibre-web synced 2024-12-18 14:10:30 +00:00

Clean expired sessions (also old sessions without expiry date)

This commit is contained in:
Ozzie Isaacs 2024-07-17 19:59:15 +02:00
parent 1d3a768dfe
commit 2d80187faa
2 changed files with 25 additions and 8 deletions

View File

@ -21,7 +21,7 @@ import datetime
from . import config, constants from . import config, constants
from .services.background_scheduler import BackgroundScheduler, CronTrigger, use_APScheduler from .services.background_scheduler import BackgroundScheduler, CronTrigger, use_APScheduler
from .tasks.database import TaskReconnectDatabase from .tasks.database import TaskReconnectDatabase
from .tasks.tempFolder import TaskDeleteTempFolder from .tasks.clean import TaskClean
from .tasks.thumbnail import TaskGenerateCoverThumbnails, TaskGenerateSeriesThumbnails, TaskClearCoverThumbnailCache from .tasks.thumbnail import TaskGenerateCoverThumbnails, TaskGenerateSeriesThumbnails, TaskClearCoverThumbnailCache
from .services.worker import WorkerThread from .services.worker import WorkerThread
from .tasks.metadata_backup import TaskBackupMetadata from .tasks.metadata_backup import TaskBackupMetadata
@ -33,7 +33,7 @@ def get_scheduled_tasks(reconnect=True):
tasks.append([lambda: TaskReconnectDatabase(), 'reconnect', False]) tasks.append([lambda: TaskReconnectDatabase(), 'reconnect', False])
# Delete temp folder # Delete temp folder
tasks.append([lambda: TaskDeleteTempFolder(), 'delete temp', True]) tasks.append([lambda: TaskClean(), 'delete temp', True])
# Generate metadata.opf file for each changed book # Generate metadata.opf file for each changed book
if config.schedule_metadata_backup: if config.schedule_metadata_backup:
@ -94,7 +94,7 @@ def register_startup_tasks():
if constants.APP_MODE in ['development', 'test'] and not should_task_be_running(start, duration): if constants.APP_MODE in ['development', 'test'] and not should_task_be_running(start, duration):
scheduler.schedule_tasks_immediately(tasks=get_scheduled_tasks(False)) scheduler.schedule_tasks_immediately(tasks=get_scheduled_tasks(False))
else: else:
scheduler.schedule_tasks_immediately(tasks=[[lambda: TaskDeleteTempFolder(), 'delete temp', True]]) scheduler.schedule_tasks_immediately(tasks=[[lambda: TaskClean(), 'delete temp', True]])
def should_task_be_running(start, duration): def should_task_be_running(start, duration):

View File

@ -16,31 +16,48 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
from urllib.request import urlopen import datetime
from flask_babel import lazy_gettext as N_ from flask_babel import lazy_gettext as N_
from sqlalchemy.sql.expression import or_
from cps import logger, file_helper from cps import logger, file_helper, ub
from cps.services.worker import CalibreTask from cps.services.worker import CalibreTask
class TaskDeleteTempFolder(CalibreTask): class TaskClean(CalibreTask):
def __init__(self, task_message=N_('Delete temp folder contents')): def __init__(self, task_message=N_('Delete temp folder contents')):
super(TaskDeleteTempFolder, self).__init__(task_message) super(TaskClean, self).__init__(task_message)
self.log = logger.create() self.log = logger.create()
self.app_db_session = ub.get_new_session_instance()
def run(self, worker_thread): def run(self, worker_thread):
# delete temp folder
try: try:
file_helper.del_temp_dir() file_helper.del_temp_dir()
except FileNotFoundError: except FileNotFoundError:
pass pass
except (PermissionError, OSError) as e: except (PermissionError, OSError) as e:
self.log.error("Error deleting temp folder: {}".format(e)) self.log.error("Error deleting temp folder: {}".format(e))
# delete expired session keys
self.log.debug("Deleted expired session_keys" )
expiry = int(datetime.datetime.now().timestamp())
try:
self.app_db_session.query(ub.User_Sessions).filter(or_(ub.User_Sessions.expiry < expiry,
ub.User_Sessions.expiry == None)).delete()
self.app_db_session.commit()
except Exception as ex:
self.log.debug('Error deleting expired session keys: ' + str(ex))
self._handleError('Error deleting expired session keys: ' + str(ex))
self.app_db_session.rollback()
return
self._handleSuccess() self._handleSuccess()
self.app_db_session.remove()
@property @property
def name(self): def name(self):
return "Delete Temp Folder" return "Clean up"
@property @property
def is_cancellable(self): def is_cancellable(self):