lavva.exalushome 2.0.112 → 2.0.113

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/build/exalushome-library-bundle.js +1 -1
  2. package/build/exalushome-library-bundle.js.map +1 -1
  3. package/build/js/Api.js +112 -112
  4. package/build/js/Api.js.map +1 -1
  5. package/build/js/AsyncLock.js +15 -15
  6. package/build/js/AsyncSemaphore.js +44 -44
  7. package/build/js/AsyncSemaphore.js.map +1 -1
  8. package/build/js/CancelationTokenSource.js +18 -18
  9. package/build/js/DataFrame.js +86 -86
  10. package/build/js/DependencyContainer.js +87 -87
  11. package/build/js/DependencyContainer.js.map +1 -1
  12. package/build/js/Event.js +24 -24
  13. package/build/js/Event.js.map +1 -1
  14. package/build/js/Guid.js +8 -8
  15. package/build/js/Helpers.js +132 -132
  16. package/build/js/Helpers.js.map +1 -1
  17. package/build/js/IDIService.js +1 -1
  18. package/build/js/INetworkService.js +41 -41
  19. package/build/js/Services/AppStateService.js +217 -217
  20. package/build/js/Services/AppStateService.js.map +1 -1
  21. package/build/js/Services/Chat/ChatImplementations/ControllerChat/ControllerChat.js +224 -224
  22. package/build/js/Services/Chat/ChatImplementations/ControllerChat/ControllerChat.js.map +1 -1
  23. package/build/js/Services/Chat/ChatImplementations/ControllerChat/IControllerChat.js +33 -33
  24. package/build/js/Services/Chat/ChatImplementations/FamillyChat/FamillyChat.js +147 -147
  25. package/build/js/Services/Chat/ChatImplementations/FamillyChat/FamillyChat.js.map +1 -1
  26. package/build/js/Services/Chat/ChatImplementations/FamillyChat/IFamillyChat.js +1 -1
  27. package/build/js/Services/Chat/ChatImplementations/GptChat/GptChat.js +184 -184
  28. package/build/js/Services/Chat/ChatImplementations/GptChat/GptChat.js.map +1 -1
  29. package/build/js/Services/Chat/ChatImplementations/GptChat/IGptChat.js +26 -26
  30. package/build/js/Services/Chat/ChatService.js +43 -43
  31. package/build/js/Services/Chat/ChatService.js.map +1 -1
  32. package/build/js/Services/Chat/IChatService.js +6 -6
  33. package/build/js/Services/Controller/ConnectedAppsService.js +117 -117
  34. package/build/js/Services/Controller/ConnectedAppsService.js.map +1 -1
  35. package/build/js/Services/Controller/ControllerConfigurationService.js +319 -319
  36. package/build/js/Services/Controller/ControllerConfigurationService.js.map +1 -1
  37. package/build/js/Services/Controller/ControllerExtensionsService.js +148 -148
  38. package/build/js/Services/Controller/ControllerExtensionsService.js.map +1 -1
  39. package/build/js/Services/Controller/FindControllerService.js +155 -155
  40. package/build/js/Services/Controller/FindControllerService.js.map +1 -1
  41. package/build/js/Services/Controller/GeolocationService.js +111 -111
  42. package/build/js/Services/Controller/GeolocationService.js.map +1 -1
  43. package/build/js/Services/Controller/IConnectedAppsService.js +24 -24
  44. package/build/js/Services/Controller/IControllerConfigurationService.js +1 -1
  45. package/build/js/Services/Controller/IControllerExtensionsService.js +1 -1
  46. package/build/js/Services/Controller/IGeolocationService.js +20 -20
  47. package/build/js/Services/DataMigrationService.js +169 -169
  48. package/build/js/Services/DataMigrationService.js.map +1 -1
  49. package/build/js/Services/Devices/ChannelsGroupsService.js +696 -696
  50. package/build/js/Services/Devices/ChannelsGroupsService.js.map +1 -1
  51. package/build/js/Services/Devices/Device.js +248 -248
  52. package/build/js/Services/Devices/Device.js.map +1 -1
  53. package/build/js/Services/Devices/DeviceChannel.js +304 -304
  54. package/build/js/Services/Devices/DeviceChannel.js.map +1 -1
  55. package/build/js/Services/Devices/DevicesService.js +1184 -1184
  56. package/build/js/Services/Devices/DevicesService.js.map +1 -1
  57. package/build/js/Services/Devices/IChannelsGroupsService.js +109 -109
  58. package/build/js/Services/Devices/IChannelsGroupsService.js.map +1 -1
  59. package/build/js/Services/Devices/IDevice.js +197 -197
  60. package/build/js/Services/Devices/IDeviceChannel.js +48 -48
  61. package/build/js/Services/Devices/IDeviceConfigService.js +1 -1
  62. package/build/js/Services/Devices/IDeviceState.d.ts +7 -1
  63. package/build/js/Services/Devices/IDeviceState.js +970 -963
  64. package/build/js/Services/Devices/IDeviceState.js.map +1 -1
  65. package/build/js/Services/Devices/IDeviceTask.js +36 -36
  66. package/build/js/Services/Devices/IDevicesService.js +9 -9
  67. package/build/js/Services/Devices/IManuallyPairedDevicesProtocolService.js +1 -1
  68. package/build/js/Services/Devices/IManuallyPairedDevicesService.js +1 -1
  69. package/build/js/Services/Devices/ManuallyPairedDevicesService.js +68 -68
  70. package/build/js/Services/Devices/ManuallyPairedDevicesService.js.map +1 -1
  71. package/build/js/Services/Devices/TaskExecutionResult.js +9 -9
  72. package/build/js/Services/Devices/Tasks/DeviceTask.js +42 -42
  73. package/build/js/Services/Devices/Tasks/Tasks.js +216 -216
  74. package/build/js/Services/Devices/dist/DevicesService.d.ts +17 -17
  75. package/build/js/Services/ExalusConnectionService.js +498 -498
  76. package/build/js/Services/ExalusConnectionService.js.map +1 -1
  77. package/build/js/Services/FieldChangeResult.js +51 -51
  78. package/build/js/Services/IAppStateService.js +66 -66
  79. package/build/js/Services/IExalusConnectionService.js +31 -31
  80. package/build/js/Services/ILocalStorageService.js +1 -1
  81. package/build/js/Services/IRemoteStorageService.js +8 -8
  82. package/build/js/Services/LocalNetworkExalusConnectionService.js +289 -289
  83. package/build/js/Services/LocalNetworkExalusConnectionService.js.map +1 -1
  84. package/build/js/Services/LocalStorageService.js +38 -38
  85. package/build/js/Services/LocalStorageService.js.map +1 -1
  86. package/build/js/Services/Logging/ILoggerService.js +8 -8
  87. package/build/js/Services/Logging/LoggerService.js +132 -132
  88. package/build/js/Services/Logging/LoggerService.js.map +1 -1
  89. package/build/js/Services/PictureInPicture.js +28 -28
  90. package/build/js/Services/PictureInPicture.js.map +1 -1
  91. package/build/js/Services/Pictures/IPicture.js +6 -6
  92. package/build/js/Services/Pictures/IPicturesService.js +1 -1
  93. package/build/js/Services/Pictures/Picture.js +50 -50
  94. package/build/js/Services/Pictures/PicturesService.js +441 -441
  95. package/build/js/Services/Pictures/PicturesService.js.map +1 -1
  96. package/build/js/Services/RemoteStorageService.js +122 -122
  97. package/build/js/Services/RemoteStorageService.js.map +1 -1
  98. package/build/js/Services/Scenes/IScenesService.js +7 -7
  99. package/build/js/Services/Scenes/LeftArgumentTypes.js +166 -166
  100. package/build/js/Services/Scenes/LeftArgumentTypes.js.map +1 -1
  101. package/build/js/Services/Scenes/SceneTaskTypes.js +32 -32
  102. package/build/js/Services/Scenes/Scenes.js +134 -134
  103. package/build/js/Services/Scenes/ScenesBuilder.js +1097 -1097
  104. package/build/js/Services/Scenes/ScenesBuilder.js.map +1 -1
  105. package/build/js/Services/Scenes/ScenesService.js +1131 -1131
  106. package/build/js/Services/Scenes/ScenesService.js.map +1 -1
  107. package/build/js/Services/Scenes/dist/ScenesService.d.ts +5 -5
  108. package/build/js/Services/Session/ISessionService.js +8 -8
  109. package/build/js/Services/Session/SessionService.js +222 -222
  110. package/build/js/Services/Session/SessionService.js.map +1 -1
  111. package/build/js/Services/StatesHistory/IStatesHistoryService.js +12 -12
  112. package/build/js/Services/StatesHistory/StatesHistory.js +75 -75
  113. package/build/js/Services/StatesHistory/StatesHistoryService.js +235 -235
  114. package/build/js/Services/StatesHistory/StatesHistoryService.js.map +1 -1
  115. package/build/js/Services/SupportedDevices/ISupportedDevicesService.js +115 -115
  116. package/build/js/Services/SupportedDevices/SupportedDevicesService.js +26 -26
  117. package/build/js/Services/Updates/CustomUpdateActions/ICustomUpdateActions.js +1 -1
  118. package/build/js/Services/Updates/IUpdateInfo.js +62 -62
  119. package/build/js/Services/Updates/IUpdatesProvider.js +48 -48
  120. package/build/js/Services/Updates/IUpdatesService.js +139 -139
  121. package/build/js/Services/Updates/UpdateProviderServices/IControllerModulesUpdatesProviderService.js +1 -1
  122. package/build/js/Services/Updates/UpdateProviderServices/IDeviceUpdateProviderService.js +1 -1
  123. package/build/js/Services/Updates/UpdateProviderServices/IUpdateProviderService.js +1 -1
  124. package/build/js/Services/Updates/UpdatesProvider.js +212 -212
  125. package/build/js/Services/Updates/UpdatesProvider.js.map +1 -1
  126. package/build/js/Services/Updates/UpdatesService.js +1487 -1487
  127. package/build/js/Services/Updates/UpdatesService.js.map +1 -1
  128. package/build/js/Services/Updates/dist/UpdatesService.d.ts +9 -9
  129. package/build/js/Services/Users/IUser.js +21 -21
  130. package/build/js/Services/Users/IUsersService.js +1 -1
  131. package/build/js/Services/Users/User.js +104 -104
  132. package/build/js/Services/Users/UsersService.js +302 -302
  133. package/build/js/Services/Users/UsersService.js.map +1 -1
  134. package/build/js/Services/WebApi/IWebApiCacheService.js +1 -1
  135. package/build/js/Services/WebApi/WebApiCacheService.js +42 -42
  136. package/build/js/Services/WebApi/WebApiCacheService.js.map +1 -1
  137. package/build/js/TypedEvent.js +23 -23
  138. package/build/js/TypedEvent.js.map +1 -1
  139. package/build/js/dist/Api.d.ts +12 -12
  140. package/build/tsconfig.tsbuildinfo +1 -1
  141. package/package.json +1 -1
@@ -1,1488 +1,1488 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { Api } from "../../Api";
11
- import { DataFrame, Method, Status } from "../../DataFrame";
12
- import { ControllerExtensionsService } from "../Controller/ControllerExtensionsService";
13
- import { DevicesService } from "../Devices/DevicesService";
14
- import { ResponseResult } from "../FieldChangeResult";
15
- import { CannotGetRuntimeErrorCode, CannotGetRuntimeInfo, UpdatesProvider } from "./UpdatesProvider";
16
- import { ControllerUpdatesInfo, ControllerUpdateType, ControllerVersion, UpdateHistory } from "./IUpdateInfo";
17
- import { ProviderType, UpdateInfo, UpdateTypes, UpdatesProviderNotFound } from "./IUpdatesProvider";
18
- import { DownloadProgressInfo, DownloadTask, UpdateBranch, UpdateErrorCode, UpdateProgressInfo, UpdateState, UpdateStatus, UserInput } from './IUpdatesService';
19
- import { AppStateService } from "../AppStateService";
20
- import { LoggerService } from "../Logging/LoggerService";
21
- import { ExalusConnectionService } from "../ExalusConnectionService";
22
- import { Helpers, ParseObjToMap } from "../../Helpers";
23
- export class UpdatesService {
24
- constructor() {
25
- this._controllerUpdates = [];
26
- this._updateRequestTimeout = 120000;
27
- this._oldUpdateVersion = 5.56;
28
- this._updateOfflineStageTime = 8.5;
29
- this._updateProviders = Api.Get(UpdatesProvider.ServiceName);
30
- this._logger = Api.Get(LoggerService.ServiceName);
31
- this._connection = Api.Get(ExalusConnectionService.ServiceName);
32
- this._appStateService = Api.Get(AppStateService.ServiceName);
33
- this._extensionService = Api.Get(ControllerExtensionsService.ServiceName);
34
- }
35
- GetAutomaticControllerUpdateDownloadStatusAsync() {
36
- return __awaiter(this, void 0, void 0, function* () {
37
- const ver = (yield this.getRuntimeInfoAsync());
38
- if (ver instanceof ResponseResult) {
39
- return ver;
40
- }
41
- if (parseFloat(ver.SoftwareVersion) <= this._oldUpdateVersion)
42
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot get update branch, feature unsupported in current version. Current version: ${ver}`);
43
- let result = yield this._connection.SendAndWaitForResponseAsync(new GetAutomaticUpdatesStatusRequest(), 10000, false);
44
- if (result.Status == Status.OK && result.Data)
45
- return true;
46
- else
47
- return false;
48
- });
49
- }
50
- GetServiceName() {
51
- return UpdatesService.ServiceName;
52
- }
53
- CheckDeviceVersionAsync(dev) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- var _a;
56
- let device;
57
- if (typeof dev == 'string') {
58
- const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
59
- if (result != null)
60
- device = result;
61
- else
62
- return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
63
- }
64
- else {
65
- device = dev;
66
- }
67
- if (device.ProtocolGuid == null)
68
- return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
69
- const softwareInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetSoftwareVersionAsync(device));
70
- if (softwareInfo.Type != null)
71
- return softwareInfo;
72
- return softwareInfo;
73
- });
74
- }
75
- CheckDeviceUpdateAsync(dev) {
76
- return __awaiter(this, void 0, void 0, function* () {
77
- var _a;
78
- let device;
79
- if (typeof dev == 'string') {
80
- const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
81
- if (result != null)
82
- device = result;
83
- else
84
- return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
85
- }
86
- else {
87
- device = dev;
88
- }
89
- if (device.ProtocolGuid == null)
90
- return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
91
- const updateInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetAvailableUpdateAsync(device));
92
- if (updateInfo.Type != null)
93
- return updateInfo;
94
- const result = new DeviceUpdate();
95
- result.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
96
- result.NewResourceVersion = updateInfo.Update.Version;
97
- result.UpdatedResourceName = updateInfo.UpdatedResourceName;
98
- result.UpdateResourceGuid = updateInfo.Update.ResourceGuid;
99
- result.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
100
- let protocol = "n/a";
101
- try {
102
- protocol = (yield this._extensionService.GetProtocolInfoAsync(device.ProtocolGuid)).first().Name;
103
- }
104
- catch (error) {
105
- this._logger.Warning(`Cannot get protocol name! error: ${error}`);
106
- }
107
- result.Protocol = protocol;
108
- result.ProtocolGuid = device.ProtocolGuid;
109
- if ((yield Api.Get(DevicesService.ServiceName).GetDevicesAsync()).any(dev => dev.ModelGuid == "952ddc14-76c4-4f47-b0bc-5d106c1f9b02"))
110
- result.IsUpdateSafe = false;
111
- return result;
112
- });
113
- }
114
- InstallDeviceUpdateAsync(dev_1, updateProgress_1, updateAction_1) {
115
- return __awaiter(this, arguments, void 0, function* (dev, updateProgress, updateAction, force = false) {
116
- var _a;
117
- let device;
118
- if (typeof dev == 'string') {
119
- const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
120
- if (result != null)
121
- device = result;
122
- else
123
- return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
124
- }
125
- else {
126
- device = dev;
127
- }
128
- if (device.ProtocolGuid == null)
129
- return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
130
- const updateInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetAvailableUpdateAsync(device));
131
- if (updateInfo.Type != null)
132
- return updateInfo;
133
- this._appStateService.DisallowHibernation();
134
- const updateInstallResult = yield (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first().InstallUpdateAsync(updateInfo, updateProgress, updateAction, force);
135
- if (updateInstallResult.Type != null) {
136
- this._appStateService.AllowHibernation();
137
- return updateInstallResult;
138
- }
139
- this._appStateService.AllowHibernation();
140
- return Status.OK;
141
- });
142
- }
143
- CheckControllerUpdatesAsync() {
144
- return __awaiter(this, void 0, void 0, function* () {
145
- this._controllerUpdates = [];
146
- let updateProviderServices = [];
147
- const updates = new ControllerUpdatesInfo();
148
- const runtimeInfo = yield this.getRuntimeInfoAsync();
149
- if (runtimeInfo instanceof ResponseResult) {
150
- const error = new ControllerUpdateNotAvailableInfo();
151
- error.UpdateType = ControllerUpdateType.SoftwareUpdate;
152
- error.ResponseResult = runtimeInfo;
153
- updates.UpdatesNotAvailable.push(error);
154
- return updates;
155
- }
156
- const swVer = parseFloat(runtimeInfo.SoftwareVersion);
157
- try {
158
- updateProviderServices = yield this._updateProviders.GetUpdatesProvidersAsync(ProviderType.Controller);
159
- }
160
- catch (error) {
161
- if (error instanceof UpdatesProviderNotFound) {
162
- this._logger.Warning(`Cannot get update providers for controller protocols! Avaliable only controller software updates!`);
163
- }
164
- else
165
- throw error;
166
- }
167
- //Radio updates
168
- for (let i = 0; i < updateProviderServices.length; i++) {
169
- const result = yield updateProviderServices[i].GetAvailableRadioUpdateAsync();
170
- if (result.Type != null) {
171
- const error = new ControllerUpdateNotAvailableInfo();
172
- error.ResponseResult = result;
173
- error.UpdateType = ControllerUpdateType.RadioUpdate;
174
- let protocol = "n/a";
175
- try {
176
- protocol = (yield this._extensionService.GetProtocolInfoAsync(updateProviderServices[i].ProtocolGuid)).first().Name;
177
- }
178
- catch (error) {
179
- this._logger.Warning(`Cannot get protocol name! error: ${error}`);
180
- }
181
- error.UpdatedResourceName = new Map([["pl-PL", protocol], ["en-US", protocol]]);
182
- error.CurrentResourceVersion = yield updateProviderServices[i].GetCurrentRadioVersionAsync();
183
- updates.UpdatesNotAvailable.push(error);
184
- }
185
- else {
186
- const updateInfo = result;
187
- const update = new ControllerUpdate();
188
- update.UpdatedResourceName = new Map([["pl-PL", updateInfo.UpdatedResourceName], ["en-US", updateInfo.UpdatedResourceName]]);
189
- update.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
190
- update.NewResourceVersion = updateInfo.Update.Version;
191
- update.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
192
- update.UpdateType = ControllerUpdateType.RadioUpdate;
193
- update.UpdateIdentifier = Helpers.GenerateUUID();
194
- update.UpdateIsDownloading = false;
195
- update.DownloadProgress = 100;
196
- update.UpdateCreationTime = null;
197
- updates.UpdatesAvailable.push(update);
198
- this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: updateProviderServices[i].GetUpdateProviderName(), UpdateType: ControllerUpdateType.RadioUpdate }));
199
- }
200
- }
201
- //Software updates (new way)
202
- if (swVer > this._oldUpdateVersion) {
203
- const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
204
- if (result == null || (result.Status != Status.OK && result.Status != Status.NoData))
205
- throw (new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`));
206
- if (result.Data != null) {
207
- const updateInfo = new UpdateInfo();
208
- updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
209
- updateInfo.UpdateDescription = ParseObjToMap(result.Data.Update.UpdateDescription);
210
- updateInfo.UpdatedResourceName = ParseObjToMap(result.Data.Update.UpdateName).get("en-US");
211
- const update = new ControllerUpdate();
212
- update.UpdatedResourceName = ParseObjToMap(result.Data.Update.UpdateName);
213
- update.UpdateDescription = ParseObjToMap(result.Data.Update.UpdateDescription);
214
- update.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
215
- update.NewResourceVersion = `${result.Data.Update.Version.BaseRuntime}.${result.Data.Update.Version.ContainerSoftwareVersion}`;
216
- update.UpdateType = ControllerUpdateType.SoftwareUpdate;
217
- update.UpdateIdentifier = result.Data.Update.Guid;
218
- update.UpdateIsDownloading = (result.Data.UpdateStep == UpdateStep.DownloadingInstaller
219
- || result.Data.UpdateStep == UpdateStep.DownloadingUpdate
220
- || result.Data.UpdateStep == UpdateStep.CheckingUpdate) ? true : false;
221
- update.DownloadProgress = result.Data.DownloadProgress;
222
- update.UpdateCreationTime = result.Data.Update.Creationtime;
223
- updates.UpdatesAvailable.push(update);
224
- this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
225
- }
226
- else {
227
- //If no updates - returns status NoData
228
- const result = yield this._connection.SendAndWaitForResponseAsync(new CheckUpdatesRequest(), 15000, false);
229
- if (result == null)
230
- throw new Error(`Cannot check updates! Response is empty.`);
231
- switch (result.Status) {
232
- case Status.NoData:
233
- const error = new ControllerUpdateNotAvailableInfo();
234
- error.UpdateType = ControllerUpdateType.SoftwareUpdate;
235
- error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
236
- error.ResponseResult = new ResponseResult(UpdateErrorCode.DeviceIsUpToDate, `Updates not found, controller is already up-to-date.`);
237
- updates.UpdatesNotAvailable.push(error);
238
- break;
239
- case Status.OK:
240
- if (result.Data == null)
241
- throw new Error(`Cannot check updates! Response data is empty.`);
242
- const updateInfo = new UpdateInfo();
243
- updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
244
- updateInfo.UpdateDescription = ParseObjToMap(result.Data.UpdateDescription);
245
- updateInfo.UpdatedResourceName = ParseObjToMap(result.Data.UpdateName).get("en-US");
246
- const update = new ControllerUpdate();
247
- update.UpdatedResourceName = ParseObjToMap(result.Data.UpdateName);
248
- update.UpdateDescription = ParseObjToMap(result.Data.UpdateDescription);
249
- update.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
250
- update.UpdateType = ControllerUpdateType.SoftwareUpdate;
251
- update.UpdateIdentifier = result.Data.Guid;
252
- update.NewResourceVersion = `${result.Data.Version.BaseRuntime}.${result.Data.Version.ContainerSoftwareVersion}`;
253
- update.UpdateIsDownloading = false;
254
- update.DownloadProgress = 0;
255
- update.UpdateCreationTime = result.Data.Creationtime;
256
- updates.UpdatesAvailable.push(update);
257
- this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
258
- break;
259
- default:
260
- throw new Error(`Cannot check updates! Response status is not OK. Status: ${result.Status}`);
261
- }
262
- }
263
- }
264
- //Software updates (old way)
265
- else {
266
- const url = `https://updates.tr7.pl/software/${runtimeInfo.UpdateChannel}/${runtimeInfo.RuntimeVersion}/${runtimeInfo.SoftwareVersion}/update.json`;
267
- try {
268
- const response = yield fetch(url);
269
- let updateData;
270
- let updateInfo = new UpdateInfo();
271
- const error = new ControllerUpdateNotAvailableInfo();
272
- error.UpdateType = ControllerUpdateType.SoftwareUpdate;
273
- error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
274
- switch (response.status) {
275
- case 200:
276
- if (response.body != null)
277
- updateData = (yield response.json());
278
- break;
279
- case 404:
280
- error.ResponseResult = new ResponseResult(UpdateErrorCode.DeviceIsUpToDate, `Updates not found, controller is already up-to-date.`);
281
- updates.UpdatesNotAvailable.push(error);
282
- break;
283
- default:
284
- error.ResponseResult = new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Response status code does not indicate success. Status: ${response.status}`);
285
- updates.UpdatesNotAvailable.push(error);
286
- break;
287
- }
288
- if (updateData != null) {
289
- updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
290
- updateInfo.Update = updateData;
291
- const update = new ControllerUpdate();
292
- update.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
293
- update.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
294
- update.NewResourceVersion = updateInfo.Update.Version;
295
- update.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
296
- update.UpdateType = ControllerUpdateType.SoftwareUpdate;
297
- update.UpdateIdentifier = Helpers.GenerateUUID();
298
- update.DownloadProgress = 100;
299
- update.UpdateIsDownloading = false;
300
- update.UpdateCreationTime = null;
301
- updates.UpdatesAvailable.push(update);
302
- this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
303
- }
304
- else if (response.status == 200)
305
- throw (new Error(`Cannot get Update Data from response. Status: ${response.status}`));
306
- }
307
- catch (err) {
308
- const runtimeInfo = (yield this.getRuntimeInfoAsync());
309
- if (runtimeInfo instanceof ResponseResult) {
310
- const error = new ControllerUpdateNotAvailableInfo();
311
- error.UpdateType = ControllerUpdateType.SoftwareUpdate;
312
- error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
313
- error.ResponseResult = runtimeInfo;
314
- updates.UpdatesNotAvailable.push(error);
315
- }
316
- else {
317
- const error = new ControllerUpdateNotAvailableInfo();
318
- error.UpdateType = ControllerUpdateType.SoftwareUpdate;
319
- error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
320
- error.ResponseResult = new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get available updates! ${err}`);
321
- error.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
322
- updates.UpdatesNotAvailable.push(error);
323
- }
324
- }
325
- }
326
- return updates;
327
- });
328
- }
329
- CheckControllerVersionAsync() {
330
- return __awaiter(this, void 0, void 0, function* () {
331
- const updateProviderServices = yield this._updateProviders.GetUpdatesProvidersAsync(ProviderType.Controller);
332
- const runtimeInfo = (yield this.getRuntimeInfoAsync());
333
- if (runtimeInfo instanceof ResponseResult) {
334
- return runtimeInfo;
335
- }
336
- const result = [];
337
- let version;
338
- //Software updates
339
- version = new ControllerVersion();
340
- version.Resource = "Controller software";
341
- version.Type = ControllerUpdateType.SoftwareUpdate;
342
- version.Version = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
343
- result.push(version);
344
- //Radio updates
345
- for (let i = 0; i < updateProviderServices.length; i++) {
346
- version = new ControllerVersion();
347
- version.Version = yield updateProviderServices[i].GetCurrentRadioVersionAsync();
348
- version.Type = ControllerUpdateType.RadioUpdate;
349
- let protocol = "n/a";
350
- try {
351
- protocol = (yield this._extensionService.GetProtocolInfoAsync(updateProviderServices[i].ProtocolGuid)).first().Name;
352
- }
353
- catch (error) {
354
- this._logger.Warning(`Cannot get protocol name! error: ${error}`);
355
- }
356
- version.Resource = protocol;
357
- result.push(version);
358
- }
359
- return result;
360
- });
361
- }
362
- GetControllerUpdateBranchAsync() {
363
- return __awaiter(this, void 0, void 0, function* () {
364
- const ver = (yield this.getRuntimeInfoAsync());
365
- if (ver instanceof ResponseResult) {
366
- return ver;
367
- }
368
- const swVerInt = parseFloat(ver.SoftwareVersion);
369
- if (swVerInt <= this._oldUpdateVersion)
370
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot get update branch, feature unsupported in current version. Current version: ${ver}`);
371
- const result = yield this._connection.SendAndWaitForResponseAsync(new GetUpdateBranchRequest(), 10000, false);
372
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
373
- return new ResponseResult(UpdateErrorCode.CannotGetUpdatesBranch, `Cannot get update branch, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
374
- switch (result.Data) {
375
- case 0:
376
- return UpdateBranch.Public;
377
- case 1:
378
- return UpdateBranch.Beta;
379
- case 2:
380
- return UpdateBranch.Development;
381
- default:
382
- return new ResponseResult(UpdateErrorCode.CannotGetUpdatesBranch, `Cannot get update branch, unknown branch number. Branch number: ${result.Data}`);
383
- }
384
- });
385
- }
386
- SetControllerUpdateBranchAsync(updateBranch) {
387
- return __awaiter(this, void 0, void 0, function* () {
388
- const ver = (yield this.getRuntimeInfoAsync());
389
- if (ver instanceof ResponseResult) {
390
- return ver;
391
- }
392
- const swVerInt = parseFloat(ver.SoftwareVersion);
393
- if (swVerInt <= this._oldUpdateVersion)
394
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot set update branch, feature unsupported in current version. Current version: ${ver}`);
395
- const result = yield this._connection.SendAndWaitForResponseAsync(new SetUpdateBranchRequest(updateBranch), 10000, false);
396
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
397
- return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot set update branch, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
398
- return Status.OK;
399
- });
400
- }
401
- EnableAutomaticControllerUpdateDonwloadAsync() {
402
- return __awaiter(this, void 0, void 0, function* () {
403
- const ver = (yield this.getRuntimeInfoAsync());
404
- if (ver instanceof ResponseResult) {
405
- return ver;
406
- }
407
- const swVerInt = parseFloat(ver.SoftwareVersion);
408
- if (swVerInt <= this._oldUpdateVersion)
409
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot enable automatic updates download, feature unsupported in current version. Current version: ${ver}`);
410
- const result = yield this._connection.SendAndWaitForResponseAsync(new EnableAutomaticUpdatesRequest(), 10000, false);
411
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
412
- return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot enable automatic updates download, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
413
- return Status.OK;
414
- });
415
- }
416
- DisableAutomaticControllerUpdateDonwloadAsync() {
417
- return __awaiter(this, void 0, void 0, function* () {
418
- const ver = (yield this.getRuntimeInfoAsync());
419
- if (ver instanceof ResponseResult) {
420
- return ver;
421
- }
422
- const swVerInt = parseFloat(ver.SoftwareVersion);
423
- if (swVerInt <= this._oldUpdateVersion)
424
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot disable automatic update download, feature unsupported in current version. Current version: ${ver}`);
425
- const result = yield this._connection.SendAndWaitForResponseAsync(new DisableAutomaticUpdatesRequest(), 10000, false);
426
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
427
- return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot disable automatic update download, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
428
- return Status.OK;
429
- });
430
- }
431
- GetControllerUpdatesHistoryAsync() {
432
- return __awaiter(this, void 0, void 0, function* () {
433
- const ver = (yield this.getRuntimeInfoAsync());
434
- if (ver instanceof ResponseResult) {
435
- return ver;
436
- }
437
- const swVerInt = parseFloat(ver.SoftwareVersion);
438
- if (swVerInt <= this._oldUpdateVersion)
439
- return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot disable automatic update download, feature unsupported in current version. Current version: ${ver}`);
440
- const result = yield this._connection.SendAndWaitForResponseAsync(new GetUpdatesHistoryRequest(), 10000, false);
441
- if (result == null)
442
- return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response is empty.`);
443
- switch (result.Status) {
444
- case Status.OK:
445
- if (result.Data != null)
446
- return result.Data.map(d => {
447
- const update = new UpdateHistory();
448
- update.UpdatedResourceName = ParseObjToMap(d.UpdateName);
449
- update.UpdateDescription = ParseObjToMap(d.UpdateDescription);
450
- update.UpdateCreationTime = d.Creationtime;
451
- update.UpdateChannel = d.UpdateChannel;
452
- update.Version = `${d.Version.BaseRuntime}.${d.Version.ContainerSoftwareVersion}`;
453
- return update;
454
- });
455
- else
456
- return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response data is empty.`);
457
- case Status.NoData:
458
- return [];
459
- default:
460
- return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response status is not OK. Status: ${result.Status}`);
461
- }
462
- });
463
- }
464
- InstallControllerUpdateAsync(updateProgress, downloadProgress, guidOrAction, downloadOnlyOrAction, updateAction) {
465
- return __awaiter(this, void 0, void 0, function* () {
466
- const regGuid = new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");
467
- const numberOfUpdates = this._controllerUpdates.length;
468
- const ver = (yield this.getRuntimeInfoAsync());
469
- if (ver instanceof ResponseResult) {
470
- return ver;
471
- }
472
- const swVerInt = parseFloat(ver.SoftwareVersion);
473
- //Check if any updates are avaliable
474
- if (this._controllerUpdates.length == 0)
475
- return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().`);
476
- //Install single update
477
- if ((typeof guidOrAction === 'string') && regGuid.test(guidOrAction)) {
478
- let updateResult;
479
- const updateToInstall = this._controllerUpdates.find(update => update.UpdateIdentifier == guidOrAction);
480
- if (updateToInstall == null)
481
- return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Update with requested guid (${guidOrAction}) not found.`);
482
- this._logger.Debug(`Installing single update type: ${updateToInstall.Update.UpdateType}, resource: ${updateToInstall.UpdatedResourceName}, version: ${updateToInstall.Update.Version}`);
483
- this._appStateService.DisallowHibernation();
484
- switch (updateToInstall.UpdateType) {
485
- case ControllerUpdateType.RadioUpdate:
486
- if (downloadOnlyOrAction)
487
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded set flag downloadOnly to false to install it.`);
488
- updateResult = yield (yield this._updateProviders.GetUpdatesProviderAsync(updateToInstall.ProviderName)).InstallRadioUpdateAsync(updateToInstall, updateProgress, updateAction);
489
- this._appStateService.AllowHibernation();
490
- if (updateResult == Status.OK)
491
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
492
- return updateResult;
493
- case ControllerUpdateType.SoftwareUpdate:
494
- //Old way
495
- if (swVerInt <= this._oldUpdateVersion) {
496
- if (downloadOnlyOrAction)
497
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded set flag downloadOnly to false to install it.`);
498
- updateResult = yield this.UpdateControllerUsingScriptAsync(updateToInstall.Update, updateProgress);
499
- this._appStateService.AllowHibernation();
500
- if (updateResult == Status.OK)
501
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
502
- }
503
- //New way
504
- else {
505
- updateResult = yield this.UpdateControllerUsingApiAsync(updateProgress, downloadProgress, downloadOnlyOrAction);
506
- this._appStateService.AllowHibernation();
507
- if (updateResult == Status.OK)
508
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
509
- }
510
- return updateResult;
511
- default:
512
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update with type ${updateToInstall.UpdateType} is not supported by UpdateService.`);
513
- }
514
- }
515
- //Install all updates
516
- else {
517
- //Handle update progress with multiple updates.
518
- const updateNumberRef = [1];
519
- const updateProgressWrapper = (progressInfo) => {
520
- progressInfo.UpdateNumber = updateNumberRef[0];
521
- progressInfo.AvailableUpdates = numberOfUpdates;
522
- updateProgress(progressInfo);
523
- };
524
- const timeout = (ms) => __awaiter(this, void 0, void 0, function* () {
525
- return new Promise(resolve => setTimeout(resolve, ms));
526
- });
527
- //First insall radio updates
528
- let updatesToInstall = this._controllerUpdates.where(update => update.UpdateType == ControllerUpdateType.RadioUpdate).toArray();
529
- let result = [];
530
- this._appStateService.DisallowHibernation();
531
- for (let i = 0; i < updatesToInstall.length; i++) {
532
- const updateResult = yield (yield this._updateProviders.GetUpdatesProviderAsync(updatesToInstall[i].ProviderName)).InstallRadioUpdateAsync(updatesToInstall[i], updateProgressWrapper, guidOrAction);
533
- //Wait between updates
534
- yield timeout(5000);
535
- if (updateResult == Status.OK)
536
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != updatesToInstall[i].UpdateIdentifier);
537
- result.push(updateResult);
538
- updateNumberRef[0]++;
539
- }
540
- //Install other updates (in the future)
541
- //....//
542
- //
543
- //Install controller update
544
- const controlerUpdate = this._controllerUpdates.find(update => update.UpdateType == ControllerUpdateType.SoftwareUpdate);
545
- if (controlerUpdate != null) {
546
- //Old way
547
- if (swVerInt <= this._oldUpdateVersion) {
548
- const updateResult = yield this.UpdateControllerUsingScriptAsync(controlerUpdate.Update, updateProgressWrapper);
549
- if (updateResult == Status.OK)
550
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != controlerUpdate.UpdateIdentifier);
551
- result.push(updateResult);
552
- updateNumberRef[0]++;
553
- }
554
- //New way
555
- else {
556
- const updateResult = yield this.UpdateControllerUsingApiAsync(updateProgressWrapper, downloadProgress, downloadOnlyOrAction);
557
- this._appStateService.AllowHibernation();
558
- if (updateResult == Status.OK)
559
- this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
560
- result.push(updateResult);
561
- updateNumberRef[0]++;
562
- }
563
- }
564
- const resultWithError = result.where(r => r instanceof ResponseResult).toArray();
565
- if (resultWithError != null && resultWithError.length != 0) {
566
- let errors = "";
567
- resultWithError.forEach(err => errors += `${err.Type}, `);
568
- this._appStateService.AllowHibernation();
569
- return new ResponseResult(UpdateErrorCode.UpdatesPartiallyInstalled, `Update installation finished - not all updates were successfully installed. Installation error codes: ${errors}`);
570
- }
571
- this._appStateService.AllowHibernation();
572
- return Status.OK;
573
- }
574
- });
575
- }
576
- UpdateControllerUsingScriptAsync(update, updateProgress) {
577
- return __awaiter(this, void 0, void 0, function* () {
578
- var _a, _b, _c, _d, _e, _f;
579
- switch (update.UpdateType) {
580
- case UpdateTypes.Container:
581
- case UpdateTypes.ContainerSoftware:
582
- try {
583
- yield ((_a = this._connection) === null || _a === void 0 ? void 0 : _a.SendAndHandleResponseAsync(new ScriptControllerUpdateRequest(update.DownloadUri), this._updateRequestTimeout, (resp) => {
584
- const progressInfo = new UpdateProgressInfo();
585
- progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
586
- switch (resp.Status) {
587
- case Status.MultiDataResponseStart:
588
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
589
- break;
590
- case Status.MultiDataResponse:
591
- if (resp.Data == null) {
592
- this._logger.Warning(UpdatesService.ServiceName, `Recived update response without data! URI: ${update.DownloadUri}`);
593
- return;
594
- }
595
- progressInfo.Percentage = Math.round(resp.Data.Progress);
596
- switch (resp.Data.State) {
597
- case UpdateState.CheckingApplicability:
598
- case UpdateState.CheckingIntegrity:
599
- case UpdateState.CheckingPackageIntegrity:
600
- progressInfo.Status = UpdateStatus.CheckingPackage;
601
- break;
602
- case UpdateState.CreatingBackup:
603
- case UpdateState.MigratingData:
604
- case UpdateState.Removing:
605
- progressInfo.Status = UpdateStatus.MovingData;
606
- break;
607
- case UpdateState.Deploying:
608
- case UpdateState.Installing:
609
- progressInfo.Status = UpdateStatus.Upgrading;
610
- break;
611
- case UpdateState.Downloading:
612
- progressInfo.Status = UpdateStatus.DownloadingPackage;
613
- break;
614
- case UpdateState.Error:
615
- progressInfo.Status = UpdateStatus.Error;
616
- break;
617
- case UpdateState.Installed:
618
- progressInfo.Status = UpdateStatus.Upgraded;
619
- break;
620
- case UpdateState.PreparingSystem:
621
- case UpdateState.ReadyToDownload:
622
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
623
- break;
624
- case UpdateState.UndoingInstallation:
625
- progressInfo.Status = UpdateStatus.InstallationStopped;
626
- break;
627
- case UpdateState.Unpackaging:
628
- progressInfo.Status = UpdateStatus.MovingData;
629
- break;
630
- case UpdateState.WaitingForUser:
631
- progressInfo.Status = UpdateStatus.Upgrading;
632
- break;
633
- }
634
- break;
635
- case Status.MultiDataResponseStop:
636
- progressInfo.Status = UpdateStatus.OK;
637
- break;
638
- }
639
- updateProgress(progressInfo);
640
- }, false));
641
- return Status.OK;
642
- }
643
- catch (error) {
644
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Cannot process update, error: ${error}`);
645
- }
646
- case UpdateTypes.RuntimeFixingScript:
647
- var howManyDevices = 10;
648
- let extVersion = "n/a";
649
- try {
650
- extVersion = (yield this._extensionService.GetExtensionsInfoAsync()).first(ext => ext.ExtensionGuid == "f4f45dac-beda-441a-8d29-efc6dc977cd1").ExtensionVersion;
651
- }
652
- catch (error) {
653
- this._logger.Warning(`Cannot get protocol name! error: ${error}`);
654
- }
655
- var updateExtVersion = extVersion;
656
- const ver = (yield this.getRuntimeInfoAsync());
657
- if (ver instanceof ResponseResult) {
658
- return ver;
659
- }
660
- var isNewApi = parseFloat(ver.RuntimeVersion) >= 2.0 ? true : (parseFloat(updateExtVersion) >= 1.2201125);
661
- try {
662
- howManyDevices = (yield Api.Get(DevicesService.ServiceName).GetDevicesAsync()).length;
663
- }
664
- catch (error) {
665
- this._logger.Warning(UpdatesService.ServiceName, `Cannot get number of devices in system! Error: ${error}. Using default value of 10 devices.`);
666
- }
667
- if (isNewApi) {
668
- let intervalId;
669
- let progressInfo = new UpdateProgressInfo();
670
- progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
671
- progressInfo.Percentage = 1;
672
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
673
- updateProgress(progressInfo);
674
- let i = 2;
675
- const startTime = Date.now();
676
- const howLongToUpgrade = (howManyDevices * 900) + 800000;
677
- const onePercentInTime = howLongToUpgrade / 100;
678
- const willEndAt = startTime + howLongToUpgrade;
679
- const updatePromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
680
- var _a;
681
- try {
682
- const OnReturnedFromSuspensionHandler = () => {
683
- this._appStateService.OnReturnedFromSuspension().Unsubscribe(OnReturnedFromSuspensionHandler);
684
- if (Date.now() > willEndAt) {
685
- clearInterval(intervalId);
686
- this._logger.Debug(`Update already finished!`);
687
- progressInfo.Percentage = 100;
688
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
689
- progressInfo.Status = UpdateStatus.Upgraded;
690
- updateProgress(progressInfo);
691
- resolve(Status.OK);
692
- }
693
- else {
694
- var msToEnd = (willEndAt - Date.now());
695
- if (msToEnd < howLongToUpgrade) {
696
- i = (95 - (msToEnd / onePercentInTime));
697
- }
698
- else {
699
- clearInterval(intervalId);
700
- intervalId = setInterval(() => {
701
- clearInterval(intervalId);
702
- progressInfo.Percentage = 100;
703
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
704
- progressInfo.Status = UpdateStatus.Upgraded;
705
- updateProgress(progressInfo);
706
- resolve(Status.OK);
707
- }, msToEnd);
708
- }
709
- }
710
- };
711
- this._appStateService.OnReturnedFromSuspension().Subscribe(OnReturnedFromSuspensionHandler);
712
- intervalId = setInterval(() => {
713
- if (i > 99) {
714
- clearInterval(intervalId);
715
- progressInfo.Percentage = 100;
716
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
717
- progressInfo.Status = UpdateStatus.Upgraded;
718
- updateProgress(progressInfo);
719
- resolve(Status.OK);
720
- }
721
- else {
722
- var percent = i;
723
- if (percent < 99) {
724
- progressInfo.Percentage = Math.round(percent);
725
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
726
- progressInfo.Status = UpdateStatus.Upgrading;
727
- updateProgress(progressInfo);
728
- }
729
- }
730
- i++;
731
- }, onePercentInTime);
732
- const result = yield ((_a = this._connection) === null || _a === void 0 ? void 0 : _a.SendAndWaitForResponseAsync(new InstallRequest(update.DownloadUri), this._updateRequestTimeout, false));
733
- if (result.Status != Status.OK) {
734
- clearInterval(intervalId);
735
- progressInfo.Percentage = 0;
736
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
737
- progressInfo.Status = UpdateStatus.InstallationError;
738
- updateProgress(progressInfo);
739
- this._logger.Debug(UpdatesService.ServiceName, `Update failed with error. Update response status: ${result.Status}`);
740
- resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. Update response status: ${result.Status}`));
741
- }
742
- }
743
- catch (error) {
744
- this._logger.Debug(UpdatesService.ServiceName, `Update failed with error. ${error}`);
745
- progressInfo.Percentage = 0;
746
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
747
- progressInfo.Status = UpdateStatus.Error;
748
- updateProgress(progressInfo);
749
- clearInterval(intervalId);
750
- resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. ${error}`));
751
- }
752
- }));
753
- return yield updatePromise;
754
- }
755
- else {
756
- let progressInfo = new UpdateProgressInfo();
757
- progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
758
- progressInfo.Percentage = 1;
759
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
760
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
761
- updateProgress(progressInfo);
762
- const currentAuthData = this._connection.GetAuthorizationInfo();
763
- if (currentAuthData == null)
764
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Cannot process update. Cannot get current controller login credentials!`);
765
- const result = yield ((_b = this._connection) === null || _b === void 0 ? void 0 : _b.SendAndWaitForResponseAsync(new LoginUserRequest({ Email: `support@support`, Password: `support@${currentAuthData.SerialNumber}:${currentAuthData.PIN}` }), 12000, false));
766
- if (result.Status === Status.OK) {
767
- progressInfo.Percentage = 1;
768
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
769
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
770
- updateProgress(progressInfo);
771
- let executeCommandResult = yield ((_c = this._connection) === null || _c === void 0 ? void 0 : _c.SendAndWaitForResponseAsync(new ExecuteCommandRequest("rm /runtime/tmp/update.sh"), 12000, false));
772
- if (executeCommandResult.Status == Status.OK) {
773
- this._logger.Debug(`Removed previous script`);
774
- progressInfo.Percentage = 2;
775
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
776
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
777
- updateProgress(progressInfo);
778
- executeCommandResult = yield ((_d = this._connection) === null || _d === void 0 ? void 0 : _d.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`wget ${update.DownloadUri} -O /runtime/tmp/update.sh --no-check-certificate`), this._updateRequestTimeout, false));
779
- if (executeCommandResult.Status == Status.OK) {
780
- this._logger.Debug(`Downloaded update script`);
781
- progressInfo.Percentage = 5;
782
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
783
- progressInfo.Status = UpdateStatus.PreparingForUpgrade;
784
- updateProgress(progressInfo);
785
- try {
786
- executeCommandResult = yield ((_e = this._connection) === null || _e === void 0 ? void 0 : _e.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`chmod a+x /runtime/tmp/update.sh`), 12000, false));
787
- if (executeCommandResult.Status == Status.OK) {
788
- this._logger.Debug(`Executed update script`);
789
- progressInfo.Percentage = 5;
790
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
791
- progressInfo.Status = UpdateStatus.Upgrading;
792
- updateProgress(progressInfo);
793
- let i = 0;
794
- let intervalId;
795
- const onePercent = 95 / 100.0;
796
- const startTime = Date.now();
797
- const howLongToUpgrade = (howManyDevices * 900) + 1500000; //ms
798
- const onePercentInTime = howLongToUpgrade / 95;
799
- const willEndAt = startTime + howLongToUpgrade;
800
- const updatePromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
801
- var _a;
802
- try {
803
- const OnReturnedFromSuspensionHandler = () => {
804
- this._appStateService.OnReturnedFromSuspension().Unsubscribe(OnReturnedFromSuspensionHandler);
805
- if (Date.now() > willEndAt) {
806
- clearInterval(intervalId);
807
- this._logger.Debug(`Update already finished!`);
808
- progressInfo.Percentage = 100;
809
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
810
- progressInfo.Status = UpdateStatus.Upgraded;
811
- updateProgress(progressInfo);
812
- resolve(Status.OK);
813
- }
814
- else {
815
- var msToEnd = (willEndAt - Date.now());
816
- if (msToEnd < howLongToUpgrade) {
817
- i = (95 - (msToEnd / onePercentInTime));
818
- }
819
- else {
820
- clearInterval(intervalId);
821
- intervalId = setInterval(() => {
822
- clearInterval(intervalId);
823
- progressInfo.Percentage = 100;
824
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
825
- progressInfo.Status = UpdateStatus.Upgraded;
826
- updateProgress(progressInfo);
827
- resolve(Status.OK);
828
- }, msToEnd);
829
- }
830
- }
831
- };
832
- this._appStateService.OnReturnedFromSuspension().Subscribe(OnReturnedFromSuspensionHandler);
833
- intervalId = setInterval(() => {
834
- if (i > 99) {
835
- clearInterval(intervalId);
836
- progressInfo.Percentage = 100;
837
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
838
- progressInfo.Status = UpdateStatus.Upgraded;
839
- updateProgress(progressInfo);
840
- resolve(Status.OK);
841
- }
842
- else {
843
- var percent = (5 + (i * onePercent));
844
- ;
845
- if (percent < 99) {
846
- progressInfo.Percentage = Math.round(percent);
847
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
848
- progressInfo.Status = UpdateStatus.Upgrading;
849
- updateProgress(progressInfo);
850
- }
851
- }
852
- i++;
853
- }, onePercentInTime);
854
- (_a = this._connection) === null || _a === void 0 ? void 0 : _a.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`/runtime/tmp/update.sh`), 12000, false);
855
- }
856
- catch (error) {
857
- resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. ${error}`));
858
- }
859
- }));
860
- return yield updatePromise;
861
- }
862
- else {
863
- progressInfo.Percentage = 0;
864
- progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
865
- progressInfo.Status = UpdateStatus.InstallationError;
866
- updateProgress(progressInfo);
867
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed!`);
868
- }
869
- }
870
- catch (err) {
871
- (_f = this._connection) === null || _f === void 0 ? void 0 : _f.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`/runtime/scripts/restart_all.sh`), 12000, false);
872
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Error ${err}`);
873
- }
874
- }
875
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Cannot clear old update script!`);
876
- }
877
- }
878
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Cannot loggin using support account!`);
879
- }
880
- default:
881
- return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Not supported update type, type: ${update.UpdateType}`);
882
- }
883
- });
884
- }
885
- UpdateControllerUsingApiAsync(updateProgress, downloadProgess, downloadOnly) {
886
- return __awaiter(this, void 0, void 0, function* () {
887
- const downloadUpdate = (pendingUpdate) => __awaiter(this, void 0, void 0, function* () {
888
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
889
- let downloadProgressEndPercentage = 50;
890
- let downloadProgressOnePercentageMultiplier = 100 / downloadProgressEndPercentage;
891
- yield this._connection.SendAndHandleResponseAsync(new DownloadUpdateRequest(), this._updateRequestTimeout, (resp) => {
892
- var _a, _b, _c, _d;
893
- const info = new DownloadProgressInfo();
894
- info.UpdatedResourceName = ParseObjToMap(pendingUpdate.Update.UpdateName);
895
- switch (resp.Status) {
896
- case Status.MultiDataResponseStart:
897
- info.Percentage = 0;
898
- info.SpeedMbps = 0;
899
- info.PercentageTotal = 0;
900
- info.CurrentTask = DownloadTask.DownloadingInstaller;
901
- downloadProgess(info);
902
- break;
903
- case Status.MultiDataResponse:
904
- if (resp.Data != null) {
905
- info.Percentage = resp.Data.StepProgressInPercentage;
906
- info.SpeedMbps = resp.Data.DownloadSpeedInMbs;
907
- if (downloadOnly)
908
- info.PercentageTotal = Math.round(((_a = resp.Data) === null || _a === void 0 ? void 0 : _a.UpdateProgressInPercentage) * downloadProgressOnePercentageMultiplier);
909
- else
910
- info.PercentageTotal = Math.round((_b = resp.Data) === null || _b === void 0 ? void 0 : _b.UpdateProgressInPercentage);
911
- switch (resp.Data.UpdateStep) {
912
- case UpdateStep.DownloadingInstaller:
913
- info.CurrentTask = DownloadTask.DownloadingInstaller;
914
- break;
915
- case UpdateStep.DownloadingUpdate:
916
- info.CurrentTask = DownloadTask.DownloadingUpdate;
917
- break;
918
- default:
919
- info.CurrentTask = DownloadTask.CheckingUpdate;
920
- break;
921
- }
922
- downloadProgess(info);
923
- }
924
- break;
925
- case Status.MultiDataResponseStop:
926
- if (resp.Data != null) {
927
- switch (resp.Data.UpdateStep) {
928
- case UpdateStep.UpdateDownloaded:
929
- info.Percentage = 100;
930
- if (downloadOnly)
931
- info.PercentageTotal = Math.round(((_c = resp.Data) === null || _c === void 0 ? void 0 : _c.UpdateProgressInPercentage) * downloadProgressOnePercentageMultiplier);
932
- else
933
- info.PercentageTotal = Math.round((_d = resp.Data) === null || _d === void 0 ? void 0 : _d.UpdateProgressInPercentage);
934
- info.SpeedMbps = 0;
935
- info.CurrentTask = DownloadTask.CheckingUpdate;
936
- downloadProgess(info);
937
- resolve(Status.OK);
938
- break;
939
- case UpdateStep.UpdateDownloadFailed:
940
- info.Percentage = 0;
941
- info.PercentageTotal = 0;
942
- info.SpeedMbps = 0;
943
- info.CurrentTask = DownloadTask.Unknown;
944
- downloadProgess(info);
945
- resolve(new ResponseResult(UpdateErrorCode.UpdateDownloadFailed, `Update download failed!`));
946
- }
947
- }
948
- break;
949
- }
950
- }, false);
951
- }));
952
- });
953
- const installUpdate = (pendingUpdate) => __awaiter(this, void 0, void 0, function* () {
954
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
955
- const endPercentage = 100;
956
- const totalTime = this._updateOfflineStageTime * 60 * 1000; // 6 minutes
957
- let percentage = 0;
958
- yield this._connection.SendAndHandleResponseAsync(new InstallUpdateRequest(), this._updateRequestTimeout, (resp) => {
959
- var _a, _b;
960
- const info = new UpdateProgressInfo();
961
- info.UpdatedResourceName = ParseObjToMap(pendingUpdate.Update.UpdateName);
962
- switch (resp.Status) {
963
- case Status.MultiDataResponseStart:
964
- info.Status = UpdateStatus.PreparingForUpgrade;
965
- info.Percentage = (_a = resp.Data) === null || _a === void 0 ? void 0 : _a.StepProgressInPercentage;
966
- info.PercentageTotal = (_b = resp.Data) === null || _b === void 0 ? void 0 : _b.UpdateProgressInPercentage;
967
- updateProgress(info);
968
- break;
969
- case Status.MultiDataResponse:
970
- if (resp.Data != null) {
971
- info.Status = UpdateStatus.Upgrading;
972
- info.Percentage = Math.round(resp.Data.StepProgressInPercentage);
973
- info.PercentageTotal = Math.round(resp.Data.UpdateProgressInPercentage);
974
- percentage = resp.Data.StepProgressInPercentage;
975
- updateProgress(info);
976
- }
977
- break;
978
- case Status.MultiDataResponseStop:
979
- if (resp.Data != null) {
980
- switch (resp.Data.UpdateStep) {
981
- case UpdateStep.UpdateInstallationFailed:
982
- info.Status = UpdateStatus.InstallationError;
983
- info.Percentage = 0;
984
- info.PercentageTotal = 0;
985
- updateProgress(info);
986
- resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update installation failed!`));
987
- break;
988
- //Add 5 minutes to finish offline stage
989
- case UpdateStep.OfflineUpdateStep:
990
- {
991
- info.Percentage = Math.round(resp.Data.StepProgressInPercentage);
992
- info.PercentageTotal = Math.round(resp.Data.UpdateProgressInPercentage);
993
- let oneUpdateProgressPercent = (100 - info.PercentageTotal) / 100;
994
- let updateProgressPercent = info.PercentageTotal;
995
- //info.PercentageTotal = resp.Data.UpdateProgressInPercentage as Progress; // 78%
996
- const incrementTime = totalTime / (endPercentage - percentage);
997
- const intervalId = setInterval(() => {
998
- percentage++;
999
- updateProgressPercent += oneUpdateProgressPercent;
1000
- if (updateProgressPercent > 100)
1001
- updateProgressPercent = 100;
1002
- if (percentage >= endPercentage) {
1003
- info.Status = UpdateStatus.Upgraded;
1004
- info.Percentage = 100;
1005
- info.PercentageTotal = 100;
1006
- updateProgress(info);
1007
- clearInterval(intervalId);
1008
- resolve(Status.OK);
1009
- }
1010
- else {
1011
- info.Status = UpdateStatus.Upgrading;
1012
- info.Percentage = Math.round(percentage);
1013
- info.PercentageTotal = Math.round(updateProgressPercent);
1014
- updateProgress(info);
1015
- }
1016
- }, incrementTime);
1017
- }
1018
- break;
1019
- }
1020
- }
1021
- break;
1022
- }
1023
- }, false);
1024
- }));
1025
- });
1026
- if (downloadOnly) {
1027
- const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
1028
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK || (result === null || result === void 0 ? void 0 : result.Data) == null)
1029
- throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
1030
- switch (result.Data.UpdateStep) {
1031
- case UpdateStep.DownloadingInstaller:
1032
- case UpdateStep.DownloadingUpdate:
1033
- case UpdateStep.UpdateDownloaded:
1034
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded, or download is in progress.`);
1035
- case UpdateStep.InstallingUpdate:
1036
- case UpdateStep.PreparingUpdate:
1037
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyInstalled, `Update already installed, or installation is in progress.`);
1038
- default:
1039
- return yield downloadUpdate(result.Data);
1040
- }
1041
- }
1042
- else {
1043
- const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
1044
- if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK || (result === null || result === void 0 ? void 0 : result.Data) == null)
1045
- throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
1046
- switch (result.Data.UpdateStep) {
1047
- case UpdateStep.DownloadingInstaller:
1048
- case UpdateStep.DownloadingUpdate:
1049
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded, or donwload in progress.`);
1050
- case UpdateStep.InstallingUpdate:
1051
- case UpdateStep.PreparingUpdate:
1052
- return new ResponseResult(UpdateErrorCode.UpdateAlreadyInstalled, `Update already installed, or installation in progress.`);
1053
- case UpdateStep.UpdateDownloaded:
1054
- return yield installUpdate(result.Data);
1055
- default:
1056
- var downloadResult = yield downloadUpdate(result.Data);
1057
- if (downloadResult != Status.OK)
1058
- return downloadResult;
1059
- else
1060
- return yield installUpdate(result.Data);
1061
- }
1062
- }
1063
- });
1064
- }
1065
- getRuntimeInfoAsync() {
1066
- return __awaiter(this, void 0, void 0, function* () {
1067
- try {
1068
- return yield this._updateProviders.GetSoftwareRuntimeInfoAsync();
1069
- }
1070
- catch (error) {
1071
- if (error instanceof CannotGetRuntimeInfo) {
1072
- if (error.code == CannotGetRuntimeErrorCode.Timeout)
1073
- return new ResponseResult(UpdateErrorCode.CannotGetCurrentControllerVersionTimeout, `Cannot get runtime info (current controller version), timeout error - please restart controller to fix issue.`);
1074
- }
1075
- return new ResponseResult(UpdateErrorCode.CannotGetCurrentControllerVersion, `Cannot get runtime info (current controller version), error: ${error}`);
1076
- }
1077
- });
1078
- }
1079
- }
1080
- UpdatesService.ServiceName = "UpdatesService";
1081
- class CachedUpdateInfo extends UpdateInfo {
1082
- constructor() {
1083
- super(...arguments);
1084
- this.UpdateIdentifier = "";
1085
- this.ProviderName = "";
1086
- this.UpdateType = null;
1087
- }
1088
- }
1089
- /**
1090
- * @type Class
1091
- */
1092
- export class ControllerUpdateNotAvailableInfo {
1093
- constructor() {
1094
- this.UpdatedResourceName = new Map();
1095
- this.CurrentResourceVersion = "";
1096
- this.UpdateType = null;
1097
- this.ResponseResult = null;
1098
- }
1099
- }
1100
- class ControllerUpdate {
1101
- constructor() {
1102
- this._updateIdentifier = "";
1103
- this._updateResourceName = new Map();
1104
- this._updateType = null;
1105
- this._currentResourceVersion = "";
1106
- this._newResourceVersion = "";
1107
- this._updateDescription = new Map();
1108
- this._updateIsDownloading = false;
1109
- this._updateCheckDownloadProgress = 0;
1110
- this._updateCreationTime = null;
1111
- }
1112
- get UpdateCreationTime() {
1113
- return this._updateCreationTime;
1114
- }
1115
- get DownloadProgress() {
1116
- return this._updateCheckDownloadProgress;
1117
- }
1118
- get UpdateDescription() {
1119
- return this._updateDescription;
1120
- }
1121
- get UpdateIdentifier() {
1122
- return this._updateIdentifier;
1123
- }
1124
- get UpdatedResourceName() {
1125
- return this._updateResourceName;
1126
- }
1127
- get UpdateType() {
1128
- return this._updateType;
1129
- }
1130
- get CurrentResourceVersion() {
1131
- return this._currentResourceVersion;
1132
- }
1133
- get NewResourceVersion() {
1134
- return this._newResourceVersion;
1135
- }
1136
- get UpdateIsDownloading() {
1137
- return this._updateIsDownloading;
1138
- }
1139
- set UpdateCreationTime(value) {
1140
- this._updateCreationTime = value;
1141
- }
1142
- set DownloadProgress(value) {
1143
- this._updateCheckDownloadProgress = value;
1144
- }
1145
- set UpdateDescription(value) {
1146
- this._updateDescription = value;
1147
- }
1148
- set UpdateIdentifier(value) {
1149
- this._updateIdentifier = value;
1150
- }
1151
- set UpdatedResourceName(value) {
1152
- this._updateResourceName = value;
1153
- }
1154
- set UpdateType(value) {
1155
- this._updateType = value;
1156
- }
1157
- set CurrentResourceVersion(value) {
1158
- this._currentResourceVersion = value;
1159
- }
1160
- set NewResourceVersion(value) {
1161
- this._newResourceVersion = value;
1162
- }
1163
- set UpdateIsDownloading(value) {
1164
- this._updateIsDownloading = value;
1165
- }
1166
- }
1167
- class DeviceUpdate {
1168
- constructor() {
1169
- this._updatedResourceName = "";
1170
- this._updateResourceGuid = "";
1171
- this._protocol = "";
1172
- this._protocolGuid = "";
1173
- this._currentResourceVersion = "";
1174
- this._newResourceVersion = "";
1175
- this._isUpdateSafe = true;
1176
- this._updateDescription = new Map();
1177
- }
1178
- get UpdateDescription() {
1179
- return this._updateDescription;
1180
- }
1181
- set UpdateDescription(value) {
1182
- this._updateDescription = value;
1183
- }
1184
- get UpdatedResourceName() {
1185
- return this._updatedResourceName;
1186
- }
1187
- get UpdateResourceGuid() {
1188
- return this._updateResourceGuid;
1189
- }
1190
- get Protocol() {
1191
- return this._protocol;
1192
- }
1193
- get ProtocolGuid() {
1194
- return this._protocolGuid;
1195
- }
1196
- get CurrentResourceVersion() {
1197
- return this._currentResourceVersion;
1198
- }
1199
- get NewResourceVersion() {
1200
- return this._newResourceVersion;
1201
- }
1202
- get IsUpdateSafe() {
1203
- return this._isUpdateSafe;
1204
- }
1205
- set UpdatedResourceName(value) {
1206
- this._updatedResourceName = value;
1207
- }
1208
- set UpdateResourceGuid(value) {
1209
- this._updateResourceGuid = value;
1210
- }
1211
- set Protocol(value) {
1212
- this._protocol = value;
1213
- }
1214
- set ProtocolGuid(value) {
1215
- this._protocolGuid = value;
1216
- }
1217
- set CurrentResourceVersion(value) {
1218
- this._currentResourceVersion = value;
1219
- }
1220
- set NewResourceVersion(value) {
1221
- this._newResourceVersion = value;
1222
- }
1223
- set IsUpdateSafe(value) {
1224
- this._isUpdateSafe = value;
1225
- }
1226
- }
1227
- //Install update
1228
- class ScriptControllerUpdateRequest extends DataFrame {
1229
- constructor(uri) {
1230
- super();
1231
- this.Resource = "/updates/update/from/uri";
1232
- this.Method = Method.Post;
1233
- this.Data = uri;
1234
- }
1235
- }
1236
- class UpdateStatusFrame {
1237
- constructor() {
1238
- this.ExpectedInstallationTime = 0;
1239
- this.Guid = "";
1240
- this.Package = new JsonPackageSchema();
1241
- this.Progress = 0;
1242
- this.State = UpdateState.PreparingSystem;
1243
- this.UserInput = UserInput.Install;
1244
- }
1245
- }
1246
- class JsonPackageSchema {
1247
- constructor() {
1248
- this.Package = new JsonPackage();
1249
- this.Publisher = new Publisher();
1250
- }
1251
- }
1252
- class JsonPackage {
1253
- constructor() {
1254
- this.CompatibleHardwareVersions = [];
1255
- this.CompatibleOperatingSystems = [];
1256
- this.CompatibleProcessorArch = [];
1257
- this.CompatibleSoftwareVersions = [];
1258
- this.DependencyRequiredExtensions = [];
1259
- this.Description = new Map();
1260
- this.Guid = "";
1261
- this.Name = new Map();
1262
- this.PackageAPIVersion = 0;
1263
- this.PackageType = PackageType.Unknown;
1264
- this.PackageVersion = 0;
1265
- this.PublicationTime = Date.now().toString();
1266
- this.PublisherGuid = "";
1267
- this.RequiredDownloadDiskSpace = 0;
1268
- this.RequiredInstallDiskSpace = 0;
1269
- this.UpdateChannels = [];
1270
- }
1271
- }
1272
- class Hardware {
1273
- constructor() {
1274
- this.Guid = "";
1275
- this.MaxVersion = 0;
1276
- this.MinVersion = 0;
1277
- }
1278
- }
1279
- var OperatingSystem;
1280
- (function (OperatingSystem) {
1281
- OperatingSystem[OperatingSystem["Windows"] = 0] = "Windows";
1282
- OperatingSystem[OperatingSystem["Linux"] = 1] = "Linux";
1283
- OperatingSystem[OperatingSystem["Unix"] = 2] = "Unix";
1284
- OperatingSystem[OperatingSystem["OSX"] = 3] = "OSX";
1285
- OperatingSystem[OperatingSystem["Android"] = 4] = "Android";
1286
- OperatingSystem[OperatingSystem["iOS"] = 5] = "iOS";
1287
- OperatingSystem[OperatingSystem["WindowsMobile"] = 6] = "WindowsMobile";
1288
- })(OperatingSystem || (OperatingSystem = {}));
1289
- var ProcessorArch;
1290
- (function (ProcessorArch) {
1291
- ProcessorArch[ProcessorArch["Any"] = 0] = "Any";
1292
- ProcessorArch[ProcessorArch["MIPS"] = 1] = "MIPS";
1293
- ProcessorArch[ProcessorArch["ARM32"] = 2] = "ARM32";
1294
- ProcessorArch[ProcessorArch["ARM64"] = 3] = "ARM64";
1295
- ProcessorArch[ProcessorArch["IntelX86"] = 4] = "IntelX86";
1296
- ProcessorArch[ProcessorArch["IntelX64"] = 5] = "IntelX64";
1297
- })(ProcessorArch || (ProcessorArch = {}));
1298
- class DependencyExtension {
1299
- constructor() {
1300
- this.CompatibleVersions = 0;
1301
- this.ExtensionGuid = 0;
1302
- this.MaximumCompatibleVersion = 0;
1303
- this.MinimumCompatibleVersion = 0;
1304
- }
1305
- }
1306
- var PackageType;
1307
- (function (PackageType) {
1308
- PackageType[PackageType["Unknown"] = 0] = "Unknown";
1309
- PackageType[PackageType["Environment"] = 1] = "Environment";
1310
- PackageType[PackageType["OperatingSystem"] = 2] = "OperatingSystem";
1311
- PackageType[PackageType["Application"] = 3] = "Application";
1312
- PackageType[PackageType["Extension"] = 4] = "Extension";
1313
- PackageType[PackageType["HardwareFirmware"] = 5] = "HardwareFirmware";
1314
- PackageType[PackageType["Script"] = 6] = "Script";
1315
- PackageType[PackageType["Command"] = 7] = "Command";
1316
- })(PackageType || (PackageType = {}));
1317
- class Publisher {
1318
- constructor() {
1319
- this.Description = "";
1320
- this.Email = "";
1321
- this.Guid = "";
1322
- this.Name = "";
1323
- this.Phone = "";
1324
- this.PublisherGuid = "";
1325
- this.Webpage = "";
1326
- }
1327
- }
1328
- //New updates
1329
- class PendingUpdateApiObject {
1330
- constructor() {
1331
- this.Id = "";
1332
- this.Update = new UpdateApiObject();
1333
- this.UpdateDownloadPath = "";
1334
- this.InstallerDownloadPath = "";
1335
- this.DownloadDateTime = "";
1336
- this.UpdateStep = UpdateStep.Unknown;
1337
- this.StepProgressInPercentage = 0;
1338
- this.UpdateProgressInPercentage = 0;
1339
- this.DownloadSpeed = 0;
1340
- this.DownloadProgress = 0;
1341
- }
1342
- }
1343
- class UpdateApiObject {
1344
- constructor() {
1345
- this.Guid = "";
1346
- this.Creationtime = "";
1347
- this.Version = new UpdateVersion();
1348
- this.UpdateChannel = "";
1349
- this.UpdateFileHash = "";
1350
- this.UpdateFileUrl = "";
1351
- this.VerifySign = "";
1352
- this.InstallerFileUrl = "";
1353
- this.InstallerFileHash = "";
1354
- this.InstallerVerifySign = "";
1355
- }
1356
- }
1357
- class UpdateVersion {
1358
- constructor() {
1359
- this.BaseRuntime = 0;
1360
- this.ContainerSoftwareVersion = 0;
1361
- }
1362
- }
1363
- var UpdateStep;
1364
- (function (UpdateStep) {
1365
- UpdateStep[UpdateStep["InstallerFileSignCheckFailed"] = -5] = "InstallerFileSignCheckFailed";
1366
- UpdateStep[UpdateStep["UpdateFileSignCheckFailed"] = -4] = "UpdateFileSignCheckFailed";
1367
- UpdateStep[UpdateStep["UpdateInstallationFailed"] = -3] = "UpdateInstallationFailed";
1368
- UpdateStep[UpdateStep["UpdateDownloadFailed"] = -2] = "UpdateDownloadFailed";
1369
- UpdateStep[UpdateStep["UpdateFileCheckFailed"] = -1] = "UpdateFileCheckFailed";
1370
- UpdateStep[UpdateStep["Unknown"] = 0] = "Unknown";
1371
- UpdateStep[UpdateStep["DownloadingUpdate"] = 1] = "DownloadingUpdate";
1372
- UpdateStep[UpdateStep["CheckingUpdate"] = 2] = "CheckingUpdate";
1373
- UpdateStep[UpdateStep["PreparingUpdate"] = 3] = "PreparingUpdate";
1374
- UpdateStep[UpdateStep["InstallingUpdate"] = 4] = "InstallingUpdate";
1375
- UpdateStep[UpdateStep["DownloadingInstaller"] = 5] = "DownloadingInstaller";
1376
- UpdateStep[UpdateStep["UpdateDownloaded"] = 6] = "UpdateDownloaded";
1377
- UpdateStep[UpdateStep["OfflineUpdateStep"] = 7] = "OfflineUpdateStep";
1378
- })(UpdateStep || (UpdateStep = {}));
1379
- class UpdateProgressResponse {
1380
- constructor() {
1381
- this.UpdateStep = UpdateStep.Unknown;
1382
- this.StepProgressInPercentage = 0;
1383
- this.UpdateProgressInPercentage = 0;
1384
- this.DownloadSpeedInMbs = 0;
1385
- }
1386
- }
1387
- class InstallRequest extends DataFrame {
1388
- constructor(uri) {
1389
- super();
1390
- this.Resource = "/updates/install/from/url";
1391
- this.Method = Method.Put;
1392
- this.Data = uri;
1393
- }
1394
- }
1395
- class LoginUserRequest extends DataFrame {
1396
- constructor(data) {
1397
- super();
1398
- this.Resource = "/users/user/login";
1399
- this.Method = Method.Put;
1400
- this.Data = data;
1401
- }
1402
- }
1403
- class LoginUser {
1404
- constructor() {
1405
- this.Email = "";
1406
- this.Password = "";
1407
- }
1408
- }
1409
- class ExecuteCommandRequest extends DataFrame {
1410
- constructor(command) {
1411
- super();
1412
- this.Resource = "/controller/runtime/execute";
1413
- this.Method = Method.Post;
1414
- this.Data = command;
1415
- }
1416
- }
1417
- class GetUpdateBranchRequest extends DataFrame {
1418
- constructor() {
1419
- super();
1420
- this.Resource = "/updates/branch";
1421
- this.Method = Method.Get;
1422
- }
1423
- }
1424
- class SetUpdateBranchRequest extends DataFrame {
1425
- constructor(data) {
1426
- super();
1427
- this.Resource = "/updates/branch";
1428
- this.Method = Method.Put;
1429
- this.Data = data;
1430
- }
1431
- }
1432
- class PendingUpdatesRequest extends DataFrame {
1433
- constructor() {
1434
- super();
1435
- this.Resource = "/updates/pending";
1436
- this.Method = Method.Get;
1437
- }
1438
- }
1439
- class CheckUpdatesRequest extends DataFrame {
1440
- constructor() {
1441
- super();
1442
- this.Resource = "/updates/check";
1443
- this.Method = Method.Get;
1444
- }
1445
- }
1446
- class DownloadUpdateRequest extends DataFrame {
1447
- constructor() {
1448
- super();
1449
- this.Resource = "/updates/download";
1450
- this.Method = Method.Post;
1451
- }
1452
- }
1453
- class InstallUpdateRequest extends DataFrame {
1454
- constructor() {
1455
- super();
1456
- this.Resource = "/updates/install";
1457
- this.Method = Method.Post;
1458
- }
1459
- }
1460
- class GetAutomaticUpdatesStatusRequest extends DataFrame {
1461
- constructor() {
1462
- super();
1463
- this.Resource = "/updates/download/automatic/status";
1464
- this.Method = Method.Get;
1465
- }
1466
- }
1467
- class EnableAutomaticUpdatesRequest extends DataFrame {
1468
- constructor() {
1469
- super();
1470
- this.Resource = "/updates/download/automatic/enable";
1471
- this.Method = Method.Put;
1472
- }
1473
- }
1474
- class DisableAutomaticUpdatesRequest extends DataFrame {
1475
- constructor() {
1476
- super();
1477
- this.Resource = "/updates/download/automatic/disable";
1478
- this.Method = Method.Put;
1479
- }
1480
- }
1481
- class GetUpdatesHistoryRequest extends DataFrame {
1482
- constructor() {
1483
- super();
1484
- this.Resource = "/updates/history";
1485
- this.Method = Method.Get;
1486
- }
1487
- }
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { Api } from "../../Api";
11
+ import { DataFrame, Method, Status } from "../../DataFrame";
12
+ import { ControllerExtensionsService } from "../Controller/ControllerExtensionsService";
13
+ import { DevicesService } from "../Devices/DevicesService";
14
+ import { ResponseResult } from "../FieldChangeResult";
15
+ import { CannotGetRuntimeErrorCode, CannotGetRuntimeInfo, UpdatesProvider } from "./UpdatesProvider";
16
+ import { ControllerUpdatesInfo, ControllerUpdateType, ControllerVersion, UpdateHistory } from "./IUpdateInfo";
17
+ import { ProviderType, UpdateInfo, UpdateTypes, UpdatesProviderNotFound } from "./IUpdatesProvider";
18
+ import { DownloadProgressInfo, DownloadTask, UpdateBranch, UpdateErrorCode, UpdateProgressInfo, UpdateState, UpdateStatus, UserInput } from './IUpdatesService';
19
+ import { AppStateService } from "../AppStateService";
20
+ import { LoggerService } from "../Logging/LoggerService";
21
+ import { ExalusConnectionService } from "../ExalusConnectionService";
22
+ import { Helpers, ParseObjToMap } from "../../Helpers";
23
+ export class UpdatesService {
24
+ constructor() {
25
+ this._controllerUpdates = [];
26
+ this._updateRequestTimeout = 120000;
27
+ this._oldUpdateVersion = 5.56;
28
+ this._updateOfflineStageTime = 8.5;
29
+ this._updateProviders = Api.Get(UpdatesProvider.ServiceName);
30
+ this._logger = Api.Get(LoggerService.ServiceName);
31
+ this._connection = Api.Get(ExalusConnectionService.ServiceName);
32
+ this._appStateService = Api.Get(AppStateService.ServiceName);
33
+ this._extensionService = Api.Get(ControllerExtensionsService.ServiceName);
34
+ }
35
+ GetAutomaticControllerUpdateDownloadStatusAsync() {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ const ver = (yield this.getRuntimeInfoAsync());
38
+ if (ver instanceof ResponseResult) {
39
+ return ver;
40
+ }
41
+ if (parseFloat(ver.SoftwareVersion) <= this._oldUpdateVersion)
42
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot get update branch, feature unsupported in current version. Current version: ${ver}`);
43
+ let result = yield this._connection.SendAndWaitForResponseAsync(new GetAutomaticUpdatesStatusRequest(), 10000, false);
44
+ if (result.Status == Status.OK && result.Data)
45
+ return true;
46
+ else
47
+ return false;
48
+ });
49
+ }
50
+ GetServiceName() {
51
+ return UpdatesService.ServiceName;
52
+ }
53
+ CheckDeviceVersionAsync(dev) {
54
+ var _a;
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ let device;
57
+ if (typeof dev == 'string') {
58
+ const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
59
+ if (result != null)
60
+ device = result;
61
+ else
62
+ return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
63
+ }
64
+ else {
65
+ device = dev;
66
+ }
67
+ if (device.ProtocolGuid == null)
68
+ return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
69
+ const softwareInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetSoftwareVersionAsync(device));
70
+ if (softwareInfo.Type != null)
71
+ return softwareInfo;
72
+ return softwareInfo;
73
+ });
74
+ }
75
+ CheckDeviceUpdateAsync(dev) {
76
+ var _a;
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ let device;
79
+ if (typeof dev == 'string') {
80
+ const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
81
+ if (result != null)
82
+ device = result;
83
+ else
84
+ return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
85
+ }
86
+ else {
87
+ device = dev;
88
+ }
89
+ if (device.ProtocolGuid == null)
90
+ return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
91
+ const updateInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetAvailableUpdateAsync(device));
92
+ if (updateInfo.Type != null)
93
+ return updateInfo;
94
+ const result = new DeviceUpdate();
95
+ result.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
96
+ result.NewResourceVersion = updateInfo.Update.Version;
97
+ result.UpdatedResourceName = updateInfo.UpdatedResourceName;
98
+ result.UpdateResourceGuid = updateInfo.Update.ResourceGuid;
99
+ result.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
100
+ let protocol = "n/a";
101
+ try {
102
+ protocol = (yield this._extensionService.GetProtocolInfoAsync(device.ProtocolGuid)).first().Name;
103
+ }
104
+ catch (error) {
105
+ this._logger.Warning(`Cannot get protocol name! error: ${error}`);
106
+ }
107
+ result.Protocol = protocol;
108
+ result.ProtocolGuid = device.ProtocolGuid;
109
+ if ((yield Api.Get(DevicesService.ServiceName).GetDevicesAsync()).any(dev => dev.ModelGuid == "952ddc14-76c4-4f47-b0bc-5d106c1f9b02"))
110
+ result.IsUpdateSafe = false;
111
+ return result;
112
+ });
113
+ }
114
+ InstallDeviceUpdateAsync(dev, updateProgress, updateAction, force = false) {
115
+ var _a;
116
+ return __awaiter(this, void 0, void 0, function* () {
117
+ let device;
118
+ if (typeof dev == 'string') {
119
+ const result = yield Api.Get(DevicesService.ServiceName).GetDevice(dev);
120
+ if (result != null)
121
+ device = result;
122
+ else
123
+ return new ResponseResult(UpdateErrorCode.CannotFindDevice, `Device with specified GUID ${dev} does not exists.`);
124
+ }
125
+ else {
126
+ device = dev;
127
+ }
128
+ if (device.ProtocolGuid == null)
129
+ return new ResponseResult(UpdateErrorCode.UnsupportedDevice, `Device does not contains data about protocol GUID.`);
130
+ const updateInfo = yield ((_a = (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first()) === null || _a === void 0 ? void 0 : _a.GetAvailableUpdateAsync(device));
131
+ if (updateInfo.Type != null)
132
+ return updateInfo;
133
+ this._appStateService.DisallowHibernation();
134
+ const updateInstallResult = yield (yield this._updateProviders.GetUpdatesProvidersByProtocolAsync(device.ProtocolGuid, ProviderType.Device)).first().InstallUpdateAsync(updateInfo, updateProgress, updateAction, force);
135
+ if (updateInstallResult.Type != null) {
136
+ this._appStateService.AllowHibernation();
137
+ return updateInstallResult;
138
+ }
139
+ this._appStateService.AllowHibernation();
140
+ return Status.OK;
141
+ });
142
+ }
143
+ CheckControllerUpdatesAsync() {
144
+ return __awaiter(this, void 0, void 0, function* () {
145
+ this._controllerUpdates = [];
146
+ let updateProviderServices = [];
147
+ const updates = new ControllerUpdatesInfo();
148
+ const runtimeInfo = yield this.getRuntimeInfoAsync();
149
+ if (runtimeInfo instanceof ResponseResult) {
150
+ const error = new ControllerUpdateNotAvailableInfo();
151
+ error.UpdateType = ControllerUpdateType.SoftwareUpdate;
152
+ error.ResponseResult = runtimeInfo;
153
+ updates.UpdatesNotAvailable.push(error);
154
+ return updates;
155
+ }
156
+ const swVer = parseFloat(runtimeInfo.SoftwareVersion);
157
+ try {
158
+ updateProviderServices = yield this._updateProviders.GetUpdatesProvidersAsync(ProviderType.Controller);
159
+ }
160
+ catch (error) {
161
+ if (error instanceof UpdatesProviderNotFound) {
162
+ this._logger.Warning(`Cannot get update providers for controller protocols! Avaliable only controller software updates!`);
163
+ }
164
+ else
165
+ throw error;
166
+ }
167
+ //Radio updates
168
+ for (let i = 0; i < updateProviderServices.length; i++) {
169
+ const result = yield updateProviderServices[i].GetAvailableRadioUpdateAsync();
170
+ if (result.Type != null) {
171
+ const error = new ControllerUpdateNotAvailableInfo();
172
+ error.ResponseResult = result;
173
+ error.UpdateType = ControllerUpdateType.RadioUpdate;
174
+ let protocol = "n/a";
175
+ try {
176
+ protocol = (yield this._extensionService.GetProtocolInfoAsync(updateProviderServices[i].ProtocolGuid)).first().Name;
177
+ }
178
+ catch (error) {
179
+ this._logger.Warning(`Cannot get protocol name! error: ${error}`);
180
+ }
181
+ error.UpdatedResourceName = new Map([["pl-PL", protocol], ["en-US", protocol]]);
182
+ error.CurrentResourceVersion = yield updateProviderServices[i].GetCurrentRadioVersionAsync();
183
+ updates.UpdatesNotAvailable.push(error);
184
+ }
185
+ else {
186
+ const updateInfo = result;
187
+ const update = new ControllerUpdate();
188
+ update.UpdatedResourceName = new Map([["pl-PL", updateInfo.UpdatedResourceName], ["en-US", updateInfo.UpdatedResourceName]]);
189
+ update.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
190
+ update.NewResourceVersion = updateInfo.Update.Version;
191
+ update.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
192
+ update.UpdateType = ControllerUpdateType.RadioUpdate;
193
+ update.UpdateIdentifier = Helpers.GenerateUUID();
194
+ update.UpdateIsDownloading = false;
195
+ update.DownloadProgress = 100;
196
+ update.UpdateCreationTime = null;
197
+ updates.UpdatesAvailable.push(update);
198
+ this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: updateProviderServices[i].GetUpdateProviderName(), UpdateType: ControllerUpdateType.RadioUpdate }));
199
+ }
200
+ }
201
+ //Software updates (new way)
202
+ if (swVer > this._oldUpdateVersion) {
203
+ const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
204
+ if (result == null || (result.Status != Status.OK && result.Status != Status.NoData))
205
+ throw (new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`));
206
+ if (result.Data != null) {
207
+ const updateInfo = new UpdateInfo();
208
+ updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
209
+ updateInfo.UpdateDescription = ParseObjToMap(result.Data.Update.UpdateDescription);
210
+ updateInfo.UpdatedResourceName = ParseObjToMap(result.Data.Update.UpdateName).get("en-US");
211
+ const update = new ControllerUpdate();
212
+ update.UpdatedResourceName = ParseObjToMap(result.Data.Update.UpdateName);
213
+ update.UpdateDescription = ParseObjToMap(result.Data.Update.UpdateDescription);
214
+ update.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
215
+ update.NewResourceVersion = `${result.Data.Update.Version.BaseRuntime}.${result.Data.Update.Version.ContainerSoftwareVersion}`;
216
+ update.UpdateType = ControllerUpdateType.SoftwareUpdate;
217
+ update.UpdateIdentifier = result.Data.Update.Guid;
218
+ update.UpdateIsDownloading = (result.Data.UpdateStep == UpdateStep.DownloadingInstaller
219
+ || result.Data.UpdateStep == UpdateStep.DownloadingUpdate
220
+ || result.Data.UpdateStep == UpdateStep.CheckingUpdate) ? true : false;
221
+ update.DownloadProgress = result.Data.DownloadProgress;
222
+ update.UpdateCreationTime = result.Data.Update.Creationtime;
223
+ updates.UpdatesAvailable.push(update);
224
+ this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
225
+ }
226
+ else {
227
+ //If no updates - returns status NoData
228
+ const result = yield this._connection.SendAndWaitForResponseAsync(new CheckUpdatesRequest(), 15000, false);
229
+ if (result == null)
230
+ throw new Error(`Cannot check updates! Response is empty.`);
231
+ switch (result.Status) {
232
+ case Status.NoData:
233
+ const error = new ControllerUpdateNotAvailableInfo();
234
+ error.UpdateType = ControllerUpdateType.SoftwareUpdate;
235
+ error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
236
+ error.ResponseResult = new ResponseResult(UpdateErrorCode.DeviceIsUpToDate, `Updates not found, controller is already up-to-date.`);
237
+ updates.UpdatesNotAvailable.push(error);
238
+ break;
239
+ case Status.OK:
240
+ if (result.Data == null)
241
+ throw new Error(`Cannot check updates! Response data is empty.`);
242
+ const updateInfo = new UpdateInfo();
243
+ updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
244
+ updateInfo.UpdateDescription = ParseObjToMap(result.Data.UpdateDescription);
245
+ updateInfo.UpdatedResourceName = ParseObjToMap(result.Data.UpdateName).get("en-US");
246
+ const update = new ControllerUpdate();
247
+ update.UpdatedResourceName = ParseObjToMap(result.Data.UpdateName);
248
+ update.UpdateDescription = ParseObjToMap(result.Data.UpdateDescription);
249
+ update.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
250
+ update.UpdateType = ControllerUpdateType.SoftwareUpdate;
251
+ update.UpdateIdentifier = result.Data.Guid;
252
+ update.NewResourceVersion = `${result.Data.Version.BaseRuntime}.${result.Data.Version.ContainerSoftwareVersion}`;
253
+ update.UpdateIsDownloading = false;
254
+ update.DownloadProgress = 0;
255
+ update.UpdateCreationTime = result.Data.Creationtime;
256
+ updates.UpdatesAvailable.push(update);
257
+ this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
258
+ break;
259
+ default:
260
+ throw new Error(`Cannot check updates! Response status is not OK. Status: ${result.Status}`);
261
+ }
262
+ }
263
+ }
264
+ //Software updates (old way)
265
+ else {
266
+ const url = `https://updates.tr7.pl/software/${runtimeInfo.UpdateChannel}/${runtimeInfo.RuntimeVersion}/${runtimeInfo.SoftwareVersion}/update.json`;
267
+ try {
268
+ const response = yield fetch(url);
269
+ let updateData;
270
+ let updateInfo = new UpdateInfo();
271
+ const error = new ControllerUpdateNotAvailableInfo();
272
+ error.UpdateType = ControllerUpdateType.SoftwareUpdate;
273
+ error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
274
+ switch (response.status) {
275
+ case 200:
276
+ if (response.body != null)
277
+ updateData = (yield response.json());
278
+ break;
279
+ case 404:
280
+ error.ResponseResult = new ResponseResult(UpdateErrorCode.DeviceIsUpToDate, `Updates not found, controller is already up-to-date.`);
281
+ updates.UpdatesNotAvailable.push(error);
282
+ break;
283
+ default:
284
+ error.ResponseResult = new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Response status code does not indicate success. Status: ${response.status}`);
285
+ updates.UpdatesNotAvailable.push(error);
286
+ break;
287
+ }
288
+ if (updateData != null) {
289
+ updateInfo.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
290
+ updateInfo.Update = updateData;
291
+ const update = new ControllerUpdate();
292
+ update.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
293
+ update.CurrentResourceVersion = updateInfo.CurrentResourceVersion;
294
+ update.NewResourceVersion = updateInfo.Update.Version;
295
+ update.UpdateDescription = new Map([["pl-PL", updateInfo.Update.Description]]);
296
+ update.UpdateType = ControllerUpdateType.SoftwareUpdate;
297
+ update.UpdateIdentifier = Helpers.GenerateUUID();
298
+ update.DownloadProgress = 100;
299
+ update.UpdateIsDownloading = false;
300
+ update.UpdateCreationTime = null;
301
+ updates.UpdatesAvailable.push(update);
302
+ this._controllerUpdates.push(Object.assign(Object.assign({}, updateInfo), { UpdateIdentifier: update.UpdateIdentifier, ProviderName: UpdatesService.ServiceName, UpdateType: ControllerUpdateType.SoftwareUpdate }));
303
+ }
304
+ else if (response.status == 200)
305
+ throw (new Error(`Cannot get Update Data from response. Status: ${response.status}`));
306
+ }
307
+ catch (err) {
308
+ const runtimeInfo = (yield this.getRuntimeInfoAsync());
309
+ if (runtimeInfo instanceof ResponseResult) {
310
+ const error = new ControllerUpdateNotAvailableInfo();
311
+ error.UpdateType = ControllerUpdateType.SoftwareUpdate;
312
+ error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
313
+ error.ResponseResult = runtimeInfo;
314
+ updates.UpdatesNotAvailable.push(error);
315
+ }
316
+ else {
317
+ const error = new ControllerUpdateNotAvailableInfo();
318
+ error.UpdateType = ControllerUpdateType.SoftwareUpdate;
319
+ error.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
320
+ error.ResponseResult = new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get available updates! ${err}`);
321
+ error.CurrentResourceVersion = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
322
+ updates.UpdatesNotAvailable.push(error);
323
+ }
324
+ }
325
+ }
326
+ return updates;
327
+ });
328
+ }
329
+ CheckControllerVersionAsync() {
330
+ return __awaiter(this, void 0, void 0, function* () {
331
+ const updateProviderServices = yield this._updateProviders.GetUpdatesProvidersAsync(ProviderType.Controller);
332
+ const runtimeInfo = (yield this.getRuntimeInfoAsync());
333
+ if (runtimeInfo instanceof ResponseResult) {
334
+ return runtimeInfo;
335
+ }
336
+ const result = [];
337
+ let version;
338
+ //Software updates
339
+ version = new ControllerVersion();
340
+ version.Resource = "Controller software";
341
+ version.Type = ControllerUpdateType.SoftwareUpdate;
342
+ version.Version = `${runtimeInfo.RuntimeVersion}.${runtimeInfo.SoftwareVersion}`;
343
+ result.push(version);
344
+ //Radio updates
345
+ for (let i = 0; i < updateProviderServices.length; i++) {
346
+ version = new ControllerVersion();
347
+ version.Version = yield updateProviderServices[i].GetCurrentRadioVersionAsync();
348
+ version.Type = ControllerUpdateType.RadioUpdate;
349
+ let protocol = "n/a";
350
+ try {
351
+ protocol = (yield this._extensionService.GetProtocolInfoAsync(updateProviderServices[i].ProtocolGuid)).first().Name;
352
+ }
353
+ catch (error) {
354
+ this._logger.Warning(`Cannot get protocol name! error: ${error}`);
355
+ }
356
+ version.Resource = protocol;
357
+ result.push(version);
358
+ }
359
+ return result;
360
+ });
361
+ }
362
+ GetControllerUpdateBranchAsync() {
363
+ return __awaiter(this, void 0, void 0, function* () {
364
+ const ver = (yield this.getRuntimeInfoAsync());
365
+ if (ver instanceof ResponseResult) {
366
+ return ver;
367
+ }
368
+ const swVerInt = parseFloat(ver.SoftwareVersion);
369
+ if (swVerInt <= this._oldUpdateVersion)
370
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot get update branch, feature unsupported in current version. Current version: ${ver}`);
371
+ const result = yield this._connection.SendAndWaitForResponseAsync(new GetUpdateBranchRequest(), 10000, false);
372
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
373
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdatesBranch, `Cannot get update branch, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
374
+ switch (result.Data) {
375
+ case 0:
376
+ return UpdateBranch.Public;
377
+ case 1:
378
+ return UpdateBranch.Beta;
379
+ case 2:
380
+ return UpdateBranch.Development;
381
+ default:
382
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdatesBranch, `Cannot get update branch, unknown branch number. Branch number: ${result.Data}`);
383
+ }
384
+ });
385
+ }
386
+ SetControllerUpdateBranchAsync(updateBranch) {
387
+ return __awaiter(this, void 0, void 0, function* () {
388
+ const ver = (yield this.getRuntimeInfoAsync());
389
+ if (ver instanceof ResponseResult) {
390
+ return ver;
391
+ }
392
+ const swVerInt = parseFloat(ver.SoftwareVersion);
393
+ if (swVerInt <= this._oldUpdateVersion)
394
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot set update branch, feature unsupported in current version. Current version: ${ver}`);
395
+ const result = yield this._connection.SendAndWaitForResponseAsync(new SetUpdateBranchRequest(updateBranch), 10000, false);
396
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
397
+ return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot set update branch, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
398
+ return Status.OK;
399
+ });
400
+ }
401
+ EnableAutomaticControllerUpdateDonwloadAsync() {
402
+ return __awaiter(this, void 0, void 0, function* () {
403
+ const ver = (yield this.getRuntimeInfoAsync());
404
+ if (ver instanceof ResponseResult) {
405
+ return ver;
406
+ }
407
+ const swVerInt = parseFloat(ver.SoftwareVersion);
408
+ if (swVerInt <= this._oldUpdateVersion)
409
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot enable automatic updates download, feature unsupported in current version. Current version: ${ver}`);
410
+ const result = yield this._connection.SendAndWaitForResponseAsync(new EnableAutomaticUpdatesRequest(), 10000, false);
411
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
412
+ return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot enable automatic updates download, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
413
+ return Status.OK;
414
+ });
415
+ }
416
+ DisableAutomaticControllerUpdateDonwloadAsync() {
417
+ return __awaiter(this, void 0, void 0, function* () {
418
+ const ver = (yield this.getRuntimeInfoAsync());
419
+ if (ver instanceof ResponseResult) {
420
+ return ver;
421
+ }
422
+ const swVerInt = parseFloat(ver.SoftwareVersion);
423
+ if (swVerInt <= this._oldUpdateVersion)
424
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot disable automatic update download, feature unsupported in current version. Current version: ${ver}`);
425
+ const result = yield this._connection.SendAndWaitForResponseAsync(new DisableAutomaticUpdatesRequest(), 10000, false);
426
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK)
427
+ return new ResponseResult(UpdateErrorCode.CannotSetUpdatesBranch, `Cannot disable automatic update download, response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
428
+ return Status.OK;
429
+ });
430
+ }
431
+ GetControllerUpdatesHistoryAsync() {
432
+ return __awaiter(this, void 0, void 0, function* () {
433
+ const ver = (yield this.getRuntimeInfoAsync());
434
+ if (ver instanceof ResponseResult) {
435
+ return ver;
436
+ }
437
+ const swVerInt = parseFloat(ver.SoftwareVersion);
438
+ if (swVerInt <= this._oldUpdateVersion)
439
+ return new ResponseResult(UpdateErrorCode.FeatureUnsupportedInCurrentVersion, `Cannot disable automatic update download, feature unsupported in current version. Current version: ${ver}`);
440
+ const result = yield this._connection.SendAndWaitForResponseAsync(new GetUpdatesHistoryRequest(), 10000, false);
441
+ if (result == null)
442
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response is empty.`);
443
+ switch (result.Status) {
444
+ case Status.OK:
445
+ if (result.Data != null)
446
+ return result.Data.map(d => {
447
+ const update = new UpdateHistory();
448
+ update.UpdatedResourceName = ParseObjToMap(d.UpdateName);
449
+ update.UpdateDescription = ParseObjToMap(d.UpdateDescription);
450
+ update.UpdateCreationTime = d.Creationtime;
451
+ update.UpdateChannel = d.UpdateChannel;
452
+ update.Version = `${d.Version.BaseRuntime}.${d.Version.ContainerSoftwareVersion}`;
453
+ return update;
454
+ });
455
+ else
456
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response data is empty.`);
457
+ case Status.NoData:
458
+ return [];
459
+ default:
460
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot get updates history, response status is not OK. Status: ${result.Status}`);
461
+ }
462
+ });
463
+ }
464
+ InstallControllerUpdateAsync(updateProgress, downloadProgress, guidOrAction, downloadOnlyOrAction, updateAction) {
465
+ return __awaiter(this, void 0, void 0, function* () {
466
+ const regGuid = new RegExp("^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$");
467
+ const numberOfUpdates = this._controllerUpdates.length;
468
+ const ver = (yield this.getRuntimeInfoAsync());
469
+ if (ver instanceof ResponseResult) {
470
+ return ver;
471
+ }
472
+ const swVerInt = parseFloat(ver.SoftwareVersion);
473
+ //Check if any updates are avaliable
474
+ if (this._controllerUpdates.length == 0)
475
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Cannot find any updates, make sure you check for available updates by calling CheckControllerUpdateAsync().`);
476
+ //Install single update
477
+ if ((typeof guidOrAction === 'string') && regGuid.test(guidOrAction)) {
478
+ let updateResult;
479
+ const updateToInstall = this._controllerUpdates.find(update => update.UpdateIdentifier == guidOrAction);
480
+ if (updateToInstall == null)
481
+ return new ResponseResult(UpdateErrorCode.CannotGetUpdates, `Update with requested guid (${guidOrAction}) not found.`);
482
+ this._logger.Debug(`Installing single update type: ${updateToInstall.Update.UpdateType}, resource: ${updateToInstall.UpdatedResourceName}, version: ${updateToInstall.Update.Version}`);
483
+ this._appStateService.DisallowHibernation();
484
+ switch (updateToInstall.UpdateType) {
485
+ case ControllerUpdateType.RadioUpdate:
486
+ if (downloadOnlyOrAction)
487
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded set flag downloadOnly to false to install it.`);
488
+ updateResult = yield (yield this._updateProviders.GetUpdatesProviderAsync(updateToInstall.ProviderName)).InstallRadioUpdateAsync(updateToInstall, updateProgress, updateAction);
489
+ this._appStateService.AllowHibernation();
490
+ if (updateResult == Status.OK)
491
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
492
+ return updateResult;
493
+ case ControllerUpdateType.SoftwareUpdate:
494
+ //Old way
495
+ if (swVerInt <= this._oldUpdateVersion) {
496
+ if (downloadOnlyOrAction)
497
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded set flag downloadOnly to false to install it.`);
498
+ updateResult = yield this.UpdateControllerUsingScriptAsync(updateToInstall.Update, updateProgress);
499
+ this._appStateService.AllowHibernation();
500
+ if (updateResult == Status.OK)
501
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
502
+ }
503
+ //New way
504
+ else {
505
+ updateResult = yield this.UpdateControllerUsingApiAsync(updateProgress, downloadProgress, downloadOnlyOrAction);
506
+ this._appStateService.AllowHibernation();
507
+ if (updateResult == Status.OK)
508
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
509
+ }
510
+ return updateResult;
511
+ default:
512
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update with type ${updateToInstall.UpdateType} is not supported by UpdateService.`);
513
+ }
514
+ }
515
+ //Install all updates
516
+ else {
517
+ //Handle update progress with multiple updates.
518
+ const updateNumberRef = [1];
519
+ const updateProgressWrapper = (progressInfo) => {
520
+ progressInfo.UpdateNumber = updateNumberRef[0];
521
+ progressInfo.AvailableUpdates = numberOfUpdates;
522
+ updateProgress(progressInfo);
523
+ };
524
+ const timeout = (ms) => __awaiter(this, void 0, void 0, function* () {
525
+ return new Promise(resolve => setTimeout(resolve, ms));
526
+ });
527
+ //First insall radio updates
528
+ let updatesToInstall = this._controllerUpdates.where(update => update.UpdateType == ControllerUpdateType.RadioUpdate).toArray();
529
+ let result = [];
530
+ this._appStateService.DisallowHibernation();
531
+ for (let i = 0; i < updatesToInstall.length; i++) {
532
+ const updateResult = yield (yield this._updateProviders.GetUpdatesProviderAsync(updatesToInstall[i].ProviderName)).InstallRadioUpdateAsync(updatesToInstall[i], updateProgressWrapper, guidOrAction);
533
+ //Wait between updates
534
+ yield timeout(5000);
535
+ if (updateResult == Status.OK)
536
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != updatesToInstall[i].UpdateIdentifier);
537
+ result.push(updateResult);
538
+ updateNumberRef[0]++;
539
+ }
540
+ //Install other updates (in the future)
541
+ //....//
542
+ //
543
+ //Install controller update
544
+ const controlerUpdate = this._controllerUpdates.find(update => update.UpdateType == ControllerUpdateType.SoftwareUpdate);
545
+ if (controlerUpdate != null) {
546
+ //Old way
547
+ if (swVerInt <= this._oldUpdateVersion) {
548
+ const updateResult = yield this.UpdateControllerUsingScriptAsync(controlerUpdate.Update, updateProgressWrapper);
549
+ if (updateResult == Status.OK)
550
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != controlerUpdate.UpdateIdentifier);
551
+ result.push(updateResult);
552
+ updateNumberRef[0]++;
553
+ }
554
+ //New way
555
+ else {
556
+ const updateResult = yield this.UpdateControllerUsingApiAsync(updateProgressWrapper, downloadProgress, downloadOnlyOrAction);
557
+ this._appStateService.AllowHibernation();
558
+ if (updateResult == Status.OK)
559
+ this._controllerUpdates = this._controllerUpdates.filter(update => update.UpdateIdentifier != guidOrAction);
560
+ result.push(updateResult);
561
+ updateNumberRef[0]++;
562
+ }
563
+ }
564
+ const resultWithError = result.where(r => r instanceof ResponseResult).toArray();
565
+ if (resultWithError != null && resultWithError.length != 0) {
566
+ let errors = "";
567
+ resultWithError.forEach(err => errors += `${err.Type}, `);
568
+ this._appStateService.AllowHibernation();
569
+ return new ResponseResult(UpdateErrorCode.UpdatesPartiallyInstalled, `Update installation finished - not all updates were successfully installed. Installation error codes: ${errors}`);
570
+ }
571
+ this._appStateService.AllowHibernation();
572
+ return Status.OK;
573
+ }
574
+ });
575
+ }
576
+ UpdateControllerUsingScriptAsync(update, updateProgress) {
577
+ var _a, _b, _c, _d, _e, _f;
578
+ return __awaiter(this, void 0, void 0, function* () {
579
+ switch (update.UpdateType) {
580
+ case UpdateTypes.Container:
581
+ case UpdateTypes.ContainerSoftware:
582
+ try {
583
+ yield ((_a = this._connection) === null || _a === void 0 ? void 0 : _a.SendAndHandleResponseAsync(new ScriptControllerUpdateRequest(update.DownloadUri), this._updateRequestTimeout, (resp) => {
584
+ const progressInfo = new UpdateProgressInfo();
585
+ progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
586
+ switch (resp.Status) {
587
+ case Status.MultiDataResponseStart:
588
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
589
+ break;
590
+ case Status.MultiDataResponse:
591
+ if (resp.Data == null) {
592
+ this._logger.Warning(UpdatesService.ServiceName, `Recived update response without data! URI: ${update.DownloadUri}`);
593
+ return;
594
+ }
595
+ progressInfo.Percentage = Math.round(resp.Data.Progress);
596
+ switch (resp.Data.State) {
597
+ case UpdateState.CheckingApplicability:
598
+ case UpdateState.CheckingIntegrity:
599
+ case UpdateState.CheckingPackageIntegrity:
600
+ progressInfo.Status = UpdateStatus.CheckingPackage;
601
+ break;
602
+ case UpdateState.CreatingBackup:
603
+ case UpdateState.MigratingData:
604
+ case UpdateState.Removing:
605
+ progressInfo.Status = UpdateStatus.MovingData;
606
+ break;
607
+ case UpdateState.Deploying:
608
+ case UpdateState.Installing:
609
+ progressInfo.Status = UpdateStatus.Upgrading;
610
+ break;
611
+ case UpdateState.Downloading:
612
+ progressInfo.Status = UpdateStatus.DownloadingPackage;
613
+ break;
614
+ case UpdateState.Error:
615
+ progressInfo.Status = UpdateStatus.Error;
616
+ break;
617
+ case UpdateState.Installed:
618
+ progressInfo.Status = UpdateStatus.Upgraded;
619
+ break;
620
+ case UpdateState.PreparingSystem:
621
+ case UpdateState.ReadyToDownload:
622
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
623
+ break;
624
+ case UpdateState.UndoingInstallation:
625
+ progressInfo.Status = UpdateStatus.InstallationStopped;
626
+ break;
627
+ case UpdateState.Unpackaging:
628
+ progressInfo.Status = UpdateStatus.MovingData;
629
+ break;
630
+ case UpdateState.WaitingForUser:
631
+ progressInfo.Status = UpdateStatus.Upgrading;
632
+ break;
633
+ }
634
+ break;
635
+ case Status.MultiDataResponseStop:
636
+ progressInfo.Status = UpdateStatus.OK;
637
+ break;
638
+ }
639
+ updateProgress(progressInfo);
640
+ }, false));
641
+ return Status.OK;
642
+ }
643
+ catch (error) {
644
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Cannot process update, error: ${error}`);
645
+ }
646
+ case UpdateTypes.RuntimeFixingScript:
647
+ var howManyDevices = 10;
648
+ let extVersion = "n/a";
649
+ try {
650
+ extVersion = (yield this._extensionService.GetExtensionsInfoAsync()).first(ext => ext.ExtensionGuid == "f4f45dac-beda-441a-8d29-efc6dc977cd1").ExtensionVersion;
651
+ }
652
+ catch (error) {
653
+ this._logger.Warning(`Cannot get protocol name! error: ${error}`);
654
+ }
655
+ var updateExtVersion = extVersion;
656
+ const ver = (yield this.getRuntimeInfoAsync());
657
+ if (ver instanceof ResponseResult) {
658
+ return ver;
659
+ }
660
+ var isNewApi = parseFloat(ver.RuntimeVersion) >= 2.0 ? true : (parseFloat(updateExtVersion) >= 1.2201125);
661
+ try {
662
+ howManyDevices = (yield Api.Get(DevicesService.ServiceName).GetDevicesAsync()).length;
663
+ }
664
+ catch (error) {
665
+ this._logger.Warning(UpdatesService.ServiceName, `Cannot get number of devices in system! Error: ${error}. Using default value of 10 devices.`);
666
+ }
667
+ if (isNewApi) {
668
+ let intervalId;
669
+ let progressInfo = new UpdateProgressInfo();
670
+ progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
671
+ progressInfo.Percentage = 1;
672
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
673
+ updateProgress(progressInfo);
674
+ let i = 2;
675
+ const startTime = Date.now();
676
+ const howLongToUpgrade = (howManyDevices * 900) + 800000;
677
+ const onePercentInTime = howLongToUpgrade / 100;
678
+ const willEndAt = startTime + howLongToUpgrade;
679
+ const updatePromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
680
+ var _g;
681
+ try {
682
+ const OnReturnedFromSuspensionHandler = () => {
683
+ this._appStateService.OnReturnedFromSuspension().Unsubscribe(OnReturnedFromSuspensionHandler);
684
+ if (Date.now() > willEndAt) {
685
+ clearInterval(intervalId);
686
+ this._logger.Debug(`Update already finished!`);
687
+ progressInfo.Percentage = 100;
688
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
689
+ progressInfo.Status = UpdateStatus.Upgraded;
690
+ updateProgress(progressInfo);
691
+ resolve(Status.OK);
692
+ }
693
+ else {
694
+ var msToEnd = (willEndAt - Date.now());
695
+ if (msToEnd < howLongToUpgrade) {
696
+ i = (95 - (msToEnd / onePercentInTime));
697
+ }
698
+ else {
699
+ clearInterval(intervalId);
700
+ intervalId = setInterval(() => {
701
+ clearInterval(intervalId);
702
+ progressInfo.Percentage = 100;
703
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
704
+ progressInfo.Status = UpdateStatus.Upgraded;
705
+ updateProgress(progressInfo);
706
+ resolve(Status.OK);
707
+ }, msToEnd);
708
+ }
709
+ }
710
+ };
711
+ this._appStateService.OnReturnedFromSuspension().Subscribe(OnReturnedFromSuspensionHandler);
712
+ intervalId = setInterval(() => {
713
+ if (i > 99) {
714
+ clearInterval(intervalId);
715
+ progressInfo.Percentage = 100;
716
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
717
+ progressInfo.Status = UpdateStatus.Upgraded;
718
+ updateProgress(progressInfo);
719
+ resolve(Status.OK);
720
+ }
721
+ else {
722
+ var percent = i;
723
+ if (percent < 99) {
724
+ progressInfo.Percentage = Math.round(percent);
725
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
726
+ progressInfo.Status = UpdateStatus.Upgrading;
727
+ updateProgress(progressInfo);
728
+ }
729
+ }
730
+ i++;
731
+ }, onePercentInTime);
732
+ const result = yield ((_g = this._connection) === null || _g === void 0 ? void 0 : _g.SendAndWaitForResponseAsync(new InstallRequest(update.DownloadUri), this._updateRequestTimeout, false));
733
+ if (result.Status != Status.OK) {
734
+ clearInterval(intervalId);
735
+ progressInfo.Percentage = 0;
736
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
737
+ progressInfo.Status = UpdateStatus.InstallationError;
738
+ updateProgress(progressInfo);
739
+ this._logger.Debug(UpdatesService.ServiceName, `Update failed with error. Update response status: ${result.Status}`);
740
+ resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. Update response status: ${result.Status}`));
741
+ }
742
+ }
743
+ catch (error) {
744
+ this._logger.Debug(UpdatesService.ServiceName, `Update failed with error. ${error}`);
745
+ progressInfo.Percentage = 0;
746
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
747
+ progressInfo.Status = UpdateStatus.Error;
748
+ updateProgress(progressInfo);
749
+ clearInterval(intervalId);
750
+ resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. ${error}`));
751
+ }
752
+ }));
753
+ return yield updatePromise;
754
+ }
755
+ else {
756
+ let progressInfo = new UpdateProgressInfo();
757
+ progressInfo.UpdatedResourceName = new Map([["pl-PL", "Oprogramowanie kontrolera"], ["en-US", "Controller software"]]);
758
+ progressInfo.Percentage = 1;
759
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
760
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
761
+ updateProgress(progressInfo);
762
+ const currentAuthData = this._connection.GetAuthorizationInfo();
763
+ if (currentAuthData == null)
764
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Cannot process update. Cannot get current controller login credentials!`);
765
+ const result = yield ((_b = this._connection) === null || _b === void 0 ? void 0 : _b.SendAndWaitForResponseAsync(new LoginUserRequest({ Email: `support@support`, Password: `support@${currentAuthData.SerialNumber}:${currentAuthData.PIN}` }), 12000, false));
766
+ if (result.Status === Status.OK) {
767
+ progressInfo.Percentage = 1;
768
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
769
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
770
+ updateProgress(progressInfo);
771
+ let executeCommandResult = yield ((_c = this._connection) === null || _c === void 0 ? void 0 : _c.SendAndWaitForResponseAsync(new ExecuteCommandRequest("rm /runtime/tmp/update.sh"), 12000, false));
772
+ if (executeCommandResult.Status == Status.OK) {
773
+ this._logger.Debug(`Removed previous script`);
774
+ progressInfo.Percentage = 2;
775
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
776
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
777
+ updateProgress(progressInfo);
778
+ executeCommandResult = yield ((_d = this._connection) === null || _d === void 0 ? void 0 : _d.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`wget ${update.DownloadUri} -O /runtime/tmp/update.sh --no-check-certificate`), this._updateRequestTimeout, false));
779
+ if (executeCommandResult.Status == Status.OK) {
780
+ this._logger.Debug(`Downloaded update script`);
781
+ progressInfo.Percentage = 5;
782
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
783
+ progressInfo.Status = UpdateStatus.PreparingForUpgrade;
784
+ updateProgress(progressInfo);
785
+ try {
786
+ executeCommandResult = yield ((_e = this._connection) === null || _e === void 0 ? void 0 : _e.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`chmod a+x /runtime/tmp/update.sh`), 12000, false));
787
+ if (executeCommandResult.Status == Status.OK) {
788
+ this._logger.Debug(`Executed update script`);
789
+ progressInfo.Percentage = 5;
790
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
791
+ progressInfo.Status = UpdateStatus.Upgrading;
792
+ updateProgress(progressInfo);
793
+ let i = 0;
794
+ let intervalId;
795
+ const onePercent = 95 / 100.0;
796
+ const startTime = Date.now();
797
+ const howLongToUpgrade = (howManyDevices * 900) + 1500000; //ms
798
+ const onePercentInTime = howLongToUpgrade / 95;
799
+ const willEndAt = startTime + howLongToUpgrade;
800
+ const updatePromise = new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
801
+ var _h;
802
+ try {
803
+ const OnReturnedFromSuspensionHandler = () => {
804
+ this._appStateService.OnReturnedFromSuspension().Unsubscribe(OnReturnedFromSuspensionHandler);
805
+ if (Date.now() > willEndAt) {
806
+ clearInterval(intervalId);
807
+ this._logger.Debug(`Update already finished!`);
808
+ progressInfo.Percentage = 100;
809
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
810
+ progressInfo.Status = UpdateStatus.Upgraded;
811
+ updateProgress(progressInfo);
812
+ resolve(Status.OK);
813
+ }
814
+ else {
815
+ var msToEnd = (willEndAt - Date.now());
816
+ if (msToEnd < howLongToUpgrade) {
817
+ i = (95 - (msToEnd / onePercentInTime));
818
+ }
819
+ else {
820
+ clearInterval(intervalId);
821
+ intervalId = setInterval(() => {
822
+ clearInterval(intervalId);
823
+ progressInfo.Percentage = 100;
824
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
825
+ progressInfo.Status = UpdateStatus.Upgraded;
826
+ updateProgress(progressInfo);
827
+ resolve(Status.OK);
828
+ }, msToEnd);
829
+ }
830
+ }
831
+ };
832
+ this._appStateService.OnReturnedFromSuspension().Subscribe(OnReturnedFromSuspensionHandler);
833
+ intervalId = setInterval(() => {
834
+ if (i > 99) {
835
+ clearInterval(intervalId);
836
+ progressInfo.Percentage = 100;
837
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
838
+ progressInfo.Status = UpdateStatus.Upgraded;
839
+ updateProgress(progressInfo);
840
+ resolve(Status.OK);
841
+ }
842
+ else {
843
+ var percent = (5 + (i * onePercent));
844
+ ;
845
+ if (percent < 99) {
846
+ progressInfo.Percentage = Math.round(percent);
847
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
848
+ progressInfo.Status = UpdateStatus.Upgrading;
849
+ updateProgress(progressInfo);
850
+ }
851
+ }
852
+ i++;
853
+ }, onePercentInTime);
854
+ (_h = this._connection) === null || _h === void 0 ? void 0 : _h.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`/runtime/tmp/update.sh`), 12000, false);
855
+ }
856
+ catch (error) {
857
+ resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update failed with error. ${error}`));
858
+ }
859
+ }));
860
+ return yield updatePromise;
861
+ }
862
+ else {
863
+ progressInfo.Percentage = 0;
864
+ progressInfo.PercentageTotal = Math.round(progressInfo.Percentage);
865
+ progressInfo.Status = UpdateStatus.InstallationError;
866
+ updateProgress(progressInfo);
867
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed!`);
868
+ }
869
+ }
870
+ catch (err) {
871
+ (_f = this._connection) === null || _f === void 0 ? void 0 : _f.SendAndWaitForResponseAsync(new ExecuteCommandRequest(`/runtime/scripts/restart_all.sh`), 12000, false);
872
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Error ${err}`);
873
+ }
874
+ }
875
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Cannot clear old update script!`);
876
+ }
877
+ }
878
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Execution failed! Cannot loggin using support account!`);
879
+ }
880
+ default:
881
+ return new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Not supported update type, type: ${update.UpdateType}`);
882
+ }
883
+ });
884
+ }
885
+ UpdateControllerUsingApiAsync(updateProgress, downloadProgess, downloadOnly) {
886
+ return __awaiter(this, void 0, void 0, function* () {
887
+ const downloadUpdate = (pendingUpdate) => __awaiter(this, void 0, void 0, function* () {
888
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
889
+ let downloadProgressEndPercentage = 50;
890
+ let downloadProgressOnePercentageMultiplier = 100 / downloadProgressEndPercentage;
891
+ yield this._connection.SendAndHandleResponseAsync(new DownloadUpdateRequest(), this._updateRequestTimeout, (resp) => {
892
+ var _a, _b, _c, _d;
893
+ const info = new DownloadProgressInfo();
894
+ info.UpdatedResourceName = ParseObjToMap(pendingUpdate.Update.UpdateName);
895
+ switch (resp.Status) {
896
+ case Status.MultiDataResponseStart:
897
+ info.Percentage = 0;
898
+ info.SpeedMbps = 0;
899
+ info.PercentageTotal = 0;
900
+ info.CurrentTask = DownloadTask.DownloadingInstaller;
901
+ downloadProgess(info);
902
+ break;
903
+ case Status.MultiDataResponse:
904
+ if (resp.Data != null) {
905
+ info.Percentage = resp.Data.StepProgressInPercentage;
906
+ info.SpeedMbps = resp.Data.DownloadSpeedInMbs;
907
+ if (downloadOnly)
908
+ info.PercentageTotal = Math.round(((_a = resp.Data) === null || _a === void 0 ? void 0 : _a.UpdateProgressInPercentage) * downloadProgressOnePercentageMultiplier);
909
+ else
910
+ info.PercentageTotal = Math.round((_b = resp.Data) === null || _b === void 0 ? void 0 : _b.UpdateProgressInPercentage);
911
+ switch (resp.Data.UpdateStep) {
912
+ case UpdateStep.DownloadingInstaller:
913
+ info.CurrentTask = DownloadTask.DownloadingInstaller;
914
+ break;
915
+ case UpdateStep.DownloadingUpdate:
916
+ info.CurrentTask = DownloadTask.DownloadingUpdate;
917
+ break;
918
+ default:
919
+ info.CurrentTask = DownloadTask.CheckingUpdate;
920
+ break;
921
+ }
922
+ downloadProgess(info);
923
+ }
924
+ break;
925
+ case Status.MultiDataResponseStop:
926
+ if (resp.Data != null) {
927
+ switch (resp.Data.UpdateStep) {
928
+ case UpdateStep.UpdateDownloaded:
929
+ info.Percentage = 100;
930
+ if (downloadOnly)
931
+ info.PercentageTotal = Math.round(((_c = resp.Data) === null || _c === void 0 ? void 0 : _c.UpdateProgressInPercentage) * downloadProgressOnePercentageMultiplier);
932
+ else
933
+ info.PercentageTotal = Math.round((_d = resp.Data) === null || _d === void 0 ? void 0 : _d.UpdateProgressInPercentage);
934
+ info.SpeedMbps = 0;
935
+ info.CurrentTask = DownloadTask.CheckingUpdate;
936
+ downloadProgess(info);
937
+ resolve(Status.OK);
938
+ break;
939
+ case UpdateStep.UpdateDownloadFailed:
940
+ info.Percentage = 0;
941
+ info.PercentageTotal = 0;
942
+ info.SpeedMbps = 0;
943
+ info.CurrentTask = DownloadTask.Unknown;
944
+ downloadProgess(info);
945
+ resolve(new ResponseResult(UpdateErrorCode.UpdateDownloadFailed, `Update download failed!`));
946
+ }
947
+ }
948
+ break;
949
+ }
950
+ }, false);
951
+ }));
952
+ });
953
+ const installUpdate = (pendingUpdate) => __awaiter(this, void 0, void 0, function* () {
954
+ return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
955
+ const endPercentage = 100;
956
+ const totalTime = this._updateOfflineStageTime * 60 * 1000; // 6 minutes
957
+ let percentage = 0;
958
+ yield this._connection.SendAndHandleResponseAsync(new InstallUpdateRequest(), this._updateRequestTimeout, (resp) => {
959
+ var _a, _b;
960
+ const info = new UpdateProgressInfo();
961
+ info.UpdatedResourceName = ParseObjToMap(pendingUpdate.Update.UpdateName);
962
+ switch (resp.Status) {
963
+ case Status.MultiDataResponseStart:
964
+ info.Status = UpdateStatus.PreparingForUpgrade;
965
+ info.Percentage = (_a = resp.Data) === null || _a === void 0 ? void 0 : _a.StepProgressInPercentage;
966
+ info.PercentageTotal = (_b = resp.Data) === null || _b === void 0 ? void 0 : _b.UpdateProgressInPercentage;
967
+ updateProgress(info);
968
+ break;
969
+ case Status.MultiDataResponse:
970
+ if (resp.Data != null) {
971
+ info.Status = UpdateStatus.Upgrading;
972
+ info.Percentage = Math.round(resp.Data.StepProgressInPercentage);
973
+ info.PercentageTotal = Math.round(resp.Data.UpdateProgressInPercentage);
974
+ percentage = resp.Data.StepProgressInPercentage;
975
+ updateProgress(info);
976
+ }
977
+ break;
978
+ case Status.MultiDataResponseStop:
979
+ if (resp.Data != null) {
980
+ switch (resp.Data.UpdateStep) {
981
+ case UpdateStep.UpdateInstallationFailed:
982
+ info.Status = UpdateStatus.InstallationError;
983
+ info.Percentage = 0;
984
+ info.PercentageTotal = 0;
985
+ updateProgress(info);
986
+ resolve(new ResponseResult(UpdateErrorCode.CannotProcessUpdate, `Update installation failed!`));
987
+ break;
988
+ //Add 5 minutes to finish offline stage
989
+ case UpdateStep.OfflineUpdateStep:
990
+ {
991
+ info.Percentage = Math.round(resp.Data.StepProgressInPercentage);
992
+ info.PercentageTotal = Math.round(resp.Data.UpdateProgressInPercentage);
993
+ let oneUpdateProgressPercent = (100 - info.PercentageTotal) / 100;
994
+ let updateProgressPercent = info.PercentageTotal;
995
+ //info.PercentageTotal = resp.Data.UpdateProgressInPercentage as Progress; // 78%
996
+ const incrementTime = totalTime / (endPercentage - percentage);
997
+ const intervalId = setInterval(() => {
998
+ percentage++;
999
+ updateProgressPercent += oneUpdateProgressPercent;
1000
+ if (updateProgressPercent > 100)
1001
+ updateProgressPercent = 100;
1002
+ if (percentage >= endPercentage) {
1003
+ info.Status = UpdateStatus.Upgraded;
1004
+ info.Percentage = 100;
1005
+ info.PercentageTotal = 100;
1006
+ updateProgress(info);
1007
+ clearInterval(intervalId);
1008
+ resolve(Status.OK);
1009
+ }
1010
+ else {
1011
+ info.Status = UpdateStatus.Upgrading;
1012
+ info.Percentage = Math.round(percentage);
1013
+ info.PercentageTotal = Math.round(updateProgressPercent);
1014
+ updateProgress(info);
1015
+ }
1016
+ }, incrementTime);
1017
+ }
1018
+ break;
1019
+ }
1020
+ }
1021
+ break;
1022
+ }
1023
+ }, false);
1024
+ }));
1025
+ });
1026
+ if (downloadOnly) {
1027
+ const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
1028
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK || (result === null || result === void 0 ? void 0 : result.Data) == null)
1029
+ throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
1030
+ switch (result.Data.UpdateStep) {
1031
+ case UpdateStep.DownloadingInstaller:
1032
+ case UpdateStep.DownloadingUpdate:
1033
+ case UpdateStep.UpdateDownloaded:
1034
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded, or download is in progress.`);
1035
+ case UpdateStep.InstallingUpdate:
1036
+ case UpdateStep.PreparingUpdate:
1037
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyInstalled, `Update already installed, or installation is in progress.`);
1038
+ default:
1039
+ return yield downloadUpdate(result.Data);
1040
+ }
1041
+ }
1042
+ else {
1043
+ const result = yield this._connection.SendAndWaitForResponseAsync(new PendingUpdatesRequest(), 10000, false);
1044
+ if (result == null || (result === null || result === void 0 ? void 0 : result.Status) != Status.OK || (result === null || result === void 0 ? void 0 : result.Data) == null)
1045
+ throw new Error(`Cannot get pending updates! Response is empty or status is not OK. Status: ${result === null || result === void 0 ? void 0 : result.Status}`);
1046
+ switch (result.Data.UpdateStep) {
1047
+ case UpdateStep.DownloadingInstaller:
1048
+ case UpdateStep.DownloadingUpdate:
1049
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyDownloaded, `Update already downloaded, or donwload in progress.`);
1050
+ case UpdateStep.InstallingUpdate:
1051
+ case UpdateStep.PreparingUpdate:
1052
+ return new ResponseResult(UpdateErrorCode.UpdateAlreadyInstalled, `Update already installed, or installation in progress.`);
1053
+ case UpdateStep.UpdateDownloaded:
1054
+ return yield installUpdate(result.Data);
1055
+ default:
1056
+ var downloadResult = yield downloadUpdate(result.Data);
1057
+ if (downloadResult != Status.OK)
1058
+ return downloadResult;
1059
+ else
1060
+ return yield installUpdate(result.Data);
1061
+ }
1062
+ }
1063
+ });
1064
+ }
1065
+ getRuntimeInfoAsync() {
1066
+ return __awaiter(this, void 0, void 0, function* () {
1067
+ try {
1068
+ return yield this._updateProviders.GetSoftwareRuntimeInfoAsync();
1069
+ }
1070
+ catch (error) {
1071
+ if (error instanceof CannotGetRuntimeInfo) {
1072
+ if (error.code == CannotGetRuntimeErrorCode.Timeout)
1073
+ return new ResponseResult(UpdateErrorCode.CannotGetCurrentControllerVersionTimeout, `Cannot get runtime info (current controller version), timeout error - please restart controller to fix issue.`);
1074
+ }
1075
+ return new ResponseResult(UpdateErrorCode.CannotGetCurrentControllerVersion, `Cannot get runtime info (current controller version), error: ${error}`);
1076
+ }
1077
+ });
1078
+ }
1079
+ }
1080
+ UpdatesService.ServiceName = "UpdatesService";
1081
+ class CachedUpdateInfo extends UpdateInfo {
1082
+ constructor() {
1083
+ super(...arguments);
1084
+ this.UpdateIdentifier = "";
1085
+ this.ProviderName = "";
1086
+ this.UpdateType = null;
1087
+ }
1088
+ }
1089
+ /**
1090
+ * @type Class
1091
+ */
1092
+ export class ControllerUpdateNotAvailableInfo {
1093
+ constructor() {
1094
+ this.UpdatedResourceName = new Map();
1095
+ this.CurrentResourceVersion = "";
1096
+ this.UpdateType = null;
1097
+ this.ResponseResult = null;
1098
+ }
1099
+ }
1100
+ class ControllerUpdate {
1101
+ constructor() {
1102
+ this._updateIdentifier = "";
1103
+ this._updateResourceName = new Map();
1104
+ this._updateType = null;
1105
+ this._currentResourceVersion = "";
1106
+ this._newResourceVersion = "";
1107
+ this._updateDescription = new Map();
1108
+ this._updateIsDownloading = false;
1109
+ this._updateCheckDownloadProgress = 0;
1110
+ this._updateCreationTime = null;
1111
+ }
1112
+ get UpdateCreationTime() {
1113
+ return this._updateCreationTime;
1114
+ }
1115
+ get DownloadProgress() {
1116
+ return this._updateCheckDownloadProgress;
1117
+ }
1118
+ get UpdateDescription() {
1119
+ return this._updateDescription;
1120
+ }
1121
+ get UpdateIdentifier() {
1122
+ return this._updateIdentifier;
1123
+ }
1124
+ get UpdatedResourceName() {
1125
+ return this._updateResourceName;
1126
+ }
1127
+ get UpdateType() {
1128
+ return this._updateType;
1129
+ }
1130
+ get CurrentResourceVersion() {
1131
+ return this._currentResourceVersion;
1132
+ }
1133
+ get NewResourceVersion() {
1134
+ return this._newResourceVersion;
1135
+ }
1136
+ get UpdateIsDownloading() {
1137
+ return this._updateIsDownloading;
1138
+ }
1139
+ set UpdateCreationTime(value) {
1140
+ this._updateCreationTime = value;
1141
+ }
1142
+ set DownloadProgress(value) {
1143
+ this._updateCheckDownloadProgress = value;
1144
+ }
1145
+ set UpdateDescription(value) {
1146
+ this._updateDescription = value;
1147
+ }
1148
+ set UpdateIdentifier(value) {
1149
+ this._updateIdentifier = value;
1150
+ }
1151
+ set UpdatedResourceName(value) {
1152
+ this._updateResourceName = value;
1153
+ }
1154
+ set UpdateType(value) {
1155
+ this._updateType = value;
1156
+ }
1157
+ set CurrentResourceVersion(value) {
1158
+ this._currentResourceVersion = value;
1159
+ }
1160
+ set NewResourceVersion(value) {
1161
+ this._newResourceVersion = value;
1162
+ }
1163
+ set UpdateIsDownloading(value) {
1164
+ this._updateIsDownloading = value;
1165
+ }
1166
+ }
1167
+ class DeviceUpdate {
1168
+ constructor() {
1169
+ this._updatedResourceName = "";
1170
+ this._updateResourceGuid = "";
1171
+ this._protocol = "";
1172
+ this._protocolGuid = "";
1173
+ this._currentResourceVersion = "";
1174
+ this._newResourceVersion = "";
1175
+ this._isUpdateSafe = true;
1176
+ this._updateDescription = new Map();
1177
+ }
1178
+ get UpdateDescription() {
1179
+ return this._updateDescription;
1180
+ }
1181
+ set UpdateDescription(value) {
1182
+ this._updateDescription = value;
1183
+ }
1184
+ get UpdatedResourceName() {
1185
+ return this._updatedResourceName;
1186
+ }
1187
+ get UpdateResourceGuid() {
1188
+ return this._updateResourceGuid;
1189
+ }
1190
+ get Protocol() {
1191
+ return this._protocol;
1192
+ }
1193
+ get ProtocolGuid() {
1194
+ return this._protocolGuid;
1195
+ }
1196
+ get CurrentResourceVersion() {
1197
+ return this._currentResourceVersion;
1198
+ }
1199
+ get NewResourceVersion() {
1200
+ return this._newResourceVersion;
1201
+ }
1202
+ get IsUpdateSafe() {
1203
+ return this._isUpdateSafe;
1204
+ }
1205
+ set UpdatedResourceName(value) {
1206
+ this._updatedResourceName = value;
1207
+ }
1208
+ set UpdateResourceGuid(value) {
1209
+ this._updateResourceGuid = value;
1210
+ }
1211
+ set Protocol(value) {
1212
+ this._protocol = value;
1213
+ }
1214
+ set ProtocolGuid(value) {
1215
+ this._protocolGuid = value;
1216
+ }
1217
+ set CurrentResourceVersion(value) {
1218
+ this._currentResourceVersion = value;
1219
+ }
1220
+ set NewResourceVersion(value) {
1221
+ this._newResourceVersion = value;
1222
+ }
1223
+ set IsUpdateSafe(value) {
1224
+ this._isUpdateSafe = value;
1225
+ }
1226
+ }
1227
+ //Install update
1228
+ class ScriptControllerUpdateRequest extends DataFrame {
1229
+ constructor(uri) {
1230
+ super();
1231
+ this.Resource = "/updates/update/from/uri";
1232
+ this.Method = Method.Post;
1233
+ this.Data = uri;
1234
+ }
1235
+ }
1236
+ class UpdateStatusFrame {
1237
+ constructor() {
1238
+ this.ExpectedInstallationTime = 0;
1239
+ this.Guid = "";
1240
+ this.Package = new JsonPackageSchema();
1241
+ this.Progress = 0;
1242
+ this.State = UpdateState.PreparingSystem;
1243
+ this.UserInput = UserInput.Install;
1244
+ }
1245
+ }
1246
+ class JsonPackageSchema {
1247
+ constructor() {
1248
+ this.Package = new JsonPackage();
1249
+ this.Publisher = new Publisher();
1250
+ }
1251
+ }
1252
+ class JsonPackage {
1253
+ constructor() {
1254
+ this.CompatibleHardwareVersions = [];
1255
+ this.CompatibleOperatingSystems = [];
1256
+ this.CompatibleProcessorArch = [];
1257
+ this.CompatibleSoftwareVersions = [];
1258
+ this.DependencyRequiredExtensions = [];
1259
+ this.Description = new Map();
1260
+ this.Guid = "";
1261
+ this.Name = new Map();
1262
+ this.PackageAPIVersion = 0;
1263
+ this.PackageType = PackageType.Unknown;
1264
+ this.PackageVersion = 0;
1265
+ this.PublicationTime = Date.now().toString();
1266
+ this.PublisherGuid = "";
1267
+ this.RequiredDownloadDiskSpace = 0;
1268
+ this.RequiredInstallDiskSpace = 0;
1269
+ this.UpdateChannels = [];
1270
+ }
1271
+ }
1272
+ class Hardware {
1273
+ constructor() {
1274
+ this.Guid = "";
1275
+ this.MaxVersion = 0;
1276
+ this.MinVersion = 0;
1277
+ }
1278
+ }
1279
+ var OperatingSystem;
1280
+ (function (OperatingSystem) {
1281
+ OperatingSystem[OperatingSystem["Windows"] = 0] = "Windows";
1282
+ OperatingSystem[OperatingSystem["Linux"] = 1] = "Linux";
1283
+ OperatingSystem[OperatingSystem["Unix"] = 2] = "Unix";
1284
+ OperatingSystem[OperatingSystem["OSX"] = 3] = "OSX";
1285
+ OperatingSystem[OperatingSystem["Android"] = 4] = "Android";
1286
+ OperatingSystem[OperatingSystem["iOS"] = 5] = "iOS";
1287
+ OperatingSystem[OperatingSystem["WindowsMobile"] = 6] = "WindowsMobile";
1288
+ })(OperatingSystem || (OperatingSystem = {}));
1289
+ var ProcessorArch;
1290
+ (function (ProcessorArch) {
1291
+ ProcessorArch[ProcessorArch["Any"] = 0] = "Any";
1292
+ ProcessorArch[ProcessorArch["MIPS"] = 1] = "MIPS";
1293
+ ProcessorArch[ProcessorArch["ARM32"] = 2] = "ARM32";
1294
+ ProcessorArch[ProcessorArch["ARM64"] = 3] = "ARM64";
1295
+ ProcessorArch[ProcessorArch["IntelX86"] = 4] = "IntelX86";
1296
+ ProcessorArch[ProcessorArch["IntelX64"] = 5] = "IntelX64";
1297
+ })(ProcessorArch || (ProcessorArch = {}));
1298
+ class DependencyExtension {
1299
+ constructor() {
1300
+ this.CompatibleVersions = 0;
1301
+ this.ExtensionGuid = 0;
1302
+ this.MaximumCompatibleVersion = 0;
1303
+ this.MinimumCompatibleVersion = 0;
1304
+ }
1305
+ }
1306
+ var PackageType;
1307
+ (function (PackageType) {
1308
+ PackageType[PackageType["Unknown"] = 0] = "Unknown";
1309
+ PackageType[PackageType["Environment"] = 1] = "Environment";
1310
+ PackageType[PackageType["OperatingSystem"] = 2] = "OperatingSystem";
1311
+ PackageType[PackageType["Application"] = 3] = "Application";
1312
+ PackageType[PackageType["Extension"] = 4] = "Extension";
1313
+ PackageType[PackageType["HardwareFirmware"] = 5] = "HardwareFirmware";
1314
+ PackageType[PackageType["Script"] = 6] = "Script";
1315
+ PackageType[PackageType["Command"] = 7] = "Command";
1316
+ })(PackageType || (PackageType = {}));
1317
+ class Publisher {
1318
+ constructor() {
1319
+ this.Description = "";
1320
+ this.Email = "";
1321
+ this.Guid = "";
1322
+ this.Name = "";
1323
+ this.Phone = "";
1324
+ this.PublisherGuid = "";
1325
+ this.Webpage = "";
1326
+ }
1327
+ }
1328
+ //New updates
1329
+ class PendingUpdateApiObject {
1330
+ constructor() {
1331
+ this.Id = "";
1332
+ this.Update = new UpdateApiObject();
1333
+ this.UpdateDownloadPath = "";
1334
+ this.InstallerDownloadPath = "";
1335
+ this.DownloadDateTime = "";
1336
+ this.UpdateStep = UpdateStep.Unknown;
1337
+ this.StepProgressInPercentage = 0;
1338
+ this.UpdateProgressInPercentage = 0;
1339
+ this.DownloadSpeed = 0;
1340
+ this.DownloadProgress = 0;
1341
+ }
1342
+ }
1343
+ class UpdateApiObject {
1344
+ constructor() {
1345
+ this.Guid = "";
1346
+ this.Creationtime = "";
1347
+ this.Version = new UpdateVersion();
1348
+ this.UpdateChannel = "";
1349
+ this.UpdateFileHash = "";
1350
+ this.UpdateFileUrl = "";
1351
+ this.VerifySign = "";
1352
+ this.InstallerFileUrl = "";
1353
+ this.InstallerFileHash = "";
1354
+ this.InstallerVerifySign = "";
1355
+ }
1356
+ }
1357
+ class UpdateVersion {
1358
+ constructor() {
1359
+ this.BaseRuntime = 0;
1360
+ this.ContainerSoftwareVersion = 0;
1361
+ }
1362
+ }
1363
+ var UpdateStep;
1364
+ (function (UpdateStep) {
1365
+ UpdateStep[UpdateStep["InstallerFileSignCheckFailed"] = -5] = "InstallerFileSignCheckFailed";
1366
+ UpdateStep[UpdateStep["UpdateFileSignCheckFailed"] = -4] = "UpdateFileSignCheckFailed";
1367
+ UpdateStep[UpdateStep["UpdateInstallationFailed"] = -3] = "UpdateInstallationFailed";
1368
+ UpdateStep[UpdateStep["UpdateDownloadFailed"] = -2] = "UpdateDownloadFailed";
1369
+ UpdateStep[UpdateStep["UpdateFileCheckFailed"] = -1] = "UpdateFileCheckFailed";
1370
+ UpdateStep[UpdateStep["Unknown"] = 0] = "Unknown";
1371
+ UpdateStep[UpdateStep["DownloadingUpdate"] = 1] = "DownloadingUpdate";
1372
+ UpdateStep[UpdateStep["CheckingUpdate"] = 2] = "CheckingUpdate";
1373
+ UpdateStep[UpdateStep["PreparingUpdate"] = 3] = "PreparingUpdate";
1374
+ UpdateStep[UpdateStep["InstallingUpdate"] = 4] = "InstallingUpdate";
1375
+ UpdateStep[UpdateStep["DownloadingInstaller"] = 5] = "DownloadingInstaller";
1376
+ UpdateStep[UpdateStep["UpdateDownloaded"] = 6] = "UpdateDownloaded";
1377
+ UpdateStep[UpdateStep["OfflineUpdateStep"] = 7] = "OfflineUpdateStep";
1378
+ })(UpdateStep || (UpdateStep = {}));
1379
+ class UpdateProgressResponse {
1380
+ constructor() {
1381
+ this.UpdateStep = UpdateStep.Unknown;
1382
+ this.StepProgressInPercentage = 0;
1383
+ this.UpdateProgressInPercentage = 0;
1384
+ this.DownloadSpeedInMbs = 0;
1385
+ }
1386
+ }
1387
+ class InstallRequest extends DataFrame {
1388
+ constructor(uri) {
1389
+ super();
1390
+ this.Resource = "/updates/install/from/url";
1391
+ this.Method = Method.Put;
1392
+ this.Data = uri;
1393
+ }
1394
+ }
1395
+ class LoginUserRequest extends DataFrame {
1396
+ constructor(data) {
1397
+ super();
1398
+ this.Resource = "/users/user/login";
1399
+ this.Method = Method.Put;
1400
+ this.Data = data;
1401
+ }
1402
+ }
1403
+ class LoginUser {
1404
+ constructor() {
1405
+ this.Email = "";
1406
+ this.Password = "";
1407
+ }
1408
+ }
1409
+ class ExecuteCommandRequest extends DataFrame {
1410
+ constructor(command) {
1411
+ super();
1412
+ this.Resource = "/controller/runtime/execute";
1413
+ this.Method = Method.Post;
1414
+ this.Data = command;
1415
+ }
1416
+ }
1417
+ class GetUpdateBranchRequest extends DataFrame {
1418
+ constructor() {
1419
+ super();
1420
+ this.Resource = "/updates/branch";
1421
+ this.Method = Method.Get;
1422
+ }
1423
+ }
1424
+ class SetUpdateBranchRequest extends DataFrame {
1425
+ constructor(data) {
1426
+ super();
1427
+ this.Resource = "/updates/branch";
1428
+ this.Method = Method.Put;
1429
+ this.Data = data;
1430
+ }
1431
+ }
1432
+ class PendingUpdatesRequest extends DataFrame {
1433
+ constructor() {
1434
+ super();
1435
+ this.Resource = "/updates/pending";
1436
+ this.Method = Method.Get;
1437
+ }
1438
+ }
1439
+ class CheckUpdatesRequest extends DataFrame {
1440
+ constructor() {
1441
+ super();
1442
+ this.Resource = "/updates/check";
1443
+ this.Method = Method.Get;
1444
+ }
1445
+ }
1446
+ class DownloadUpdateRequest extends DataFrame {
1447
+ constructor() {
1448
+ super();
1449
+ this.Resource = "/updates/download";
1450
+ this.Method = Method.Post;
1451
+ }
1452
+ }
1453
+ class InstallUpdateRequest extends DataFrame {
1454
+ constructor() {
1455
+ super();
1456
+ this.Resource = "/updates/install";
1457
+ this.Method = Method.Post;
1458
+ }
1459
+ }
1460
+ class GetAutomaticUpdatesStatusRequest extends DataFrame {
1461
+ constructor() {
1462
+ super();
1463
+ this.Resource = "/updates/download/automatic/status";
1464
+ this.Method = Method.Get;
1465
+ }
1466
+ }
1467
+ class EnableAutomaticUpdatesRequest extends DataFrame {
1468
+ constructor() {
1469
+ super();
1470
+ this.Resource = "/updates/download/automatic/enable";
1471
+ this.Method = Method.Put;
1472
+ }
1473
+ }
1474
+ class DisableAutomaticUpdatesRequest extends DataFrame {
1475
+ constructor() {
1476
+ super();
1477
+ this.Resource = "/updates/download/automatic/disable";
1478
+ this.Method = Method.Put;
1479
+ }
1480
+ }
1481
+ class GetUpdatesHistoryRequest extends DataFrame {
1482
+ constructor() {
1483
+ super();
1484
+ this.Resource = "/updates/history";
1485
+ this.Method = Method.Get;
1486
+ }
1487
+ }
1488
1488
  //# sourceMappingURL=UpdatesService.js.map