-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
485 lines (411 loc) · 14.5 KB
/
server.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
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
const https = require('https');
const fs = require('fs');
const express = require('express');
const msal = require('@azure/msal-node');
const cors = require('cors');
const app = express();
const port = 3002;
app.use(cors());
app.use(express.json());
let credentials = {};
let siteName = {};
// Get the credentials of ArcGIS server.
app.post('/set-credentials', (req, res) => {
credentials = req.body;
res.send({ status: 'Credentials set' });
});
const httpsOptions = {
key: fs.readFileSync('server.key'), // replace with actual path
cert: fs.readFileSync('server.cert') // replace with actual path
};
const server = https.createServer(httpsOptions, app);
// Get the site Name of ArcGIS server.
app.post('/set-siteName', (req, res) => {
siteName = req.body;
res.send({ status: 'Name set' });
});
// Function to check if a token is expired.
function isTokenExpired(token) {
const currentTime = new Date();
return currentTime >= token.expiresOn;
}
// Initialize cachedToken variable.
let cachedToken = null;
// Function to get a valid token.
async function getValidToken() {
if (!cachedToken || isTokenExpired(cachedToken)) {
const cca = new msal.ConfidentialClientApplication({
auth: {
clientId: credentials.client_id,
authority: "https://login.microsoftonline.com/" + credentials.tenant_id,
clientSecret: credentials.client_secret,
},
});
const response = await cca.acquireTokenByClientCredential({
scopes: ["https://graph.microsoft.com/.default"],
});
cachedToken = response;
}
return cachedToken;
}
async function termMiddleware(req, res, next) {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
let termGroupId;
let termSetId;
//------------------------TERM GROUP---------------------------
const termGroupsResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/groups', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const dataGroups = await termGroupsResponse.json();
const foundGroup = dataGroups.value.find(termGroup => termGroup.displayName === "GeoTag");
if (foundGroup) {
console.log("Found TermGroup GeoTag!");
termGroupId = foundGroup.id;
} else {
console.log("Creating TermGroup GeoTag...");
const urlencoded = new URLSearchParams();
urlencoded.append("displayName", "GeoTag");
const createTermGroupsResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/groups', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
},
body: urlencoded,
redirect: 'follow'
});
const dataCreateGroups = await createTermGroupsResponse.json();
termGroupId = dataCreateGroups.id;
}
//------------------------TERM SET---------------------------
const termSetsResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/groups/' + termGroupId + '/sets', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const dataSets = await termSetsResponse.json();
const foundSet = dataSets.value.find(termSet =>
termSet.localizedNames.some(localizedName => localizedName.name === "GeoTag")
);
if (foundSet) {
console.log("Found TermSet GeoTag!");
termSetId = foundSet.id;
} else {
console.log("Creating TermSet GeoTag...");
const createTermSetsResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/sets', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
},
body: JSON.stringify({
"parentGroup": {
"id": termGroupId
},
"description": "GeoTag",
"localizedNames": [
{
"languageTag": "en-US",
"name": "GeoTag"
}
]
}),
redirect: 'follow'
});
const dataCreateSets = await createTermSetsResponse.json();
termSetId = dataCreateSets.id;
}
req.termData = {
termGroupId: termGroupId,
termSetId: termSetId
};
next();
} catch (err) {
console.log(err);
res.status(500).send(err);
}
}
// Get token.
app.get('/token', async (req, res) => {
try {
const token = await getValidToken();
res.send(token);
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
// Get data.
app.get('/getSites', async (req, res) => {
let sitesData = [];
let siteId;
try {
const token = await getValidToken();
const sitesResponse = await fetch('https://graph.microsoft.com/v1.0/sites', {
headers: {
'Authorization': token.accessToken,
}
});
const data = await sitesResponse.json();
sitesData = data.value;
sitesData.forEach(site => {
if (siteName.site_name == site.name) {
siteId = site.id;
siteWebUrl = site.webUrl;
}
});
if (siteId != undefined) {
res.json({ siteId, siteWebUrl });
} else {
res.send(null);
}
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
app.get('/display-ff', async (req, res) => {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
let folderId = req.headers.folderid;
if (folderId === "null") {
folderId = "root";
}
const filesResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/drive/items/' + folderId + '/children?&select=id,eTag,package&expand=listitem(expand=fields(select=FileLeafRef,DocIcon,GeoTag,ContentType))', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const data = await filesResponse.json();
res.send(data);
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
app.patch('/addTag', termMiddleware, async (req, res) => {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
const tag = req.body.tag;
const fileTags = req.body.fileTags;
const fileId = req.body.fileId;
//------------------------TERM---------------------------
const termResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/sets/' + req.termData.termSetId + '/terms', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const dataTerms = await termResponse.json();
const foundTerm = dataTerms.value.find(term =>
term.labels.some(label => label.name.toLowerCase() === tag.toLowerCase())
);
if (foundTerm) {
console.log("Found Term " + tag + "!");
termId = foundTerm.id;
} else {
console.log("Creating Term " + tag + "...");
const createTermResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/sets/' + req.termData.termSetId + '/children', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
},
body: JSON.stringify({
"labels": [
{
"languageTag": "en-US",
"name": tag,
"isDefault": true
}
]
}),
redirect: 'follow'
});
const dataCreateTerms = await createTermResponse.json();
termId = dataCreateTerms.id;
}
//---------------------GET GEOTAG COLUMN---------------------------
const getColumnResponse = await fetch("https://graph.microsoft.com/v1.0/sites/" + siteId + "/lists/Documents/columns?$select=hidden,id,name,displayName&$filter=displayName eq 'GeoTag_0'", {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.1',
'Authorization': token.accessToken
}
});
const dataColumn = await getColumnResponse.json();
if (dataColumn.value.length === 0) {
res.send({ label: "columnNotFound", termGuid: "columnNotFound" });
} else {
nameGeoTAGColumn = dataColumn.value[0].name
//console.log(nameGeoTAGColumn)
//---------------------ADD TAG---------------------------
const oldTags = fileTags.map(tag => tag.label + "|" + tag.termGuid + ";");
const createTagResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/lists/Documents/items/' + fileId + '/fields', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
},
body: JSON.stringify({
[nameGeoTAGColumn]: oldTags + tag + "|" + termId
}),
redirect: 'follow'
});
const dataCreateTag = await createTagResponse.json();
//console.log(dataCreateTag)
res.send({ label: tag, termGuid: termId });
}
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
// ----- DELETE TAG ----- //
app.patch('/delTag', termMiddleware, async (req, res) => {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
const tag = req.body.tag;
const fileTags = req.body.fileTags;
const fileId = req.body.fileId;
console.log("File id: ", fileId);
//------------------------TERM---------------------------
// Fetch the term ID for the specified tag
const termResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/sets/' + req.termData.termSetId + '/terms', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken,
},
});
const dataTerms = await termResponse.json();
const foundTerm = dataTerms.value.find(term =>
term.labels.some(label => label.name.toLowerCase() === tag.toLowerCase())
);
if (!foundTerm) {
return res.status(404).send({ message: "Term not found!" });
}
const termId = foundTerm.id;
//---------------------GET GEOTAG COLUMN---------------------------
const getColumnResponse = await fetch("https://graph.microsoft.com/v1.0/sites/" + siteId + "/lists/Documents/columns?$select=hidden,id,name,displayName&$filter=displayName eq 'GeoTag_0'", {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.1',
'Authorization': token.accessToken
}
});
const dataColumn = await getColumnResponse.json();
if (dataColumn.value.length === 0) {
res.send({ label: "columnNotFound", termGuid: "columnNotFound" });
} else {
nameGeoTAGColumn = dataColumn.value[0].name
//console.log(nameGeoTAGColumn)
//---------------------DELETE TAG---------------------------
// Construct the new list of tags (excluding the one to be deleted)
const updatedTags = fileTags
.filter(existingTag => existingTag.label.toLowerCase() !== tag.toLowerCase())
.map(tag => tag.label + "|" + tag.termGuid + ";"); // To format the output: "TAG" | "termGuid";
console.log("Updated tags: " + updatedTags);
// Update the file's tags
const updateTagsResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/lists/Documents/items/' + fileId + '/fields', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken,
},
body: JSON.stringify({
[nameGeoTAGColumn]: updatedTags.join(''),
}),
redirect: 'follow',
});
const dataUpdateTags = await updateTagsResponse.json();
console.log("Data update tags: ", JSON.stringify(dataUpdateTags, null, 2));
res.send({ label: tag, termGuid: termId });
}
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
app.get('/seeTaggedFiles', termMiddleware, async (req, res) => {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
const nameTag = req.headers.nametag.toLowerCase();
const termResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/termStore/sets/' + req.termData.termSetId + '/terms', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const dataTerms = await termResponse.json();
//console.log(dataTerms)
const foundTerm = dataTerms.value.find(term =>
term.labels.some(label => label.name.toLowerCase() === nameTag.toLowerCase())
);
if (foundTerm) {
console.log("Found Term " + nameTag + "!");
termId = foundTerm.id;
console.log(termId)
const taggedFilesResponse = await fetch(`https://graph.microsoft.com/v1.0/sites/${siteId}/drive/root/search(q='${termId}')`, {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const dataTaggedFiles = await taggedFilesResponse.json();
console.log(dataTaggedFiles);
res.send(dataTaggedFiles);
} else {
console.log(nameTag + " not found!");
res.status(404).send({ message: "Term not found!" });
}
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
app.get('/seeDataTaggedFile', async (req, res) => {
try {
const token = await getValidToken();
const siteId = req.headers.siteid;
let fileId = req.headers.fileid;
const filesResponse = await fetch('https://graph.microsoft.com/v1.0/sites/' + siteId + '/drive/items/' + fileId + '?&select=id,eTag,name&expand=listitem(expand=fields(select=GeoTag))', {
headers: {
'Content-Type': 'application/json',
'Prefer': 'apiversion=2.0',
'Authorization': token.accessToken
}
});
const data = await filesResponse.json();
console.log(data)
res.send(data);
} catch (err) {
console.log(err);
res.status(500).send(err);
}
});
server.listen(port, () => {
console.log(`Server running on https://localhost:${port}`);
});