-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathCommentProvider.js
351 lines (328 loc) · 11.3 KB
/
CommentProvider.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
/**
* Comment Provider
* Provides functionality to send or receive danmaku
* @license MIT
* @author Jim Chen
**/
var CommentProvider = (function () {
function CommentProvider () {
this._started = false;
this._destroyed = false;
this._staticSources = {};
this._dynamicSources = {};
this._parsers = {}
this._targets = [];
}
CommentProvider.SOURCE_JSON = 'JSON';
CommentProvider.SOURCE_XML = 'XML';
CommentProvider.SOURCE_TEXT = 'TEXT';
/**
* Provider for HTTP content. This returns a promise that resolves to TEXT.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {string} responseType - type of response expected.
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.BaseHttpProvider = function (method, url, responseType, args, body) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
var uri = url;
if (args && (method === 'POST' || method === 'PUT')) {
uri += '?';
var argsArray = [];
for (var key in args) {
if (args.hasOwnProperty(key)) {
argsArray.push(encodeURIComponent(key) +
'=' + encodeURIComponent(args[key]));
}
}
uri += argsArray.join('&');
}
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(this.response);
} else {
reject(new Error(this.status + " " + this.statusText));
}
};
xhr.onerror = function () {
reject(new Error(this.status + " " + this.statusText));
};
xhr.open(method, uri);
// Limit the response type based on input
xhr.responseType = typeof responseType === "string" ?
responseType : "";
if (typeof body !== 'undefined') {
xhr.send(body);
} else {
xhr.send();
}
});
};
/**
* Provider for JSON content. This returns a promise that resolves to JSON.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.JSONProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "json", args, body).then(function (response) {
return response;
});
};
/**
* Provider for XML content. This returns a promise that resolves to Document.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.XMLProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "document", args, body).then(function (response) {
return response;
});
};
/**
* Provider for text content. This returns a promise that resolves to Text.
*
* @param {string} method - HTTP method to use
* @param {string} url - Base URL
* @param {Object} args - Arguments for query string. Note: This is only used when
* method is POST or PUT
* @param {any} body - Text body content. If not provided will omit a body
* @return {Promise} that resolves or rejects based on the success or failure
* of the request
**/
CommentProvider.TextProvider = function (method, url, args, body) {
return CommentProvider.BaseHttpProvider(
method, url, "text", args, body).then(function (response) {
return response;
});
};
/**
* Attaches a static source to the corresponding type.
* NOTE: Multiple static sources will race to determine the initial comment
* list so it is imperative that they all parse to the SAME content.
*
* @param {Provider} source - Promise that resolves to one of the supported types
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addStaticSource = function (source, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more sources.');
}
if (!(type in this._staticSources)) {
this._staticSources[type] = [];
}
this._staticSources[type].push(source);
return this;
};
/**
* Attaches a dynamic source to the corresponding type
* NOTE: Multiple dynamic sources will collectively provide comment data.
*
* @param {DynamicProvider} source - Listenable that resolves to one of the supported types
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addDynamicSource = function (source, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more sources.');
}
if (!(type in this._dynamicSources)) {
this._dynamicSources[type] = [];
}
this._dynamicSources[type].push(source);
return this;
};
/**
* Attaches a target comment manager so that we can stream comments to it
*
* @param {CommentManager} commentManager - Comment Manager instance to attach to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addTarget = function (commentManager) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, '
+'cannot attach more targets.');
}
if (!(commentManager instanceof CommentManager)) {
throw new Error(
'Expected the target to be an instance of CommentManager.');
}
this._targets.push(commentManager);
return this;
};
/**
* Adds a parser for an incoming data type. If multiple parsers are added,
* parsers added later take precedence.
*
* @param {CommentParser} parser - Parser spec compliant parser
* @param {Type} type - Type that the provider resolves to
* @return {CommentProvider} this
**/
CommentProvider.prototype.addParser = function (parser, type) {
if (this._destroyed) {
throw new Error(
'Comment provider has been destroyed, ' +
'cannot attach more parsers.');
}
if (!(type in this._parsers)) {
this._parsers[type] = [];
}
this._parsers[type].unshift(parser);
return this;
};
CommentProvider.prototype.applyParsersOne = function (data, type) {
return new Promise(function (resolve, reject) {
if (!(type in this._parsers)) {
reject(new Error('No parsers defined for "' + type + '"'));
return;
}
for (var i = 0; i < this._parsers[type].length; i++) {
var output = null;
try {
output = this._parsers[type][i].parseOne(data);
} catch (e) {
// TODO: log this failure
console.error(e);
}
if (output !== null) {
resolve(output);
return;
}
}
reject(new Error("Ran out of parsers for they target type"));
}.bind(this));
};
CommentProvider.prototype.applyParsersList = function (data, type) {
return new Promise(function (resolve, reject) {
if (!(type in this._parsers)) {
reject(new Error('No parsers defined for "' + type + '"'));
return;
}
for (var i = 0; i < this._parsers[type].length; i++) {
var output = null;
try {
output = this._parsers[type][i].parseMany(data);
} catch (e) {
// TODO: log this failure
console.error(e);
}
if (output !== null) {
resolve(output);
return;
}
}
reject(new Error("Ran out of parsers for the target type"));
}.bind(this));
};
/**
* (Re)loads static comments
*
* @return {Promise} that is resolved when the static sources have been
* loaded
*/
CommentProvider.prototype.load = function () {
if (this._destroyed) {
throw new Error('Cannot load sources on a destroyed provider.');
}
var promises = [];
// TODO: This race logic needs to be rethought to provide redundancy
for (var type in this._staticSources) {
promises.push(Promises.any(this._staticSources[type])
.then(function (data) {
return this.applyParsersList(data, type);
}.bind(this)));
}
if (promises.length === 0) {
// No static loaders
return Promise.resolve([]);
}
return Promises.any(promises).then(function (commentList) {
for (var i = 0; i < this._targets.length; i++) {
this._targets[i].load(commentList);
}
return Promise.resolve(commentList);
}.bind(this));
};
/**
* Commit the changes and boot up the provider
*
* @return {Promise} that is resolved when all the static sources are loaded
* and all the dynamic sources are hooked up
**/
CommentProvider.prototype.start = function () {
if (this._destroyed) {
throw new Error('Cannot start a provider that has been destroyed.');
}
this._started = true;
return this.load().then(function (commentList) {
// Bind the dynamic sources
for (var type in this._dynamicSources) {
this._dynamicSources[type].forEach(function (source) {
source.addEventListener('receive', function (data) {
for (var i = 0; i < this._targets.length; i++) {
this._targets[i].send(
this.applyParserOne(data, type));
}
}.bind(this));
}.bind(this));
}
return Promise.resolve(commentList);
}.bind(this));
};
/**
* Send out comments to both dynamic sources and POST targets.
*
* @param commentData - commentData to be sent to the server. Object.
* @param requireAll - Do we require that all servers to accept the comment
* for the promise to resolve. Defaults to true. If
* false, the returned promise will resolve as long as a
* single target accepts.
* @return Promise that is resolved when the server accepts or rejects the
* comment. Dynamic sources will decide based on their promise while
* POST targets are considered accepted if they return a successful
* HTTP response code.
**/
CommentProvider.prototype.send = function (commentData, requireAll) {
throw new Error('Not implemented');
};
/**
* Stop providing dynamic comments to the targets
*
* @return Promise that is resolved when all bindings between dynamic
* sources have been successfully unloaded.
**/
CommentProvider.prototype.destroy = function () {
if (this._destroyed) {
return Promise.resolve();
}
// TODO: implement debinding for sources
this._destroyed = true;
return Promise.resolve();
};
return CommentProvider;
})();