cky-image-public
Version:
public image to public host
134 lines (110 loc) • 3.53 kB
JavaScript
const fs = require("fs");
const async = require('async');
const cheerio = require('cheerio');
const { google } = require('googleapis');
const _ = require('lodash');
let log = require('debug')('CKY-IMAGE-PUBLIC').extend('DRIVE');
const request = require('request').defaults({
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36'
}
})
let helper = require('../helper');
class Drive {
constructor (options = {}) {
let { access_token, client_id, client_secret, redirect_uris } = options;
this.access_token = access_token;
this.oAuth2Client = new google.auth.OAuth2(
// client_id,
// client_secret,
// redirect_uris
);
this.oAuth2Client.setCredentials({
access_token
});
this.drive = google.drive({
version: 'v3',
auth: this.oAuth2Client
});
}
upload (imgPath, callback) {
async.waterfall([
(next) => {
const fileSize = fs.statSync(imgPath).size;
this.drive.files.create({
requestBody: {
// a requestBody element is required if you want to use multipart
},
media: {
body: fs.createReadStream(imgPath),
},
}, {
// Use the `onUploadProgress` event from Axios to track the
// number of bytes uploaded to this point.
onUploadProgress: evt => {
const progress = (evt.bytesRead / fileSize) * 100;
log(`upload: ${Math.round(progress)}% complete`);
},
}, (err, result) => {
if (err) return next('ECREATEFILE', err);
return next(null, result.data);
});
},
(upload, next) => {
let permission = {
'type': 'anyone',
'role': 'reader',
}
this.drive.permissions.create({
resource: permission,
fileId: upload.id,
fields: 'id',
}, (err, res) =>{
if (err) return next('ECREATEPERMISSION', err);
let data = res.data;
data.urlShare = `https://drive.google.com/file/d/${upload.id}/view?usp=sharing`;
return next(null, data);
});
},
(shared, next) => {
this.getUrlImageFromShare(shared.urlShare, (err, img_urls) => {
shared.img_urls = img_urls;
return next(null, shared);
});
}
], callback);
}
getUrlImageFromShare (linkShare, callback) {
request({
url: linkShare,
method: 'GET'
}, (err, response, body) => {
if (err || !body) return callback(null, []);
let $ = cheerio.load(body);
let scripts = $('script');
let _listScript = [];
_.forEach(scripts, (s) => {
_listScript.push($(s).html());
});
let _findConfig = _listScript.find((s) => {
return s.indexOf('window.viewerData') > -1;
});
let img_urls = [];
if (_findConfig) {
let window = {};
eval(_findConfig);
if (window.viewerData && window.viewerData.itemJson) {
let itemJson = window.viewerData.itemJson;
_.forEach(itemJson, (item) => {
if (item && item.toString().indexOf('googleusercontent') > -1) {
img_urls.push(decodeURIComponent(item));
}
});
}
}
img_urls = _.uniq(img_urls);
return callback(null, img_urls);
});
}
}
module.exports = Drive;