### Quick Start: Get User and File Info Source: https://github.com/foyoux/aligo/blob/main/README.md Initialize Aligo, get user information, and list files in the root directory. The first use will prompt for QR code scanning for login. ```python """快速入门""" from aligo import Aligo if __name__ == '__main__': ali = Aligo() # 第一次使用,会弹出二维码,供扫描登录 user = ali.get_user() # 获取用户信息 print(user.user_name, user.nick_name, user.phone) # 打印用户信息 file_list = ali.get_file_list() # 获取网盘根目录文件列表 for file in file_list: # 遍历文件列表 # 注意:print(file) 默认只显示部分信息,但是实际上file有很多的属性 print(file.file_id, file.name, file.type) # 打印文件信息 ``` -------------------------------- ### Install Aligo SDK Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Install the Aligo SDK using pip. This is the first step to using the library. ```bash pip install aligo ``` -------------------------------- ### Install Aligo Source: https://github.com/foyoux/aligo/blob/main/README.md Install the aligo library using pip. It is recommended to upgrade to the latest version. ```sh pip install -U aligo pip install git+https://github.com/foyoux/aligo.git ``` -------------------------------- ### Drive Information Example Source: https://github.com/foyoux/aligo/wiki/获取简单信息 An example of the JSON structure returned when fetching drive information. ```json5 { "drive_id": "1066884", "used_size": 6998969779282, "total_size": 8480412925952, "drive_name": "Default", "owner": "3e935da769594ca4849c7c1409efb96f", "description": "Created by system", "drive_type": "normal", "creator": "System", "domain_id": "bj29", "status": "enabled", "store_id": "b5e9de389ef241d084733b520ea8b57d", "owner_type": "user", "relative_path": "", "encrypt_mode": "none", "encrypt_data_access": false, "permission": null, "created_at": "2021-02-25T08:16:02.642Z", "subdomain_id": "" } ``` -------------------------------- ### Basic Aligo Usage Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Initialize the Aligo client and perform basic operations like getting user info, listing files, and getting download URLs. The client displays a QR code for first-time login. ```python from aligo import Aligo # Initialize client (displays QR code for first login) ali = Aligo() # Get user information user = ali.get_user() print(user.user_name, user.nick_name) # List files in root directory files = ali.get_file_list() for file in files: print(file.name, file.type) # Get download URL response = ali.get_download_url('file_id') print(response.url) ``` -------------------------------- ### Basic Configuration File Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Example of a basic configuration file (`config.json5`) for Aligo. This sets up general parameters like API level, proxy usage, and request timeouts. ```json5 { "level": 10, "use_aria2": false, "proxies": { "https": "http://localhost:10809", }, "port": null, "request_interval": 0, "requests_timeout": 30, } ``` -------------------------------- ### Example: Using and Setting Default Drive ID Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Demonstrates how to print the current default drive ID and how to switch the default drive to a specific one, such as the 'resource' drive, by first listing available drives. ```python ali = Aligo() print(ali.default_drive_id) # Print default drive ID # Switch to resource drive drives = ali.list_my_drives() resource_drive = [d for d in drives if d.drive_name == 'resource'][0] ali.default_drive_id = resource_drive.drive_id ``` -------------------------------- ### Type Hinting for Aligo Objects Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Provides examples of type hints for core Aligo objects like `BaseFile`, `BaseUser`, and `BaseDrive`. This aids in static analysis and improves code readability. ```python from aligo import BaseFile, BaseUser, BaseDrive file: BaseFile # File/folder object user: BaseUser # User account info drive: BaseDrive # Storage drive info ``` -------------------------------- ### Get File by ID Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/File.md Retrieve detailed information about a single file using its ID. Ensure the 'aligo' library is imported. ```python from aligo import Aligo ali = Aligo() # Get file by ID file = ali.get_file('file_id_here') print(file.name, file.size, file.type) ``` -------------------------------- ### Handle AligoRefreshFailed and Re-authenticate Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Example of handling AligoRefreshFailed by creating a new Aligo instance to re-authenticate. This is necessary when the session token expires and automatic re-login is disabled. ```python from aligo import Aligo, AligoRefreshFailed # Create with automatic re-login disabled ali = Aligo(re_login=False) try: # After long inactivity, token may expire file = ali.get_file('file_id') except AligoRefreshFailed: print("Session expired, need to re-authenticate") # Create new instance for fresh login ali = Aligo() file = ali.get_file('file_id') ``` -------------------------------- ### Move and Rename File Simultaneously Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Move.md This example demonstrates moving a file to a new location and renaming it in a single operation. Both the destination folder ID and the new file name are specified. ```python from aligo import Aligo ali = Aligo() # Move and rename simultaneously result = ali.move_file( file_id='file_id', parent_file_id='destination_id', new_name='new_filename.txt' ) ``` -------------------------------- ### Get Album Details Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Album.md Retrieves detailed information about a specific album using its album ID. ```python from aligo import Aligo ali = Aligo() # Get album details album = ali.get_album('album_id') print(f"Album: {album.name}") print(f"Created: {album.created_at}") ``` -------------------------------- ### Handle AligoException Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Example of catching the base AligoException to handle any aligo-related error during an operation. This is useful for general error reporting or fallback mechanisms. ```python from aligo import Aligo, AligoException ali = Aligo() try: file = ali.get_file('invalid_file_id') except AligoException as e: print(f"Operation failed: {e}") ``` -------------------------------- ### Handle Access Denied Error in Aligo Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Detect and handle 'permission denied' errors when attempting to access a restricted file. This example checks the exception message for relevant terms. ```python from aligo import Aligo, AligoException ali = Aligo() try: # Try to access restricted file file = ali.get_file('restricted_file_id') except AligoException as e: if 'permission' in str(e).lower() or 'denied' in str(e).lower(): print("Access denied to this file") else: raise ``` -------------------------------- ### Handle AligoFatalError Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Example of catching AligoFatalError to gracefully handle situations where an operation has failed fatally and cannot be recovered. This ensures the application state is managed appropriately. ```python from aligo import Aligo, AligoFatalError ali = Aligo() try: # Some operation that fails fatally pass except AligoFatalError as e: print(f"Fatal error, operation aborted: {e}") ``` -------------------------------- ### Handle Share Link Limit Exceeded Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Example of handling AligoShareLinkCreateExceedDailyLimit by informing the user and suggesting alternatives like waiting or deleting old shares. This helps manage API usage quotas. ```python from aligo import Aligo, AligoShareLinkCreateExceedDailyLimit ali = Aligo() try: share = ali.share_file('file_id') except AligoShareLinkCreateExceedDailyLimit: print("Daily share limit reached. Try again tomorrow.") # Alternatively, delete old shares to free quota shares = ali.get_share_list() if shares: ali.cancel_share(shares[0].share_id) ``` -------------------------------- ### Enable Aria2c for Downloads Source: https://github.com/foyoux/aligo/blob/main/_autodocs/configuration.md Configure the Aligo client to use aria2c for file downloads, which can improve download speeds. Ensure aria2c is installed and accessible in your system's PATH. ```python from aligo import Aligo # Use aria2c for downloads (if installed) ali = Aligo(use_aria2=True) # Download file (will use aria2c if available) ali.download_file(file_id='...') ``` ```json5 { "use_aria2": true } ``` -------------------------------- ### Get User Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieve the current user's basic information. The result is cached and can be refreshed by passing `f5=True`. ```python user = ali.get_user() ``` ```python user = ali.get_user(f5=True) ``` -------------------------------- ### Custom File Deletion Function Source: https://github.com/foyoux/aligo/blob/main/images/old_readme.md Implement a custom file deletion function by extending the Aligo class. This example shows how to define and use a custom method for deleting files. ```python """ """ from aligo import Aligo class CustomAligo(Aligo): """自定义 aligo """ V2_FILE_DELETE = '/v2/file/delete' def delete_file(self, file_id: str): """删除文件""" response = self.post(self.V2_FILE_DELETE, body={'file_id': file_id}) return response.json() cali = CustomAligo() cali.delete_file('') ``` -------------------------------- ### Aligo File Operations Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Perform common file operations such as getting file info, listing directories, uploading, and downloading files. Use file IDs or paths as needed. ```python from aligo import Aligo ali = Aligo() # Get file information file = ali.get_file('file_id') # List directory files = ali.get_file_list(parent_file_id='folder_id') # Get file by path file = ali.get_file_by_path('path/to/file.txt') # Create folder folder = ali.create_folder('MyFolder') # Upload file result = ali.upload_file('/local/path/file.txt') # Download file (get URL) response = ali.get_download_url('file_id') ``` -------------------------------- ### Get Download URL for Files and Folders Source: https://github.com/foyoux/aligo/blob/main/_autodocs/DOCUMENTATION_INDEX.md Use this snippet to obtain download URLs for single files, multiple files, or entire folders. Ensure you have the correct file or folder IDs. ```python ali = Aligo() # Single file response = ali.get_download_url('file_id') print(response.url) # Multiple files urls = ali.batch_download_url(['id1', 'id2', 'id3']) # Download folder local_path = ali.download_folder('folder_id') ``` -------------------------------- ### Get Cloud Drive Space Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Fetch the used and total space available in the user's cloud drive. Access specific details like `used_size` and `total_size` from the returned object. ```python personal_info = ali.get_personal_info() # 已用大小 used_size = personal_info.personal_space_info.used_size # 总大小 total_size = personal_info.personal_space_info.total_size ``` -------------------------------- ### Custom QR Code Display Function Source: https://github.com/foyoux/aligo/wiki/登录 Define a custom function to display QR codes, useful in environments where direct display is not possible. This example sends the QR code via email. ```python import tempfile import qrcode import yagmail from aligo import Aligo, Auth def show(qr_link: str): """自定义显示二维码""" # 1.将二维码链接转为图片 qr_img = qrcode.make(qr_link) png_file = tempfile.mktemp('.png') qr_img.save(png_file) # 2.将二维码发送到自己的(手机)邮箱, 这里以QQ邮箱为例 # 使用 yagmail 库发送邮件, `pip install yagmail[all]` yag = yagmail.SMTP('<你的邮箱地址>', '授权码/密码', 'smtp.qq.com', 465) yag.send('<目标邮箱>', 'aligo扫码登录', qr_link, attachments=[png_file]) ali = Aligo(name='xxx', show=show) ``` -------------------------------- ### Rename File with Auto-Rename Conflict Mode Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Move.md This example shows how to rename a file while specifying the 'auto_rename' mode to handle potential name conflicts. If a file with the new name already exists, it will be automatically renamed. ```python from aligo import Aligo ali = Aligo() # Rename with auto-rename if name exists result = ali.rename_file( 'file_id', 'document.pdf', check_name_mode='auto_rename' ) ``` -------------------------------- ### Get Starred Files List Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Star.md Retrieves a list of all starred files. Supports sorting by creation date, update date, name, or size, and can specify the direction of sorting. Allows filtering of returned fields. ```python from aligo import Aligo ali = Aligo() # Get all starred files starred = ali.get_starred_list() for file in starred: print(f"⭐ {file.name}") # Get starred files sorted by size starred = ali.get_starred_list( order_by='size', order_direction='DESC' ) total_size = sum(f.size or 0 for f in starred) print(f"Total starred: {total_size / (1024**3):.2f} GB") ``` -------------------------------- ### Initialize Aligo and Log in with QR Code Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Demonstrates basic initialization of the Aligo client and logging in by scanning a QR code. After successful login, it shows how to retrieve user information and list files in the root directory. ```python from aligo import Aligo # First use - displays QR code for scanning ali = Aligo() # Get user information user = ali.get_user() print(user.user_name, user.nick_name, user.phone) # List files in root directory file_list = ali.get_file_list() for file in file_list: print(file.file_id, file.name, file.type) ``` -------------------------------- ### Get Default Drive ID Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Access the `default_drive_id` attribute directly to get the ID of the user's default cloud drive. ```python drive_id = ali.default_drive_id ``` -------------------------------- ### Get Drive Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieve detailed information about a specific cloud drive. An optional `drive_id` parameter can be provided to get information for a drive other than the default. ```python # 有一个可选的 `drive_id` 参数 drive = ali.get_drive() ``` -------------------------------- ### Multiple Accounts Configuration Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Demonstrates how to configure and initialize Aligo for multiple accounts by specifying a custom configuration folder and instantiating Aligo with different names. ```python from aligo import set_config_folder, Aligo set_config_folder('/path/to/config') ali1 = Aligo(name='account1') ali2 = Aligo(name='account2') ``` -------------------------------- ### Initialize Aligo Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Instantiate the Aligo client to begin making API calls. ```python from aligo import Aligo ali = Aligo() ``` -------------------------------- ### Get Default Drive ID Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieves the default drive ID for the user. ```APIDOC ## Get Default Drive ID ### Description Retrieves the default drive ID associated with the user's account. ### Method ```python default_drive_id ``` ### Response #### Success Response Returns the default drive ID as a string. ### Response Example ```python drive_id = ali.default_drive_id ``` ``` -------------------------------- ### Initialize Aligo and Send QR Code Source: https://github.com/foyoux/aligo/wiki/发送二维码到邮箱 Initializes the Aligo client with email credentials and retrieves user information. This is a prerequisite for sending QR codes via email. ```python """发送二维码到邮箱""" from aligo import Aligo if __name__ == '__main__': # 详情请查看源码中的文档字符串 ali = Aligo(email=('xxxx@qq.com', '防伪字符串')) user = ali.get_user() print(user.user_id, user.user_name, user.nick_name) ``` -------------------------------- ### Get Drive Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieves details about a specific cloud drive. An optional `drive_id` can be provided. ```APIDOC ## Get Drive Information ### Description Retrieves details about a specific cloud drive. An optional `drive_id` can be provided. ### Method ```python get_drive(drive_id: str = None) ``` ### Parameters #### Query Parameters - **drive_id** (str) - Optional - The ID of the drive to retrieve information for. If not provided, the default drive is used. ### Response #### Success Response Returns a JSON object containing drive information, including `drive_id`, `used_size`, `total_size`, `drive_name`, and `owner`. ### Response Example ```json { "drive_id": "1066884", "used_size": 6998969779282, "total_size": 8480412925952, "drive_name": "Default", "owner": "3e935da769594ca4849c7c1409efb96f", "description": "Created by system", "drive_type": "normal", "creator": "System", "domain_id": "bj29", "status": "enabled", "store_id": "b5e9de389ef241d084733b520ea8b57d", "owner_type": "user", "relative_path": "", "encrypt_mode": "none", "encrypt_data_access": false, "permission": null, "created_at": "2021-02-25T08:16:02.642Z", "subdomain_id": "" } ``` ``` -------------------------------- ### Get Starred List Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Star.md Retrieves a list of all starred or favorite files. Supports sorting and field selection. ```APIDOC ## Get Starred List ### Description Lists all starred/favorite files. This operation allows for sorting the results by various criteria and specifying which fields to return for each file. ### Method GET (Implied by SDK method) ### Endpoint Not explicitly defined, but the SDK method `get_starred_list` interacts with the relevant API endpoint. ### Parameters #### Query Parameters - **drive_id** (str) - Optional - Drive ID to list from. If None, uses default. - **order_by** (GetFileListOrderBy) - Optional - Sort by: `'name'`, `'created_at'`, `'updated_at'`, `'size'`. Defaults to `'created_at'`. - **order_direction** (OrderDirection) - Optional - Sort direction: `'ASC'` or `'DESC'`. Defaults to `'DESC'`. - **fields** (GetStarredListFields) - Optional - Fields to return: `'*'` (all) or `'thumbnail'` (basic fields). Defaults to `'*'`. ### Response #### Success Response - **List[BaseFile]** - A list of file objects, where each file has `starred=True`. #### Response Example ```json [ { "file_id": "file123", "name": "important_document.pdf", "type": "file", "size": 102400, "created_at": 1678886400, "updated_at": 1678886400, "starred": true // ... other fields } ] ``` ``` -------------------------------- ### Proxy Configuration for Aligo Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Shows how to initialize an Aligo instance with specific proxy settings for HTTPS connections. This is useful when operating in environments that require network traffic to be routed through a proxy. ```python from aligo import Aligo ali = Aligo( proxies={"https": "socks5://localhost:10808"} ) ``` -------------------------------- ### Get User Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieves the current user's basic information. This method caches the information and can be refreshed by passing `f5=True`. ```APIDOC ## Get User Information ### Description Retrieves the current user's basic information. This method caches the information and can be refreshed by passing `f5=True`. ### Method ```python get_user(f5: bool = False) ``` ### Parameters #### Query Parameters - **f5** (bool) - Optional - If True, refreshes the cached user information. ### Response #### Success Response Returns a `BaseUser` object containing user details such as `user_name`, `user_id`, `nick_name`, and `created_at`. ### Response Example ```python # Example of BaseUser object structure (fields may vary) class BaseUser: user_name: str user_id: str default_drive_id: str nick_name: str created_at: int # ... other fields ``` ``` -------------------------------- ### List Root Directory Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/File.md List all files and folders in the root directory of the Aliyun Drive. The 'aligo' library must be imported. ```python from aligo import Aligo ali = Aligo() # List root directory file_list = ali.get_file_list() for file in file_list: print(file.name, file.type) ``` -------------------------------- ### Aligo Login with Email Configuration Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Configures Aligo client for email-based login. Requires setting up SMTP details including email address, username, password, host, and port. ```python from aligo import Aligo, EMailConfig email_config = EMailConfig( email='your-email@example.com', user='smtp-username', password='smtp-password', host='smtp.gmail.com', port=587, ) ali = Aligo(email=email_config) ``` -------------------------------- ### Initialize Aligo for Authentication Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/BaseAligo.md Instantiate Aligo to handle authentication. The first instantiation triggers the authentication process. Subsequent instantiations load cached tokens. You can also force re-authentication by providing a new refresh token. ```python from aligo import Aligo # First use - triggers authentication ali = Aligo() # Subsequent uses - loads cached token ali2 = Aligo() # Force re-authentication ali3 = Aligo(refresh_token='new_token') ``` -------------------------------- ### Get Cloud Drive Space Information Source: https://github.com/foyoux/aligo/wiki/获取简单信息 Retrieves information about the user's cloud drive space, including used and total size. ```APIDOC ## Get Cloud Drive Space Information ### Description Retrieves information about the user's cloud drive space, including used and total size. ### Method ```python get_personal_info() ``` ### Response #### Success Response Returns an object containing personal space information, including `used_size` and `total_size`. ### Response Example ```python # Accessing space information personal_info = ali.get_personal_info() used_size = personal_info.personal_space_info.used_size total_size = personal_info.personal_space_info.total_size ``` ``` -------------------------------- ### Sharing Operations Source: https://github.com/foyoux/aligo/wiki/API-概览 APIs for managing file and folder shares, including getting lists, creating, canceling, updating, and retrieving share information. ```APIDOC ## Sharing Operations ### Description APIs for managing file and folder shares, including getting lists, creating, canceling, updating, and retrieving share information. ### Methods - `get_share_list` - `share_file` - `cancel_share` - `batch_cancel_share` - `update_share` - `get_share_info` - `get_share_token` - `get_share_file` - `get_share_file_list` - `share_file_saveto_drive` - `batch_share_file_saveto_drive` - `get_share_link_download_url` ``` -------------------------------- ### Multi-Account Support Source: https://github.com/foyoux/aligo/wiki/登录 Initialize multiple Aligo clients for different accounts by providing a unique 'name' parameter for each. ```python from aligo import Aligo, Auth ali1 = Aligo(name='帐户1') ali2 = Aligo(name='帐户2') ``` -------------------------------- ### 使用 Python logging 模块设置 Aligo 日志级别 Source: https://github.com/foyoux/aligo/wiki/修改日志等级 直接使用 Python 的 `logging` 模块来获取 'aligo' 的 logger 并设置其级别。这是一种更通用的日志配置方式。 ```python import logging from aligo import Aligo if __name__ == '__main__': ali = Aligo() logging.getLogger('aligo').setLevel(logging.ERROR) ``` -------------------------------- ### Switch to Resource Drive Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Drive.md Finds a drive named 'resource' from the list of available drives and sets it as the default for subsequent operations. Prints a message if no resource drive is found. ```python from aligo import Aligo ali = Aligo() # Get resource drive drives = ali.list_my_drives() resource_drive = next((d for d in drives if d.drive_name == 'resource'), None) if resource_drive: # Set as default for operations ali.default_drive_id = resource_drive.drive_id # Now operations use resource drive files = ali.get_file_list() else: print("No resource drive available") ``` -------------------------------- ### Login via Web Scan Source: https://github.com/foyoux/aligo/blob/main/README.md Initialize Aligo with a specified port to enable web-based QR code scanning for login. Access the provided URL in your browser. ```python from aligo import Aligo # 提供 port 参数即可, 之后打开浏览器访问 http://: ali = Aligo(port=8080) ``` -------------------------------- ### Batch Get Multiple Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/File.md Retrieve information for multiple files simultaneously using a list of their IDs. Handles potential retrieval errors for individual files. ```python from aligo import Aligo, Null ali = Aligo() files = ali.batch_get_files(['id1', 'id2', 'id3']) for file in files: if isinstance(file, Null): print('Failed to retrieve this file') else: print(file.name, file.size) ``` -------------------------------- ### Get File using Request Object Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/File.md Retrieve file information by providing a fully constructed GetFileRequest object. This is an alternative to passing file_id and drive_id directly. ```python from aligo import Aligo, GetFileRequest ali = Aligo() # Get file with request object file = ali.get_file(body=GetFileRequest(file_id='file_id_here')) ``` -------------------------------- ### Python aligo 扩展实现文件彻底删除和批量删除 Source: https://github.com/foyoux/aligo/wiki/自定义功能---彻底删除文件 此代码定义了一个 CustomAligo 类,继承自 aligo,增加了单文件彻底删除、批量彻底删除和清空回收站的方法。使用时需要实例化 CustomAligo 类并调用相应方法。 ```python """扩展实现彻底删除文件功能""" import pprint from typing import List from aligo import Aligo, BatchRequest, BatchSubRequest class CustomAligo(Aligo): """自定义 aligo """ V3_FILE_DELETE = '/v3/file/delete' def delete_file(self, file_id: str, drive_id: str = None) -> bool: """删除文件""" drive_id = drive_id or self.default_drive_id response = self.post(self.V3_FILE_DELETE, body={ 'drive_id': drive_id, 'file_id': file_id }) return response.status_code == 204 def batch_delete_files(self, file_id_list: List[str], drive_id: str = None): """批量删除文件""" drive_id = drive_id or self.default_drive_id result = self.batch_request(BatchRequest( requests=[BatchSubRequest( id=file_id, url='/file/delete', body={ 'drive_id': drive_id, 'file_id': file_id } ) for file_id in file_id_list] ), dict) return list(result) def clear_recyclebin(self, drive_id: str = None): """清空回收站""" drive_id = drive_id or self.default_drive_id response = self.post('/v2/recyclebin/clear', body={ 'drive_id': drive_id }) return response.status_code == 202 ali = CustomAligo() # x = ali.delete_file('646604d56d3ee7cfe2654b4as9ed4xse59cf76') # print(x) # 清空回收站 # ll = ali.get_recyclebin_list() # rr = ali.batch_delete_files([f.file_id for f in ll]) # 新的清空回收站方法,异步的 rr = ali.clear_recyclebin() pprint.pprint(rr) ``` -------------------------------- ### Manage Multiple Aligo Accounts Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Shows how to manage multiple Aligo accounts by setting a custom configuration folder and creating separate Aligo instances for each account. Each account's authentication token is stored independently. ```python from aligo import set_config_folder, Aligo # Set custom config directory before creating instances set_config_folder('/home/aligo') # Create separate instances for different accounts ali1 = Aligo(name='account1') ali2 = Aligo(name='account2') # Each account's token is stored separately in config folder ``` -------------------------------- ### 设置 Aligo 认证日志级别 Source: https://github.com/foyoux/aligo/wiki/修改日志等级 通过直接访问 Aligo 实例的认证模块来设置日志级别。使用 `level=100` 来禁用所有日志。 ```python from aligo import Aligo if __name__ == '__main__': ali = Aligo() ali._auth.log.setLevel(level=100) ``` -------------------------------- ### default_drive_id Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Manages the default drive ID for the Aligo client. This property allows you to get the current default drive ID and set a new one for subsequent operations. ```APIDOC ## default_drive_id ### Description Get or set the default drive ID for the current user. This typically refers to the main cloud storage drive. ### Method GET (for retrieving) SET (for setting) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Get default drive ID ali = Aligo() print(ali.default_drive_id) # Set a new default drive ID drives = ali.list_my_drives() resource_drive = [d for d in drives if d.drive_name == 'resource'][0] ali.default_drive_id = resource_drive.drive_id ``` ### Response #### Success Response (200) - **default_drive_id** (str) - The ID of the default drive. #### Response Example ```json "drive-id-string" ``` ``` -------------------------------- ### Move All Files from One Folder to Another Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Move.md Demonstrates how to retrieve all files from a source folder and move them to a destination folder using batch operations. Ensure you have the correct source and destination IDs. ```python from aligo import Aligo ali = Aligo() # Get all files in source folder source_files = ali.get_file_list(parent_file_id='source_id') file_ids = [f.file_id for f in source_files if f.type == 'file'] # Move all to destination if file_ids: ali.batch_move_files(file_ids, 'destination_id') ``` -------------------------------- ### Default QR Code Login Source: https://github.com/foyoux/aligo/wiki/登录 Use this snippet for the default login method by scanning a QR code. It initializes the Aligo client. ```python from aligo import Aligo ali = Aligo() ``` -------------------------------- ### Create Album Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Album.md Creates a new photo album with a specified name and an optional description. ```python from aligo import Aligo ali = Aligo() # Create album album = ali.create_album( name='Vacation 2023', description='Summer vacation photos' ) print(f"Created album: {album.album_id}") ``` -------------------------------- ### Search for Media by Tag Source: https://github.com/foyoux/aligo/blob/main/images/old_readme.md Use the create_by_hash method to search for media files based on their tags. The size parameter should be an integer. ```python x = ali.create_by_hash('壁纸.jpg', content_hash='<图中有>', size='<图中有>') # 注意: size 参数应该是 int 类型, 虽然给 str 也是没有问题的, 但是 Pycharm 可能会黄色警告🤣 ``` -------------------------------- ### 初始化 Aligo 时设置日志级别 Source: https://github.com/foyoux/aligo/wiki/修改日志等级 在创建 Aligo 实例时,通过 `level` 参数直接指定日志级别。例如,使用 `logging.ERROR` 来只显示错误日志。 ```python import logging from aligo import Aligo if __name__ == '__main__': ali = Aligo(level=logging.ERROR) ``` -------------------------------- ### Quick Access to Important Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Star.md Fetches all starred files to quickly access and display important items. Shows the first 10 starred files if any exist. ```python from aligo import Aligo ali = Aligo() # Get all important files important = ali.get_starred_list() if important: print("Your important files:") for file in important[:10]: # Show first 10 print(f" 📌 {file.name}") else: print("No starred files yet") ``` -------------------------------- ### Create Share with Password and Expiration Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Share.md Use this snippet to create a share link for a single file with a password and a specific expiration date. A description can also be provided. ```python from aligo import Aligo ali = Aligo() # Create share with password and expiration share = ali.share_file( file_id='file_id', share_pwd='2020', expiration='2023-12-31T23:59:59.000Z', description='Project document' ) print(f"Link: {share.share_url}") print(f"Password: {share.share_pwd}") ``` -------------------------------- ### create_album Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Album.md Creates a new photo album with a specified name and an optional description. ```APIDOC ## create_album ### Description Create a new photo album. ### Method POST ### Endpoint /albums ### Parameters #### Request Body - **name** (str) - Required - Album name. - **description** (str) - Optional - Album description. ### Response #### Success Response (200) - **BaseAlbum** - Created album object ``` -------------------------------- ### Configure Custom Proxy and Timeout for Aligo Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Aligo.md Sets up custom proxy and request timeout configurations for the Aligo client. It also includes a request interval to manage rate limiting. ```python from aligo import Aligo ali = Aligo( proxies={"https": "socks5://localhost:10808"}, requests_timeout=60, request_interval=1, # 1 second delay between requests to avoid rate limiting ) ``` -------------------------------- ### Aligo Error Handling Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Illustrates how to handle common Aligo exceptions, such as `AligoRefreshFailed` for token expiration and general `AligoException` for other API errors. It shows how to re-initialize Aligo if the token has expired. ```python from aligo import Aligo, AligoException, AligoRefreshFailed ali = Aligo() try: file = ali.get_file('file_id') except AligoRefreshFailed: # Token expired ali = Aligo() except AligoException as e: # Other aligo errors print(f"Error: {e}") ``` -------------------------------- ### File and Folder Operations Source: https://github.com/foyoux/aligo/wiki/API-概览 Provides methods for creating, renaming, moving, copying, retrieving, and listing files and folders. ```APIDOC ## File and Folder Operations ### Description Provides methods for creating, renaming, moving, copying, retrieving, and listing files and folders. ### Methods - `create_folder` - `rename_file` - `batch_rename_files` - `move_file` - `batch_move_files` - `copy_file` - `batch_copy_files` - `get_file` - `batch_get_files` - `get_file_by_path` - `get_file_list` - `get_path` ``` -------------------------------- ### Set Custom Configuration Folder Source: https://github.com/foyoux/aligo/blob/main/README.md Specify a custom directory for storing Aligo configuration files before creating Aligo objects. This allows for managing multiple accounts with separate configuration files. ```python from aligo import set_config_folder, Aligo if __name__ == '__main__': # 创建 Aligo 对象前,先设置配置文件目录,默认是 <用户目录>/.aligo set_config_folder('/home/aligo') # 会创建 /home/aligo/小号1.json 配置文件 ali1 = Aligo(name='小号1') # 会创建 /home/aligo/小号2.json 配置文件 ali2 = Aligo(name='小号2') ``` -------------------------------- ### Custom POST Request with Aligo Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Demonstrates how to make a custom POST request to an Aligo API endpoint using the Aligo client. This is useful for advanced users who need to interact with specific API paths not directly exposed as methods. ```python from aligo import Aligo ali = Aligo() # Use custom POST request response = ali.post( path='v2/file/get', body={'file_id': 'file_id', 'drive_id': None} ) ``` -------------------------------- ### Configure Request Interval Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Set a delay between requests to avoid triggering rate limits. Initialize Aligo with `request_interval`. ```python from aligo import Aligo # Add delay between requests ali = Aligo(request_interval=1) ``` -------------------------------- ### Create Public Share Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Share.md Use this snippet to create a public share link for a single file. The share will not have a password and will not expire. ```python from aligo import Aligo ali = Aligo() # Create public share share = ali.share_file('file_id') print(f"Share link: {share.share_url}") ``` -------------------------------- ### Monitor Storage Across All Drives Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Drive.md Iterates through all available drives, printing their individual usage in GB and percentage. It also calculates and prints the total used space and total capacity across all drives. ```python from aligo import Aligo ali = Aligo() # Get all drives and their usage drives = ali.list_my_drives() total_used = 0 total_capacity = 0 for drive in drives: print(f"\n{drive.drive_name}:") used_gb = drive.used_space / (1024**3) total_gb = drive.total_space / (1024**3) percent = (drive.used_space / drive.total_space) * 100 print(f" {used_gb:.2f} GB / {total_gb:.2f} GB ({percent:.1f}%)") total_used += drive.used_space total_capacity += drive.total_space print(f"\nTotal: {total_used / (1024**3):.2f} GB / {total_capacity / (1024**3):.2f} GB") ``` -------------------------------- ### Check Available Storage Space Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Drive.md Calculates and prints the used percentage and available space in GB. Issues a warning if available space is less than 1 GB. ```python from aligo import Aligo ali = Aligo() drive = ali.get_drive() available = drive.total_space - drive.used_space percent_used = (drive.used_space / drive.total_space) * 100 print(f"Used: {percent_used:.1f}%") print(f"Available: {available / (1024**3):.2f} GB") if available < 1024**9: # Less than 1 GB print("Warning: Low storage space") ``` -------------------------------- ### Handle AligoStatus500 with Retries Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Demonstrates how to handle AligoStatus500 errors by implementing a retry mechanism with exponential backoff. This is crucial for dealing with temporary server issues. ```python from aligo import Aligo, AligoStatus500 import time ali = Aligo() max_retries = 3 for attempt in range(max_retries): try: file = ali.get_file('file_id') break except AligoStatus500: if attempt < max_retries - 1: wait_time = 2 ** attempt print(f"Server error, retrying in {wait_time}s...") time.sleep(wait_time) else: print("Max retries exceeded") raise ``` -------------------------------- ### Manage Existing Share Links Source: https://github.com/foyoux/aligo/blob/main/_autodocs/DOCUMENTATION_INDEX.md This snippet demonstrates how to list, update, and cancel existing share links. Use this to maintain control over shared files. ```python # List shares shares = ali.get_share_list() # Update share ali.update_share(share.share_id, share_pwd='newpwd') # Cancel share ali.cancel_share(share.share_id) ``` -------------------------------- ### Storage Analysis by Importance Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Star.md Calculates and prints the total size of starred files and compares it to the total storage size. Useful for understanding storage distribution. ```python from aligo import Aligo ali = Aligo() # Analyze starred vs normal files starred = ali.get_starred_list() all_files = ali.get_file_list() starred_size = sum(f.size or 0 for f in starred) total_size = sum(f.size or 0 for f in all_files) print(f"Starred: {starred_size / (1024**3):.2f} GB") print(f"Total: {total_size / (1024**3):.2f} GB") print(f"Percentage: {(starred_size / total_size * 100):.1f}%") ``` -------------------------------- ### List Files with Custom Ordering Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/File.md List files with custom sorting criteria, such as creation date in descending order, and a specified limit. Useful for paginating results. ```python from aligo import Aligo ali = Aligo() # List with custom ordering files = ali.get_file_list( order_by='created_at', order_direction='DESC', limit=100 ) ``` -------------------------------- ### Create Share Links for Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/DOCUMENTATION_INDEX.md Generate shareable links for files, with options for setting passwords and expiration dates. This is useful for securely sharing specific files. ```python ali = Aligo() # Simple share share = ali.share_file('file_id') print(share.share_url) # With password share = ali.share_file('file_id', share_pwd='password') # With expiration share = ali.share_file( 'file_id', expiration='2024-12-31T23:59:59.000Z' ) # Multiple files share = ali.share_files(['id1', 'id2'], share_pwd='pwd') ``` -------------------------------- ### Check Drive Capacity and Details Source: https://github.com/foyoux/aligo/blob/main/_autodocs/DOCUMENTATION_INDEX.md Retrieve information about your cloud storage usage, including used space, total capacity, and detailed capacity breakdowns. This is essential for managing your storage. ```python ali = Aligo() # Get default drive drive = ali.get_drive() print(f"Used: {drive.used_space} bytes") print(f"Total: {drive.total_space} bytes") # List all drives drives = ali.list_my_drives() # Capacity details details = ali.drive_capacity_details() ``` -------------------------------- ### Backup Important Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Star.md Copies all starred files to a specified backup folder, creating the folder if it does not exist. Uses auto-rename mode to handle naming conflicts. ```python from aligo import Aligo ali = Aligo() # Get starred files and create backup starred = ali.get_starred_list() # Create backup folder backup = ali.get_folder_by_path('Backups/Important', create_folder=True) # Copy all starred files to backup for file in starred: ali.copy_file( file_id=file.file_id, parent_file_id=backup.file_id, check_name_mode='auto_rename' ) print(f"Backed up {len(starred)} files") ``` -------------------------------- ### Configure Request Timeout Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Increase the timeout for requests to handle slow network conditions. Initialize Aligo with `requests_timeout`. ```python # Increase timeout for slow networks ali = Aligo(requests_timeout=60) ``` -------------------------------- ### Share Multiple Files Together Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Share.md Use this snippet to create a single share link for multiple files. A password can be set for the share. ```python from aligo import Aligo ali = Aligo() # Share multiple files together share = ali.share_files( file_id_list=['id1', 'id2', 'id3'], share_pwd='secret' ) print(share.share_url) ``` -------------------------------- ### Web-Based Login for Aligo Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Configure Aligo to use web-based login by specifying a port. This allows login via a web browser at the specified local address. ```python from aligo import Aligo # Enable web browser login at http://localhost:8080 ali = Aligo(port=8080) ``` -------------------------------- ### List Album Files Source: https://github.com/foyoux/aligo/blob/main/_autodocs/api-reference/Album.md Lists all files contained within a specific album, with an option to specify the sort direction. ```python from aligo import Aligo ali = Aligo() # List album files files = ali.list_album_files('album_id') for file in files: print(f"{file.name} ({file.size} bytes)") ``` -------------------------------- ### Search for Files by Name and Category Source: https://github.com/foyoux/aligo/blob/main/_autodocs/DOCUMENTATION_INDEX.md Find files using various criteria such as filename, category, and sorting options. This helps in locating specific files within your storage. ```python ali = Aligo() # Search by name results = ali.search('filename') # Filter by category images = ali.search('photo', category='image') # Sort results results = ali.search( 'document', order_by='created_at', order_direction='DESC' ) ``` -------------------------------- ### Download Operations Source: https://github.com/foyoux/aligo/wiki/API-概览 Methods for downloading files and folders, and retrieving download URLs. ```APIDOC ## Download Operations ### Description Methods for downloading files and folders, and retrieving download URLs. ### Methods - `download_file` - `download_files` - `download_folder` - `get_download_url` - `batch_download_url` ``` -------------------------------- ### Define AligoShareLinkCreateExceedDailyLimit Class Source: https://github.com/foyoux/aligo/blob/main/_autodocs/errors.md Indicates that the daily limit for creating share links has been exceeded. This exception is triggered when the user has created too many share links within a 24-hour period. ```python class AligoShareLinkCreateExceedDailyLimit(AligoException): """Exceeded daily share link creation limit""" ``` -------------------------------- ### Aligo Search and Organization Source: https://github.com/foyoux/aligo/blob/main/_autodocs/README.md Search for files by name or category, retrieve starred files, and manage the starred status of files. This helps in organizing and quickly accessing important files. ```python from aligo import Aligo ali = Aligo() # Search files results = ali.search('filename', category='image') # Get starred files starred = ali.get_starred_list() # Star a file ali.starred_file('file_id', starred=True) ``` -------------------------------- ### Login with Refresh Token Source: https://github.com/foyoux/aligo/wiki/登录 Use this method if scanning a QR code is inconvenient. Note that the refresh token is typically single-use; remove it after successful login to avoid future failures. ```python from aligo import Aligo # 特别注意:登录完后请在下次使用之前,删除此参数,因为理论上 refresh_token 只能用一次。 # 如果不删除会导致,第二次使用无效的 refresh_token 登录,登录失败,并且可能覆盖第一次录成功的信息 ali = Aligo(refresh_token='') ```