import * as fs from "fs" ; import * as tmp from "tmp" ; import { DirOptions , FileOptions } from "tmp" ; import { Stream } from "stream" ; import { Requests } from "./Requests" ; import { UploadedFile } from "express-fileupload" ; export const URL_DIR = "/tmp/url" ; export const UPL_DIR = "/tmp/upl" ; export const USR_DIR = "/tmp/usr" ; export const MOJ_DIR = "/tmp/moj" ; export class TempDir { constructor ( public readonly path , private readonly removeCallback ) { } remove ( ) { this . removeCallback ( ) ; } } export class TempFile extends TempDir { constructor ( public readonly path , public readonly fd , removeCallback ) { super ( path , removeCallback ) ; } remove ( ) { super . remove ( ) ; fs . close ( this . fd , ( ) => { } ) ; } } tmp . setGracefulCleanup ( ) ; export class Temp { static async file ( options ? ) { return new Promise ( ( resolve , reject ) => { tmp . file ( options || { } , ( err , name , fd , removeCallback ) => { if ( err ) { reject ( err ) ; } else { resolve ( new TempFile ( name , fd , removeCallback ) ) ; } } ) ; } ) ; } static async dir ( options ? ) { return new Promise ( ( resolve , reject ) => { tmp . dir ( options || { } , ( err , name , removeCallback ) => { if ( err ) { reject ( err ) ; } else { resolve ( new TempDir ( name , removeCallback ) ) ; } } ) ; } ) ; } public static async downloadImage ( url , tmpFile ? , breadcrumb ? ) { if ( ! tmpFile ) { tmpFile = await this . file ( ) ; } try { const response = await Requests . genericRequest ( { method : "GET" , url : url , responseType : "stream" } , breadcrumb ) ; ( response . data as Stream ) . pipe ( fs . createWriteStream ( tmpFile . path ) ) ; } catch ( e ) { if ( tmpFile ) { tmpFile . remove ( ) ; } throw e ; } return tmpFile ; } public static async copyUploadedImage ( uploadedFile , tmpFile ? ) { if ( ! tmpFile ) { tmpFile = await this . file ( ) ; } try { await uploadedFile . mv ( tmpFile . path ) ; } catch ( e ) { if ( tmpFile ) { tmpFile . remove ( ) ; } throw e ; } return tmpFile ; } }