2017-02-16 14:46:14 -06:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import * as URL from 'url';
|
2017-03-08 12:50:09 -06:00
|
|
|
import $ from 'cafy';
|
2018-02-03 23:52:33 -06:00
|
|
|
import { validateFileName, pack } from '../../../models/drive-file';
|
2017-02-16 14:46:14 -06:00
|
|
|
import create from '../../../common/add-file-to-drive';
|
2017-11-13 12:46:30 -06:00
|
|
|
import * as debug from 'debug';
|
|
|
|
import * as tmp from 'tmp';
|
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as request from 'request';
|
|
|
|
|
2017-11-13 12:47:42 -06:00
|
|
|
const log = debug('misskey:endpoint:upload_from_url');
|
2017-02-16 14:46:14 -06:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a file from a URL
|
|
|
|
*
|
2017-03-01 02:37:01 -06:00
|
|
|
* @param {any} params
|
|
|
|
* @param {any} user
|
|
|
|
* @return {Promise<any>}
|
2017-02-16 14:46:14 -06:00
|
|
|
*/
|
2017-11-13 13:28:51 -06:00
|
|
|
module.exports = async (params, user): Promise<any> => {
|
2017-02-16 14:46:14 -06:00
|
|
|
// Get 'url' parameter
|
2017-02-20 18:28:11 -06:00
|
|
|
// TODO: Validate this url
|
2017-03-08 12:50:09 -06:00
|
|
|
const [url, urlErr] = $(params.url).string().$;
|
2017-11-13 13:28:51 -06:00
|
|
|
if (urlErr) throw 'invalid url param';
|
2017-02-16 14:46:14 -06:00
|
|
|
|
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get 'folder_id' parameter
|
2017-03-08 12:50:09 -06:00
|
|
|
const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$;
|
2017-11-13 13:28:51 -06:00
|
|
|
if (folderIdErr) throw 'invalid folder_id param';
|
2017-02-16 14:46:14 -06:00
|
|
|
|
2017-11-13 12:46:30 -06:00
|
|
|
// Create temp file
|
2017-11-13 13:28:51 -06:00
|
|
|
const path = await new Promise((res: (string) => void, rej) => {
|
2017-11-13 12:46:30 -06:00
|
|
|
tmp.file((e, path) => {
|
2017-11-13 12:47:42 -06:00
|
|
|
if (e) return rej(e);
|
|
|
|
res(path);
|
|
|
|
});
|
2017-11-13 13:28:51 -06: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();
|
|
|
|
res(path);
|
|
|
|
})
|
|
|
|
.pipe(writable)
|
|
|
|
.on('error', rej);
|
|
|
|
});
|
|
|
|
|
|
|
|
const driveFile = await create(user, path, name, null, folderId);
|
|
|
|
|
|
|
|
// clean-up
|
|
|
|
fs.unlink(path, (e) => {
|
|
|
|
if (e) log(e.stack);
|
|
|
|
});
|
|
|
|
|
2018-02-01 17:21:30 -06:00
|
|
|
return pack(driveFile);
|
2017-11-13 13:28:51 -06:00
|
|
|
};
|