2017-02-16 21:46:14 +01:00
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import * as URL from 'url';
|
|
|
|
const download = require('download');
|
2017-03-05 04:00:39 +01:00
|
|
|
import it from 'cafy';
|
2017-02-16 21:46:14 +01:00
|
|
|
import { validateFileName } from '../../../models/drive-file';
|
|
|
|
import serialize from '../../../serializers/drive-file';
|
|
|
|
import create from '../../../common/add-file-to-drive';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a file from a URL
|
|
|
|
*
|
2017-03-01 09:37:01 +01:00
|
|
|
* @param {any} params
|
|
|
|
* @param {any} user
|
|
|
|
* @return {Promise<any>}
|
2017-02-16 21:46:14 +01:00
|
|
|
*/
|
2017-03-03 20:28:38 +01:00
|
|
|
module.exports = (params, user) => new Promise(async (res, rej) => {
|
2017-02-16 21:46:14 +01:00
|
|
|
// Get 'url' parameter
|
2017-02-21 01:28:11 +01:00
|
|
|
// TODO: Validate this url
|
2017-03-05 04:00:39 +01:00
|
|
|
const [url, urlErr] = it(params.url).expect.string().required().get();
|
2017-03-03 11:33:14 +01:00
|
|
|
if (urlErr) return rej('invalid url param');
|
2017-02-16 21:46:14 +01:00
|
|
|
|
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get 'folder_id' parameter
|
2017-03-05 04:00:39 +01:00
|
|
|
const [folderId = null, folderIdErr] = it(params.folder_id).expect.nullable.id().get();
|
2017-03-03 11:33:14 +01:00
|
|
|
if (folderIdErr) return rej('invalid folder_id param');
|
2017-02-16 21:46:14 +01:00
|
|
|
|
|
|
|
// Download file
|
|
|
|
const data = await download(url);
|
|
|
|
|
|
|
|
// Create file
|
2017-03-03 11:33:14 +01:00
|
|
|
const driveFile = await create(user, data, name, null, folderId);
|
2017-02-16 21:46:14 +01:00
|
|
|
|
|
|
|
// Serialize
|
|
|
|
const fileObj = await serialize(driveFile);
|
|
|
|
|
|
|
|
// Response
|
|
|
|
res(fileObj);
|
|
|
|
});
|