import { Service } from "../lib/service" import * as mongodb from "mongodb" import * as Leaf from "leaf-ts" import * as express from "express" import * as crypto from "crypto" import * as fs from "fs" import * as fsExtra from "fs-extra" import * as pathModule from "path" import * as uuid from "uuid" import { MongodbService } from "./mongodbService" import { ExpressService } from "./expressService" import { IncrementalIdService } from "./incrementalIdService" export type Callback = (e?: E, result?: T) => void export const Errors = Leaf.ErrorDoc.build({ HashError: {}, UnknowError: {}, NotFound: {} }) export interface Blob { name: string hash: string ext: string id: string mime?: string size?: number urls?: { type: string, value: string }[] } export class BlobService extends Service { readonly name = "BlobService" public blobCollection: mongodb.Collection readonly dependencies = ["MongodbService", "ExpressService"] readonly collectionName = "blob" services: { MongodbService: MongodbService IncrementalIdService: IncrementalIdService ExpressService: ExpressService } constructor(settings: Type.Root.BlobService.Settings) { super({ blob: { route: "/blob", storage: "/tmp/blob", } }, settings) } initialize(done) { this.blobCollection = this.services.MongodbService.db.collection(this.collectionName) this.blobCollection.createIndex({ id: 1 }) this.blobCollection.createIndex({ hash: 1 }) fsExtra.ensureDirSync(this.settings.blob.storage) // ensure this.services.ExpressService.server.post(this.settings.blob.route + "/:blobId/GET", (req, res) => { this.accessAuth(req, res, () => { this.getBlob({ id: req.params.blobId }, (err, blob) => { if (err) { res.json({ error: new Errors.NotFound(), state: false }) return } res.json({ state: true, data: blob }) }) }) }) let route = this.settings.blob.route + "/:blobId/:anything" this.services.ExpressService.server.get(route, this.handleRouteDownload.bind(this)) done() } setAccessAuth(handler: (req: Express.Request, res: Express.Response, next: Function) => void) { this.accessAuth = handler } private accessAuth = (req: Express.Request, res: Express.Response, next: Function) => { next() } private handleRouteDownload(req, res) { this.accessAuth(req, res, () => { let id = req.params.blobId console.error(id) this.getBlob({ id: id }, (err, blob) => { if (err || blob == null) { res.status(404).end("404") return } let path = this.createPathByHash(blob.hash) res.sendFile(path) }) }) } createBlob(option: { path: string, name: string }, callback: Callback) { this.stat(option.path, (err, stat) => { if (err) { callback(err) return } let ext = pathModule.extname(option.name) let id = uuid.v4() let blob: Blob = { name: option.name, ext, id, hash: stat.hash, size: stat.size, urls: [{ type: "local", value: `/blob/${id}/${option.name}` }] } let targetPath = pathModule.join(this.settings.blob.storage, blob.hash) this.blobCollection.findOne({ hash: blob.hash }, (err, one) => { if (one) { callback(null, one) return } fs.link(option.path, targetPath, (err) => { if (err) { callback(new Errors.UnknowError("Fail to hardlink")) return } this.blobCollection.insert(blob, (err, result) => { if (err) { if (err.code == 10010) { this.blobCollection.findOne(blob, (err, result) => { delete result["_id"] callback(err, result) }) } else { callback(new Errors.UnknowError("Fail to update database", { via: err })) } return } }) callback(null, blob) }) }) }) } private stat(path, callback: Callback<{ hash: string size: number }>) { let hash = crypto.createHash("md5") let stream = fs.createReadStream(path) let size = 0 stream.on("data", (data) => { size += data.length hash.update(data) }) stream.on("error", (err) => { stream.destroy() callback(new Errors.HashError("Fil to read disk file", { via: err })) }) stream.on("end", () => { let hex = hash.digest("hex") callback(null, { hash: hex, size }) }) } private createPathByHash(hash: string) { let path = `${this.settings.blob.storage}/${hash}` return path } getBlob(option: { id: string }, callback: Callback) { this.blobCollection.findOne({ id: option.id }, (err, blob) => { if (err || !blob) { callback(new Errors.NotFound("not fond in mongodb")) return } callback(null, blob) }) } }