2018-03-27 00:51:12 -07:00
|
|
|
import * as URL from 'url';
|
|
|
|
|
2018-05-25 04:19:14 -07:00
|
|
|
import { IDriveFile, validateFileName } from '../../models/drive-file';
|
|
|
|
import create from './add-file';
|
2018-06-17 04:04:19 -07:00
|
|
|
import { IUser } from '../../models/user';
|
2018-06-17 22:28:43 -07:00
|
|
|
import * as mongodb from 'mongodb';
|
2019-02-02 23:45:13 -08:00
|
|
|
import { driveLogger } from './logger';
|
2019-03-20 12:50:44 -07:00
|
|
|
import { createTemp } from '../../misc/create-temp';
|
|
|
|
import { downloadUrl } from '../../misc/donwload-url';
|
2018-05-25 04:19:14 -07:00
|
|
|
|
2019-02-02 23:45:13 -08:00
|
|
|
const logger = driveLogger.createSubLogger('downloader');
|
2018-03-27 00:51:12 -07:00
|
|
|
|
2018-11-06 19:12:43 -08:00
|
|
|
export default async (
|
|
|
|
url: string,
|
|
|
|
user: IUser,
|
|
|
|
folderId: mongodb.ObjectID = null,
|
|
|
|
uri: string = null,
|
|
|
|
sensitive = false,
|
2018-11-07 02:43:21 -08:00
|
|
|
force = false,
|
|
|
|
link = false
|
2018-11-06 19:12:43 -08:00
|
|
|
): Promise<IDriveFile> => {
|
2018-03-27 00:51:12 -07:00
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create temp file
|
2019-03-20 12:50:44 -07:00
|
|
|
const [path, cleanup] = await createTemp();
|
2018-03-27 00:51:12 -07:00
|
|
|
|
|
|
|
// write content at URL to temp file
|
2019-03-20 12:50:44 -07:00
|
|
|
await downloadUrl(url, path);
|
2018-03-27 00:51:12 -07:00
|
|
|
|
2018-04-09 12:11:52 -07:00
|
|
|
let driveFile: IDriveFile;
|
|
|
|
let error;
|
|
|
|
|
|
|
|
try {
|
2018-11-07 02:43:21 -08:00
|
|
|
driveFile = await create(user, path, name, null, folderId, force, link, url, uri, sensitive);
|
2019-02-03 00:09:16 -08:00
|
|
|
logger.succ(`Got: ${driveFile._id}`);
|
2018-04-09 12:11:52 -07:00
|
|
|
} catch (e) {
|
|
|
|
error = e;
|
2019-03-02 15:00:39 -08:00
|
|
|
logger.error(`Failed to create drive file: ${e}`, {
|
|
|
|
url: url,
|
|
|
|
e: e
|
|
|
|
});
|
2018-04-09 12:11:52 -07:00
|
|
|
}
|
2018-04-05 02:08:51 -07:00
|
|
|
|
2018-03-27 00:51:12 -07:00
|
|
|
// clean-up
|
2018-04-09 12:02:25 -07:00
|
|
|
cleanup();
|
2018-03-27 00:51:12 -07:00
|
|
|
|
2018-04-09 12:11:52 -07:00
|
|
|
if (error) {
|
|
|
|
throw error;
|
|
|
|
} else {
|
|
|
|
return driveFile;
|
|
|
|
}
|
2018-03-27 00:51:12 -07:00
|
|
|
};
|