import * as Promise from 'bluebird' import { extract } from '../../../modules/archive' import { CoError } from '../../../modules/co-error' import { getPresentationPackagePath } from '../../../modules/pack-presentation' import { PresentationClient, Status } from '../../../services/presentation' import { copy, remove, removeExtension } from './fs' export default function (presentationClient: PresentationClient, presentationDir: string, presentationId: string): Promise { const presentationPackage = getPresentationPackagePath(presentationId) const tempDir = removeExtension(presentationPackage) return checkPresentationStatus(presentationClient, presentationId) .then(downloadPresentation(presentationClient, presentationPackage)) .then(extractToTempDir(presentationPackage, tempDir)) .then(copyPresentation(tempDir, presentationDir)) .then(removeTempFiles([tempDir])) .catch(removeTempFilesAndRethrowErr([tempDir])) } function checkPresentationStatus(presentationClient: PresentationClient, presentationId: string): Promise { return presentationClient.getPresentationStatus(presentationId) .then(failIfNotSuccess) .return(presentationId) } function failIfNotSuccess(status: Status): void { if(status === Status.InProgress){ throw new CoError('CLONED_PRESENTATION_IN_PROGRESS') } if(status === Status.Failed){ throw new CoError('CLONED_PRESENTATION_FAILED') } } function downloadPresentation(presentationClient: PresentationClient, tempZip: string): (id: string) => Promise { return function (id) { return presentationClient.downloadPresentation(id, tempZip) } } function extractToTempDir(tempZip: string, tempDir: string): () => Promise { return () => extract(tempZip, tempDir); } function copyPresentation(newPresentationDir: string, oldPresentationDir: string): () => Promise { return function () { return copy(newPresentationDir, oldPresentationDir) } } function removeTempFiles(files: string[]): () => Promise { return function () { return remove(files) } } function removeTempFilesAndRethrowErr(files: string[]): (err: Error) => Promise { return function (err) { return remove(files) .then(() => { throw err }) } }