forked from iann0036/cloud9-sync
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileManager.ts
349 lines (316 loc) · 14.8 KB
/
fileManager.ts
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import * as vscode from 'vscode';
import * as Utils from './utils';
import { EventEmitter } from 'events';
import * as request from 'request';
import * as path from 'path';
import * as fs from 'fs';
const SYNC_TIME_VARIANCE = 20000;
export class FileManager {
public awsregion;
public environmentId;
public cookieJar;
public xauth;
constructor(
private eventEmitter
) {
this.awsregion = Utils.GetRegion();
}
getFileWorkspacePath() {
if (vscode.workspace.workspaceFolders) {
let folders = vscode.workspace.workspaceFolders;
let workspaceFolder;
while (workspaceFolder = folders.pop()) {
if (workspaceFolder.uri.scheme == "file") {
return workspaceFolder.uri.fsPath;
}
};
}
return null;
}
recursiveDownload(startPath) {
console.log("Performing lookup from " + startPath);
return new Promise((resolve, reject) => {
request.get({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment' + startPath + "/",
jar: this.cookieJar,
headers: {
'Content-Type': 'text/plain',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
proxy: Utils.GetProxy()
}, (err, httpResponse, body) => {
Utils.ReducePromises(JSON.parse(body), (inode) => {
if (startPath + "/" + inode['name'] == "/.c9" || startPath + "/" + inode['name'] == "/.vscode") {
return Promise.resolve();
}
let workspacePath = this.getFileWorkspacePath();
if (workspacePath == null) {
vscode.window.showWarningMessage("Could not find local directory to sync to");
return Promise.reject();
}
let inodePath = path.join(workspacePath, startPath + "/" + inode['name']);
if (inode['mime'] == "inode/directory") {
if (!fs.existsSync(inodePath)){
console.log("Creating the directory " + inodePath);
fs.mkdirSync(inodePath);
}
return this.recursiveDownload(startPath + "/" + inode['name']);
} else {
if (fs.existsSync(inodePath)) {
let ftime = inode['mtime'];
let fstat = fs.statSync(inodePath);
let lftime = new Date(fstat['mtime']).getTime();
console.log(lftime);
console.log(ftime);
if (lftime + SYNC_TIME_VARIANCE > ftime) {
console.log(inodePath + " is up to date, skipping...");
return Promise.resolve();
}
}
return this.downloadFile(startPath + "/" + inode['name'], inodePath, inode);
}
})
.then(resolve, reject)
.catch((err) => {
console.error(err);
});
});
});
}
stat(filename) {
return new Promise((resolve, reject) => {
this.eventEmitter.emit('send_ch4_message', ["stat", "/" + filename, {}, {$: 91}]);
this.eventEmitter.on('ch4_data', (data, environmentId) => {
if (Array.isArray(data)) {
if (data.length>2) {
if (data[0] == 91) {
let contents = data[2];
resolve(contents);
}
}
}
});
});
}
listdir(filename): Thenable<Object[]> {
return new Promise((resolve, reject) => {
if (!filename.endsWith("/")) {
filename += "/";
}
request.get({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment/' + filename,
jar: this.cookieJar,
headers: {
'Content-Type': 'application/json',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
proxy: Utils.GetProxy()
}, function(err, httpResponse, body) {
console.warn("LISTDIR RESPONSE");
console.log(httpResponse);
console.log(body);
try {
let parsed_body = JSON.parse(body);
resolve(parsed_body);
} catch(err) {
reject(body)
}
});
});
}
downloadFile(filename, inodePath, inode): Thenable<string> {
return new Promise((resolve, reject) => {
request.get({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment/' + filename,
jar: this.cookieJar,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
proxy: Utils.GetProxy()
}, function(err, httpResponse, body) {
if (inodePath != null) {
console.log("Downloading the file " + inodePath);
fs.writeFileSync(inodePath, body);
//fs.utimes(inodePath, parseInt(inode.mtime/1000), parseInt(inode.mtime/1000), resolve); TODO: Fix
}
resolve(body); // REMOVE ME
});
});
}
uploadExistingFile(filename, content): Thenable<void> {
return new Promise((resolve, reject) => {
request.post({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment/' + filename,
jar: this.cookieJar,
headers: {
'Content-Type': 'text/plain',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
body: content,
proxy: Utils.GetProxy()
}, function(err, httpResponse, body) {
console.log(httpResponse);
console.log(body);
resolve();
});
});
}
uploadRemoteFile(filename, content): Thenable<void> {
return new Promise((resolve, reject) => {
request.put({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment/' + filename,
jar: this.cookieJar,
headers: {
'Content-Type': 'text/plain',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
body: content,
proxy: Utils.GetProxy()
}, function(err, httpResponse, body) {
console.log(httpResponse);
console.log(body);
if (httpResponse.statusCode == 429) { // retry with backoff
console.warn("retrying with backoff");
let response = JSON.parse(httpResponse);
setTimeout(() => {
this.uploadRemoteFile(filename, content).then(() => {
resolve();
}).catch(err => {
reject(err);
});
}, response.error.retryIn);
} else {
resolve();
}
});
});
}
deleteRemoteFile(filename): Thenable<void> {
return new Promise((resolve, reject) => {
request.delete({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment/' + filename,
jar: this.cookieJar,
headers: {
'Content-Type': 'text/plain',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
proxy: Utils.GetProxy()
}, function(err, httpResponse, body) {
console.log(err);
console.log(httpResponse);
console.log(body);
resolve();
});
});
}
recursiveUpload(startPath) {
console.log("Performing lookup from " + startPath);
return new Promise((resolve, reject) => {
let workspacePath = this.getFileWorkspacePath();
if (workspacePath == null) {
vscode.window.showWarningMessage("Could not find local directory to sync to");
reject("no local directory");
return;
}
let inodePath = path.join(workspacePath, startPath + "/");
request.get({
url: 'https://vfs.cloud9.' + this.awsregion + '.amazonaws.com/vfs/' + this.environmentId + '/environment' + Utils.EnsureLeadingSlash(startPath) + "/",
jar: this.cookieJar,
headers: {
'Content-Type': 'text/plain',
'Origin': 'https://' + this.awsregion + '.console.aws.amazon.com',
'Referer': 'https://' + this.awsregion + '.console.aws.amazon.com/cloud9/ide/' + this.environmentId,
'x-authorization': this.xauth
},
proxy: Utils.GetProxy()
}, (err, httpResponse, body) => {
console.log("REMOTE STAT FOR UPLOAD");
console.log(err);
console.log(body);
let remoteStats = [];
try {
remoteStats = JSON.parse(body);
if ('error' in remoteStats) {
reject();
}
} catch(err) {
console.log("Could not get remote stats");
console.log(body);
resolve();
}
console.log("About to do readdir on" + inodePath);
fs.readdir(inodePath, (err, files) => {
if (err) reject(err);
console.log("Reading - " + inodePath);
console.log(files);
if (!files) {
console.log("No files, skipping...");
resolve();
}
Utils.ReducePromises(files, (file) => {
let relativePath = path.join(startPath + "/", file);
console.log("Processing file: " + relativePath);
if (relativePath == "/.c9" || relativePath == "/.vscode" || relativePath == "/.git") {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
var filepath = path.join(inodePath, file);
console.log("Beginning upload processing of " + filepath + " (" + relativePath + ")");
fs.stat(filepath, (err, fstat) => {
if (fstat.isDirectory()) {
this.eventEmitter.emit('send_ch4_message',
["mkdir",relativePath,{},{"$":33}]
);
this.recursiveUpload(relativePath).then(function(){
resolve();
}).catch((err) => {
console.error(err);
});
} else if (fstat.isFile()) {
let ftime = null;
let lftime = new Date(fstat['mtime']).getTime();
console.log("Checking remote stats now");
remoteStats.forEach(remoteStat => {
if (remoteStat.name == relativePath) {
ftime = remoteStat.mtime;
}
});
console.log("ftime: " + ftime);
if (ftime == null) {
console.log("Uploading new file");
this.uploadRemoteFile(relativePath, fs.readFileSync(filepath));
} else if (lftime > ftime + SYNC_TIME_VARIANCE) {
console.log("Updating existing file");
this.uploadExistingFile(relativePath, fs.readFileSync(filepath));
}
resolve();
} else {
console.log("Unknown file type");
resolve();
}
});
});
})
.then(resolve, reject)
.catch((err) => {
console.error(err);
});
});
});
});
}
}