-
Notifications
You must be signed in to change notification settings - Fork 1
/
theScript.js
229 lines (211 loc) · 6.92 KB
/
theScript.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
//Node js script to convert a docx file to Google Doc and create a shortcut in its place
var ncp=require('copy-paste');
var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var ws=require('windows-shortcuts');
var child_process=require('child_process');
var path=require('path');
var args=process.argv.slice(2);
if(args.length==0){
console.log('Enter a file path');
process.exit();
}
var driveFolderName='GConvert';
var mtMap = {'xls':'application/vnd.google-apps.spreadsheet','xlsx':'application/vnd.google-apps.spreadsheet','csv':'application/vnd.google-apps.spreadsheet','doc':'application/vnd.google-apps.document','docx':'application/vnd.google-apps.document','pptx':'application/vnd.google-apps.presentation','ppt':'application/vnd.google-apps.presentation','txt':'text/plain'};
var filePath = args[0];
var fileName=filePath.substring(filePath.lastIndexOf('\\')+1);
var fileExtension=fileName.replace(/^.*\.(.*)$/,"$1");
var fileMainName=filePath.replace(/\.(.*)?$/,'');
/*
console.log('>>> filePath '+filePath);
console.log('>> fileName '+fileName);
console.log('>> fileExtnesion '+fileExtension);
console.log('fileMainName '+fileMainName);
*/
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
// If modifying these scopes, delete your previously saved credentials
// at ~/creds/gToken.json
var SCOPES = ['https://www.googleapis.com/auth/drive'];
var BASE_DIR=getUserHome()+'\\';
var TOKEN_DIR = BASE_DIR+'creds\\';
var TOKEN_PATH = TOKEN_DIR + 'gToken.json';
//console.log(TOKEN_PATH);
console.log('Converting....');
// Load client secrets from a local file.
fs.readFile(path.resolve(__dirname,'client_id.json'), function processClientSecrets(err, content) {
if (err) {
console.log('Error loading client secret file: ' + err);
console.log('Please copy client_id.json to the same folder as your script');
setTimeout(function(){},5000);
return;
}
// Authorize a client with the loaded credentials, then call the
// Drive API.
// authorize(JSON.parse(content), listFiles);
authorize(JSON.parse(content), listFiles);
});
/**
* Create an OAuth2 client with the given credentials, and then execute the
* given callback function.
*
* @param {Object} credentials The authorization client credentials.
* @param {function} callback The callback to call with the authorized client.
*/
function authorize(credentials, callback) {
var clientSecret = credentials.installed.client_secret;
var clientId = credentials.installed.client_id;
var redirectUrl = credentials.installed.redirect_uris[0];
var oauth2Client = new google.auth.OAuth2(clientId, clientSecret, redirectUrl);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, function(err, token) {
if (err) {
getNewToken(oauth2Client, callback);
} else {
oauth2Client.credentials = JSON.parse(token);
callback(oauth2Client);
}
});
}
/**
* Get and store new token after prompting for user authorization, and then
* execute the given callback with the authorized OAuth2 client.
*
* @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
* @param {getEventsCallback} callback The callback to call with the authorized
* client.
*/
function getNewToken(oauth2Client, callback) {
var authUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: SCOPES
});
console.log('Authorize this app by visiting this url: ', authUrl);
ncp.copy(authUrl);
console.log('The url has already been copied to your clipboard for your convenience');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('Enter the code from that page here: ', function(code) {
rl.close();
oauth2Client.getToken(code, function(err, token) {
if (err) {
console.log('Error while trying to retrieve access token', err);
return;
}
oauth2Client.credentials = token;
storeToken(token);
callback(oauth2Client);
});
});
}
/**
* Store token to disk be used in later program executions.
*
* @param {Object} token The token to store to disk.
*/
function storeToken(token) {
try {
fs.mkdirSync(TOKEN_DIR);
} catch (err) {
if (err.code != 'EEXIST') {
throw err;
}
}
fs.writeFile(TOKEN_PATH, JSON.stringify(token));
console.log('Token stored to ' + TOKEN_PATH);
}
/**
* Check whether the folder we are looking for to store the files, exist. If not call createFolder.
*
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
*/
function listFiles(auth) {
var service = google.drive('v3');
service.files.list({
q:"name='"+driveFolderName+"'",
auth: auth,
pageSize: 10,
fields: "nextPageToken, files(id, name)"
}, function(err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var files = response.files;
if (files.length == 0) {
console.log('No files found.');
createFolder(auth);
} else {
/* for (var i = 0; i < files.length; i++) {
var file = files[i];
console.log('%s (%s)', file.name, file.id);
}*/
insertFile(auth,files[0].id);
}
});
}
/**
* Create the folder to store the converted files in your root folder (My Drive) on Google Drive
*
*/
function createFolder(auth){
var service=google.drive('v3');
service.files.create({
auth: auth,
resource:{
'name':driveFolderName,
'mimeType':'application/vnd.google-apps.folder'
},
fields:'id'
},function(err,file){
if(err){
console.log('Could not create folder '+err);
insertFile(auth,'');
}
else
insertFile(auth,file.id);
});
}
/**
* Upload the selected file to drive, convert it if applicable,create a shortcut to the file in the same folder and open the file
*
*
*/
function insertFile(auth,pFolderId) {
var service=google.drive('v3');
service.files.create({
auth: auth,
fields:'id,webViewLink',
resource:{
// mimeType:'application/vnd.google-apps.document',
mimeType:mtMap[fileExtension]||'',
name:fileName,
parents:[pFolderId]
},
mediaUrl:'https://www.googleapis.com/upload/drive/v3/files',
media:{
// mimeType:'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
body:fs.createReadStream(filePath)
}
},function (err,resp) {
if(err){
console.log('An error occured '+err);
}else{
console.log('upload succeeded');
console.log(JSON.stringify(resp));
// ncp.copy(resp.webViewLink);
ws.create(fileMainName+'.g'+fileExtension+'.lnk',
{target:'chrome.exe',args: '--app="'+resp.webViewLink+'"',runStyle:ws.MIN},
function(err){
if(err)
console.log('An eror occured '+err);
else
child_process.execFile('chrome.exe',["--app="+resp.webViewLink]);
});
}
});
}