feat/admin: add data editing

This commit is contained in:
Kentai Radiquum 2025-02-18 22:40:15 +05:00
parent 92114d9741
commit 56c246a2e7
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
2 changed files with 86 additions and 76 deletions

View file

@ -56,8 +56,8 @@ def Home():
for object in db_objects: for object in db_objects:
name = object.id name = object.id
path = name.split('.')[0] path = name.split(".")[0]
ext = name.split('.')[-1] ext = name.split(".")[-1]
img = f"{path}/{path}-512.{ext}" img = f"{path}/{path}-512.{ext}"
obj = object.to_dict() obj = object.to_dict()
@ -199,9 +199,7 @@ def ApiUpload():
size = 512, 512 size = 512, 512
Image.thumbnail(size, PIL.Image.Resampling.LANCZOS) Image.thumbnail(size, PIL.Image.Resampling.LANCZOS)
Image.save( Image.save(os.path.join(app.config["UPLOAD_FOLDER"], f"{file_path}-512.{file_ext}"))
os.path.join(app.config["UPLOAD_FOLDER"], f"{file_path}-512.{file_ext}")
)
Image.close() Image.close()
temp_file = open( temp_file = open(
@ -218,7 +216,10 @@ def ApiUpload():
request.files["file"].filename request.files["file"].filename
).delete() ).delete()
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_path}/{filename}") s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_path}/{filename}")
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_path}/{file_path}-512.{file_ext}") s3.delete_object(
Bucket=os.getenv("AWS_BUCKET"),
Key=f"{file_path}/{file_path}-512.{file_ext}",
)
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_path}/") s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_path}/")
return Response( return Response(
json.dumps({"status": "error", "message": f"S3 ERR: {s3BlurFileResponse}"}), json.dumps({"status": "error", "message": f"S3 ERR: {s3BlurFileResponse}"}),
@ -237,8 +238,8 @@ def Edit(id):
document = db.collection(os.getenv("PREFIX")).document(id).get() document = db.collection(os.getenv("PREFIX")).document(id).get()
if document.exists: if document.exists:
name = document.id name = document.id
path = name.split('.')[0] path = name.split(".")[0]
ext = name.split('.')[-1] ext = name.split(".")[-1]
img = f"{path}/{path}-512.{ext}" img = f"{path}/{path}-512.{ext}"
obj = document.to_dict() obj = document.to_dict()
@ -249,7 +250,7 @@ def Edit(id):
date = datetime.fromtimestamp(float(float(str(obj["date"])[:10]))).strftime( date = datetime.fromtimestamp(float(float(str(obj["date"])[:10]))).strftime(
"%d/%m/%Y" "%d/%m/%Y"
) )
alt=obj["alt"] alt = obj["alt"]
return render_template( return render_template(
"edit.html", "edit.html",
name=name, name=name,
@ -273,6 +274,30 @@ def ApiDelete(file):
db.collection(os.getenv("PREFIX")).document(file).delete() db.collection(os.getenv("PREFIX")).document(file).delete()
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/{file}") s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/{file}")
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/{file_name}-512.{file_ext}") s3.delete_object(
Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/{file_name}-512.{file_ext}"
)
s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/") s3.delete_object(Bucket=os.getenv("AWS_BUCKET"), Key=f"{file_name}/")
return Response(json.dumps({"status": "ok", "message": f"deleted {file}"}), 200) return Response(json.dumps({"status": "ok", "message": f"deleted {file}"}), 200)
@app.route("/api/edit/<string:file>", methods=["PUT"])
def ApiUpdate(file):
tags = request.form.get("tags").split(",") or []
if not tags or tags == "" or tags[0] == "":
tags = []
urls = []
for url in request.form.get("urls").split(";"):
if url == "":
continue
urls.append(json.loads(url))
db.collection(os.getenv("PREFIX")).document(file).update(
{
"alt": request.form.get("alt"),
"date": int(request.form.get("date")),
"tags": tags,
"urls": urls,
}
)
return Response(json.dumps({"status": "ok", "message": f"updated {file}"}), 200)

View file

@ -188,77 +188,62 @@
}); });
// btnReset.addEventListener('click', () => { const form = document.getElementById('upload-form');
// tagInp.value = ''; form.addEventListener('keydown', (e) => {
// tagCon.innerHTML = ''; if (e.key === "Enter") {
// tags = []; e.preventDefault(); // Prevent form submission
// urlInp.value = ''; }
// urlCon.innerHTML = ''; });
// urls = []; form.addEventListener('submit', (e) => {
// datepicker.setDate("today"); e.preventDefault();
// });
// const form = document.getElementById('upload-form'); const formFields = form.elements;
// form.addEventListener('keydown', (e) => { const formData = new FormData(form);
// if (e.key === "Enter") { if (!datepicker.getDate()) {
// e.preventDefault(); // Prevent form submission alert('Please select a date');
// } return;
// }); }
// form.addEventListener('submit', (e) => {
// e.preventDefault();
// const formFields = form.elements; let convertedUrls = "";
// const formData = new FormData(form); urls.forEach(url => {
// if (!formFields['file'].files.length > 0) { convertedUrls += `{"name":"${url.name}","value":"${url.value}"};`;
// alert('Please select a file'); });
// return; formData.set('alt', formFields['alt'].value.trim());
// } formData.append('tags', tags.toString());
// if (!datepicker.getDate()) { formData.append('urls', convertedUrls.toString());
// alert('Please select a date'); formData.append('date', datepicker.getDatepickerInstance().picker.viewDate);
// return;
// }
// let convertedUrls = ""; for (let pair of formData.entries()) {
// urls.forEach(url => { if (pair[0] == "urls") {
// convertedUrls += `{"name":"${url.name}","value":"${url.value}"};`; console.log(`${pair[0]}:`, urls);
// }); } else {
// formData.set('file', formFields['file'].files[0]); console.log(`${pair[0]}: ${pair[1]}`);
// formData.set('alt', formFields['alt'].value.trim()); }
// formData.append('tags', tags.toString()); }
// formData.append('urls', convertedUrls.toString());
// formData.append('date', datepicker.getDatepickerInstance().picker.viewDate);
// for (let pair of formData.entries()) { btnSubmit.setAttribute('disabled', true);
// if (pair[0] == "urls") {
// console.log(`${pair[0]}:`, urls);
// } else {
// console.log(`${pair[0]}: ${pair[1]}`);
// }
// }
// btnSubmit.setAttribute('disabled', true); fetch('{{ url_for("ApiUpdate", file=name) }}', {
method: 'PUT',
// fetch('{{ url_for("ApiUpload") }}', { body: formData
// method: 'POST', })
// body: formData .then(res => {
// }) return res.json();
// .then(res => { })
// return res.json(); .then(data => {
// }) console.log(data);
// .then(data => { btnSubmit.removeAttribute('disabled');
// console.log(data); alert(data.message);
// btnSubmit.removeAttribute('disabled'); if (data.status != "error") {
// alert(data.message); window.location.href = "{{ url_for('Home') }}";
// if (data.status != "error") { }
// window.location.href = "{{ url_for('Home') }}"; })
// } .catch(err => {
// }) console.log(err);
// .catch(err => { btnSubmit.removeAttribute('disabled');
// console.log(err); alert(err.message);
// btnSubmit.removeAttribute('disabled'); })
// alert(err.message); });
// })
// });
</script> </script>