import fs = require ( 'fs' ) ; import mime = require ( 'mime-types' ) ; import gdrive = require ( './drive/drive-upload' ) ; import { DlVars } from './dl_model/detail' ; param { string } path param { string } parent param { function } callback export function uploadRecursive ( dlDetails , path , parent , callback ) { fs . stat ( path , ( err , stat ) => { if ( err ) { callback ( err . message , null , false ) ; return ; } if ( stat . isDirectory ( ) ) { gdrive . uploadFileOrFolder ( dlDetails , path , 'application/vnd.google-apps.folder' , parent , 0 , ( err , fileId ) => { if ( err ) { callback ( err , null , false ) ; } else { walkSubPath ( dlDetails , path , fileId , ( err ) => { if ( err ) { callback ( err , null , false ) ; } else { gdrive . getSharableLink ( fileId , true , callback ) ; } } ) ; } } ) ; } else { processFileOrDir ( dlDetails , path , parent , ( err , fileId ) => { if ( err ) { callback ( err , null , false ) ; } else { gdrive . getSharableLink ( fileId , false , callback ) ; } } ) ; } } ) ; } function walkSubPath ( dlDetails , path , parent , callback ) { fs . readdir ( path , ( err , files ) => { if ( err ) { callback ( err . message ) ; } else { walkSingleDir ( dlDetails , path , files , parent , callback ) ; } } ) ; } function walkSingleDir ( dlDetails , path , files , parent , callback ) { if ( files . length === 0 ) { callback ( null ) ; return ; } var uploadNext = function ( position ) : void { processFileOrDir ( dlDetails , path + '/' + files [ position ] , parent , ( err ) => { if ( err ) { callback ( err ) ; } else { if ( ++ position < files . length ) { uploadNext ( position ) ; } else { callback ( null ) ; } } } ) ; } ; uploadNext ( 0 ) ; } function processFileOrDir ( dlDetails , path , parent , callback ) { fs . stat ( path , ( err , stat ) => { if ( err ) { callback ( err . message ) ; return ; } if ( stat . isDirectory ( ) ) { gdrive . uploadFileOrFolder ( dlDetails , path , 'application/vnd.google-apps.folder' , parent , 0 , ( err , fileId ) => { if ( err ) { callback ( err ) ; } else { walkSubPath ( dlDetails , path , fileId , callback ) ; } } ) ; } else { var mimeType = mime . lookup ( path ) ; if ( ! mimeType ) { mimeType = 'application/octet-stream' ; } gdrive . uploadFileOrFolder ( dlDetails , path , mimeType , parent , stat . size , ( err , fileId ) => { if ( err ) { callback ( err ) ; } else { callback ( null , fileId ) ; } } ) ; } } ) ; }