monkeeShark/src/services/drive/upload-from-url.ts

56 lines
1.2 KiB
TypeScript
Raw Normal View History

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