UNPKG

@mieweb/wikigdrive

Version:

Google Drive to MarkDown synchronization

191 lines (190 loc) 11.7 kB
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { var useValue = arguments.length > 2; for (var i = 0; i < initializers.length; i++) { value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); } return useValue ? value : void 0; }; var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); var _, done = false; for (var i = decorators.length - 1; i >= 0; i--) { var context = {}; for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; for (var p in contextIn.access) context.access[p] = contextIn.access[p]; context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); if (kind === "accessor") { if (result === void 0) continue; if (result === null || typeof result !== "object") throw new TypeError("Object expected"); if (_ = accept(result.get)) descriptor.get = _; if (_ = accept(result.set)) descriptor.set = _; if (_ = accept(result.init)) initializers.unshift(_); } else if (_ = accept(result)) { if (kind === "field") initializers.unshift(_); else descriptor[key] = _; } } if (target) Object.defineProperty(target, contextIn.name, descriptor); done = true; }; import { Controller, RouteGet, RouteResponse } from './Controller.js'; import { GitScanner } from '../../../git/GitScanner.js'; import { UserConfigService } from '../../google_folder/UserConfigService.js'; import { GoogleDriveService } from '../../../google/GoogleDriveService.js'; import { MarkdownTreeProcessor } from '../../transform/MarkdownTreeProcessor.js'; import { googleMimeToExt } from '../../transform/TaskLocalFileTransform.js'; import { GoogleTreeProcessor } from '../../google_folder/GoogleTreeProcessor.js'; import { getContentFileService } from '../../transform/utils.js'; import { redirError } from '../auth.js'; let DriveController = (() => { var _a; let _classSuper = Controller; let _instanceExtraInitializers = []; let _getDrives_decorators; let _getDrive_decorators; let _downloadOdt_decorators; let _downloadTransformed_decorators; return _a = class DriveController extends _classSuper { constructor(subPath, filesService, folderRegistryContainer, authContainer) { super(subPath); Object.defineProperty(this, "filesService", { enumerable: true, configurable: true, writable: true, value: (__runInitializers(this, _instanceExtraInitializers), filesService) }); Object.defineProperty(this, "folderRegistryContainer", { enumerable: true, configurable: true, writable: true, value: folderRegistryContainer }); Object.defineProperty(this, "authContainer", { enumerable: true, configurable: true, writable: true, value: authContainer }); } async getDrives(ctx) { const user = await ctx.routeParamUser(); if (!user?.google_access_token) { throw redirError(ctx.req, 'Not authenticated'); } const folders = await this.folderRegistryContainer.getFolders(); const googleDriveService = new GoogleDriveService(ctx.logger, null); const drives = await googleDriveService.listDrives(user.google_access_token); return drives.map(drive => { return { id: drive.id, folderId: drive.id, name: drive.name, exists: !!folders[drive.id] }; }); } async getDrive(ctx) { const driveId = await ctx.routeParamPath('driveId'); const folders = await this.folderRegistryContainer.getFolders(); const drive = folders[driveId] || await this.folderRegistryContainer.registerFolder(driveId); const transformedFileSystem = await this.filesService.getSubFileService(driveId + '_transform', ''); const googleFileSystem = await this.filesService.getSubFileService(driveId, ''); const userConfigService = new UserConfigService(googleFileSystem); const userConfig = await userConfigService.load(); const gitScanner = new GitScanner(ctx.logger, transformedFileSystem.getRealPath(), 'wikigdrive@wikigdrive.com'); await gitScanner.initialize(); const contentFileService = await getContentFileService(transformedFileSystem, userConfigService); const markdownTreeProcessor = new MarkdownTreeProcessor(contentFileService); await markdownTreeProcessor.load(); const transformedTree = markdownTreeProcessor.getTree(); const tocFile = transformedTree.find(item => item.path === '/toc.md'); const navFile = transformedTree.find(item => item.path === '/.navigation.md' || item.path === '/navigation.md'); let tocFilePath = null; let navFilePath = null; if (userConfigService.config.transform_subdir && userConfigService.config.transform_subdir.length > 0) { const contentPrefix = (!userConfigService.config.transform_subdir.startsWith('/') ? '/' : '') + userConfigService.config.transform_subdir; tocFilePath = tocFile ? contentPrefix + tocFile.path : null; navFilePath = navFile ? contentPrefix + navFile.path : null; } return { ...drive, gitStats: await gitScanner.getStats(userConfig), tocFilePath, navFilePath }; } async downloadOdt(ctx) { const driveId = await ctx.routeParamPath('driveId'); const fileId = await ctx.routeParamPath('fileId'); try { const driveFileSystem = await this.filesService.getSubFileService(driveId, ''); const googleTreeProcessor = new GoogleTreeProcessor(driveFileSystem); await googleTreeProcessor.load(); const [file, drivePath] = await googleTreeProcessor.findById(fileId); if (file && drivePath) { const odtPath = drivePath + '.odt'; if (await driveFileSystem.exists(odtPath)) { driveFileSystem.createReadStream(odtPath).pipe(ctx.res); return; } } ctx.res.status(404).json({}); } catch (err) { if (err.message === 'Drive not shared with wikigdrive') { const authConfig = this.authContainer['authConfig']; ctx.res.status(404).json({ not_registered: true, share_email: authConfig.share_email }); return; } throw err; } } async downloadTransformed(ctx) { const driveId = await ctx.routeParamPath('driveId'); const fileId = await ctx.routeParamPath('fileId'); try { const driveFileSystem = await this.filesService.getSubFileService(driveId, ''); const googleTreeProcessor = new GoogleTreeProcessor(driveFileSystem); await googleTreeProcessor.load(); const [file, drivePath] = await googleTreeProcessor.findById(fileId); if (file && drivePath) { const filePath = `${drivePath}.${googleMimeToExt(file.mimeType, '')}`; if (await driveFileSystem.exists(filePath)) { ctx.res.header('Content-Disposition', `attachment; filename="${file['name']}.${googleMimeToExt(file.mimeType, '')}"`); driveFileSystem.createReadStream(filePath).pipe(ctx.res); return; } } ctx.res.status(404).json({}); } catch (err) { if (err.message === 'Drive not shared with wikigdrive') { const authConfig = this.authContainer['authConfig']; ctx.res.status(404).json({ not_registered: true, share_email: authConfig.share_email }); return; } throw err; } } }, (() => { const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0; _getDrives_decorators = [RouteGet('/')]; _getDrive_decorators = [RouteGet('/:driveId')]; _downloadOdt_decorators = [RouteGet('/:driveId/file/(:fileId).odt'), RouteResponse('stream', {}, 'application/vnd.oasis.opendocument.text')]; _downloadTransformed_decorators = [RouteGet('/:driveId/transformed/(:fileId)'), RouteResponse('stream', {}, 'image')]; __esDecorate(_a, null, _getDrives_decorators, { kind: "method", name: "getDrives", static: false, private: false, access: { has: obj => "getDrives" in obj, get: obj => obj.getDrives }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _getDrive_decorators, { kind: "method", name: "getDrive", static: false, private: false, access: { has: obj => "getDrive" in obj, get: obj => obj.getDrive }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _downloadOdt_decorators, { kind: "method", name: "downloadOdt", static: false, private: false, access: { has: obj => "downloadOdt" in obj, get: obj => obj.downloadOdt }, metadata: _metadata }, null, _instanceExtraInitializers); __esDecorate(_a, null, _downloadTransformed_decorators, { kind: "method", name: "downloadTransformed", static: false, private: false, access: { has: obj => "downloadTransformed" in obj, get: obj => obj.downloadTransformed }, metadata: _metadata }, null, _instanceExtraInitializers); if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); })(), _a; })(); export { DriveController };