2018-05-25 20:19:14 +09:00
|
|
|
import * as fs from 'fs';
|
2018-03-27 16:51:12 +09:00
|
|
|
import * as URL from 'url';
|
2018-05-25 20:19:14 +09:00
|
|
|
|
2018-03-27 16:51:12 +09:00
|
|
|
import * as debug from 'debug';
|
|
|
|
import * as tmp from 'tmp';
|
|
|
|
import * as request from 'request';
|
|
|
|
|
2018-05-25 20:19:14 +09:00
|
|
|
import { IDriveFile, validateFileName } from '../../models/drive-file';
|
|
|
|
import create from './add-file';
|
|
|
|
import config from '../../config';
|
2018-06-17 20:04:19 +09:00
|
|
|
import { IUser } from '../../models/user';
|
|
|
|
import * as mongodb from "mongodb";
|
2018-05-25 20:19:14 +09:00
|
|
|
|
2018-04-05 18:08:51 +09:00
|
|
|
const log = debug('misskey:drive:upload-from-url');
|
2018-03-27 16:51:12 +09:00
|
|
|
|
2018-06-17 20:04:19 +09:00
|
|
|
export default async (url: string, user: IUser, folderId: mongodb.ObjectID = null, uri: string = null): Promise<IDriveFile> => {
|
2018-04-05 18:08:51 +09:00
|
|
|
log(`REQUESTED: ${url}`);
|
|
|
|
|
2018-03-27 16:51:12 +09:00
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
2018-04-05 18:08:51 +09:00
|
|
|
log(`name: ${name}`);
|
|
|
|
|
2018-03-27 16:51:12 +09:00
|
|
|
// Create temp file
|
2018-04-10 04:02:25 +09:00
|
|
|
const [path, cleanup] = await new Promise<[string, any]>((res, rej) => {
|
|
|
|
tmp.file((e, path, fd, cleanup) => {
|
2018-03-27 16:51:12 +09:00
|
|
|
if (e) return rej(e);
|
2018-04-10 04:02:25 +09:00
|
|
|
res([path, cleanup]);
|
2018-03-27 16:51:12 +09:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// 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();
|
2018-04-10 04:03:25 +09:00
|
|
|
res();
|
2018-03-27 16:51:12 +09:00
|
|
|
})
|
|
|
|
.pipe(writable)
|
|
|
|
.on('error', rej);
|
|
|
|
});
|
|
|
|
|
2018-04-10 04:11:52 +09:00
|
|
|
let driveFile: IDriveFile;
|
|
|
|
let error;
|
|
|
|
|
|
|
|
try {
|
2018-05-25 20:19:14 +09:00
|
|
|
driveFile = await create(user, path, name, null, folderId, false, config.preventCacheRemoteFiles, url, uri);
|
2018-04-10 04:11:52 +09:00
|
|
|
log(`created: ${driveFile._id}`);
|
|
|
|
} catch (e) {
|
|
|
|
error = e;
|
|
|
|
log(`failed: ${e}`);
|
|
|
|
}
|
2018-04-05 18:08:51 +09:00
|
|
|
|
2018-03-27 16:51:12 +09:00
|
|
|
// clean-up
|
2018-04-10 04:02:25 +09:00
|
|
|
cleanup();
|
2018-03-27 16:51:12 +09:00
|
|
|
|
2018-04-10 04:11:52 +09:00
|
|
|
if (error) {
|
|
|
|
throw error;
|
|
|
|
} else {
|
|
|
|
return driveFile;
|
|
|
|
}
|
2018-03-27 16:51:12 +09:00
|
|
|
};
|