2017-02-17 05:46:14 +09:00
|
|
|
'use strict';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Module dependencies
|
|
|
|
*/
|
|
|
|
import * as URL from 'url';
|
|
|
|
const download = require('download');
|
|
|
|
import * as mongo from 'mongodb';
|
|
|
|
import File from '../../../models/drive-file';
|
|
|
|
import { validateFileName } from '../../../models/drive-file';
|
|
|
|
import User from '../../../models/user';
|
|
|
|
import serialize from '../../../serializers/drive-file';
|
|
|
|
import create from '../../../common/add-file-to-drive';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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(async (res, rej) =>
|
|
|
|
{
|
|
|
|
// Get 'url' parameter
|
2017-02-21 09:28:11 +09:00
|
|
|
// TODO: Validate this url
|
2017-02-17 05:46:14 +09:00
|
|
|
const url = params.url;
|
|
|
|
if (url == null) {
|
|
|
|
return rej('url is required');
|
|
|
|
}
|
|
|
|
|
|
|
|
let name = URL.parse(url).pathname.split('/').pop();
|
|
|
|
if (!validateFileName(name)) {
|
|
|
|
name = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get 'folder_id' parameter
|
|
|
|
let folder = params.folder_id;
|
|
|
|
if (folder === undefined || folder === null) {
|
|
|
|
folder = null;
|
|
|
|
} else {
|
|
|
|
folder = new mongo.ObjectID(folder);
|
|
|
|
}
|
|
|
|
|
|
|
|
// Download file
|
|
|
|
const data = await download(url);
|
|
|
|
|
|
|
|
// Create file
|
|
|
|
const driveFile = await create(user, data, name, null, folder);
|
|
|
|
|
|
|
|
// Serialize
|
|
|
|
const fileObj = await serialize(driveFile);
|
|
|
|
|
|
|
|
// Response
|
|
|
|
res(fileObj);
|
|
|
|
});
|