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: 'POST',
361                  url: DataService.getHost() + "/xyz/openbmc_project/state/host0",
362                  headers: {
363                      'Accept': 'application/json',
364                      'Content-Type': 'application/json'
365                  },
366                  withCredentials: true,
367                  data: JSON.stringify({"data": []}),
368                }).then(function(response){
369                      var json = JSON.stringify(response.data);
370                      var content = JSON.parse(json);
371                      if(callback){
372                          return callback(content);
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                            selected: false,
449                            search_text: ("#" + content.data[key].Id + " " + severityCode + " " + content.data[key].Severity + " " + content.data[key].AdditionalData.join(" ")).toLowerCase(),
450                            meta: false,
451                            confirm: false,
452                            related_items: relatedItems,
453                            data: {key: key, value: content.data[key]}
454                          }, content.data[key]));
455                        }
456                      }
457                      deferred.resolve({data: data, original: dataClone});
458                }, function(error){
459                  console.log(error);
460                  deferred.reject(error);
461                });
462
463                return deferred.promise;
464              },
465              getAllSensorStatus: function(callback){
466                $http({
467                  method: 'GET',
468                  url: DataService.getHost() + "/xyz/openbmc_project/sensors/enumerate",
469                  headers: {
470                      'Accept': 'application/json',
471                      'Content-Type': 'application/json'
472                  },
473                  withCredentials: true
474                }).then(function(response){
475                      var json = JSON.stringify(response.data);
476                      var content = JSON.parse(json);
477                      var dataClone = JSON.parse(JSON.stringify(content.data));
478                      var sensorData = [];
479                      var severity = {};
480                      var title = "";
481                      var tempKeyParts = [];
482                      var order = 0;
483                      var customOrder = 0;
484
485                      function getScaledValue(value, scale){
486                        scale = scale + "";
487                        scale = parseInt(scale, 10);
488                        var power = Math.abs(parseInt(scale,10));
489
490                        if(scale > 0){
491                          value = value * Math.pow(10, power);
492                        }else if(scale < 0){
493                          value = value / Math.pow(10, power);
494                        }
495                        return value;
496                      }
497
498                      function getSensorStatus(reading){
499                        var severityFlags = {critical: false, warning: false, normal: false}, severityText = '', order = 0;
500
501                        if(reading.hasOwnProperty('CriticalLow') &&
502                          reading.Value < reading.CriticalLow
503                          ){
504                          severityFlags.critical = true;
505                          severityText = 'critical';
506                          order = 2;
507                        }else if(reading.hasOwnProperty('CriticalHigh') &&
508                          reading.Value > reading.CriticalHigh
509                          ){
510                          severityFlags.critical = true;
511                          severityText = 'critical';
512                          order = 2;
513                        }else if(reading.hasOwnProperty('CriticalLow') &&
514                          reading.hasOwnProperty('WarningLow') &&
515                          reading.Value >= reading.CriticalLow && reading.Value <= reading.WarningLow){
516                          severityFlags.warning = true;
517                          severityText = 'warning';
518                          order = 1;
519                        }else if(reading.hasOwnProperty('WarningHigh') &&
520                          reading.hasOwnProperty('CriticalHigh') &&
521                          reading.Value >= reading.WarningHigh && reading.Value <= reading.CriticalHigh){
522                          severityFlags.warning = true;
523                          severityText = 'warning';
524                          order = 1;
525                        }else{
526                          severityFlags.normal = true;
527                          severityText = 'normal';
528                        }
529                        return { flags: severityFlags, severityText: severityText, order: order};
530                      }
531
532                      for(var key in content.data){
533                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Unit')){
534
535                          severity = getSensorStatus(content.data[key]);
536
537                          if(!content.data[key].hasOwnProperty('CriticalLow')){
538                            content.data[key].CriticalLow = "--";
539                            content.data[key].CriticalHigh = "--";
540                          }
541
542                          if(!content.data[key].hasOwnProperty('WarningLow')){
543                            content.data[key].WarningLow = "--";
544                            content.data[key].WarningHigh = "--";
545                          }
546
547                          tempKeyParts = key.split("/");
548                          title = tempKeyParts.pop();
549                          title = tempKeyParts.pop() + '_' + title;
550                          title = title.split("_").map(function(item){
551                             return item.toLowerCase().charAt(0).toUpperCase() + item.slice(1);
552                          }).reduce(function(prev, el){
553                            return prev + " " + el;
554                          });
555
556                          content.data[key].Value = getScaledValue(content.data[key].Value, content.data[key].Scale);
557
558                          if(Constants.SENSOR_SORT_ORDER.indexOf(content.data[key].Unit) > -1){
559                            customOrder = Constants.SENSOR_SORT_ORDER.indexOf(content.data[key].Unit);
560                          }else{
561                            customOrder = Constants.SENSOR_SORT_ORDER_DEFAULT;
562                          }
563
564                          sensorData.push(Object.assign({
565                            path: key,
566                            selected: false,
567                            confirm: false,
568                            copied: false,
569                            title: title,
570                            unit: Constants.SENSOR_UNIT_MAP[content.data[key].Unit],
571                            severity_flags: severity.flags,
572                            status: severity.severityText,
573                            order: severity.order,
574                            custom_order: customOrder,
575                            search_text: (title + " " + content.data[key].Value + " " +
576                               Constants.SENSOR_UNIT_MAP[content.data[key].Unit] + " " +
577                               severity.severityText + " " +
578                               content.data[key].CriticalLow + " " +
579                               content.data[key].CriticalHigh + " " +
580                               content.data[key].WarningLow + " " +
581                               content.data[key].WarningHigh + " "
582                               ).toLowerCase(),
583                            original_data: {key: key, value: content.data[key]}
584                          }, content.data[key]));
585                        }
586                      }
587
588                      callback(sensorData, dataClone);
589                }, function(error){
590                  console.log(error);
591                });
592              },
593              getFirmwares: function(){
594                var deferred = $q.defer();
595                $http({
596                  method: 'GET',
597                  url: DataService.getHost() + "/xyz/openbmc_project/software/enumerate",
598                  headers: {
599                      'Accept': 'application/json',
600                      'Content-Type': 'application/json'
601                  },
602                  withCredentials: true
603                }).then(function(response){
604                      var json = JSON.stringify(response.data);
605                      var content = JSON.parse(json);
606                      var data = [];
607                      var active = false;
608                      var functional = false;
609                      var ready = false;
610                      var activationStatus = {active: false, ready: false, functional: false};
611                      var isExtended = false;
612                      var bmcActiveVersion = "";
613                      var hostActiveVersion = "";
614                      var imageType = "";
615                      var extendedVersions = [];
616
617                      function getFormatedExtendedVersions(extendedVersion){
618                        var versions = [];
619                        extendedVersion = extendedVersion.split(",");
620
621                        extendedVersion.forEach(function(item){
622                          var parts = item.split("-");
623                          var numberIndex = 0;
624                          for(var i = 0; i < parts.length; i++){
625                            if(/[0-9]/.test(parts[i])){
626                              numberIndex = i;
627                              break;
628                            }
629                          }
630                          var titlePart = parts.splice(0, numberIndex);
631                          titlePart = titlePart.join("");
632                          titlePart = titlePart[0].toUpperCase() + titlePart.substr(1, titlePart.length);
633                          var versionPart = parts.join("-");
634                          versions.push({
635                            title: titlePart,
636                            version: versionPart
637                          });
638                        });
639
640                        return versions;
641                      }
642
643                      for(var key in content.data){
644                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Version')){
645
646                          functional = (content.data[key].Priority == 0);
647                          active = !functional && (/\.Active$/).test(content.data[key].Activation);
648                          ready = (/\.Ready$/).test(content.data[key].Activation);
649                          activationStatus = {functional: functional, active: active, ready: ready};
650                          imageType = content.data[key].Purpose.split(".").pop();
651                          isExtended = content.data[key].hasOwnProperty('ExtendedVersion') && content.data[key].ExtendedVersion != "";
652                          if(isExtended){
653                            extendedVersions = getFormatedExtendedVersions(content.data[key].ExtendedVersion);
654                          }
655                          data.push(Object.assign({
656                            path: key,
657                            functional: functional,
658                            activationFlags: activationStatus,
659                            imageId: key.split("/").pop(),
660                            imageType: imageType,
661                            isExtended: isExtended,
662                            extended: {
663                              show: false,
664                              versions: extendedVersions
665                            },
666                            data: {key: key, value: content.data[key]}
667                          }, content.data[key]));
668
669                          if(functional && imageType == 'BMC'){
670                            bmcActiveVersion = content.data[key].Version;
671                          }
672
673                          if(functional && imageType == 'Host'){
674                            hostActiveVersion = content.data[key].Version;
675                          }
676                        }
677                      }
678
679                      deferred.resolve({
680                          data: data,
681                          bmcActiveVersion: bmcActiveVersion,
682                          hostActiveVersion: hostActiveVersion
683                      });
684                }, function(error){
685                  console.log(error);
686                  deferred.reject(error);
687                });
688
689                return deferred.promise;
690              },
691              changePriority: function(imageId, priority){
692                var deferred = $q.defer();
693                $http({
694                  method: 'PUT',
695                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/Priority",
696                  headers: {
697                      'Accept': 'application/json',
698                      'Content-Type': 'application/json'
699                  },
700                  withCredentials: true,
701                  data: JSON.stringify({"data": priority})
702                }).then(function(response){
703                      var json = JSON.stringify(response.data);
704                      var content = JSON.parse(json);
705                      deferred.resolve(content);
706                }, function(error){
707                  console.log(error);
708                  deferred.reject(error);
709                });
710
711                return deferred.promise;
712              },
713              deleteImage: function(imageId){
714                var deferred = $q.defer();
715                $http({
716                  method: 'POST',
717                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/action/Delete",
718                  headers: {
719                      'Accept': 'application/json',
720                      'Content-Type': 'application/json'
721                  },
722                  withCredentials: true,
723                  data: JSON.stringify({"data": []})
724                }).then(function(response){
725                      var json = JSON.stringify(response.data);
726                      var content = JSON.parse(json);
727                      deferred.resolve(content);
728                }, function(error){
729                  console.log(error);
730                  deferred.reject(error);
731                });
732
733                return deferred.promise;
734              },
735              activateImage: function(imageId){
736                var deferred = $q.defer();
737                $http({
738                  method: 'PUT',
739                  url: DataService.getHost() + "/xyz/openbmc_project/software/" + imageId + "/attr/RequestedActivation",
740                  headers: {
741                      'Accept': 'application/json',
742                      'Content-Type': 'application/json'
743                  },
744                  withCredentials: true,
745                  data: JSON.stringify({"data": Constants.FIRMWARE.ACTIVATE_FIRMWARE})
746                }).then(function(response){
747                      var json = JSON.stringify(response.data);
748                      var content = JSON.parse(json);
749                      deferred.resolve(content);
750                }, function(error){
751                  console.log(error);
752                  deferred.reject(error);
753                });
754
755                return deferred.promise;
756              },
757              uploadImage: function(file){
758                var deferred = $q.defer();
759                $http({
760                  method: 'POST',
761                  timeout: 5 * 60 * 1000,
762                  url: DataService.getHost() + "/upload/image/",
763                  headers: {
764                    'Content-Type': 'application/octet-stream'
765                  },
766                  withCredentials: true,
767                  data: file
768                }).then(function(response){
769                      var json = JSON.stringify(response.data);
770                      var content = JSON.parse(json);
771                      deferred.resolve(content);
772                }, function(error){
773                  console.log(error);
774                  deferred.reject(error);
775                });
776
777                return deferred.promise;
778              },
779              downloadImage: function(host, filename){
780                var deferred = $q.defer();
781                $http({
782                  method: 'POST',
783                  url: DataService.getHost() + "/org/openbmc/control/flash/bmc/action/updateViaTftp",
784                  headers: {
785                      'Accept': 'application/json',
786                      'Content-Type': 'application/json'
787                  },
788                  withCredentials: true,
789                  data: JSON.stringify({"data": [host, filename]}),
790                  responseType: 'arraybuffer'
791                }).then(function(response, status, headers){
792                  deferred.resolve({
793                    data: response,
794                    status: status,
795                    headers: headers
796                  });
797                }, function(error){
798                  console.log(error);
799                  deferred.reject(error);
800                });
801
802                return deferred.promise;
803              },
804              getBMCEthernetInfo: function(){
805                var deferred = $q.defer();
806                $http({
807                  method: 'GET',
808                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc/ethernet",
809                  headers: {
810                      'Accept': 'application/json',
811                      'Content-Type': 'application/json'
812                  },
813                  withCredentials: true
814                }).then(function(response){
815                    var json = JSON.stringify(response.data);
816                    var content = JSON.parse(json);
817                    deferred.resolve(content.data);
818                }, function(error){
819                  console.log(error);
820                  deferred.reject(error);
821                });
822
823                return deferred.promise;
824              },
825              getBMCInfo: function(callback){
826                var deferred = $q.defer();
827                $http({
828                  method: 'GET',
829                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/system/chassis/motherboard/boxelder/bmc",
830                  headers: {
831                      'Accept': 'application/json',
832                      'Content-Type': 'application/json'
833                  },
834                  withCredentials: true
835                }).then(function(response){
836                    var json = JSON.stringify(response.data);
837                    var content = JSON.parse(json);
838                    deferred.resolve(content.data);
839                }, function(error){
840                  console.log(error);
841                  deferred.reject(error);
842                });
843                return deferred.promise;
844              },
845              getHardwares: function(callback){
846                $http({
847                  method: 'GET',
848                  url: DataService.getHost() + "/xyz/openbmc_project/inventory/enumerate",
849                  headers: {
850                      'Accept': 'application/json',
851                      'Content-Type': 'application/json'
852                  },
853                  withCredentials: true
854                }).then(function(response){
855                      var json = JSON.stringify(response.data);
856                      var content = JSON.parse(json);
857                      var hardwareData = [];
858                      var keyIndexMap = {};
859                      var title = "";
860                      var data = [];
861                      var searchText = "";
862                      var componentIndex = -1;
863                      var tempParts = [];
864
865
866                      function isSubComponent(key){
867
868                        for(var i = 0; i < Constants.HARDWARE.parent_components.length; i++){
869                          if(key.split(Constants.HARDWARE.parent_components[i]).length == 2) return true;
870                        }
871
872                        return false;
873                      }
874
875                      function titlelize(title){
876                        title = title.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
877                        for(var i = 0; i < Constants.HARDWARE.uppercase_titles.length; i++){
878                          if(title.toLowerCase().indexOf((Constants.HARDWARE.uppercase_titles[i] + " ")) > -1){
879                            return title.toUpperCase();
880                          }
881                        }
882
883                        return title;
884                      }
885
886                      function camelcaseToLabel(obj){
887                        var transformed = [], label = "", value = "";
888                        for(var key in obj){
889                          label = key.replace(/([A-Z0-9]+)/g, " $1").replace(/^\s+/, "");
890                          if(obj[key] !== ""){
891                            value = obj[key];
892                            if(value == 1 || value == 0){
893                              value = (value == 1) ? 'Yes' : 'No';
894                            }
895                            transformed.push({key:label, value: value});
896                          }
897                        }
898
899                        return transformed;
900                      }
901
902                      function getSearchText(data){
903                        var searchText = "";
904                        for(var i = 0; i < data.length; i++){
905                          searchText += " " + data[i].key + " " + data[i].value;
906                        }
907
908                        return searchText;
909                      }
910
911                      for(var key in content.data){
912                        if(content.data.hasOwnProperty(key) &&
913                           key.indexOf(Constants.HARDWARE.component_key_filter) == 0){
914
915                          data = camelcaseToLabel(content.data[key]);
916                          searchText = getSearchText(data);
917                          title = key.split("/").pop();
918
919                          title = titlelize(title);
920
921                          if(!isSubComponent(key)){
922                              hardwareData.push(Object.assign({
923                                path: key,
924                                title: title,
925                                selected: false,
926                                expanded: false,
927                                search_text: title.toLowerCase() + " " + searchText.toLowerCase(),
928                                sub_components: [],
929                                original_data: {key: key, value: content.data[key]}
930                              }, {items: data}));
931
932                              keyIndexMap[key] = hardwareData.length - 1;
933                          }else{
934                            var tempParts = key.split("/");
935                            tempParts.pop();
936                            tempParts = tempParts.join("/");
937                            componentIndex = keyIndexMap[tempParts];
938                            data = content.data[key];
939                            data.title = title;
940                            hardwareData[componentIndex].sub_components.push(data);
941                            hardwareData[componentIndex].search_text += " " + title.toLowerCase();
942                          }
943                      }
944                    }
945
946                    if(callback){
947                       callback(hardwareData, content.data);
948                    }else{
949                       return { data: hardwareData, original_data: content.data};
950                    }
951                });
952              },
953              deleteLogs: function(logs) {
954                  var defer = $q.defer();
955                  var promises = [];
956
957                  function finished(){
958                      defer.resolve();
959                  }
960
961                  logs.forEach(function(item){
962                    promises.push($http({
963                                      method: 'POST',
964                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/action/Delete",
965                                      headers: {
966                                          'Accept': 'application/json',
967                                          'Content-Type': 'application/json'
968                                      },
969                                      withCredentials: true,
970                                      data: JSON.stringify({"data": []})
971                                 }));
972                  });
973
974                  $q.all(promises).then(finished);
975
976                  return defer.promise;
977              },
978              resolveLogs: function(logs) {
979                  var defer = $q.defer();
980                  var promises = [];
981
982                  function finished(){
983                      defer.resolve();
984                  }
985
986                  logs.forEach(function(item){
987                    promises.push($http({
988                                      method: 'PUT',
989                                      url: DataService.getHost() + "/xyz/openbmc_project/logging/entry/"+item.Id+"/attr/Resolved",
990                                      headers: {
991                                          'Accept': 'application/json',
992                                          'Content-Type': 'application/json'
993                                      },
994                                      withCredentials: true,
995                                      data: JSON.stringify({"data": "1"})
996                                 }));
997                  });
998
999                  $q.all(promises).then(finished);
1000
1001                  return defer.promise;
1002              },
1003          };
1004          return SERVICE;
1005        }]);
1006
1007        })(window.angular);
1008