import { join, basename } from 'path' import * as Promise from 'bluebird' // @ts-ignore import * as sanitize from 'sanitize-filename' import { PresentationClient, PresentationDetail } from '../../../services/presentation' import clonePresentation from '../src/clonePresentation' import { isEmptyDirectory } from '../src/fs' import { CoError } from '../../../modules/co-error' import ChecksumCalculator from '../src/ChecksumCalculator' import CobaltFilesHandler from '../src/CobaltFilesHandler' import PresentationFileChecksums from '../src/PresentationFileChecksums' export function clone (checksumCalculator: ChecksumCalculator, cobaltFileHandler: CobaltFilesHandler, presentationClient: PresentationClient, presentationDir: string, presentationId: string): Promise { return getPresentationName(presentationClient, presentationId) .then(getFullPresentationPath(presentationDir, presentationId)) .then(ensureDirectoryIsEmpty) .then((presentationPath: string) => clonePresentation(presentationClient, presentationPath, presentationId).return(presentationPath)) .then(createChecksum(checksumCalculator, cobaltFileHandler)) } function getFullPresentationPath(presentationDir: string, presentationId: string): (presentationName: string) => string { return function (presentationName) { return join(presentationDir, presentationName || presentationId) } } function ensureDirectoryIsEmpty(presentationDir: string): Promise { return isEmptyDirectory(presentationDir) .then(isEmpty => { if(!isEmpty){ throw new CoError('NOT_EMPTY_DIRECTORY', basename(presentationDir)) } }) .catch(err => { if(err.code !== 'ENOENT'){ throw err } }) .return(presentationDir) } function getPresentationName(presentationClient: PresentationClient, presentationId: string): Promise{ return presentationClient.getPresentationById(presentationId) .get('name') .then(normalizeFileName) } function normalizeFileName(name: string): string { return sanitize(name).trim() } function createChecksum(checksumCalculator: ChecksumCalculator, cobaltFileHandler: CobaltFilesHandler): (presentationPath: string) => Promise { return function(presentationPath) { cobaltFileHandler.setPresentationPath(presentationPath); return checksumCalculator.calculate(presentationPath) .then((checksum) => cobaltFileHandler.saveChecksums(checksum)); } }