-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
496 lines (438 loc) · 15 KB
/
index.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
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
import request, { Response } from 'request'
import { getLogger } from './logger'
import {
getData,
getArray,
putData,
postData,
deleteData,
createRobotOption,
createEnterpriseOption,
createCommunityOption,
} from './utils'
import {
ICrudService,
IRobotCrudService,
IUserCrudService,
IRoleCrudService,
ISettingCrudService,
IAuditLogCrudService,
ILogCrudService,
IMachineCrudService,
IReleaseCrudService,
IProcessCrudService,
IJobCrudService,
IQueueDefinitionCrudService,
IQueueCrudService,
IAssetCrudService,
IUtilService,
ITenantCrudService,
IHostLicenseCrudService,
IEnvironmentCrudService,
IQueueItemCrudService,
IFolderCrudService,
ILicenseCrudService,
} from './Interfaces'
import { json2excel, json2excelBlob } from 'excel-csv-read-write'
const logger = getLogger('main')
export interface LicenseRuntimeDto {
Key: string
MachineId: number
MachineName: string
Runtimes: number
RobotsCount: number
ExecutingCount: number
IsOnline: boolean
IsLicensed: boolean
Enabled: boolean
}
export interface LicenseNamedUserDto {
Key: string
UserName: string
LastLoginDate: Date
MachinesCount: number
IsLicensed: boolean
IsExternalLicensed: boolean
ActiveRobotId: number
MachineNames: string[]
ActiveMachineNames: string[]
}
export interface LicenseDto {
HostLicenseId: number
Id: number
ExpireDate: number
GracePeriodEndDate: number
GracePeriod: number
AttendedConcurrent: boolean
DevelopmentConcurrent: boolean
StudioXConcurrent: boolean
LicensedFeatures: string[]
IsRegistered: boolean
IsExpired: boolean
CreationTime: Date
Code: string
Allowed: LicenseFields
Used: LicenseFields
}
export interface LicenseFields {
Unattended: number
Attended: number
NonProduction: number
Development: number
StudioX: number
}
/**
* Interfaceのデフォルト実装(全部でOverrideするのはメンドイので)
*/
export class BaseCrudService implements ICrudService {
constructor(public parent: IOrchestratorApi) {}
findAll(obj?: any, asArray: boolean = true): Promise<Array<any>> {
throw Error('Not implemented yet.')
}
find(obj?: any): Promise<any> {
throw Error('Not implemented yet.')
}
create(obj: any): Promise<any> {
throw Error('Not implemented yet.')
}
update(obj: any): Promise<any> {
throw Error('Not implemented yet.')
}
delete(obj: any): Promise<any> {
throw Error('Not implemented yet.')
}
save2Excel(
instances: any[],
outputFullPath: string,
templateFullPath: string = '',
sheetName: string = 'Sheet1',
applyStyles?: (instances: any[], workbook: any, sheetName: string) => void,
): Promise<string> {
const converters = {
// RobotVersions: (value: any) => value[0].Count,
}
return json2excel(instances, outputFullPath, templateFullPath, sheetName, converters, applyStyles)
}
save2ExcelBlob(
instances: any[],
sheetName: string = 'Sheet1',
applyStyles?: (instances: any[], workbook: any, sheetName: string) => void,
): Promise<Blob> {
const converters = {
// RobotVersions: (value: any) => value[0].Count,
}
return json2excelBlob(instances, sheetName, converters, applyStyles)
}
}
/**
* Orchestrator API Wrapper
* cf. https://docs.uipath.com/orchestrator/v2019/reference
*/
export interface IOrchestratorApi {
authenticate: () => Promise<any>
license: ILicenseCrudService
robot: IRobotCrudService
user: IUserCrudService
role: IRoleCrudService
machine: IMachineCrudService
release: IReleaseCrudService
process: IProcessCrudService
library: IProcessCrudService
job: IJobCrudService
schedule: ICrudService
folder: IFolderCrudService
queueDefinition: IQueueDefinitionCrudService
queueItem: IQueueItemCrudService
queueOperation: IQueueCrudService
log: ILogCrudService
auditLog: IAuditLogCrudService
setting: ISettingCrudService
asset: IAssetCrudService
util: IUtilService
tenant: ITenantCrudService
hostLicense: IHostLicenseCrudService
environment: IEnvironmentCrudService
// 以下、汎用的なメソッド
getArray: (apiPath: string, queries?: any) => Promise<Array<any>>
getData: (apiPath: string) => Promise<any>
postData: (apiPath: string, obj: any) => Promise<any>
putData: (apiPath: string, obj: any) => Promise<void>
deleteData: (apiPath: string) => Promise<any>
isEnterprise: boolean
isCommunity: boolean
isRobot: boolean
isToken: boolean
config: any
organizationUnitId: number
accessToken: string
}
/**
* OrchestratorのAPIのWrapperクラス
* (Mainのクラスです)
*/
export class OrchestratorApi implements IOrchestratorApi {
isEnterprise: boolean = false
isCommunity: boolean = false
isRobot: boolean = false
isToken: boolean = false
accessToken: string = ''
get organizationUnitId() {
return this.config.organizationUnitIdFromAPI
}
set organizationUnitId(organizationUnitId: number) {
logger.info(`Folder Idを[${organizationUnitId}]に切り替えます`)
this.config = Object.assign({}, this.config, { organizationUnitIdFromAPI: organizationUnitId })
}
constructor(public config: any) {
const { isEnterprise, isCommunity, isRobot, isToken } = getConfigState(config)
this.isEnterprise = isEnterprise
this.isCommunity = isCommunity
this.isRobot = isRobot
this.isToken = isToken
// 全部falseだったら、エラーなので例外で落とす。
if (!(this.isEnterprise || this.isCommunity || this.isRobot)) {
throw new Error('Invalid Configuration.')
}
}
/**
* Orchestrator API の認証システムに対して、認証を実施しアクセストークンを取得する。
*/
authenticate(): Promise<any> {
logger.debug(this.config.serverinfo.servername)
// Enterprise版かCommunity版かで認証処理が異なるので、設定ファイルによって振り分ける。
let promise: Promise<any>
if (this.config.token && this.config.token.access_token !== '') {
logger.info('Tokenモードとして処理開始')
this.accessToken = this.config.token.access_token
// とりあえず、マシン一覧を取ることで、エラーが出たらトークンがつかえないと見なす。
promise = new Promise((resolve, reject) => {
getArray(this.config, this.accessToken, '/odata/Machines')
.then(() => resolve())
.catch((error) => reject(error))
})
} else if (this.isRobot) {
logger.info('Robotモードとして処理開始')
logger.debug(this.config.robotInfo.machineKey)
logger.debug(this.config.robotInfo.machineName)
logger.debug(this.config.robotInfo.userName)
const auth_options = createRobotOption(this.config)
promise = new Promise((resolve, reject) => {
request.post(auth_options, (err: any, _response: Response, body: any): void => {
if (err) {
reject(err)
return
}
const obj = body
if (!obj.robotKey) {
reject(obj)
return
}
const access_token = obj.robotKey
this.accessToken = access_token
logger.debug(access_token)
resolve(obj)
})
})
} else if (this.isEnterprise) {
logger.info('Enterprise版として処理開始')
logger.debug(this.config.userinfo.tenancyName)
logger.debug(this.config.userinfo.usernameOrEmailAddress)
logger.debug(this.config.userinfo.password)
const auth_options = createEnterpriseOption(this.config)
promise = new Promise((resolve, reject) => {
request.post(auth_options, (err: any, _response: Response, body: any): void => {
if (err) {
reject(err)
return
}
// const obj = JSON.parse(body)
const obj = body
if (!obj.success) {
reject(obj)
return
}
const access_token = obj.result
this.accessToken = access_token
logger.debug(access_token)
resolve(obj)
})
})
} else {
logger.info('Community版として処理開始')
const auth_options = createCommunityOption(this.config)
promise = new Promise((resolve, reject) => {
request.post(auth_options, (err: any, _response: Response, body: any): void => {
if (err) {
reject(err)
return
}
// const obj = JSON.parse(body)
const obj = body
if (!obj.access_token) {
reject(obj)
return
}
logger.debug(obj)
const access_token = obj.access_token
this.accessToken = access_token
logger.debug(access_token)
resolve(obj)
})
})
}
return promise
}
license: ILicenseCrudService = new LicenseCrudService(this)
robot: IRobotCrudService = new RobotCrudService(this)
user: IUserCrudService = new UserCrudService(this)
role: IRoleCrudService = new RoleCrudService(this)
machine: IMachineCrudService = new MachineCrudService(this)
release: IReleaseCrudService = new ReleaseCrudService(this)
process: IProcessCrudService = new ProcessCrudService(this)
library: IProcessCrudService = new LibraryCrudService(this)
job: IJobCrudService = new JobCrudService(this)
schedule: ICrudService = new (class extends BaseCrudService {
constructor(parent: IOrchestratorApi) {
super(parent)
}
findAll(queries?: any, asArray: boolean = true): Promise<Array<any>> {
return getArray(this.parent.config, this.parent.accessToken, '/odata/ProcessSchedules', queries, asArray)
}
})(this)
folder: IFolderCrudService = new FolderCrudService(this)
tenant: ITenantCrudService = new TenantCrudService(this)
hostLicense: IHostLicenseCrudService = new HostLicenseCrudService(this)
environment: IEnvironmentCrudService = new EnvironmentCrudService(this)
queueDefinition: IQueueDefinitionCrudService = new QueueDefinitionCrudService(this)
queueItem: IQueueItemCrudService = new QueueItemCrudService(this)
queueOperation: IQueueCrudService = new QueueCrudService(this)
log: ILogCrudService = new LogCrudService(this)
auditLog: IAuditLogCrudService = new AuditLogCrudService(this)
setting: ISettingCrudService = new SettingCrudService(this)
asset: IAssetCrudService = new AssetCrudService(this)
util: IUtilService = new UtilService(this)
// タスク(Enterpriseには、ない)
// フォルダー(OU)
// Webhook
getArray = (apiPath: string, queries?: any, isOdata: boolean = true): Promise<Array<any>> => {
return getArray(this.config, this.accessToken, apiPath, queries, isOdata)
}
getData = (apiPath: string): Promise<any> => {
return getData(this.config, this.accessToken, apiPath)
}
postData = (apiPath: string, obj: any): Promise<any> => {
return postData(this.config, this.accessToken, apiPath, obj)
}
putData = (apiPath: string, obj: any): Promise<any> => {
return putData(this.config, this.accessToken, apiPath, obj)
}
deleteData = (apiPath: string): Promise<any> => {
return deleteData(this.config, this.accessToken, apiPath)
}
}
/**
* 与えられたConfigの状態
*/
export const getConfigState = (
config: any,
): {
isEnterprise: boolean
isCommunity: boolean
isRobot: boolean
isToken: boolean
} => {
let isEnterprise = false
let isCommunity = false
let isRobot = false
let isToken = false
if (config.token && config.token.access_token !== '') {
isToken = true
}
if (config.serverinfo) {
// Enterpriseだったら、trueにする
if (!config.serverinfo.tenant_logical_name) {
// serverinfo.tenant_logical_nameプロパティがなければEnterprise
isEnterprise = true
} else {
//
}
isCommunity = !isEnterprise // Enterpriseの逆にする。
// Enterprise/Community判定は tenant_logical_name があるなしだけの判定なので、
// tenant_logical_nameナシかつ robotInfoだけあれば、userinfoなくてもロボットモードで動くようにする
if (config.robotInfo) {
isRobot = true
} else {
//
}
}
return { isEnterprise, isCommunity, isRobot, isToken }
}
export default OrchestratorApi
import { RobotCrudService } from './services/RobotCrudService'
import { RoleCrudService } from './services/RoleCrudService'
import { MachineCrudService } from './services/MachineCrudService'
import { ReleaseCrudService } from './services/ReleaseCrudService'
import { ProcessCrudService } from './services/ProcessCrudService'
import { JobCrudService } from './services/JobCrudService'
import { QueueDefinitionCrudService } from './services/QueueDefinitionCrudService'
import { LogCrudService } from './services/LogCrudService'
import { AuditLogCrudService } from './services/AuditLogCrudService'
import { SettingCrudService } from './services/SettingCrudService'
import { QueueCrudService } from './services/QueueCrudService'
import { UserCrudService } from './services/UserCrudService'
import { AssetCrudService } from './services/AssetCrudService'
import { UtilService } from './services/UtilService'
import { TenantCrudService } from './services/TenantCrudService'
import { HostLicenseCrudService } from './services/HostLicenseCrudService'
import { EnvironmentCrudService } from './services/EnvironmentCrudService'
import { QueueItemCrudService } from './services/QueueItemCrudService'
import { LibraryCrudService } from './services/LibraryCrudService'
import { FolderCrudService } from './services/FolderCrudService'
import { LicenseCrudService } from './services/LicenseCrudService'
// const getConfig = () => {
// // 設定ファイルから読むパタン
// return config
// // Own Codingするパタン
// // return {
// // userinfo: {
// // tenancyName: 'default',
// // usernameOrEmailAddress: 'aaa',
// // password: 'bbb',
// // },
// // serverinfo: {
// // servername: 'https://platform.uipath.com/',
// // },
// // }
// }
// if (!module.parent) {
// async function main() {
// const api: IOrchestratorApi = new OrchestratorApi(getConfig())
// try {
// // まずは認証
// await api.authenticate()
// let instances: any[] = []
// // instances = await api.asset.findAll({ $expand: 'RobotValues' })
// instances = await api.asset.findAllEx()
// console.table(instances)
// // console.log(instances[0])
// // api.asset.save2Excel(instances, 'assets.xlsx')
// // await api.asset.upload('assets.xlsx')
// await api.asset.uploadPerRobot('assets.xlsx', 'perRobot_assets.xlsx')
// // instances = await api.queueItem.findAll()
// // for (const instance of instances) {
// // console.log(instance)
// // }
// // console.log(instances.length)
// // const queueItemId = instances[0].Id
// // const result = await api.queueItem.find(queueItemId)
// // console.log(result)
// // let queueDef = await api.queueDefinition.findByName('QueueTest')
// // // console.table(queueDef)
// // queueDef = await api.queueDefinition.find(1)
// // console.table(queueDef)
// } catch (error) {
// console.log(error)
// }
// }
// main()
// }