summaryrefslogtreecommitdiffstats
path: root/server/lib/external-backends/backends/idoit-backend.js
blob: d3d992f1703291a20cbc6d2bf506ea4f8f179276 (plain) (blame)
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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
/* global __appdir */
const path = require('path')
const ExternalBackends = require(path.join(__appdir, 'lib', 'external-backends'))
var axios = require('axios')

class IdoitBackend extends ExternalBackends {
  // ############################################################################
  // ######################## needed functions  #################################

  /*
   * Returns the credential structure / fields, defined in the backends.
   */
  getCredentials () {
    return [
      { type: 'text', id: 1, name: 'API URL', icon: 'link' },
      { type: 'password', id: 2, name: 'API Token', icon: 'vpn_key', show: false },
      {
        type: 'switch',
        id: 3,
        name: 'Login',
        icon: 'lock_open',
        elements: [
          { type: 'text', id: 4, name: 'Username', icon: 'person_outline' },
          { type: 'password', id: 5, name: 'Password', icon: 'lock', show: false }
        ]
      }
    ]
  }

  /*
   * Checks the connection of a given backend.
   * idoIT: Checks if we can get a valid session id. If so the connection must be successfull.
   *
   * return: { success: <boolean>, status: '<STATUS_CODE_IF_ERROR>', error: '<ERROR_MESSAGE>' }
   */
  checkConnection (credentials) {
    var c = this.mapCredentials(credentials)
    return this.getSession(c)
  }

  // Return the list of object types created in iDoIT.
  async getObjectTypes (credentials) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    // Headers
    var headers = {
      'X-RPC-Auth-Session': sid
    }

    // Params
    var params = {
      'apikey': c.apikey,
      'language': 'en'
    }

    var result = {}
    result.types = await this.axiosRequest(c.url, 'cmdb.object_types', params, headers)
    result.types = result.types.data.result

    var types = []
    result.types.forEach(type => {
      types.push({ id: type.id, title: type.title })
    })

    return types
  }

  getSyncTypes () {
    return ['None', 'Two-Way', 'Upload Only', 'Upload Then Delete', 'Upload Mirror', 'Download Only', 'Download Then Delete', 'Download Mirror']
  }

  /*
   * Gets all objects and searches for the ip. Because idoit cannot search for ip or mac.
   *
   */
  async getClient (credentials, client) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']
    // var uuid = client.uuid

    // Headers
    var headers = {
      'X-RPC-Auth-Session': sid,
      'Content-Type': 'application/json'
    }

    // Params to get all clients.
    var params = {
      'apikey': c.apikey,
      'language': 'en',
      'filter': {
        'type': 10
      }
    }

    // Get all client objects.
    var clients = await this.axiosRequest(c.url, 'cmdb.objects', params, headers)
    clients = clients.data.result

    var bodies = []

    clients.forEach(client => {
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.read',
        'params': {
          'objID': client.id,
          'apikey': c.apikey,
          'language': 'en',
          'category': 'C__CATG__MODEL'
        },
        'id': client.id
      })
    })

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }
    var requestClient = await axios.post(c.url, bodies, config)
    requestClient = requestClient.data.filter(x => x.result.length >= 1 && x.result[0].productid === client.uuid)

    return requestClient.length >= 1 ? { succes: true, data: requestClient[0].result[0].objID } : { success: false, error: 'NO_CLIENT_FOUND', msg: 'There is no client matching with the provided uuid.' }
  }

  async getObjects (credentials) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    // Headers
    var headers = {
      'X-RPC-Auth-Session': sid
    }

    // Params
    var params = {
      'apikey': c.apikey,
      'language': 'en'
    }

    var result = {}
    result.objects = await this.axiosRequest(c.url, 'cmdb.objects', params, headers)
    result.objects = result.objects.data.result

    return result
  }

  async getObject (credentials, oid) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    // Headers
    var headers = {
      'X-RPC-Auth-Session': sid
    }

    // Params
    var params = {
      'id': oid,
      'apikey': c.apikey,
      'language': 'en'
    }

    var result = {}
    result.object = await this.axiosRequest(c.url, 'cmdb.object.read', params, headers)
    result.childs = await this.axiosRequest(c.url, 'cmdb.location_tree', params, headers)
    result.object = result.object.data.result
    result.childs = result.childs.data.result
    return result
  }

  async deleteObjects (credentials, objectIds) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }

    var bodies = []

    objectIds.forEach(oid => {
    // Body
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.object.delete',
        'params': {
          'id': oid,
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': oid
      })
    })

    var requestDelete = await axios.post(c.url, bodies, config)

    return { success: requestDelete.success, data: requestDelete.data }
  }

  // Function to use the same session for multiple requests
  async getDataTree (credentials, objects) {
    var c = this.mapCredentials(credentials)

    // LOGIN
    // Open and get a session
    const body = {
      'version': '2.0',
      'method': 'idoit.login',
      'params': {
        'apikey': c.apikey,
        'language': 'en'
      },
      'id': 1
    }

    // Headers
    var headers = {}
    // Optional credentials
    if (c.login) {
      headers['X-RPC-Auth-Username'] = c.username
      headers['X-RPC-Auth-Password'] = c.password
    }

    var config = {
      timeout: 180000,
      headers: headers
    }

    // Make a login request and see if we are authenticated.
    var log = await axios.post(c.url, body, config)
    log = log.data.result
    var sid = log['session-id']

    // Headers
    config.headers = { 'X-RPC-Auth-Session': sid, 'Content-Type': 'application/json' }
    body.method = 'cmdb.location_tree'

    // Go through the objects and get all the childs.
    var promises = []

    var counter = 0
    var index = 0
    var gids = {}

    // Prepare all the batch request bodies.
    var e
    for (e in objects) {
      // Pack 400 requests in one batch request to reduce api calls.
      if (counter >= 400) {
        counter = 0
        index++
      }
      if (counter === 0) promises[index] = []
      counter++

      var element = objects[e]
      const bod = {
        'version': '2.0',
        'method': 'cmdb.location_tree',
        'params': {
          'id': element.eid,
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': element.eid
      }
      promises[index].push(bod)
      gids[element.eid] = element.gid
    }

    // Send all the batch request and post proccess the result into one array.
    var result = []
    var p
    var counter2 = 1
    for (p in promises) {
      // TODO: Remove
      // Counter for getting an overview, how far the requests are.
      console.log(counter2 + '/' + promises.length + ' requests send')
      counter2++

      // Send the request.
      var requestResult = await axios.post(c.url, promises[p], config)
      const args = requestResult.data

      // Post process the data.
      var a
      for (a in args) {
        result.push({ gid: gids[args[a].id], childs: args[a].result })
      }
    }
    return result
  }

  /*
   * Adds the client to the backend.
   *
   * credentials: <BACKEND_CREDENTIALS>
   * The client parameters are all optional. If the client has an id the object is not created but the categories of the object.
   * client: {
   *            id: <CLIENT_ID>, title: <CLIENT_TITLE>, parentId: <PARENT_ID>,
   *            network: { mac: <MAC_ADDRESS>, ip: <IP_ADDRESS> }
   *         }
   */
  async addClient (credentials, client) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }
    var bodies = []
    var clientid
    if (!client.id) {
      // Create the object in idoIT.
      var params = {
        'type': 10,
        'title': client.title,
        'apikey': c.apikey,
        'language': 'en'
      }
      // 1 = Production
      // 2 = Test
      // 3 = Quality Assurance
      // 5 = PVS
      // 7 = Pool PC
      // 8 = Mitarbeiter Arbeitsplatz
      if (client.purpose === 'Pool PC') params.purpose = 7

      var requestCreate = await this.axiosRequest(c.url, 'cmdb.object.create', params, config.headers)

      clientid = requestCreate.data.result.id
    } else {
      clientid = client.id

      // Update the client title
      var bodyGeneral = {
        'version': '2.0',
        'method': 'cmdb.object.update',
        'params': {
          'id': clientid,
          'title': client.title,
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_title'
      }
      if (client.purpose === 'Pool PC') bodyGeneral.params.purpose = 7

      bodies.push(bodyGeneral)
    }

    if (client.uuid) {
      // Update the productid to the uuid.
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.update',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__MODEL',
          'data': {
            'productid': client.uuid
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_uuid'
      })
    }

    if (client.network) {
      // Update the object. MAC-Address
      if (client.network.mac) {
        // First read if there are current entries.
        // Delete the previous entries.
        // Finally create the new entry.
        bodies.push({
          'version': '2.0',
          'method': 'cmdb.category.create',
          'params': {
            'objID': clientid,
            'category': 'C__CATG__NETWORK_PORT',
            'data': {
              'category_id': 1,
              'mac': client.network.mac
            },
            'apikey': c.apikey,
            'language': 'en'
          },
          'id': 'create_mac'
        })
      }

      // Update the object. IP-Address
      if (client.network.ip) {
        bodies.push({
          'version': '2.0',
          'method': 'cmdb.category.create',
          'params': {
            'objID': clientid,
            'category': 'C__CATG__IP',
            'data': {
              'category_id': 1,
              'ipv4_address': client.network.ip
            },
            'apikey': c.apikey,
            'language': 'en'
          },
          'id': 'create_ip'
        })
      }
    }

    // Update the object. Location
    if (client.parentId) {
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.update',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__LOCATION',
          'data': {
            'parent': client.parentId
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_parent'
      })
    }

    var requestUpdate = await axios.post(c.url, bodies, config)

    var result = {
      success: true,
      id: clientid,
      type: 10,
      create: requestCreate ? requestCreate.success : false,
      update: requestUpdate ? requestUpdate.success : false,
      createData: requestCreate ? requestCreate.data : false,
      updateData: requestUpdate ? requestUpdate.data : false
    }

    return result
  }

  /*
   * Updates the client information in the backend.
   *
   * credentials: <BACKEND_CREDENTIALS>
   * The client parameters are all optional.
   * client: {
   *            id: <CLIENT_ID>, title: <CLIENT_TITLE>, parentId: <PARENT_ID>,
   *            system: { model: <SYSTEM_MODEL>, manufacturer: <SYSTEM_MANUFACTURER>,  serialnumber: <SYSTEM_SERIALNUMBER> },
   *            cpu: { model: <CPU_MODEL>, manufacturer: <CPU_MANUFACTURER>, type: <CPU_TYPE>, frequency: <CPU_FREQUENCY>, cores: <CPU_CORES> },
   *            ram: [{ title: <RAM_TITLE>, manufacturer: <RAM_MANUFACTURER>, type: <RAM_TYPE>,  capacity: <RAM_CAPACITY>, unit: <RAM_UNIT> }, ...],
   *            drives: [{model: <DRIVE_MODEL>,}, serial: <DRIVE_SERIAL>, capacity: <DRIVE_CAPACITY>, unit: <DRIVE_UNIT>, type: <DRIVE_TYPE>, formfactor: <DRIVE_FORMFACTOR>, connection: <DRIVE_CONNECTION> ...]
   *         }
   */
  async updateClient (credentials, client) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }

    var clientid = client.id
    var bodies = []
    var counter

    if (client.title) {
      // Update title of the object
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.object.update',
        'params': {
          'id': clientid,
          'title': client.title,
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_title'
      })
    }

    if (client.uuid) {
      // Update the productid to the uuid.
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.update',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__MODEL',
          'data': {
            'productid': client.uuid
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_uuid'
      })
    }

    // Update the object. Location
    if (client.parentId) {
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.update',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__LOCATION',
          'data': {
            'parent': client.parentId
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_parent'
      })
    }

    if (client.system) {
      // Update the object.
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.update',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__MODEL',
          'data': {
            'manufacturer': client.system.manufacturer,
            'title': client.system.model,
            'serial': client.system.serialnumber
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_model'
      })
    }

    if (client.cpu) {
      // TODO: Delete cpu if exists?
      // Update the object.
      bodies.push({
        'version': '2.0',
        'method': 'cmdb.category.create',
        'params': {
          'objID': clientid,
          'category': 'C__CATG__CPU',
          'data': {
            'category_id': 1,
            'manufacturer': client.cpu.manufacturer,
            'title': client.cpu.model,
            'type': client.cpu.type,
            'frequency': client.cpu.frequency,
            'frequency_unit': 3,
            'cores': client.cpu.cores
          },
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 'update_cpu'
      })
    }

    if (client.ram) {
      counter = 1
      for (var memory in client.ram) {
        var mem = client.ram[memory]
        var ramId = 'create_memory_' + counter
        if (mem.unit === 'MB') mem.capacity = mem.capacity / 1024

        // 2 = MB
        // 3 = GB
        // Update the object.
        bodies.push({
          'version': '2.0',
          'method': 'cmdb.category.create',
          'params': {
            'objID': clientid,
            'category': 'C__CATG__MEMORY',
            'data': {
              'title': mem.title,
              'manufacturer': mem.manufacturer,
              'type': mem.type,
              'capacity': mem.capacity,
              'unit': 3
            },
            'apikey': c.apikey,
            'language': 'en'
          },
          'id': ramId
        })
        counter++
      }
    }

    if (client.drives) {
      counter = 1
      for (var drive in client.drives) {
        var d = client.drives[drive]
        var driveId = 'create_drive_' + counter

        // UNIT
        var unit = 0
        if (d.unit === 'GB') unit = 3
        else if (d.unit === 'TB') unit = 4
        else if (d.unit === 'MB') unit = 2
        else if (d.unit === 'KB') unit = 1
        else if (d.unit === 'B') unit = 0

        // Update the object.
        bodies.push({
          'version': '2.0',
          'method': 'cmdb.category.create',
          'params': {
            'objID': clientid,
            'category': 'C__CATG__STORAGE_DEVICE',
            'data': {
              'title': d.model,
              'type': d.type,
              // 'manufacturer': ,
              // 'model': ,
              'capacity': d.capacity,
              'unit': unit,
              'serial': d.serial,
              'connected': d.connection
            },
            'apikey': c.apikey,
            'language': 'en'
          },
          'id': driveId
        })
      }
    }
    try {
      var requestUpdate = await axios.post(c.url, bodies, config)
    } catch (error) {
      console.log(error)
    }
    // 10 is the idoit object id for clients.
    var result = {
      success: true,
      id: clientid,
      type: 10,
      update: requestUpdate ? requestUpdate.success : false,
      updateData: requestUpdate ? requestUpdate.data : false
    }

    return result
  }

  async getFileList (credentials, externalId) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }
    var body = {
      'version': '2.0',
      'method': 'cmdb.category.read',
      'params': {
        'objID': externalId,
        'category': 'C__CATG__FILE',
        'apikey': c.apikey,
        'language': 'en'
      },
      'id': 1
    }
    let result = await axios.post(c.url, body, config)
    return result.data.result
  }

  async getFile (credentials, externalId, filename) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }

    var body = {
      'version': '2.0',
      'method': 'cmdb.category.read',
      'params': {
        'objID': externalId,
        'category': 'C__CATG__FILE',
        'apikey': c.apikey,
        'language': 'en'
      },
      'id': 1
    }
    let files = await axios.post(c.url, body, config)
    let fileObjId = files.data.result.find(x => x.file.title === filename).file.id

    var body2 = {
      'version': '2.0',
      'method': 'cmdb.category.read',
      'params': {
        'objID': fileObjId,
        'category': 'C__CMDB__SUBCAT__FILE_VERSIONS',
        'apikey': c.apikey,
        'language': 'en'
      },
      'id': 1
    }
    let result = await axios.post(c.url, body2, config)
    result = result.data.result[0]

    return { filename: result.file_title, value: result.file_content.value, md5: result.md5_hash }
  }

  async uploadFiles (credentials, externalId, files) {
    var c = this.mapCredentials(credentials)
    var login = await this.getSession(c)
    var sid = login.data.result['session-id']

    var config = {
      timeout: 180000,
      headers: {
        'X-RPC-Auth-Session': sid,
        'Content-Type': 'application/json'
      }
    }
    var result = []
    for (var key in files) {
      var body = {
        'version': '2.0',
        'method': 'cmdb.object.create',
        'params': {
          'type': 29,
          'title': files[key].name,
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': key
      }
      var fileObject = await axios.post(c.url, body, config)
      result.push(fileObject)

      /* eslint-disable */
      var buffer = new Buffer.from(files[key].data)
      /* eslint-enable */

      var filename = files[key].name

      // Upload file to fileobject.
      body = {
        'version': '2.0',
        'method': 'cmdb.category.create',
        'params': {
          'objID': fileObject.data.result.id,
          'data': {
            'file_content': buffer.toString('base64'),
            'file_physical': filename,
            'file_title': filename,
            'version_description': key
          },
          'category': 'C__CMDB__SUBCAT__FILE_VERSIONS',
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': key
      }
      var fileupload = await axios.post(c.url, body, config)
      result.push(fileupload)

      // Combine fileObject with object.
      body = {
        'version': '2.0',
        'method': 'cmdb.category.create',
        'params': {
          'objID': externalId,
          'data': {
            'file': fileObject.data.result.id
          },
          'category': 'C__CATG__FILE',
          'apikey': c.apikey,
          'language': 'en'
        },
        'id': 4
      }
      var concat = await axios.post(c.url, body, config)
      result.push(concat)
    }

    return { result: result }
  }

  // ############################################################################
  // ####################### helper/optional functions  #########################

  // Helper function, to map the array of credential objects into a single js object.
  mapCredentials (credentials) {
    const c = JSON.parse(credentials)
    const login = c.find(x => x.id === 3)
    var mapped = {
      url: c.find(x => x.id === 1).value,
      apikey: c.find(x => x.id === 2).value,
      login: login.value
    }

    if (mapped.login) {
      mapped.username = login.elements.find(x => x.id === 4).value
      mapped.password = login.elements.find(x => x.id === 5).value
    }
    return mapped
  }

  // Username and password are optional.
  async getSession (credentials) {
    // Headers
    var headers = {}
    // Optional credentials
    if (credentials.login) {
      headers['X-RPC-Auth-Username'] = credentials.username
      headers['X-RPC-Auth-Password'] = credentials.password
    }

    // Params
    var params = {
      'apikey': credentials.apikey,
      'language': 'en'
    }

    // Make a login request and see if we are authenticated.
    return this.axiosRequest(credentials.url, 'idoit.login', params, headers)
  }

  // Helper function to make the axios http/https requests to reduced copy pasta code in this backend. Including the error handling.
  async axiosRequest (url, method, params, headers) {
    const body = {
      'version': '2.0',
      'method': method,
      'params': params,
      'id': 1
    }

    var config = {
      timeout: 180000,
      headers: headers
    }
    config.headers['Content-Type'] = 'application/json'
    var response = await axios.post(url, body, config)
      .then(response => {
        return response
      })
      .catch(error => {
        console.log(error)
        return error.response ? error.response : { status: 900, statusText: 'Request failed timeout' }
      })
    // Axios error handling
    if (response.status !== 200) {
      return { success: false, error: response.status, msg: response.statusText }
    }
    // iDoIT error handling.
    if (response.data.result) {
      return { success: true, data: response.data }
    } else if (response.data.error) {
      console.log(response.data.error)
      return { success: false, error: response.data.error.message, msg: response.data.error.data.error }
    } else {
      return { success: false, error: 'UNNOWN_ERROR' }
    }
  }
}

module.exports = IdoitBackend