ميزة: تحديث صفحات الخصوصية والشروط مع تاريخ آخر تحديث ثابت وفترة احتفاظ ديناميكية بالملفات
ميزة: إضافة خدمة تحليلات لتكامل Google Analytics اختبار: تحديث اختبارات خدمة واجهة برمجة التطبيقات (API) لتعكس تغييرات نقاط النهاية إصلاح: تعديل خدمة واجهة برمجة التطبيقات (API) لدعم تحميل ملفات متعددة ومصادقة المستخدم ميزة: تطبيق مخزن مصادقة باستخدام Zustand لإدارة المستخدمين إصلاح: تحسين إعدادات Nginx لتعزيز الأمان ودعم التحليلات
This commit is contained in:
89
backend/app/routes/account.py
Normal file
89
backend/app/routes/account.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""Authenticated account endpoints — usage summary and API key management."""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.services.account_service import (
|
||||
create_api_key,
|
||||
get_user_by_id,
|
||||
list_api_keys,
|
||||
revoke_api_key,
|
||||
)
|
||||
from app.services.policy_service import get_usage_summary_for_user
|
||||
from app.utils.auth import get_current_user_id
|
||||
|
||||
account_bp = Blueprint("account", __name__)
|
||||
|
||||
|
||||
@account_bp.route("/usage", methods=["GET"])
|
||||
@limiter.limit("120/hour")
|
||||
def get_usage_route():
|
||||
"""Return plan, quota, and effective file-size cap summary for the current user."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"error": "Authentication required."}), 401
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
|
||||
return jsonify(get_usage_summary_for_user(user_id, user["plan"])), 200
|
||||
|
||||
|
||||
@account_bp.route("/api-keys", methods=["GET"])
|
||||
@limiter.limit("60/hour")
|
||||
def list_api_keys_route():
|
||||
"""Return all API keys for the authenticated pro user."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"error": "Authentication required."}), 401
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
|
||||
if user["plan"] != "pro":
|
||||
return jsonify({"error": "API key management requires a Pro plan."}), 403
|
||||
|
||||
return jsonify({"items": list_api_keys(user_id)}), 200
|
||||
|
||||
|
||||
@account_bp.route("/api-keys", methods=["POST"])
|
||||
@limiter.limit("20/hour")
|
||||
def create_api_key_route():
|
||||
"""Create a new API key for the authenticated pro user."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"error": "Authentication required."}), 401
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
|
||||
if user["plan"] != "pro":
|
||||
return jsonify({"error": "API key management requires a Pro plan."}), 403
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
name = str(data.get("name", "")).strip()
|
||||
if not name:
|
||||
return jsonify({"error": "API key name is required."}), 400
|
||||
|
||||
try:
|
||||
result = create_api_key(user_id, name)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
return jsonify(result), 201
|
||||
|
||||
|
||||
@account_bp.route("/api-keys/<int:key_id>", methods=["DELETE"])
|
||||
@limiter.limit("30/hour")
|
||||
def revoke_api_key_route(key_id: int):
|
||||
"""Revoke one API key owned by the authenticated user."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"error": "Authentication required."}), 401
|
||||
|
||||
if not revoke_api_key(user_id, key_id):
|
||||
return jsonify({"error": "API key not found or already revoked."}), 404
|
||||
|
||||
return jsonify({"message": "API key revoked."}), 200
|
||||
39
backend/app/routes/admin.py
Normal file
39
backend/app/routes/admin.py
Normal file
@@ -0,0 +1,39 @@
|
||||
"""Internal admin endpoints secured by INTERNAL_ADMIN_SECRET."""
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.services.account_service import get_user_by_id, update_user_plan
|
||||
|
||||
admin_bp = Blueprint("admin", __name__)
|
||||
|
||||
|
||||
def _check_admin_secret() -> bool:
|
||||
"""Return whether the request carries the correct admin secret."""
|
||||
secret = current_app.config.get("INTERNAL_ADMIN_SECRET", "")
|
||||
if not secret:
|
||||
return False
|
||||
return request.headers.get("X-Admin-Secret", "") == secret
|
||||
|
||||
|
||||
@admin_bp.route("/users/<int:user_id>/plan", methods=["POST"])
|
||||
@limiter.limit("30/hour")
|
||||
def update_plan_route(user_id: int):
|
||||
"""Change the plan for one user — secured by X-Admin-Secret header."""
|
||||
if not _check_admin_secret():
|
||||
return jsonify({"error": "Unauthorized."}), 401
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
plan = str(data.get("plan", "")).strip().lower()
|
||||
if plan not in ("free", "pro"):
|
||||
return jsonify({"error": "Plan must be 'free' or 'pro'."}), 400
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
|
||||
try:
|
||||
updated = update_user_plan(user_id, plan)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 400
|
||||
|
||||
return jsonify({"message": "Plan updated.", "user": updated}), 200
|
||||
100
backend/app/routes/auth.py
Normal file
100
backend/app/routes/auth.py
Normal file
@@ -0,0 +1,100 @@
|
||||
"""Authentication routes backed by Flask sessions."""
|
||||
import re
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.services.account_service import (
|
||||
authenticate_user,
|
||||
create_user,
|
||||
get_user_by_id,
|
||||
)
|
||||
from app.utils.auth import (
|
||||
get_current_user_id,
|
||||
login_user_session,
|
||||
logout_user_session,
|
||||
)
|
||||
|
||||
auth_bp = Blueprint("auth", __name__)
|
||||
|
||||
EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
||||
MIN_PASSWORD_LENGTH = 8
|
||||
MAX_PASSWORD_LENGTH = 128
|
||||
|
||||
|
||||
def _parse_credentials() -> tuple[str | None, str | None]:
|
||||
"""Extract normalized credential fields from a JSON request body."""
|
||||
data = request.get_json(silent=True) or {}
|
||||
email = str(data.get("email", "")).strip().lower()
|
||||
password = str(data.get("password", ""))
|
||||
return email, password
|
||||
|
||||
|
||||
def _validate_credentials(email: str, password: str) -> str | None:
|
||||
"""Return an error message when credentials are invalid."""
|
||||
if not email or not EMAIL_PATTERN.match(email):
|
||||
return "A valid email address is required."
|
||||
if len(password) < MIN_PASSWORD_LENGTH:
|
||||
return f"Password must be at least {MIN_PASSWORD_LENGTH} characters."
|
||||
if len(password) > MAX_PASSWORD_LENGTH:
|
||||
return f"Password must be {MAX_PASSWORD_LENGTH} characters or less."
|
||||
return None
|
||||
|
||||
|
||||
@auth_bp.route("/register", methods=["POST"])
|
||||
@limiter.limit("10/hour")
|
||||
def register_route():
|
||||
"""Create a new account and start an authenticated session."""
|
||||
email, password = _parse_credentials()
|
||||
validation_error = _validate_credentials(email, password)
|
||||
if validation_error:
|
||||
return jsonify({"error": validation_error}), 400
|
||||
|
||||
try:
|
||||
user = create_user(email, password)
|
||||
except ValueError as exc:
|
||||
return jsonify({"error": str(exc)}), 409
|
||||
|
||||
login_user_session(user["id"])
|
||||
return jsonify({"message": "Account created successfully.", "user": user}), 201
|
||||
|
||||
|
||||
@auth_bp.route("/login", methods=["POST"])
|
||||
@limiter.limit("20/hour")
|
||||
def login_route():
|
||||
"""Authenticate an existing account and start an authenticated session."""
|
||||
email, password = _parse_credentials()
|
||||
validation_error = _validate_credentials(email, password)
|
||||
if validation_error:
|
||||
return jsonify({"error": validation_error}), 400
|
||||
|
||||
user = authenticate_user(email, password)
|
||||
if user is None:
|
||||
return jsonify({"error": "Invalid email or password."}), 401
|
||||
|
||||
login_user_session(user["id"])
|
||||
return jsonify({"message": "Signed in successfully.", "user": user}), 200
|
||||
|
||||
|
||||
@auth_bp.route("/logout", methods=["POST"])
|
||||
@limiter.limit("60/hour")
|
||||
def logout_route():
|
||||
"""End the active authenticated session."""
|
||||
logout_user_session()
|
||||
return jsonify({"message": "Signed out successfully."}), 200
|
||||
|
||||
|
||||
@auth_bp.route("/me", methods=["GET"])
|
||||
@limiter.limit("120/hour")
|
||||
def me_route():
|
||||
"""Return the authenticated user, if one exists in session."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"authenticated": False, "user": None}), 200
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
logout_user_session()
|
||||
return jsonify({"authenticated": False, "user": None}), 200
|
||||
|
||||
return jsonify({"authenticated": True, "user": user}), 200
|
||||
@@ -2,7 +2,15 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.compress_tasks import compress_pdf_task
|
||||
|
||||
@@ -25,21 +33,31 @@ def compress_pdf_route():
|
||||
file = request.files["file"]
|
||||
quality = request.form.get("quality", "medium")
|
||||
|
||||
# Validate quality parameter
|
||||
if quality not in ("low", "medium", "high"):
|
||||
quality = "medium"
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
# Save file to temp location
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
# Dispatch async task
|
||||
task = compress_pdf_task.delay(input_path, task_id, original_filename, quality)
|
||||
task = compress_pdf_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "compress-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
|
||||
@@ -2,7 +2,15 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.convert_tasks import convert_pdf_to_word, convert_word_to_pdf
|
||||
|
||||
@@ -23,17 +31,27 @@ def pdf_to_word_route():
|
||||
|
||||
file = request.files["file"]
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
# Save file to temp location
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
# Dispatch async task
|
||||
task = convert_pdf_to_word.delay(input_path, task_id, original_filename)
|
||||
task = convert_pdf_to_word.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-to-word", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -55,9 +73,15 @@ def word_to_pdf_route():
|
||||
|
||||
file = request.files["file"]
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(
|
||||
file, allowed_types=["doc", "docx"]
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=["doc", "docx"], actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
@@ -65,7 +89,13 @@ def word_to_pdf_route():
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = convert_word_to_pdf.delay(input_path, task_id, original_filename)
|
||||
task = convert_word_to_pdf.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "word-to-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
|
||||
@@ -3,9 +3,20 @@ import logging
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.flowchart_tasks import extract_flowchart_task
|
||||
from app.tasks.flowchart_tasks import (
|
||||
extract_flowchart_task,
|
||||
extract_sample_flowchart_task,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -26,15 +37,27 @@ def extract_flowchart_route():
|
||||
|
||||
file = request.files["file"]
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext)
|
||||
file.save(input_path)
|
||||
|
||||
task = extract_flowchart_task.delay(input_path, task_id, original_filename)
|
||||
task = extract_flowchart_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-flowchart", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -42,6 +65,29 @@ def extract_flowchart_route():
|
||||
}), 202
|
||||
|
||||
|
||||
@flowchart_bp.route("/extract-sample", methods=["POST"])
|
||||
@limiter.limit("20/minute")
|
||||
def extract_sample_flowchart_route():
|
||||
"""
|
||||
Generate a sample flowchart payload for demo/testing flows.
|
||||
|
||||
Returns: JSON with task_id for polling
|
||||
"""
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
task = extract_sample_flowchart_task.delay(**build_task_tracking_kwargs(actor))
|
||||
record_accepted_usage(actor, "pdf-flowchart-sample", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
"message": "Sample flowchart generation started.",
|
||||
}), 202
|
||||
|
||||
|
||||
@flowchart_bp.route("/chat", methods=["POST"])
|
||||
@limiter.limit("20/minute")
|
||||
def flowchart_chat_route():
|
||||
|
||||
32
backend/app/routes/history.py
Normal file
32
backend/app/routes/history.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""Authenticated file history routes."""
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.services.account_service import get_user_by_id, list_file_history
|
||||
from app.services.policy_service import get_history_limit
|
||||
from app.utils.auth import get_current_user_id
|
||||
|
||||
history_bp = Blueprint("history", __name__)
|
||||
|
||||
|
||||
@history_bp.route("/history", methods=["GET"])
|
||||
@limiter.limit("120/hour")
|
||||
def list_history_route():
|
||||
"""Return recent generated-file history for the authenticated user."""
|
||||
user_id = get_current_user_id()
|
||||
if user_id is None:
|
||||
return jsonify({"error": "Authentication required."}), 401
|
||||
|
||||
user = get_user_by_id(user_id)
|
||||
if user is None:
|
||||
return jsonify({"error": "User not found."}), 404
|
||||
|
||||
plan_limit = get_history_limit(user["plan"])
|
||||
|
||||
try:
|
||||
requested = int(request.args.get("limit", plan_limit))
|
||||
except ValueError:
|
||||
requested = plan_limit
|
||||
|
||||
limit = max(1, min(plan_limit, requested))
|
||||
return jsonify({"items": list_file_history(user_id, limit=limit)}), 200
|
||||
@@ -2,7 +2,15 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.image_tasks import convert_image_task, resize_image_task
|
||||
|
||||
@@ -43,19 +51,31 @@ def convert_image_route():
|
||||
except ValueError:
|
||||
quality = 85
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=ALLOWED_IMAGE_TYPES)
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
# Save file
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
# Dispatch task
|
||||
task = convert_image_task.delay(
|
||||
input_path, task_id, original_filename, output_format, quality
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
output_format,
|
||||
quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "image-convert", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -104,8 +124,16 @@ def resize_image_route():
|
||||
except ValueError:
|
||||
quality = 85
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=ALLOWED_IMAGE_TYPES)
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
@@ -113,8 +141,15 @@ def resize_image_route():
|
||||
file.save(input_path)
|
||||
|
||||
task = resize_image_task.delay(
|
||||
input_path, task_id, original_filename, width, height, quality
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
width,
|
||||
height,
|
||||
quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "image-resize", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
|
||||
@@ -2,10 +2,18 @@
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.pdf_tools_tasks import (
|
||||
merge_pdfs_task,
|
||||
@@ -43,24 +51,36 @@ def merge_pdfs_route():
|
||||
if len(files) > 20:
|
||||
return jsonify({"error": "Maximum 20 files allowed."}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
input_paths = []
|
||||
original_filenames = []
|
||||
|
||||
for f in files:
|
||||
try:
|
||||
original_filename, ext = validate_file(f, allowed_types=["pdf"])
|
||||
original_filename, ext = validate_actor_file(f, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
upload_dir = os.path.join("/tmp/uploads", task_id)
|
||||
upload_dir = os.path.join(current_app.config["UPLOAD_FOLDER"], task_id)
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
file_path = os.path.join(upload_dir, f"{uuid.uuid4()}.{ext}")
|
||||
f.save(file_path)
|
||||
input_paths.append(file_path)
|
||||
original_filenames.append(original_filename)
|
||||
|
||||
task = merge_pdfs_task.delay(input_paths, task_id, original_filenames)
|
||||
task = merge_pdfs_task.delay(
|
||||
input_paths,
|
||||
task_id,
|
||||
original_filenames,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "merge-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -98,15 +118,29 @@ def split_pdf_route():
|
||||
"error": "Please specify which pages to extract (e.g. 1,3,5-8)."
|
||||
}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = split_pdf_task.delay(input_path, task_id, original_filename, mode, pages)
|
||||
task = split_pdf_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
mode,
|
||||
pages,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "split-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -144,15 +178,29 @@ def rotate_pdf_route():
|
||||
|
||||
pages = request.form.get("pages", "all")
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = rotate_pdf_task.delay(input_path, task_id, original_filename, rotation, pages)
|
||||
task = rotate_pdf_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
rotation,
|
||||
pages,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "rotate-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -193,8 +241,14 @@ def add_page_numbers_route():
|
||||
except ValueError:
|
||||
start_number = 1
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
@@ -202,8 +256,14 @@ def add_page_numbers_route():
|
||||
file.save(input_path)
|
||||
|
||||
task = add_page_numbers_task.delay(
|
||||
input_path, task_id, original_filename, position, start_number
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
position,
|
||||
start_number,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "page-numbers", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -239,8 +299,14 @@ def pdf_to_images_route():
|
||||
except ValueError:
|
||||
dpi = 200
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
@@ -248,8 +314,14 @@ def pdf_to_images_route():
|
||||
file.save(input_path)
|
||||
|
||||
task = pdf_to_images_task.delay(
|
||||
input_path, task_id, original_filename, output_format, dpi
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
output_format,
|
||||
dpi,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-to-images", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -276,24 +348,38 @@ def images_to_pdf_route():
|
||||
if len(files) > 50:
|
||||
return jsonify({"error": "Maximum 50 images allowed."}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
input_paths = []
|
||||
original_filenames = []
|
||||
|
||||
for f in files:
|
||||
try:
|
||||
original_filename, ext = validate_file(f, allowed_types=ALLOWED_IMAGE_TYPES)
|
||||
original_filename, ext = validate_actor_file(
|
||||
f, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
upload_dir = os.path.join("/tmp/uploads", task_id)
|
||||
upload_dir = os.path.join(current_app.config["UPLOAD_FOLDER"], task_id)
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
file_path = os.path.join(upload_dir, f"{uuid.uuid4()}.{ext}")
|
||||
f.save(file_path)
|
||||
input_paths.append(file_path)
|
||||
original_filenames.append(original_filename)
|
||||
|
||||
task = images_to_pdf_task.delay(input_paths, task_id, original_filenames)
|
||||
task = images_to_pdf_task.delay(
|
||||
input_paths,
|
||||
task_id,
|
||||
original_filenames,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "images-to-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -333,8 +419,14 @@ def watermark_pdf_route():
|
||||
except ValueError:
|
||||
opacity = 0.3
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
@@ -342,8 +434,14 @@ def watermark_pdf_route():
|
||||
file.save(input_path)
|
||||
|
||||
task = watermark_pdf_task.delay(
|
||||
input_path, task_id, original_filename, watermark_text, opacity
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
watermark_text,
|
||||
opacity,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "watermark-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -377,15 +475,28 @@ def protect_pdf_route():
|
||||
if len(password) < 4:
|
||||
return jsonify({"error": "Password must be at least 4 characters."}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = protect_pdf_task.delay(input_path, task_id, original_filename, password)
|
||||
task = protect_pdf_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
password,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "protect-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
@@ -416,15 +527,28 @@ def unlock_pdf_route():
|
||||
if not password:
|
||||
return jsonify({"error": "Password is required."}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=["pdf"])
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = unlock_pdf_task.delay(input_path, task_id, original_filename, password)
|
||||
task = unlock_pdf_task.delay(
|
||||
input_path,
|
||||
task_id,
|
||||
original_filename,
|
||||
password,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "unlock-pdf", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
|
||||
1
backend/app/routes/v1/__init__.py
Normal file
1
backend/app/routes/v1/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""B2B API v1 blueprint package."""
|
||||
682
backend/app/routes/v1/tools.py
Normal file
682
backend/app/routes/v1/tools.py
Normal file
@@ -0,0 +1,682 @@
|
||||
"""B2B API v1 tool routes — authenticated via X-API-Key, Pro plan only."""
|
||||
import os
|
||||
import uuid
|
||||
import logging
|
||||
|
||||
from celery.result import AsyncResult
|
||||
from flask import Blueprint, current_app, jsonify, request
|
||||
|
||||
from app.extensions import celery, limiter
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
assert_api_task_access,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_api_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.compress_tasks import compress_pdf_task
|
||||
from app.tasks.convert_tasks import convert_pdf_to_word, convert_word_to_pdf
|
||||
from app.tasks.image_tasks import convert_image_task, resize_image_task
|
||||
from app.tasks.video_tasks import create_gif_task
|
||||
from app.tasks.pdf_tools_tasks import (
|
||||
merge_pdfs_task,
|
||||
split_pdf_task,
|
||||
rotate_pdf_task,
|
||||
add_page_numbers_task,
|
||||
pdf_to_images_task,
|
||||
images_to_pdf_task,
|
||||
watermark_pdf_task,
|
||||
protect_pdf_task,
|
||||
unlock_pdf_task,
|
||||
)
|
||||
from app.tasks.flowchart_tasks import extract_flowchart_task
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
v1_bp = Blueprint("v1", __name__)
|
||||
|
||||
ALLOWED_IMAGE_TYPES = ["png", "jpg", "jpeg", "webp"]
|
||||
ALLOWED_VIDEO_TYPES = ["mp4", "webm"]
|
||||
ALLOWED_OUTPUT_FORMATS = ["jpg", "png", "webp"]
|
||||
|
||||
|
||||
def _resolve_and_check() -> tuple:
|
||||
"""Resolve API actor and assert quota. Returns (actor, error_response | None)."""
|
||||
try:
|
||||
actor = resolve_api_actor()
|
||||
except PolicyError as e:
|
||||
return None, (jsonify({"error": e.message}), e.status_code)
|
||||
|
||||
try:
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return None, (jsonify({"error": e.message}), e.status_code)
|
||||
|
||||
return actor, None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task status — GET /api/v1/tasks/<task_id>/status
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/tasks/<task_id>/status", methods=["GET"])
|
||||
@limiter.limit("300/minute", override_defaults=True)
|
||||
def get_task_status(task_id: str):
|
||||
"""Poll the status of an async API task."""
|
||||
try:
|
||||
actor = resolve_api_actor()
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
assert_api_task_access(actor, task_id)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
result = AsyncResult(task_id, app=celery)
|
||||
response: dict = {"task_id": task_id, "state": result.state}
|
||||
|
||||
if result.state == "PENDING":
|
||||
response["progress"] = "Task is waiting in queue..."
|
||||
elif result.state == "PROCESSING":
|
||||
response["progress"] = (result.info or {}).get("step", "Processing...")
|
||||
elif result.state == "SUCCESS":
|
||||
response["result"] = result.result or {}
|
||||
elif result.state == "FAILURE":
|
||||
response["error"] = str(result.info) if result.info else "Task failed."
|
||||
|
||||
return jsonify(response)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Compress — POST /api/v1/compress/pdf
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/compress/pdf", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def compress_pdf_route():
|
||||
"""Compress a PDF file."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
quality = request.form.get("quality", "medium")
|
||||
if quality not in ("low", "medium", "high"):
|
||||
quality = "medium"
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = compress_pdf_task.delay(
|
||||
input_path, task_id, original_filename, quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "compress-pdf", task.id)
|
||||
|
||||
return jsonify({"task_id": task.id, "message": "Compression started."}), 202
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Convert — POST /api/v1/convert/pdf-to-word & /api/v1/convert/word-to-pdf
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/convert/pdf-to-word", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def pdf_to_word_route():
|
||||
"""Convert a PDF to Word (DOCX)."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = convert_pdf_to_word.delay(
|
||||
input_path, task_id, original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-to-word", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Conversion started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/convert/word-to-pdf", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def word_to_pdf_route():
|
||||
"""Convert a Word (DOC/DOCX) file to PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=["doc", "docx"], actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = convert_word_to_pdf.delay(
|
||||
input_path, task_id, original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "word-to-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Conversion started."}), 202
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Image — POST /api/v1/image/convert & /api/v1/image/resize
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/image/convert", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def convert_image_route():
|
||||
"""Convert an image to a different format."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
output_format = request.form.get("format", "").lower()
|
||||
if output_format not in ALLOWED_OUTPUT_FORMATS:
|
||||
return jsonify({"error": f"Invalid format. Supported: {', '.join(ALLOWED_OUTPUT_FORMATS)}"}), 400
|
||||
|
||||
try:
|
||||
quality = max(1, min(100, int(request.form.get("quality", "85"))))
|
||||
except ValueError:
|
||||
quality = 85
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = convert_image_task.delay(
|
||||
input_path, task_id, original_filename, output_format, quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "image-convert", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Image conversion started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/image/resize", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def resize_image_route():
|
||||
"""Resize an image."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
width = int(request.form.get("width")) if request.form.get("width") else None
|
||||
height = int(request.form.get("height")) if request.form.get("height") else None
|
||||
except ValueError:
|
||||
return jsonify({"error": "Width and height must be integers."}), 400
|
||||
|
||||
if width is None and height is None:
|
||||
return jsonify({"error": "At least one of width or height is required."}), 400
|
||||
if width and not (1 <= width <= 10000):
|
||||
return jsonify({"error": "Width must be between 1 and 10000."}), 400
|
||||
if height and not (1 <= height <= 10000):
|
||||
return jsonify({"error": "Height must be between 1 and 10000."}), 400
|
||||
|
||||
try:
|
||||
quality = max(1, min(100, int(request.form.get("quality", "85"))))
|
||||
except ValueError:
|
||||
quality = 85
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = resize_image_task.delay(
|
||||
input_path, task_id, original_filename, width, height, quality,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "image-resize", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Image resize started."}), 202
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Video — POST /api/v1/video/to-gif
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/video/to-gif", methods=["POST"])
|
||||
@limiter.limit("5/minute")
|
||||
def video_to_gif_route():
|
||||
"""Convert a video clip to an animated GIF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
start_time = float(request.form.get("start_time", 0))
|
||||
duration = float(request.form.get("duration", 5))
|
||||
fps = int(request.form.get("fps", 10))
|
||||
width = int(request.form.get("width", 480))
|
||||
except (ValueError, TypeError):
|
||||
return jsonify({"error": "Invalid parameters. Must be numeric."}), 400
|
||||
|
||||
if start_time < 0:
|
||||
return jsonify({"error": "Start time cannot be negative."}), 400
|
||||
if not (0 < duration <= 15):
|
||||
return jsonify({"error": "Duration must be between 0.5 and 15 seconds."}), 400
|
||||
if not (1 <= fps <= 20):
|
||||
return jsonify({"error": "FPS must be between 1 and 20."}), 400
|
||||
if not (100 <= width <= 640):
|
||||
return jsonify({"error": "Width must be between 100 and 640 pixels."}), 400
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_VIDEO_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
task = create_gif_task.delay(
|
||||
input_path, task_id, original_filename, start_time, duration, fps, width,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "video-to-gif", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "GIF creation started."}), 202
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# PDF Tools — all single-file and multi-file routes
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@v1_bp.route("/pdf-tools/merge", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def merge_pdfs_route():
|
||||
"""Merge multiple PDF files into one."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
files = request.files.getlist("files")
|
||||
if not files or len(files) < 2:
|
||||
return jsonify({"error": "Please upload at least 2 PDF files."}), 400
|
||||
if len(files) > 20:
|
||||
return jsonify({"error": "Maximum 20 files allowed."}), 400
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
input_paths, original_filenames = [], []
|
||||
for f in files:
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(f, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
upload_dir = os.path.join(current_app.config["UPLOAD_FOLDER"], task_id)
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
file_path = os.path.join(upload_dir, f"{uuid.uuid4()}.{ext}")
|
||||
f.save(file_path)
|
||||
input_paths.append(file_path)
|
||||
original_filenames.append(original_filename)
|
||||
|
||||
task = merge_pdfs_task.delay(
|
||||
input_paths, task_id, original_filenames,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "merge-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Merge started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/split", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def split_pdf_route():
|
||||
"""Split a PDF into pages or a range."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
mode = request.form.get("mode", "all")
|
||||
pages = request.form.get("pages")
|
||||
if mode not in ("all", "range"):
|
||||
mode = "all"
|
||||
if mode == "range" and not (pages and pages.strip()):
|
||||
return jsonify({"error": "Please specify which pages to extract."}), 400
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = split_pdf_task.delay(
|
||||
input_path, task_id, original_filename, mode, pages,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "split-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Split started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/rotate", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def rotate_pdf_route():
|
||||
"""Rotate pages in a PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
rotation = int(request.form.get("rotation", 90))
|
||||
except ValueError:
|
||||
rotation = 90
|
||||
if rotation not in (90, 180, 270):
|
||||
return jsonify({"error": "Rotation must be 90, 180, or 270 degrees."}), 400
|
||||
pages = request.form.get("pages", "all")
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = rotate_pdf_task.delay(
|
||||
input_path, task_id, original_filename, rotation, pages,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "rotate-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Rotation started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/page-numbers", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def add_page_numbers_route():
|
||||
"""Add page numbers to a PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
position = request.form.get("position", "bottom-center")
|
||||
valid_positions = [
|
||||
"bottom-center", "bottom-right", "bottom-left",
|
||||
"top-center", "top-right", "top-left",
|
||||
]
|
||||
if position not in valid_positions:
|
||||
position = "bottom-center"
|
||||
try:
|
||||
start_number = max(1, int(request.form.get("start_number", 1)))
|
||||
except ValueError:
|
||||
start_number = 1
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = add_page_numbers_task.delay(
|
||||
input_path, task_id, original_filename, position, start_number,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "page-numbers", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Page numbering started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/pdf-to-images", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def pdf_to_images_route():
|
||||
"""Convert PDF pages to images."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
output_format = request.form.get("format", "png").lower()
|
||||
if output_format not in ("png", "jpg"):
|
||||
output_format = "png"
|
||||
try:
|
||||
dpi = max(72, min(600, int(request.form.get("dpi", 200))))
|
||||
except ValueError:
|
||||
dpi = 200
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = pdf_to_images_task.delay(
|
||||
input_path, task_id, original_filename, output_format, dpi,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-to-images", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Conversion started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/images-to-pdf", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def images_to_pdf_route():
|
||||
"""Convert multiple images to a single PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
files = request.files.getlist("files")
|
||||
if not files:
|
||||
return jsonify({"error": "Please upload at least 1 image."}), 400
|
||||
if len(files) > 50:
|
||||
return jsonify({"error": "Maximum 50 images allowed."}), 400
|
||||
|
||||
task_id = str(uuid.uuid4())
|
||||
input_paths, original_filenames = [], []
|
||||
for f in files:
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
f, allowed_types=ALLOWED_IMAGE_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
upload_dir = os.path.join(current_app.config["UPLOAD_FOLDER"], task_id)
|
||||
os.makedirs(upload_dir, exist_ok=True)
|
||||
file_path = os.path.join(upload_dir, f"{uuid.uuid4()}.{ext}")
|
||||
f.save(file_path)
|
||||
input_paths.append(file_path)
|
||||
original_filenames.append(original_filename)
|
||||
|
||||
task = images_to_pdf_task.delay(
|
||||
input_paths, task_id, original_filenames,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "images-to-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Conversion started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/watermark", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def watermark_pdf_route():
|
||||
"""Add a text watermark to a PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
watermark_text = request.form.get("text", "").strip()
|
||||
if not watermark_text:
|
||||
return jsonify({"error": "Watermark text is required."}), 400
|
||||
if len(watermark_text) > 100:
|
||||
return jsonify({"error": "Watermark text must be 100 characters or less."}), 400
|
||||
try:
|
||||
opacity = max(0.1, min(1.0, float(request.form.get("opacity", 0.3))))
|
||||
except ValueError:
|
||||
opacity = 0.3
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = watermark_pdf_task.delay(
|
||||
input_path, task_id, original_filename, watermark_text, opacity,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "watermark-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Watermarking started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/protect", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def protect_pdf_route():
|
||||
"""Add password protection to a PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
password = request.form.get("password", "").strip()
|
||||
if not password:
|
||||
return jsonify({"error": "Password is required."}), 400
|
||||
if len(password) < 4:
|
||||
return jsonify({"error": "Password must be at least 4 characters."}), 400
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = protect_pdf_task.delay(
|
||||
input_path, task_id, original_filename, password,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "protect-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Protection started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/pdf-tools/unlock", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def unlock_pdf_route():
|
||||
"""Remove password protection from a PDF."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file provided."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
password = request.form.get("password", "").strip()
|
||||
if not password:
|
||||
return jsonify({"error": "Password is required."}), 400
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
task = unlock_pdf_task.delay(
|
||||
input_path, task_id, original_filename, password,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "unlock-pdf", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Unlock started."}), 202
|
||||
|
||||
|
||||
@v1_bp.route("/flowchart/extract", methods=["POST"])
|
||||
@limiter.limit("10/minute")
|
||||
def extract_flowchart_route():
|
||||
"""Extract procedures from a PDF and generate flowcharts."""
|
||||
actor, err = _resolve_and_check()
|
||||
if err:
|
||||
return err
|
||||
|
||||
if "file" not in request.files:
|
||||
return jsonify({"error": "No file uploaded."}), 400
|
||||
|
||||
file = request.files["file"]
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(file, allowed_types=["pdf"], actor=actor)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
task_id, input_path = generate_safe_path(ext)
|
||||
file.save(input_path)
|
||||
task = extract_flowchart_task.delay(
|
||||
input_path, task_id, original_filename,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "pdf-flowchart", task.id)
|
||||
return jsonify({"task_id": task.id, "message": "Flowchart extraction started."}), 202
|
||||
@@ -2,7 +2,15 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
|
||||
from app.extensions import limiter
|
||||
from app.utils.file_validator import validate_file, FileValidationError
|
||||
from app.services.policy_service import (
|
||||
assert_quota_available,
|
||||
build_task_tracking_kwargs,
|
||||
PolicyError,
|
||||
record_accepted_usage,
|
||||
resolve_web_actor,
|
||||
validate_actor_file,
|
||||
)
|
||||
from app.utils.file_validator import FileValidationError
|
||||
from app.utils.sanitizer import generate_safe_path
|
||||
from app.tasks.video_tasks import create_gif_task
|
||||
|
||||
@@ -49,20 +57,28 @@ def video_to_gif_route():
|
||||
if width < 100 or width > 640:
|
||||
return jsonify({"error": "Width must be between 100 and 640 pixels."}), 400
|
||||
|
||||
actor = resolve_web_actor()
|
||||
try:
|
||||
original_filename, ext = validate_file(file, allowed_types=ALLOWED_VIDEO_TYPES)
|
||||
assert_quota_available(actor)
|
||||
except PolicyError as e:
|
||||
return jsonify({"error": e.message}), e.status_code
|
||||
|
||||
try:
|
||||
original_filename, ext = validate_actor_file(
|
||||
file, allowed_types=ALLOWED_VIDEO_TYPES, actor=actor
|
||||
)
|
||||
except FileValidationError as e:
|
||||
return jsonify({"error": e.message}), e.code
|
||||
|
||||
# Save file
|
||||
task_id, input_path = generate_safe_path(ext, folder_type="upload")
|
||||
file.save(input_path)
|
||||
|
||||
# Dispatch task
|
||||
task = create_gif_task.delay(
|
||||
input_path, task_id, original_filename,
|
||||
start_time, duration, fps, width,
|
||||
**build_task_tracking_kwargs(actor),
|
||||
)
|
||||
record_accepted_usage(actor, "video-to-gif", task.id)
|
||||
|
||||
return jsonify({
|
||||
"task_id": task.id,
|
||||
|
||||
Reference in New Issue
Block a user