-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
678 lines (611 loc) · 26 KB
/
index.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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
const { app, BrowserWindow, safeStorage, ipcRenderer, Menu, dialog} = require('electron')
const path = require('path')
const util = require("util");
let { ipcMain } = require("electron")
const {XMLParser} = require("fast-xml-parser");
const https = require('https');
const fetch = require('node-fetch');
const parser = new XMLParser({ignoreAttributes : false});
const moment = require('moment-timezone')
const Store = require('electron-store');
const _ = require("lodash")
const getArray = require("./utils");
const { autoUpdater } = require('electron-updater');
let tokensNeeded = ['LtpaToken2', 'JSESSIONID'];
let cookiesMap = new Map();
const args = process.argv;
let agent = new https.Agent({
rejectUnauthorized: false
});
//TODO refactor
//TODO open details in new page?
//TODO after modify filters are deleted
//TODO check state before updating if it has not been updated since
//TODO use constants instead of text
//TODO hide row (or just select differnt color)
//TODO fix timezone incorrect
//TODO remove filter when column is hidden
//TODO search RTC number directly (use right top search maybe)
//https://redacted_url:9443/jazz/rpt/repository/generic?fields=generic/com.ibm.team.process.TeamArea[projectArea/name=%22redacted%20(RTC)%22]/(contributors/name)
//https://jazz.net/sandbox01-ccm/oslc/users?oslc.where=foaf:name="Tibor*"}&oslc.prefix=foaf=<http://xmlns.com/foaf/0.1/>&oslc.select=foaf:name
//OSLC-Core-Version: 2.0 needs in header
//TODO nicetohave: zoom
//TODO nicetohave: custom icon
//TODO nicetohave: connection error show error
if (process.env.PORTABLE_EXECUTABLE_DIR)
app.setPath ('userData', path.join(process.env.PORTABLE_EXECUTABLE_DIR, "data"));
require('electron-debug')({ showDevTools: false });
const store = new Store({
name: 'credentials',
watch: true,
encryptionKey: 'very_secure_obfuscation_key',
});
/**
*
* @type {
* {
* baseUrl: string,
* useSavedPassword: boolean,
* projectAreas: *[],
* history: {lastProjectArea: string, lastFilterBy: string, lastFilterType: string, lastStartDate: string, lastEndDate: string},
* hasSavedPassword: boolean,
* customAttributes: string,
* datatablesState: object
* }
* }
*/
let defaultConfig = {
history: {
/** string */ lastProjectArea: '',
/** string */ lastStartDate: '',
/** string */ lastEndDate: '',
/** string */ lastFilterBy: '',
/** string */ lastFilterType: ''
},
/** string[] */ projectAreas: [],
/** string */ customAttributes: '',
/** string */ baseUrl: '',
/** boolean */ hasSavedPassword: false,
/** boolean */ useSavedPassword: false,
/** object */ datatablesState: {}
}
if(!store.get("config")) {
store.set("config", defaultConfig);
}
let _win;
function createConfigWindow() {
const configWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
devTools: true
}
});
configWindow.loadFile(`pages/config/config.html`);
configWindow.setTitle("Configuration")
}
function createWindow () {
const menu = Menu.getApplicationMenu(); // get default menu
const menuTest = Menu.buildFromTemplate(
[{
label: "Caches",
submenu: [
{
label: "Delete all data",
click: () => {
let text = "You are about to delete stored passwords, base url and project areas.\nAre you sure?";
let options = {
buttons: ["Yes","No", "Cancel"],
message: text
}
dialog.showMessageBox(options).then((response, checkboxChecked) => {
if(response.response === 0) {
cookiesMap.clear();
store.set("config", defaultConfig);
store.delete("user");
store.delete("pass");
}
})
}
}, {
label: "Logout",
click: () => {
let text = "You are about to logout.\nAre you sure?";
let options = {
buttons: ["Yes","No", "Cancel"],
message: text
}
dialog.showMessageBox(options).then((response, checkboxChecked) => {
if (response.response === 0) {
store.delete("user");
store.delete("pass");
store.set("config.hasSavedPassword", false);
store.set("config.useSavedPassword", false);
_win.loadFile("pages/login/login.html");
_win.setTitle("Login")
}
})
}
}
]
}])
menu.append(menuTest.items[0]);
menu.append(Menu.buildFromTemplate([{
label: "Open configs",
click: () => {
createConfigWindow();
}
}]).items[0]);
menu.append(Menu.buildFromTemplate([{
label: "Scroll to top",
click: () => {
_win.webContents.executeJavaScript('document.body.scrollTop = 0; document.documentElement.scrollTop = 0;');
}
}]).items[0])
Menu.setApplicationMenu(menu); // set the modified menu
const win = new BrowserWindow({
width: 800,
height: 600,
minWidth: 1024,
minHeight: 720,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
devTools: true,
}
})
autoUpdater.on('error', e => {
// This gets called when an error occurs but it doesn't count as
// the rejection getting handled
console.error('Failed to check for updates');
console.error(e);
});
autoUpdater.checkForUpdates().catch(e => {
// This does not get called when a download error occurs
console.error('Failed to check for updates');
console.error(e);
});
win.once('ready-to-show', () => {
autoUpdater.checkForUpdatesAndNotify();
});
win.webContents.on('will-navigate', (event, url) => {
event.preventDefault();
require("electron").shell.openExternal(url);
});
let cookies = win.webContents.session.cookies;
cookies.on('changed', function(event, cookie, cause, removed) {
if (tokensNeeded.includes(cookie.name) && cookie.session && !removed) {
let [k,v] = cookie.split("=")
cookiesMap.set(k, v);
}
if(cookiesMap.size < tokensNeeded.length) {
//win.setSize(200, 400);
win.loadFile("pages/main/main.html");
win.setTitle("ih8rtcgui tool")
}
});
win.loadFile("pages/login/login.html");
win.setTitle("Login")
_win = win;
}
app.whenReady().then(() => {
createWindow()
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
app.exit(0);
}
})
let allDataList = [];
ipcMain.handle("getDefaultValues", (event) => {
return store.get("config");
})
ipcMain.handle("loadWorkItems", async (event, projectArea, startDateString, endDateString, filterBy, filterType, additionalData) => {
store.set("config.history.lastProjectArea", projectArea);
store.set("config.history.lastStartDate", startDateString);
store.set("config.history.lastEndDate", endDateString);
store.set("config.history.lastFilterBy", filterBy);
store.set("config.history.lastFilterType", filterType);
let andFilters = [`projectArea/name='${projectArea}'`];
let orFilters = [];
//let tagFilters = tag.split(",").map(t => `tags=|${t}|`).join(" or ");
let andFilterList = [];
let orFilterList = [];
if(additionalData) {
orFilterList.push({
data: additionalData.filterData,
operator: additionalData.filterType,
filterBy: additionalData.filterBy
});
orFilterList.forEach(data => {
data.data.split(",").forEach(d => {
orFilters.push(`${data.filterBy}${data.operator}${d}`);
})
})
} else {
andFilterList.push({
data: moment(startDateString).utc(true).format("YYYY-MM-DDTHH:mm:ss.SSSZZ").replace("+", "-"),
operator: ">",
filterBy: filterBy
})
andFilterList.push({
data: moment(endDateString).utc(true).format("YYYY-MM-DDTHH:mm:ss.SSSZZ").replace("+", "-"),
operator: "<",
filterBy: filterBy
})
andFilterList.forEach(data => {
if(filterType !== data.operator && filterType !== "!!") return;
andFilters.push(`${data.filterBy}${data.operator}${data.data}`);
})
}
//filters.push(tagFilters);
let size = 5;
let pos = 0;
let filterString = andFilters.join(" and ");
if(orFilters && orFilters.length > 0) filterString += " and " + orFilters.join(" or ");
let workItemsUrl = `${store.get("config.baseUrl")}/rpt/repository/workitem?fields=workitem/workItem[${filterString}]/(id|summary|state/name|modified|owner/name|tags|subscriptions/name|state/workflow/id|state/name|itemHistory/modifiedBy/name)`
allDataList = [];
let text = await recursivelyCheckAllRemainingData(workItemsUrl, ['workitem', 'workItem']);
allDataList = text;
return allDataList;
});
function addCookiesToCookiesMap(/** String[] */listOfCookies, specificCookiesMap = new Map()) {
listOfCookies?.forEach(cookies => {
let [,k,v] = cookies.match(/(.*?)=(.*)/)
if(!specificCookiesMap) {
if(v) cookiesMap.set(k, v.split(";")[0]);
} else {
if(v) specificCookiesMap.set(k, v.split(";")[0]);
}
})
}
function getCookiesString(specificCookiesMap) {
let allowedCookies = ["JSESSIONID", "LtpaToken2", "WASReqURL", "Node-web"]
let cmap = specificCookiesMap || cookiesMap;
return [...cmap.entries()].filter((entry, index) => entry[1]).map((entry,index) => `${entry[0]}=${entry[1]}`).join(";");
}
/**
* @returns string[]
*/
async function login(username, password) {
let loginCookiesMap = new Map()
var myHeaders = new Headers();
let url = new URL(store.get("config.baseUrl"));
myHeaders.append("Referer", `${store.get("config.baseUrl")}/authenticated/identity`);
myHeaders.append("Host", `${url.host}`);
myHeaders.append("Content-Type", "text/xml");
myHeaders.append("Origin", `${url.protocol}//${url.host}`);
var requestOptions = {
agent: new https.Agent({
rejectUnauthorized: false
}),
method: 'GET',
headers: myHeaders,
body: undefined,
redirect: 'manual'
};
let rootResponse = await fetch(store.get("config.baseUrl"), requestOptions);
addCookiesToCookiesMap(rootResponse?.headers?.raw()?.["set-cookie"], loginCookiesMap)
myHeaders.set("Cookie", getCookiesString(loginCookiesMap));
requestOptions.headers = myHeaders;
let identityResponse = await fetch(store.get("config.baseUrl") + "/secure/authenticated/identity", requestOptions);
addCookiesToCookiesMap(identityResponse?.headers?.raw()?.["set-cookie"]?.filter(c => !c.startsWith("JSESSIONID")), loginCookiesMap)
requestOptions.body = new URLSearchParams({
j_username: username,
j_password: password
});
requestOptions.method = "POST"
requestOptions.redirect = 'manual';
myHeaders.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
myHeaders.set("Cookie", getCookiesString(loginCookiesMap));
requestOptions.headers = myHeaders;
let firstSecurityCheckResponse = await fetch(store.get("config.baseUrl") + "/auth/j_security_check", requestOptions);
addCookiesToCookiesMap(firstSecurityCheckResponse?.headers?.raw()?.["set-cookie"], loginCookiesMap);
if(firstSecurityCheckResponse.headers?.raw()?.["x-com-ibm-team-repository-web-auth-msg"] || !loginCookiesMap.get("JSESSIONID")) {
console.log('Unsuccessful auth');
return new Map()
}
return loginCookiesMap;
}
ipcMain.handle("getUserNameAndDummyPass", (event) => {
let user = store.get("user");
let pass = store.get("pass");
return {user: user, pass: "*".repeat(8), hasSavedPass: store.get("config.hasSavedPassword"), useSavedPass: store.get("config.useSavedPassword")};
})
let DATATABLES_STATE_KEY = "datatablesState"
ipcMain.handle("saveDataTables", (event, data) => {
return store.set(DATATABLES_STATE_KEY, data);
})
ipcMain.handle("loadDataTables", (event) => {
return store.get(DATATABLES_STATE_KEY);
})
async function loginWithSavedCredentials() {
return await loginProcess(store.get("user"), safeStorage.decryptString(Buffer.from(store.get("pass"))), store.get("saveCredentials"));
}
async function loginProcess(username, password, saveCredentials, useSavedCredentials) {
if(useSavedCredentials) {
if(store.get("user") && store.get("pass")) {
username = store.get("user");
password = safeStorage.decryptString(Buffer.from(store.get("pass")));
} else {
return {success: false, message: 'You have no stored password, please enter password.'};
}
store.set("config.useSavedPassword", useSavedCredentials)
}
let cookiesFromLogin = await login(username, password);
if(cookiesFromLogin.size >= 2) {
cookiesMap = cookiesFromLogin;
if(saveCredentials) {
store.set("pass", safeStorage.encryptString(password));
store.set("user", username);
store.set("config.hasSavedPassword", true)
//save credentials
}
return {success: true, message: ''};
//successful login
} else {
return {success: false, message: 'Wrong username/password combination'};
}
}
ipcMain.handle("getContributorName", async (event, itemId) => {
let jtsUrl = `${store.get("config.baseUrl").replace("ccm", "jts")}/rpt/repository/foundation?fields=projectArea/contributor[itemId=${itemId}]/name`;
let response = await getData(jtsUrl);
return response?.['foundation']?.['contributor']?.['name'];
})
ipcMain.handle("login", async (event, username, password, saveCredentials, useSavedCredentials) => {
let loginResponse = await loginProcess(username, password, saveCredentials, useSavedCredentials);
if(loginResponse.success) {
_win.loadFile("pages/main/main.html");
_win.setTitle("ih8rtcgui tool")
}
return loginResponse;
});
ipcMain.handle("loadWorkItemData", async (event, rtcNo) => {
let url = `${store.get("config.baseUrl")}/rpt/repository/workitem?fields=workitem/workItem[id=${rtcNo}]/(*|creator/name|creator/itemType|comments/creator/name|comments/formattedContent|comments/creationDate|itemHistory/modifiedBy/name|itemHistory/*|itemHistory/owner/name|itemHistory/state/name|itemHistory/subscriptions/name|auditableLinks/targetRef/referencedItem/href|auditableLinks/targetRef/comment|auditableLinks/modified|allExtensions/key|allExtensions/displayValue|customAttributes/identifier|customAttributes/itemType|customAttributes/attributeType|allExtensions/itemValue/itemId|state/name|state/workflow/id)`;
let dataPreprocessed = await getData(url);
//let stateName = dataPreprocessed?.['workitem']?.['workItem']?.['state']?.['name'];
//let workflowId = dataPreprocessed?.['workitem']?.['workItem']?.['state']?.['workflow']?.['id'];
//let possibleActions = await getPossibleStates(workflowId, stateName);
//dataPreprocessed['actions'] = possibleActions;
if(dataPreprocessed?.['workitem']?.['workItem']) {
let wi = dataPreprocessed['workitem']['workItem'];
wi.id = wi.id + ` <a href="${store.get("config.baseUrl")}/web/projects/${store.get("config.history.lastProjectArea")}#action=com.ibm.team.workitem.viewWorkItem&id=${wi.id}"><i class="fa fa-external-link" aria-hidden="true"></i></a>`;
}
return dataPreprocessed;
})
ipcMain.handle("saveConfig", (event, baseUrl, projectAreas, customAttributes) => {
store.set("config.baseUrl", baseUrl);
store.set("config.projectAreas", projectAreas.split("\n"))
let customAttributesRows = customAttributes.split("\n");
let customAttributesMap = new Map()
customAttributesRows.forEach(car => {
let keyValues = car.split("=");
customAttributesMap.set(keyValues[0], keyValues[1]);
});
store.set("config.customAttributes", JSON.stringify(Object.fromEntries(customAttributesMap)))
_win.webContents.send("changedConfig", store.get("config"));
return "Saved config successfully";
})
ipcMain.handle("getAllStates", async (event) => {
return await getAllStates();
})
ipcMain.handle("getUsersByCondition", async (event, searchText) => {
return await getUsersByCondition(searchText);
})
ipcMain.handle("getTeamAreaUsers", async (event) => {
return await getTeamAreaUsers();
})
ipcMain.handle("modifyState", async (event, id, stateId, userId, comment) => {
await modifyState(id, stateId, userId, comment);
return true;
})
let STEPS = 1000;
async function recursivelyCheckAllRemainingData(url, selectors, size = STEPS, pos = 0, customHeader = {}) {
let list = [];
let text = await getData(url+`&size=${size}&pos=${pos}`, false, customHeader);
if(_.get(text, selectors.join('.')) != null) {
if(Array.isArray(_.get(text, selectors.join('.')))) {
list.push(..._.get(text, selectors.join('.')));
} else {
list.push(_.get(text, selectors.join('.')));
}
list.push(...await recursivelyCheckAllRemainingData(url, selectors, size, pos + size));
}
return list;
}
async function sendData(url, method = 'POST', body = {}) {
let jsessionid = cookiesMap.get("JSESSIONID");
let workitems = await fetch(url, {
method: method,
agent: agent,
headers: {
'Cookie': getCookiesString(),
'X-Jazz-CSRF-Prevent': jsessionid,
'Accept': 'application/x-oslc-cm-change-request+json',
'Content-Type': 'application/json'
//'Cookie': cookiesMap.map(cookie => `${cookie.name}=${cookie.value}`).join(";")
},
body: JSON.stringify(body)
});
console.log(workitems.status);
console.log(await workitems.text())
}
async function getData(url, overrideStatus = false, customHeader = {}) {
let jsessionid = cookiesMap.get("JSESSIONID");
let inputHeaders = {
'Cookie': getCookiesString(),
'X-Jazz-CSRF-Prevent': jsessionid,
//'Cookie': cookiesMap.map(cookie => `${cookie.name}=${cookie.value}`).join(";")
}
for (const ch in customHeader) {
inputHeaders[ch] = customHeader[ch];
}
let workitems = await fetch(url, {
agent: agent,
headers: inputHeaders
}).catch(err => {
console.log(err);
return null;
});
if(workitems.status === 500) return null;
let headers = workitems.headers;
let authRequiredHeader = headers.get('X-com-ibm-team-repository-web-auth-msg');
if((authRequiredHeader !== null || workitems.status !== 200) && !overrideStatus) {
if(store.get("config.hasSavedPassword") === true) {
if(!await loginWithSavedCredentials()) {
//can't login
_win.loadFile("pages/login/login.html");
_win.setTitle("Login")
} else {
return getData(url);
}
} else {
_win.loadFile("pages/login/login.html");
_win.setTitle("Login")
}
}
return await parser.parse(await workitems.text());
}
async function getContentId() {
let teamarea = store.get("config.history.lastProjectArea") || store.get("config.projectAreas")?.[0];
let contentIdUrl = `${store.get("config.baseUrl")}/rpt/repository/generic?fields=generic/com.ibm.team.process.ProjectArea[name='${teamarea}']/processData[key=%27com.ibm.team.internal.process.compiled.xml%27]/value/contentId`
let content = await getData(contentIdUrl);
return content?.['generic']?.['com.ibm.team.process.ProjectArea']?.['processData']?.['value']?.['contentId'];
}
async function getPossibleStates(type, currentState) {
let contentId = await getContentId();
let resourceUrl = `${store.get("config.baseUrl")}/resource/content/${contentId}`;
let resources = await getData(resourceUrl, true);
let configurationData = _.get(resources, 'process-specification.project-configuration.data.configuration-data');
let workflowDefinitions = _.find(configurationData, (value) => {
return value?.['@_id'] === 'com.ibm.team.workitem.configuration.workflow'
})?.['workflowDefinition'];
let currentWorkflowDefinition = _.find(workflowDefinitions, (value) => {
return value?.['@_id'] === type
})
let possibleStates = _.find(currentWorkflowDefinition?.['workflow']?.['state'], (value) => {
return value?.['@_name'] === currentState
});
return getArray(possibleStates, ['action']).map(ps => {
return {
humanFriendlyName: currentWorkflowDefinition['workflow']?.['action'].find(a => a['@_id'] === ps['@_id'])?.['@_name'],
action: ps['@_id']
}
});
}
async function getAllStates() {
let contentId = await getContentId();
let resourceUrl = `${store.get("config.baseUrl")}/resource/content/${contentId}`;
let resources = await getData(resourceUrl, true);
let configurationData = _.get(resources, 'process-specification.project-configuration.data.configuration-data');
let workflowDefinitions = _.find(configurationData, (value) => {
return value?.['@_id'] === 'com.ibm.team.workitem.configuration.workflow'
})?.['workflowDefinition'];
return workflowDefinitions?.map(wd => {
return {
workflowName: wd?.['@_id'],
states: wd?.['workflow']?.['state'].filter(e => e['action']).map(ps => {
return {
stateName: ps?.['@_name'],
possibleStates: getArray(ps, ['action']).map(ps => {
return {
humanFriendlyName: wd['workflow']?.['action'].find(a => a['@_id'] === ps['@_id'])?.['@_name'],
action: ps['@_id']
}
})
}
})
}
})
}
async function getTeamAreaUsers() {
let url = `${store.get("config.baseUrl")}/rpt/repository/generic?fields=generic/com.ibm.team.process.TeamArea[projectArea/name="${store.get("config.history.lastProjectArea")}"]/contributors[archived=false]/(name|href)`;
let teamareas = await getData(url, false);
return _.flatMap(getArray(teamareas, ['generic', 'com.ibm.team.process.TeamArea']).filter(ta => ta), 'contributors').map(contributor => {
return {
text: contributor['name'],
id: contributor['@_href']
}
})
}
async function getUsersByCondition(condition) {
let conditionWithWildcard = condition ? `*${condition}*` : '*';
let conditionName = new ConditionBuilder().setKey("oslc.where").setValue("foaf:name=\"" + conditionWithWildcard + "\" and foaf:archived=false")
let conditionPrefixFoaf = new ConditionBuilder().setWrapQuotes(false).setKey("oslc.prefix").setValue("foaf=<http://xmlns.com/foaf/0.1/>")
let conditionSelect = new ConditionBuilder().setKey("oslc.select").setValue("foaf:name")
let conditionWhere = [conditionName.toString(), conditionPrefixFoaf.toString(), conditionSelect.toString()].join("&")
let resourceUrl = `${store.get("config.baseUrl")}/oslc/users?${conditionWhere}`;
let resources = await getData(resourceUrl, false, {"OSLC-Core-Version": "2.0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"});
let users = getArray(resources, ['rdf:RDF', 'rdf:Description', 'rdfs:member'])?.map(tm => {
return {
text: tm['foaf:Person']?.['foaf:name']?.['#text'],
id: tm['foaf:Person']?.['@_rdf:about']
}
});
let teamAreaUsers = await getTeamAreaUsers();
if(condition) {
teamAreaUsers = teamAreaUsers.filter(tau => tau.text.toLowerCase().indexOf(condition.toLowerCase()) > -1);
}
return {
results: [
{
text: "Team Area Users",
children: _.orderBy(_.uniqBy(teamAreaUsers, 'text'), 'text')
},
{
text: "Search",
children: _.orderBy(users, 'text')
}
]
};
}
class ConditionBuilder {
key;
value;
wrapQuotes = false;
setKey(key) {
this.key = key;
return this;
}
setValue(value) {
this.value = value;
return this;
}
setWrapQuotes(wrapQuotes) {
this.wrapQuotes = wrapQuotes;
return this;
}
toString() {
let quote = this.wrapQuotes ? '"' : '';
return this.key + "=" + encodeURIComponent(quote + this.value + quote);
}
}
async function modifyState(id, actionId, userId, comment) {
let modifyStateUrl = `${store.get("config.baseUrl")}/oslc/workitems/${id}`;
let modifyStateOwnerUrl = modifyStateUrl;
let modifyStateCommentUrl = modifyStateUrl;
if(actionId) modifyStateOwnerUrl += `?_action=${actionId}`;
let body = {};
if(userId) {
body = {
"rtc_cm:ownedBy": userId
}
}
if(userId || actionId) {
await sendData(modifyStateOwnerUrl, 'PUT', body);
}
if(comment && comment.replace(/\s/g, '').length) {
let commentBody = {
"dc:description": comment.replace("\n", "<br>")
}
await sendData(`${modifyStateCommentUrl}/rtc_cm:comments`, 'POST', commentBody);
}
}