60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
import os, uuid
|
|
from flask import Blueprint, request, jsonify, send_file, render_template, current_app
|
|
from werkzeug.utils import secure_filename
|
|
|
|
from .logic import unlock_pdf, WrongPasswordError
|
|
|
|
pdf_unlock_bp = Blueprint("pdf_unlock", __name__, url_prefix="/pdf-unlock")
|
|
|
|
|
|
@pdf_unlock_bp.route("/")
|
|
def index():
|
|
return render_template("pdf_unlock/index.html")
|
|
|
|
|
|
@pdf_unlock_bp.route("/api/unlock", methods=["POST"])
|
|
def api_unlock():
|
|
f = request.files.get("pdf_file")
|
|
if not f or not f.filename:
|
|
return jsonify({"error": "No PDF uploaded"}), 400
|
|
if not f.filename.lower().endswith(".pdf"):
|
|
return jsonify({"error": "Please upload a .pdf file"}), 400
|
|
|
|
password = request.form.get("password") or None
|
|
|
|
in_path = os.path.join(
|
|
current_app.config["UPLOAD_FOLDER"],
|
|
f"{uuid.uuid4()}_{secure_filename(f.filename)}",
|
|
)
|
|
f.save(in_path)
|
|
|
|
base_name = secure_filename(f.filename)
|
|
out_name = f"{uuid.uuid4()}_unlocked_{base_name}"
|
|
out_path = os.path.join(current_app.config["OUTPUT_FOLDER"], out_name)
|
|
|
|
try:
|
|
was_protected = unlock_pdf(in_path, out_path, password=password)
|
|
except WrongPasswordError as e:
|
|
return jsonify({"error": str(e)}), 400
|
|
except Exception as e:
|
|
return jsonify({"error": f"Could not process this PDF: {e}"}), 400
|
|
finally:
|
|
os.remove(in_path)
|
|
|
|
return jsonify({
|
|
"status": "ok",
|
|
"filename": out_name,
|
|
"download_name": f"unlocked_{base_name}",
|
|
"was_protected": was_protected,
|
|
}), 200
|
|
|
|
|
|
@pdf_unlock_bp.route("/api/download/<filename>")
|
|
def api_download(filename):
|
|
safe = secure_filename(filename)
|
|
fpath = os.path.join(current_app.config["OUTPUT_FOLDER"], safe)
|
|
if not os.path.exists(fpath):
|
|
return jsonify({"error": "File not found"}), 404
|
|
download_name = request.args.get("as") or safe
|
|
return send_file(fpath, as_attachment=True, download_name=secure_filename(download_name))
|