drivekit 1.0.2 → 1.1.1
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/dist/cli.cjs +1300 -33
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1300 -31
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1302 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +294 -1
- package/dist/index.d.ts +294 -1
- package/dist/index.js +1320 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
4
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
5
|
+
}) : x)(function(x) {
|
|
6
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
7
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
8
|
+
});
|
|
3
9
|
var __esm = (fn, res) => function __init() {
|
|
4
10
|
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
5
11
|
};
|
|
@@ -298,11 +304,13 @@ var init_path_resolver = __esm({
|
|
|
298
304
|
cache = /* @__PURE__ */ new Map();
|
|
299
305
|
cacheTTL;
|
|
300
306
|
enableCache;
|
|
307
|
+
metadataCache;
|
|
301
308
|
constructor(drive2, rootFolderId = "root", options) {
|
|
302
309
|
this.drive = drive2;
|
|
303
310
|
this.rootFolderId = rootFolderId;
|
|
304
311
|
this.enableCache = options?.enableCache ?? true;
|
|
305
312
|
this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
|
|
313
|
+
this.metadataCache = options?.metadataCache;
|
|
306
314
|
}
|
|
307
315
|
/**
|
|
308
316
|
* Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
|
|
@@ -317,21 +325,31 @@ var init_path_resolver = __esm({
|
|
|
317
325
|
/**
|
|
318
326
|
* Gets cache key for a path
|
|
319
327
|
*/
|
|
320
|
-
getCacheKey(
|
|
321
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
328
|
+
getCacheKey(path10) {
|
|
329
|
+
return `${this.rootFolderId}:${this.normalizePath(path10)}`;
|
|
322
330
|
}
|
|
323
331
|
/**
|
|
324
332
|
* Clears the path cache
|
|
325
333
|
*/
|
|
326
334
|
clearCache() {
|
|
327
335
|
this.cache.clear();
|
|
336
|
+
if (this.metadataCache) {
|
|
337
|
+
this.metadataCache.clear();
|
|
338
|
+
}
|
|
328
339
|
}
|
|
329
340
|
/**
|
|
330
341
|
* Invalidate a single path from cache
|
|
331
342
|
*/
|
|
332
|
-
invalidatePath(
|
|
333
|
-
const
|
|
343
|
+
invalidatePath(path10) {
|
|
344
|
+
const norm = this.normalizePath(path10);
|
|
345
|
+
const key = this.getCacheKey(norm);
|
|
334
346
|
this.cache.delete(key);
|
|
347
|
+
if (this.metadataCache) {
|
|
348
|
+
const item = this.metadataCache.getByPath(norm);
|
|
349
|
+
if (item) {
|
|
350
|
+
this.metadataCache.deleteFile(item.id);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
335
353
|
}
|
|
336
354
|
/**
|
|
337
355
|
* Resolves a path to a Google Drive item (file or folder).
|
|
@@ -347,6 +365,17 @@ var init_path_resolver = __esm({
|
|
|
347
365
|
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
|
|
348
366
|
};
|
|
349
367
|
}
|
|
368
|
+
if (this.metadataCache) {
|
|
369
|
+
const persistentCached = this.metadataCache.getByPath(norm);
|
|
370
|
+
if (persistentCached) {
|
|
371
|
+
return {
|
|
372
|
+
id: persistentCached.id,
|
|
373
|
+
name: persistentCached.name,
|
|
374
|
+
isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
375
|
+
mimeType: persistentCached.mimeType
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
}
|
|
350
379
|
if (this.enableCache) {
|
|
351
380
|
const cached = this.cache.get(this.getCacheKey(norm));
|
|
352
381
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -365,6 +394,21 @@ var init_path_resolver = __esm({
|
|
|
365
394
|
const segment = segments[i];
|
|
366
395
|
const isLast = i === segments.length - 1;
|
|
367
396
|
currentPath += `/${segment}`;
|
|
397
|
+
if (this.metadataCache) {
|
|
398
|
+
const pCached = this.metadataCache.getByPath(currentPath);
|
|
399
|
+
if (pCached) {
|
|
400
|
+
currentParentId = pCached.id;
|
|
401
|
+
if (isLast) {
|
|
402
|
+
return {
|
|
403
|
+
id: pCached.id,
|
|
404
|
+
name: pCached.name,
|
|
405
|
+
isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
406
|
+
mimeType: pCached.mimeType
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
continue;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
368
412
|
if (this.enableCache) {
|
|
369
413
|
const cached = this.cache.get(this.getCacheKey(currentPath));
|
|
370
414
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -408,7 +452,18 @@ var init_path_resolver = __esm({
|
|
|
408
452
|
file = sharedResponse.data.files?.[0];
|
|
409
453
|
}
|
|
410
454
|
if (file && file.id) {
|
|
455
|
+
const segmentParentId = currentParentId;
|
|
411
456
|
currentParentId = file.id;
|
|
457
|
+
if (this.metadataCache) {
|
|
458
|
+
this.metadataCache.upsertFile({
|
|
459
|
+
id: file.id,
|
|
460
|
+
name: file.name || segment,
|
|
461
|
+
mimeType: file.mimeType || "",
|
|
462
|
+
parentId: segmentParentId,
|
|
463
|
+
path: currentPath,
|
|
464
|
+
trashed: false
|
|
465
|
+
});
|
|
466
|
+
}
|
|
412
467
|
if (this.enableCache) {
|
|
413
468
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
414
469
|
id: file.id,
|
|
@@ -442,7 +497,18 @@ var init_path_resolver = __esm({
|
|
|
442
497
|
if (!newFolder.id) {
|
|
443
498
|
throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
|
|
444
499
|
}
|
|
500
|
+
const segmentParentId = currentParentId;
|
|
445
501
|
currentParentId = newFolder.id;
|
|
502
|
+
if (this.metadataCache) {
|
|
503
|
+
this.metadataCache.upsertFile({
|
|
504
|
+
id: newFolder.id,
|
|
505
|
+
name: segment,
|
|
506
|
+
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
507
|
+
parentId: segmentParentId,
|
|
508
|
+
path: currentPath,
|
|
509
|
+
trashed: false
|
|
510
|
+
});
|
|
511
|
+
}
|
|
446
512
|
if (this.enableCache) {
|
|
447
513
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
448
514
|
id: newFolder.id,
|
|
@@ -919,6 +985,24 @@ var init_downloader = __esm({
|
|
|
919
985
|
size: totalBytes
|
|
920
986
|
};
|
|
921
987
|
}
|
|
988
|
+
/**
|
|
989
|
+
* Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
|
|
990
|
+
*/
|
|
991
|
+
async createReadStream(fileId, options) {
|
|
992
|
+
const headers = {};
|
|
993
|
+
if (options?.start !== void 0 || options?.end !== void 0) {
|
|
994
|
+
const start = options.start ?? 0;
|
|
995
|
+
const end = options.end !== void 0 ? options.end : "";
|
|
996
|
+
headers["Range"] = `bytes=${start}-${end}`;
|
|
997
|
+
}
|
|
998
|
+
const res = await withRetry(async () => {
|
|
999
|
+
return await this.drive.files.get(
|
|
1000
|
+
{ fileId, alt: "media", supportsAllDrives: true },
|
|
1001
|
+
{ responseType: "stream", headers }
|
|
1002
|
+
);
|
|
1003
|
+
});
|
|
1004
|
+
return res.data;
|
|
1005
|
+
}
|
|
922
1006
|
};
|
|
923
1007
|
}
|
|
924
1008
|
});
|
|
@@ -1047,6 +1131,19 @@ var init_query_builder = __esm({
|
|
|
1047
1131
|
this.conditions.push(`(${condition})`);
|
|
1048
1132
|
return this;
|
|
1049
1133
|
}
|
|
1134
|
+
/**
|
|
1135
|
+
* Custom raw query condition (alias for raw)
|
|
1136
|
+
*/
|
|
1137
|
+
custom(condition) {
|
|
1138
|
+
return this.raw(condition);
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* Filter: Exact MD5 checksum match
|
|
1142
|
+
*/
|
|
1143
|
+
md5(checksum) {
|
|
1144
|
+
this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
|
|
1145
|
+
return this;
|
|
1146
|
+
}
|
|
1050
1147
|
/**
|
|
1051
1148
|
* Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
|
|
1052
1149
|
*/
|
|
@@ -1093,6 +1190,12 @@ var init_query_builder = __esm({
|
|
|
1093
1190
|
});
|
|
1094
1191
|
return res.data.files || [];
|
|
1095
1192
|
}
|
|
1193
|
+
/**
|
|
1194
|
+
* Executes query and returns array of matching files (alias for list)
|
|
1195
|
+
*/
|
|
1196
|
+
async execute() {
|
|
1197
|
+
return await this.list();
|
|
1198
|
+
}
|
|
1096
1199
|
/**
|
|
1097
1200
|
* Returns the first matching file, or null if not found
|
|
1098
1201
|
*/
|
|
@@ -1734,6 +1837,22 @@ var init_resource_refs = __esm({
|
|
|
1734
1837
|
async getLink() {
|
|
1735
1838
|
return await this.drive.getShareableLink(this.pathOrId);
|
|
1736
1839
|
}
|
|
1840
|
+
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
1841
|
+
async createReadStream(options) {
|
|
1842
|
+
return await this.drive.createReadStream(this.pathOrId, options);
|
|
1843
|
+
}
|
|
1844
|
+
/** Grants access to a specific email with custom role and notification */
|
|
1845
|
+
async grantAccess(options) {
|
|
1846
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
1847
|
+
}
|
|
1848
|
+
/** Revokes access by permission ID or user email */
|
|
1849
|
+
async revokeAccess(permissionIdOrEmail) {
|
|
1850
|
+
return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
|
|
1851
|
+
}
|
|
1852
|
+
/** Lists all granted permissions on this file */
|
|
1853
|
+
async listPermissions() {
|
|
1854
|
+
return await this.drive.listPermissions(this.pathOrId);
|
|
1855
|
+
}
|
|
1737
1856
|
};
|
|
1738
1857
|
DriveFolderRef = class {
|
|
1739
1858
|
drive;
|
|
@@ -1771,11 +1890,21 @@ var init_resource_refs = __esm({
|
|
|
1771
1890
|
async watch(options = {}) {
|
|
1772
1891
|
return await this.drive.watch(this.pathOrId, options);
|
|
1773
1892
|
}
|
|
1893
|
+
/** Grants access to this entire folder */
|
|
1894
|
+
async grantAccess(options) {
|
|
1895
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
1896
|
+
}
|
|
1897
|
+
/** Creates a writable stream directly into a file inside this folder */
|
|
1898
|
+
async createWriteStream(fileName, options) {
|
|
1899
|
+
const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
|
|
1900
|
+
return await this.drive.createWriteStream(targetPath, options);
|
|
1901
|
+
}
|
|
1774
1902
|
};
|
|
1775
1903
|
}
|
|
1776
1904
|
});
|
|
1777
1905
|
|
|
1778
1906
|
// src/core/plugins.ts
|
|
1907
|
+
import path5 from "path";
|
|
1779
1908
|
var PluginManager;
|
|
1780
1909
|
var init_plugins = __esm({
|
|
1781
1910
|
"src/core/plugins.ts"() {
|
|
@@ -1783,10 +1912,36 @@ var init_plugins = __esm({
|
|
|
1783
1912
|
init_esm_shims();
|
|
1784
1913
|
PluginManager = class {
|
|
1785
1914
|
plugins = [];
|
|
1915
|
+
/**
|
|
1916
|
+
* Register a plugin. If a plugin with the same name already exists,
|
|
1917
|
+
* it replaces the old one to avoid duplicate side-effects.
|
|
1918
|
+
*/
|
|
1786
1919
|
use(plugin) {
|
|
1920
|
+
this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
|
|
1787
1921
|
this.plugins.push(plugin);
|
|
1788
1922
|
return this;
|
|
1789
1923
|
}
|
|
1924
|
+
/**
|
|
1925
|
+
* Unregister a plugin by its name.
|
|
1926
|
+
* Returns true if a plugin was found and removed, false otherwise.
|
|
1927
|
+
*/
|
|
1928
|
+
unuse(pluginName) {
|
|
1929
|
+
const initialLen = this.plugins.length;
|
|
1930
|
+
this.plugins = this.plugins.filter((p) => p.name !== pluginName);
|
|
1931
|
+
return this.plugins.length < initialLen;
|
|
1932
|
+
}
|
|
1933
|
+
/**
|
|
1934
|
+
* Check if a plugin with given name is currently active
|
|
1935
|
+
*/
|
|
1936
|
+
has(pluginName) {
|
|
1937
|
+
return this.plugins.some((p) => p.name === pluginName);
|
|
1938
|
+
}
|
|
1939
|
+
/**
|
|
1940
|
+
* Returns all currently registered plugins
|
|
1941
|
+
*/
|
|
1942
|
+
getPlugins() {
|
|
1943
|
+
return [...this.plugins];
|
|
1944
|
+
}
|
|
1790
1945
|
async runBeforeUpload(options) {
|
|
1791
1946
|
let current = { ...options };
|
|
1792
1947
|
for (const plugin of this.plugins) {
|
|
@@ -1831,13 +1986,702 @@ var init_plugins = __esm({
|
|
|
1831
1986
|
}
|
|
1832
1987
|
});
|
|
1833
1988
|
|
|
1989
|
+
// src/core/cache.ts
|
|
1990
|
+
import os from "os";
|
|
1991
|
+
import path6 from "path";
|
|
1992
|
+
import fs5 from "fs";
|
|
1993
|
+
var SqliteMetadataCache, MemoryMetadataCache;
|
|
1994
|
+
var init_cache = __esm({
|
|
1995
|
+
"src/core/cache.ts"() {
|
|
1996
|
+
"use strict";
|
|
1997
|
+
init_esm_shims();
|
|
1998
|
+
SqliteMetadataCache = class {
|
|
1999
|
+
db = null;
|
|
2000
|
+
dbPath;
|
|
2001
|
+
initialized = false;
|
|
2002
|
+
fallbackMemory;
|
|
2003
|
+
constructor(customPath) {
|
|
2004
|
+
if (customPath) {
|
|
2005
|
+
this.dbPath = customPath;
|
|
2006
|
+
} else {
|
|
2007
|
+
const dir = path6.join(os.homedir(), ".drivekit");
|
|
2008
|
+
if (!fs5.existsSync(dir)) {
|
|
2009
|
+
try {
|
|
2010
|
+
fs5.mkdirSync(dir, { recursive: true });
|
|
2011
|
+
} catch {
|
|
2012
|
+
}
|
|
2013
|
+
}
|
|
2014
|
+
this.dbPath = path6.join(dir, "cache.db");
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
init() {
|
|
2018
|
+
if (this.initialized) return;
|
|
2019
|
+
try {
|
|
2020
|
+
const { DatabaseSync } = __require("sqlite");
|
|
2021
|
+
if (!DatabaseSync) {
|
|
2022
|
+
throw new Error("DatabaseSync not available");
|
|
2023
|
+
}
|
|
2024
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
2025
|
+
this.db.exec(`
|
|
2026
|
+
PRAGMA journal_mode = WAL;
|
|
2027
|
+
PRAGMA synchronous = NORMAL;
|
|
2028
|
+
|
|
2029
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
2030
|
+
id TEXT PRIMARY KEY,
|
|
2031
|
+
name TEXT NOT NULL,
|
|
2032
|
+
mimeType TEXT,
|
|
2033
|
+
size INTEGER,
|
|
2034
|
+
parentId TEXT,
|
|
2035
|
+
path TEXT,
|
|
2036
|
+
md5Checksum TEXT,
|
|
2037
|
+
trashed INTEGER DEFAULT 0,
|
|
2038
|
+
modifiedTime TEXT,
|
|
2039
|
+
updatedAt INTEGER
|
|
2040
|
+
);
|
|
2041
|
+
|
|
2042
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
2043
|
+
key TEXT PRIMARY KEY,
|
|
2044
|
+
value TEXT NOT NULL
|
|
2045
|
+
);
|
|
2046
|
+
|
|
2047
|
+
CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
|
|
2048
|
+
CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
|
|
2049
|
+
CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
|
|
2050
|
+
CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
|
|
2051
|
+
`);
|
|
2052
|
+
this.initialized = true;
|
|
2053
|
+
} catch (err) {
|
|
2054
|
+
this.fallbackMemory = new MemoryMetadataCache();
|
|
2055
|
+
this.fallbackMemory.init();
|
|
2056
|
+
this.initialized = true;
|
|
2057
|
+
this.db = null;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
getById(id) {
|
|
2061
|
+
if (this.fallbackMemory) return this.fallbackMemory.getById(id);
|
|
2062
|
+
if (!this.initialized || !this.db) return null;
|
|
2063
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
|
|
2064
|
+
const row = stmt.get(id);
|
|
2065
|
+
return row ? this.mapRow(row) : null;
|
|
2066
|
+
}
|
|
2067
|
+
getByPath(normalizedPath) {
|
|
2068
|
+
if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
|
|
2069
|
+
if (!this.initialized || !this.db) return null;
|
|
2070
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
|
|
2071
|
+
const row = stmt.get(normalizedPath);
|
|
2072
|
+
return row ? this.mapRow(row) : null;
|
|
2073
|
+
}
|
|
2074
|
+
getChildren(parentId) {
|
|
2075
|
+
if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
|
|
2076
|
+
if (!this.initialized || !this.db) return [];
|
|
2077
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
|
|
2078
|
+
const rows = stmt.all(parentId);
|
|
2079
|
+
return rows.map((r) => this.mapRow(r));
|
|
2080
|
+
}
|
|
2081
|
+
findByMd5(md5) {
|
|
2082
|
+
if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
|
|
2083
|
+
if (!this.initialized || !this.db || !md5) return null;
|
|
2084
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
|
|
2085
|
+
const row = stmt.get(md5.toLowerCase());
|
|
2086
|
+
return row ? this.mapRow(row) : null;
|
|
2087
|
+
}
|
|
2088
|
+
searchByName(query) {
|
|
2089
|
+
if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
|
|
2090
|
+
if (!this.initialized || !this.db) return [];
|
|
2091
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
|
|
2092
|
+
const rows = stmt.all(`%${query}%`);
|
|
2093
|
+
return rows.map((r) => this.mapRow(r));
|
|
2094
|
+
}
|
|
2095
|
+
upsertFile(entry) {
|
|
2096
|
+
if (this.fallbackMemory) {
|
|
2097
|
+
this.fallbackMemory.upsertFile(entry);
|
|
2098
|
+
return;
|
|
2099
|
+
}
|
|
2100
|
+
if (!this.initialized || !this.db) return;
|
|
2101
|
+
const stmt = this.db.prepare(`
|
|
2102
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2103
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2104
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2105
|
+
name = excluded.name,
|
|
2106
|
+
mimeType = excluded.mimeType,
|
|
2107
|
+
size = excluded.size,
|
|
2108
|
+
parentId = excluded.parentId,
|
|
2109
|
+
path = COALESCE(excluded.path, files.path),
|
|
2110
|
+
md5Checksum = excluded.md5Checksum,
|
|
2111
|
+
trashed = excluded.trashed,
|
|
2112
|
+
modifiedTime = excluded.modifiedTime,
|
|
2113
|
+
updatedAt = excluded.updatedAt
|
|
2114
|
+
`);
|
|
2115
|
+
stmt.run(
|
|
2116
|
+
entry.id,
|
|
2117
|
+
entry.name,
|
|
2118
|
+
entry.mimeType ?? null,
|
|
2119
|
+
entry.size ?? null,
|
|
2120
|
+
entry.parentId ?? null,
|
|
2121
|
+
entry.path ?? null,
|
|
2122
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2123
|
+
entry.trashed ? 1 : 0,
|
|
2124
|
+
entry.modifiedTime ?? null,
|
|
2125
|
+
entry.updatedAt ?? Date.now()
|
|
2126
|
+
);
|
|
2127
|
+
}
|
|
2128
|
+
upsertFiles(entries) {
|
|
2129
|
+
if (this.fallbackMemory) {
|
|
2130
|
+
this.fallbackMemory.upsertFiles(entries);
|
|
2131
|
+
return;
|
|
2132
|
+
}
|
|
2133
|
+
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2134
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2135
|
+
try {
|
|
2136
|
+
for (const entry of entries) {
|
|
2137
|
+
this.upsertFile(entry);
|
|
2138
|
+
}
|
|
2139
|
+
this.db.exec("COMMIT;");
|
|
2140
|
+
} catch (e) {
|
|
2141
|
+
this.db.exec("ROLLBACK;");
|
|
2142
|
+
throw e;
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
deleteFile(id) {
|
|
2146
|
+
if (this.fallbackMemory) {
|
|
2147
|
+
this.fallbackMemory.deleteFile(id);
|
|
2148
|
+
return;
|
|
2149
|
+
}
|
|
2150
|
+
if (!this.initialized || !this.db) return;
|
|
2151
|
+
const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2152
|
+
stmt.run(id);
|
|
2153
|
+
}
|
|
2154
|
+
pruneMissing(activeIds) {
|
|
2155
|
+
if (this.fallbackMemory) {
|
|
2156
|
+
return this.fallbackMemory.pruneMissing(activeIds);
|
|
2157
|
+
}
|
|
2158
|
+
if (!this.initialized || !this.db || activeIds.length === 0) return 0;
|
|
2159
|
+
const idSet = new Set(activeIds);
|
|
2160
|
+
const rows = this.db.prepare("SELECT id FROM files").all();
|
|
2161
|
+
let pruned = 0;
|
|
2162
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2163
|
+
try {
|
|
2164
|
+
const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2165
|
+
for (const row of rows) {
|
|
2166
|
+
if (!idSet.has(row.id)) {
|
|
2167
|
+
deleteStmt.run(row.id);
|
|
2168
|
+
pruned++;
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
this.db.exec("COMMIT;");
|
|
2172
|
+
return pruned;
|
|
2173
|
+
} catch (e) {
|
|
2174
|
+
this.db.exec("ROLLBACK;");
|
|
2175
|
+
throw e;
|
|
2176
|
+
}
|
|
2177
|
+
}
|
|
2178
|
+
clear() {
|
|
2179
|
+
if (this.fallbackMemory) {
|
|
2180
|
+
this.fallbackMemory.clear();
|
|
2181
|
+
return;
|
|
2182
|
+
}
|
|
2183
|
+
if (!this.initialized || !this.db) return;
|
|
2184
|
+
this.db.exec("DELETE FROM files; DELETE FROM meta;");
|
|
2185
|
+
}
|
|
2186
|
+
getMeta(key) {
|
|
2187
|
+
if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
|
|
2188
|
+
if (!this.initialized || !this.db) return null;
|
|
2189
|
+
const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
|
|
2190
|
+
const row = stmt.get(key);
|
|
2191
|
+
return row ? row.value : null;
|
|
2192
|
+
}
|
|
2193
|
+
setMeta(key, value) {
|
|
2194
|
+
if (this.fallbackMemory) {
|
|
2195
|
+
this.fallbackMemory.setMeta(key, value);
|
|
2196
|
+
return;
|
|
2197
|
+
}
|
|
2198
|
+
if (!this.initialized || !this.db) return;
|
|
2199
|
+
const stmt = this.db.prepare(`
|
|
2200
|
+
INSERT INTO meta (key, value) VALUES (?, ?)
|
|
2201
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
2202
|
+
`);
|
|
2203
|
+
stmt.run(key, value);
|
|
2204
|
+
}
|
|
2205
|
+
getStats() {
|
|
2206
|
+
if (this.fallbackMemory) return this.fallbackMemory.getStats();
|
|
2207
|
+
if (!this.initialized || !this.db) {
|
|
2208
|
+
return {
|
|
2209
|
+
fileCount: 0,
|
|
2210
|
+
folderCount: 0,
|
|
2211
|
+
totalSizeBytes: 0,
|
|
2212
|
+
lastSyncTime: null,
|
|
2213
|
+
databasePath: this.dbPath
|
|
2214
|
+
};
|
|
2215
|
+
}
|
|
2216
|
+
const fileCountRow = this.db.prepare(
|
|
2217
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2218
|
+
).get();
|
|
2219
|
+
const folderCountRow = this.db.prepare(
|
|
2220
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2221
|
+
).get();
|
|
2222
|
+
const totalSizeRow = this.db.prepare(
|
|
2223
|
+
"SELECT SUM(size) as total FROM files WHERE trashed = 0"
|
|
2224
|
+
).get();
|
|
2225
|
+
const lastSync = this.getMeta("last_sync_timestamp");
|
|
2226
|
+
return {
|
|
2227
|
+
fileCount: fileCountRow?.count || 0,
|
|
2228
|
+
folderCount: folderCountRow?.count || 0,
|
|
2229
|
+
totalSizeBytes: totalSizeRow?.total || 0,
|
|
2230
|
+
lastSyncTime: lastSync,
|
|
2231
|
+
databasePath: this.dbPath
|
|
2232
|
+
};
|
|
2233
|
+
}
|
|
2234
|
+
close() {
|
|
2235
|
+
if (this.fallbackMemory) {
|
|
2236
|
+
this.fallbackMemory.close();
|
|
2237
|
+
this.fallbackMemory = void 0;
|
|
2238
|
+
}
|
|
2239
|
+
if (this.db) {
|
|
2240
|
+
try {
|
|
2241
|
+
this.db.close();
|
|
2242
|
+
} catch {
|
|
2243
|
+
}
|
|
2244
|
+
this.initialized = false;
|
|
2245
|
+
this.db = null;
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
mapRow(row) {
|
|
2249
|
+
return {
|
|
2250
|
+
id: row.id,
|
|
2251
|
+
name: row.name,
|
|
2252
|
+
mimeType: row.mimeType,
|
|
2253
|
+
size: row.size != null ? Number(row.size) : void 0,
|
|
2254
|
+
parentId: row.parentId || void 0,
|
|
2255
|
+
path: row.path || void 0,
|
|
2256
|
+
md5Checksum: row.md5Checksum || void 0,
|
|
2257
|
+
trashed: row.trashed === 1,
|
|
2258
|
+
modifiedTime: row.modifiedTime || void 0,
|
|
2259
|
+
updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
|
|
2260
|
+
};
|
|
2261
|
+
}
|
|
2262
|
+
};
|
|
2263
|
+
MemoryMetadataCache = class {
|
|
2264
|
+
files = /* @__PURE__ */ new Map();
|
|
2265
|
+
meta = /* @__PURE__ */ new Map();
|
|
2266
|
+
init() {
|
|
2267
|
+
}
|
|
2268
|
+
getById(id) {
|
|
2269
|
+
return this.files.get(id) || null;
|
|
2270
|
+
}
|
|
2271
|
+
getByPath(normalizedPath) {
|
|
2272
|
+
for (const f of this.files.values()) {
|
|
2273
|
+
if (f.path === normalizedPath && !f.trashed) return f;
|
|
2274
|
+
}
|
|
2275
|
+
return null;
|
|
2276
|
+
}
|
|
2277
|
+
getChildren(parentId) {
|
|
2278
|
+
const list = [];
|
|
2279
|
+
for (const f of this.files.values()) {
|
|
2280
|
+
if (f.parentId === parentId && !f.trashed) list.push(f);
|
|
2281
|
+
}
|
|
2282
|
+
return list;
|
|
2283
|
+
}
|
|
2284
|
+
findByMd5(md5) {
|
|
2285
|
+
const target = md5.toLowerCase();
|
|
2286
|
+
for (const f of this.files.values()) {
|
|
2287
|
+
if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
|
|
2288
|
+
}
|
|
2289
|
+
return null;
|
|
2290
|
+
}
|
|
2291
|
+
searchByName(query) {
|
|
2292
|
+
const q = query.toLowerCase();
|
|
2293
|
+
const list = [];
|
|
2294
|
+
for (const f of this.files.values()) {
|
|
2295
|
+
if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
|
|
2296
|
+
}
|
|
2297
|
+
return list;
|
|
2298
|
+
}
|
|
2299
|
+
upsertFile(entry) {
|
|
2300
|
+
this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
|
|
2301
|
+
}
|
|
2302
|
+
upsertFiles(entries) {
|
|
2303
|
+
for (const e of entries) this.upsertFile(e);
|
|
2304
|
+
}
|
|
2305
|
+
deleteFile(id) {
|
|
2306
|
+
this.files.delete(id);
|
|
2307
|
+
}
|
|
2308
|
+
pruneMissing(activeIds) {
|
|
2309
|
+
const idSet = new Set(activeIds);
|
|
2310
|
+
let pruned = 0;
|
|
2311
|
+
for (const id of Array.from(this.files.keys())) {
|
|
2312
|
+
if (!idSet.has(id)) {
|
|
2313
|
+
this.files.delete(id);
|
|
2314
|
+
pruned++;
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
return pruned;
|
|
2318
|
+
}
|
|
2319
|
+
clear() {
|
|
2320
|
+
this.files.clear();
|
|
2321
|
+
this.meta.clear();
|
|
2322
|
+
}
|
|
2323
|
+
getMeta(key) {
|
|
2324
|
+
return this.meta.get(key) || null;
|
|
2325
|
+
}
|
|
2326
|
+
setMeta(key, value) {
|
|
2327
|
+
this.meta.set(key, value);
|
|
2328
|
+
}
|
|
2329
|
+
getStats() {
|
|
2330
|
+
let fileCount = 0;
|
|
2331
|
+
let folderCount = 0;
|
|
2332
|
+
let totalSizeBytes = 0;
|
|
2333
|
+
for (const f of this.files.values()) {
|
|
2334
|
+
if (f.trashed) continue;
|
|
2335
|
+
if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
|
|
2336
|
+
else {
|
|
2337
|
+
fileCount++;
|
|
2338
|
+
totalSizeBytes += f.size || 0;
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
return {
|
|
2342
|
+
fileCount,
|
|
2343
|
+
folderCount,
|
|
2344
|
+
totalSizeBytes,
|
|
2345
|
+
lastSyncTime: this.meta.get("last_sync_timestamp") || null,
|
|
2346
|
+
databasePath: ":memory:"
|
|
2347
|
+
};
|
|
2348
|
+
}
|
|
2349
|
+
close() {
|
|
2350
|
+
this.clear();
|
|
2351
|
+
}
|
|
2352
|
+
};
|
|
2353
|
+
}
|
|
2354
|
+
});
|
|
2355
|
+
|
|
2356
|
+
// src/server/webdav.ts
|
|
2357
|
+
var webdav_exports = {};
|
|
2358
|
+
__export(webdav_exports, {
|
|
2359
|
+
escapeXml: () => escapeXml,
|
|
2360
|
+
startWebDAVServer: () => startWebDAVServer
|
|
2361
|
+
});
|
|
2362
|
+
import http2 from "http";
|
|
2363
|
+
import url from "url";
|
|
2364
|
+
import path7 from "path";
|
|
2365
|
+
function escapeXml(unsafe) {
|
|
2366
|
+
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2367
|
+
}
|
|
2368
|
+
async function startWebDAVServer(drive2, options = {}) {
|
|
2369
|
+
const port = options.port || 8080;
|
|
2370
|
+
const host = options.host || "127.0.0.1";
|
|
2371
|
+
await drive2.init();
|
|
2372
|
+
const server = http2.createServer(async (req, res) => {
|
|
2373
|
+
try {
|
|
2374
|
+
if (options.auth?.username && options.auth?.password) {
|
|
2375
|
+
const authHeader = req.headers["authorization"];
|
|
2376
|
+
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
2377
|
+
res.writeHead(401, {
|
|
2378
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
2379
|
+
"Content-Type": "text/plain"
|
|
2380
|
+
});
|
|
2381
|
+
res.end("Authentication required");
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
|
|
2385
|
+
const [user, pass] = credentials.split(":");
|
|
2386
|
+
if (user !== options.auth.username || pass !== options.auth.password) {
|
|
2387
|
+
res.writeHead(401, {
|
|
2388
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
2389
|
+
"Content-Type": "text/plain"
|
|
2390
|
+
});
|
|
2391
|
+
res.end("Invalid credentials");
|
|
2392
|
+
return;
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
const parsedUrl = url.parse(req.url || "/", true);
|
|
2396
|
+
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
2397
|
+
const virtualPath = decodedPath === "" ? "/" : decodedPath;
|
|
2398
|
+
switch (req.method) {
|
|
2399
|
+
case "OPTIONS": {
|
|
2400
|
+
res.writeHead(200, {
|
|
2401
|
+
DAV: "1, 2",
|
|
2402
|
+
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
2403
|
+
"MS-Author-Via": "DAV",
|
|
2404
|
+
"Accept-Ranges": "bytes"
|
|
2405
|
+
});
|
|
2406
|
+
res.end();
|
|
2407
|
+
return;
|
|
2408
|
+
}
|
|
2409
|
+
case "PROPFIND": {
|
|
2410
|
+
const depth = req.headers["depth"] || "1";
|
|
2411
|
+
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
2412
|
+
res.writeHead(207, {
|
|
2413
|
+
"Content-Type": "application/xml; charset=utf-8"
|
|
2414
|
+
});
|
|
2415
|
+
res.end(xml);
|
|
2416
|
+
return;
|
|
2417
|
+
}
|
|
2418
|
+
case "GET":
|
|
2419
|
+
case "HEAD": {
|
|
2420
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
2421
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2422
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
try {
|
|
2426
|
+
const file = await drive2.getFile(virtualPath);
|
|
2427
|
+
if (file.mimeType === "application/vnd.google-apps.folder") {
|
|
2428
|
+
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
2429
|
+
res.end("Cannot GET a directory");
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
2432
|
+
const fileSize = file.size ? parseInt(file.size, 10) : void 0;
|
|
2433
|
+
const rangeHeader = req.headers["range"];
|
|
2434
|
+
if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
|
|
2435
|
+
const parts = rangeHeader.replace("bytes=", "").split("-");
|
|
2436
|
+
const start = parseInt(parts[0], 10);
|
|
2437
|
+
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
|
|
2438
|
+
if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
|
|
2439
|
+
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
|
|
2440
|
+
res.end();
|
|
2441
|
+
return;
|
|
2442
|
+
}
|
|
2443
|
+
const stream = await drive2.createReadStream(virtualPath, { start, end });
|
|
2444
|
+
const chunkLength = end - start + 1;
|
|
2445
|
+
res.writeHead(206, {
|
|
2446
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
2447
|
+
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
|
|
2448
|
+
"Content-Length": chunkLength,
|
|
2449
|
+
"Accept-Ranges": "bytes"
|
|
2450
|
+
});
|
|
2451
|
+
if (req.method === "HEAD") {
|
|
2452
|
+
res.end();
|
|
2453
|
+
} else {
|
|
2454
|
+
stream.pipe(res);
|
|
2455
|
+
}
|
|
2456
|
+
} else {
|
|
2457
|
+
const stream = await drive2.createReadStream(virtualPath);
|
|
2458
|
+
res.writeHead(200, {
|
|
2459
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
2460
|
+
"Content-Length": file.size || void 0,
|
|
2461
|
+
"Accept-Ranges": "bytes"
|
|
2462
|
+
});
|
|
2463
|
+
if (req.method === "HEAD") {
|
|
2464
|
+
res.end();
|
|
2465
|
+
} else {
|
|
2466
|
+
stream.pipe(res);
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
} catch (e) {
|
|
2470
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2471
|
+
res.end("File Not Found");
|
|
2472
|
+
}
|
|
2473
|
+
return;
|
|
2474
|
+
}
|
|
2475
|
+
case "PUT": {
|
|
2476
|
+
const remoteDir = path7.dirname(virtualPath);
|
|
2477
|
+
await drive2.mkdirp(remoteDir);
|
|
2478
|
+
let existed = false;
|
|
2479
|
+
try {
|
|
2480
|
+
const existingFile = await drive2.getFile(virtualPath);
|
|
2481
|
+
if (existingFile && existingFile.id) {
|
|
2482
|
+
existed = true;
|
|
2483
|
+
}
|
|
2484
|
+
} catch {
|
|
2485
|
+
existed = false;
|
|
2486
|
+
}
|
|
2487
|
+
try {
|
|
2488
|
+
const uploadStream = await drive2.createWriteStream(virtualPath, {
|
|
2489
|
+
overwrite: true
|
|
2490
|
+
});
|
|
2491
|
+
req.pipe(uploadStream);
|
|
2492
|
+
await uploadStream.done;
|
|
2493
|
+
res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
|
|
2494
|
+
res.end(existed ? "" : "Created");
|
|
2495
|
+
} catch (err) {
|
|
2496
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2497
|
+
res.end(err.message || "Upload failed");
|
|
2498
|
+
}
|
|
2499
|
+
return;
|
|
2500
|
+
}
|
|
2501
|
+
case "MKCOL": {
|
|
2502
|
+
try {
|
|
2503
|
+
await drive2.mkdirp(virtualPath);
|
|
2504
|
+
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
2505
|
+
res.end("Collection Created");
|
|
2506
|
+
} catch (err) {
|
|
2507
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2508
|
+
res.end(err.message);
|
|
2509
|
+
}
|
|
2510
|
+
return;
|
|
2511
|
+
}
|
|
2512
|
+
case "DELETE": {
|
|
2513
|
+
try {
|
|
2514
|
+
await drive2.delete(virtualPath, true);
|
|
2515
|
+
res.writeHead(204);
|
|
2516
|
+
res.end();
|
|
2517
|
+
} catch (err) {
|
|
2518
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2519
|
+
res.end("Not Found");
|
|
2520
|
+
}
|
|
2521
|
+
return;
|
|
2522
|
+
}
|
|
2523
|
+
case "MOVE": {
|
|
2524
|
+
const destination = req.headers["destination"];
|
|
2525
|
+
if (!destination || typeof destination !== "string") {
|
|
2526
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
2527
|
+
res.end("Destination header missing");
|
|
2528
|
+
return;
|
|
2529
|
+
}
|
|
2530
|
+
try {
|
|
2531
|
+
const file = await drive2.getFile(virtualPath);
|
|
2532
|
+
if (!file?.id) {
|
|
2533
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2534
|
+
res.end("Source file not found");
|
|
2535
|
+
return;
|
|
2536
|
+
}
|
|
2537
|
+
const destUrl = url.parse(destination);
|
|
2538
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2539
|
+
const newName = path7.basename(destPath);
|
|
2540
|
+
const newParentDir = path7.dirname(destPath);
|
|
2541
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2542
|
+
const currentParentDir = path7.dirname(virtualPath);
|
|
2543
|
+
if (newParentDir !== currentParentDir) {
|
|
2544
|
+
await drive2.move(file.id, newParentFolderId);
|
|
2545
|
+
}
|
|
2546
|
+
if (newName !== path7.basename(virtualPath)) {
|
|
2547
|
+
await drive2.rename(file.id, newName);
|
|
2548
|
+
}
|
|
2549
|
+
res.writeHead(201);
|
|
2550
|
+
res.end("Moved");
|
|
2551
|
+
} catch (err) {
|
|
2552
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2553
|
+
res.end(err.message);
|
|
2554
|
+
}
|
|
2555
|
+
return;
|
|
2556
|
+
}
|
|
2557
|
+
case "COPY": {
|
|
2558
|
+
const destination = req.headers["destination"];
|
|
2559
|
+
if (!destination || typeof destination !== "string") {
|
|
2560
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
2561
|
+
res.end("Destination header missing");
|
|
2562
|
+
return;
|
|
2563
|
+
}
|
|
2564
|
+
try {
|
|
2565
|
+
const file = await drive2.getFile(virtualPath);
|
|
2566
|
+
if (!file?.id) {
|
|
2567
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2568
|
+
res.end("Source file not found");
|
|
2569
|
+
return;
|
|
2570
|
+
}
|
|
2571
|
+
const destUrl = url.parse(destination);
|
|
2572
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2573
|
+
const newName = path7.basename(destPath);
|
|
2574
|
+
const newParentDir = path7.dirname(destPath);
|
|
2575
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2576
|
+
await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
|
|
2577
|
+
res.writeHead(201);
|
|
2578
|
+
res.end("Copied");
|
|
2579
|
+
} catch (err) {
|
|
2580
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2581
|
+
res.end(err.message);
|
|
2582
|
+
}
|
|
2583
|
+
return;
|
|
2584
|
+
}
|
|
2585
|
+
default: {
|
|
2586
|
+
res.writeHead(501, { "Content-Type": "text/plain" });
|
|
2587
|
+
res.end("Method Not Implemented");
|
|
2588
|
+
}
|
|
2589
|
+
}
|
|
2590
|
+
} catch (globalErr) {
|
|
2591
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2592
|
+
res.end(`Internal Server Error: ${globalErr.message}`);
|
|
2593
|
+
}
|
|
2594
|
+
});
|
|
2595
|
+
return new Promise((resolve) => {
|
|
2596
|
+
server.listen(port, host, () => {
|
|
2597
|
+
const serverUrl = `http://${host}:${port}`;
|
|
2598
|
+
resolve({
|
|
2599
|
+
server,
|
|
2600
|
+
url: serverUrl,
|
|
2601
|
+
close: () => new Promise((resClose) => server.close(() => resClose()))
|
|
2602
|
+
});
|
|
2603
|
+
});
|
|
2604
|
+
});
|
|
2605
|
+
}
|
|
2606
|
+
async function handlePropfind(drive2, virtualPath, depth) {
|
|
2607
|
+
const responses = [];
|
|
2608
|
+
let isFolder = false;
|
|
2609
|
+
let selfItem = null;
|
|
2610
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
2611
|
+
isFolder = true;
|
|
2612
|
+
responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
|
|
2613
|
+
} else {
|
|
2614
|
+
try {
|
|
2615
|
+
selfItem = await drive2.getFile(virtualPath);
|
|
2616
|
+
isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
|
|
2617
|
+
responses.push(
|
|
2618
|
+
renderWebDAVResponse(
|
|
2619
|
+
virtualPath,
|
|
2620
|
+
isFolder,
|
|
2621
|
+
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
2622
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2623
|
+
)
|
|
2624
|
+
);
|
|
2625
|
+
} catch {
|
|
2626
|
+
return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
if (isFolder && depth !== "0") {
|
|
2630
|
+
try {
|
|
2631
|
+
const children = await drive2.ls(virtualPath);
|
|
2632
|
+
for (const child of children) {
|
|
2633
|
+
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
2634
|
+
const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
|
|
2635
|
+
responses.push(
|
|
2636
|
+
renderWebDAVResponse(
|
|
2637
|
+
childPath,
|
|
2638
|
+
childIsFolder,
|
|
2639
|
+
child.size ? parseInt(child.size, 10) : 0,
|
|
2640
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2641
|
+
)
|
|
2642
|
+
);
|
|
2643
|
+
}
|
|
2644
|
+
} catch {
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
2648
|
+
<D:multistatus xmlns:D="DAV:">
|
|
2649
|
+
${responses.join("\n")}
|
|
2650
|
+
</D:multistatus>`;
|
|
2651
|
+
}
|
|
2652
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
2653
|
+
const encodedHref = encodeURI(href);
|
|
2654
|
+
const displayName = escapeXml(path7.basename(href) || "root");
|
|
2655
|
+
const resourceType = isDir ? "<D:collection/>" : "";
|
|
2656
|
+
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
2657
|
+
return ` <D:response>
|
|
2658
|
+
<D:href>${encodedHref}</D:href>
|
|
2659
|
+
<D:propstat>
|
|
2660
|
+
<D:prop>
|
|
2661
|
+
<D:displayname>${displayName}</D:displayname>
|
|
2662
|
+
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
2663
|
+
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
2664
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>
|
|
2665
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2666
|
+
</D:prop>
|
|
2667
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2668
|
+
</D:propstat>
|
|
2669
|
+
</D:response>`;
|
|
2670
|
+
}
|
|
2671
|
+
var init_webdav = __esm({
|
|
2672
|
+
"src/server/webdav.ts"() {
|
|
2673
|
+
"use strict";
|
|
2674
|
+
init_esm_shims();
|
|
2675
|
+
}
|
|
2676
|
+
});
|
|
2677
|
+
|
|
1834
2678
|
// src/core/client.ts
|
|
1835
2679
|
var client_exports = {};
|
|
1836
2680
|
__export(client_exports, {
|
|
1837
2681
|
DriveKit: () => DriveKit
|
|
1838
2682
|
});
|
|
1839
|
-
import
|
|
1840
|
-
import
|
|
2683
|
+
import fs6 from "fs";
|
|
2684
|
+
import path8 from "path";
|
|
1841
2685
|
import { drive } from "@googleapis/drive";
|
|
1842
2686
|
var DriveKit;
|
|
1843
2687
|
var init_client = __esm({
|
|
@@ -1859,13 +2703,15 @@ var init_client = __esm({
|
|
|
1859
2703
|
init_retry();
|
|
1860
2704
|
init_format();
|
|
1861
2705
|
init_mime();
|
|
1862
|
-
|
|
2706
|
+
init_cache();
|
|
2707
|
+
DriveKit = class _DriveKit {
|
|
1863
2708
|
options;
|
|
1864
2709
|
authenticator;
|
|
1865
2710
|
driveClient = null;
|
|
1866
2711
|
pathResolverInstance = null;
|
|
1867
2712
|
uploaderInstance = null;
|
|
1868
2713
|
downloaderInstance = null;
|
|
2714
|
+
metadataCacheInstance = null;
|
|
1869
2715
|
rootFolderId;
|
|
1870
2716
|
pluginManager = new PluginManager();
|
|
1871
2717
|
constructor(options = {}) {
|
|
@@ -1899,9 +2745,14 @@ var init_client = __esm({
|
|
|
1899
2745
|
if (!this.driveClient) {
|
|
1900
2746
|
const auth = await this.authenticator.getAuthClient();
|
|
1901
2747
|
this.driveClient = drive({ version: "v3", auth });
|
|
2748
|
+
if (this.options.enablePersistentCache !== false) {
|
|
2749
|
+
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2750
|
+
this.metadataCacheInstance.init();
|
|
2751
|
+
}
|
|
1902
2752
|
this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
|
|
1903
2753
|
enableCache: this.options.enablePathCache ?? true,
|
|
1904
|
-
cacheTTL: this.options.pathCacheTTL
|
|
2754
|
+
cacheTTL: this.options.pathCacheTTL,
|
|
2755
|
+
metadataCache: this.metadataCacheInstance || void 0
|
|
1905
2756
|
});
|
|
1906
2757
|
this.uploaderInstance = new ResumableUploader(
|
|
1907
2758
|
this.driveClient,
|
|
@@ -1983,8 +2834,9 @@ var init_client = __esm({
|
|
|
1983
2834
|
* Lists contents of a folder (by folder ID or path)
|
|
1984
2835
|
*/
|
|
1985
2836
|
async ls(folderIdOrPath = "/") {
|
|
1986
|
-
if (folderIdOrPath === "/" || folderIdOrPath === "root") {
|
|
1987
|
-
|
|
2837
|
+
if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
|
|
2838
|
+
const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
|
|
2839
|
+
return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
|
|
1988
2840
|
}
|
|
1989
2841
|
const folderId = await this.resolveId(folderIdOrPath);
|
|
1990
2842
|
return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
|
|
@@ -2006,16 +2858,71 @@ var init_client = __esm({
|
|
|
2006
2858
|
if (parentId && parentId.startsWith("/")) {
|
|
2007
2859
|
parentId = await this.mkdirp(parentId);
|
|
2008
2860
|
}
|
|
2009
|
-
|
|
2010
|
-
|
|
2861
|
+
const targetName = opts.name || opts.filename;
|
|
2862
|
+
if (opts.overwrite && targetName && parentId) {
|
|
2863
|
+
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
2011
2864
|
if (existing?.id) {
|
|
2012
2865
|
await this.delete(existing.id, true);
|
|
2013
2866
|
}
|
|
2014
2867
|
}
|
|
2868
|
+
if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
|
|
2869
|
+
const localMd5 = await calculateFileMd5(opts.source);
|
|
2870
|
+
let existingId;
|
|
2871
|
+
if (this.metadataCacheInstance) {
|
|
2872
|
+
const cached = this.metadataCacheInstance.findByMd5(localMd5);
|
|
2873
|
+
if (cached) existingId = cached.id;
|
|
2874
|
+
}
|
|
2875
|
+
if (!existingId) {
|
|
2876
|
+
const found = await this.query().md5(localMd5).notTrashed().first();
|
|
2877
|
+
if (found?.id) {
|
|
2878
|
+
existingId = found.id;
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
if (existingId) {
|
|
2882
|
+
const fileName = targetName || path8.basename(opts.source);
|
|
2883
|
+
const raw = await this.getRawClient();
|
|
2884
|
+
const copyRes = await withRetry(async () => {
|
|
2885
|
+
return await raw.files.copy({
|
|
2886
|
+
fileId: existingId,
|
|
2887
|
+
requestBody: {
|
|
2888
|
+
name: fileName,
|
|
2889
|
+
parents: parentId ? [parentId] : void 0,
|
|
2890
|
+
description: opts.description
|
|
2891
|
+
},
|
|
2892
|
+
fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
|
|
2893
|
+
supportsAllDrives: true
|
|
2894
|
+
});
|
|
2895
|
+
});
|
|
2896
|
+
const file = copyRes.data;
|
|
2897
|
+
if (this.metadataCacheInstance && file.id) {
|
|
2898
|
+
this.metadataCacheInstance.upsertFile({
|
|
2899
|
+
id: file.id,
|
|
2900
|
+
name: file.name || fileName,
|
|
2901
|
+
mimeType: file.mimeType || "",
|
|
2902
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2903
|
+
parentId,
|
|
2904
|
+
md5Checksum: localMd5,
|
|
2905
|
+
trashed: false
|
|
2906
|
+
});
|
|
2907
|
+
}
|
|
2908
|
+
return await this.pluginManager.runAfterUpload(file);
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2015
2911
|
const uploaded = await uploader.upload({
|
|
2016
2912
|
...opts,
|
|
2913
|
+
name: targetName,
|
|
2017
2914
|
parent: parentId
|
|
2018
2915
|
});
|
|
2916
|
+
if (this.metadataCacheInstance && uploaded.id) {
|
|
2917
|
+
this.metadataCacheInstance.upsertFile({
|
|
2918
|
+
id: uploaded.id,
|
|
2919
|
+
name: uploaded.name || targetName || "untitled",
|
|
2920
|
+
mimeType: uploaded.mimeType || "",
|
|
2921
|
+
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2922
|
+
parentId,
|
|
2923
|
+
trashed: false
|
|
2924
|
+
});
|
|
2925
|
+
}
|
|
2019
2926
|
return await this.pluginManager.runAfterUpload(uploaded);
|
|
2020
2927
|
}
|
|
2021
2928
|
/**
|
|
@@ -2256,16 +3163,16 @@ var init_client = __esm({
|
|
|
2256
3163
|
durationMs: 0
|
|
2257
3164
|
};
|
|
2258
3165
|
const collectFiles = async (dir, base) => {
|
|
2259
|
-
const entries = await
|
|
3166
|
+
const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
|
|
2260
3167
|
const files = [];
|
|
2261
3168
|
for (const entry of entries) {
|
|
2262
|
-
const fullPath =
|
|
2263
|
-
const relPath =
|
|
3169
|
+
const fullPath = path8.join(dir, entry.name);
|
|
3170
|
+
const relPath = path8.join(base, entry.name);
|
|
2264
3171
|
if (entry.isDirectory()) {
|
|
2265
3172
|
const sub = await collectFiles(fullPath, relPath);
|
|
2266
3173
|
files.push(...sub);
|
|
2267
3174
|
} else if (entry.isFile()) {
|
|
2268
|
-
const stat = await
|
|
3175
|
+
const stat = await fs6.promises.stat(fullPath);
|
|
2269
3176
|
files.push({ fullPath, relPath, size: stat.size });
|
|
2270
3177
|
}
|
|
2271
3178
|
}
|
|
@@ -2278,11 +3185,11 @@ var init_client = __esm({
|
|
|
2278
3185
|
if (remoteDirCache.has(relDir)) {
|
|
2279
3186
|
return remoteDirCache.get(relDir);
|
|
2280
3187
|
}
|
|
2281
|
-
const parts = relDir.split(
|
|
3188
|
+
const parts = relDir.split(path8.sep).filter(Boolean);
|
|
2282
3189
|
let currentParent = targetFolderId;
|
|
2283
3190
|
let currentRel = "";
|
|
2284
3191
|
for (const part of parts) {
|
|
2285
|
-
currentRel = currentRel ?
|
|
3192
|
+
currentRel = currentRel ? path8.join(currentRel, part) : part;
|
|
2286
3193
|
if (remoteDirCache.has(currentRel)) {
|
|
2287
3194
|
currentParent = remoteDirCache.get(currentRel);
|
|
2288
3195
|
continue;
|
|
@@ -2311,8 +3218,8 @@ var init_client = __esm({
|
|
|
2311
3218
|
};
|
|
2312
3219
|
await pool.map(allFiles, async (fileItem) => {
|
|
2313
3220
|
try {
|
|
2314
|
-
const relDir =
|
|
2315
|
-
const fileName =
|
|
3221
|
+
const relDir = path8.dirname(fileItem.relPath);
|
|
3222
|
+
const fileName = path8.basename(fileItem.relPath);
|
|
2316
3223
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
2317
3224
|
if (options.onFileStart) {
|
|
2318
3225
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -2430,6 +3337,256 @@ var init_client = __esm({
|
|
|
2430
3337
|
const engine = new SmartSyncEngine(this.driveClient);
|
|
2431
3338
|
return await engine.pullFolder(folderId, localDestinationDir, options);
|
|
2432
3339
|
}
|
|
3340
|
+
// ==========================================
|
|
3341
|
+
// STREAMS & RANGE REQUESTS
|
|
3342
|
+
// ==========================================
|
|
3343
|
+
/**
|
|
3344
|
+
* Creates a readable stream for a file, supporting partial range requests
|
|
3345
|
+
*/
|
|
3346
|
+
async createReadStream(pathOrId, options) {
|
|
3347
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3348
|
+
const downloader = await this.getDownloader();
|
|
3349
|
+
return await downloader.createReadStream(fileId, options);
|
|
3350
|
+
}
|
|
3351
|
+
/**
|
|
3352
|
+
* Creates a writable stream directly into Google Drive
|
|
3353
|
+
*/
|
|
3354
|
+
async createWriteStream(remotePath, options = {}) {
|
|
3355
|
+
await this.init();
|
|
3356
|
+
const { PassThrough } = await import("stream");
|
|
3357
|
+
const passThrough = new PassThrough();
|
|
3358
|
+
let resolveDone;
|
|
3359
|
+
let rejectDone;
|
|
3360
|
+
const donePromise = new Promise((resolve, reject) => {
|
|
3361
|
+
resolveDone = resolve;
|
|
3362
|
+
rejectDone = reject;
|
|
3363
|
+
});
|
|
3364
|
+
passThrough.done = donePromise;
|
|
3365
|
+
const remoteDir = path8.dirname(remotePath);
|
|
3366
|
+
const fileName = options.name || options.filename || path8.basename(remotePath);
|
|
3367
|
+
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3368
|
+
const mimeType = options.mimeType || "application/octet-stream";
|
|
3369
|
+
const raw = this.driveClient;
|
|
3370
|
+
raw.files.create({
|
|
3371
|
+
requestBody: {
|
|
3372
|
+
name: fileName,
|
|
3373
|
+
parents: [targetParentId],
|
|
3374
|
+
description: options.description
|
|
3375
|
+
},
|
|
3376
|
+
media: {
|
|
3377
|
+
mimeType,
|
|
3378
|
+
body: passThrough
|
|
3379
|
+
},
|
|
3380
|
+
fields: "id, name, mimeType, size, md5Checksum",
|
|
3381
|
+
supportsAllDrives: true
|
|
3382
|
+
}).then((res) => {
|
|
3383
|
+
const file = res.data;
|
|
3384
|
+
if (file.id && this.metadataCacheInstance) {
|
|
3385
|
+
this.metadataCacheInstance.upsertFile({
|
|
3386
|
+
id: file.id,
|
|
3387
|
+
name: fileName,
|
|
3388
|
+
mimeType,
|
|
3389
|
+
parentId: targetParentId,
|
|
3390
|
+
path: remotePath,
|
|
3391
|
+
trashed: false
|
|
3392
|
+
});
|
|
3393
|
+
}
|
|
3394
|
+
resolveDone(file);
|
|
3395
|
+
}).catch((err) => {
|
|
3396
|
+
passThrough.destroy(err);
|
|
3397
|
+
rejectDone(err);
|
|
3398
|
+
});
|
|
3399
|
+
return passThrough;
|
|
3400
|
+
}
|
|
3401
|
+
// ==========================================
|
|
3402
|
+
// METADATA CACHE OPERATIONS
|
|
3403
|
+
// ==========================================
|
|
3404
|
+
/**
|
|
3405
|
+
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3406
|
+
*/
|
|
3407
|
+
async getMetadataCache() {
|
|
3408
|
+
await this.init();
|
|
3409
|
+
return this.metadataCacheInstance;
|
|
3410
|
+
}
|
|
3411
|
+
/**
|
|
3412
|
+
* Returns cache statistics (total files, folders, size, last sync)
|
|
3413
|
+
*/
|
|
3414
|
+
async getCacheStats() {
|
|
3415
|
+
await this.init();
|
|
3416
|
+
return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
|
|
3417
|
+
}
|
|
3418
|
+
/**
|
|
3419
|
+
* Clears the path and metadata cache
|
|
3420
|
+
*/
|
|
3421
|
+
async clearCache() {
|
|
3422
|
+
await this.init();
|
|
3423
|
+
if (this.pathResolverInstance) {
|
|
3424
|
+
this.pathResolverInstance.clearCache();
|
|
3425
|
+
}
|
|
3426
|
+
}
|
|
3427
|
+
/**
|
|
3428
|
+
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
3429
|
+
*/
|
|
3430
|
+
async syncCache(options) {
|
|
3431
|
+
await this.init();
|
|
3432
|
+
if (!this.metadataCacheInstance) {
|
|
3433
|
+
throw new Error("Persistent cache is disabled on this DriveKit instance");
|
|
3434
|
+
}
|
|
3435
|
+
const client = this.driveClient;
|
|
3436
|
+
let pageToken = void 0;
|
|
3437
|
+
let totalScanned = 0;
|
|
3438
|
+
const rawFiles = [];
|
|
3439
|
+
do {
|
|
3440
|
+
const res = await withRetry(async () => {
|
|
3441
|
+
return await client.files.list({
|
|
3442
|
+
pageSize: 1e3,
|
|
3443
|
+
pageToken,
|
|
3444
|
+
fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
|
|
3445
|
+
spaces: "drive",
|
|
3446
|
+
supportsAllDrives: true,
|
|
3447
|
+
includeItemsFromAllDrives: true,
|
|
3448
|
+
q: "trashed = false"
|
|
3449
|
+
});
|
|
3450
|
+
});
|
|
3451
|
+
const files = res.data.files || [];
|
|
3452
|
+
for (const f of files) {
|
|
3453
|
+
if (f.id) rawFiles.push(f);
|
|
3454
|
+
}
|
|
3455
|
+
totalScanned += files.length;
|
|
3456
|
+
options?.onProgress?.(totalScanned);
|
|
3457
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
3458
|
+
} while (pageToken);
|
|
3459
|
+
const fileMap = /* @__PURE__ */ new Map();
|
|
3460
|
+
for (const f of rawFiles) {
|
|
3461
|
+
fileMap.set(f.id, f);
|
|
3462
|
+
}
|
|
3463
|
+
const pathMemo = /* @__PURE__ */ new Map();
|
|
3464
|
+
const rootId = this.rootFolderId;
|
|
3465
|
+
function computePath(id, visited = /* @__PURE__ */ new Set()) {
|
|
3466
|
+
if (pathMemo.has(id)) return pathMemo.get(id);
|
|
3467
|
+
if (visited.has(id)) return "";
|
|
3468
|
+
visited.add(id);
|
|
3469
|
+
const f = fileMap.get(id);
|
|
3470
|
+
if (!f || !f.name) return "";
|
|
3471
|
+
const parentId = f.parents?.[0];
|
|
3472
|
+
if (!parentId || parentId === "root" || parentId === rootId) {
|
|
3473
|
+
const p = `/${f.name}`;
|
|
3474
|
+
pathMemo.set(id, p);
|
|
3475
|
+
return p;
|
|
3476
|
+
}
|
|
3477
|
+
const parentPath = computePath(parentId, visited);
|
|
3478
|
+
const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
|
|
3479
|
+
pathMemo.set(id, fullPath);
|
|
3480
|
+
return fullPath;
|
|
3481
|
+
}
|
|
3482
|
+
const entries = rawFiles.map((f) => ({
|
|
3483
|
+
id: f.id,
|
|
3484
|
+
name: f.name || "untitled",
|
|
3485
|
+
mimeType: f.mimeType || "",
|
|
3486
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3487
|
+
parentId: f.parents?.[0],
|
|
3488
|
+
path: computePath(f.id),
|
|
3489
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
3490
|
+
trashed: !!f.trashed,
|
|
3491
|
+
modifiedTime: f.modifiedTime || void 0
|
|
3492
|
+
}));
|
|
3493
|
+
this.metadataCacheInstance.upsertFiles(entries);
|
|
3494
|
+
this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
|
|
3495
|
+
this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
|
|
3496
|
+
return this.metadataCacheInstance.getStats();
|
|
3497
|
+
}
|
|
3498
|
+
// ==========================================
|
|
3499
|
+
// SHARED DRIVES & ENTERPRISE PERMISSIONS
|
|
3500
|
+
// ==========================================
|
|
3501
|
+
/**
|
|
3502
|
+
* Lists all Google Workspace Shared Drives accessible by current user or service account
|
|
3503
|
+
*/
|
|
3504
|
+
async listSharedDrives(options = {}) {
|
|
3505
|
+
await this.init();
|
|
3506
|
+
const raw = await this.getRawClient();
|
|
3507
|
+
const res = await withRetry(async () => {
|
|
3508
|
+
return await raw.drives.list({
|
|
3509
|
+
pageSize: options.pageSize || 100,
|
|
3510
|
+
fields: "drives(id, name)"
|
|
3511
|
+
});
|
|
3512
|
+
});
|
|
3513
|
+
return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
|
|
3514
|
+
}
|
|
3515
|
+
/**
|
|
3516
|
+
* Creates a scoped DriveKit client locked to a specific Shared Drive
|
|
3517
|
+
*/
|
|
3518
|
+
sharedDrive(driveId) {
|
|
3519
|
+
return new _DriveKit({
|
|
3520
|
+
...this.options,
|
|
3521
|
+
rootFolderId: driveId
|
|
3522
|
+
});
|
|
3523
|
+
}
|
|
3524
|
+
/**
|
|
3525
|
+
* Grants access to a specific email with custom role and notification
|
|
3526
|
+
*/
|
|
3527
|
+
async grantAccess(pathOrId, options) {
|
|
3528
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3529
|
+
const raw = await this.getRawClient();
|
|
3530
|
+
const res = await withRetry(async () => {
|
|
3531
|
+
return await raw.permissions.create({
|
|
3532
|
+
fileId,
|
|
3533
|
+
requestBody: {
|
|
3534
|
+
type: "user",
|
|
3535
|
+
role: options.role || "reader",
|
|
3536
|
+
emailAddress: options.email
|
|
3537
|
+
},
|
|
3538
|
+
sendNotificationEmail: options.notify ?? true,
|
|
3539
|
+
emailMessage: options.message,
|
|
3540
|
+
fields: "id, type, role, emailAddress, displayName",
|
|
3541
|
+
supportsAllDrives: true
|
|
3542
|
+
});
|
|
3543
|
+
});
|
|
3544
|
+
return res.data;
|
|
3545
|
+
}
|
|
3546
|
+
/**
|
|
3547
|
+
* Revokes access for a specific permission ID or email address
|
|
3548
|
+
*/
|
|
3549
|
+
async revokeAccess(pathOrId, permissionIdOrEmail) {
|
|
3550
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3551
|
+
const raw = await this.getRawClient();
|
|
3552
|
+
let targetId = permissionIdOrEmail;
|
|
3553
|
+
if (permissionIdOrEmail.includes("@")) {
|
|
3554
|
+
const listRes = await this.listPermissions(fileId);
|
|
3555
|
+
const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
|
|
3556
|
+
if (found && found.id) {
|
|
3557
|
+
targetId = found.id;
|
|
3558
|
+
}
|
|
3559
|
+
}
|
|
3560
|
+
await withRetry(async () => {
|
|
3561
|
+
return await raw.permissions.delete({
|
|
3562
|
+
fileId,
|
|
3563
|
+
permissionId: targetId,
|
|
3564
|
+
supportsAllDrives: true
|
|
3565
|
+
});
|
|
3566
|
+
});
|
|
3567
|
+
}
|
|
3568
|
+
/**
|
|
3569
|
+
* Lists all active permissions on a file or folder
|
|
3570
|
+
*/
|
|
3571
|
+
async listPermissions(pathOrId) {
|
|
3572
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3573
|
+
const raw = await this.getRawClient();
|
|
3574
|
+
const res = await withRetry(async () => {
|
|
3575
|
+
return await raw.permissions.list({
|
|
3576
|
+
fileId,
|
|
3577
|
+
fields: "permissions(id, type, role, emailAddress, displayName)",
|
|
3578
|
+
supportsAllDrives: true
|
|
3579
|
+
});
|
|
3580
|
+
});
|
|
3581
|
+
return res.data.permissions || [];
|
|
3582
|
+
}
|
|
3583
|
+
/**
|
|
3584
|
+
* Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
|
|
3585
|
+
*/
|
|
3586
|
+
async serveWebDAV(options) {
|
|
3587
|
+
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3588
|
+
return await startWebDAVServer2(this, options);
|
|
3589
|
+
}
|
|
2433
3590
|
/**
|
|
2434
3591
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
2435
3592
|
*/
|
|
@@ -2450,8 +3607,8 @@ var init_client = __esm({
|
|
|
2450
3607
|
init_esm_shims();
|
|
2451
3608
|
init_client();
|
|
2452
3609
|
init_format();
|
|
2453
|
-
import
|
|
2454
|
-
import
|
|
3610
|
+
import fs7 from "fs";
|
|
3611
|
+
import path9 from "path";
|
|
2455
3612
|
import { Command } from "commander";
|
|
2456
3613
|
import chalk2 from "chalk";
|
|
2457
3614
|
import ora from "ora";
|
|
@@ -2461,8 +3618,8 @@ init_esm_shims();
|
|
|
2461
3618
|
init_format();
|
|
2462
3619
|
import readline from "readline";
|
|
2463
3620
|
import chalk from "chalk";
|
|
2464
|
-
function terminalLink(text,
|
|
2465
|
-
return `\x1B]8;;${
|
|
3621
|
+
function terminalLink(text, url2) {
|
|
3622
|
+
return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
|
|
2466
3623
|
}
|
|
2467
3624
|
function renderFileRow(item, index) {
|
|
2468
3625
|
const isDir = item.mimeType === "application/vnd.google-apps.folder";
|
|
@@ -2612,7 +3769,14 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
|
|
|
2612
3769
|
|
|
2613
3770
|
// src/cli.ts
|
|
2614
3771
|
var program = new Command();
|
|
2615
|
-
|
|
3772
|
+
var pkgVersion = "1.1.1";
|
|
3773
|
+
try {
|
|
3774
|
+
const pkgPath = new URL("../package.json", import.meta.url);
|
|
3775
|
+
const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
|
|
3776
|
+
if (pkg.version) pkgVersion = pkg.version;
|
|
3777
|
+
} catch {
|
|
3778
|
+
}
|
|
3779
|
+
program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
|
|
2616
3780
|
function getAuthConfig(cmdOptions) {
|
|
2617
3781
|
const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
|
|
2618
3782
|
const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
|
|
@@ -2684,12 +3848,12 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
|
|
|
2684
3848
|
process.exit(1);
|
|
2685
3849
|
}
|
|
2686
3850
|
});
|
|
2687
|
-
program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").action(async (localFile, remotePath = "/", options) => {
|
|
2688
|
-
if (!
|
|
3851
|
+
program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
|
|
3852
|
+
if (!fs7.existsSync(localFile)) {
|
|
2689
3853
|
console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
|
|
2690
3854
|
process.exit(1);
|
|
2691
3855
|
}
|
|
2692
|
-
const fileName =
|
|
3856
|
+
const fileName = path9.basename(localFile);
|
|
2693
3857
|
const spinner = ora(`Preparing upload: ${fileName}...`).start();
|
|
2694
3858
|
try {
|
|
2695
3859
|
const client = await getClient(options);
|
|
@@ -2700,6 +3864,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
|
|
|
2700
3864
|
name: fileName,
|
|
2701
3865
|
parent: remotePath,
|
|
2702
3866
|
overwrite: options.overwrite,
|
|
3867
|
+
deduplicate: options.dedup,
|
|
2703
3868
|
onProgress: (p) => {
|
|
2704
3869
|
process.stdout.write(
|
|
2705
3870
|
`\r\u{1F680} Uploading: ${chalk2.cyan(p.percentage + "%")} | Speed: ${chalk2.green(p.speedFormatted)} | ETA: ${chalk2.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
|
|
@@ -2784,7 +3949,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
|
|
|
2784
3949
|
}
|
|
2785
3950
|
});
|
|
2786
3951
|
program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
|
|
2787
|
-
if (!
|
|
3952
|
+
if (!fs7.existsSync(localDir)) {
|
|
2788
3953
|
console.error(chalk2.red(`\u274C Local directory not found: ${localDir}`));
|
|
2789
3954
|
process.exit(1);
|
|
2790
3955
|
}
|
|
@@ -2952,8 +4117,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
2952
4117
|
if (result.tokens.refresh_token) {
|
|
2953
4118
|
console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
|
|
2954
4119
|
}
|
|
2955
|
-
const outPath =
|
|
2956
|
-
|
|
4120
|
+
const outPath = path9.resolve("./gdrive-tokens.json");
|
|
4121
|
+
fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
|
|
2957
4122
|
console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
|
|
2958
4123
|
`);
|
|
2959
4124
|
} catch (err) {
|
|
@@ -2961,6 +4126,110 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
2961
4126
|
process.exit(1);
|
|
2962
4127
|
}
|
|
2963
4128
|
});
|
|
4129
|
+
var cacheCmd = program.command("cache").description("Manage local persistent SQLite metadata cache");
|
|
4130
|
+
cacheCmd.command("status").description("Display SQLite cache statistics and database path").action(async (options) => {
|
|
4131
|
+
try {
|
|
4132
|
+
const client = await getClient(options);
|
|
4133
|
+
const stats = await client.getCacheStats();
|
|
4134
|
+
if (!stats) {
|
|
4135
|
+
console.log(chalk2.yellow("\u26A0\uFE0F Persistent cache is disabled or not available."));
|
|
4136
|
+
return;
|
|
4137
|
+
}
|
|
4138
|
+
console.log(chalk2.bold.cyan("\n\u26A1 DriveKit Persistent SQLite Cache Status:"));
|
|
4139
|
+
console.log(`\u{1F4C1} Database Path: ${chalk2.dim(stats.databasePath)}`);
|
|
4140
|
+
console.log(`\u{1F4C2} Cached Folders: ${chalk2.bold.green(stats.folderCount.toLocaleString())}`);
|
|
4141
|
+
console.log(`\u{1F4C4} Cached Files: ${chalk2.bold.cyan(stats.fileCount.toLocaleString())}`);
|
|
4142
|
+
console.log(`\u{1F4BE} Indexed Size: ${chalk2.bold.white(formatBytes(stats.totalSizeBytes))}`);
|
|
4143
|
+
console.log(`\u{1F552} Last Full Sync: ${chalk2.dim(stats.lastSyncTime || "Never")}
|
|
4144
|
+
`);
|
|
4145
|
+
} catch (err) {
|
|
4146
|
+
console.error(chalk2.red(`Cache status failed: ${err.message}`));
|
|
4147
|
+
process.exit(1);
|
|
4148
|
+
}
|
|
4149
|
+
});
|
|
4150
|
+
cacheCmd.command("sync").description("Crawl Google Drive and index all file metadata into local SQLite for 0ms lookups").action(async (options) => {
|
|
4151
|
+
const spinner = ora("Indexing Google Drive metadata into SQLite...").start();
|
|
4152
|
+
try {
|
|
4153
|
+
const client = await getClient(options);
|
|
4154
|
+
const stats = await client.syncCache({
|
|
4155
|
+
onProgress: (scanned) => {
|
|
4156
|
+
spinner.text = `Indexing Google Drive metadata... (${chalk2.cyan(scanned.toLocaleString())} items scanned)`;
|
|
4157
|
+
}
|
|
4158
|
+
});
|
|
4159
|
+
spinner.succeed(chalk2.green(`Indexed ${stats.fileCount + stats.folderCount} items successfully!`));
|
|
4160
|
+
console.log(`\u{1F4BE} Database: ${chalk2.dim(stats.databasePath)}
|
|
4161
|
+
`);
|
|
4162
|
+
} catch (err) {
|
|
4163
|
+
spinner.fail(chalk2.red(`Cache sync failed: ${err.message}`));
|
|
4164
|
+
process.exit(1);
|
|
4165
|
+
}
|
|
4166
|
+
});
|
|
4167
|
+
cacheCmd.command("clear").description("Clear all cached metadata from local SQLite database").action(async (options) => {
|
|
4168
|
+
try {
|
|
4169
|
+
const client = await getClient(options);
|
|
4170
|
+
await client.clearCache();
|
|
4171
|
+
console.log(chalk2.green("\u{1F9F9} Local SQLite cache cleared successfully."));
|
|
4172
|
+
} catch (err) {
|
|
4173
|
+
console.error(chalk2.red(`Cache clear failed: ${err.message}`));
|
|
4174
|
+
process.exit(1);
|
|
4175
|
+
}
|
|
4176
|
+
});
|
|
4177
|
+
program.command("shared-drives").description("List accessible Google Workspace Shared Drives").action(async (options) => {
|
|
4178
|
+
const spinner = ora("Fetching Shared Drives...").start();
|
|
4179
|
+
try {
|
|
4180
|
+
const client = await getClient(options);
|
|
4181
|
+
const drives = await client.listSharedDrives();
|
|
4182
|
+
spinner.stop();
|
|
4183
|
+
if (drives.length === 0) {
|
|
4184
|
+
console.log(chalk2.yellow("\nNo Shared Drives found or accessible for this account.\n"));
|
|
4185
|
+
return;
|
|
4186
|
+
}
|
|
4187
|
+
console.log(chalk2.bold.cyan(`
|
|
4188
|
+
\u{1F3E2} Google Workspace Shared Drives (${drives.length}):`));
|
|
4189
|
+
for (const d of drives) {
|
|
4190
|
+
console.log(` \u{1F4C1} ${chalk2.bold.blue(d.name.padEnd(35))} ${chalk2.dim(`(ID: ${d.id})`)}`);
|
|
4191
|
+
}
|
|
4192
|
+
console.log("");
|
|
4193
|
+
} catch (err) {
|
|
4194
|
+
spinner.fail(chalk2.red(`Failed to list shared drives: ${err.message}`));
|
|
4195
|
+
process.exit(1);
|
|
4196
|
+
}
|
|
4197
|
+
});
|
|
4198
|
+
program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-u, --username <username>", "HTTP Basic auth username").option("-P, --password <password>", "HTTP Basic auth password").action(async (options) => {
|
|
4199
|
+
try {
|
|
4200
|
+
const client = await getClient(options);
|
|
4201
|
+
const port = parseInt(options.port, 10) || 8080;
|
|
4202
|
+
const host = options.host || "127.0.0.1";
|
|
4203
|
+
const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
|
|
4204
|
+
console.log(chalk2.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
|
|
4205
|
+
console.log("Starting local WebDAV bridge to Google Drive...\n");
|
|
4206
|
+
const serverInstance = await client.serveWebDAV({ port, host, auth });
|
|
4207
|
+
console.log(chalk2.bold.green(`\u{1F680} Server active at: ${chalk2.underline(serverInstance.url)}`));
|
|
4208
|
+
if (auth) {
|
|
4209
|
+
console.log(chalk2.yellow(`\u{1F512} Basic Authentication: ENABLED (User: ${auth.username})`));
|
|
4210
|
+
} else {
|
|
4211
|
+
console.log(chalk2.dim("\u{1F513} Authentication: Anonymous (Localhost only recommended)"));
|
|
4212
|
+
}
|
|
4213
|
+
console.log(chalk2.white("\n\u{1F4CC} How to mount on macOS Finder:"));
|
|
4214
|
+
console.log(` 1. Open Finder and press ${chalk2.bold.cyan("Cmd + K")} (Connect to Server)`);
|
|
4215
|
+
console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}`);
|
|
4216
|
+
console.log(` 3. Click ${chalk2.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
|
|
4217
|
+
`);
|
|
4218
|
+
console.log(chalk2.white("\u{1F4CC} How to mount on Windows:"));
|
|
4219
|
+
console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);
|
|
4220
|
+
console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}
|
|
4221
|
+
`);
|
|
4222
|
+
console.log(chalk2.dim("Press Ctrl+C to stop the WebDAV server.\n"));
|
|
4223
|
+
process.on("SIGINT", async () => {
|
|
4224
|
+
await serverInstance.close();
|
|
4225
|
+
console.log(chalk2.yellow("\nWebDAV server stopped. Goodbye!"));
|
|
4226
|
+
process.exit(0);
|
|
4227
|
+
});
|
|
4228
|
+
} catch (err) {
|
|
4229
|
+
console.error(chalk2.red(`Failed to start WebDAV server: ${err.message}`));
|
|
4230
|
+
process.exit(1);
|
|
4231
|
+
}
|
|
4232
|
+
});
|
|
2964
4233
|
function runCLI() {
|
|
2965
4234
|
program.parse(process.argv);
|
|
2966
4235
|
}
|