2018-03-27 07:51:12 +00:00
|
|
|
import * as URL from 'url';
|
2018-04-04 18:21:11 +00:00
|
|
|
import { IDriveFile, validateFileName } from '../../models/drive-file';
|
2018-03-27 07:51:12 +00:00
|
|
|
import create from './add-file';
|
|
|
|
import * as debug from 'debug';
|
|
|
|
import * as tmp from 'tmp';
|
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as request from 'request';
|
|
|
|
|
2018-04-05 09:08:51 +00:00
|
|
|
const log = debug('misskey:drive:upload-from-url');
|
2018-03-27 07:51:12 +00:00
|
|
|
|
2018-04-03 14:45:13 +00:00
|
|
|
export default async (url, user, folderId = null, uri = null): Promise<IDriveFile> => {
|
2018-04-05 09:08:51 +00:00
|
|
|
log(`REQUESTED: ${url}`);
|
|
|
|
|
2018-03-27 07:51:12 +00:00
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
2018-04-05 09:08:51 +00:00
|
|
|
log(`name: ${name}`);
|
|
|
|
|
2018-03-27 07:51:12 +00:00
|
|
|
// Create temp file
|
2018-04-09 17:20:06 +00:00
|
|
|
const path = await new Promise<string>((res, rej) => {
|
2018-03-27 07:51:12 +00:00
|
|
|
tmp.file((e, path) => {
|
|
|
|
if (e) return rej(e);
|
|
|
|
res(path);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
|
|
|
|
// 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(path);
|
|
|
|
})
|
|
|
|
.pipe(writable)
|
|
|
|
.on('error', rej);
|
|
|
|
});
|
|
|
|
|
2018-04-03 14:45:13 +00:00
|
|
|
const driveFile = await create(user, path, name, null, folderId, false, uri);
|
2018-03-27 07:51:12 +00:00
|
|
|
|
2018-04-05 09:08:51 +00:00
|
|
|
log(`created: ${driveFile._id}`);
|
|
|
|
|
2018-03-27 07:51:12 +00:00
|
|
|
// clean-up
|
2018-04-09 17:20:06 +00:00
|
|
|
fs.unlink(path, e => {
|
|
|
|
if (e) console.error(e);
|
2018-03-27 07:51:12 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
return driveFile;
|
|
|
|
};
|