-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patho2.js
More file actions
277 lines (251 loc) · 10 KB
/
o2.js
File metadata and controls
277 lines (251 loc) · 10 KB
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
"use strict";
var menuBar = require('menubar');
var Client = require('node-rest-client').Client;
var shell = require('shell');
var ipc = require('ipc');
var fs = require('fs-promise');
var app = require('app');
var _ = require('underscore');
var sanitize = require('sanitize-filename');
var nodePath = require('path');
var foldToAscii = require('fold-to-ascii');
var ConfigStore = require('configstore');
var pkg = require('./package.json');
var nodeRequest = require('request');
var dialog = require('dialog');
var move = require('./fileSystem.js');
var Menu = require("menu");
var mbOptions = {"width": 400, "height": 400};
var appSettings = new ConfigStore(pkg.name);
var userSettings = null;
var mb = menuBar(mbOptions);
var webContents = null;
var baseUrl = 'https://staging-api.osf.io/v2/';
var showNodes = function(nodes) {
console.log('sending getNodes to ui');
mb.window.send('getNodes', nodes);
};
var getNodeFiles = function(nodeId) {
console.log('Getting node files');
var files = {};
var statusCode;
mb.window._client.methods.nodeFiles({'path':{'id': nodeId}}, function(data, response) {
statusCode = response.statusCode;
if(statusCode === 200) {
var fileData = JSON.parse(data.toString());
var increment = 1;
_.each(fileData.data, function (file) {
var safeFilename;
var sanitizedName = sanitize(foldToAscii.fold(file.attributes.name));
var currentFilenames = _.keys(files);
if (_.contains(currentFilenames, sanitizedName)) {
var parsedName = nodePath.parse(sanitizedName);
safeFilename = parsedName.name + '_' + increment + parsedName.ext;
increment += 1;
} else {
safeFilename = sanitizedName;
}
if (safeFilename !== file.attributes.name) {
var args = {
'data': {
'action': 'rename',
'rename': safeFilename
},
'headers': {
'Content-Type': 'application/vnd.api+json'
}
};
mb.window._client.post(file.links.move, args, function (data, response) {
var parsedData = JSON.parse(data.toString());
mb.window.send('addStatusMessage', 'Renamed ' + parsedData.data.id + ' to ' + parsedData.data.attributes.name);
});
}
files[safeFilename] = _.extend(file.attributes, file.links);
});
getRemoteFiles(files);
} else{
if (statusCode === 401) {
mb.window.send('setLogin', false, "Problem with your login. Please try again.");
} else if (statusCode === 400 || statusCode >= 500){
mb.window.send('setNodeLoc', true, "Problem with OSF. If it persists, contact us.");
}
else {
userSettings.del('syncFolder');
userSettings.del('currentNode');
var problemMessage = "Problem retrieving your node.";
if (statusCode === 404) {
problemMessage = "Could not find your node.";
} else if (statusCode === 403) {
problemMessage = "You do not have permission for this node.";
}
mb.window.send('setNodeLoc', false, problemMessage + " Please select a new node.");
getNodes();
}
}
});
};
var getRemoteFiles = function(files) {
var tempDir = app.getPath('temp');
var finalDir = userSettings.get('syncFolder');
_.each(files, function(file, sanitizedFilename) {
// get the file payload from osf
mb.window._client.get(file.download, function(data, response) {
// create a local stream
var filePointer = fs.createWriteStream(nodePath.join(tempDir, sanitizedFilename));
// get the file body from the ☁️
nodeRequest.get(response.headers.location).pipe(filePointer);
filePointer.on('finish', function() {
var finalDirStat;
try {
// see if the final dir exists
finalDirStat = fs.statSync(finalDir);
mb.window.send('addStatusMessage', 'Found directory '+ finalDir);
} catch (e) {
// create it if it doesn't
// TODO: figure out what the error is if the dir can't be created, then clear syncFolder, stop transfer, and setNodeLoc to false
var literallyUndefined = fs.mkdirSync(finalDir);
mb.window.send('addStatusMessage', 'Created '+ finalDir);
} finally {
// move each file from tmp to final
move(nodePath.join(tempDir, sanitizedFilename), nodePath.join(finalDir, sanitizedFilename), function(err, oldName, newName) {
if (err !== null) {
mb.window.send('addStatusMessage', 'Failed to move '+oldName+' to '+newName+' '+err);
} else {
mb.window.send('addStatusMessage', 'Downloaded '+ newName);
}
});
}
});
});
});
};
var showFiles = function(files){
mb.window.send('getFiles', files);
};
ipc.on('user-login', function(ev, auth) {
console.log('caught user-login');
setupClient(auth.username, auth.password);
appSettings.set('lastUsername', auth.username);
});
var setupClient = function (username, password) {
var client;
if((username === null) && (password === null) || (username === '') && (password === '')) {
client = new Client();
mb.window.send('setLogin', false);
} else {
var options_auth = { user: username, password: password };
client = new Client(options_auth);
client.registerMethod('me', baseUrl+'users/me/', 'GET');
client.methods.me(function(data, response) {
if(response.statusCode === 200) {
var json = JSON.parse(data.toString());
var user_id = json.data.id;
userSettings = new ConfigStore(pkg.name + user_id);
mb.window.send('setLogin', true, 'Logged in.');
var currentNode = userSettings.get('currentNode');
var syncFolder = userSettings.get('syncFolder');
if (currentNode && syncFolder) {
console.log("Already have node " + currentNode + " and folder " + syncFolder);
mb.window.send('setNodeLoc', true);
getNodeFiles(currentNode);
} else {
getNodes();
}
} else {
mb.window.send('setLogin', false, "Problem with your login. Please try again.");
}
});
}
client.registerMethod("nodes", baseUrl+"nodes/", "GET");
client.registerMethod("myNodes", baseUrl+"users/me/nodes/?page[size]=100", "GET");
client.registerMethod("nodeOptions", baseUrl+'nodes/${id}', 'OPTIONS');
client.registerMethod('nodeFiles', baseUrl+'nodes/${id}/files/osfstorage/?filter[kind]=file&page[size]=100', 'GET');
mb.window._client = client;
console.log('Client setup.');
};
var getNodes = function () {
console.log('Getting Nodes');
if(!mb.window._client) {
setupClient();
}
console.log('making http request');
mb.window._client.methods.myNodes(function(data, response) {
var json = JSON.parse(data.toString());
console.log('got http response');
showNodes(json.data);
});
};
mb.on('ready', function ready () {
ipc.on('did-finish-load',function(){
var email = appSettings.get('lastUsername');
mb.window.send('setEmailField', email);
// getNodes();
console.log('Starting file list');
var path = process.cwd();
// readdir requires a trailing slash.
if (path.substr(path.length-1) !== '/') {
path = path + '/';
}
var theFiles = fs.readdir(path).then(function(files) {
var onlyFiles = {};
for (var i = 0; i < files.length; i++) {
var filePath = path + files[i];
var fileStat = fs.statSync(filePath);
if(!fileStat.isDirectory()) {
onlyFiles[path+files[i]] = {'stat': fileStat, 'sha': null};
}
}
return onlyFiles;
}).then(function(files) {
showFiles(files);
});
});
ipc.on('exit', function() {
app.quit();
});
ipc.on('sync', function() {
console.log("We should sync");
mb.window.send('addStatusMessage', "Syncing now…");
});
ipc.on('settings', function() {
mb.window.send('setNodeLoc', false);
getNodes();
});
ipc.on('did-select-node', function(ev, nodeId, nodeTitle, parentFolder) {
userSettings.set('currentNode', nodeId);
var nodeTitleFolderName = sanitize(foldToAscii.fold(nodeTitle));
userSettings.set('syncFolder', nodePath.join(parentFolder[0], nodeTitleFolderName));
mb.window.send('setNodeLoc', true);
getNodeFiles(nodeId);
});
ipc.on('choose-local-folder', function(){
dialog.showOpenDialog(mb.window, {properties: ['openDirectory']}, function (folderPath) {
mb.window.send('setLocalFolder', folderPath);
});
});
// Create the Application's main menu
var template = [{
label: "Application",
submenu: [
{ label: "About Application", selector: "orderFrontStandardAboutPanel:" },
{ type: "separator" },
{ label: "Quit", accelerator: "Command+Q", click: function() { app.quit(); }}
]}, {
label: "Edit",
submenu: [
{ label: "Undo", accelerator: "CmdOrCtrl+Z", selector: "undo:" },
{ label: "Redo", accelerator: "Shift+CmdOrCtrl+Z", selector: "redo:" },
{ type: "separator" },
{ label: "Cut", accelerator: "CmdOrCtrl+X", selector: "cut:" },
{ label: "Copy", accelerator: "CmdOrCtrl+C", selector: "copy:" },
{ label: "Paste", accelerator: "CmdOrCtrl+V", selector: "paste:" },
{ label: "Select All", accelerator: "CmdOrCtrl+A", selector: "selectAll:" }
]}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
console.log('app is ready and updating');
});
mb.on('after-create-window', function ready () {
webContents = mb.window.webContents;
//mb.window.openDevTools();
});