Added a media delete mechanism
This commit is contained in:
1 parent
6c44950d23
commit
a58903d58e
7 files changed
+490
-3
No files matched your search
@@ -96,6 +96,35 @@ extensions or URL schemes; no schema changes are required.
|
|||||||
As with uploads, keep this interface on a trusted network until authentication
|
As with uploads, keep this interface on a trusted network until authentication
|
||||||
and broader access controls are implemented.
|
and broader access controls are implemented.
|
||||||
|
|
||||||
|
### Deleting media
|
||||||
|
|
||||||
|
Choose **Delete** beneath an item in `/media`. A separate confirmation page names
|
||||||
|
the item and explains whether its stored file will be deleted or retained.
|
||||||
|
Nothing is deleted by opening that page; use **Cancel** to go back or **Yes,
|
||||||
|
delete media** to confirm. If the record or file changed since the prompt, it
|
||||||
|
must be reviewed and confirmed again. This works without JavaScript.
|
||||||
|
|
||||||
|
Confirmed deletion removes the `media` row and its playback options. Local files
|
||||||
|
inside the configured image, video, and legacy upload folders are removed to
|
||||||
|
free storage, including files downloaded from YouTube. A file used by another
|
||||||
|
media row is retained until its last reference is deleted. Streams, missing
|
||||||
|
files, paths outside managed storage, directories, and symbolic links only lose
|
||||||
|
their database record; no remote source, outside file, or directory tree is
|
||||||
|
deleted. YouTube job history remains unchanged.
|
||||||
|
|
||||||
|
Deleting active/default media lets the player choose the next active/default
|
||||||
|
item or black on its next check. An open player process can retain the deleted
|
||||||
|
file's disk space until it releases that file. Cached thumbnails for the item
|
||||||
|
are also removed (including the current legacy-format thumbnail, if present).
|
||||||
|
|
||||||
|
A local file is temporarily renamed in place before the database transaction
|
||||||
|
commits. Database errors restore it rather than destroying it. If final file
|
||||||
|
cleanup fails after commit, the page explicitly reports that storage was not
|
||||||
|
freed; the server log identifies the retained `.deleting-*` file for an
|
||||||
|
administrator to remove. A forced shutdown during deletion can also leave a
|
||||||
|
`.deleting-*` file: check the database before restoring its original filename
|
||||||
|
(if the record remains) or removing it (if the deletion committed).
|
||||||
|
|
||||||
## Submission validation
|
## Submission validation
|
||||||
|
|
||||||
All new image, video, stream, and YouTube submissions require a nonblank media
|
All new image, video, stream, and YouTube submissions require a nonblank media
|
||||||
@@ -262,5 +291,5 @@ WHERE youtube_download_job_id = 123
|
|||||||
Run the database and worker tests without downloading any videos:
|
Run the database and worker tests without downloading any videos:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test test.media_library_test test.submission_validation_test -v
|
python3 -m unittest test.youtube_download_job_test test.youtube_download_web_test test.upload_video_test test.upload_photo_test test.player_test test.media_library_test test.submission_validation_test test.media_deletion_test -v
|
||||||
```
|
```
|
||||||
@@ -29,6 +29,8 @@ an FFplay-based player with unified playback selection; device control is still
|
|||||||
|
|
||||||
- [x] Link the home page to a unified media library with Play buttons, live selection
|
- [x] Link the home page to a unified media library with Play buttons, live selection
|
||||||
indicators, media-type icons, and cached local image/video thumbnails.
|
indicators, media-type icons, and cached local image/video thumbnails.
|
||||||
|
- [x] Delete media with a confirmation step, removing records/playback options and
|
||||||
|
unshared files in managed storage while preserving outside/shared sources.
|
||||||
- [ ] Connect the existing placeholder controls to backend actions.
|
- [ ] Connect the existing placeholder controls to backend actions.
|
||||||
- [x] Add input validation for media names, duplicate names, stream URLs, and
|
- [x] Add input validation for media names, duplicate names, stream URLs, and
|
||||||
uploaded files.
|
uploaded files.
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<title>Delete Media - Sanctuary Commander</title>
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||||
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="container py-3">
|
||||||
|
<h1>Delete Media</h1>
|
||||||
|
{% if error %}
|
||||||
|
<div class="alert alert-danger" role="alert">{{ error }}</div>
|
||||||
|
{% endif %}
|
||||||
|
{% if media is defined %}
|
||||||
|
<p>Are you sure you want to delete <strong class="text-break">{{ media[1] }}</strong>?</p>
|
||||||
|
<div class="alert alert-warning">
|
||||||
|
<p>{{ plan.message }}</p>
|
||||||
|
<p class="mb-0">The media record and its playback options will be permanently removed. This cannot be undone.</p>
|
||||||
|
</div>
|
||||||
|
{% if media[3] == 1 or media[4] == 1 %}
|
||||||
|
<p>This item is active or marked as default. The player will select another active/default item, or a blank screen, on its next check.</p>
|
||||||
|
{% endif %}
|
||||||
|
<form method="POST" action="{{ url_for('media_library.delete_media', media_id=media[0]) }}">
|
||||||
|
<input type="hidden" name="version" value="{{ version }}">
|
||||||
|
<a class="btn btn-secondary" href="{{ url_for('media_library.media_list') }}">Cancel</a>
|
||||||
|
<button class="btn btn-danger" type="submit" name="confirm" value="yes">Yes, delete media</button>
|
||||||
|
</form>
|
||||||
|
{% else %}
|
||||||
|
<a class="btn btn-secondary" href="{{ url_for('media_library.media_list') }}">Return to media library</a>
|
||||||
|
{% endif %}
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -55,6 +55,9 @@
|
|||||||
<span aria-hidden="true">▶</span> Play <span class="visually-hidden">{{ item.media_name }}</span>
|
<span aria-hidden="true">▶</span> Play <span class="visually-hidden">{{ item.media_name }}</span>
|
||||||
</button>
|
</button>
|
||||||
</form>
|
</form>
|
||||||
|
<a class="btn btn-outline-danger w-100 mt-2" href="{{ url_for('media_library.delete_media', media_id=item.media_id) }}">
|
||||||
|
Delete <span class="visually-hidden">{{ item.media_name }}</span>
|
||||||
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -3,10 +3,13 @@ from pathlib import Path
|
|||||||
import subprocess
|
import subprocess
|
||||||
from tempfile import NamedTemporaryFile
|
from tempfile import NamedTemporaryFile
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, send_file, url_for
|
from flask import Blueprint, abort, current_app, jsonify, redirect, render_template, request, send_file, url_for
|
||||||
|
|
||||||
from utilities.tools import get_db
|
from utilities.tools import get_db
|
||||||
|
from utilities.media_deletion import confirmation_version, deletion_plan
|
||||||
|
from utilities.validation import write_transaction
|
||||||
|
|
||||||
|
|
||||||
media_library_bp = Blueprint('media_library', __name__, url_prefix='/media', template_folder='.')
|
media_library_bp = Blueprint('media_library', __name__, url_prefix='/media', template_folder='.')
|
||||||
@@ -102,6 +105,97 @@ def play_media(media_id):
|
|||||||
return redirect(url_for('media_library.media_list'), code=303)
|
return redirect(url_for('media_library.media_list'), code=303)
|
||||||
|
|
||||||
|
|
||||||
|
def deletion_media(db, media_id):
|
||||||
|
rows = db.query('SELECT media_id, media_name, media_uri, media_active, media_default '
|
||||||
|
'FROM media WHERE media_id = ?', [media_id])[1]
|
||||||
|
if not rows:
|
||||||
|
abort(404)
|
||||||
|
return rows[0]
|
||||||
|
|
||||||
|
|
||||||
|
def restore_staged_file(staged, source):
|
||||||
|
try:
|
||||||
|
if staged is not None and staged.exists():
|
||||||
|
if source.exists() or source.is_symlink():
|
||||||
|
raise OSError('Original file location is occupied; recovery file retained')
|
||||||
|
staged.rename(source)
|
||||||
|
except OSError:
|
||||||
|
current_app.logger.exception('Restore media manually from %s to %s', staged, source)
|
||||||
|
|
||||||
|
|
||||||
|
@media_library_bp.route('/<int:media_id>/delete', methods=['GET', 'POST'])
|
||||||
|
def delete_media(media_id):
|
||||||
|
db = get_db()
|
||||||
|
directory = current_app.config['CONFIG_DIRECTORY']
|
||||||
|
config = current_app.config['config']
|
||||||
|
staged = None
|
||||||
|
source = None
|
||||||
|
legacy_thumbnail = None
|
||||||
|
try:
|
||||||
|
if request.method == 'GET':
|
||||||
|
media = deletion_media(db, media_id)
|
||||||
|
plan = deletion_plan(db, media, directory, config)
|
||||||
|
return render_template('media_delete.html', media=media, plan=plan,
|
||||||
|
version=confirmation_version(media, plan))
|
||||||
|
# Reject cross-site browser submissions to this destructive endpoint.
|
||||||
|
origin = request.headers.get('Origin')
|
||||||
|
if (request.headers.get('Sec-Fetch-Site') == 'cross-site'
|
||||||
|
or (origin and origin.rstrip('/') != request.host_url.rstrip('/'))):
|
||||||
|
abort(403)
|
||||||
|
with write_transaction(db):
|
||||||
|
media = deletion_media(db, media_id)
|
||||||
|
plan = deletion_plan(db, media, directory, config)
|
||||||
|
version = confirmation_version(media, plan)
|
||||||
|
if request.form.get('confirm') != 'yes':
|
||||||
|
return render_template('media_delete.html', media=media, plan=plan, version=version,
|
||||||
|
error='Please confirm the deletion using the button below.'), 400
|
||||||
|
if request.form.get('version') != version:
|
||||||
|
return render_template('media_delete.html', media=media, plan=plan, version=version,
|
||||||
|
error='This media or its storage has changed. Please review and confirm again.'), 409
|
||||||
|
preview = local_preview_source(media[2])
|
||||||
|
if preview is not None:
|
||||||
|
stat = preview.stat()
|
||||||
|
legacy_thumbnail = hashlib.sha256(
|
||||||
|
f'{media_id}:{preview}:{stat.st_mtime_ns}:{stat.st_size}'.encode()
|
||||||
|
).hexdigest() + '.png'
|
||||||
|
source = plan['path']
|
||||||
|
if source is not None:
|
||||||
|
# Rename within the same directory so a database failure can be undone.
|
||||||
|
staged = source.with_name(f'.deleting-{uuid4().hex}-{source.name}')
|
||||||
|
source.rename(staged)
|
||||||
|
db.query('DELETE FROM media_playback_option WHERE media_id = ?', [media_id])
|
||||||
|
db.query('DELETE FROM media WHERE media_id = ?', [media_id])
|
||||||
|
except (OSError, RuntimeError):
|
||||||
|
restore_staged_file(staged, source)
|
||||||
|
current_app.logger.exception('Unable to prepare deletion of media %s', media_id)
|
||||||
|
return render_template('media_delete.html', error='Unable to access or remove the stored file. '
|
||||||
|
'The media record was not deleted. Please try again or contact the administrator.'), 500
|
||||||
|
except BaseException:
|
||||||
|
restore_staged_file(staged, source)
|
||||||
|
raise
|
||||||
|
|
||||||
|
# Only destroy the staged file after the database transaction has committed.
|
||||||
|
if staged is not None:
|
||||||
|
try:
|
||||||
|
staged.unlink()
|
||||||
|
except OSError:
|
||||||
|
current_app.logger.exception('Media record %s deleted, but storage cleanup is needed at %s', media_id, staged)
|
||||||
|
return render_template('media_delete.html', error='The database record was deleted, but its file '
|
||||||
|
'could not be removed. Storage has not been freed; contact the administrator '
|
||||||
|
'to clean up the retained file (details are in the server log).'), 500
|
||||||
|
cache = Path(directory) / '.thumbnails'
|
||||||
|
try:
|
||||||
|
if not cache.is_symlink():
|
||||||
|
thumbnails = list(cache.glob(f'{media_id}-*.png'))
|
||||||
|
if legacy_thumbnail:
|
||||||
|
thumbnails.append(cache / legacy_thumbnail)
|
||||||
|
for path in thumbnails:
|
||||||
|
path.unlink(missing_ok=True)
|
||||||
|
except OSError:
|
||||||
|
current_app.logger.warning('Could not clean cached thumbnails for deleted media %s', media_id)
|
||||||
|
return redirect(url_for('media_library.media_list'), code=303)
|
||||||
|
|
||||||
|
|
||||||
@media_library_bp.route('/<int:media_id>/thumbnail')
|
@media_library_bp.route('/<int:media_id>/thumbnail')
|
||||||
def thumbnail(media_id):
|
def thumbnail(media_id):
|
||||||
rows = get_db().query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1]
|
rows = get_db().query('SELECT media_uri FROM media WHERE media_id = ?', [media_id])[1]
|
||||||
@@ -115,7 +209,7 @@ def thumbnail(media_id):
|
|||||||
key = hashlib.sha256(f'{media_id}:{source}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest()
|
key = hashlib.sha256(f'{media_id}:{source}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest()
|
||||||
cache = Path(current_app.config['CONFIG_DIRECTORY']) / '.thumbnails'
|
cache = Path(current_app.config['CONFIG_DIRECTORY']) / '.thumbnails'
|
||||||
cache.mkdir(parents=True, exist_ok=True)
|
cache.mkdir(parents=True, exist_ok=True)
|
||||||
destination = cache / f'{key}.png'
|
destination = cache / f'{media_id}-{key}.png'
|
||||||
if not destination.is_file():
|
if not destination.is_file():
|
||||||
temporary = None
|
temporary = None
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -0,0 +1,260 @@
|
|||||||
|
from contextlib import closing
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import runpy
|
||||||
|
import sqlite3
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from utilities.database.sqlite import SQLite
|
||||||
|
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class MediaDeletionTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.directory = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.directory.cleanup)
|
||||||
|
self.workdir = Path(self.directory.name)
|
||||||
|
self.database = self.workdir / 'test.db'
|
||||||
|
(self.workdir / 'config.json').write_text(json.dumps({
|
||||||
|
'database': {'type': 'SQLite', 'name': str(self.database)},
|
||||||
|
'upload_location': 'uploads'
|
||||||
|
}))
|
||||||
|
subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')],
|
||||||
|
cwd=self.workdir, check=True, capture_output=True)
|
||||||
|
original = Path.cwd()
|
||||||
|
try:
|
||||||
|
os.chdir(self.workdir)
|
||||||
|
self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app']
|
||||||
|
finally:
|
||||||
|
os.chdir(original)
|
||||||
|
self.app.config['TESTING'] = True
|
||||||
|
self.client = self.app.test_client()
|
||||||
|
|
||||||
|
def add_media(self, uri='Images/photo.png', name='Image', active=0, default=0):
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
media_id = db.execute(
|
||||||
|
'INSERT INTO media (media_name, media_uri, media_active, media_default) VALUES (?, ?, ?, ?)',
|
||||||
|
[name, uri, active, default]
|
||||||
|
).lastrowid
|
||||||
|
db.execute('INSERT INTO media_playback_option (media_id, media_playback_option, '
|
||||||
|
'media_playback_option_weight) VALUES (?, ?, ?)', [media_id, '-fs', 1])
|
||||||
|
db.commit()
|
||||||
|
return media_id
|
||||||
|
|
||||||
|
def create_file(self, name='Images/photo.png'):
|
||||||
|
path = self.workdir / name
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(b'stored file')
|
||||||
|
return path
|
||||||
|
|
||||||
|
def exists_in_db(self, media_id):
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
return db.execute('SELECT COUNT(*) FROM media WHERE media_id = ?', [media_id]).fetchone()[0] == 1
|
||||||
|
|
||||||
|
def prompt(self, media_id):
|
||||||
|
response = self.client.get(f'/media/{media_id}/delete')
|
||||||
|
self.assertEqual(response.status_code, 200)
|
||||||
|
version = re.search(rb'name="version" value="([a-f0-9]+)"', response.data).group(1).decode()
|
||||||
|
return response, {'confirm': 'yes', 'version': version}
|
||||||
|
|
||||||
|
def delete(self, media_id):
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
return self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
|
||||||
|
def test_library_links_to_confirmation_and_get_deletes_nothing(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media(name='<Image>')
|
||||||
|
response = self.client.get('/media')
|
||||||
|
self.assertIn(f'/media/{media_id}/delete'.encode(), response.data)
|
||||||
|
response, _ = self.prompt(media_id)
|
||||||
|
self.assertIn(b'<Image>', response.data)
|
||||||
|
self.assertIn(b'Cancel', response.data)
|
||||||
|
self.assertIn(b'Yes, delete media', response.data)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_confirmed_local_deletion_removes_record_options_file_and_thumbnails(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
cache = self.workdir / '.thumbnails'
|
||||||
|
cache.mkdir()
|
||||||
|
preview = cache / f'{media_id}-old-preview.png'
|
||||||
|
preview.write_bytes(b'preview')
|
||||||
|
stat = path.stat()
|
||||||
|
legacy = cache / (hashlib.sha256(
|
||||||
|
f'{media_id}:{path}:{stat.st_mtime_ns}:{stat.st_size}'.encode()).hexdigest() + '.png')
|
||||||
|
legacy.write_bytes(b'legacy preview')
|
||||||
|
unrelated = cache / '999-preview.png'
|
||||||
|
unrelated.write_bytes(b'unrelated')
|
||||||
|
response = self.delete(media_id)
|
||||||
|
self.assertEqual(response.status_code, 303)
|
||||||
|
self.assertTrue(response.location.endswith('/media'))
|
||||||
|
self.assertFalse(path.exists())
|
||||||
|
self.assertFalse(self.exists_in_db(media_id))
|
||||||
|
self.assertFalse(preview.exists())
|
||||||
|
self.assertFalse(legacy.exists())
|
||||||
|
self.assertTrue(unrelated.exists())
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
self.assertEqual(db.execute('SELECT COUNT(*) FROM media_playback_option').fetchone(), (0,))
|
||||||
|
self.assertEqual(list(path.parent.glob('.deleting-*')), [])
|
||||||
|
|
||||||
|
def test_video_legacy_and_custom_storage_files_are_deleted(self):
|
||||||
|
for filename in ('Videos/job-1.mp4', 'uploads/Old image/old.jpg', 'CustomImages/new.png'):
|
||||||
|
with self.subTest(filename=filename):
|
||||||
|
self.app.config['config']['image_upload_location'] = 'CustomImages'
|
||||||
|
path = self.create_file(filename)
|
||||||
|
media_id = self.add_media(str(path))
|
||||||
|
self.assertEqual(self.delete(media_id).status_code, 303)
|
||||||
|
self.assertFalse(path.exists())
|
||||||
|
|
||||||
|
def test_stream_and_missing_files_only_remove_records(self):
|
||||||
|
for uri in ('https://example.com/live', 'rtsp://example.com/live', 'Images/missing.png', None):
|
||||||
|
with self.subTest(uri=uri):
|
||||||
|
media_id = self.add_media(uri)
|
||||||
|
self.assertEqual(self.delete(media_id).status_code, 303)
|
||||||
|
self.assertFalse(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_shared_file_is_retained_until_last_reference_deleted(self):
|
||||||
|
path = self.create_file()
|
||||||
|
first = self.add_media('Images/photo.png')
|
||||||
|
second = self.add_media(path.as_uri())
|
||||||
|
response, _ = self.prompt(first)
|
||||||
|
self.assertIn(b'Another media item uses this file', response.data)
|
||||||
|
self.assertEqual(self.delete(first).status_code, 303)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(second))
|
||||||
|
self.assertEqual(self.delete(second).status_code, 303)
|
||||||
|
self.assertFalse(path.exists())
|
||||||
|
|
||||||
|
def test_outside_paths_and_symlinks_are_not_deleted(self):
|
||||||
|
outside = self.create_file('private/image.png')
|
||||||
|
managed = self.create_file('Images/real.png')
|
||||||
|
(self.workdir / 'Images/link-out.png').symlink_to(outside)
|
||||||
|
(self.workdir / 'Images/link-in.png').symlink_to(managed)
|
||||||
|
for uri in (str(outside), 'Images/link-out.png', 'Images/link-in.png'):
|
||||||
|
media_id = self.add_media(uri)
|
||||||
|
self.assertEqual(self.delete(media_id).status_code, 303)
|
||||||
|
self.assertTrue(outside.exists())
|
||||||
|
self.assertTrue(managed.exists())
|
||||||
|
self.assertTrue((self.workdir / 'Images/link-in.png').is_symlink())
|
||||||
|
self.assertTrue((self.workdir / 'Images/link-out.png').is_symlink())
|
||||||
|
|
||||||
|
def test_directories_are_never_recursively_deleted(self):
|
||||||
|
path = self.create_file('Images/folder/image.png')
|
||||||
|
media_id = self.add_media('Images/folder')
|
||||||
|
self.assertEqual(self.delete(media_id).status_code, 303)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
|
||||||
|
def test_confirmation_is_required_and_stale_prompt_must_be_reviewed(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
self.assertEqual(self.client.post(f'/media/{media_id}/delete').status_code, 400)
|
||||||
|
self.assertEqual(self.client.post(f'/media/{media_id}/delete', data={'confirm': 'yes'}).status_code, 409)
|
||||||
|
path.write_bytes(b'changed file')
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
self.assertEqual(response.status_code, 409)
|
||||||
|
self.assertIn(b'review and confirm again', response.data)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_cross_site_confirmation_is_rejected(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data,
|
||||||
|
headers={'Origin': 'https://unrelated.example'})
|
||||||
|
self.assertEqual(response.status_code, 403)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_database_delete_failure_restores_file_and_options(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
db.execute("""CREATE TRIGGER reject_delete BEFORE DELETE ON media
|
||||||
|
BEGIN SELECT RAISE(ABORT, 'Test failure'); END""")
|
||||||
|
db.commit()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
self.assertEqual(response.status_code, 503)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
self.assertEqual(list(path.parent.glob('.deleting-*')), [])
|
||||||
|
with closing(sqlite3.connect(self.database)) as db:
|
||||||
|
self.assertEqual(db.execute('SELECT COUNT(*) FROM media_playback_option').fetchone(), (1,))
|
||||||
|
|
||||||
|
def test_commit_failure_also_restores_file(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
original_query = SQLite.query
|
||||||
|
def failing_commit(db, query, parameters=None):
|
||||||
|
if query == 'COMMIT':
|
||||||
|
raise sqlite3.OperationalError('Commit failed')
|
||||||
|
return original_query(db, query, parameters)
|
||||||
|
with patch.object(SQLite, 'query', failing_commit):
|
||||||
|
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
self.assertEqual(response.status_code, 503)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_storage_rename_failure_leaves_record_unchanged(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
with patch.object(Path, 'rename', side_effect=PermissionError('Permission denied')):
|
||||||
|
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertIn(b'record was not deleted', response.data)
|
||||||
|
self.assertTrue(path.exists())
|
||||||
|
self.assertTrue(self.exists_in_db(media_id))
|
||||||
|
|
||||||
|
def test_final_cleanup_failure_reports_retained_storage(self):
|
||||||
|
path = self.create_file()
|
||||||
|
media_id = self.add_media()
|
||||||
|
_, data = self.prompt(media_id)
|
||||||
|
original_unlink = Path.unlink
|
||||||
|
def failing_cleanup(file, *args, **kwargs):
|
||||||
|
if file.name.startswith('.deleting-'):
|
||||||
|
raise PermissionError('Permission denied')
|
||||||
|
return original_unlink(file, *args, **kwargs)
|
||||||
|
with patch.object(Path, 'unlink', failing_cleanup):
|
||||||
|
with self.assertLogs(self.app.logger, level='ERROR'):
|
||||||
|
response = self.client.post(f'/media/{media_id}/delete', data=data)
|
||||||
|
self.assertEqual(response.status_code, 500)
|
||||||
|
self.assertIn(b'Storage has not been freed', response.data)
|
||||||
|
self.assertFalse(self.exists_in_db(media_id))
|
||||||
|
retained = list(path.parent.glob('.deleting-*'))
|
||||||
|
self.assertEqual(len(retained), 1)
|
||||||
|
self.assertEqual(retained[0].read_bytes(), b'stored file')
|
||||||
|
|
||||||
|
def test_deleting_active_media_updates_default_or_blank_selection(self):
|
||||||
|
first = self.add_media('https://example.com/first', active=1)
|
||||||
|
second = self.add_media('https://example.com/default', default=1)
|
||||||
|
response, _ = self.prompt(first)
|
||||||
|
self.assertIn(b'active or marked as default', response.data)
|
||||||
|
self.assertEqual(self.delete(first).status_code, 303)
|
||||||
|
self.assertEqual(self.client.get('/media/status').json['selected_id'], second)
|
||||||
|
self.assertEqual(self.delete(second).status_code, 303)
|
||||||
|
self.assertTrue(self.client.get('/media/status').json['blank'])
|
||||||
|
|
||||||
|
def test_missing_media_returns_not_found(self):
|
||||||
|
self.assertEqual(self.client.get('/media/999/delete').status_code, 404)
|
||||||
|
self.assertEqual(self.client.post('/media/999/delete', data={'confirm': 'yes'}).status_code, 404)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
"""Plan local-file removal conservatively; never recursively delete a directory."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import unquote, urlsplit
|
||||||
|
|
||||||
|
|
||||||
|
def local_media_path(uri, directory):
|
||||||
|
if not uri or not uri.strip() or '\x00' in uri:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
parsed = urlsplit(uri)
|
||||||
|
except ValueError:
|
||||||
|
return None # An invalid legacy URI must never be treated as a deletion path.
|
||||||
|
if parsed.scheme == 'file':
|
||||||
|
if parsed.netloc.lower() not in ('', 'localhost') or parsed.query or parsed.fragment:
|
||||||
|
return None
|
||||||
|
uri = unquote(parsed.path)
|
||||||
|
elif parsed.scheme:
|
||||||
|
return None
|
||||||
|
if '\x00' in uri:
|
||||||
|
return None
|
||||||
|
return Path(directory) / uri
|
||||||
|
|
||||||
|
|
||||||
|
def deletion_plan(db, media, directory, config):
|
||||||
|
"""media is (id, name, uri, active, default). Return a message and optional file."""
|
||||||
|
plan = {'path': None, 'reason': 'remote', 'identity': None}
|
||||||
|
source = local_media_path(media[2], directory)
|
||||||
|
if source is None:
|
||||||
|
plan['message'] = 'Only the database record will be removed. No stored file is associated with this source.'
|
||||||
|
return plan
|
||||||
|
resolved = source.resolve()
|
||||||
|
roots = [(Path(directory) / config.get(key, default)).resolve() for key, default in (
|
||||||
|
('image_upload_location', 'Images'), ('youtube_download_location', 'Videos'),
|
||||||
|
('upload_location', 'uploads')
|
||||||
|
)]
|
||||||
|
if not any(resolved.is_relative_to(root) and resolved != root for root in roots):
|
||||||
|
plan.update(reason='outside', message='This file is outside managed media storage. Its database record will be removed, but the file will be kept.')
|
||||||
|
return plan
|
||||||
|
if source.is_symlink():
|
||||||
|
plan.update(reason='symlink', message='This source is a symbolic link. Its database record will be removed, but the link and target file will be kept.')
|
||||||
|
return plan
|
||||||
|
if not resolved.exists():
|
||||||
|
plan.update(reason='missing', message='The stored file is already missing. Its database record will be removed.')
|
||||||
|
return plan
|
||||||
|
if not resolved.is_file():
|
||||||
|
plan.update(reason='directory', message='This source is not a regular file. Its database record will be removed, but the source will be kept.')
|
||||||
|
return plan
|
||||||
|
for other_id, other_uri in db.query('SELECT media_id, media_uri FROM media WHERE media_id != ?', [media[0]])[1]:
|
||||||
|
other = local_media_path(other_uri, directory)
|
||||||
|
if other is not None and other.resolve() == resolved:
|
||||||
|
plan.update(reason='shared', message='Another media item uses this file. Only this database record will be removed; the shared file will be kept.')
|
||||||
|
return plan
|
||||||
|
stat = resolved.stat()
|
||||||
|
plan.update(path=resolved, reason='managed',
|
||||||
|
identity=(stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns),
|
||||||
|
message='The stored file will be permanently deleted from the server to free its storage.')
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
|
def confirmation_version(media, plan):
|
||||||
|
value = [list(media), plan['reason'], str(plan['path']), plan['identity']]
|
||||||
|
return hashlib.sha256(json.dumps(value).encode()).hexdigest()
|
||||||
Reference in new issue
Block a user