node-miio 0.0.0-dev-20250810-f1674d0

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 (104) hide show
  1. package/.editorconfig +21 -0
  2. package/.eslintrc +32 -0
  3. package/.github/workflows/build.yml +50 -0
  4. package/.github/workflows/codecov.yml +35 -0
  5. package/.github/workflows/codeql.yml +24 -0
  6. package/.github/workflows/publish-dev-from-main.yml +92 -0
  7. package/.github/workflows/publish-release-to-npm.yml +48 -0
  8. package/CONTRIBUTING.md +104 -0
  9. package/LICENSE.md +20 -0
  10. package/README.md +216 -0
  11. package/cli/commands/configure.js +69 -0
  12. package/cli/commands/control.js +54 -0
  13. package/cli/commands/discover.js +36 -0
  14. package/cli/commands/inspect.js +197 -0
  15. package/cli/commands/protocol/call.js +66 -0
  16. package/cli/commands/protocol/json-dump.js +52 -0
  17. package/cli/commands/protocol/packet.js +29 -0
  18. package/cli/commands/protocol.js +8 -0
  19. package/cli/commands/tokens/update.js +58 -0
  20. package/cli/commands/tokens.js +8 -0
  21. package/cli/device-finder.js +66 -0
  22. package/cli/index.js +9 -0
  23. package/cli/log.js +89 -0
  24. package/docs/advanced-api.md +103 -0
  25. package/docs/devices/README.md +111 -0
  26. package/docs/devices/air-purifier.md +142 -0
  27. package/docs/devices/controller.md +89 -0
  28. package/docs/devices/gateway.md +41 -0
  29. package/docs/devices/humidifier.md +136 -0
  30. package/docs/devices/light.md +141 -0
  31. package/docs/devices/power-outlet.md +56 -0
  32. package/docs/devices/power-plug.md +69 -0
  33. package/docs/devices/power-strip.md +73 -0
  34. package/docs/devices/sensor.md +74 -0
  35. package/docs/devices/vacuum.md +80 -0
  36. package/docs/devices/wall-switch.md +62 -0
  37. package/docs/management.md +109 -0
  38. package/docs/missing-devices.md +48 -0
  39. package/docs/protocol.md +77 -0
  40. package/docs/reporting-issues.md +47 -0
  41. package/example.js +11 -0
  42. package/lib/checkResult.js +13 -0
  43. package/lib/connectToDevice.js +62 -0
  44. package/lib/device.js +290 -0
  45. package/lib/device_info.js +329 -0
  46. package/lib/device_info.test.js +337 -0
  47. package/lib/devices/air-monitor.js +53 -0
  48. package/lib/devices/air-purifier.js +162 -0
  49. package/lib/devices/capabilities/battery-level.js +16 -0
  50. package/lib/devices/capabilities/buzzer.js +78 -0
  51. package/lib/devices/capabilities/changeable-led-brightness.js +48 -0
  52. package/lib/devices/capabilities/colorable.js +14 -0
  53. package/lib/devices/capabilities/dimmable.js +14 -0
  54. package/lib/devices/capabilities/mode.js +13 -0
  55. package/lib/devices/capabilities/power.js +14 -0
  56. package/lib/devices/capabilities/sensor.js +50 -0
  57. package/lib/devices/capabilities/switchable-led.js +49 -0
  58. package/lib/devices/chuangmi.plug.v1.js +61 -0
  59. package/lib/devices/eyecare-lamp2.js +179 -0
  60. package/lib/devices/gateway/86sw1.js +28 -0
  61. package/lib/devices/gateway/86sw2.js +44 -0
  62. package/lib/devices/gateway/ctrl_ln1.js +44 -0
  63. package/lib/devices/gateway/ctrl_ln2.js +53 -0
  64. package/lib/devices/gateway/ctrl_neutral1.js +44 -0
  65. package/lib/devices/gateway/ctrl_neutral2.js +53 -0
  66. package/lib/devices/gateway/cube.js +55 -0
  67. package/lib/devices/gateway/developer-api.js +120 -0
  68. package/lib/devices/gateway/light-channel.js +32 -0
  69. package/lib/devices/gateway/light-mixin.js +71 -0
  70. package/lib/devices/gateway/magnet.js +29 -0
  71. package/lib/devices/gateway/magnet2.js +13 -0
  72. package/lib/devices/gateway/motion.js +27 -0
  73. package/lib/devices/gateway/motion2.js +31 -0
  74. package/lib/devices/gateway/plug.js +45 -0
  75. package/lib/devices/gateway/sensor_ht.js +17 -0
  76. package/lib/devices/gateway/subdevice.js +227 -0
  77. package/lib/devices/gateway/subdevices.js +37 -0
  78. package/lib/devices/gateway/switch.js +29 -0
  79. package/lib/devices/gateway/switch2.js +27 -0
  80. package/lib/devices/gateway/voltage.js +28 -0
  81. package/lib/devices/gateway/weather.js +22 -0
  82. package/lib/devices/gateway.js +244 -0
  83. package/lib/devices/humidifier.js +162 -0
  84. package/lib/devices/mijiavacuum.js +22 -0
  85. package/lib/devices/philips-light-bulb.js +73 -0
  86. package/lib/devices/power-plug.js +26 -0
  87. package/lib/devices/power-strip.js +38 -0
  88. package/lib/devices/vacuum.js +412 -0
  89. package/lib/devices/viomivacuum.js +250 -0
  90. package/lib/devices/yeelight.color.js +6 -0
  91. package/lib/devices/yeelight.js +286 -0
  92. package/lib/devices/yeelight.mono.js +9 -0
  93. package/lib/discovery.js +192 -0
  94. package/lib/index.js +40 -0
  95. package/lib/infoFromHostname.js +24 -0
  96. package/lib/management.js +102 -0
  97. package/lib/models.js +77 -0
  98. package/lib/network.js +234 -0
  99. package/lib/packet.js +191 -0
  100. package/lib/placeholder.js +12 -0
  101. package/lib/safeishJSON.js +14 -0
  102. package/lib/tokens.js +129 -0
  103. package/npm-shrinkwrap.json +853 -0
  104. package/package.json +40 -0
package/lib/models.js ADDED
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Mapping from models into high-level devices.
5
+ */
6
+ const AirMonitor = require('./devices/air-monitor');
7
+ const AirPurifier = require('./devices/air-purifier');
8
+ const Gateway = require('./devices/gateway');
9
+
10
+ const Vacuum = require('./devices/vacuum');
11
+ const MijiaVacuum = require('./devices/mijiavacuum');
12
+ const ViomiVacuum = require('./devices/viomivacuum');
13
+
14
+ const PowerPlug = require('./devices/power-plug');
15
+ const PowerStrip = require('./devices/power-strip');
16
+
17
+ const Humidifier = require('./devices/humidifier');
18
+
19
+ const YeelightColor = require('./devices/yeelight.color');
20
+ const YeelightMono = require('./devices/yeelight.mono');
21
+
22
+ module.exports = {
23
+ 'zhimi.airmonitor.v1': AirMonitor,
24
+
25
+ // Air Purifier 1 (and Pro?)
26
+ 'zhimi.airpurifier.v1': AirPurifier,
27
+ 'zhimi.airpurifier.v2': AirPurifier,
28
+ 'zhimi.airpurifier.v3': AirPurifier,
29
+ 'zhimi.airpurifier.v6': AirPurifier,
30
+
31
+ // Air Purifier 2
32
+ 'zhimi.airpurifier.m1': AirPurifier,
33
+ 'zhimi.airpurifier.m2': AirPurifier,
34
+
35
+ // Air Purifier 2S
36
+ 'zhimi.airpurifier.ma2': AirPurifier,
37
+
38
+ 'zhimi.humidifier.v1': Humidifier,
39
+
40
+ 'chuangmi.plug.m1': PowerPlug,
41
+ 'chuangmi.plug.v1': require('./devices/chuangmi.plug.v1'),
42
+ 'chuangmi.plug.v2': PowerPlug,
43
+
44
+ 'rockrobo.vacuum.v1': Vacuum,
45
+ 'roborock.vacuum.s5': Vacuum,
46
+ 'roborock.vacuum.s5e': Vacuum,
47
+ 'roborock.vacuum.c1': Vacuum,
48
+ 'roborock.vacuum.s6': Vacuum,
49
+ 'roborock.vacuum.t6': Vacuum,
50
+ 'roborock.vacuum.e2': Vacuum,
51
+ 'roborock.vacuum.s4': Vacuum,
52
+ 'roborock.vacuum.a10': Vacuum,
53
+
54
+ 'roborock.vacuum.m1s': MijiaVacuum,
55
+
56
+ 'dreame.vacuum.mc1808': ViomiVacuum,
57
+ 'viomi.vacuum.v7': ViomiVacuum,
58
+ 'viomi.vacuum.v8': ViomiVacuum,
59
+
60
+ 'lumi.gateway.v2': Gateway.WithLightAndSensor,
61
+ 'lumi.gateway.v3': Gateway.WithLightAndSensor,
62
+ 'lumi.acpartner.v1': Gateway.Basic,
63
+ 'lumi.acpartner.v2': Gateway.Basic,
64
+ 'lumi.acpartner.v3': Gateway.Basic,
65
+
66
+ 'qmi.powerstrip.v1': PowerStrip,
67
+ 'zimi.powerstrip.v2': PowerStrip,
68
+
69
+ 'yeelink.light.lamp1': YeelightMono,
70
+ 'yeelink.light.mono1': YeelightMono,
71
+ 'yeelink.light.color1': YeelightColor,
72
+ 'yeelink.light.strip1': YeelightColor,
73
+
74
+ 'philips.light.sread1': require('./devices/eyecare-lamp2'),
75
+ 'philips.light.bulb': require('./devices/philips-light-bulb')
76
+
77
+ };
package/lib/network.js ADDED
@@ -0,0 +1,234 @@
1
+ 'use strict';
2
+
3
+ const EventEmitter = require('events');
4
+ const dgram = require('dgram');
5
+
6
+ const debug = require('debug');
7
+
8
+ const Packet = require('./packet');
9
+ const DeviceInfo = require('./device_info');
10
+ const PORT = 54321;
11
+
12
+ /**
13
+ * Class for keeping track of the current network of devices. This is used to
14
+ * track a few things:
15
+ *
16
+ * 1) Mapping between adresses and device identifiers. Used when connecting to
17
+ * a device directly via IP or hostname.
18
+ *
19
+ * 2) Mapping between id and detailed device info such as the model.
20
+ *
21
+ */
22
+ class Network extends EventEmitter {
23
+ constructor() {
24
+ super();
25
+
26
+ this.packet = new Packet(true);
27
+
28
+ this.addresses = new Map();
29
+ this.devices = new Map();
30
+
31
+ this.references = 0;
32
+ this.debug = debug('miio:network');
33
+ }
34
+
35
+ search() {
36
+ this.packet.handshake();
37
+ const data = Buffer.from(this.packet.raw);
38
+ this.socket.send(data, 0, data.length, PORT, '255.255.255.255');
39
+
40
+ // Broadcast an extra time in 500 milliseconds in case the first brodcast misses a few devices
41
+ setTimeout(() => {
42
+ this.socket.send(data, 0, data.length, PORT, '255.255.255.255');
43
+ }, 500);
44
+ }
45
+
46
+ findDevice(id, rinfo) {
47
+ // First step, check if we know about the device based on id
48
+ let device = this.devices.get(id);
49
+ if (!device && rinfo) {
50
+ // If we have info about the address, try to resolve again
51
+ device = this.addresses.get(rinfo.address);
52
+
53
+ if (!device) {
54
+ // No device found, keep track of this one
55
+ device = new DeviceInfo(this, id, rinfo.address, rinfo.port);
56
+ this.devices.set(id, device);
57
+ this.addresses.set(rinfo.address, device);
58
+
59
+ return device;
60
+ }
61
+ }
62
+
63
+ return device;
64
+ }
65
+
66
+ async findDeviceViaAddress(options) {
67
+ if (!this.socket) {
68
+ throw new Error(
69
+ 'Implementation issue: Using network without a reference'
70
+ );
71
+ }
72
+
73
+ let device = this.addresses.get(options.address);
74
+ if (!device) {
75
+ // No device was found at the address, try to discover it
76
+ device = new DeviceInfo(
77
+ this,
78
+ null,
79
+ options.address,
80
+ options.port || PORT
81
+ );
82
+ this.addresses.set(options.address, device);
83
+ }
84
+
85
+ // Update the token if we have one
86
+ if (typeof options.token === 'string') {
87
+ device.token = Buffer.from(options.token, 'hex');
88
+ } else if (options.token instanceof Buffer) {
89
+ device.token = options.token;
90
+ }
91
+
92
+ // Set the model if provided
93
+ if (!device.model && options.model) {
94
+ device.model = options.model;
95
+ }
96
+
97
+ // Perform a handshake with the device to see if we can connect
98
+ try {
99
+ await device.handshake();
100
+ } catch (err) {
101
+ // Supress missing tokens - enrich should take care of that
102
+ if (err.code !== 'missing-token') {
103
+ throw err;
104
+ }
105
+ }
106
+
107
+ const cachedDevice = this.cacheDevice(device);
108
+ await cachedDevice.enrich();
109
+ return cachedDevice;
110
+ }
111
+
112
+ /**
113
+ * Caches the device if not previously cached (could be the reason of failures when reconnecting?)
114
+ * @private
115
+ * @param device {@link DeviceInfo}
116
+ * @returns {DeviceInfo} New device or the previously cached one
117
+ */
118
+ cacheDevice(device) {
119
+ if (!this.devices.has(device.id)) {
120
+ // This is a new device, keep track of it
121
+ this.devices.set(device.id, device);
122
+ }
123
+ // Sanity, make sure that the device in the map is returned
124
+ return this.devices.get(device.id);
125
+ }
126
+
127
+ createSocket() {
128
+ this._socket = dgram.createSocket('udp4');
129
+
130
+ // Bind the socket and when it is ready mark it for broadcasting
131
+ this._socket.bind();
132
+ this._socket.on('listening', () => {
133
+ this._socket.setBroadcast(true);
134
+
135
+ const address = this._socket.address();
136
+ this.debug('Network bound to port', address.port);
137
+ });
138
+
139
+ // On any incoming message, parse it, update the discovery
140
+ this._socket.on('message', (msg, rinfo) => {
141
+ const buf = Buffer.from(msg);
142
+ try {
143
+ this.packet.raw = buf;
144
+ } catch (ex) {
145
+ this.debug('Could not handle incoming message');
146
+ return;
147
+ }
148
+
149
+ if (!this.packet.deviceId) {
150
+ this.debug('No device identifier in incoming packet');
151
+ return;
152
+ }
153
+
154
+ const device = this.findDevice(this.packet.deviceId, rinfo);
155
+ device.onMessage(buf);
156
+
157
+ if (!this.packet.data) {
158
+ if (!device.enriched) {
159
+ // This is the first time we see this device
160
+ device
161
+ .enrich()
162
+ .then(() => {
163
+ this.emit('device', device);
164
+ })
165
+ .catch((err) => {
166
+ this.emit('device', device);
167
+ });
168
+ } else {
169
+ this.emit('device', device);
170
+ }
171
+ }
172
+ });
173
+ }
174
+
175
+ list() {
176
+ return this.devices.values();
177
+ }
178
+
179
+ /**
180
+ * Get a reference to the network. Helps with locking of a socket.
181
+ */
182
+ ref() {
183
+ this.debug('Grabbing reference to network');
184
+ this.references++;
185
+ this.updateSocket();
186
+
187
+ let released = false;
188
+ let self = this;
189
+ return {
190
+ release() {
191
+ if (released) return;
192
+
193
+ self.debug('Releasing reference to network');
194
+
195
+ released = true;
196
+ self.references--;
197
+
198
+ self.updateSocket();
199
+ },
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Update wether the socket is available or not. Instead of always keeping
205
+ * a socket we track if it is available to allow Node to exit if no
206
+ * discovery or device is being used.
207
+ */
208
+ updateSocket() {
209
+ if (this.references === 0) {
210
+ // No more references, kill the socket
211
+ if (this._socket) {
212
+ this.debug('Network no longer active, destroying socket');
213
+ this._socket.close();
214
+ this._socket = null;
215
+ }
216
+ } else if (this.references === 1 && !this._socket) {
217
+ // This is the first reference, create the socket
218
+ this.debug('Making network active, creating socket');
219
+ this.createSocket();
220
+ }
221
+ }
222
+
223
+ get socket() {
224
+ if (!this._socket) {
225
+ throw new Error(
226
+ 'Network communication is unavailable, device might be destroyed'
227
+ );
228
+ }
229
+
230
+ return this._socket;
231
+ }
232
+ }
233
+
234
+ module.exports = new Network();
package/lib/packet.js ADDED
@@ -0,0 +1,191 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const debug = require('debug')('miio:packet');
5
+
6
+ class Packet {
7
+ constructor(discovery = false) {
8
+ this.discovery = discovery;
9
+
10
+ this.header = Buffer.alloc(2 + 2 + 4 + 4 + 4 + 16);
11
+ this.header[0] = 0x21;
12
+ this.header[1] = 0x31;
13
+
14
+ for (let i = 4; i < 32; i++) {
15
+ this.header[i] = 0xff;
16
+ }
17
+
18
+ this._serverStampTime = 0;
19
+ this._token = null;
20
+ }
21
+
22
+ handshake() {
23
+ this.data = null;
24
+ }
25
+
26
+ handleHandshakeReply() {
27
+ if (this._token === null) {
28
+ const token = this.checksum;
29
+ if (token.toString('hex').match(/^[fF0]+$/)) {
30
+ // Device did not return its token so we set our token to null
31
+ this._token = null;
32
+ } else {
33
+ this.token = this.checksum;
34
+ }
35
+ }
36
+ }
37
+
38
+ get needsHandshake() {
39
+ /*
40
+ * Handshake if we:
41
+ * 1) do not have a token
42
+ * 2) it has been longer then 120 seconds since last received message
43
+ */
44
+ return !this._token || Date.now() - this._serverStampTime > 120000;
45
+ }
46
+
47
+ get raw() {
48
+ if (this.data) {
49
+ // Send a command to the device
50
+ if (!this._token) {
51
+ throw new Error('Token is required to send commands');
52
+ }
53
+
54
+ for (let i = 4; i < 8; i++) {
55
+ this.header[i] = 0x00;
56
+ }
57
+
58
+ // Update the stamp to match server
59
+ if (this._serverStampTime) {
60
+ const secondsPassed = Math.floor(
61
+ (Date.now() - this._serverStampTime) / 1000
62
+ );
63
+ try {
64
+ this.header.writeUInt32BE(this._serverStamp + secondsPassed, 12);
65
+ } catch (err) {
66
+ // If it fails to post the difference in seconds, just use the same stamp it previously had
67
+ this.header.writeUInt32BE(this._serverStamp, 12);
68
+ }
69
+ }
70
+
71
+ // Encrypt the data
72
+ let cipher = crypto.createCipheriv(
73
+ 'aes-128-cbc',
74
+ this._tokenKey,
75
+ this._tokenIV
76
+ );
77
+ let encrypted = Buffer.concat([cipher.update(this.data), cipher.final()]);
78
+
79
+ // Set the length
80
+ this.header.writeUInt16BE(32 + encrypted.length, 2);
81
+
82
+ // Calculate the checksum
83
+ let digest = crypto
84
+ .createHash('md5')
85
+ .update(this.header.slice(0, 16))
86
+ .update(this._token)
87
+ .update(encrypted)
88
+ .digest();
89
+ digest.copy(this.header, 16);
90
+
91
+ debug('->', this.header);
92
+ return Buffer.concat([this.header, encrypted]);
93
+ } else {
94
+ // Handshake
95
+ this.header.writeUInt16BE(32, 2);
96
+
97
+ for (let i = 4; i < 32; i++) {
98
+ this.header[i] = 0xff;
99
+ }
100
+
101
+ debug('->', this.header);
102
+ return this.header;
103
+ }
104
+ }
105
+
106
+ set raw(msg) {
107
+ msg.copy(this.header, 0, 0, 32);
108
+ debug('<-', this.header);
109
+
110
+ const stamp = this.stamp;
111
+ if (stamp > 0) {
112
+ // If the device returned a stamp, store it
113
+ this._serverStamp = this.stamp;
114
+ this._serverStampTime = Date.now();
115
+ }
116
+
117
+ const encrypted = msg.slice(32);
118
+
119
+ if (this.discovery) {
120
+ // This packet is only intended to be used for discovery
121
+ this.data = encrypted.length > 0;
122
+ } else {
123
+ // Normal packet, decrypt data
124
+ if (encrypted.length > 0) {
125
+ if (!this._token) {
126
+ debug('<- No token set, unable to handle packet');
127
+ this.data = null;
128
+ return;
129
+ }
130
+
131
+ const digest = crypto
132
+ .createHash('md5')
133
+ .update(this.header.slice(0, 16))
134
+ .update(this._token)
135
+ .update(encrypted)
136
+ .digest();
137
+
138
+ const checksum = this.checksum;
139
+ if (!checksum.equals(digest)) {
140
+ debug(
141
+ '<- Invalid packet, checksum was',
142
+ checksum,
143
+ 'should be',
144
+ digest
145
+ );
146
+ this.data = null;
147
+ } else {
148
+ let decipher = crypto.createDecipheriv(
149
+ 'aes-128-cbc',
150
+ this._tokenKey,
151
+ this._tokenIV
152
+ );
153
+ this.data = Buffer.concat([
154
+ decipher.update(encrypted),
155
+ decipher.final(),
156
+ ]);
157
+ }
158
+ } else {
159
+ this.data = null;
160
+ }
161
+ }
162
+ }
163
+
164
+ get token() {
165
+ return this._token;
166
+ }
167
+
168
+ set token(t) {
169
+ this._token = Buffer.from(t);
170
+ this._tokenKey = crypto.createHash('md5').update(t).digest();
171
+ this._tokenIV = crypto
172
+ .createHash('md5')
173
+ .update(this._tokenKey)
174
+ .update(t)
175
+ .digest();
176
+ }
177
+
178
+ get checksum() {
179
+ return this.header.slice(16);
180
+ }
181
+
182
+ get deviceId() {
183
+ return this.header.readUInt32BE(8);
184
+ }
185
+
186
+ get stamp() {
187
+ return this.header.readUInt32BE(12);
188
+ }
189
+ }
190
+
191
+ module.exports = Packet;
@@ -0,0 +1,12 @@
1
+ 'use strict';
2
+
3
+ const { Thing } = require('abstract-things');
4
+ const MiioApi = require('./device');
5
+
6
+ module.exports = class extends Thing.with(MiioApi) {
7
+
8
+ static get type() {
9
+ return 'placeholder';
10
+ }
11
+
12
+ };
@@ -0,0 +1,14 @@
1
+ 'use strict';
2
+
3
+ module.exports = function(str) {
4
+ try {
5
+ return JSON.parse(str);
6
+ } catch(ex) {
7
+ // Case 1: Load for subdevices fail as they return empty values
8
+ str = str.replace('[,]', '[null,null]');
9
+ // for aqara body sensor (lumi.motion.aq2)
10
+ str = str.replace('[,,]', '[null,null,null]');
11
+
12
+ return JSON.parse(str);
13
+ }
14
+ };
package/lib/tokens.js ADDED
@@ -0,0 +1,129 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ const mkdirp = require('mkdirp');
7
+ const AppDirectory = require('appdirectory');
8
+ const dirs = new AppDirectory('miio');
9
+
10
+ const CHECK_TIME = 1000;
11
+ const MAX_STALE_TIME = 120000;
12
+
13
+ const debug = require('debug')('miio:tokens');
14
+
15
+ /**
16
+ * Shared storage for tokens of devices. Keeps a simple JSON file synced
17
+ * with tokens connected to device ids.
18
+ */
19
+ class Tokens {
20
+ constructor() {
21
+ this._file = path.join(dirs.userData(), 'tokens.json');
22
+ this._data = {};
23
+ this._lastSync = 0;
24
+ }
25
+
26
+ get(deviceId) {
27
+ const now = Date.now();
28
+ const diff = now - this._lastSync;
29
+
30
+ if(diff > CHECK_TIME) {
31
+ return this._loadAndGet(deviceId);
32
+ }
33
+
34
+ return Promise.resolve(this._get(deviceId));
35
+ }
36
+
37
+ _get(deviceId) {
38
+ return this._data[deviceId];
39
+ }
40
+
41
+ _loadAndGet(deviceId) {
42
+ return this._load()
43
+ .then(() => this._get(deviceId))
44
+ .catch(() => null);
45
+ }
46
+
47
+ _load() {
48
+ if(this._loading) return this._loading;
49
+
50
+ return this._loading = new Promise((resolve, reject) => {
51
+ debug('Loading token storage from', this._file);
52
+ fs.stat(this._file, (err, stat) => {
53
+ if(err) {
54
+ delete this._loading;
55
+ if(err.code === 'ENOENT') {
56
+ debug('Token storage does not exist');
57
+ this._lastSync = Date.now();
58
+ resolve(this._data);
59
+ } else {
60
+ reject(err);
61
+ }
62
+
63
+ return;
64
+ }
65
+
66
+ if(! stat.isFile()) {
67
+ // tokens.json does not exist
68
+ delete this._loading;
69
+ reject(new Error('tokens.json exists but is not a file'));
70
+ } else if(Date.now() - this._lastSync > MAX_STALE_TIME || stat.mtime.getTime() > this._lastSync) {
71
+ debug('Loading tokens');
72
+ fs.readFile(this._file, (err, result) => {
73
+ this._data = JSON.parse(result.toString());
74
+ this._lastSync = Date.now();
75
+ delete this._loading;
76
+ resolve(this._data);
77
+ });
78
+ } else {
79
+ delete this._loading;
80
+ this._lastSync = Date.now();
81
+ resolve(this._data);
82
+ }
83
+ });
84
+ });
85
+ }
86
+
87
+ update(deviceId, token) {
88
+ return this._load()
89
+ .then(() => {
90
+ this._data[deviceId] = token;
91
+
92
+ if(this._saving) {
93
+ this._dirty = true;
94
+ return this._saving;
95
+ }
96
+
97
+ return this._saving = new Promise((resolve, reject) => {
98
+ const save = () => {
99
+ debug('About to save tokens');
100
+ fs.writeFile(this._file, JSON.stringify(this._data, null, 2), (err) => {
101
+ if(err) {
102
+ reject(err);
103
+ } else {
104
+ if(this._dirty) {
105
+ debug('Redoing save due to multiple updates');
106
+ this._dirty = false;
107
+ save();
108
+ } else {
109
+ delete this._saving;
110
+ resolve();
111
+ }
112
+ }
113
+ });
114
+ };
115
+
116
+ mkdirp(dirs.userData(), (err) => {
117
+ if(err) {
118
+ reject(err);
119
+ return;
120
+ }
121
+
122
+ save();
123
+ });
124
+ });
125
+ });
126
+ }
127
+ }
128
+
129
+ module.exports = new Tokens();