Sharkey/src/api/drive/upload-from-url.ts

47 lines
1.1 KiB
TypeScript
Raw Normal View History

2018-03-27 09:51:12 +02:00
import * as URL from 'url';
2018-04-02 05:58:53 +02:00
import { IDriveFile, validateFileName } from '../models/drive-file';
2018-03-27 09:51:12 +02: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';
const log = debug('misskey:common:drive:upload_from_url');
2018-04-03 16:45:13 +02:00
export default async (url, user, folderId = null, uri = null): Promise<IDriveFile> => {
2018-03-27 09:51:12 +02:00
let name = URL.parse(url).pathname.split('/').pop();
if (!validateFileName(name)) {
name = null;
}
// Create temp file
const path = await new Promise((res: (string) => void, rej) => {
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 16:45:13 +02:00
const driveFile = await create(user, path, name, null, folderId, false, uri);
2018-03-27 09:51:12 +02:00
// clean-up
fs.unlink(path, (e) => {
if (e) log(e.stack);
});
return driveFile;
};