@homebridge-eufy-security/eufy-security-client 3.7.2-dev.0

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 (129) hide show
  1. package/.prettierignore/342/200/216 +8 -0
  2. package/.prettierrc +11 -0
  3. package/LICENSE +21 -0
  4. package/README.md +970 -0
  5. package/build/error.d.ts +138 -0
  6. package/build/error.js +190 -0
  7. package/build/error.js.map +1 -0
  8. package/build/eufysecurity.d.ts +180 -0
  9. package/build/eufysecurity.js +3148 -0
  10. package/build/eufysecurity.js.map +1 -0
  11. package/build/http/api.d.ts +119 -0
  12. package/build/http/api.js +1877 -0
  13. package/build/http/api.js.map +1 -0
  14. package/build/http/cache.d.ts +8 -0
  15. package/build/http/cache.js +34 -0
  16. package/build/http/cache.js.map +1 -0
  17. package/build/http/const.d.ts +8 -0
  18. package/build/http/const.js +3054 -0
  19. package/build/http/const.js.map +1 -0
  20. package/build/http/device.d.ts +490 -0
  21. package/build/http/device.js +5256 -0
  22. package/build/http/device.js.map +1 -0
  23. package/build/http/error.d.ts +73 -0
  24. package/build/http/error.js +101 -0
  25. package/build/http/error.js.map +1 -0
  26. package/build/http/index.d.ts +10 -0
  27. package/build/http/index.js +30 -0
  28. package/build/http/index.js.map +1 -0
  29. package/build/http/interfaces.d.ts +248 -0
  30. package/build/http/interfaces.js +3 -0
  31. package/build/http/interfaces.js.map +1 -0
  32. package/build/http/models.d.ts +608 -0
  33. package/build/http/models.js +3 -0
  34. package/build/http/models.js.map +1 -0
  35. package/build/http/parameter.d.ts +7 -0
  36. package/build/http/parameter.js +119 -0
  37. package/build/http/parameter.js.map +1 -0
  38. package/build/http/station.d.ts +382 -0
  39. package/build/http/station.js +15735 -0
  40. package/build/http/station.js.map +1 -0
  41. package/build/http/types.d.ts +1358 -0
  42. package/build/http/types.js +10333 -0
  43. package/build/http/types.js.map +1 -0
  44. package/build/http/utils.d.ts +89 -0
  45. package/build/http/utils.js +916 -0
  46. package/build/http/utils.js.map +1 -0
  47. package/build/index.d.ts +8 -0
  48. package/build/index.js +29 -0
  49. package/build/index.js.map +1 -0
  50. package/build/interfaces.d.ts +147 -0
  51. package/build/interfaces.js +7 -0
  52. package/build/interfaces.js.map +1 -0
  53. package/build/logging.d.ts +36 -0
  54. package/build/logging.js +119 -0
  55. package/build/logging.js.map +1 -0
  56. package/build/mqtt/interface.d.ts +6 -0
  57. package/build/mqtt/interface.js +3 -0
  58. package/build/mqtt/interface.js.map +1 -0
  59. package/build/mqtt/model.d.ts +24 -0
  60. package/build/mqtt/model.js +3 -0
  61. package/build/mqtt/model.js.map +1 -0
  62. package/build/mqtt/mqtt-eufy.crt +79 -0
  63. package/build/mqtt/proto/lock.proto +33 -0
  64. package/build/mqtt/service.d.ts +28 -0
  65. package/build/mqtt/service.js +196 -0
  66. package/build/mqtt/service.js.map +1 -0
  67. package/build/p2p/ble.d.ts +59 -0
  68. package/build/p2p/ble.js +281 -0
  69. package/build/p2p/ble.js.map +1 -0
  70. package/build/p2p/error.d.ts +49 -0
  71. package/build/p2p/error.js +69 -0
  72. package/build/p2p/error.js.map +1 -0
  73. package/build/p2p/index.d.ts +8 -0
  74. package/build/p2p/index.js +28 -0
  75. package/build/p2p/index.js.map +1 -0
  76. package/build/p2p/interfaces.d.ts +423 -0
  77. package/build/p2p/interfaces.js +3 -0
  78. package/build/p2p/interfaces.js.map +1 -0
  79. package/build/p2p/models.d.ts +295 -0
  80. package/build/p2p/models.js +3 -0
  81. package/build/p2p/models.js.map +1 -0
  82. package/build/p2p/session.d.ts +186 -0
  83. package/build/p2p/session.js +3737 -0
  84. package/build/p2p/session.js.map +1 -0
  85. package/build/p2p/talkback.d.ts +8 -0
  86. package/build/p2p/talkback.js +23 -0
  87. package/build/p2p/talkback.js.map +1 -0
  88. package/build/p2p/types.d.ts +1164 -0
  89. package/build/p2p/types.js +1219 -0
  90. package/build/p2p/types.js.map +1 -0
  91. package/build/p2p/utils.d.ts +72 -0
  92. package/build/p2p/utils.js +865 -0
  93. package/build/p2p/utils.js.map +1 -0
  94. package/build/push/client.d.ts +49 -0
  95. package/build/push/client.js +344 -0
  96. package/build/push/client.js.map +1 -0
  97. package/build/push/error.d.ts +73 -0
  98. package/build/push/error.js +101 -0
  99. package/build/push/error.js.map +1 -0
  100. package/build/push/index.d.ts +6 -0
  101. package/build/push/index.js +26 -0
  102. package/build/push/index.js.map +1 -0
  103. package/build/push/interfaces.d.ts +19 -0
  104. package/build/push/interfaces.js +3 -0
  105. package/build/push/interfaces.js.map +1 -0
  106. package/build/push/models.d.ts +328 -0
  107. package/build/push/models.js +38 -0
  108. package/build/push/models.js.map +1 -0
  109. package/build/push/parser.d.ts +25 -0
  110. package/build/push/parser.js +231 -0
  111. package/build/push/parser.js.map +1 -0
  112. package/build/push/proto/checkin.proto +266 -0
  113. package/build/push/proto/mcs.proto +328 -0
  114. package/build/push/service.d.ts +46 -0
  115. package/build/push/service.js +965 -0
  116. package/build/push/service.js.map +1 -0
  117. package/build/push/types.d.ts +220 -0
  118. package/build/push/types.js +244 -0
  119. package/build/push/types.js.map +1 -0
  120. package/build/push/utils.d.ts +7 -0
  121. package/build/push/utils.js +116 -0
  122. package/build/push/utils.js.map +1 -0
  123. package/build/utils.d.ts +115 -0
  124. package/build/utils.js +438 -0
  125. package/build/utils.js.map +1 -0
  126. package/eslint.config.mts +68 -0
  127. package/jest.config.js +14 -0
  128. package/package.json +85 -0
  129. package/scripts/cut_release.sh +31 -0
@@ -0,0 +1,965 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.PushNotificationService = void 0;
37
+ const qs = __importStar(require("qs"));
38
+ const tiny_typed_emitter_1 = require("tiny-typed-emitter");
39
+ const utils_1 = require("./utils");
40
+ const client_1 = require("./client");
41
+ const device_1 = require("../http/device");
42
+ const types_1 = require("../http/types");
43
+ const utils_2 = require("../http/utils");
44
+ const utils_3 = require("../utils");
45
+ const error_1 = require("./error");
46
+ const error_2 = require("../error");
47
+ const logging_1 = require("../logging");
48
+ const _1 = require(".");
49
+ const station_1 = require("../http/station");
50
+ class PushNotificationService extends tiny_typed_emitter_1.TypedEmitter {
51
+ APP_PACKAGE = "com.oceanwing.battery.cam";
52
+ APP_ID = "1:348804314802:android:440a6773b3620da7";
53
+ APP_SENDER_ID = "348804314802";
54
+ APP_CERT_SHA1 = "F051262F9F99B638F3C76DE349830638555B4A0A";
55
+ FCM_PROJECT_ID = "batterycam-3250a";
56
+ GOOGLE_API_KEY = "AIzaSyCSz1uxGrHXsEktm7O3_wv-uLGpC9BvXR8";
57
+ AUTH_VERSION = "FIS_v2";
58
+ pushClient;
59
+ credentialsTimeout;
60
+ retryTimeout;
61
+ retryDelay = 0;
62
+ credentials;
63
+ persistentIds = [];
64
+ connected = false;
65
+ connecting = false;
66
+ got;
67
+ constructor() {
68
+ super();
69
+ }
70
+ async loadLibraries() {
71
+ const { default: got } = await import("got");
72
+ this.got = got;
73
+ }
74
+ static async initialize() {
75
+ const service = new PushNotificationService();
76
+ await service.loadLibraries();
77
+ return service;
78
+ }
79
+ buildExpiresAt(expiresIn) {
80
+ if (expiresIn.endsWith("ms")) {
81
+ return new Date().getTime() + Number.parseInt(expiresIn.substring(0, expiresIn.length - 2));
82
+ }
83
+ else if (expiresIn.endsWith("s")) {
84
+ return new Date().getTime() + Number.parseInt(expiresIn.substring(0, expiresIn.length - 1)) * 1000;
85
+ }
86
+ throw new error_1.UnknownExpiryFormaError("Unknown expiresIn-format", { context: { format: expiresIn } });
87
+ }
88
+ async registerFid(fid) {
89
+ const url = `https://firebaseinstallations.googleapis.com/v1/projects/${this.FCM_PROJECT_ID}/installations`;
90
+ try {
91
+ const response = await this.got(url, {
92
+ method: "post",
93
+ json: {
94
+ fid: fid,
95
+ appId: `${this.APP_ID}`,
96
+ authVersion: `${this.AUTH_VERSION}`,
97
+ sdkVersion: "a:16.3.1",
98
+ },
99
+ headers: {
100
+ "X-Android-Package": `${this.APP_PACKAGE}`,
101
+ "X-Android-Cert": `${this.APP_CERT_SHA1}`,
102
+ "x-goog-api-key": `${this.GOOGLE_API_KEY}`,
103
+ },
104
+ responseType: "json",
105
+ http2: false,
106
+ throwHttpErrors: false,
107
+ retry: {
108
+ limit: 3,
109
+ methods: ["POST"],
110
+ },
111
+ hooks: {
112
+ beforeError: [
113
+ (error) => {
114
+ const { response, options } = error;
115
+ const statusCode = response?.statusCode || 0;
116
+ const { method, url, prefixUrl } = options;
117
+ const shortUrl = (0, utils_3.getShortUrl)(typeof url === "string" ? new URL(url) : url === undefined ? new URL("") : url, typeof prefixUrl === "string" ? prefixUrl : prefixUrl.toString());
118
+ const body = response?.body ? response.body : error.message;
119
+ if (response?.body) {
120
+ error.name = "RegisterFidError";
121
+ error.message = `${statusCode} ${method} ${shortUrl}\n${body}`;
122
+ }
123
+ return error;
124
+ },
125
+ ],
126
+ },
127
+ });
128
+ if (response.statusCode == 200) {
129
+ const result = response.body;
130
+ return {
131
+ ...result,
132
+ authToken: {
133
+ ...result.authToken,
134
+ expiresAt: this.buildExpiresAt(result.authToken.expiresIn),
135
+ },
136
+ };
137
+ }
138
+ else {
139
+ logging_1.rootPushLogger.error("Register FID - Status return code not 200", {
140
+ status: response.statusCode,
141
+ statusText: response.statusMessage,
142
+ data: response.body,
143
+ });
144
+ throw new error_1.FidRegistrationFailedError("FID registration failed", {
145
+ context: { status: response.statusCode, statusText: response.statusMessage, data: response.body },
146
+ });
147
+ }
148
+ }
149
+ catch (err) {
150
+ const error = (0, error_2.ensureError)(err);
151
+ logging_1.rootPushLogger.error("Register FID - Generic Error", { error: (0, utils_3.getError)(error) });
152
+ throw new error_1.FidRegistrationFailedError("FID registration failed", { cause: error, context: { fid: fid } });
153
+ }
154
+ }
155
+ async renewFidToken(fid, refreshToken) {
156
+ const url = `https://firebaseinstallations.googleapis.com/v1/projects/${this.FCM_PROJECT_ID}/installations/${fid}/authTokens:generate`;
157
+ try {
158
+ const response = await this.got(url, {
159
+ method: "post",
160
+ json: {
161
+ installation: {
162
+ appId: `${this.APP_ID}`,
163
+ sdkVersion: "a:16.3.1",
164
+ },
165
+ },
166
+ headers: {
167
+ "X-Android-Package": `${this.APP_PACKAGE}`,
168
+ "X-Android-Cert": `${this.APP_CERT_SHA1}`,
169
+ "x-goog-api-key": `${this.GOOGLE_API_KEY}`,
170
+ Authorization: `${this.AUTH_VERSION} ${refreshToken}`,
171
+ },
172
+ responseType: "json",
173
+ http2: false,
174
+ throwHttpErrors: false,
175
+ retry: {
176
+ limit: 3,
177
+ methods: ["POST"],
178
+ },
179
+ hooks: {
180
+ beforeError: [
181
+ (error) => {
182
+ const { response, options } = error;
183
+ const statusCode = response?.statusCode || 0;
184
+ const { method, url, prefixUrl } = options;
185
+ const shortUrl = (0, utils_3.getShortUrl)(typeof url === "string" ? new URL(url) : url === undefined ? new URL("") : url, typeof prefixUrl === "string" ? prefixUrl : prefixUrl.toString());
186
+ const body = response?.body ? response.body : error.message;
187
+ if (response?.body) {
188
+ error.name = "RenewFidTokenError";
189
+ error.message = `${statusCode} ${method} ${shortUrl}\n${body}`;
190
+ }
191
+ return error;
192
+ },
193
+ ],
194
+ },
195
+ });
196
+ if (response.statusCode == 200) {
197
+ const result = response.body;
198
+ return {
199
+ ...result,
200
+ expiresAt: this.buildExpiresAt(result.expiresIn),
201
+ };
202
+ }
203
+ else {
204
+ logging_1.rootPushLogger.error("Renew FID Token - Status return code not 200", {
205
+ status: response.statusCode,
206
+ statusText: response.statusMessage,
207
+ data: response.body,
208
+ });
209
+ throw new error_1.RenewFidTokenFailedError("FID Token renewal failed", {
210
+ context: { status: response.statusCode, statusText: response.statusMessage, data: response.body },
211
+ });
212
+ }
213
+ }
214
+ catch (err) {
215
+ const error = (0, error_2.ensureError)(err);
216
+ logging_1.rootPushLogger.error("Renew FID Token - Generic Error", { error: (0, utils_3.getError)(error) });
217
+ throw new error_1.RenewFidTokenFailedError("FID Token renewal failed", {
218
+ cause: error,
219
+ context: { fid: fid, refreshToken: refreshToken },
220
+ });
221
+ }
222
+ }
223
+ async createPushCredentials() {
224
+ const generatedFid = (0, utils_1.generateFid)();
225
+ return await this.registerFid(generatedFid)
226
+ .then(async (registerFidResponse) => {
227
+ const checkinResponse = await this.executeCheckin();
228
+ return {
229
+ fidResponse: registerFidResponse,
230
+ checkinResponse: checkinResponse,
231
+ };
232
+ })
233
+ .then(async (result) => {
234
+ const registerGcmResponse = await this.registerGcm(result.fidResponse, result.checkinResponse);
235
+ return {
236
+ ...result,
237
+ gcmResponse: registerGcmResponse,
238
+ };
239
+ })
240
+ .catch((err) => {
241
+ const error = (0, error_2.ensureError)(err);
242
+ throw error;
243
+ });
244
+ }
245
+ async renewPushCredentials(credentials) {
246
+ return await this.renewFidToken(credentials.fidResponse.fid, credentials.fidResponse.refreshToken)
247
+ .then(async (response) => {
248
+ credentials.fidResponse.authToken = response;
249
+ return await this.executeCheckin();
250
+ })
251
+ .then(async (response) => {
252
+ const registerGcmResponse = await this.registerGcm(credentials.fidResponse, response);
253
+ return {
254
+ fidResponse: credentials.fidResponse,
255
+ checkinResponse: response,
256
+ gcmResponse: registerGcmResponse,
257
+ };
258
+ })
259
+ .catch(() => {
260
+ return this.createPushCredentials();
261
+ });
262
+ }
263
+ async loginPushCredentials(credentials) {
264
+ logging_1.rootPushLogger.info("fidresponse", credentials.fidResponse);
265
+ return await this.executeCheckin()
266
+ .then(async (response) => {
267
+ const registerGcmResponse = await this.registerGcm(credentials.fidResponse, response);
268
+ return {
269
+ fidResponse: credentials.fidResponse,
270
+ checkinResponse: response,
271
+ gcmResponse: registerGcmResponse,
272
+ };
273
+ })
274
+ .catch(() => {
275
+ return this.createPushCredentials();
276
+ });
277
+ }
278
+ async executeCheckin() {
279
+ const url = "https://android.clients.google.com/checkin";
280
+ try {
281
+ const buffer = await (0, utils_1.buildCheckinRequest)();
282
+ const response = await this.got(url, {
283
+ method: "post",
284
+ body: Buffer.from(buffer),
285
+ headers: {
286
+ "Content-Type": "application/x-protobuf",
287
+ },
288
+ responseType: "buffer",
289
+ http2: false,
290
+ throwHttpErrors: false,
291
+ retry: {
292
+ limit: 3,
293
+ methods: ["POST"],
294
+ },
295
+ hooks: {
296
+ beforeError: [
297
+ (error) => {
298
+ const { response, options } = error;
299
+ const statusCode = response?.statusCode || 0;
300
+ const { method, url, prefixUrl } = options;
301
+ const shortUrl = (0, utils_3.getShortUrl)(typeof url === "string" ? new URL(url) : url === undefined ? new URL("") : url, typeof prefixUrl === "string" ? prefixUrl : prefixUrl.toString());
302
+ const body = response?.body ? response.body : error.message;
303
+ if (response?.body) {
304
+ error.name = "ExecuteCheckInError";
305
+ error.message = `${statusCode} ${method} ${shortUrl}\n${body}`;
306
+ }
307
+ return error;
308
+ },
309
+ ],
310
+ },
311
+ });
312
+ if (response.statusCode == 200) {
313
+ return await (0, utils_1.parseCheckinResponse)(response.body);
314
+ }
315
+ else {
316
+ logging_1.rootPushLogger.error("Check in - Status return code not 200", {
317
+ status: response.statusCode,
318
+ statusText: response.statusMessage,
319
+ data: response.body,
320
+ });
321
+ throw new error_1.ExecuteCheckInError("Google checkin failed", {
322
+ context: { status: response.statusCode, statusText: response.statusMessage, data: response.body },
323
+ });
324
+ }
325
+ }
326
+ catch (err) {
327
+ const error = (0, error_2.ensureError)(err);
328
+ logging_1.rootPushLogger.error("Check in - Generic Error", { error: (0, utils_3.getError)(error) });
329
+ throw new error_1.ExecuteCheckInError("Google checkin failed", { cause: error });
330
+ }
331
+ }
332
+ async registerGcm(fidInstallationResponse, checkinResponse) {
333
+ const url = "https://android.clients.google.com/c2dm/register3";
334
+ const androidId = checkinResponse.androidId;
335
+ const fid = fidInstallationResponse.fid;
336
+ const securityToken = checkinResponse.securityToken;
337
+ const retry = 5;
338
+ try {
339
+ for (let retry_count = 1; retry_count <= retry; retry_count++) {
340
+ logging_1.rootPushLogger.debug(`Register GCM - Attempt ${retry_count} of ${retry}`, {
341
+ androidId: androidId,
342
+ fid: fid,
343
+ securityToken: securityToken,
344
+ });
345
+ const response = await this.got(url, {
346
+ method: "post",
347
+ body: qs.stringify({
348
+ "X-subtype": `${this.APP_SENDER_ID}`,
349
+ sender: `${this.APP_SENDER_ID}`,
350
+ "X-app_ver": "741",
351
+ "X-osv": "25",
352
+ "X-cliv": "fiid-20.2.0",
353
+ "X-gmsv": "201216023",
354
+ "X-appid": `${fid}`,
355
+ "X-scope": "*",
356
+ "X-Goog-Firebase-Installations-Auth": `${fidInstallationResponse.authToken.token}`,
357
+ "X-gmp_app_id": `${this.APP_ID}`,
358
+ "X-Firebase-Client": "fire-abt/17.1.1+fire-installations/16.3.1+fire-android/+fire-analytics/17.4.2+fire-iid/20.2.0+fire-rc/17.0.0+fire-fcm/20.2.0+fire-cls/17.0.0+fire-cls-ndk/17.0.0+fire-core/19.3.0",
359
+ "X-firebase-app-name-hash": "R1dAH9Ui7M-ynoznwBdw01tLxhI",
360
+ "X-Firebase-Client-Log-Type": "1",
361
+ "X-app_ver_name": "v2.2.2_741",
362
+ app: `${this.APP_PACKAGE}`,
363
+ device: `${androidId}`,
364
+ app_ver: "741",
365
+ info: "g3EMJXXElLwaQEb1aBJ6XhxiHjPTUxc",
366
+ gcm_ver: "201216023",
367
+ plat: "0",
368
+ cert: `${this.APP_CERT_SHA1}`,
369
+ target_ver: "28",
370
+ }),
371
+ headers: {
372
+ Authorization: `AidLogin ${androidId}:${securityToken}`,
373
+ app: `${this.APP_PACKAGE}`,
374
+ gcm_ver: "201216023",
375
+ "User-Agent": "Android-GCM/1.5",
376
+ "content-type": "application/x-www-form-urlencoded",
377
+ },
378
+ http2: false,
379
+ throwHttpErrors: false,
380
+ retry: {
381
+ limit: 3,
382
+ methods: ["POST"],
383
+ },
384
+ hooks: {
385
+ beforeError: [
386
+ (error) => {
387
+ const { response, options } = error;
388
+ const statusCode = response?.statusCode || 0;
389
+ const { method, url, prefixUrl } = options;
390
+ const shortUrl = (0, utils_3.getShortUrl)(typeof url === "string" ? new URL(url) : url === undefined ? new URL("") : url, typeof prefixUrl === "string" ? prefixUrl : prefixUrl.toString());
391
+ const body = response?.body ? response.body : error.message;
392
+ if (response?.body) {
393
+ error.name = "RegisterGcmError";
394
+ error.message = `${statusCode} ${method} ${shortUrl}\n${body}`;
395
+ }
396
+ return error;
397
+ },
398
+ ],
399
+ },
400
+ });
401
+ if (response.statusCode == 200) {
402
+ const result = response.body.split("=");
403
+ if (result[0] == "Error") {
404
+ logging_1.rootPushLogger.debug("GCM register error, retry...", {
405
+ retry: retry,
406
+ retryCount: retry_count,
407
+ response: response.body,
408
+ });
409
+ if (retry_count == retry)
410
+ throw new error_1.RegisterGcmError("Max GCM registration retries reached", {
411
+ context: { message: result[1], retry: retry, retryCount: retry_count },
412
+ });
413
+ }
414
+ else {
415
+ return {
416
+ token: result[1],
417
+ };
418
+ }
419
+ }
420
+ else {
421
+ logging_1.rootPushLogger.error("Register GCM - Status return code not 200", {
422
+ status: response.statusCode,
423
+ statusText: response.statusMessage,
424
+ data: response.body,
425
+ });
426
+ throw new error_1.RegisterGcmError("Google register to GCM failed", {
427
+ context: { status: response.statusCode, statusText: response.statusMessage, data: response.body },
428
+ });
429
+ }
430
+ await (0, utils_1.sleep)(10000 * retry_count);
431
+ }
432
+ throw new error_1.RegisterGcmError("Max GCM registration retries reached");
433
+ }
434
+ catch (err) {
435
+ const error = (0, error_2.ensureError)(err);
436
+ logging_1.rootPushLogger.error("Register GCM - Generic Error", { error: (0, utils_3.getError)(error) });
437
+ throw new error_1.RegisterGcmError("Google register to GCM failed", {
438
+ cause: error,
439
+ context: { fidInstallationResponse: fidInstallationResponse, checkinResponse: checkinResponse },
440
+ });
441
+ }
442
+ }
443
+ _normalizePushMessage(message) {
444
+ const normalizedMessage = {
445
+ name: "",
446
+ event_time: 0,
447
+ type: -1,
448
+ station_sn: "",
449
+ device_sn: "",
450
+ };
451
+ if (message.payload.payload) {
452
+ const payload = message.payload;
453
+ // CusPush
454
+ try {
455
+ normalizedMessage.type = Number.parseInt(payload.type);
456
+ }
457
+ catch (err) {
458
+ const error = (0, error_2.ensureError)(err);
459
+ logging_1.rootPushLogger.error(`Normalize push message - type - Error`, { error: (0, utils_3.getError)(error), message: message });
460
+ }
461
+ if (normalizedMessage.type in _1.ServerPushEvent) {
462
+ // server push notification
463
+ const serverPushData = payload.payload;
464
+ normalizedMessage.email = serverPushData.email;
465
+ normalizedMessage.person_name = serverPushData.nick_name;
466
+ normalizedMessage.verify_code = serverPushData.verify_code;
467
+ switch (normalizedMessage.type) {
468
+ case _1.ServerPushEvent.ALARM_NOTIFY:
469
+ case _1.ServerPushEvent.ALARM_GUEST_NOTIFY:
470
+ const alarmPushData = payload.payload;
471
+ normalizedMessage.device_sn = alarmPushData.device_sn;
472
+ normalizedMessage.station_sn = alarmPushData.station_sn;
473
+ normalizedMessage.alarm_status = alarmPushData.alarm_status;
474
+ normalizedMessage.alarm_action = alarmPushData.alarm_action_channel;
475
+ try {
476
+ normalizedMessage.alarm_type = Number.parseInt(alarmPushData.alarm_id);
477
+ }
478
+ catch (err) {
479
+ const error = (0, error_2.ensureError)(err);
480
+ logging_1.rootPushLogger.error(`Normalize push message - alarm_type - Error`, {
481
+ error: (0, utils_3.getError)(error),
482
+ message: message,
483
+ });
484
+ }
485
+ try {
486
+ normalizedMessage.event_time =
487
+ alarmPushData.alert_time !== undefined
488
+ ? (0, utils_1.convertTimestampMs)(alarmPushData.alert_time)
489
+ : Number.parseInt(alarmPushData.alert_time);
490
+ }
491
+ catch (err) {
492
+ const error = (0, error_2.ensureError)(err);
493
+ logging_1.rootPushLogger.error(`Normalize push message - event_time - Error`, {
494
+ error: (0, utils_3.getError)(error),
495
+ message: message,
496
+ });
497
+ }
498
+ break;
499
+ }
500
+ }
501
+ else {
502
+ try {
503
+ normalizedMessage.event_time =
504
+ payload.event_time !== undefined
505
+ ? (0, utils_1.convertTimestampMs)(Number.parseInt(payload.event_time))
506
+ : Number.parseInt(payload.event_time);
507
+ }
508
+ catch (err) {
509
+ const error = (0, error_2.ensureError)(err);
510
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPush - event_time - Error`, { error: (0, utils_3.getError)(error), message: message });
511
+ }
512
+ try {
513
+ normalizedMessage.push_time =
514
+ payload.push_time !== undefined
515
+ ? (0, utils_1.convertTimestampMs)(Number.parseInt(payload.push_time))
516
+ : Number.parseInt(payload.push_time);
517
+ }
518
+ catch (err) {
519
+ const error = (0, error_2.ensureError)(err);
520
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPush - push_time - Error`, { error: (0, utils_3.getError)(error), message: message });
521
+ }
522
+ normalizedMessage.station_sn = payload.station_sn;
523
+ normalizedMessage.title = payload.title;
524
+ normalizedMessage.content = payload.content;
525
+ if (normalizedMessage.type === types_1.DeviceType.FLOODLIGHT)
526
+ normalizedMessage.device_sn = payload.station_sn;
527
+ else
528
+ normalizedMessage.device_sn = payload.device_sn;
529
+ if ((0, utils_3.isEmpty)(normalizedMessage.device_sn) && !(0, utils_3.isEmpty)(normalizedMessage.station_sn)) {
530
+ normalizedMessage.device_sn = normalizedMessage.station_sn;
531
+ }
532
+ if (station_1.Station.isStationHomeBase3(normalizedMessage.type) ||
533
+ (normalizedMessage.station_sn.startsWith("T8030") && device_1.Device.isCamera(normalizedMessage.type))) {
534
+ const platformPushData = payload.payload;
535
+ normalizedMessage.name = platformPushData.name ? platformPushData.name : "";
536
+ normalizedMessage.channel = platformPushData.channel !== undefined ? platformPushData.channel : 0;
537
+ normalizedMessage.cipher = platformPushData.cipher !== undefined ? platformPushData.cipher : 0;
538
+ normalizedMessage.event_session =
539
+ platformPushData.session_id !== undefined ? platformPushData.session_id : "";
540
+ normalizedMessage.event_type =
541
+ platformPushData.a !== undefined ? platformPushData.a : platformPushData.event_type;
542
+ normalizedMessage.file_path = platformPushData.file_path !== undefined ? platformPushData.file_path : "";
543
+ normalizedMessage.pic_url = platformPushData.pic_url !== undefined ? platformPushData.pic_url : "";
544
+ normalizedMessage.push_count = platformPushData.push_count !== undefined ? platformPushData.push_count : 1;
545
+ normalizedMessage.notification_style = platformPushData.notification_style;
546
+ normalizedMessage.storage_type =
547
+ platformPushData.storage_type !== undefined ? platformPushData.storage_type : 1;
548
+ normalizedMessage.msg_type = platformPushData.msg_type;
549
+ normalizedMessage.person_name = platformPushData.nick_name;
550
+ normalizedMessage.person_id = platformPushData.person_id;
551
+ normalizedMessage.tfcard_status = platformPushData.tfcard_status;
552
+ normalizedMessage.user_type = platformPushData.user;
553
+ normalizedMessage.user_name = platformPushData.user_name;
554
+ normalizedMessage.station_guard_mode = platformPushData.arming;
555
+ normalizedMessage.station_current_mode = platformPushData.mode;
556
+ normalizedMessage.alarm_delay = platformPushData.alarm_delay;
557
+ normalizedMessage.sound_alarm =
558
+ platformPushData.alarm !== undefined ? (platformPushData.alarm === 1 ? true : false) : undefined;
559
+ }
560
+ else if (device_1.Device.isBatteryDoorbell(normalizedMessage.type) ||
561
+ device_1.Device.isWiredDoorbellDual(normalizedMessage.type)) {
562
+ const batteryDoorbellPushData = payload.payload;
563
+ normalizedMessage.name = batteryDoorbellPushData.name ? batteryDoorbellPushData.name : "";
564
+ //Get family face names from Doorbell Dual "Family Recognition" event
565
+ if (batteryDoorbellPushData.objects !== undefined) {
566
+ normalizedMessage.person_name =
567
+ batteryDoorbellPushData.objects.names !== undefined
568
+ ? batteryDoorbellPushData.objects.names.join(",")
569
+ : "";
570
+ }
571
+ if (normalizedMessage.person_name === "") {
572
+ normalizedMessage.person_name = batteryDoorbellPushData.nick_name;
573
+ }
574
+ normalizedMessage.channel =
575
+ batteryDoorbellPushData.channel !== undefined ? batteryDoorbellPushData.channel : 0;
576
+ normalizedMessage.cipher = batteryDoorbellPushData.cipher !== undefined ? batteryDoorbellPushData.cipher : 0;
577
+ normalizedMessage.event_session =
578
+ batteryDoorbellPushData.session_id !== undefined ? batteryDoorbellPushData.session_id : "";
579
+ normalizedMessage.event_type = batteryDoorbellPushData.event_type;
580
+ normalizedMessage.file_path =
581
+ batteryDoorbellPushData.file_path !== undefined &&
582
+ batteryDoorbellPushData.file_path !== "" &&
583
+ batteryDoorbellPushData.channel !== undefined
584
+ ? (0, utils_2.getAbsoluteFilePath)(normalizedMessage.type, batteryDoorbellPushData.channel, batteryDoorbellPushData.file_path)
585
+ : "";
586
+ normalizedMessage.pic_url =
587
+ batteryDoorbellPushData.pic_url !== undefined ? batteryDoorbellPushData.pic_url : "";
588
+ normalizedMessage.push_count =
589
+ batteryDoorbellPushData.push_count !== undefined ? batteryDoorbellPushData.push_count : 1;
590
+ normalizedMessage.notification_style = batteryDoorbellPushData.notification_style;
591
+ }
592
+ else if (device_1.Device.isIndoorCamera(normalizedMessage.type) ||
593
+ device_1.Device.isSoloCameras(normalizedMessage.type) ||
594
+ device_1.Device.isWallLightCam(normalizedMessage.type) ||
595
+ device_1.Device.isOutdoorPanAndTiltCamera(normalizedMessage.type) ||
596
+ device_1.Device.isFloodLightT8420X(normalizedMessage.type, normalizedMessage.device_sn) ||
597
+ (device_1.Device.isFloodLight(normalizedMessage.type) && normalizedMessage.type !== types_1.DeviceType.FLOODLIGHT)) {
598
+ const indoorPushData = payload.payload;
599
+ normalizedMessage.name = indoorPushData.name ? indoorPushData.name : "";
600
+ normalizedMessage.channel = indoorPushData.channel;
601
+ normalizedMessage.cipher = indoorPushData.cipher;
602
+ normalizedMessage.event_session = indoorPushData.session_id;
603
+ normalizedMessage.event_type = indoorPushData.event_type;
604
+ //normalizedMessage.file_path = indoorPushData.file_path !== undefined && indoorPushData.file_path !== "" && indoorPushData.channel !== undefined ? getAbsoluteFilePath(normalizedMessage.type, indoorPushData.channel, indoorPushData.file_path) : "";
605
+ normalizedMessage.file_path = indoorPushData.file_path;
606
+ normalizedMessage.pic_url = indoorPushData.pic_url !== undefined ? indoorPushData.pic_url : "";
607
+ normalizedMessage.push_count = indoorPushData.push_count !== undefined ? indoorPushData.push_count : 1;
608
+ normalizedMessage.notification_style = indoorPushData.notification_style;
609
+ normalizedMessage.msg_type = indoorPushData.msg_type;
610
+ normalizedMessage.timeout = indoorPushData.timeout;
611
+ normalizedMessage.tfcard_status = indoorPushData.tfcard_status;
612
+ normalizedMessage.storage_type = indoorPushData.storage_type !== undefined ? indoorPushData.storage_type : 1;
613
+ normalizedMessage.unique_id = indoorPushData.unique_id;
614
+ }
615
+ else if (device_1.Device.isSmartSafe(normalizedMessage.type)) {
616
+ const smartSafePushData = payload.payload;
617
+ normalizedMessage.event_type = smartSafePushData.event_type;
618
+ normalizedMessage.event_value = smartSafePushData.event_value;
619
+ /*
620
+ event_value: {
621
+ type: 3, 3/4
622
+ action: 1,
623
+ figure_id: 0,
624
+ user_id: 0
625
+ }
626
+ */
627
+ normalizedMessage.name = smartSafePushData.dev_name !== undefined ? smartSafePushData.dev_name : "";
628
+ /*normalizedMessage.short_user_id = smartSafePushData.short_user_id !== undefined ? smartSafePushData.short_user_id : "";
629
+ normalizedMessage.user_id = smartSafePushData.user_id !== undefined ? smartSafePushData.user_id : "";*/
630
+ }
631
+ else if (device_1.Device.isLock(normalizedMessage.type) && !device_1.Device.isLockWifiVideo(normalizedMessage.type)) {
632
+ const lockPushData = payload.payload;
633
+ normalizedMessage.event_type = lockPushData.event_type;
634
+ normalizedMessage.short_user_id = lockPushData.short_user_id !== undefined ? lockPushData.short_user_id : "";
635
+ normalizedMessage.user_id = lockPushData.user_id !== undefined ? lockPushData.user_id : "";
636
+ normalizedMessage.name = lockPushData.device_name !== undefined ? lockPushData.device_name : "";
637
+ normalizedMessage.person_name = lockPushData.nick_name !== undefined ? lockPushData.nick_name : "";
638
+ }
639
+ else if (device_1.Device.isLockWifiVideo(normalizedMessage.type)) {
640
+ const lockPushData = payload.payload;
641
+ normalizedMessage.event_type = lockPushData.event_type;
642
+ normalizedMessage.short_user_id = lockPushData.short_user_id !== undefined ? lockPushData.short_user_id : "";
643
+ normalizedMessage.user_id = lockPushData.user_id !== undefined ? lockPushData.user_id : "";
644
+ normalizedMessage.name = lockPushData.device_name !== undefined ? lockPushData.device_name : "";
645
+ normalizedMessage.person_name = lockPushData.nick_name !== undefined ? lockPushData.nick_name : "";
646
+ }
647
+ else if (device_1.Device.isGarageCamera(normalizedMessage.type)) {
648
+ const garageDoorPushData = payload.payload;
649
+ normalizedMessage.event_type = garageDoorPushData.event_type;
650
+ normalizedMessage.user_name = garageDoorPushData.user_name !== undefined ? garageDoorPushData.user_name : "";
651
+ normalizedMessage.door_id = garageDoorPushData.door_id !== undefined ? garageDoorPushData.door_id : -1;
652
+ normalizedMessage.name = garageDoorPushData.door_name !== undefined ? garageDoorPushData.door_name : "";
653
+ normalizedMessage.pic_url = garageDoorPushData.pic_url !== undefined ? garageDoorPushData.pic_url : "";
654
+ normalizedMessage.file_path = garageDoorPushData.file_path !== undefined ? garageDoorPushData.file_path : "";
655
+ normalizedMessage.storage_type =
656
+ garageDoorPushData.storage_type !== undefined ? garageDoorPushData.storage_type : 1;
657
+ normalizedMessage.power = garageDoorPushData.power !== undefined ? garageDoorPushData.power : undefined;
658
+ }
659
+ else {
660
+ const cusPushData = payload.payload;
661
+ normalizedMessage.name =
662
+ cusPushData.device_name && cusPushData.device_name !== null && cusPushData.device_name !== ""
663
+ ? cusPushData.device_name
664
+ : cusPushData.n
665
+ ? cusPushData.n
666
+ : cusPushData.name
667
+ ? cusPushData.name
668
+ : "";
669
+ normalizedMessage.channel = cusPushData.c ? cusPushData.c : cusPushData.channel;
670
+ normalizedMessage.cipher = cusPushData.k ? cusPushData.k : cusPushData.cipher;
671
+ normalizedMessage.event_session = cusPushData.session_id;
672
+ normalizedMessage.event_type = cusPushData.a ? cusPushData.a : cusPushData.event_type;
673
+ normalizedMessage.file_path =
674
+ cusPushData.c !== undefined && cusPushData.p !== undefined && cusPushData.p !== ""
675
+ ? (0, utils_2.getAbsoluteFilePath)(normalizedMessage.type, cusPushData.c, cusPushData.p)
676
+ : cusPushData.file_path
677
+ ? cusPushData.file_path
678
+ : "";
679
+ normalizedMessage.pic_url = cusPushData.pic_url !== undefined ? cusPushData.pic_url : "";
680
+ normalizedMessage.push_count = cusPushData.push_count !== undefined ? cusPushData.push_count : 1;
681
+ normalizedMessage.notification_style = cusPushData.notification_style;
682
+ normalizedMessage.tfcard_status = cusPushData.tfcard;
683
+ normalizedMessage.alarm_delay_type = cusPushData.alarm_type;
684
+ normalizedMessage.alarm_delay = cusPushData.alarm_delay;
685
+ normalizedMessage.alarm_type = cusPushData.type;
686
+ normalizedMessage.sound_alarm =
687
+ cusPushData.alarm !== undefined ? (cusPushData.alarm === 1 ? true : false) : undefined;
688
+ normalizedMessage.user_name = cusPushData.user_name;
689
+ normalizedMessage.user_type = cusPushData.user;
690
+ normalizedMessage.user_id = cusPushData.user_id;
691
+ normalizedMessage.short_user_id = cusPushData.short_user_id;
692
+ normalizedMessage.station_guard_mode = cusPushData.arming;
693
+ normalizedMessage.station_current_mode = cusPushData.mode;
694
+ normalizedMessage.person_name =
695
+ cusPushData.f && cusPushData.f !== ""
696
+ ? cusPushData.f
697
+ : cusPushData.nick_name && cusPushData.nick_name
698
+ ? cusPushData.nick_name
699
+ : "";
700
+ normalizedMessage.sensor_open =
701
+ cusPushData.e !== undefined ? (cusPushData.e == "1" ? true : false) : undefined;
702
+ normalizedMessage.device_online =
703
+ cusPushData.m !== undefined ? (cusPushData.m === 1 ? true : false) : undefined;
704
+ try {
705
+ normalizedMessage.fetch_id = cusPushData.i !== undefined ? Number.parseInt(cusPushData.i) : undefined;
706
+ }
707
+ catch (err) {
708
+ const error = (0, error_2.ensureError)(err);
709
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPushData - fetch_id - Error`, { error: (0, utils_3.getError)(error), message: message });
710
+ }
711
+ normalizedMessage.sense_id = cusPushData.j;
712
+ normalizedMessage.battery_powered =
713
+ cusPushData.batt_powered !== undefined ? (cusPushData.batt_powered === 1 ? true : false) : undefined;
714
+ try {
715
+ normalizedMessage.battery_low =
716
+ cusPushData.bat_low !== undefined ? Number.parseInt(cusPushData.bat_low) : undefined;
717
+ }
718
+ catch (err) {
719
+ const error = (0, error_2.ensureError)(err);
720
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPushData - battery_low - Error`, { error: (0, utils_3.getError)(error), message: message });
721
+ }
722
+ normalizedMessage.storage_type = cusPushData.storage_type !== undefined ? cusPushData.storage_type : 1;
723
+ normalizedMessage.unique_id = cusPushData.unique_id;
724
+ normalizedMessage.automation_id = cusPushData.automation_id;
725
+ normalizedMessage.click_action = cusPushData.click_action;
726
+ normalizedMessage.news_id = cusPushData.news_id;
727
+ normalizedMessage.msg_type = cusPushData.msg_type;
728
+ if (device_1.Device.isStarlight4GLTE(normalizedMessage.type)) {
729
+ if (cusPushData.channel && cusPushData.channel !== null && cusPushData.channel !== undefined) {
730
+ normalizedMessage.channel = cusPushData.channel;
731
+ }
732
+ if (cusPushData.cipher && cusPushData.cipher !== null && cusPushData.cipher !== undefined) {
733
+ normalizedMessage.cipher = cusPushData.cipher;
734
+ }
735
+ if (cusPushData.event_type && cusPushData.event_type !== null && cusPushData.event_type !== undefined) {
736
+ normalizedMessage.event_type = cusPushData.event_type;
737
+ }
738
+ if (cusPushData.file_path && cusPushData.file_path !== null && cusPushData.file_path !== undefined) {
739
+ normalizedMessage.file_path = cusPushData.file_path;
740
+ }
741
+ normalizedMessage.msg_type = cusPushData.msg_type;
742
+ }
743
+ else if (device_1.Device.isSmartDrop(normalizedMessage.type)) {
744
+ try {
745
+ normalizedMessage.open = cusPushData.e !== undefined ? Number.parseInt(cusPushData.e) : 0;
746
+ }
747
+ catch (err) {
748
+ const error = (0, error_2.ensureError)(err);
749
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPushData - open - Error`, { error: (0, utils_3.getError)(error), message: message });
750
+ }
751
+ try {
752
+ normalizedMessage.openType = cusPushData.r !== undefined ? Number.parseInt(cusPushData.r) : 0;
753
+ }
754
+ catch (err) {
755
+ const error = (0, error_2.ensureError)(err);
756
+ logging_1.rootPushLogger.error(`Normalize push message - Type ${types_1.DeviceType[normalizedMessage.type]} CusPushData - openType - Error`, { error: (0, utils_3.getError)(error), message: message });
757
+ }
758
+ normalizedMessage.person_name = cusPushData.p;
759
+ normalizedMessage.pin = cusPushData.u;
760
+ normalizedMessage.channel = cusPushData.channel !== undefined ? cusPushData.channel : 0;
761
+ normalizedMessage.cipher = cusPushData.cipher !== undefined ? cusPushData.cipher : 0;
762
+ normalizedMessage.event_session = cusPushData.session_id !== undefined ? cusPushData.session_id : "";
763
+ normalizedMessage.file_path = cusPushData.file_path !== undefined ? cusPushData.file_path : "";
764
+ }
765
+ }
766
+ }
767
+ }
768
+ else if (message.payload.doorbell !== undefined) {
769
+ const doorbellPushData = (0, utils_3.parseJSON)(message.payload.doorbell, logging_1.rootPushLogger);
770
+ if (doorbellPushData !== undefined) {
771
+ normalizedMessage.name = "Doorbell";
772
+ normalizedMessage.type = 5;
773
+ normalizedMessage.event_time =
774
+ doorbellPushData.create_time !== undefined
775
+ ? (0, utils_1.convertTimestampMs)(doorbellPushData.create_time)
776
+ : doorbellPushData.create_time;
777
+ normalizedMessage.station_sn = doorbellPushData.device_sn;
778
+ normalizedMessage.device_sn = doorbellPushData.device_sn;
779
+ normalizedMessage.title = doorbellPushData.title;
780
+ normalizedMessage.content = doorbellPushData.content;
781
+ normalizedMessage.push_time =
782
+ doorbellPushData.event_time !== undefined
783
+ ? (0, utils_1.convertTimestampMs)(doorbellPushData.event_time)
784
+ : doorbellPushData.event_time;
785
+ normalizedMessage.channel = doorbellPushData.channel;
786
+ normalizedMessage.cipher = doorbellPushData.cipher;
787
+ normalizedMessage.event_session = doorbellPushData.event_session;
788
+ normalizedMessage.event_type = doorbellPushData.event_type;
789
+ normalizedMessage.file_path = doorbellPushData.file_path;
790
+ normalizedMessage.pic_url = doorbellPushData.pic_url;
791
+ normalizedMessage.push_count = doorbellPushData.push_count !== undefined ? doorbellPushData.push_count : 1;
792
+ normalizedMessage.doorbell_url = doorbellPushData.url;
793
+ normalizedMessage.doorbell_url_ex = doorbellPushData.url_ex;
794
+ normalizedMessage.doorbell_video_url = doorbellPushData.video_url;
795
+ }
796
+ }
797
+ return normalizedMessage;
798
+ }
799
+ onMessage(message) {
800
+ logging_1.rootPushLogger.debug("Raw push message received", { message: message });
801
+ this.emit("raw message", message);
802
+ const normalizedMessage = this._normalizePushMessage(message);
803
+ logging_1.rootPushLogger.debug("Normalized push message received", { message: normalizedMessage });
804
+ this.emit("message", normalizedMessage);
805
+ }
806
+ getCurrentPushRetryDelay() {
807
+ const delay = this.retryDelay == 0 ? 5000 : this.retryDelay;
808
+ if (this.retryDelay < 60000)
809
+ this.retryDelay += 10000;
810
+ if (this.retryDelay >= 60000 && this.retryDelay < 600000)
811
+ this.retryDelay += 60000;
812
+ return delay;
813
+ }
814
+ setCredentials(credentials) {
815
+ this.credentials = credentials;
816
+ }
817
+ getCredentials() {
818
+ return this.credentials;
819
+ }
820
+ setPersistentIds(persistentIds) {
821
+ this.persistentIds = persistentIds;
822
+ }
823
+ getPersistentIds() {
824
+ return this.persistentIds;
825
+ }
826
+ async _open(renew = false, forceNew = false) {
827
+ if (forceNew ||
828
+ !this.credentials ||
829
+ Object.keys(this.credentials).length === 0 ||
830
+ (this.credentials &&
831
+ this.credentials.fidResponse &&
832
+ new Date().getTime() >= this.credentials.fidResponse.authToken.expiresAt)) {
833
+ logging_1.rootPushLogger.debug(`Create new push credentials...`, { credentials: this.credentials, renew: renew });
834
+ this.credentials = await this.createPushCredentials().catch((err) => {
835
+ const error = (0, error_2.ensureError)(err);
836
+ logging_1.rootPushLogger.error("Create push credentials Error", {
837
+ error: (0, utils_3.getError)(error),
838
+ credentials: this.credentials,
839
+ renew: renew,
840
+ });
841
+ return undefined;
842
+ });
843
+ }
844
+ else if (this.credentials && renew) {
845
+ logging_1.rootPushLogger.debug(`Renew push credentials...`, { credentials: this.credentials, renew: renew });
846
+ this.credentials = await this.renewPushCredentials(this.credentials).catch((err) => {
847
+ const error = (0, error_2.ensureError)(err);
848
+ logging_1.rootPushLogger.error("Push credentials renew Error", {
849
+ error: (0, utils_3.getError)(error),
850
+ credentials: this.credentials,
851
+ renew: renew,
852
+ });
853
+ return undefined;
854
+ });
855
+ }
856
+ else {
857
+ logging_1.rootPushLogger.debug(`Login with previous push credentials...`, { credentials: this.credentials });
858
+ this.credentials = await this.loginPushCredentials(this.credentials).catch((err) => {
859
+ const error = (0, error_2.ensureError)(err);
860
+ logging_1.rootPushLogger.error("Push credentials login Error", {
861
+ error: (0, utils_3.getError)(error),
862
+ credentials: this.credentials,
863
+ renew: renew,
864
+ });
865
+ return undefined;
866
+ });
867
+ }
868
+ if (this.credentials) {
869
+ this.emit("credential", this.credentials);
870
+ logging_1.rootPushLogger.debug("Push notification token received", {
871
+ token: this.credentials.gcmResponse.token,
872
+ credentials: this.credentials,
873
+ });
874
+ this.clearCredentialsTimeout();
875
+ this.credentialsTimeout = setTimeout(async () => {
876
+ logging_1.rootPushLogger.info("Push notification token is expiring, renew it.");
877
+ await this._open(true);
878
+ }, this.credentials.fidResponse.authToken.expiresAt - new Date().getTime() - 60000);
879
+ if (this.pushClient) {
880
+ this.pushClient.removeAllListeners();
881
+ }
882
+ logging_1.rootPushLogger.debug("Init PushClient with credentials", { credentials: this.credentials });
883
+ this.pushClient = await client_1.PushClient.init({
884
+ androidId: this.credentials.checkinResponse.androidId,
885
+ securityToken: this.credentials.checkinResponse.securityToken,
886
+ });
887
+ if (this.persistentIds)
888
+ this.pushClient.setPersistentIds(this.persistentIds);
889
+ const token = this.credentials.gcmResponse.token;
890
+ this.pushClient.on("connect", () => {
891
+ this.emit("connect", token);
892
+ this.connected = true;
893
+ this.connecting = false;
894
+ });
895
+ this.pushClient.on("close", () => {
896
+ this.emit("close");
897
+ this.connected = false;
898
+ this.connecting = false;
899
+ });
900
+ this.pushClient.on("message", (msg) => this.onMessage(msg));
901
+ this.pushClient.connect();
902
+ }
903
+ else {
904
+ this.emit("close");
905
+ this.connected = false;
906
+ this.connecting = false;
907
+ logging_1.rootPushLogger.error("Push notifications are disabled, because the registration failed!", {
908
+ credentials: this.credentials,
909
+ renew: renew,
910
+ });
911
+ }
912
+ }
913
+ async open() {
914
+ if (!this.connecting && !this.connected) {
915
+ this.connecting = true;
916
+ await this._open(false, true).catch((err) => {
917
+ const error = (0, error_2.ensureError)(err);
918
+ logging_1.rootPushLogger.error(`Got exception trying to initialize push notifications`, {
919
+ error: (0, utils_3.getError)(error),
920
+ credentials: this.credentials,
921
+ });
922
+ });
923
+ if (!this.credentials) {
924
+ this.clearRetryTimeout();
925
+ const delay = this.getCurrentPushRetryDelay();
926
+ logging_1.rootPushLogger.info(`Retry to register/login for push notification in ${delay / 1000} seconds...`);
927
+ this.retryTimeout = setTimeout(async () => {
928
+ logging_1.rootPushLogger.info(`Retry to register/login for push notification`);
929
+ await this.open();
930
+ }, delay);
931
+ }
932
+ else {
933
+ this.resetRetryTimeout();
934
+ this.emit("credential", this.credentials);
935
+ }
936
+ }
937
+ return this.credentials;
938
+ }
939
+ close() {
940
+ this.resetRetryTimeout();
941
+ this.clearCredentialsTimeout();
942
+ this.pushClient?.close();
943
+ }
944
+ clearCredentialsTimeout() {
945
+ if (this.credentialsTimeout) {
946
+ clearTimeout(this.credentialsTimeout);
947
+ this.credentialsTimeout = undefined;
948
+ }
949
+ }
950
+ clearRetryTimeout() {
951
+ if (this.retryTimeout) {
952
+ clearTimeout(this.retryTimeout);
953
+ this.retryTimeout = undefined;
954
+ }
955
+ }
956
+ resetRetryTimeout() {
957
+ this.clearRetryTimeout();
958
+ this.retryDelay = 0;
959
+ }
960
+ isConnected() {
961
+ return this.connected;
962
+ }
963
+ }
964
+ exports.PushNotificationService = PushNotificationService;
965
+ //# sourceMappingURL=service.js.map