summaryrefslogtreecommitdiff
path: root/src/services/drive/upload-from-url.ts
blob: 73d9b1123a2c8be85c8605b9a95151ccbbe7d66e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as fs from 'fs';
import * as URL from 'url';

import * as debug from 'debug';
import * as tmp from 'tmp';
import * as request from 'request';

import { IDriveFile, validateFileName } from '../../models/drive-file';
import create from './add-file';
import config from '../../config';
import { IUser } from '../../models/user';
import * as mongodb from 'mongodb';

const log = debug('misskey:drive:upload-from-url');

export default async (url: string, user: IUser, folderId: mongodb.ObjectID = null, uri: string = null): Promise<IDriveFile> => {
	log(`REQUESTED: ${url}`);

	let name = URL.parse(url).pathname.split('/').pop();
	if (!validateFileName(name)) {
		name = null;
	}

	log(`name: ${name}`);

	// Create temp file
	const [path, cleanup] = await new Promise<[string, any]>((res, rej) => {
		tmp.file((e, path, fd, cleanup) => {
			if (e) return rej(e);
			res([path, cleanup]);
		});
	});

	// write content at URL to temp file
	await new Promise((res, rej) => {
		const writable = fs.createWriteStream(path);
		request(url)
			.on('error', rej)
			.on('end', () => {
				writable.close();
				res();
			})
			.pipe(writable)
			.on('error', rej);
	});

	let driveFile: IDriveFile;
	let error;

	try {
		driveFile = await create(user, path, name, null, folderId, false, config.preventCacheRemoteFiles, url, uri);
		log(`created: ${driveFile._id}`);
	} catch (e) {
		error = e;
		log(`failed: ${e}`);
	}

	// clean-up
	cleanup();

	if (error) {
		throw error;
	} else {
		return driveFile;
	}
};