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:
name = object.id
path = name.split('.')[0]
ext = name.split('.')[-1]
path = name.split(".")[0]
ext = name.split(".")[-1]
img = f"{path}/{path}-512.{ext}"
obj = object.to_dict()
@ -199,9 +199,7 @@ def ApiUpload():
size = 512, 512
Image.thumbnail(size, PIL.Image.Resampling.LANCZOS)
Image.save(
os.path.join(app.config["UPLOAD_FOLDER"], f"{file_path}-512.{file_ext}")
)
Image.save(os.path.join(app.config["UPLOAD_FOLDER"], f"{file_path}-512.{file_ext}"))
Image.close()
temp_file = open(
@ -218,7 +216,10 @@ def ApiUpload():
request.files["file"].filename
).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}/{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}/")
return Response(
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()
if document.exists:
name = document.id
path = name.split('.')[0]
ext = name.split('.')[-1]
path = name.split(".")[0]
ext = name.split(".")[-1]
img = f"{path}/{path}-512.{ext}"
obj = document.to_dict()
@ -249,7 +250,7 @@ def Edit(id):
date = datetime.fromtimestamp(float(float(str(obj["date"])[:10]))).strftime(
"%d/%m/%Y"
)
alt=obj["alt"]
alt = obj["alt"]
return render_template(
"edit.html",
name=name,
@ -273,6 +274,30 @@ def ApiDelete(file):
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_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}/")
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', () => {
// tagInp.value = '';
// tagCon.innerHTML = '';
// tags = [];
// urlInp.value = '';
// urlCon.innerHTML = '';
// urls = [];
// datepicker.setDate("today");
// });
const form = document.getElementById('upload-form');
form.addEventListener('keydown', (e) => {
if (e.key === "Enter") {
e.preventDefault(); // Prevent form submission
}
});
form.addEventListener('submit', (e) => {
e.preventDefault();
// const form = document.getElementById('upload-form');
// form.addEventListener('keydown', (e) => {
// if (e.key === "Enter") {
// e.preventDefault(); // Prevent form submission
// }
// });
// form.addEventListener('submit', (e) => {
// e.preventDefault();
const formFields = form.elements;
const formData = new FormData(form);
if (!datepicker.getDate()) {
alert('Please select a date');
return;
}
// const formFields = form.elements;
// const formData = new FormData(form);
// if (!formFields['file'].files.length > 0) {
// alert('Please select a file');
// return;
// }
// if (!datepicker.getDate()) {
// alert('Please select a date');
// return;
// }
let convertedUrls = "";
urls.forEach(url => {
convertedUrls += `{"name":"${url.name}","value":"${url.value}"};`;
});
formData.set('alt', formFields['alt'].value.trim());
formData.append('tags', tags.toString());
formData.append('urls', convertedUrls.toString());
formData.append('date', datepicker.getDatepickerInstance().picker.viewDate);
// let convertedUrls = "";
// urls.forEach(url => {
// convertedUrls += `{"name":"${url.name}","value":"${url.value}"};`;
// });
// formData.set('file', formFields['file'].files[0]);
// 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()) {
if (pair[0] == "urls") {
console.log(`${pair[0]}:`, urls);
} else {
console.log(`${pair[0]}: ${pair[1]}`);
}
}
// for (let pair of formData.entries()) {
// if (pair[0] == "urls") {
// console.log(`${pair[0]}:`, urls);
// } else {
// console.log(`${pair[0]}: ${pair[1]}`);
// }
// }
btnSubmit.setAttribute('disabled', true);
// btnSubmit.setAttribute('disabled', true);
// fetch('{{ url_for("ApiUpload") }}', {
// method: 'POST',
// body: formData
// })
// .then(res => {
// return res.json();
// })
// .then(data => {
// console.log(data);
// btnSubmit.removeAttribute('disabled');
// alert(data.message);
// if (data.status != "error") {
// window.location.href = "{{ url_for('Home') }}";
// }
// })
// .catch(err => {
// console.log(err);
// btnSubmit.removeAttribute('disabled');
// alert(err.message);
// })
// });
fetch('{{ url_for("ApiUpdate", file=name) }}', {
method: 'PUT',
body: formData
})
.then(res => {
return res.json();
})
.then(data => {
console.log(data);
btnSubmit.removeAttribute('disabled');
alert(data.message);
if (data.status != "error") {
window.location.href = "{{ url_for('Home') }}";
}
})
.catch(err => {
console.log(err);
btnSubmit.removeAttribute('disabled');
alert(err.message);
})
});
</script>