sharkey/src/api/endpoints/drive/files/upload_from_url.ts

93 lines
2.2 KiB
TypeScript
Raw Normal View History

2017-02-17 05:46:14 +09:00
/**
* Module dependencies
*/
import * as URL from 'url';
2017-03-09 03:50:09 +09:00
import $ from 'cafy';
2017-02-17 05:46:14 +09:00
import { validateFileName } from '../../../models/drive-file';
import serialize from '../../../serializers/drive-file';
import create from '../../../common/add-file-to-drive';
import * as debug from 'debug';
import * as tmp from 'tmp';
import * as fs from 'fs';
import * as request from 'request';
import * as crypto from 'crypto';
const log = debug('misskey:endpoint:upload_from_url')
2017-02-17 05:46:14 +09:00
/**
* Create a file from a URL
*
2017-03-01 17:37:01 +09:00
* @param {any} params
* @param {any} user
* @return {Promise<any>}
2017-02-17 05:46:14 +09:00
*/
module.exports = (params, user) => new Promise((res, rej) => {
2017-02-17 05:46:14 +09:00
// Get 'url' parameter
2017-02-21 09:28:11 +09:00
// TODO: Validate this url
2017-03-09 03:50:09 +09:00
const [url, urlErr] = $(params.url).string().$;
2017-03-03 19:33:14 +09:00
if (urlErr) return rej('invalid url param');
2017-02-17 05:46:14 +09:00
let name = URL.parse(url).pathname.split('/').pop();
if (!validateFileName(name)) {
name = null;
}
// Get 'folder_id' parameter
2017-03-09 03:50:09 +09:00
const [folderId = null, folderIdErr] = $(params.folder_id).optional.nullable.id().$;
2017-03-03 19:33:14 +09:00
if (folderIdErr) return rej('invalid folder_id param');
2017-02-17 05:46:14 +09:00
// Create temp file
new Promise((res, rej) => {
tmp.file((e, path) => {
if (e) return rej(e)
res(path)
})
})
// Download file
.then((path: string) => 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)
}))
// Calculate hash & content-type
.then((path: string) => new Promise((res, rej) => {
const readable = fs.createReadStream(path)
const hash = crypto.createHash('md5')
readable
.on('error', rej)
.on('end', () => {
hash.end()
res([path, hash.digest('hex')])
})
.pipe(hash)
.on('error', rej)
}))
// Create file
.then((rv: string[]) => new Promise((res, rej) => {
const [path, hash] = rv
create(user, {
stream: fs.createReadStream(path),
name,
hash
}, null, folderId)
.then(driveFile => {
res(driveFile)
// crean-up
fs.unlink(path, (e) => {
if (e) log(e.stack)
})
})
.catch(rej)
}))
// Serialize
.then(serialize)
.then(res)
.catch(rej)
2017-02-17 05:46:14 +09:00
});