misskey/src/services/drive/upload-from-url.ts

51 lines
1.2 KiB
TypeScript
Raw Normal View History

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