1/**
2 * API utilities service
3 *
4 * @module app/common/services/api-utils
5 * @exports APIUtils
6 * @name APIUtils
7 * @version 0.0.1
8 */
9
10window.angular && (function (angular) {
11    'use strict';
12    angular
13        .module('app.common.services')
14        .factory('APIUtils', ['$http', 'Constants', '$q', 'dataService',function($http, Constants, $q, DataService){
15          var SERVICE = {
16              LOGIN_CREDENTIALS: Constants.LOGIN_CREDENTIALS,
17              API_CREDENTIALS: Constants.API_CREDENTIALS,
18              API_RESPONSE: Constants.API_RESPONSE,
19              CHASSIS_POWER_STATE: Constants.CHASSIS_POWER_STATE,
20              HOST_STATE_TEXT: Constants.HOST_STATE,
21              HOST_STATE: Constants.HOST_STATE,
22              LED_STATE: Constants.LED_STATE,
23              LED_STATE_TEXT: Constants.LED_STATE_TEXT,
24              HOST_SESSION_STORAGE_KEY: Constants.API_CREDENTIALS.host_storage_key,
25              getChassisState: function(callback){
26                $http({
27                  method: 'GET',
28                  url: DataService.getHost() + "/xyz/openbmc_project/state/chassis0",
29                  headers: {
30                      'Accept': 'application/json',
31                      'Content-Type': 'application/json'
32                  },
33                  withCredentials: true
34                }).then(function(response){
35                      var json = JSON.stringify(response.data);
36                      var content = JSON.parse(json);
37                      callback(content.data.CurrentPowerState);
38                }, function(error){
39                  console.log(error);
40                });
41              },
42              getHostState: function(callback){
43                $http({
44                  method: 'GET',
45                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0",
46                  headers: {
47                      'Accept': 'application/json',
48                      'Content-Type': 'application/json'
49                  },
50                  withCredentials: true
51                }).then(function(response){
52                      var json = JSON.stringify(response.data);
53                      var content = JSON.parse(json);
54                      callback(content.data.CurrentHostState);
55                }, function(error){
56                  console.log(error);
57                });
58              },
59              getNetworkInfo: function(){
60                var deferred = $q.defer();
61                $http({
62                  method: 'GET',
63                  url: DataService.getHost() + "/xyz/openbmc_project/network/enumerate",
64                  headers: {
65                      'Accept': 'application/json',
66                      'Content-Type': 'application/json'
67                  },
68                  withCredentials: true
69                }).then(function(response){
70                    var json = JSON.stringify(response.data);
71                    var content = JSON.parse(json);
72                    var hostname = "";
73                    var macAddress = "";
74
75                    function parseNetworkData(content){
76                      var data = {
77                        interface_ids: [],
78                        interfaces: {
79                        }
80                      };
81                      var interfaceId = '', keyParts = [], interfaceHash = '', interfaceType = '';
82                      for(var key in content.data){
83                        if(key.match(/network\/eth\d+$/ig)){
84                          interfaceId = key.split("/").pop();
85                          if(data.interface_ids.indexOf(interfaceId) == -1){
86                            data.interface_ids.push(interfaceId);
87                            data.interfaces[interfaceId] = {
88                              interfaceIname: '',
89                              domainName:'',
90                              MACAddress:'',
91                              Nameservers: [],
92                              DHCPEnabled: 0,
93                              ipv4:
94                                {
95                                 ids: [],
96                                 values: []
97                                },
98                              ipv6:
99                                {
100                                 ids: [],
101                                 values: []
102                                }
103                            };
104                            data.interfaces[interfaceId].MACAddress = content.data[key].MACAddress;
105                            data.interfaces[interfaceId].DomainName = content.data[key].DomainName.join(" ");
106                            data.interfaces[interfaceId].Nameservers = content.data[key].Nameservers;
107                            data.interfaces[interfaceId].DHCPEnabled = content.data[key].DHCPEnabled;
108                          }
109                        }else if(key.match(/network\/eth\d+\/ipv[4|6]\/[a-z0-9]+$/ig)){
110                          keyParts = key.split("/");
111                          interfaceHash = keyParts.pop();
112                          interfaceType = keyParts.pop();
113                          interfaceId = keyParts.pop();
114
115                          if(data.interfaces[interfaceId][interfaceType].ids.indexOf(interfaceHash) == -1){
116                            data.interfaces[interfaceId][interfaceType].ids.push(interfaceHash);
117                            data.interfaces[interfaceId][interfaceType].values.push(content.data[key]);
118                          }
119                        }
120                      }
121                      return data;
122                    }
123
124                    if(content.data.hasOwnProperty('/xyz/openbmc_project/network/config') &&
125                      content.data['/xyz/openbmc_project/network/config'].hasOwnProperty('HostName')
126                      ){
127                      hostname = content.data['/xyz/openbmc_project/network/config'].HostName;
128                    }
129
130                    if(content.data.hasOwnProperty('/xyz/openbmc_project/network/eth0') &&
131                      content.data['/xyz/openbmc_project/network/eth0'].hasOwnProperty('MACAddress')
132                      ){
133                      macAddress = content.data['/xyz/openbmc_project/network/eth0'].MACAddress;
134                    }
135
136                    deferred.resolve({
137                      data: content.data,
138                      hostname: hostname,
139                      mac_address: macAddress,
140                      formatted_data: parseNetworkData(content)
141                    });
142                }, function(error){
143                  console.log(error);
144                  deferred.reject(error);
145                });
146                return deferred.promise;
147              },
148              getLEDState: function(){
149                var deferred = $q.defer();
150                $http({
151                  method: 'GET',
152                  url: DataService.getHost() + "/xyz/openbmc_project/led/groups/enclosure_identify",
153                  headers: {
154                      'Accept': 'application/json',
155                      'Content-Type': 'application/json'
156                  },
157                  withCredentials: true
158                }).then(function(response){
159                    var json = JSON.stringify(response.data);
160                    var content = JSON.parse(json);
161                    deferred.resolve(content.data.Asserted);
162                }, function(error){
163                  console.log(error);
164                  deferred.reject(error);
165                });
166                return deferred.promise;
167              },
168              login: function(username, password, callback){
169                $http({
170                  method: 'POST',
171                  url: DataService.getHost() + "/login",
172                  headers: {
173                      'Accept': 'application/json',
174                      'Content-Type': 'application/json'
175                  },
176                  withCredentials: true,
177                  data: JSON.stringify({"data": [username, password]})
178                }).then(function(response){
179                  if(callback){
180                      callback(response.data);
181                  }
182                }, function(error){
183                  if(callback){
184                      if(error && error.status && error.status == 'error'){
185                        callback(error);
186                      }else{
187                        callback(error, true);
188                      }
189                  }
190                  console.log(error);
191                });
192              },
193              logout: function(callback){
194                $http({
195                  method: 'POST',
196                  url: DataService.getHost() + "/logout",
197                  headers: {
198                      'Accept': 'application/json',
199                      'Content-Type': 'application/json'
200                  },
201                  withCredentials: true,
202                  data: JSON.stringify({"data": []})
203                }).then(function(response){
204                  if(callback){
205                      callback(response.data);
206                  }
207                }, function(error){
208                  if(callback){
209                      callback(null, error);
210                  }
211                  console.log(error);
212                });
213              },
214              chassisPowerOn: function(callback){
215                $http({
216                  method: 'POST',
217                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0",
218                  headers: {
219                      'Accept': 'application/json',
220                      'Content-Type': 'application/json'
221                  },
222                  withCredentials: true,
223                  data: JSON.stringify({"data": []})
224                }).then(function(response){
225                      var json = JSON.stringify(response.data);
226                      var content = JSON.parse(json);
227                      if(callback){
228                          return callback(content.data.CurrentPowerState);
229                      }
230                }, function(error){
231                  if(callback){
232                      callback(error);
233                  }else{
234                      console.log(error);
235                  }
236                });
237              },
238              chassisPowerOff: function(callback){
239                $http({
240                  method: 'PUT',
241                  url: DataService.getHost() + "/xyz/openbmc_project/state/chassis0/attr/RequestedPowerTransition",
242                  headers: {
243                      'Accept': 'application/json',
244                      'Content-Type': 'application/json'
245                  },
246                  withCredentials: true,
247                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Chassis.Transition.Off"})
248                }).then(function(response){
249                      var json = JSON.stringify(response.data);
250                      var content = JSON.parse(json);
251                      if(callback){
252                          return callback(content.status);
253                      }
254                }, function(error){
255                  if(callback){
256                      callback(error);
257                  }else{
258                      console.log(error);
259                  }
260                });
261              },
262              setLEDState: function(state, callback){
263                $http({
264                  method: 'PUT',
265                  url: DataService.getHost() + "/xyz/openbmc_project/led/groups/enclosure_identify/attr/Asserted",
266                  headers: {
267                      'Accept': 'application/json',
268                      'Content-Type': 'application/json'
269                  },
270                  withCredentials: true,
271                  data: JSON.stringify({"data": state})
272                }).then(function(response){
273                      var json = JSON.stringify(response.data);
274                      var content = JSON.parse(json);
275                      if(callback){
276                          return callback(content.status);
277                      }
278                }, function(error){
279                  if(callback){
280                      callback(error);
281                  }else{
282                      console.log(error);
283                  }
284                });
285              },
286              bmcReboot: function(callback){
287                $http({
288                  method: 'PUT',
289                  url: DataService.getHost() + "/xyz/openbmc_project/state/bmc0/attr/RequestedBmcTransition",
290                  headers: {
291                      'Accept': 'application/json',
292                      'Content-Type': 'application/json'
293                  },
294                  withCredentials: true,
295                  data: JSON.stringify({"data": "xyz.openbmc_project.State.BMC.Transition.Reboot"})
296                }).then(function(response){
297                      var json = JSON.stringify(response.data);
298                      var content = JSON.parse(json);
299                      if(callback){
300                          return callback(content.status);
301                      }
302                }, function(error){
303                  if(callback){
304                      callback(error);
305                  }else{
306                      console.log(error);
307                  }
308                });
309              },
310              hostPowerOn: function(callback){
311                $http({
312                  method: 'PUT',
313                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0/attr/RequestedHostTransition",
314                  headers: {
315                      'Accept': 'application/json',
316                      'Content-Type': 'application/json'
317                  },
318                  withCredentials: true,
319                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Host.Transition.On"})
320                }).then(function(response){
321                      var json = JSON.stringify(response.data);
322                      var content = JSON.parse(json);
323                      if(callback){
324                          return callback(content.status);
325                      }
326                }, function(error){
327                  if(callback){
328                      callback(error);
329                  }else{
330                      console.log(error);
331                  }
332                });
333              },
334              hostPowerOff: function(callback){
335                $http({
336                  method: 'PUT',
337                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0/attr/RequestedHostTransition",
338                  headers: {
339                      'Accept': 'application/json',
340                      'Content-Type': 'application/json'
341                  },
342                  withCredentials: true,
343                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Host.Transition.Off"})
344                }).then(function(response){
345                      var json = JSON.stringify(response.data);
346                      var content = JSON.parse(json);
347                      if(callback){
348                          return callback(content.status);
349                      }
350                }, function(error){
351                  if(callback){
352                      callback(error);
353                  }else{
354                      console.log(error);
355                  }
356                });
357              },
358              hostReboot: function(callback){
359                $http({
360                  method: 'PUT',
361                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0/attr/RequestedHostTransition",
362                  headers: {
363                      'Accept': 'application/json',
364                      'Content-Type': 'application/json'
365                  },
366                  withCredentials: true,
367                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Host.Transition.Reboot"})
368                }).then(function(response){
369                      var json = JSON.stringify(response.data);
370                      var content = JSON.parse(json);
371                      if(callback){
372                          return callback(content.status);
373                      }
374                }, function(error){
375                  if(callback){
376                      callback(error);
377                  }else{
378                      console.log(error);
379                  }
380                });
381              },
382              hostShutdown: function(callback){
383                $http({
384                  method: 'POST',
385                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0",
386                  headers: {
387                      'Accept': 'application/json',
388                      'Content-Type': 'application/json'
389                  },
390                  withCredentials: true,
391                  data: JSON.stringify({"data": []})
392                }).then(function(response){
393                      var json = JSON.stringify(response.data);
394                      var content = JSON.parse(json);
395                      if(callback){
396                          return callback(content);
397                      }
398                }, function(error){
399                  if(callback){
400                      callback(error);
401                  }else{
402                      console.log(error);
403                  }
404                });
405              },
406              getLogs: function(){
407                var deferred = $q.defer();
408                $http({
409                  method: 'GET',
410                  url: DataService.getHost() + "/xyz/openbmc_project/logging/enumerate",
411                  headers: {
412                      'Accept': 'application/json',
413                      'Content-Type': 'application/json'
414                  },
415                  withCredentials: true
416                }).then(function(response){
417                      var json = JSON.stringify(response.data);
418                      var content = JSON.parse(json);
419                      var dataClone = JSON.parse(JSON.stringify(content.data));
420                      var data = [];
421                      var severityCode = '';
422                      var priority = '';
423                      var health = '';
424                      var relatedItems = [];
425
426                      for(var key in content.data){
427                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Id')){
428                          var severityFlags = {low: false, medium: false, high: false};
429                          var healthFlags = {critical: false, warning: false, good: false};
430                          severityCode = content.data[key].Severity.split(".").pop();
431                          priority = Constants.SEVERITY_TO_PRIORITY_MAP[severityCode];
432                          severityFlags[priority.toLowerCase()] = true;
433                          health = Constants.SEVERITY_TO_HEALTH_MAP[severityCode];
434                          healthFlags[health.toLowerCase()] = true;
435                          relatedItems = [];
436                          content.data[key].associations.forEach(function(item){
437                            relatedItems.push(item[2]);
438                          });
439
440                          data.push(Object.assign({
441                            path: key,
442                            copied: false,
443                            priority: priority,
444                            severity_code: severityCode,
445                            severity_flags: severityFlags,
446                            health_flags: healthFlags,
447                            additional_data: content.data[key].AdditionalData.join("\n"),
448                            type: content.data[key].Message,
449                            selected: false,
450                            search_text: ("#" + content.data[key].Id + " " + severityCode + " " + content.data[key].Severity + " " + content.data[key].AdditionalData.join(" ")).toLowerCase(),
451                            meta: false,
452                            confirm: false,
453                            related_items: relatedItems,
454                            data: {key: key, value: content.data[key]}
455                          }, content.data[key]));
456                        }
457                      }
458                      deferred.resolve({data: data, original: dataClone});
459                }, function(error){
460                  console.log(error);
461                  deferred.reject(error);
462                });
463
464                return deferred.promise;
465              },
466              getAllSensorStatus: function(callback){
467                $http({
468                  method: 'GET',
469                  url: DataService.getHost() + "/xyz/openbmc_project/sensors/enumerate",
470                  headers: {
471                      'Accept': 'application/json',
472                      'Content-Type': 'application/json'
473                  },
474                  withCredentials: true
475                }).then(function(response){
476                      var json = JSON.stringify(response.data);
477                      var content = JSON.parse(json);
478                      var dataClone = JSON.parse(JSON.stringify(content.data));
479                      var sensorData = [];
480                      var severity = {};
481                      var title = "";
482                      var tempKeyParts = [];
483                      var order = 0;
484                      var customOrder = 0;
485
486                      function getScaledValue(value, scale){
487                        scale = scale + "";
488                        scale = parseInt(scale, 10);
489                        var power = Math.abs(parseInt(scale,10));
490
491                        if(scale > 0){
492                          value = value * Math.pow(10, power);
493                        }else if(scale < 0){
494                          value = value / Math.pow(10, power);
495                        }
496                        return value;
497                      }
498
499                      function getSensorStatus(reading){
500                        var severityFlags = {critical: false, warning: false, normal: false}, severityText = '', order = 0;
501
502                        if(reading.hasOwnProperty('CriticalLow') &&
503                          reading.Value < reading.CriticalLow
504                          ){
505                          severityFlags.critical = true;
506                          severityText = 'critical';
507                          order = 2;
508                        }else if(reading.hasOwnProperty('CriticalHigh') &&
509                          reading.Value > reading.CriticalHigh
510                          ){
511                          severityFlags.critical = true;
512                          severityText = 'critical';
513                          order = 2;
514                        }else if(reading.hasOwnProperty('CriticalLow') &&
515                          reading.hasOwnProperty('WarningLow') &&
516                          reading.Value >= reading.CriticalLow && reading.Value <= reading.WarningLow){
517                          severityFlags.warning = true;
518                          severityText = 'warning';
519                          order = 1;
520                        }else if(reading.hasOwnProperty('WarningHigh') &&
521                          reading.hasOwnProperty('CriticalHigh') &&
522                          reading.Value >= reading.WarningHigh && reading.Value <= reading.CriticalHigh){
523                          severityFlags.warning = true;
524                          severityText = 'warning';
525                          order = 1;
526                        }else{
527                          severityFlags.normal = true;
528                          severityText = 'normal';
529                        }
530                        return { flags: severityFlags, severityText: severityText, order: order};
531                      }
532
533                      for(var key in content.data){
534                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Unit')){
535
536                          severity = getSensorStatus(content.data[key]);
537
538                          if(!content.data[key].hasOwnProperty('CriticalLow')){
539                            content.data[key].CriticalLow = "--";
540                            content.data[key].CriticalHigh = "--";
541                          }
542
543                          if(!content.data[key].hasOwnProperty('WarningLow')){
544                            content.data[key].WarningLow = "--";
545                            content.data[key].WarningHigh = "--";
546                          }
547
548                          tempKeyParts = key.split("/");
549                          title = tempKeyParts.pop();
550                          title = tempKeyParts.pop() + '_' + title;
551                          title = title.split("_").map(function(item){
552                             return item.toLowerCase().charAt(0).toUpperCase() + item.slice(1);
553                          }).reduce(function(prev, el){
554                            return prev + " " + el;
555                          });
556
557                          content.data[key].Value = getScaledValue(content.data[key].Value, content.data[key].Scale);
558                          content.data[key].CriticalLow = getScaledValue(content.data[key].CriticalLow, content.data[key].Scale);
559                          content.data[key].CriticalHigh = getScaledValue(content.data[key].CriticalHigh, content.data[key].Scale);
560                          content.data[key].WarningLow = getScaledValue(content.data[key].WarningLow, content.data[key].Scale);
561                          content.data[key].WarningHigh = getScaledValue(content.data[key].WarningHigh, content.data[key].Scale);
562                          if(Constants.SENSOR_SORT_ORDER.indexOf(content.data[key].Unit) > -1){
563                            customOrder = Constants.SENSOR_SORT_ORDER.indexOf(content.data[key].Unit);
564                          }else{
565                            customOrder = Constants.SENSOR_SORT_ORDER_DEFAULT;
566                          }
567
568                          sensorData.push(Object.assign({
569                            path: key,
570                            selected: false,
571                            confirm: false,
572                            copied: false,
573                            title: title,
574                            unit: Constants.SENSOR_UNIT_MAP[content.data[key].Unit],
575                            severity_flags: severity.flags,
576                            status: severity.severityText,
577                            order: severity.order,
578                            custom_order: customOrder,
579                            search_text: (title + " " + content.data[key].Value + " " +
580                               Constants.SENSOR_UNIT_MAP[content.data[key].Unit] + " " +
581                               severity.severityText + " " +
582                               content.data[key].CriticalLow + " " +
583                               content.data[key].CriticalHigh + " " +
584                               content.data[key].WarningLow + " " +
585                               content.data[key].WarningHigh + " "
586                               ).toLowerCase(),
587                            original_data: {key: key, value: content.data[key]}
588                          }, content.data[key]));
589                        }
590                      }
591
592                      callback(sensorData, dataClone);
593                }, function(error){
594                  console.log(error);
595                });
596              },
597              getFirmwares: function(){
598                var deferred = $q.defer();
599                $http({
600                  method: 'GET',
601                  url: DataService.getHost() + "/xyz/openbmc_project/software/enumerate",
602                  headers: {
603                      'Accept': 'application/json',
604                      'Content-Type': 'application/json'
605                  },
606                  withCredentials: true
607                }).then(function(response){
608                      var json = JSON.stringify(response.data);
609                      var content = JSON.parse(json);
610                      var data = [];
611                      var active = false;
612                      var functional = false;
613                      var ready = false;
614                      var activationStatus = {active: false, ready: false, functional: false};
615                      var isExtended = false;
616                      var bmcActiveVersion = "";
617                      var hostActiveVersion = "";
618                      var imageType = "";
619                      var extendedVersions = [];
620
621                      function getFormatedExtendedVersions(extendedVersion){
622                        var versions = [];
623                        extendedVersion = extendedVersion.split(",");
624
625                        extendedVersion.forEach(function(item){
626                          var parts = item.split("-");
627                          var numberIndex = 0;
628                          for(var i = 0; i < parts.length; i++){
629                            if(/[0-9]/.test(parts[i])){
630                              numberIndex = i;
631                              break;
632                            }
633                          }
634                          var titlePart = parts.splice(0, numberIndex);
635                          titlePart = titlePart.join("");
636                          titlePart = titlePart[0].toUpperCase() + titlePart.substr(1, titlePart.length);
637                          var versionPart = parts.join("-");
638                          versions.push({
639                            title: titlePart,
640                            version: versionPart
641                          });
642                        });
643
644                        return versions;
645                      }
646
647                      for(var key in content.data){
648                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Version')){
649
650                          functional = (content.data[key].Priority == 0);
651                          active = !functional && (/\.Active$/).test(content.data[key].Activation);
652                          ready = (/\.Ready$/).test(content.data[key].Activation);
653                          activationStatus = {functional: functional, active: active, ready: ready};
654                          imageType = content.data[key].Purpose.split(".").pop();
655                          isExtended = content.data[key].hasOwnProperty('ExtendedVersion') && content.data[key].ExtendedVersion != "";
656                          if(isExtended){
657                            extendedVersions = getFormatedExtendedVersions(content.data[key].ExtendedVersion);
658                          }
659                          data.push(Object.assign({
660                            path: key,
661                            functional: functional,
662                            activationFlags: activationStatus,
663                            imageId: key.split("/").pop(),
664                            imageType: imageType,
665                            isExtended: isExtended,
666                            extended: {
667                              show: false,
668                              versions: extendedVersions
669                            },
670                            data: {key: key, value: content.data[key]}
671                          }, content.data[key]));
672
673                          if(functional && imageType == 'BMC'){
674                            bmcActiveVersion = content.data[key].Version;
675                          }
676
677                          if(functional && imageType == 'Host'){
678                            hostActiveVersion = content.data[key].Version;
679                          }
680                        }
681                      }
682
683                      deferred.resolve({
684                          data: data,
685                          bmcActiveVersion: bmcActiveVersion,
686                          hostActiveVersion: hostActiveVersion
687                      });
688                }, function(error){
689                  console.log(error);
690                  deferred.reject(error);
691                });
692
693                return deferred.promise;
694              },
695              changePriority: function(imageId, priority){
696                var deferred = $q.defer();
697                $http({
698                  method: 'PUT',
699                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/Priority",
700                  headers: {
701                      'Accept': 'application/json',
702                      'Content-Type': 'application/json'
703                  },
704                  withCredentials: true,
705                  data: JSON.stringify({"data": priority})
706                }).then(function(response){
707                      var json = JSON.stringify(response.data);
708                      var content = JSON.parse(json);
709                      deferred.resolve(content);
710                }, function(error){
711                  console.log(error);
712                  deferred.reject(error);
713                });
714
715                return deferred.promise;
716              },
717              deleteImage: function(imageId){
718                var deferred = $q.defer();
719                $http({
720                  method: 'POST',
721                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/action/Delete",
722                  headers: {
723                      'Accept': 'application/json',
724                      'Content-Type': 'application/json'
725                  },
726                  withCredentials: true,
727                  data: JSON.stringify({"data": []})
728                }).then(function(response){
729                      var json = JSON.stringify(response.data);
730                      var content = JSON.parse(json);
731                      deferred.resolve(content);
732                }, function(error){
733                  console.log(error);
734                  deferred.reject(error);
735                });
736
737                return deferred.promise;
738              },
739              activateImage: function(imageId){
740                var deferred = $q.defer();
741                $http({
742                  method: 'PUT',
743                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/RequestedActivation",
744                  headers: {
745                      'Accept': 'application/json',
746                      'Content-Type': 'application/json'
747                  },
748                  withCredentials: true,
749                  data: JSON.stringify({"data": Constants.FIRMWARE.ACTIVATE_FIRMWARE})
750                }).then(function(response){
751                      var json = JSON.stringify(response.data);
752                      var content = JSON.parse(json);
753                      deferred.resolve(content);
754                }, function(error){
755                  console.log(error);
756                  deferred.reject(error);
757                });
758
759                return deferred.promise;
760              },
761              uploadImage: function(file){
762                var deferred = $q.defer();
763                $http({
764                  method: 'POST',
765                  timeout: 5 * 60 * 1000,
766                  url: DataService.getHost() + "/upload/image",
767                  headers: {
768                    'Content-Type': 'application/octet-stream'
769                  },
770                  withCredentials: true,
771                  data: file
772                }).then(function(response){
773                      var json = JSON.stringify(response.data);
774                      var content = JSON.parse(json);
775                      deferred.resolve(content);
776                }, function(error){
777                  console.log(error);
778                  deferred.reject(error);
779                });
780
781                return deferred.promise;
782              },
783              downloadImage: function(host, filename){
784                var deferred = $q.defer();
785                $http({
786                  method: 'POST',
787                  url: DataService.getHost() + "/xyz/openbmc_project/software/action/DownloadViaTFTP",
788                  headers: {
789                      'Accept': 'application/json',
790                      'Content-Type': 'application/json'
791                  },
792                  withCredentials: true,
793                  data: JSON.stringify({"data": [filename, host]}),
794                  responseType: 'arraybuffer'
795                }).then(function(response, status, headers){
796                  deferred.resolve({
797                    data: response,
798                    status: status,
799                    headers: headers
800                  });
801                }, function(error){
802                  console.log(error);
803                  deferred.reject(error);
804                });
805
806                return deferred.promise;
807              },
808              getBMCEthernetInfo: function(){
809                var deferred = $q.defer();
810                $http({
811                  method: 'GET',
812                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc/ethernet",
813                  headers: {
814                      'Accept': 'application/json',
815                      'Content-Type': 'application/json'
816                  },
817                  withCredentials: true
818                }).then(function(response){
819                    var json = JSON.stringify(response.data);
820                    var content = JSON.parse(json);
821                    deferred.resolve(content.data);
822                }, function(error){
823                  console.log(error);
824                  deferred.reject(error);
825                });
826
827                return deferred.promise;
828              },
829              getBMCInfo: function(callback){
830                var deferred = $q.defer();
831                $http({
832                  method: 'GET',
833                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc",
834                  headers: {
835                      'Accept': 'application/json',
836                      'Content-Type': 'application/json'
837                  },
838                  withCredentials: true
839                }).then(function(response){
840                    var json = JSON.stringify(response.data);
841                    var content = JSON.parse(json);
842                    deferred.resolve(content.data);
843                }, function(error){
844                  console.log(error);
845                  deferred.reject(error);
846                });
847                return deferred.promise;
848              },
849              getHardwares: function(callback){
850                $http({
851                  method: 'GET',
852                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/enumerate",
853                  headers: {
854                      'Accept': 'application/json',
855                      'Content-Type': 'application/json'
856                  },
857                  withCredentials: true
858                }).then(function(response){
859                      var json = JSON.stringify(response.data);
860                      var content = JSON.parse(json);
861                      var hardwareData = [];
862                      var keyIndexMap = {};
863                      var title = "";
864                      var data = [];
865                      var searchText = "";
866                      var componentIndex = -1;
867                      var tempParts = [];
868
869
870                      function isSubComponent(key){
871
872                        for(var i = 0; i < Constants.HARDWARE.parent_components.length; i++){
873                          if(key.split(Constants.HARDWARE.parent_components[i]).length == 2) return true;
874                        }
875
876                        return false;
877                      }
878
879                      function titlelize(title){
880                        title = title.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
881                        for(var i = 0; i < Constants.HARDWARE.uppercase_titles.length; i++){
882                          if(title.toLowerCase().indexOf((Constants.HARDWARE.uppercase_titles[i] + " ")) > -1){
883                            return title.toUpperCase();
884                          }
885                        }
886
887                        return title;
888                      }
889
890                      function camelcaseToLabel(obj){
891                        var transformed = [], label = "", value = "";
892                        for(var key in obj){
893                          label = key.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
894                          if(obj[key] !== ""){
895                            value = obj[key];
896                            if(value == 1 || value == 0){
897                              value = (value == 1) ? 'Yes' : 'No';
898                            }
899                            transformed.push({key:label, value: value});
900                          }
901                        }
902
903                        return transformed;
904                      }
905
906                      function getSearchText(data){
907                        var searchText = "";
908                        for(var i = 0; i < data.length; i++){
909                          searchText += " " + data[i].key + " " + data[i].value;
910                        }
911
912                        return searchText;
913                      }
914
915                      for(var key in content.data){
916                        if(content.data.hasOwnProperty(key) &&
917                           key.indexOf(Constants.HARDWARE.component_key_filter) == 0){
918
919                          data = camelcaseToLabel(content.data[key]);
920                          searchText = getSearchText(data);
921                          title = key.split("/").pop();
922
923                          title = titlelize(title);
924
925                          if(!isSubComponent(key)){
926                              hardwareData.push(Object.assign({
927                                path: key,
928                                title: title,
929                                selected: false,
930                                expanded: false,
931                                search_text: title.toLowerCase() + " " + searchText.toLowerCase(),
932                                sub_components: [],
933                                original_data: {key: key, value: content.data[key]}
934                              }, {items: data}));
935
936                              keyIndexMap[key] = hardwareData.length - 1;
937                          }else{
938                            var tempParts = key.split("/");
939                            tempParts.pop();
940                            tempParts = tempParts.join("/");
941                            componentIndex = keyIndexMap[tempParts];
942                            data = content.data[key];
943                            data.title = title;
944                            hardwareData[componentIndex].sub_components.push(data);
945                            hardwareData[componentIndex].search_text += " " + title.toLowerCase();
946                          }
947                      }
948                    }
949
950                    if(callback){
951                       callback(hardwareData, content.data);
952                    }else{
953                       return { data: hardwareData, original_data: content.data};
954                    }
955                });
956              },
957              deleteLogs: function(logs) {
958                  var defer = $q.defer();
959                  var promises = [];
960
961                  function finished(){
962                      defer.resolve();
963                  }
964
965                  logs.forEach(function(item){
966                    promises.push($http({
967                                      method: 'POST',
968                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/action/Delete",
969                                      headers: {
970                                          'Accept': 'application/json',
971                                          'Content-Type': 'application/json'
972                                      },
973                                      withCredentials: true,
974                                      data: JSON.stringify({"data": []})
975                                 }));
976                  });
977
978                  $q.all(promises).then(finished);
979
980                  return defer.promise;
981              },
982              resolveLogs: function(logs) {
983                  var defer = $q.defer();
984                  var promises = [];
985
986                  function finished(){
987                      defer.resolve();
988                  }
989
990                  logs.forEach(function(item){
991                    promises.push($http({
992                                      method: 'PUT',
993                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/attr/Resolved",
994                                      headers: {
995                                          'Accept': 'application/json',
996                                          'Content-Type': 'application/json'
997                                      },
998                                      withCredentials: true,
999                                      data: JSON.stringify({"data": "1"})
1000                                 }));
1001                  });
1002
1003                  $q.all(promises).then(finished);
1004
1005                  return defer.promise;
1006              },
1007          };
1008          return SERVICE;
1009        }]);
1010
1011        })(window.angular);
1012