@reactoo/watchtogether-sdk-js 2.4.40 → 2.5.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 (50) hide show
  1. package/dist/watchtogether-sdk.js +2187 -2418
  2. package/dist/watchtogether-sdk.min.js +2 -2
  3. package/example/bulk_join_room/bulk_join_room.html +200 -0
  4. package/example/bulk_join_room/persons_gifs/1.gif +0 -0
  5. package/example/bulk_join_room/persons_gifs/10.gif +0 -0
  6. package/example/bulk_join_room/persons_gifs/11.gif +0 -0
  7. package/example/bulk_join_room/persons_gifs/12.gif +0 -0
  8. package/example/bulk_join_room/persons_gifs/13.gif +0 -0
  9. package/example/bulk_join_room/persons_gifs/14.gif +0 -0
  10. package/example/bulk_join_room/persons_gifs/15.gif +0 -0
  11. package/example/bulk_join_room/persons_gifs/16.gif +0 -0
  12. package/example/bulk_join_room/persons_gifs/17.gif +0 -0
  13. package/example/bulk_join_room/persons_gifs/18.gif +0 -0
  14. package/example/bulk_join_room/persons_gifs/19.gif +0 -0
  15. package/example/bulk_join_room/persons_gifs/2.gif +0 -0
  16. package/example/bulk_join_room/persons_gifs/20.gif +0 -0
  17. package/example/bulk_join_room/persons_gifs/21.gif +0 -0
  18. package/example/bulk_join_room/persons_gifs/22.gif +0 -0
  19. package/example/bulk_join_room/persons_gifs/23.gif +0 -0
  20. package/example/bulk_join_room/persons_gifs/24.gif +0 -0
  21. package/example/bulk_join_room/persons_gifs/25.gif +0 -0
  22. package/example/bulk_join_room/persons_gifs/26.gif +0 -0
  23. package/example/bulk_join_room/persons_gifs/27.gif +0 -0
  24. package/example/bulk_join_room/persons_gifs/28.gif +0 -0
  25. package/example/bulk_join_room/persons_gifs/29.gif +0 -0
  26. package/example/bulk_join_room/persons_gifs/3.gif +0 -0
  27. package/example/bulk_join_room/persons_gifs/30.gif +0 -0
  28. package/example/bulk_join_room/persons_gifs/31.gif +0 -0
  29. package/example/bulk_join_room/persons_gifs/32.gif +0 -0
  30. package/example/bulk_join_room/persons_gifs/4.gif +0 -0
  31. package/example/bulk_join_room/persons_gifs/5.gif +0 -0
  32. package/example/bulk_join_room/persons_gifs/6.gif +0 -0
  33. package/example/bulk_join_room/persons_gifs/7.gif +0 -0
  34. package/example/bulk_join_room/persons_gifs/8.gif +0 -0
  35. package/example/bulk_join_room/persons_gifs/9.gif +0 -0
  36. package/example/index.html +19 -13
  37. package/package.json +8 -8
  38. package/src/index.js +7 -6
  39. package/src/models/auth.js +2 -2
  40. package/src/models/iot.js +81 -70
  41. package/src/models/room-session.js +31 -12
  42. package/src/models/room.js +138 -97
  43. package/src/models/system.js +45 -0
  44. package/src/models/user.js +11 -6
  45. package/src/modules/wt-iot.js +124 -74
  46. package/src/modules/wt-room.js +65 -131
  47. package/src/modules/wt-utils.js +2 -2
  48. package/example/shaka-basic-sync.html +0 -137
  49. package/src/models/iot2.js +0 -119
  50. package/src/modules/wt-iot2.js +0 -238
@@ -0,0 +1,200 @@
1
+ <!doctype html>
2
+
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <title>The Bulk Join</title>
7
+ <script src="../../dist/watchtogether-sdk.js"></script>
8
+ </head>
9
+ <body>
10
+ <form action="javascript:joinParticipants()">
11
+ <label for="users-count">Users count</label><br>
12
+ <input type="number" id="users-count" min="1" max="30" placeholder="30">
13
+
14
+ <br><br>
15
+
16
+ <!--<label for="instance-type">Instance type</label><br>-->
17
+ <!--<input type="text" id="instance-type" placeholder="reactooDemo" size="40">-->
18
+
19
+ <!--<br><br>-->
20
+
21
+ <label for="room-id">Room ID</label><br>
22
+ <input type="text" id="room-id" placeholder="0512f218-6a4a-45e1-9d05-d5a0e5afb33d" size="40">
23
+
24
+ <br><br>
25
+
26
+ <label for="room-id">Timeout between participants joints</label><br>
27
+ <input type="number" id="connection-timeout" placeholder="5000" min="0">
28
+
29
+ <br><br>
30
+
31
+ <button type="submit" id="join-room">Create users and join room</button>
32
+
33
+ <button type="button" id="leave-room" onclick="leaveParticipants()">Leave room</button>
34
+ </form>
35
+
36
+ <br><hr><br>
37
+
38
+ <div id="stats-container">
39
+ <label for="joined-participants-count">Joined participants count</label><br>
40
+ <input disabled id="joined-participants-count" placeholder="0">
41
+ </div>
42
+
43
+ <script>
44
+ // Inspired by:
45
+ // https://github.com/w3c/webcodecs/blob/f73dd2ccea32c0652ef94d48b87d728e4f709569/samples/image-decoder/animated-gif-renderer.html
46
+ // multiuser.html example
47
+
48
+ let participantsCount = 3;
49
+ let instanceType = "reactooDemo";
50
+ let roomId = "0512f218-6a4a-45e1-9d05-d5a0e5afb33d";
51
+ let timeoutBetweenParticipantsJoins = 5000;
52
+
53
+ let participantsData = null;
54
+
55
+ let joinedParticipantsCount = 0;
56
+
57
+ // This will generate array with length 32 and numbers from 0 to 31. Every number is unique
58
+ let randomGifOrder = Array(32).fill(0)
59
+ .map((_, i) => i + 1)
60
+ .map((value) => ({ value, sort: Math.random() }))
61
+ .sort((a, b) => a.sort - b.sort)
62
+ .map(({ value }) => value);
63
+
64
+ function joinParticipants() {
65
+ participantsCount = parseInt(document.getElementById('users-count').value);
66
+ // instanceType = document.getElementById('instance-type').value;
67
+ roomId = document.getElementById('room-id').value;
68
+ timeoutBetweenParticipantsJoins = document.getElementById('connection-timeout').value;
69
+
70
+ document.getElementById('join-room').setAttribute('disabled', true);
71
+ document.getElementById('joined-participants-count').value = joinedParticipantsCount;
72
+
73
+ // TODO - toto tu na konci nebude. Je to len preistotu, aby som znova nezhodil server
74
+ if (participantsCount > 4) {
75
+ participantsCount = 4;
76
+ }
77
+
78
+ participantsData = Array(participantsCount).fill(0).map((_, i) => {
79
+ const canvas = document.createElement('canvas');
80
+ const canvasContext = canvas.getContext('2d');
81
+
82
+ return {
83
+ id: i + 1,
84
+ gifUrl: `./persons_gifs/${randomGifOrder[i]}.gif`,
85
+ frameIndex: 0, // gif image order
86
+ reverseOrder: false,// boomerang -
87
+ imageDecoder: null, // will be set after gif image is loaded
88
+ width: null, // image and canvas width
89
+ height: null, // image and canvas height
90
+ canvas,
91
+ canvasContext,
92
+ sdkInstance: WatchTogetherSDK({debug:true, storagePrefix: `user_${i+1}`})({instanceType}),
93
+ session: null // Room session
94
+ };
95
+ });
96
+
97
+ return participantsData.reduce((promiseChain, participantData) => {
98
+ return promiseChain.then(() => fetch(participantData.gifUrl))
99
+ .then(response => createGifDecoder(response.body, participantData))
100
+ .then(() => participantData.imageDecoder.decode({frameIndex: participantData.frameIndex}))
101
+ .then(decodeResult => renderImage(decodeResult, participantData))
102
+ .then(() => joinRoom(participantData))
103
+ .then(() => new Promise(resolve => setTimeout(resolve, timeoutBetweenParticipantsJoins)));
104
+ }, Promise.resolve());
105
+ }
106
+
107
+ function leaveParticipants() {
108
+ const disconnectPromises = [];
109
+
110
+ participantsData?.forEach(participantData => {
111
+ disconnectPromises.push(disconnectRoom(participantData));
112
+ });
113
+
114
+ return Promise.all(disconnectPromises);
115
+ }
116
+
117
+ function createGifDecoder(imageByteStream, participantData) {
118
+ participantData.imageDecoder = new ImageDecoder({data: imageByteStream, type: 'image/gif'});
119
+ }
120
+
121
+ function renderImage(decodeResult, participantData) {
122
+ if (participantData.width === null || participantData.height === null) {
123
+ participantData.width = decodeResult.image.displayWidth;
124
+ participantData.canvas.width = decodeResult.image.displayWidth;
125
+
126
+ participantData.height = decodeResult.image.displayHeight;
127
+ participantData.canvas.height = decodeResult.image.displayHeight;
128
+
129
+ participantData.canvas.id = `canvas-${participantData.id}`;
130
+
131
+ // document.getElementById(participantData.canvas.id)?.remove();
132
+ // document.getElementById('canvas-container').appendChild(participantData.canvas);
133
+ }
134
+
135
+ participantData.canvasContext.drawImage(decodeResult.image, 0, 0);
136
+
137
+ const track = participantData.imageDecoder.tracks.selectedTrack;
138
+
139
+ // We check complete here since `frameCount` won't be stable until all data
140
+ // has been received. This may cause us to receive a RangeError during the
141
+ // decode() call below which needs to be handled.
142
+ if (participantData.imageDecoder.complete) {
143
+ if (track.frameCount == 1) {
144
+ return;
145
+ }
146
+
147
+ if ((participantData.reverseOrder && participantData.frameIndex - 1 <= 0) || (!participantData.reverseOrder && participantData.frameIndex + 1 >= track.frameCount)) {
148
+ participantData.reverseOrder = !participantData.reverseOrder;
149
+ }
150
+ }
151
+
152
+ if (participantData.reverseOrder) {
153
+ --participantData.frameIndex;
154
+ } else {
155
+ ++participantData.frameIndex;
156
+ }
157
+
158
+ // Decode the next frame ahead of display so it's ready in time.
159
+ participantData.imageDecoder.decode({frameIndex: participantData.frameIndex})
160
+ .then( nextDecodeResult => setTimeout(_ => {
161
+ renderImage(nextDecodeResult, participantData);
162
+ }, decodeResult.image.duration / 1000.0))
163
+ .catch(e => {
164
+ // We can end up requesting an imageIndex past the end since we're using
165
+ // a ReadableStrem from fetch(), when this happens just wrap around.
166
+ if (e instanceof RangeError) {
167
+ participantData.frameIndex = 0;
168
+ participantData.imageDecoder.decode({frameIndex: imageIndex}).then(decodeResult => renderImage(decodeResult, participantData));
169
+ } else {
170
+ throw e;
171
+ }
172
+ });
173
+ }
174
+
175
+ function joinRoom(participantData) {
176
+ return participantData.sdkInstance.auth.deviceLogin(participantData.id)
177
+ .then(() => participantData.sdkInstance.room.createSession({roomId}))
178
+ .then(session => {
179
+ participantData.session = session;
180
+ return Promise.all([session, session.connect()])
181
+ })
182
+ .then(([session, _]) => session.publishLocal(participantData.canvas.captureStream(), {getStreamIfEmpty: false}))
183
+ .then(() => document.getElementById('joined-participants-count').value = ++joinedParticipantsCount);
184
+ }
185
+
186
+ function disconnectRoom(participantData) {
187
+ return participantData.session.disconnect();
188
+ }
189
+
190
+ document.addEventListener("DOMContentLoaded", function() {
191
+ document.getElementById('users-count').value = participantsCount;
192
+ // document.getElementById('instance-type').value = instanceType;
193
+ document.getElementById('room-id').value = roomId;
194
+ document.getElementById('connection-timeout').value = timeoutBetweenParticipantsJoins;
195
+ });
196
+
197
+ </script>
198
+
199
+ </body>
200
+ </html>
@@ -31,6 +31,7 @@
31
31
 
32
32
  let participants = document.querySelector('.participants');
33
33
  var video = document.querySelector('.contentVideo');
34
+ let constructId = 'test';
34
35
 
35
36
  // if(Hls.isSupported()) {
36
37
  // var hls = new Hls();
@@ -70,28 +71,36 @@
70
71
 
71
72
 
72
73
  function disconnectRoom() {
73
- sessionHandler.disconnect();
74
+ Instance.room.getSessionByConstructId(constructId)
75
+ .then(session => session.disconnect());
74
76
  }
75
77
 
76
78
  function startRoom() {
77
- sessionHandler.connect()
78
- .then(() => sessionHandler.publishLocal(null, {getStreamIfEmpty: false, unpublishFirst:true}))
79
+ Instance.room.getSessionByConstructId(constructId)
80
+ .then(session => session.connect())
81
+ .then(() => Instance.room.getSessionByConstructId(constructId))
82
+ .then(session => session.publishLocal(null, {getStreamIfEmpty: true, unpublishFirst:true}))
79
83
  }
80
84
 
81
85
  function unpublish() {
82
- sessionHandler.unpublishLocal()
86
+ Instance.room.getSessionByConstructId(constructId)
87
+ .then(session => session.unpublishLocal());
83
88
  }
84
89
 
85
90
  function publish() {
86
- sessionHandler.publishLocal(null, {unpublishFirst:true})
91
+ Instance.room.getSessionByConstructId(constructId)
92
+ .then(session => session.publishLocal(null, {unpublishFirst:true}));
93
+
87
94
  }
88
95
 
89
96
  function toggleVideo() {
90
- sessionHandler.toggleVideo();
97
+ Instance.room.getSessionByConstructId(constructId)
98
+ .then(session => session.toggleVideo());
91
99
  }
92
100
 
93
101
  function toggleAudio() {
94
- sessionHandler.toggleAudio();
102
+ Instance.room.getSessionByConstructId(constructId)
103
+ .then(session => session.toggleAudio());
95
104
  }
96
105
 
97
106
  function setRoom() {
@@ -99,7 +108,7 @@
99
108
  }
100
109
 
101
110
  let Instance = WatchTogetherSDK({debug:true})({instanceType:'reactooDemo'});
102
- let sessionHandler = null;
111
+
103
112
 
104
113
 
105
114
 
@@ -151,12 +160,9 @@
151
160
  })
152
161
 
153
162
  })
154
- .then(r => Instance.room.createSession({roomId:r.roomId, pinHash: r.pinHash})) // pin hash is not needed if you're owner of the room
163
+ .then(r => Instance.room.createSession({constructId, roomId:r.roomId, pinHash: r.pinHash})) // pin hash is not needed if you're owner of the room
155
164
  .then(session => {
156
165
 
157
-
158
- sessionHandler = session;
159
-
160
166
  session.$on('connecting', (status) => {
161
167
  console.log('connecting', status);
162
168
  });
@@ -249,7 +255,7 @@
249
255
  });
250
256
 
251
257
  //attaching player
252
- sessionHandler.attachPlayer('hlsnative-vod',{videoElement:window.thevideo});
258
+ session.attachPlayer('hlsnative-vod',{videoElement:window.thevideo});
253
259
 
254
260
  })
255
261
  .catch(e => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reactoo/watchtogether-sdk-js",
3
- "version": "2.4.40",
3
+ "version": "2.5.0",
4
4
  "description": "Javascript SDK for Reactoo",
5
5
  "main": "src/index.js",
6
6
  "unpkg": "dist/watchtogether-sdk.min.js",
@@ -25,11 +25,11 @@
25
25
  },
26
26
  "homepage": "https://github.com/picitujeromanov/WR-SDK",
27
27
  "devDependencies": {
28
- "@babel/core": "^7.16.0",
29
- "@babel/plugin-proposal-class-properties": "^7.16.0",
30
- "@babel/plugin-proposal-optional-chaining": "^7.16.0",
31
- "@babel/plugin-proposal-private-property-in-object": "^7.16.0",
32
- "@babel/preset-env": "^7.16.4",
28
+ "@babel/core": "^7.16.5",
29
+ "@babel/plugin-proposal-class-properties": "^7.16.5",
30
+ "@babel/plugin-proposal-optional-chaining": "^7.16.5",
31
+ "@babel/plugin-proposal-private-property-in-object": "^7.16.5",
32
+ "@babel/preset-env": "^7.16.5",
33
33
  "acorn": "^6.4.2",
34
34
  "babel-core": "^6.26.3",
35
35
  "babel-loader": "^8.2.3",
@@ -46,8 +46,8 @@
46
46
  "aws-iot-device-sdk": "^2.2.11",
47
47
  "paho-mqtt": "^1.1.0",
48
48
  "serialize-error": "^7.0.1",
49
- "swagger-client": "^3.17.0",
50
- "webrtc-adapter": "^7.7.1"
49
+ "swagger-client": "^3.18.0",
50
+ "webrtc-adapter": "^8.1.1"
51
51
  },
52
52
  "browserslist": [
53
53
  "> 0.5%",
package/src/index.js CHANGED
@@ -2,14 +2,15 @@
2
2
 
3
3
  import Room from './modules/wt-room';
4
4
  import Auth from './modules/wt-auth';
5
- import Iot2 from './modules/wt-iot2';
5
+ import Iot from './modules/wt-iot';
6
6
 
7
7
  import auth from './models/auth';
8
8
  import room from './models/room';
9
9
  import user from './models/user';
10
10
  import asset from "./models/asset";
11
+ import system from "./models/system"
11
12
  import utils from './models/utils';
12
- import iot from './models/iot2'
13
+ import iot from './models/iot'
13
14
 
14
15
  function WatchTogether(modules = {}, instanceType, debug, playerFactory, providerAuth) {
15
16
  this.username = null;
@@ -27,7 +28,7 @@ function WatchTogether(modules = {}, instanceType, debug, playerFactory, provide
27
28
 
28
29
  this.setInstanceType = (newInstanceType) => this.__instanceType = newInstanceType;
29
30
 
30
- this.isReady = modules.room.isReady;
31
+ this.isReady = modules.room.whenInitialized;
31
32
  this.browser = modules.room.browser;
32
33
  this.browserDetails = modules.room.browserDetails
33
34
 
@@ -35,15 +36,15 @@ function WatchTogether(modules = {}, instanceType, debug, playerFactory, provide
35
36
  this.user = {...user.call(this)};
36
37
  this.room = {...room.call(this)};
37
38
  this.asset = {...asset.call(this)};
39
+ this.system = {...system.call(this)}
38
40
  this.iot = {...iot.call(this)};
39
41
  this.utils = utils;
40
42
  }
41
43
 
42
- let watchTogether = function ({debug = true, isProduction = true, language = 'en-GB', storagePrefix = "", apiUrl = null} = {}) {
44
+ let watchTogether = function ({debug = true, isProduction = true, language = 'en-GB', storagePrefix = "reactoo_", apiUrl = null} = {}) {
43
45
  let room = new Room(debug);
44
46
  let auth = new Auth(debug, isProduction, language, storagePrefix, apiUrl);
45
- // let iot = new Iot(debug);
46
- let iot = new Iot2(debug);
47
+ let iot = new Iot(debug);
47
48
 
48
49
  return ({instanceType = 'reactooDemo', playerFactory = null, providerAuth = null} = {}) => {
49
50
  return new WatchTogether({room, auth, iot}, instanceType, debug, playerFactory, providerAuth);
@@ -33,9 +33,9 @@ let auth = function () {
33
33
  return this.__privates.providerAuth;
34
34
  },
35
35
 
36
- deviceLogin: () => {
36
+ deviceLogin: (salt) => {
37
37
  return wait(300)
38
- .then(() => getBrowserFingerprint(this.__instanceType))
38
+ .then(() => getBrowserFingerprint(this.__instanceType, salt))
39
39
  .then( deviceId => Promise.all([deviceId, this.__privates.auth.__client]))
40
40
  .then(([deviceId, client]) => client.apis.auth.deviceSignIn({},{requestBody:{deviceId, domain: location.hostname}}))
41
41
  .then(response => {
package/src/models/iot.js CHANGED
@@ -4,101 +4,112 @@ let iot = function () {
4
4
  let __currentTopics = [];
5
5
  let __ = null;
6
6
  return {
7
-
7
+
8
8
  __promise: null,
9
-
10
- __reconnect: (badDisconnect) => {
11
-
12
- if(!badDisconnect) {
13
- return
9
+
10
+ __reconnect: (err) => {
11
+
12
+ this.__privates.iot.log('MQTT Error:', err, `Is event error: ${err instanceof Event}`);
13
+
14
+ if(err instanceof Event && err.type === 'error') {
15
+ this.__privates.iot.log('SDK MQTT Reconnection attempt');
16
+ clearTimeout(__);
17
+ __ = setTimeout(() => {
18
+ this.iot.iotLogin(true, true).catch((e) => this.__privates.iot.log('MQTT Connection Error:', e))
19
+ }, 1000);
14
20
  }
15
-
16
- clearTimeout(__);
17
- __ = setTimeout(() => {
18
- this.iot.iotLogin(true)
19
- .catch(() => this.iot.__reconnect());
20
- }, 1000);
21
21
  },
22
-
23
- iotLogin: (subscribeToSuggestedTopics = true) => {
24
-
25
- this.iot.$off('disconnected', this.iot.__reconnect);
26
- this.iot.$on('disconnected', this.iot.__reconnect );
27
-
28
- this.__promise = new Promise((resolve, reject) => {
29
- this.__privates.auth.__client
30
- .then(client => client.apis.auth.iotSignIn({}, {requestBody: {suggestedTopics:true, domain: location.hostname}}))
31
- .then(response => Promise.all([response.data.suggestedTopics, this.__privates.iot.connect(response.data.uri, response.data.clientId, response.data.timeout, response.data.mqttVersion, response.data.useSSL)]))
22
+
23
+ __updateCredentials: () => {
24
+ this.iot.getCredentials()
25
+ .then(response => this.__privates.iot.updateWebSocketCredentials(response.data.credentials.accessKeyId, response.data.credentials.secretAccessKey, response.data.credentials.sessionToken, response.data.credentials.expiration));
26
+ },
27
+
28
+ getCredentials: () => {
29
+ return this.__privates.auth.__client
30
+ .then(client => client.apis.auth.iotSignIn({}, {requestBody: {suggestedTopics:true, domain: location.hostname}}))
31
+
32
+ },
33
+
34
+ iotLogin: (subscribeToSuggestedTopics = true, forceDisconnect = false) => {
35
+ this.iot.$off('error', this.iot.__reconnect, this);
36
+ this.iot.__promise = new Promise((resolve, reject) => {
37
+ this.iot.getCredentials()
38
+ .then(response => {
39
+ return Promise.all([
40
+ response.data.suggestedTopics,
41
+ this.__privates.iot.connect(response.data.endpoint, response.data.clientId, response.data.region, response.data.credentials.accessKeyId, response.data.credentials.secretAccessKey, response.data.credentials.sessionToken, response.data.credentials.expiration, forceDisconnect)
42
+ ])
43
+ })
32
44
  .then(resolve)
33
45
  .catch(reject)
34
46
  });
35
-
36
- this.__promise.then(([suggestedTopic, instance]) => (subscribeToSuggestedTopics ?
37
- Promise.all([...suggestedTopic, ...__currentTopics].map(topic => this.iot.subscribe(topic))).then(() => instance) :
38
- Promise.resolve(instance)
39
- ));
40
-
41
- return this.__promise;
42
-
43
- },
44
-
45
- iotLogout: () => {
47
+
48
+ let __currentTopicsCopy = [...__currentTopics];
46
49
  __currentTopics.length = 0;
47
- clearTimeout(__);
48
- this.iot.$off('disconnected', this.iot.__reconnect);
49
- return this.__privates.iot.disconnect();
50
+
51
+ this.iot.__promise
52
+ .then(([suggestedTopic, instance]) => (subscribeToSuggestedTopics ?
53
+ Promise.all([...suggestedTopic, ...__currentTopicsCopy].map(topic => this.iot.subscribe(topic))).then(() => instance) :
54
+ Promise.resolve(instance)
55
+ ))
56
+ .then((instance) => {
57
+ this.iot.$on('error', this.iot.__reconnect, this);
58
+ this.iot.$on('updateCredentials', this.iot.__updateCredentials, this);
59
+ return instance;
60
+ });
61
+
62
+ return this.iot.__promise;
50
63
  },
51
-
64
+
65
+ iotLogout: (keepCurrentTopics = false) => {
66
+ this.iot.$off('error', this.iot.__reconnect, this);
67
+ this.iot.$off('updateCredentials', this.iot.__updateCredentials, this);
68
+ if(!keepCurrentTopics) {
69
+ __currentTopics.length = 0;
70
+ }
71
+ return this.__privates.iot.disconnect()
72
+ .then(() => {
73
+ this.iot.__promise = null;
74
+ return true;
75
+ });
76
+ },
77
+
52
78
  isConnected: () => {
53
79
  return this.__privates.iot.isConnected();
54
80
  },
55
-
81
+
56
82
  subscribe: (topic) => {
57
- if(__currentTopics.indexOf(topic) === -1) __currentTopics.push(topic);
58
- return this.__promise.then(() => this.__privates.iot.subscribe(topic));
59
- },
60
-
61
- //not tested yet
62
- subscribeOnce: (topic, resolveOn = () => {return true}, rejectOn = () => {return false}) => {
63
- if(__currentTopics.indexOf(topic) === -1) __currentTopics.push(topic);
64
- return this.__promise.then(() => {
65
- this.__privates.iot.subscribe(topic);
66
- return new Promise((resolve, reject) => {
67
- let __ = (data) => {
68
- if(resolveOn(data) === true) {
69
- this.$off('message', __);
70
- this.__privates.iot.unsubscribe(topic);
71
- resolve(data);
72
- }
73
- if(rejectOn(data) === true) {
74
- this.$off('message', __);
75
- this.__privates.iot.unsubscribe(topic);
76
- reject(data);
77
- }
78
- };
79
- this.iot.$on('message', __);
80
- })
81
- });
83
+ if(__currentTopics.indexOf(topic) === -1) {
84
+ __currentTopics.push(topic);
85
+ if(!this.iot.__promise) return Promise.resolve('not_connected');
86
+ return this.iot.__promise.then(() => this.__privates.iot.subscribe(topic));
87
+ }
82
88
  },
83
-
89
+
84
90
  unsubscribe: (topic) => {
85
91
  let index = __currentTopics.indexOf(topic);
86
92
  (index > -1) && __currentTopics.splice(index, 1);
87
- return this.__promise.then(() => this.__privates.iot.unsubscribe(topic));
93
+ if(!this.iot.__promise) return Promise.resolve('not_connected');
94
+ return this.iot.__promise.then(() => this.__privates.iot.unsubscribe(topic));
88
95
  },
89
-
96
+
90
97
  send: (topic, message) => {
91
- return this.__promise.then(() => this.__privates.iot.send(topic,message));
98
+ return this.iot.__promise.then(() => this.__privates.iot.send(topic,message));
92
99
  },
93
-
100
+
101
+ $once: (key, callback, that) => {
102
+ return this.__privates.iot.once(key, callback, that || this);
103
+ },
104
+
94
105
  $on: (key, callback, that) => {
95
106
  return this.__privates.iot.on(key, callback, that || this);
96
107
  },
97
-
108
+
98
109
  $off: (key, callback, that) => {
99
110
  return this.__privates.iot.off(key, callback, that || this);
100
111
  },
101
-
112
+
102
113
  $clear: () => {
103
114
  return this.__privates.iot.clear();
104
115
  }