### Run TG Storage Cluster Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Execute the tgstorage command to start the cluster service. Ensure your .env and tokens.txt files are correctly configured in the project directory. ```bash tgstorage ``` -------------------------------- ### Install TG Storage Cluster Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Install the tgstorage-cluster package using pip. Ensure you have Python 3.10 or higher. ```bash pip install tgstorage-cluster ``` -------------------------------- ### Setup Systemd Service for TG Storage Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Configure a Systemd service file to manage the TG Storage background process, ensuring it runs continuously and restarts on failure. Ensure the `ExecStart` path points to your compiled `tgstorage` binary. ```ini [Unit] Description=TG Storage Cluster After=network.target [Service] User=root WorkingDirectory=/path/to/your/project ExecStart=/usr/local/bin/tgstorage Restart=always [Install] WantedBy=multi-user.target ``` ```bash sudo systemctl daemon-reload sudo systemctl enable tgstorage sudo systemctl start tgstorage ``` -------------------------------- ### Python Async File Upload with httpx Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Example of uploading a file asynchronously using Python's `httpx` library. This snippet demonstrates preparing the request, sending it to the TG Storage API, and handling the response. Ensure the `API_URL` and `API_KEY` are correctly configured. ```python import httpx import asyncio import os API_URL = "http://localhost:8082" API_KEY = "my_secure_pass" async def upload_and_share(file_path): if not os.path.exists(file_path): print("❌ File not found!") return async with httpx.AsyncClient(timeout=300) as client: # 1. Prepare Request files = {'file': open(file_path, 'rb')} data = {'expiration_days': 7} # Optional: Auto-delete after 7 days headers = {'X-API-Key': API_KEY} print(f"📤 Uploading {file_path}...") try: # 2. Send Request response = await client.post(f"{API_URL}/upload", files=files, data=data, headers=headers) if response.status_code == 200: result = response.json() print(f"✅ Upload Success!") print(f"📂 File ID: {result['file_id']}") print(f"🔗 Direct Link: {result['direct_link']}") print(f"🌍 Share Link: {result['share_link']}") else: print(f"❌ Upload Failed: {response.text}") except Exception as e: print(f"❌ Error: {e}") if __name__ == "__main__": # Create a dummy file for testing with open("test.txt", "w") as f: f.write("Hello TG Storage!") asyncio.run(upload_and_share("test.txt")) ``` -------------------------------- ### Download File using wget Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Download a file from the TG Storage Cluster using a GET request. Supports HTTP Range requests for streaming. Append ?password=YOUR_PASS if the file is password-protected. ```bash # Direct download wget "http://127.0.0.1:8082/dl/BQACAgQAAx0C.../video.mp4" # With password wget "http://127.0.0.1:8082/dl/BQACAgQAAx0C.../video.mp4?password=12345" ``` -------------------------------- ### Get System Stats using cURL Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Fetch system statistics, including total storage usage, file count, and views, by sending a GET request to the /stats endpoint. ```bash curl "http://127.0.0.1:8082/stats" -H "X-API-Key: my_secure_pass" ``` -------------------------------- ### List Files using cURL Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Retrieve a list of files stored in the TG Storage Cluster using a GET request to the /files endpoint. Supports pagination with limit and offset, and filtering with a search parameter. ```bash curl "http://127.0.0.1:8082/files?limit=10&search=movie" \ -H "X-API-Key: my_secure_pass" ``` -------------------------------- ### Configure TG Storage Cluster (.env) Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Create a .env file to configure the TG Storage Cluster. Required parameters include CHANNEL_ID and ADMIN_API_KEY. Optional settings for server configuration and proxy are also available. ```env # Required CHANNEL_ID=-100xxxxxxxxxx # Your Channel ID ADMIN_API_KEY=my_secure_pass # Master password for the API/Dashboard # Server Config HOST=0.0.0.0 PORT=8082 BASE_URL=https://your-domain.com # Public URL (for generating share links) # Optional Proxy Config (if running on a restricted server) # PROXY_HOST=127.0.0.1 # PROXY_PORT=1080 # PROXY_USER=user # PROXY_PASS=pass ``` -------------------------------- ### Provide Bot Tokens (tokens.txt) Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Create a tokens.txt file and list your Telegram bot API tokens, one per line. This file is used by the cluster to manage uploads. ```text 123456789:ABCdefGHIjklMNOpqrSTUvwxYZ 987654321:ZYXwvuTSRqponMLKjihgfeDCBA ``` -------------------------------- ### Load and Display Files Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Fetches the list of uploaded files and renders them in a table. Handles cases with no files or errors during loading. ```javascript async function loadFiles() { try { const res = await apiFetch('/files'); if (!res.ok) { document.getElementById('files-tbody').innerHTML = `Error loading files: ${res.status}`; return; } const files = await res.json(); const tbody = document.getElementById('files-tbody'); tbody.innerHTML = ''; if (files.length === 0) { tbody.innerHTML = 'No files uploaded yet.'; return; } files.forEach(file => { const isImage = file.mime_type.includes('image'); const rawUrl = `${API_BASE}/f/${file.file_id}/${file.file_name}`; const dlUrl = `${API_BASE}/dl/${file.file_id}/${file.file_name}`; const shareUrl = `${API_BASE}/share/${file.share_token}`; const row = ` ${isImage ? `` : `
📄
`} ${file.file_name}
${file.mime_type} ${(file.file_size / 1024).toFixed(1)} KB ${file.view_count}
View Download
`; tbody.innerHTML += row; }); } catch (e) {} } ``` -------------------------------- ### Generate TG Storage API Keys Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Use the `tgstorage-key` CLI tool to generate API keys for third-party applications. Specify the owner of the new key as an argument. ```bash tgstorage-key --owner "NewApp" ``` -------------------------------- ### List Files Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Retrieves a list of files stored in the TG Storage Cluster, with options for pagination and searching. ```APIDOC ## GET /files ### Description Retrieves a list of files stored in the TG Storage Cluster, with options for pagination and searching. ### Method GET ### Endpoint /files ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of files to return (default: 50). - **offset** (integer) - Optional - The number of files to skip (default: 0). - **search** (string) - Optional - A search term to filter files by name. ### Request Example ```bash curl "http://127.0.0.1:8082/files?limit=10&search=movie" \ -H "X-API-Key: my_secure_pass" ``` ``` -------------------------------- ### Load File Statistics Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Fetches and displays statistics about stored files, including total count, size, and views. Includes basic error handling. ```javascript async function loadStats() { try { const res = await apiFetch('/stats'); const data = await res.json(); document.getElementById('stat-count').innerText = data.total_files; document.getElementById('stat-size').innerText = (data.total_size_bytes / (1024 * 1024)).toFixed(2) + " MB"; document.getElementById('stat-views').innerText = data.total_views; } catch (e) {} } ``` -------------------------------- ### Copy to Clipboard Utility Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html A utility function to copy provided text to the user's clipboard using the Navigator Clipboard API. ```javascript function copyToClipboard(text) { navigator.clipboard.writeText(text).then(() => { alert("Raw link copied to clipboard!"); }); } ``` -------------------------------- ### Load and Save API Key Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Manages the API key stored in local storage. Loads the key on page load and saves it when the user inputs a new one. ```javascript function saveKey() { const key = document.getElementById('api-key').value; localStorage.setItem('tg_api_key', key); loadStats(); loadFiles(); } // Load key on start window.onload = () => { const savedKey = localStorage.getItem('tg_api_key'); if (savedKey) { document.getElementById('api-key').value = savedKey; loadStats(); loadFiles(); } }; ``` -------------------------------- ### Upload File with Node.js (axios) Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Use this snippet for server-side file uploads. Requires 'axios' and 'form-data' packages. Ensure the file exists before attempting to upload. ```javascript const axios = require('axios'); const fs = require('fs'); const FormData = require('form-data'); const path = require('path'); const API_URL = 'http://localhost:8082'; const API_KEY = 'my_secure_pass'; async function uploadFile(filePath) { if (!fs.existsSync(filePath)) { console.error("❌ File not found!"); return; } const form = new FormData(); form.append('file', fs.createReadStream(filePath)); form.append('expiration_days', 7); // Optional // form.append('password', 'secret123'); // Optional try { console.log(`📤 Uploading ${path.basename(filePath)}...`); const response = await axios.post(`${API_URL}/upload`, form, { headers: { ...form.getHeaders(), 'X-API-Key': API_KEY }, maxContentLength: Infinity, maxBodyLength: Infinity // Prevent axios from capping large files }); const data = response.data; console.log('✅ Upload Success!'); console.log(`📂 File ID: ${data.file_id}`); console.log(`🔗 Direct Link: ${data.direct_link}`); console.log(`🌍 Share Link: ${data.share_link}`); } catch (error) { if (error.response) { console.error(`❌ Server Error: ${error.response.status}`, error.response.data); } else { console.error(`❌ Request Error: ${error.message}`); } } } // Run // fs.writeFileSync('test.txt', 'Hello TG Storage Node!'); uploadFile('test.txt'); ``` -------------------------------- ### System Stats Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Retrieves statistics about the TG Storage Cluster, including storage usage, file count, and views. ```APIDOC ## GET /stats ### Description Retrieves statistics about the TG Storage Cluster, including total storage usage, file count, and views. ### Method GET ### Endpoint /stats ### Request Example ```bash curl "http://127.0.0.1:8082/stats" -H "X-API-Key: my_secure_pass" ``` ``` -------------------------------- ### Drag and Drop File Upload Logic Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Implements drag and drop functionality for file uploads. Adds visual feedback during drag over and triggers file upload on drop. ```javascript const dz = document.getElementById('drop-zone'); dz.addEventListener('dragover', (e) => { e.preventDefault(); dz.classList.add('bg-light'); }); dz.addEventListener('dragleave', () => dz.classList.remove('bg-light')); dz.addEventListener('drop', (e) => { e.preventDefault(); dz.classList.remove('bg-light'); const dt = e.dataTransfer; const files = dt.files; handleFileSelect({ target: { files: files } }); }); ``` -------------------------------- ### Configure Nginx Reverse Proxy for TG Storage Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Set up Nginx as a reverse proxy to handle HTTPS, large file uploads, and improve performance. Adjust `client_max_body_size` and timeouts as needed for your file size requirements. Buffering is disabled for efficient streaming. ```nginx server { listen 80; server_name storage.your-domain.com; # Increase body size for large uploads (e.g., 2GB) client_max_body_size 2048M; # Increase timeouts for large file processing proxy_read_timeout 3600s; proxy_send_timeout 3600s; location / { proxy_pass http://127.0.0.1:8082; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Disable buffering for smooth streaming proxy_buffering off; proxy_request_buffering off; } } ``` ```bash sudo ln -s /etc/nginx/sites-available/tgstorage /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl restart nginx ``` -------------------------------- ### Upload File using cURL Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Upload a file to the TG Storage Cluster using a POST request with multipart/form-data. You can specify optional parameters like expiration_days and password. ```bash curl -X POST "http://127.0.0.1:8082/upload" \ -H "X-API-Key: my_secure_pass" \ -F "file=@/path/to/video.mp4" \ -F "expiration_days=7" ``` -------------------------------- ### Handle File Upload Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Handles the selection and upload of a single file using FormData and the API. Provides feedback on upload status. ```javascript async function handleFileSelect(event) { const file = event.target.files[0]; if (!file) return; const formData = new FormData(); formData.append('file', file); const statusDiv = document.getElementById('upload-status'); statusDiv.innerHTML = `
Uploading ${file.name}...
`; try { const res = await apiFetch('/upload', { method: 'POST', body: formData }); const data = await res.json(); if (data.status === 'success') { statusDiv.innerHTML = `
Uploaded! Share Link
`; loadFiles(); loadStats(); } else { statusDiv.innerHTML = `
Error: ${data.detail || 'Upload failed'}
`; } } catch (e) { statusDiv.innerHTML = `
Network Error
`; } } ``` -------------------------------- ### Debug Database Function Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Asynchronously fetches debug information from the database endpoint and displays it as a formatted JSON alert. ```javascript async function debugDB() { const res = await apiFetch('/debug/db'); const data = await res.json(); alert(JSON.stringify(data, null, 2)); } ``` -------------------------------- ### Upload File Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Uploads a file to the TG Storage Cluster. Supports optional expiration and password protection. ```APIDOC ## POST /upload ### Description Uploads a file to the TG Storage Cluster. Supports optional expiration and password protection. ### Method POST ### Endpoint /upload ### Parameters #### Request Body - **file** (File) - Required - The binary file to upload. - **expiration_days** (Int) - Optional - Auto-delete after X days. - **password** (Str) - Optional - Password protect the download link. ### Request Example ```bash curl -X POST "http://127.0.0.1:8082/upload" \ -H "X-API-Key: my_secure_pass" \ -F "file=@/path/to/video.mp4" \ -F "expiration_days=7" ``` ### Response #### Success Response (200) - **status** (str) - Indicates success or failure of the operation. - **file_id** (str) - The unique identifier for the uploaded file. - **direct_link** (str) - A direct link to access the uploaded file. - **share_link** (str) - A shareable link for the uploaded file. #### Response Example ```json { "status": "success", "file_id": "BQACAgQAAx0C...", "direct_link": "https://your-domain.com/dl/BQACAgQAAx0C.../video.mp4", "share_link": "https://your-domain.com/share/v7f897s9f7s98f7" } ``` ``` -------------------------------- ### Upload File with Browser JavaScript Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Use this snippet for client-side file uploads directly from a web browser. It utilizes the Fetch API and FormData. ```javascript const API_URL = "http://localhost:8082"; const API_KEY = "my_secure_pass"; async function uploadFile(fileInput) { const file = fileInput.files[0]; if (!file) return; const formData = new FormData(); formData.append("file", file); formData.append("expiration_days", 7); try { const response = await fetch(`${API_URL}/upload`, { method: "POST", headers: { "X-API-Key": API_KEY }, body: formData }); if (response.ok) { const data = await response.json(); console.log("✅ Uploaded:", data); alert(`File Uploaded! Link: ${data.share_link}`); } else { console.error("Upload failed"); } } catch (error) { console.error("Error:", error); } } ``` -------------------------------- ### Fetch API Data Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Fetches data from a specified API endpoint and parses the JSON response. Handles potential 403 errors by alerting the user. ```javascript async function apiFetch(endpoint, options = {}) { const key = localStorage.getItem('tg_api_key'); options.headers = { ...options.headers, 'X-API-Key': key }; const response = await fetch(`${API_BASE}${endpoint}`, options); if (response.status === 403) alert("Invalid API Key!"); return response; } ``` -------------------------------- ### Download / Stream File Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Downloads or streams a file from the TG Storage Cluster. Supports HTTP Range requests for seekable media. ```APIDOC ## GET /dl/{file_id}/{filename} or /f/{file_id}/{filename} ### Description Downloads or streams a file from the TG Storage Cluster. Supports HTTP Range requests for seekable media. If the file is password-protected, append `?password=YOUR_PASS` to the URL. ### Method GET ### Endpoint /dl/{file_id}/{filename} or /f/{file_id}/{filename} ### Parameters #### Path Parameters - **file_id** (string) - Required - The unique identifier of the file. - **filename** (string) - Required - The name of the file. #### Query Parameters - **password** (string) - Optional - The password for accessing a password-protected file. ### Request Example ```bash # Direct download wget "http://127.0.0.1:8082/dl/BQACAgQAAx0C.../video.mp4" # With password wget "http://127.0.0.1:8082/dl/BQACAgQAAx0C.../video.mp4?password=12345" ``` ``` -------------------------------- ### Delete File Functionality Source: https://github.com/draxonv1/tgstorage/blob/main/src/tgstorage/index.html Deletes a file from the server after user confirmation. Refreshes the file list and stats upon successful deletion. ```javascript async function deleteFile(fileId) { if (!confirm("Are you sure?")) return; const res = await apiFetch(`/file/${fileId}`, { method: 'DELETE' }); if (res.ok) { loadFiles(); loadStats(); } } ``` -------------------------------- ### Delete File using cURL Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Delete a file from both the TG Storage Cluster database and Telegram channel by sending a DELETE request to the /file/{file_id} endpoint. ```bash curl -X DELETE "http://127.0.0.1:8082/file/BQACAgQAAx0C..." \ -H "X-API-Key: my_secure_pass" ``` -------------------------------- ### Delete File Source: https://github.com/draxonv1/tgstorage/blob/main/README.md Deletes a file from both the TG Storage Cluster database and Telegram. ```APIDOC ## DELETE /file/{file_id} ### Description Deletes a file from the TG Storage Cluster database and Telegram. ### Method DELETE ### Endpoint /file/{file_id} ### Parameters #### Path Parameters - **file_id** (string) - Required - The unique identifier of the file to delete. ### Request Example ```bash curl -X DELETE "http://127.0.0.1:8082/file/BQACAgQAAx0C..." \ -H "X-API-Key: my_secure_pass" ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.