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', function($http, Constants){
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              getChassisState: function(callback){
25                $http({
26                  method: 'GET',
27                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/chassis0",
28                  headers: {
29                      'Accept': 'application/json',
30                      'Content-Type': 'application/json'
31                  },
32                  withCredentials: true
33                }).success(function(response){
34                      var json = JSON.stringify(response);
35                      var content = JSON.parse(json);
36                      callback(content.data.CurrentPowerState);
37                }).error(function(error){
38                  console.log(error);
39                });
40              },
41              getHostState: function(callback){
42                $http({
43                  method: 'GET',
44                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0",
45                  headers: {
46                      'Accept': 'application/json',
47                      'Content-Type': 'application/json'
48                  },
49                  withCredentials: true
50                }).success(function(response){
51                      var json = JSON.stringify(response);
52                      var content = JSON.parse(json);
53                      callback(content.data.CurrentHostState);
54                }).error(function(error){
55                  console.log(error);
56                });
57              },
58              getLEDState: function(callback){
59                $http({
60                  method: 'GET',
61                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/led/groups/enclosure_identify",
62                  headers: {
63                      'Accept': 'application/json',
64                      'Content-Type': 'application/json'
65                  },
66                  withCredentials: true
67                }).success(function(response){
68                      var json = JSON.stringify(response);
69                      var content = JSON.parse(json);
70                      callback(content.data.Asserted);
71                }).error(function(error){
72                  console.log(error);
73                });
74              },
75              login: function(username, password, callback){
76                $http({
77                  method: 'POST',
78                  url: SERVICE.API_CREDENTIALS.host + "/login",
79                  headers: {
80                      'Accept': 'application/json',
81                      'Content-Type': 'application/json'
82                  },
83                  withCredentials: true,
84                  data: JSON.stringify({"data": [username, password]})
85                }).success(function(response){
86                  if(callback){
87                      callback(response);
88                  }
89                }).error(function(error){
90                  if(callback){
91                      if(error && error.status && error.status == 'error'){
92                        callback(error);
93                      }else{
94                        callback(error, true);
95                      }
96                  }
97                  console.log(error);
98                });
99              },
100              logout: function(callback){
101                $http({
102                  method: 'POST',
103                  url: SERVICE.API_CREDENTIALS.host + "/logout",
104                  headers: {
105                      'Accept': 'application/json',
106                      'Content-Type': 'application/json'
107                  },
108                  withCredentials: true,
109                  data: JSON.stringify({"data": []})
110                }).success(function(response){
111                  if(callback){
112                      callback(response);
113                  }
114                }).error(function(error){
115                  if(callback){
116                      callback(null, error);
117                  }
118                  console.log(error);
119                });
120              },
121              chassisPowerOn: function(callback){
122                $http({
123                  method: 'POST',
124                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0",
125                  headers: {
126                      'Accept': 'application/json',
127                      'Content-Type': 'application/json'
128                  },
129                  withCredentials: true,
130                  data: JSON.stringify({"data": []})
131                }).success(function(response){
132                      var json = JSON.stringify(response);
133                      var content = JSON.parse(json);
134                      if(callback){
135                          return callback(content.data.CurrentPowerState);
136                      }
137                }).error(function(error){
138                  if(callback){
139                      callback(error);
140                  }else{
141                      console.log(error);
142                  }
143                });
144              },
145              chassisPowerOff: function(callback){
146                $http({
147                  method: 'POST',
148                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0",
149                  headers: {
150                      'Accept': 'application/json',
151                      'Content-Type': 'application/json'
152                  },
153                  withCredentials: true,
154                  data: JSON.stringify({"data": []})
155                }).success(function(response){
156                      var json = JSON.stringify(response);
157                      var content = JSON.parse(json);
158                      if(callback){
159                          return callback(content.data.CurrentPowerState);
160                      }
161                }).error(function(error){
162                  if(callback){
163                      callback(error);
164                  }else{
165                      console.log(error);
166                  }
167                });
168              },
169              setLEDState: function(state, callback){
170                $http({
171                  method: 'PUT',
172                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/led/groups/enclosure_identify/attr/Asserted",
173                  headers: {
174                      'Accept': 'application/json',
175                      'Content-Type': 'application/json'
176                  },
177                  withCredentials: true,
178                  data: JSON.stringify({"data": state})
179                }).success(function(response){
180                      var json = JSON.stringify(response);
181                      var content = JSON.parse(json);
182                      if(callback){
183                          return callback(content.status);
184                      }
185                }).error(function(error){
186                  if(callback){
187                      callback(error);
188                  }else{
189                      console.log(error);
190                  }
191                });
192              },
193              bmcReboot: function(callback){
194                $http({
195                  method: 'PUT',
196                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/bmc0/attr/RequestedBmcTransition",
197                  headers: {
198                      'Accept': 'application/json',
199                      'Content-Type': 'application/json'
200                  },
201                  withCredentials: true,
202                  data: JSON.stringify({"data": "xyz.openbmc_project.State.BMC.Transition.Reboot"})
203                }).success(function(response){
204                      var json = JSON.stringify(response);
205                      var content = JSON.parse(json);
206                      if(callback){
207                          return callback(content.status);
208                      }
209                }).error(function(error){
210                  if(callback){
211                      callback(error);
212                  }else{
213                      console.log(error);
214                  }
215                });
216              },
217              hostPowerOn: function(callback){
218                $http({
219                  method: 'PUT',
220                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0/attr/RequestedHostTransition",
221                  headers: {
222                      'Accept': 'application/json',
223                      'Content-Type': 'application/json'
224                  },
225                  withCredentials: true,
226                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Host.Transition.On"})
227                }).success(function(response){
228                      var json = JSON.stringify(response);
229                      var content = JSON.parse(json);
230                      if(callback){
231                          return callback(content.status);
232                      }
233                }).error(function(error){
234                  if(callback){
235                      callback(error);
236                  }else{
237                      console.log(error);
238                  }
239                });
240              },
241              hostPowerOff: function(callback){
242                $http({
243                  method: 'PUT',
244                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0/attr/RequestedHostTransition",
245                  headers: {
246                      'Accept': 'application/json',
247                      'Content-Type': 'application/json'
248                  },
249                  withCredentials: true,
250                  data: JSON.stringify({"data": "xyz.openbmc_project.State.Host.Transition.Off"})
251                }).success(function(response){
252                      var json = JSON.stringify(response);
253                      var content = JSON.parse(json);
254                      if(callback){
255                          return callback(content.status);
256                      }
257                }).error(function(error){
258                  if(callback){
259                      callback(error);
260                  }else{
261                      console.log(error);
262                  }
263                });
264              },
265              hostReboot: function(callback){
266                $http({
267                  method: 'POST',
268                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0",
269                  headers: {
270                      'Accept': 'application/json',
271                      'Content-Type': 'application/json'
272                  },
273                  withCredentials: true,
274                  data: JSON.stringify({"data": []}),
275                }).success(function(response){
276                      var json = JSON.stringify(response);
277                      var content = JSON.parse(json);
278                      if(callback){
279                          return callback(content);
280                      }
281                }).error(function(error){
282                  if(callback){
283                      callback(error);
284                  }else{
285                      console.log(error);
286                  }
287                });
288              },
289              hostShutdown: function(callback){
290                $http({
291                  method: 'POST',
292                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/state/host0",
293                  headers: {
294                      'Accept': 'application/json',
295                      'Content-Type': 'application/json'
296                  },
297                  withCredentials: true,
298                  data: JSON.stringify({"data": []})
299                }).success(function(response){
300                      var json = JSON.stringify(response);
301                      var content = JSON.parse(json);
302                      if(callback){
303                          return callback(content);
304                      }
305                }).error(function(error){
306                  if(callback){
307                      callback(error);
308                  }else{
309                      console.log(error);
310                  }
311                });
312              },
313              getLogs: function(callback){
314                $http({
315                  method: 'GET',
316                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/logging/enumerate",
317                  headers: {
318                      'Accept': 'application/json',
319                      'Content-Type': 'application/json'
320                  },
321                  withCredentials: true
322                }).success(function(response){
323                      var json = JSON.stringify(response);
324                      var content = JSON.parse(json);
325                      var dataClone = JSON.parse(JSON.stringify(content.data));
326                      var data = [];
327                      var severityCode = '';
328                      var priority = '';
329                      var relatedItems = [];
330
331                      for(var key in content.data){
332                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Id')){
333                          var severityFlags = {low: false, medium: false, high: false};
334                          severityCode = content.data[key].Severity.split(".").pop();
335                          priority = Constants.SEVERITY_TO_PRIORITY_MAP[severityCode];
336                          severityFlags[priority.toLowerCase()] = true;
337                          relatedItems = [];
338                          content.data[key].associations.forEach(function(item){
339                            relatedItems.push(item[2]);
340                          });
341
342                          data.push(Object.assign({
343                            path: key,
344                            copied: false,
345                            priority: priority,
346                            severity_code: severityCode,
347                            severity_flags: severityFlags,
348                            additional_data: content.data[key].AdditionalData.join("\n"),
349                            selected: false,
350                            search_text: ("#" + content.data[key].Id + " " + severityCode + " " + content.data[key].Severity + " " + content.data[key].AdditionalData.join(" ")).toLowerCase(),
351                            meta: false,
352                            confirm: false,
353                            related_items: relatedItems,
354                            data: {key: key, value: content.data[key]}
355                          }, content.data[key]));
356                        }
357                      }
358                      callback(data, dataClone);
359                }).error(function(error){
360                  console.log(error);
361                });
362              },
363              getAllSensorStatus: function(callback){
364                /**
365                GET   https://9.3.185.156/xyz/openbmc_project/sensors/enumerate
366                */
367                $http({
368                  method: 'GET',
369                  url: "/assets/mocks/sensors.json",
370                  headers: {
371                      'Accept': 'application/json',
372                      'Content-Type': 'application/json'
373                  },
374                  withCredentials: true
375                }).success(function(response){
376                      var json = JSON.stringify(response);
377                      var content = JSON.parse(json);
378                      var dataClone = JSON.parse(JSON.stringify(content.data));
379                      var sensorData = [];
380                      var allSensorSeveries = [];
381                      var allSensorRows = [];
382                      var total = 0;
383                      var status = 'normal';
384                      var data = {
385                                   total: 0,
386                                   status: '',
387                                   sensors: [{
388                                      title: 'All Sensors',
389                                      type: 'all',
390                                      status: '',
391                                      severity_flags: {},
392                                      search_text: '',
393                                      display_headers: ['Sensor (Unit)', 'Reading', 'State'],
394                                      data: []
395                                   }]
396                                 };
397
398                      function getSensorStatus(reading){
399                        var severityFlags = {critical: false, warning: false, normal: false}, severityText = '';
400                        if(reading.Value >= reading.CriticalLow && reading.Value <= reading.CriticalHigh){
401                          severityFlags.critical = true;
402                          severityText = 'critical';
403                        }
404                        else if(reading.Value >= reading.WarningLow && reading.Value <= reading.WarningHigh){
405                          severityFlags.warning = true;
406                          severityText = 'warning';
407                        }else{
408                          severityFlags.normal = true;
409                          severityText = 'normal';
410                        }
411                        return { flags: severityFlags, severityText: severityText};
412                      }
413
414                      for(var key in content.data){
415                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Unit')){
416                          sensorData.push(Object.assign({
417                            path: key,
418                            selected: false,
419                            confirm: false,
420                            copied: false,
421                            original_data: {key: key, value: content.data[key]}
422                          }, content.data[key]));
423                        }
424                      }
425
426                      Constants.SENSOR_DATA_TEMPLATE.sensors.forEach(function(sensor){
427                          var rowData = [];
428                          var severities = [];
429                          var thisSensorData = sensorData.filter(function(el){
430                            return el.path.indexOf('sensors/'+sensor.key_search) > -1;
431                          });
432
433                          for(var i = 0; i < thisSensorData.length; i++){
434
435                             var severity = getSensorStatus(thisSensorData[i]);
436                             severities.push(severity.severityText);
437                             rowData.push(Object.assign({
438                                title: sensor.sensor_row.title + (i+1),
439                                status: severity.severityText,
440                                severity_flags: severity.flags,
441                                reading: thisSensorData[i].Value + sensor.sensor_row.reading,
442                                search_text: (sensor.sensor_row.title + (i+1) + " " + severity.severityText + " " + thisSensorData[i].Value + sensor.sensor_row.reading).toLowerCase(),
443                                indicator: (severity.flags.critical) ? '90%' : ((severity.flags.warning) ? '15%' : '50%')
444                             }, thisSensorData[i]));
445                          }
446
447                          status = (severities.indexOf('critical') > -1) ? 'critical' : ((severities.indexOf('warning') > -1) ? 'warning' : 'normal');
448                          total += rowData.length;
449                          allSensorSeveries.push(status);
450                          var sevFlags =  {critical: false, warning: false, normal: false};
451                          sevFlags[status] = true;
452                          data.sensors.push({
453                            title: sensor.title,
454                            type: sensor.type,
455                            status: status,
456                            severity_flags: sevFlags,
457                            search_text: (sensor.title + " " + status).toLowerCase(),
458                            display_headers: sensor.display_headers,
459                            data: rowData
460                          });
461                          Array.prototype.push.apply(allSensorRows, rowData);
462                      });
463
464                      data.status = (allSensorSeveries.indexOf('critical') > -1) ? 'critical' : ((allSensorSeveries.indexOf('warning') > -1) ? 'warning' : 'normal');
465                      data.total = total;
466                      if(allSensorRows.length){
467                        data.sensors[0].status = data.status;
468                        data.sensors[0].data = allSensorRows;
469                        data.sensors[0].search_text = (data.sensors[0].title + " " + data.sensors[0].status).toLowerCase();
470                        var flags = {critical: false, warning: false, normal: false};
471                        flags[data.status] = true;
472                        data.sensors[0].severity_flags = flags;
473                      }
474                      callback(data, dataClone);
475                }).error(function(error){
476                  console.log(error);
477                });
478              },
479              getFirmwares: function(callback){
480                $http({
481                  method: 'GET',
482                  //url: SERVICE.API_CREDENTIALS.mock_host + "/software",
483                  url: SERVICE.API_CREDENTIALS.host + "/xyz/openbmc_project/software/enumerate",
484                  headers: {
485                      'Accept': 'application/json',
486                      'Content-Type': 'application/json'
487                  },
488                  withCredentials: true
489                }).success(function(response){
490                      var json = JSON.stringify(response);
491                      var content = JSON.parse(json);
492                      var data = [];
493                      var active = false;
494                      var isExtended = false;
495                      var bmcActiveVersion = "";
496                      var hostActiveVersion = "";
497                      var imageType = "";
498                      var extendedVersions = [];
499
500                      function getFormatedExtendedVersions(extendedVersion){
501                        var versions = [];
502                        extendedVersion = extendedVersion.split(",");
503
504                        extendedVersion.forEach(function(item){
505                          var parts = item.split("-");
506                          var numberIndex = 0;
507                          for(var i = 0; i < parts.length; i++){
508                            if(/[0-9]/.test(parts[i])){
509                              numberIndex = i;
510                              break;
511                            }
512                          }
513                          var titlePart = parts.splice(0, numberIndex);
514                          titlePart = titlePart.join("");
515                          titlePart = titlePart[0].toUpperCase() + titlePart.substr(1, titlePart.length);
516                          var versionPart = parts.join("-");
517                          versions.push({
518                            title: titlePart,
519                            version: versionPart
520                          });
521                        });
522
523                        return versions;
524                      }
525
526                      for(var key in content.data){
527                        if(content.data.hasOwnProperty(key) && content.data[key].hasOwnProperty('Version')){
528                          active = (/\.Active$/).test(content.data[key].Activation);
529                          imageType = content.data[key].Purpose.split(".").pop();
530                          isExtended = content.data[key].hasOwnProperty('ExtendedVersion') && content.data[key].ExtendedVersion != "";
531                          if(isExtended){
532                            extendedVersions = getFormatedExtendedVersions(content.data[key].ExtendedVersion);
533                          }
534                          data.push(Object.assign({
535                            path: key,
536                            active: active,
537                            imageId: key.split("/").pop(),
538                            imageType: imageType,
539                            isExtended: isExtended,
540                            extended: {
541                              show: false,
542                              versions: extendedVersions
543                            },
544                            data: {key: key, value: content.data[key]}
545                          }, content.data[key]));
546
547                          if(active && imageType == 'BMC'){
548                            bmcActiveVersion = content.data[key].Version;
549                          }
550
551                          if(active && imageType == 'Host'){
552                            hostActiveVersion = content.data[key].Version;
553                          }
554                        }
555                      }
556                      callback(data, bmcActiveVersion, hostActiveVersion);
557                }).error(function(error){
558                  console.log(error);
559                });
560              },
561              uploadImage: function(file, callback){
562                $http({
563                  method: 'PUT',
564                  timeout: 5 * 60 * 1000,
565                  //url: 'http://localhost:3002/upload',
566                  url: SERVICE.API_CREDENTIALS.host + "/upload/image/",
567                  headers: {
568                      'Accept': 'application/octet-stream',
569                      'Content-Type': 'application/octet-stream'
570                  },
571                  withCredentials: true,
572                  data: file
573                }).success(function(response){
574                      var json = JSON.stringify(response);
575                      var content = JSON.parse(json);
576                      if(callback){
577                          return callback(content);
578                      }
579                }).error(function(error){
580                  if(callback){
581                      callback(error);
582                  }else{
583                      console.log(error);
584                  }
585                });
586              },
587          };
588          return SERVICE;
589        }]);
590
591        })(window.angular);
592