-
Notifications
You must be signed in to change notification settings - Fork 105
/
AnnotationService.js
307 lines (282 loc) · 10.8 KB
/
AnnotationService.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
import 'whatwg-fetch';
import EventEmitter from 'events';
import autobind from 'autobind-decorator';
import Annotation from './Annotation';
import { getHeaders } from '../util';
const ANONYMOUS_USER = {
id: '0',
name: __('annotation_anonymous_user_name')
};
@autobind class AnnotationService extends EventEmitter {
//--------------------------------------------------------------------------
// Static
//--------------------------------------------------------------------------
/**
* Generates a rfc4122v4-compliant GUID, from
* http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript.
*
* @return {string} UUID for annotation
*/
static generateID() {
/* eslint-disable */
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
var r = (Math.random() * 16) | 0, v = c == 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
/* eslint-enable */
}
//--------------------------------------------------------------------------
// Typedef
//--------------------------------------------------------------------------
/**
* The data object for constructing an Annotation Service.
* @typedef {Object} AnnotationServiceData
* @property {string} apiHost API root
* @property {string} fileId File ID
* @property {string} token Access token
* @property {boolean} canAnnotate Can user annotate
*/
//--------------------------------------------------------------------------
// Public
//--------------------------------------------------------------------------
/**
* [constructor]
*
* @param {AnnotationServiceData} data - Annotation Service data
* @return {AnnotationService} AnnotationService instance
*/
constructor(data) {
super();
this.api = data.apiHost;
this.fileId = data.fileId;
this.headers = getHeaders({}, data.token);
this.canAnnotate = data.canAnnotate;
this.user = ANONYMOUS_USER;
}
/**
* Create an annotation.
*
* @param {Annotation} annotation - Annotation to save
* @return {Promise} Promise that resolves with created annotation
*/
create(annotation) {
return new Promise((resolve, reject) => {
fetch(`${this.api}/2.0/annotations`, {
method: 'POST',
headers: this.headers,
body: JSON.stringify({
item: {
type: 'file_version',
id: annotation.fileVersionId
},
details: {
type: annotation.type,
location: annotation.location,
threadID: annotation.threadID
},
message: annotation.text,
thread: annotation.thread
})
})
.then((response) => response.json())
.then((data) => {
if (data.type !== 'error' && data.id) {
// @TODO(tjin): Remove this when response has permissions
const tempData = data;
tempData.permissions = {
can_edit: true,
can_delete: true
};
const createdAnnotation = this.createAnnotation(tempData);
// Set user if not set already
if (this.user.id === '0') {
this.user = createdAnnotation.user;
}
resolve(createdAnnotation);
} else {
reject(new Error('Could not create annotation'));
this.emit('annotationerror', {
reason: 'create'
});
}
})
/* istanbul ignore next */
.catch(() => {
reject(new Error('Could not create annotation due to invalid or expired token'));
this.emit('annotationerror', {
reason: 'authorization'
});
});
});
}
/**
* Reads annotations from file version ID.
*
* @param {string} fileVersionId - File version ID to fetch annotations for
* @return {Promise} Promise that resolves with fetched annotations
*/
read(fileVersionId) {
this.annotations = [];
let resolve;
let reject;
const promise = new Promise((success, failure) => {
resolve = success;
reject = failure;
});
this.readFromMarker(resolve, reject, fileVersionId);
return promise;
}
/**
* Delete an annotation.
*
* @param {string} annotationID - Id of annotation to delete
* @return {Promise} Promise to delete annotation
*/
delete(annotationID) {
return new Promise((resolve, reject) => {
fetch(`${this.api}/2.0/annotations/${annotationID}`, {
method: 'DELETE',
headers: this.headers
})
.then((response) => {
if (response.status === 204) {
resolve();
} else {
reject(new Error(`Could not delete annotation with ID ${annotationID}`));
this.emit('annotationerror', {
reason: 'delete'
});
}
})
/* istanbul ignore next */
.catch(() => {
reject(new Error('Could not delete annotation due to invalid or expired token'));
this.emit('annotationerror', {
reason: 'authorization'
});
});
});
}
/**
* Gets a map of thread ID to annotations in that thread.
*
* @param {string} fileVersionId - File version ID to fetch annotations for
* @return {Promise} Promise that resolves with thread map
*/
getThreadMap(fileVersionId) {
return this.read(fileVersionId).then(this.createThreadMap);
}
//--------------------------------------------------------------------------
// Private
//--------------------------------------------------------------------------
/**
* Generates a map of thread ID to annotations in thread.
*
* @private
* @param {Annotation[]} annotations - Annotations to generate map from
* @return {Object} Map of thread ID to annotations in that thread
*/
createThreadMap(annotations) {
const threadMap = {};
// Construct map of thread ID to annotations
annotations.forEach((annotation) => {
const threadID = annotation.threadID;
threadMap[threadID] = threadMap[threadID] || [];
threadMap[threadID].push(annotation);
});
// Sort annotations by date created
Object.keys(threadMap).forEach((threadID) => {
threadMap[threadID].sort((a, b) => {
return new Date(a.created) - new Date(b.created);
});
});
return threadMap;
}
/**
* Generates an Annotation object from an API response.
*
* @private
* @param {Object} data - API response data
* @return {Annotation} Created annotation
*/
createAnnotation(data) {
return new Annotation({
annotationID: data.id,
fileVersionId: data.item.id,
threadID: data.details.threadID,
type: data.details.type,
thread: data.thread,
text: data.message,
location: data.details.location,
user: {
id: data.created_by.id,
name: data.created_by.name,
avatarUrl: data.created_by.profile_image
},
permissions: data.permissions,
created: data.created_at,
modified: data.modified_at
});
}
/**
* Construct the URL to read annotations with a marker or limit added
*
* @private
* @param {string} fileVersionId - File version ID to fetch annotations for
* @param {string} marker - Marker to use if there are more than limit annotations
* @param {int} limit - The amout of annotations the API will return per call
* @return {Promise} Promise that resolves with fetched annotations
*/
getReadUrl(fileVersionId, marker = null, limit = null) {
let apiUrl = `${this.api}/2.0/files/${this.fileId}/annotations?version=${fileVersionId}&fields=item,thread,details,message,created_by,created_at,modified_at,permissions`;
if (marker) {
apiUrl += `&marker=${marker}`;
}
if (limit) {
apiUrl += `&limit=${limit}`;
}
return apiUrl;
}
/**
* Reads annotations from file version ID starting at a marker. The default
* limit is 100 annotations per API call.
*
* @private
* @param {Function} resolve - Promise resolution handler
* @param {Function} reject - Promise rejection handler
* @param {string} fileVersionId - File version ID to fetch annotations for
* @param {string} marker - Marker to use if there are more than limit annotations
* @param {int} limit - The amout of annotations the API will return per call
* @return {void}
*/
readFromMarker(resolve, reject, fileVersionId, marker = null, limit = null) {
fetch(this.getReadUrl(fileVersionId, marker, limit), {
headers: this.headers
})
.then((response) => response.json())
.then((data) => {
if (data.type === 'error' || !Array.isArray(data.entries)) {
reject(new Error(`Could not read annotations from file version with ID ${fileVersionId}`));
this.emit('annotationerror', {
reason: 'read'
});
} else {
data.entries.forEach((annotationData) => {
this.annotations.push(this.createAnnotation(annotationData));
});
if (data.next_marker) {
this.readFromMarker(resolve, reject, fileVersionId, data.next_marker, limit);
} else {
resolve(this.annotations);
}
}
})
.catch(() => {
reject(new Error('Could not read annotations from file due to invalid or expired token'));
this.emit('annotationerror', {
reason: 'authorization'
});
});
}
}
export default AnnotationService;