-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathContextObserver.js
302 lines (234 loc) · 10.3 KB
/
ContextObserver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
//import IdentityManager from '../identityManager/IdentityManager';
//import Syncher from '../syncher/Syncher.js';
//import Discovery from '../discovery/Discovery.js';
//import {divideURL} from '../utils/utils';
//import Search from '../utils/Search';
import EventEmitter from '../utils/EventEmitter';
/**
* Context Observer;
* @author Paulo Chainho [[email protected]]
*/
class ContextObserver extends EventEmitter {
constructor(hypertyURL, bus, configuration, contextResourceTypes, factory, syncher) {
if (!hypertyURL) throw new Error('The hypertyURL is a needed parameter');
if (!bus) throw new Error('The MiniBus is a needed parameter');
if (!configuration) throw new Error('The configuration is a needed parameter ');
if (!factory) throw new Error('The factory is a needed parameter ');
super();
let _this = this;
_this._contextResourceTypes = contextResourceTypes;
_this._url = hypertyURL;
_this._discoverUsersPromises = {}; // object with promises executed at discoverUsers function
_this._observePromises = {}; // object with promises executed at observe function
//let identityManager = new IdentityManager(hypertyURL, configuration.runtimeURL, bus);
console.log('[ContextObserver] started with hypertyURL->', hypertyURL);
_this._domain = factory.divideURL(configuration.runtimeURL).domain;
_this._objectDescURL = 'hyperty-catalogue://catalogue.' + _this._domain + '/.well-known/dataschema/Context';
_this._users2observe = [];
_this._observers = {};
this._syncher = syncher ? syncher : factory.createSyncher(hypertyURL, bus, configuration);
let discovery = factory.createDiscovery(hypertyURL, configuration.runtimeURL, bus);
_this._discovery = discovery;
_this._discoveries = {}; //list of discovered objects
//_this.identityManager = identityManager;
//_this.search = new Search(discovery, identityManager);
window.discovery = _this._discovery;
}
start(resumedContext, disconnectedCallBack) {
let _this = this;
console.log('[ContextObserver.start] ');
return new Promise((resolve, reject) => {
_this._syncher.resumeObservers({store: true}).then((observers) => {
let observersList = Object.keys(observers);
if (observersList.length > 0) {
console.log('[ContextObserver.start] resuming: ', observers);
/*observersList.forEach((i)=>{
_this._users2observe.push(new UserAvailabilityController(observers[i]));
});*/
_this._observers = observers;
resolve(observers);
observersList.forEach((observer) =>{
let Context = observers[observer];
// By default resumed context is set with resumedContext.
if (resumedContext) context.data.values = resumedContext;
// Context will will be updated with value synchronized with reporter if connected
Context.sync();
//Add listener to be notified when reporter is abruptly disconnected
if (disconnectedCallBack) Context.onDisconnected(disconnectedCallBack);
});
} else {
resolve(false);
}
}).catch((reason) => {
console.info('[ContextObserver] Resume Observer failed | ', reason);
resolve(false);
});
}).catch((reason) => {
reject('[ContextObserver] Start failed | ', reason);
});
}
resumeDiscoveries() {
let _this = this;
return new Promise((resolve, reject) => {
_this._discovery.resumeDiscoveries().then((discoveries) => {
console.log('[ContextObserver._resumeDiscoveries] found: ', discoveries);
discoveries.forEach((discovery) =>{
if (discovery.data.resources && discovery.data.resources[0] === _this._contextResourceTypes[0]) {
console.log('[ContextObserver._resumeDiscoveries] resuming: ', discovery);
if (discovery.data.status === 'live') { // previously discovered object is now live
resolve([discovery.data]);
discovery.unsubscribeLive(_this._url);
} else { // previously discovered object is still disconnected
discovery.onLive(_this._url, ()=>{
console.log('[ContextObserver._resumeDiscoveries] disconnected Hyperty is back to live', discovery);
resolve([discovery.data]);
discovery.unsubscribeLive(_this._url);
});
}
}
});
});
}).catch((reason) => {
reject('[ContextObserver] resumeDiscoveries failed | ', reason);
});
}
onResumeObserver(callback) {
let _this = this;
_this._onResumeObserver = callback;
}
discoverUsers(email, domain) {
let _this = this;
let user = email + '@' + domain;
if (!_this._discoverUsersPromises[user]) {
_this._discoverUsersPromises[user] = new Promise(function(resolve, reject) {
_this._discovery.discoverHypertiesDO(email, ['context'], _this._contextResourceTypes, domain).then(hyperties =>{
//_this.search.users([email], [domain], ['context'], ['Context_context']).then(function(a) {
console.log('[ContextObserver.discoverUsers] discovery result->', hyperties);
let discovered = [];
let disconnected = [];
hyperties.forEach(hyperty =>{
_this._discoveries[hyperty.data.hypertyID] = hyperty;
if (hyperty.data.status === 'live') {
discovered.push(hyperty.data);
} else {
disconnected.push(hyperty);
}
});
if (discovered.length > 0) {
console.log('[ContextObserver.discoverUsers] returning discovered hyperties data->', discovered);
resolve(discovered);
} else if (disconnected.length > 0) {
console.log('[ContextObserver.discoverUsers] disconnected Hyperties ', disconnected);
//resolve([]);
disconnected[0].onLive(_this._url, ()=>{
console.log('[ContextObserver.discoverUsers] disconnected Hyperty is back to live', disconnected[0]);
discovered.push(disconnected[0].data);
resolve(discovered);
disconnected[0].unsubscribeLive(_this._url);
});
}
});
});
}
return _this._discoverUsersPromises[user];
}
/**
* This function is used to start the user Context observation for a certain user Context reporter
* @param {DiscoveredObject} hyperty Hyperty to be observed.
* @return {<Promise> DataObjectObserver} It returns as a Promise the UserAvailability Data Object Observer.
*/
observe(hyperty, domainSubscription = true) {
let _this = this;
if (!_this._observePromises[hyperty.hypertyID]) {
_this._observePromises[hyperty.hypertyID] = new Promise(function(resolve, reject) {
//check if we are already observing it
_this._users2observe.forEach((Context) => {
if (Context._reporter === hyperty.hypertyID) return resolve(Context);
});
_this._discovery.discoverDataObjectsPerReporter(hyperty.hypertyID, ['context'], _this._contextResourceTypes, _this._domain).then(function(dataObjects) {
console.log('[ContextObserver.discoverAvailability] discovered context objects ', dataObjects);
let last = 0;
let url;
dataObjects.forEach((dataObject) => {
if (dataObject.hasOwnProperty('lastModified') && dataObject.hasOwnProperty('url') && Date.parse(dataObject.lastModified) > last) {
last = dataObject.lastModified;
url = dataObject.url;
//console.log('URL DATA Object', url);
}
});
if (last != 0 && url) {
resolve(_this._subscribeContext(hyperty, url, domainSubscription));
} else {
reject('[ContextObserver.observe] discovered DataObjecs are invalid', dataObjects);
}
});
});
}
return _this._observePromises[hyperty.hypertyID];
}
_subscribeContext(hyperty, url, domainSubscription = true) {
let _this = this;
// avoid duplicated subscriptions
return new Promise(function(resolve, reject) {
_this._users2observe.forEach((Context) => {
if (Context.url === url) return resolve(Context);
});
let input = {
schema: _this._objectDescURL,
resource: url,
store: null,
p2p: null,
mutual: null,
domain_subscription: domainSubscription
};
_this._syncher.subscribe(input).then((Context) => {
console.log('[ContextObserver._subscribeContext] observer object', Context);
//let newUserAvailability = new UserAvailabilityController(Context, userID);
_this._users2observe.push(Context);
// When Object is disconnected set user Context status as unavailable
Context.onDisconnected(()=>{
console.log('[ContextObserver.onDisconnected]: ', Context);
Context.data.values[0].value = 'unavailable';
Context.sync();
});
resolve(Context);
});
});
}
_discoverAndSubscribeLegacyUsers(name) {
let _this = this;
return new Promise(function(resolve, reject) {
_this._discovery.discoverDataObjectsPerName(name).then(function(result) {
console.log('[ContextObserver._discoverAndSubscribeLegacyUsers] All DataObjects Result', result);
result.forEach(function(obj) {
if (obj.status === 'live') {
console.log('Live obj', obj);
if (!obj.hypertyID) {
obj.hypertyID = obj.reporter;
}
_this._subscribeContext(obj.schema, obj.url).then(function(resultSubscribe) {
console.log('[ContextObserver._discoverAndSubscribeLegacyUsers] _subscribeContext', resultSubscribe);
return resolve(resultSubscribe);
});
}
});
}).catch(function(err) {
console.log('error ', err);
});
});
}
/**
* This function is used to stop the user Context observation for a certain user
* @param {string} Context the UserAvailability Data Object Observer URL to be unobserved.
*/
unobserve(Context) {
let _this = this;
_this._users2observe.forEach((user, index) => {
if (user.url === Context) {
user.unsubscribe();
_this._users2observe.splice(index, 1);
}
});
}
}
export default ContextObserver;