teledrive 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Herliansyah <https://github.com/herliansyah/teledrive>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,281 @@
1
+ <div align="center">
2
+
3
+ # ⚡ TeleDrive
4
+
5
+ **High-Capacity Cloud Storage Powered by Telegram MTProto Infrastructure**
6
+
7
+ *Turn your Telegram account into a secure, unlimited personal cloud drive with a Google Drive-like Web Dashboard and CLI.*
8
+
9
+ [![Go Version](https://img.shields.io/badge/Go-1.22%2B-00ADD8?style=flat&logo=go)](https://go.dev/)
10
+ [![Author](https://img.shields.io/badge/Author-Herliansyah-purple?style=flat&logo=github)](https://github.com/herliansyah)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
12
+ [![npm version](https://img.shields.io/npm/v/teledrive.svg?style=flat&logo=npm)](https://www.npmjs.com/package/teledrive)
13
+ [![GitHub](https://img.shields.io/badge/GitHub-herliansyah%2Fteledrive-181717?style=flat&logo=github)](https://github.com/herliansyah/teledrive)
14
+ [![Platform](https://img.shields.io/badge/Platform-Linux%20%7C%20macOS%20%7C%20Windows-blue)](https://github.com/herliansyah/teledrive)
15
+ [![Pure Go](https://img.shields.io/badge/CGO-Zero%20(Pure%20Go)-orange)](https://modernc.org/sqlite)
16
+
17
+ [English](#english) &bull; [Bahasa Indonesia](#bahasa-indonesia)
18
+
19
+ ---
20
+
21
+ </div>
22
+
23
+ <a name="english"></a>
24
+ ## 🌟 English Overview
25
+
26
+ **TeleDrive** is a lightweight, single-binary personal cloud storage bridge. It uses Telegram's distributed cloud infrastructure as an object store via native **MTProto** (`gotd/td`), providing up to **2 GB (Free accounts)** or **4 GB (Premium accounts)** per file transfer, without intermediate disk spooling on your server.
27
+
28
+ ### ✨ Key Features
29
+
30
+ - **🎨 Modern Zero-Build Web Interface**:
31
+ - Dark & Light mode toggle with persistent state in local storage.
32
+ - Dual-view explorer: instant toggle between **Grid View** (visual file cards) and **Table/List View** with instant in-memory column sorting (Name, Size, Modified Date).
33
+ - Floating Upload Manager Drawer at bottom-right with real-time chunk progress (`Chunk 3/8`), minimizable pill state, and sequential safe-mode processing.
34
+ - Crisp embedded Lucide SVG vector icons with zero additional network requests.
35
+ - In-app non-intrusive toast notifications and custom modal dialogs (replacing native browser alerts/prompts).
36
+ - Shared Links Management view in dashboard to audit active links, copy URLs, review downloads, and revoke access.
37
+ - Expanded media and code viewer: seekable video (HTTP 206), audio, image, PDF, and syntax/plain text viewer for code files (`.txt`, `.md`, `.json`, `.go`, `.py`, `.log`).
38
+ - Built-in **Mobile QR Code Generator** on public share links for frictionless smartphone handoff.
39
+ - **📁 Virtual File System**: Full hierarchical folder management (create, rename, move with cycle prevention, delete, search) backed by SQLite with WAL mode.
40
+ - **⚡ Resumable Chunked Upload**: Browser slices files into 5 MB chunks and streams them directly into 512 KB MTProto parts with zero VPS disk wear.
41
+ - **🎬 Instant Media Streaming (HTTP 206 Range)**: Stream and seek large videos, audio, images, and PDFs in real-time without downloading the complete file first.
42
+ - **🔗 Secure Public Share Links**: Generate public links (`/s/:token`) with optional bcrypt password protection and automatic expiration timers.
43
+ - **🛡️ Primary Account Safe Mode (Strict Telegram ToS Compliance)**:
44
+ - Realistic official desktop client telemetry fingerprinting (`PC 64bit`, `Linux/x86_64`, `AppVersion 5.0.0`).
45
+ - Strict sequential single-worker queue (concurrency = 1) mimicking human desktop usage.
46
+ - Adaptive 30ms pacing delay between 512 KB parts.
47
+ - Automated defensive `FLOOD_WAIT_X` backoff without crashing or retrying aggressively.
48
+ - Strictly private Storage Channel (`TeleDrive Vault`) with zero external members.
49
+ - **🔐 Military-Grade Security at Rest**: Telegram MTProto session strings (`auth_key`) are encrypted at rest in SQLite using **AES-256-GCM** with SHA-256 key derivation.
50
+ - **💾 Automated Snapshots & Point-in-Time Restore**: Online SQLite snapshots stored directly in your private Telegram Storage Channel with 5-snapshot rolling retention, 24-hour background scheduler, automated snapshot on graceful shutdown, web-based point-in-time restore, direct `.db.gz` offsite downloads, and local upload-and-restore.
51
+
52
+ ---
53
+
54
+ ### 📥 Pre-built Binary Downloads
55
+
56
+ Download the latest pre-compiled binary for your operating system:
57
+
58
+ | Operating System | Architecture | Binary Archive |
59
+ | :--- | :--- | :--- |
60
+ | **Linux** | x86_64 (amd64) | [`teledrive-v1.0.0-linux-amd64.tar.gz`](dist/teledrive-v1.0.0-linux-amd64.tar.gz) |
61
+ | **Linux** | ARM64 (aarch64) | [`teledrive-v1.0.0-linux-arm64.tar.gz`](dist/teledrive-v1.0.0-linux-arm64.tar.gz) |
62
+ | **macOS** | Apple Silicon (arm64) | [`teledrive-v1.0.0-darwin-arm64.tar.gz`](dist/teledrive-v1.0.0-darwin-arm64.tar.gz) |
63
+ | **macOS** | Intel (amd64) | [`teledrive-v1.0.0-darwin-amd64.tar.gz`](dist/teledrive-v1.0.0-darwin-amd64.tar.gz) |
64
+ | **Windows** | x86_64 (amd64) | [`teledrive-v1.0.0-windows-amd64.tar.gz`](dist/teledrive-v1.0.0-windows-amd64.tar.gz) |
65
+
66
+ *Checksums are verified in [`sha256sums.txt`](dist/sha256sums.txt).*
67
+
68
+ ---
69
+
70
+ ### 🚀 Quick Start Guide
71
+
72
+ #### ⚡ Run Instantly with `npx` (No installation or compiler required!)
73
+
74
+ If you have Node.js installed, you can launch TeleDrive directly without downloading binaries or installing Go:
75
+
76
+ ```bash
77
+ # Pair your Telegram account:
78
+ npx teledrive login
79
+
80
+ # Launch the Web Dashboard:
81
+ npx teledrive server
82
+
83
+ # Or install globally as a system command:
84
+ npm install -g teledrive
85
+ ```
86
+
87
+ ---
88
+
89
+ #### 📦 Or Run the Pre-compiled Binary Directly
90
+
91
+ ##### 1. Setup & Telegram Pairing (First Time Only)
92
+
93
+ Obtain your personal `API_ID` and `API_HASH` from [my.telegram.org](https://my.telegram.org) (Application Type: Desktop). Then run the interactive terminal wizard:
94
+
95
+ ```bash
96
+ ./teledrive login
97
+ ```
98
+
99
+ <div align="center">
100
+ <img src="docs/assets/teledrive-login.png" alt="TeleDrive Login Terminal Wizard" width="600" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); margin: 12px 0;">
101
+ </div>
102
+
103
+ The wizard will guide you through:
104
+ 1. Entering your `API_ID` and `API_HASH`.
105
+ 2. Entering your Telegram phone number.
106
+ 3. Submitting the confirmation code sent to your Telegram app.
107
+ 4. Submitting your 2FA Cloud Password (if enabled).
108
+ 5. Auto-creating the private `TeleDrive Vault` storage channel.
109
+
110
+ > 💡 **New to TeleDrive?** Read the [Full User Guide & How It Works (docs/USER_GUIDE.md)](docs/USER_GUIDE.md) for detailed architecture explanations, visual walkthroughs, and security practices.
111
+
112
+ #### 2. Start the Web Dashboard
113
+
114
+ ```bash
115
+ ./teledrive server
116
+ ```
117
+
118
+ Open your browser and navigate to:
119
+ 👉 **`http://localhost:8080`**
120
+
121
+ - **Default Admin Password**: `admin123` (Change via `TELEDRIVE_ADMIN_PASSWORD`).
122
+
123
+ ---
124
+
125
+ ### 💻 Command-Line Interface (CLI)
126
+
127
+ ```bash
128
+ # Upload a file to TeleDrive
129
+ ./teledrive upload ./sample_video.mp4
130
+
131
+ # Upload to a specific virtual folder
132
+ ./teledrive upload ./report.pdf --folder <folder_id>
133
+
134
+ # Download a file back to your local machine
135
+ ./teledrive download <file_id> --output ./restored_report.pdf
136
+
137
+ # List root folders and files
138
+ ./teledrive list
139
+
140
+ # Create a full SQLite database snapshot and upload it to Telegram
141
+ ./teledrive backup
142
+
143
+ # Restore SQLite database from the pinned snapshot in your Telegram channel
144
+ ./teledrive restore
145
+ ```
146
+
147
+ ---
148
+
149
+ ### ⚙️ Configuration & Environment Variables
150
+
151
+ | Variable | Default | Description |
152
+ | :--- | :--- | :--- |
153
+ | `TELEDRIVE_PORT` | `8080` | HTTP port for the web dashboard |
154
+ | `TELEDRIVE_DB_PATH` | `teledrive.db` | Path to the SQLite database file |
155
+ | `TELEDRIVE_ADMIN_PASSWORD` | `admin123` | Password for admin dashboard login |
156
+ | `TELEDRIVE_SECRET_KEY` | *(auto-generated)* | 32-byte secret key used for AES-256-GCM session encryption |
157
+ | `TELEDRIVE_TG_APP_ID` | *(prompted)* | Telegram App ID from `my.telegram.org` |
158
+ | `TELEDRIVE_TG_APP_HASH` | *(prompted)* | Telegram App Hash from `my.telegram.org` |
159
+
160
+ ---
161
+
162
+ ### 👤 Author & Credits
163
+
164
+ Developed and maintained by **Herliansyah**:
165
+ - **Creator Profile**: [@herliansyah](https://github.com/herliansyah)
166
+ - **Source Code**: [https://github.com/herliansyah/teledrive](https://github.com/herliansyah/teledrive)
167
+ - **License**: Released under the [MIT License](LICENSE). Open-source, free for personal and educational use.
168
+
169
+ <hr style="margin: 40px 0;">
170
+
171
+ <a name="bahasa-indonesia"></a>
172
+ ## 🇮🇩 Panduan Bahasa Indonesia
173
+
174
+ **TeleDrive** adalah jembatan penyimpanan awan (*cloud storage*) berbasis Go (single binary) yang memanfaatkan infrastruktur Telegram sebagai backend penyimpanan melalui protokol resmi **MTProto** (`gotd/td`). Dengan TeleDrive, Anda dapat menikmati kapasitas upload hingga **2 GB (akun reguler)** atau **4 GB (akun Telegram Premium)** per file dengan tampilan web mirip Google Drive.
175
+
176
+ ### 🎯 Fitur Unggulan
177
+
178
+ - **Single Binary Portabel (Zero CGO)**: Kompilasi 100% Pure Go tanpa dependensi compiler C/gcc (`modernc.org/sqlite` dan `gotd/td`).
179
+ - **Antarmuka Web Modern (Zero-Build)**:
180
+ - Dukungan Dark & Light Mode dengan toggle instan dan penyimpanan preferensi di browser.
181
+ - Mode tampilan ganda: **Grid View** (kartu file interaktif) dan **Table/List View** (tabel detail dengan sorting instan Nama, Ukuran, dan Tanggal).
182
+ - Floating Upload Manager Drawer di pojok kanan bawah dengan pemantauan per-chunk progresif (`Chunk 3/8`) dan antrean sekuensial aman dari *Flood Wait*.
183
+ - Ikon vektor modern Lucide SVG resolusi tinggi tanpa penambahan request HTTP.
184
+ - Notifikasi toast dan dialog modal elegan (tanpa `alert`, `confirm`, atau `prompt` bawaan browser).
185
+ - Tab Manajemen Shared Links di dashboard untuk memantau, menyalin URL, dan mencabut (*revoke*) link berbagi aktif.
186
+ - Penampil pratinjau media dan dokumen teks/kode (`.txt`, `.md`, `.json`, `.go`, `.py`, dll).
187
+ - Fitur **QR Code Generator** pada link publik untuk unduhan instan langsung dari smartphone.
188
+ - **Struktur Folder Virtual**: Mengatur hierarki folder, memindahkan file (*move* dengan proteksi siklus), rename, hapus permanen, dan pencarian cepat berbasis SQLite WAL.
189
+ - **Upload Chunked Resumable**: File dipotong menjadi chunk 5MB di browser dan dialirkan langsung ke part 512KB MTProto tanpa memenuhi disk server VPS.
190
+ - **Streaming Media Langsung (HTTP 206)**: Menonton video besar, memutar audio, atau membuka dokumen PDF langsung di browser tanpa perlu mengunduh seluruh file terlebih dahulu.
191
+ - **Link Berbagi Publik (Share Link)**: Buat link publik dengan proteksi password (bcrypt) dan masa berlaku (*expiration timer*).
192
+ - **Safe Mode Kepatuhan ToS (Aman untuk Akun Utama)**:
193
+ - Menggunakan telemetri perangkat resmi (`PC 64bit`, `Linux/x86_64`, `AppVersion 5.0.0`).
194
+ - Antrean upload strictly 1 koneksi aktif pada satu waktu (meniru aplikasi resmi Telegram Desktop).
195
+ - Jeda adaptif 30ms antar-part untuk menjaga koneksi tetap dingin.
196
+ - Penanganan jeda otomatis `FLOOD_WAIT` dari server Telegram.
197
+ - Channel storage berstatus **Private** dan terisolasi (0 anggota luar).
198
+ - **Keamanan Data**: Kunci session string MTProto dienkripsi menggunakan algoritma **AES-256-GCM** sebelum disimpan di database.
199
+ - **Disaster Recovery & Snapshots**: Snapshot online SQLite otomatis (setiap 24 jam dan saat shutdown) tersimpan di Telegram Storage Channel dengan retensi bergulir 5 snapshot, riwayat snapshot di dashboard web, pemulihan point-in-time, serta unduh dan unggah backup database lokal (`teledrive backup` & `teledrive restore`).
200
+
201
+ ---
202
+
203
+ ### 🚀 Cara Penggunaan Singkat
204
+
205
+ #### ⚡ Jalankan Instan dengan `npx` (Tanpa install Go / unduh manual)
206
+
207
+ Jika di komputer Anda sudah terpasang Node.js, Anda bisa langsung menjalankan TeleDrive dalam hitungan detik:
208
+
209
+ ```bash
210
+ # Pasangkan akun Telegram Anda:
211
+ npx teledrive login
212
+
213
+ # Jalankan server Web Dashboard:
214
+ npx teledrive server
215
+
216
+ # Atau instal secara global di sistem:
217
+ npm install -g teledrive
218
+ ```
219
+
220
+ ---
221
+
222
+ #### 📦 Atau Jalankan Binary Kompilasi Langsung
223
+
224
+ ##### 1. Pasangkan Akun Telegram Anda (Login Pertama Kali)
225
+ Dapatkan `API_ID` dan `API_HASH` Anda dari [my.telegram.org](https://my.telegram.org), lalu jalankan:
226
+ ```bash
227
+ ./teledrive login
228
+ ```
229
+
230
+ <div align="center">
231
+ <img src="docs/assets/teledrive-login.png" alt="Wizard Login Terminal TeleDrive" width="600" style="border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.15); margin: 12px 0;">
232
+ </div>
233
+
234
+ Ikuti petunjuk di layar untuk memasukkan nomor telepon, kode OTP dari Telegram, dan password 2FA Anda.
235
+
236
+ > 💡 **Butuh panduan lengkap dan penjelasan cara kerja sistem?** Baca [Panduan Pengguna Lengkap & Cara Kerja (docs/USER_GUIDE.md)](docs/USER_GUIDE.md).
237
+
238
+ #### 2. Jalankan Server Web Dashboard
239
+ ```bash
240
+ ./teledrive server
241
+ ```
242
+ Buka browser di **`http://localhost:8080`** (Password admin: `admin123`).
243
+
244
+ #### 3. Perintah Terminal (CLI)
245
+ ```bash
246
+ # Mengunggah file
247
+ ./teledrive upload ./laporan.pdf
248
+
249
+ # Menampilkan daftar file dan folder
250
+ ./teledrive list
251
+
252
+ # Mengunduh kembali file ke komputer
253
+ ./teledrive download <file_id> --output ./hasil.pdf
254
+
255
+ # Cadangkan database metadata ke Telegram
256
+ ./teledrive backup
257
+
258
+ # Pulihkan database dari Telegram jika pindah server
259
+ ./teledrive restore
260
+ ```
261
+
262
+ ---
263
+
264
+ ### 📚 Dokumentasi Teknis Lanjutan
265
+
266
+ - [docs/USER_GUIDE.md](docs/USER_GUIDE.md) — Panduan lengkap pengguna, arsitektur, dan cara kerja TeleDrive.
267
+ - [CONTEXT.md](CONTEXT.md) — Glosarium kanonik konsep domain TeleDrive.
268
+ - [ARCHITECTURE.md](ARCHITECTURE.md) — Diagram alur data upload, streaming HTTP 206, dan skema SQLite.
269
+ - [SECURITY.md](SECURITY.md) — Panduan keamanan, enkripsi session, dan mitigasi banned Telegram.
270
+ - [MILESTONES.md](MILESTONES.md) — Rincian tahapan pengembangan dan verifikasi.
271
+ - [docs/adr/](docs/adr/) — Arsip Catatan Keputusan Arsitektur (*Architectural Decision Records*).
272
+
273
+ ---
274
+
275
+ ### 👤 Pembuat & Lisensi
276
+
277
+ Diciptakan dan dikembangkan oleh **Herliansyah**:
278
+ - **Profil GitHub**: [@herliansyah](https://github.com/herliansyah)
279
+ - **Repositori Resmi**: [https://github.com/herliansyah/teledrive](https://github.com/herliansyah/teledrive)
280
+ - **Lisensi**: Didistribusikan di bawah [Lisensi MIT](LICENSE). Bebas digunakan, dipelajari, dan dimodifikasi untuk keperluan personal maupun edukasi.
281
+
@@ -0,0 +1,186 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * TeleDrive CLI / Server Runner
5
+ * Official Node.js binary wrapper for TeleDrive
6
+ * Zero external dependencies.
7
+ */
8
+
9
+ const { spawnSync } = require('node:child_process');
10
+ const fs = require('node:fs');
11
+ const https = require('node:https');
12
+ const os = require('node:os');
13
+ const path = require('node:path');
14
+
15
+ const VERSION = '1.2.0';
16
+
17
+ // Map process.platform to TeleDrive release platform name
18
+ const PLATFORM_MAP = {
19
+ linux: 'linux',
20
+ darwin: 'darwin',
21
+ win32: 'windows'
22
+ };
23
+
24
+ // Map process.arch to TeleDrive release architecture name
25
+ const ARCH_MAP = {
26
+ x64: 'amd64',
27
+ arm64: 'arm64'
28
+ };
29
+
30
+ function getBinaryName() {
31
+ return process.platform === 'win32' ? 'teledrive.exe' : 'teledrive';
32
+ }
33
+
34
+ function getCacheDir() {
35
+ const custom = process.env.TELEDRIVE_CACHE_DIR;
36
+ if (custom) return custom;
37
+
38
+ if (process.platform === 'win32') {
39
+ return path.join(process.env.LOCALAPPDATA || os.homedir(), 'teledrive', 'bin');
40
+ }
41
+ return path.join(os.homedir(), '.cache', 'teledrive', 'bin');
42
+ }
43
+
44
+ function findLocalBinary() {
45
+ // 1. Explicit environment override
46
+ if (process.env.TELEDRIVE_BINARY_PATH && fs.existsSync(process.env.TELEDRIVE_BINARY_PATH)) {
47
+ return process.env.TELEDRIVE_BINARY_PATH;
48
+ }
49
+
50
+ // 2. Local cache directory
51
+ const cached = path.join(getCacheDir(), `teledrive-v${VERSION}${process.platform === 'win32' ? '.exe' : ''}`);
52
+ if (fs.existsSync(cached)) {
53
+ return cached;
54
+ }
55
+
56
+ // 3. Local repo root binary (if running inside git clone)
57
+ const repoBin = path.join(__dirname, '..', getBinaryName());
58
+ if (fs.existsSync(repoBin)) {
59
+ return repoBin;
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ function downloadUrl(url, destPath) {
66
+ return new Promise((resolve, reject) => {
67
+ const options = {
68
+ headers: {
69
+ 'User-Agent': `teledrive-npm-wrapper/${VERSION}`
70
+ }
71
+ };
72
+ if (process.env.GITHUB_TOKEN) {
73
+ options.headers['Authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`;
74
+ }
75
+
76
+ const request = https.get(url, options, (res) => {
77
+ // Handle redirects (GitHub Releases redirect to AWS S3/CDN)
78
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
79
+ return downloadUrl(res.headers.location, destPath).then(resolve).catch(reject);
80
+ }
81
+
82
+ if (res.statusCode !== 200) {
83
+ return reject(new Error(`Server returned HTTP ${res.statusCode} (${res.statusMessage})`));
84
+ }
85
+
86
+ const fileStream = fs.createWriteStream(destPath);
87
+ res.pipe(fileStream);
88
+ fileStream.on('finish', () => {
89
+ fileStream.close(() => resolve(destPath));
90
+ });
91
+ fileStream.on('error', (err) => {
92
+ fs.unlink(destPath, () => reject(err));
93
+ });
94
+ });
95
+
96
+ request.on('error', (err) => {
97
+ fs.unlink(destPath, () => reject(err));
98
+ });
99
+ });
100
+ }
101
+
102
+ async function ensureBinary() {
103
+ const existing = findLocalBinary();
104
+ if (existing) return existing;
105
+
106
+ const platform = PLATFORM_MAP[process.platform];
107
+ const arch = ARCH_MAP[process.arch];
108
+
109
+ if (!platform || !arch) {
110
+ throw new Error(`Unsupported platform or architecture: ${process.platform}-${process.arch}`);
111
+ }
112
+
113
+ const cacheDir = getCacheDir();
114
+ fs.mkdirSync(cacheDir, { recursive: true });
115
+
116
+ const binTarget = path.join(cacheDir, `teledrive-v${VERSION}${process.platform === 'win32' ? '.exe' : ''}`);
117
+ const archiveName = `teledrive-v${VERSION}-${platform}-${arch}.tar.gz`;
118
+ const downloadArchive = path.join(cacheDir, archiveName);
119
+ const releaseUrl = `https://github.com/herliansyah/teledrive/releases/download/v${VERSION}/${archiveName}`;
120
+
121
+ console.log(`[teledrive] Binary not found locally. Downloading TeleDrive v${VERSION} for ${platform}/${arch}...`);
122
+
123
+ try {
124
+ await downloadUrl(releaseUrl, downloadArchive);
125
+
126
+ // Extract using system tar
127
+ const extractResult = spawnSync('tar', ['-xzf', downloadArchive, '-C', cacheDir], { stdio: 'inherit' });
128
+ if (extractResult.status !== 0) {
129
+ throw new Error(`tar extraction failed with exit code ${extractResult.status}`);
130
+ }
131
+
132
+ // Clean up archive
133
+ try { fs.unlinkSync(downloadArchive); } catch (_) {}
134
+
135
+ // In archive, the binary is named 'teledrive' (or 'teledrive.exe')
136
+ const extractedBin = path.join(cacheDir, getBinaryName());
137
+ if (extractedBin !== binTarget && fs.existsSync(extractedBin)) {
138
+ fs.renameSync(extractedBin, binTarget);
139
+ }
140
+
141
+ if (process.platform !== 'win32') {
142
+ fs.chmodSync(binTarget, 0o755);
143
+ }
144
+
145
+ console.log(`[teledrive] Successfully cached binary at: ${binTarget}`);
146
+ return binTarget;
147
+ } catch (err) {
148
+ // Attempt build fallback if go is installed
149
+ console.warn(`[teledrive] Download failed: ${err.message}`);
150
+ const goCheck = spawnSync('go', ['version'], { stdio: 'pipe' });
151
+ if (goCheck.status === 0) {
152
+ console.log(`[teledrive] Go compiler detected. Attempting to build binary locally...`);
153
+ const repoRoot = path.join(__dirname, '..');
154
+ const buildRes = spawnSync('go', ['build', '-o', binTarget, './cmd/teledrive'], {
155
+ cwd: repoRoot,
156
+ stdio: 'inherit'
157
+ });
158
+ if (buildRes.status === 0 && fs.existsSync(binTarget)) {
159
+ console.log(`[teledrive] Local build succeeded!`);
160
+ return binTarget;
161
+ }
162
+ }
163
+
164
+ throw new Error(
165
+ `Could not obtain TeleDrive binary for ${platform}-${arch}.\n` +
166
+ `URL: ${releaseUrl}\n` +
167
+ `Details: ${err.message}\n\n` +
168
+ `You can manually place the binary at:\n ${binTarget}\n` +
169
+ `Or set TELEDRIVE_BINARY_PATH=/path/to/teledrive`
170
+ );
171
+ }
172
+ }
173
+
174
+ async function main() {
175
+ try {
176
+ const binPath = await ensureBinary();
177
+ const args = process.argv.slice(2);
178
+ const result = spawnSync(binPath, args, { stdio: 'inherit' });
179
+ process.exit(result.status ?? 0);
180
+ } catch (err) {
181
+ console.error(`[teledrive error] ${err.message}`);
182
+ process.exit(1);
183
+ }
184
+ }
185
+
186
+ main();
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "teledrive",
3
+ "version": "1.2.0",
4
+ "description": "High-Capacity Cloud Storage Powered by Telegram MTProto Infrastructure",
5
+ "main": "bin/teledrive.js",
6
+ "bin": {
7
+ "teledrive": "bin/teledrive.js"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "engines": {
15
+ "node": ">=16.0.0"
16
+ },
17
+ "keywords": [
18
+ "telegram",
19
+ "cloud-storage",
20
+ "drive",
21
+ "mtproto",
22
+ "file-manager",
23
+ "cli",
24
+ "self-hosted",
25
+ "web-drive"
26
+ ],
27
+ "author": "Herliansyah (https://github.com/herliansyah)",
28
+ "license": "MIT",
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/herliansyah/teledrive.git"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/herliansyah/teledrive/issues"
35
+ },
36
+ "homepage": "https://github.com/herliansyah/teledrive#readme",
37
+ "publishConfig": {
38
+ "access": "public"
39
+ }
40
+ }