2018-05-25 04:19:14 -07:00
|
|
|
import create from './add-file';
|
2019-04-07 05:50:36 -07:00
|
|
|
import { User } from '../../models/entities/user';
|
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';
|
2020-04-11 03:49:25 -07:00
|
|
|
import { downloadUrl } from '../../misc/download-url';
|
2019-04-07 05:50:36 -07:00
|
|
|
import { DriveFolder } from '../../models/entities/drive-folder';
|
|
|
|
import { DriveFile } from '../../models/entities/drive-file';
|
|
|
|
import { DriveFiles } from '../../models';
|
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,
|
2020-01-29 13:06:50 -08:00
|
|
|
user: User | null,
|
2019-04-12 09:43:22 -07:00
|
|
|
folderId: DriveFolder['id'] | null = null,
|
|
|
|
uri: string | null = null,
|
2018-11-06 19:12:43 -08:00
|
|
|
sensitive = false,
|
2018-11-07 02:43:21 -08:00
|
|
|
force = false,
|
2020-10-17 04:12:00 -07:00
|
|
|
link = false,
|
|
|
|
comment = null
|
2019-04-07 05:50:36 -07:00
|
|
|
): Promise<DriveFile> => {
|
2019-04-12 09:43:22 -07:00
|
|
|
let name = new URL(url).pathname.split('/').pop() || null;
|
|
|
|
if (name == null || !DriveFiles.validateFileName(name)) {
|
2018-03-27 00:51:12 -07:00
|
|
|
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
|
|
|
|
2019-04-07 05:50:36 -07:00
|
|
|
let driveFile: DriveFile;
|
2018-04-09 12:11:52 -07:00
|
|
|
let error;
|
|
|
|
|
|
|
|
try {
|
2020-10-17 04:12:00 -07:00
|
|
|
driveFile = await create(user, path, name, comment, folderId, force, link, url, uri, sensitive);
|
2019-04-07 05:50:36 -07: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 {
|
2019-04-12 09:43:22 -07:00
|
|
|
return driveFile!;
|
2018-04-09 12:11:52 -07:00
|
|
|
}
|
2018-03-27 00:51:12 -07:00
|
|
|
};
|