file_app.py
Overview
file_app.py is a Flask-based web API module that manages file and folder operations within the InfiniFlow platform. It provides endpoints for uploading, creating, listing, retrieving, renaming, moving, and deleting files and folders, all secured via user authentication (flask_login). This module acts as a controller layer interfacing between HTTP requests and the backend services that handle file metadata (FileService), document associations (DocumentService, File2DocumentService), and storage operations (via STORAGE_IMPL).
The file ensures user access control, enforces business rules (e.g., maximum file counts), maintains file hierarchy integrity, and coordinates consistent state between storage and database layers.
Classes and Functions
This module primarily defines Flask route handler functions; no classes are defined here. Below is a detailed explanation of each route handler.
1. upload()
Route:
/uploadMethods: POST
Decorators:
@login_requiredPurpose: Upload one or more files to a specified parent folder.
Parameters
parent_id(form data, optional): ID of the parent folder where files will be uploaded. Defaults to the user's root folder if not provided.file(form data): One or multiple files uploaded in the request.
Returns
JSON response indicating success or failure.
On success, returns metadata of uploaded files.
Behavior and Implementation Details
Validates presence of files in the request.
Enforces a maximum file count per user via environment variable
MAX_FILE_NUM_PER_USER.Parses file names and ensures the folder structure exists or creates missing folders.
Checks for duplicate file names, adjusting the name with underscores if necessary.
Reads file content, stores it using the configured storage implementation (
STORAGE_IMPL).Inserts file metadata into the database.
Handles exceptions by returning server error responses.
Usage Example (cURL)
curl -X POST -F "parent_id=<folder_id>" -F "file=@path/to/file1" -F "file=@path/to/file2" https://api.infinitflow.com/upload
2. create()
Route:
/createMethods: POST
Decorators:
@login_required,@validate_request("name")Purpose: Create a new folder or virtual file under a specified parent folder.
Parameters (JSON Body)
name(string, required): Name of the new folder or file.parent_id(string, optional): Parent folder ID. Defaults to user's root folder if omitted.type(string, optional): Type of the file object; eitherFOLDERorVIRTUAL.
Returns
JSON with metadata of the created file/folder or error messages.
Behavior
Checks if the parent folder exists.
Ensures no duplicate folder names within the parent.
Inserts new metadata with appropriate file type.
Returns created entity's JSON representation.
Usage Example
POST /create
{
"name": "NewFolder",
"parent_id": "12345",
"type": "FOLDER"
}
3. list_files()
Route:
/listMethods: GET
Decorators:
@login_requiredPurpose: List files and folders under a given parent folder with optional filtering, pagination, and sorting.
Query Parameters
parent_id(string, optional): Folder ID to list. Defaults to root folder.keywords(string, optional): Search keywords to filter file names.page(int, optional): Page number, default1.page_size(int, optional): Items per page, default15.orderby(string, optional): Field to order by, defaultcreate_time.desc(boolean, optional): Descending order flag, defaultTrue.
Returns
JSON with total count, list of files (metadata), and the parent folder info.
Behavior
Initializes knowledge base documents if listing root folder.
Retrieves paged and filtered file list.
Returns structured response or error if folder not found.
4. get_root_folder()
Route:
/root_folderMethods: GET
Decorators:
@login_requiredPurpose: Retrieve the root folder information for the current user.
Returns
JSON containing root folder metadata.
5. get_parent_folder()
Route:
/parent_folderMethods: GET
Decorators:
@login_requiredPurpose: Retrieves the immediate parent folder of a given file or folder.
Query Parameters
file_id(string, required): ID of the file/folder.
Returns
JSON with the parent folder metadata.
6. get_all_parent_folders()
Route:
/all_parent_folderMethods: GET
Decorators:
@login_requiredPurpose: Retrieves all parent folders up to the root for a given file/folder.
Query Parameters
file_id(string, required): ID of the file/folder.
Returns
JSON array of parent folder metadata in hierarchical order.
7. rm()
Route:
/rmMethods: POST
Decorators:
@login_required,@validate_request("file_ids")Purpose: Remove one or more files or folders.
Parameters (JSON Body)
file_ids(list of strings): IDs of files/folders to delete.
Returns
JSON indicating success or failure.
Behavior
Validates existence and tenant ownership.
Skips files from the knowledge base source.
Recursively deletes files inside folders.
Removes physical blobs from storage.
Deletes metadata entries and related document associations.
Handles database consistency and error reporting.
8. rename()
Route:
/renameMethods: POST
Decorators:
@login_required,@validate_request("file_id", "name")Purpose: Rename a file or folder.
Parameters (JSON Body)
file_id(string): ID of the file or folder.name(string): New name.
Returns
JSON success flag or error message.
Behavior
Prevents changing file extensions for non-folder files.
Ensures no duplicate names in the same folder.
Updates file metadata and associated document name if applicable.
9. get(file_id)
Route:
/get/<file_id>Methods: GET
Decorators:
@login_requiredPurpose: Retrieve the content blob of a file by ID.
Parameters
file_id(path parameter): File ID.
Returns
Binary content of the file with appropriate HTTP content-type headers.
Behavior
Retrieves file metadata.
Attempts to fetch blob from primary storage location.
Falls back to alternative storage address if needed.
Sets content type based on file extension and type.
10. move()
Route:
/mvMethods: POST
Decorators:
@login_required,@validate_request("src_file_ids", "dest_file_id")Purpose: Move files or folders to a new parent folder.
Parameters (JSON Body)
src_file_ids(list of strings): IDs of source files/folders.dest_file_id(string): Destination folder ID.
Returns
JSON success flag or error message.
Behavior
Validates existence and ownership of files and destination.
Performs the move operation in database metadata.
Important Implementation Details
Storage Abstraction: The module uses
STORAGE_IMPL, an abstraction for storage operations (read, write, delete). This decouples file metadata management from physical storage handling.File Hierarchy Management: Folder structure creation and file placement rely on hierarchical name parsing and folder existence checks, ensuring consistent filesystem-like behavior.
File Type Handling: Files are distinguished by types such as
FOLDER,VIRTUAL, andVISUALusingFileTypeenums, affecting behavior like content type resolution.Error Handling: The API uniformly wraps operations in try-except blocks, returning structured JSON error responses and HTTP codes defined in
settings.RetCode.Authentication: All endpoints require user login, ensuring operations are tenant/user scoped via
current_user.Duplicate Name Handling: The
duplicate_nameservice function ensures uniqueness of file names within a folder, appending suffixes as needed.
Interactions with Other Components
FileService: Manages file and folder metadata CRUD operations and queries.DocumentService&File2DocumentService: Handle associations between files and documents, enabling synchronized updates and deletions.STORAGE_IMPL: Abstract storage backend interface used for physical file operations.api.utils: Utility functions for API responses, validation, and helper functions like UUID generation.flask_login: Authentication management to restrict access to logged-in users.settings: Application-wide constants for return codes and configuration.
This module acts as the REST API layer, coordinating between HTTP requests, business logic, persistent storage, and authentication.
Visual Diagram
classDiagram
class file_app {
+upload()
+create()
+list_files()
+get_root_folder()
+get_parent_folder()
+get_all_parent_folders()
+rm()
+rename()
+get(file_id)
+move()
}
file_app ..> FileService : Uses for metadata operations
file_app ..> DocumentService : Uses for document management
file_app ..> File2DocumentService : Uses for file-document links
file_app ..> STORAGE_IMPL : Uses for physical file storage
file_app ..> flask_login : Uses for user authentication
file_app ..> api.utils.api_utils : Uses for response and validation utilities
Summary
file_app.py is a core API component within InfiniFlow that facilitates comprehensive file and folder management functionalities. It ensures secure, consistent, and user-scoped file handling integrated with document management and physical storage. The module's design promotes modularity by delegating specialized tasks to dedicated services and utilities, enabling maintainable and scalable file management features in the application.