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 activationStatus = "";
612                      var isExtended = false;
613                      var bmcActiveVersion = "";
614                      var hostActiveVersion = "";
615                      var imageType = "";
616                      var extendedVersions = [];
617                      var functionalImages = [];
618
619                      function getFormatedExtendedVersions(extendedVersion){
620                        var versions = [];
621                        extendedVersion = extendedVersion.split(",");
622
623                        extendedVersion.forEach(function(item){
624                          var parts = item.split("-");
625                          var numberIndex = 0;
626                          for(var i = 0; i < parts.length; i++){
627                            if(/[0-9]/.test(parts[i])){
628                              numberIndex = i;
629                              break;
630                            }
631                          }
632                          var titlePart = parts.splice(0, numberIndex);
633                          titlePart = titlePart.join("");
634                          titlePart = titlePart[0].toUpperCase() + titlePart.substr(1, titlePart.length);
635                          var versionPart = parts.join("-");
636                          versions.push({
637                            title: titlePart,
638                            version: versionPart
639                          });
640                        });
641
642                        return versions;
643                      }
644
645                      // Get the list of functional images so we can compare
646                      // later if an image is functional
647                      if (content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH])
648                      {
649                        functionalImages = content.data[Constants.FIRMWARE.FUNCTIONAL_OBJPATH].endpoints;
650                      }
651                      for(var key in content.data){
652                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Version')){
653                          // If the image is "Functional" use that for the
654                          // activation status, else use the value of "Activation"
655                          // github.com/openbmc/phosphor-dbus-interfaces/blob/master/xyz/openbmc_project/Software/Activation.interface.yaml
656                          activationStatus = content.data[key].Activation.split(".").pop();
657                          if (functionalImages.includes(key))
658                          {
659                            activationStatus = "Functional";
660                          }
661
662                          imageType = content.data[key].Purpose.split(".").pop();
663                          isExtended = content.data[key].hasOwnProperty('ExtendedVersion') && content.data[key].ExtendedVersion != "";
664                          if(isExtended){
665                            extendedVersions = getFormatedExtendedVersions(content.data[key].ExtendedVersion);
666                          }
667                          data.push(Object.assign({
668                            path: key,
669                            activationStatus: activationStatus,
670                            imageId: key.split("/").pop(),
671                            imageType: imageType,
672                            isExtended: isExtended,
673                            extended: {
674                              show: false,
675                              versions: extendedVersions
676                            },
677                            data: {key: key, value: content.data[key]}
678                          }, content.data[key]));
679
680                          if(activationStatus == 'Functional' && imageType == 'BMC'){
681                            bmcActiveVersion = content.data[key].Version;
682                          }
683
684                          if(activationStatus == 'Functional' && imageType == 'Host'){
685                            hostActiveVersion = content.data[key].Version;
686                          }
687                        }
688                      }
689
690                      deferred.resolve({
691                          data: data,
692                          bmcActiveVersion: bmcActiveVersion,
693                          hostActiveVersion: hostActiveVersion
694                      });
695                }, function(error){
696                  console.log(error);
697                  deferred.reject(error);
698                });
699
700                return deferred.promise;
701              },
702              changePriority: function(imageId, priority){
703                var deferred = $q.defer();
704                $http({
705                  method: 'PUT',
706                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/Priority",
707                  headers: {
708                      'Accept': 'application/json',
709                      'Content-Type': 'application/json'
710                  },
711                  withCredentials: true,
712                  data: JSON.stringify({"data": priority})
713                }).then(function(response){
714                      var json = JSON.stringify(response.data);
715                      var content = JSON.parse(json);
716                      deferred.resolve(content);
717                }, function(error){
718                  console.log(error);
719                  deferred.reject(error);
720                });
721
722                return deferred.promise;
723              },
724              deleteImage: function(imageId){
725                var deferred = $q.defer();
726                $http({
727                  method: 'POST',
728                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/action/Delete",
729                  headers: {
730                      'Accept': 'application/json',
731                      'Content-Type': 'application/json'
732                  },
733                  withCredentials: true,
734                  data: JSON.stringify({"data": []})
735                }).then(function(response){
736                      var json = JSON.stringify(response.data);
737                      var content = JSON.parse(json);
738                      deferred.resolve(content);
739                }, function(error){
740                  console.log(error);
741                  deferred.reject(error);
742                });
743
744                return deferred.promise;
745              },
746              activateImage: function(imageId){
747                var deferred = $q.defer();
748                $http({
749                  method: 'PUT',
750                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/RequestedActivation",
751                  headers: {
752                      'Accept': 'application/json',
753                      'Content-Type': 'application/json'
754                  },
755                  withCredentials: true,
756                  data: JSON.stringify({"data": Constants.FIRMWARE.ACTIVATE_FIRMWARE})
757                }).then(function(response){
758                      var json = JSON.stringify(response.data);
759                      var content = JSON.parse(json);
760                      deferred.resolve(content);
761                }, function(error){
762                  console.log(error);
763                  deferred.reject(error);
764                });
765
766                return deferred.promise;
767              },
768              uploadImage: function(file){
769                var deferred = $q.defer();
770                $http({
771                  method: 'POST',
772                  timeout: 5 * 60 * 1000,
773                  url: DataService.getHost() + "/upload/image",
774                  headers: {
775                    'Content-Type': 'application/octet-stream'
776                  },
777                  withCredentials: true,
778                  data: file
779                }).then(function(response){
780                      var json = JSON.stringify(response.data);
781                      var content = JSON.parse(json);
782                      deferred.resolve(content);
783                }, function(error){
784                  console.log(error);
785                  deferred.reject(error);
786                });
787
788                return deferred.promise;
789              },
790              downloadImage: function(host, filename){
791                var deferred = $q.defer();
792                $http({
793                  method: 'POST',
794                  url: DataService.getHost() + "/xyz/openbmc_project/software/action/DownloadViaTFTP",
795                  headers: {
796                      'Accept': 'application/json',
797                      'Content-Type': 'application/json'
798                  },
799                  withCredentials: true,
800                  data: JSON.stringify({"data": [filename, host]}),
801                  responseType: 'arraybuffer'
802                }).then(function(response, status, headers){
803                  deferred.resolve({
804                    data: response,
805                    status: status,
806                    headers: headers
807                  });
808                }, function(error){
809                  console.log(error);
810                  deferred.reject(error);
811                });
812
813                return deferred.promise;
814              },
815              getBMCEthernetInfo: function(){
816                var deferred = $q.defer();
817                $http({
818                  method: 'GET',
819                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc/ethernet",
820                  headers: {
821                      'Accept': 'application/json',
822                      'Content-Type': 'application/json'
823                  },
824                  withCredentials: true
825                }).then(function(response){
826                    var json = JSON.stringify(response.data);
827                    var content = JSON.parse(json);
828                    deferred.resolve(content.data);
829                }, function(error){
830                  console.log(error);
831                  deferred.reject(error);
832                });
833
834                return deferred.promise;
835              },
836              getBMCInfo: function(callback){
837                var deferred = $q.defer();
838                $http({
839                  method: 'GET',
840                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc",
841                  headers: {
842                      'Accept': 'application/json',
843                      'Content-Type': 'application/json'
844                  },
845                  withCredentials: true
846                }).then(function(response){
847                    var json = JSON.stringify(response.data);
848                    var content = JSON.parse(json);
849                    deferred.resolve(content.data);
850                }, function(error){
851                  console.log(error);
852                  deferred.reject(error);
853                });
854                return deferred.promise;
855              },
856              getHardwares: function(callback){
857                $http({
858                  method: 'GET',
859                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/enumerate",
860                  headers: {
861                      'Accept': 'application/json',
862                      'Content-Type': 'application/json'
863                  },
864                  withCredentials: true
865                }).then(function(response){
866                      var json = JSON.stringify(response.data);
867                      var content = JSON.parse(json);
868                      var hardwareData = [];
869                      var keyIndexMap = {};
870                      var title = "";
871                      var data = [];
872                      var searchText = "";
873                      var componentIndex = -1;
874                      var tempParts = [];
875
876
877                      function isSubComponent(key){
878
879                        for(var i = 0; i < Constants.HARDWARE.parent_components.length; i++){
880                          if(key.split(Constants.HARDWARE.parent_components[i]).length == 2) return true;
881                        }
882
883                        return false;
884                      }
885
886                      function titlelize(title){
887                        title = title.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
888                        for(var i = 0; i < Constants.HARDWARE.uppercase_titles.length; i++){
889                          if(title.toLowerCase().indexOf((Constants.HARDWARE.uppercase_titles[i] + " ")) > -1){
890                            return title.toUpperCase();
891                          }
892                        }
893
894                        return title;
895                      }
896
897                      function camelcaseToLabel(obj){
898                        var transformed = [], label = "", value = "";
899                        for(var key in obj){
900                          label = key.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
901                          if(obj[key] !== ""){
902                            value = obj[key];
903                            if(value == 1 || value == 0){
904                              value = (value == 1) ? 'Yes' : 'No';
905                            }
906                            transformed.push({key:label, value: value});
907                          }
908                        }
909
910                        return transformed;
911                      }
912
913                      function getSearchText(data){
914                        var searchText = "";
915                        for(var i = 0; i < data.length; i++){
916                          searchText += " " + data[i].key + " " + data[i].value;
917                        }
918
919                        return searchText;
920                      }
921
922                      for(var key in content.data){
923                        if(content.data.hasOwnProperty(key) &&
924                           key.indexOf(Constants.HARDWARE.component_key_filter) == 0){
925
926                          data = camelcaseToLabel(content.data[key]);
927                          searchText = getSearchText(data);
928                          title = key.split("/").pop();
929
930                          title = titlelize(title);
931
932                          if(!isSubComponent(key)){
933                              hardwareData.push(Object.assign({
934                                path: key,
935                                title: title,
936                                selected: false,
937                                expanded: false,
938                                search_text: title.toLowerCase() + " " + searchText.toLowerCase(),
939                                sub_components: [],
940                                original_data: {key: key, value: content.data[key]}
941                              }, {items: data}));
942
943                              keyIndexMap[key] = hardwareData.length - 1;
944                          }else{
945                            var tempParts = key.split("/");
946                            tempParts.pop();
947                            tempParts = tempParts.join("/");
948                            componentIndex = keyIndexMap[tempParts];
949                            data = content.data[key];
950                            data.title = title;
951                            hardwareData[componentIndex].sub_components.push(data);
952                            hardwareData[componentIndex].search_text += " " + title.toLowerCase();
953                          }
954                      }
955                    }
956
957                    if(callback){
958                       callback(hardwareData, content.data);
959                    }else{
960                       return { data: hardwareData, original_data: content.data};
961                    }
962                });
963              },
964              deleteLogs: function(logs) {
965                  var defer = $q.defer();
966                  var promises = [];
967
968                  function finished(){
969                      defer.resolve();
970                  }
971
972                  logs.forEach(function(item){
973                    promises.push($http({
974                                      method: 'POST',
975                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/action/Delete",
976                                      headers: {
977                                          'Accept': 'application/json',
978                                          'Content-Type': 'application/json'
979                                      },
980                                      withCredentials: true,
981                                      data: JSON.stringify({"data": []})
982                                 }));
983                  });
984
985                  $q.all(promises).then(finished);
986
987                  return defer.promise;
988              },
989              resolveLogs: function(logs) {
990                  var defer = $q.defer();
991                  var promises = [];
992
993                  function finished(){
994                      defer.resolve();
995                  }
996
997                  logs.forEach(function(item){
998                    promises.push($http({
999                                      method: 'PUT',
1000                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/attr/Resolved",
1001                                      headers: {
1002                                          'Accept': 'application/json',
1003                                          'Content-Type': 'application/json'
1004                                      },
1005                                      withCredentials: true,
1006                                      data: JSON.stringify({"data": "1"})
1007                                 }));
1008                  });
1009
1010                  $q.all(promises).then(finished);
1011
1012                  return defer.promise;
1013              },
1014          };
1015          return SERVICE;
1016        }]);
1017
1018        })(window.angular);
1019