Repository navigation
Expand file tree
/
Copy pathpaperhive-source.js
More file actions
294 lines (231 loc) · 8.41 KB
/
Copy pathpaperhive-source.js
File metadata and controls
294 lines (231 loc) · 8.41 KB
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
'use strict'
const DocloopEndpoint = require('docloop').DocloopEndpoint,
DocloopError = require('docloop').DocloopError,
request = require('request-promise-native').defaults({json:true}),
Promise = require('bluebird')
/**
* Class representing a paperhive document.
*
* @alias PaperhiveSource
* @memberOf module:paperhiveAdapter
*
* @extends {DocloopEndpoint}
*/
class PaperhiveSource extends DocloopEndpoint{
constructor(adapter, {id, _id, identifier, config, decor, data}){
super(adapter, {
id,
_id,
identifier,
config,
decor: decor || {
image: null,
title: 'Paperhive Document',
details: 'unknown'
},
data
})
if(!identifier.document_id) throw new ReferenceError("PaperhiveSource.constructor() missing identifier.document_id")
if(adapter.id != identifier.adapter) throw new Error("PaperhiveSource.constructor() adapter mismatch")
}
/**
* Fetch document data from the paperhive API
* @async
* @param {DocloopAdapter} adapter The adpater configured for a paperhive instance
* @param {String} [document_id] The paperhive document id
* @param {String} [document_item_id] The paperhive document item id
* @return {Object} The document's data by id or item id
* @throws {Error} If paperhive API request fails
*/
static async getDocument(adapter, document_id, document_item_id){
var url, response
if(document_id) url = adapter.config.documentItemsById.replace(/%s/,document_id)
if(document_item_id) url = adapter.config.documentItemByItemId.replace(/%s/,document_item_id)
if(!url) throw new Error("PaperhiveSource.getDocument() missing id")
try { response = await request.get(url)}
catch(e){ throw new Error("PaperhiveSource.getDocument() unable to get document: "+ e) } //TODO Error type, status code?
return document_item_id
? response
: response.documentItems[0]
}
/**
* Creates a new instance of {@link Paperhivesource} from the provided document data
* @static
* @param {PaperhiveAdapter} adapter The adapter the new source will be associated with.
* @param {Object} ph_document Data of a paperhive document. See {@link PaperhiveSource.getDocument}
* @return {Paperhivesource} New instance of {@link Paperhivesource}
*/
static fromDocument(adapter, ph_document){
if(!adapter || !ph_document) throw new ReferenceError("PaperhiveSource.fromDocument() missing adapter or paperhive document")
if(!adapter.id) throw new ReferenceError("PaperhiveSource.fromDocument() missing adapter id")
if(!ph_document.document) throw new ReferenceError("PaperhiveSource.fromDocument() missing document id")
return new PaperhiveSource(adapter, {
identifier : {
adapter: adapter.id,
document_id: ph_document.document
},
decor: PaperhiveSource.documentToDecor(ph_document)
})
}
/**
* Translates document data into {@link EndpointDecoration}.
* @static
* @param {Object} ph_document Data of a paperhive document. See {@link PaperhiveSource.getDocument}
* @returns {Decoration}
*/
static documentToDecor(ph_document){
return ph_document
? {
title: ph_document.metadata && ph_document.metadata.title,
details: ph_document.metadata && (ph_document.metadata.authors[0].name || ph_document.metadata.publisher)
}
: {
title: 'document broken',
details: 'something went wrong'
}
}
/**
* Tries to guess a document id from provided string and create a new instance of {@link PaperhiveSource} associated with it.
* @async
* @param {PaperhiveAdapter} adapter The adapter the new source will be associated with.
* @param {String} str A string to guess the document id from.
* @return {PaperhiveSource}
* @throws {ReferenceError} If adapter is missing
* @throws {TypeError} If str is not a string
* @throws {DocloopError} If str contains no matchable document_id
*/
static async guess(adapter, str){
var matches, ph_document, document_item_id, endpoint
if(!adapter) throw new ReferenceError("PaperhiveSource.guess() missing adapter")
if(typeof str != 'string') throw new TypeError("PaperhiveSource.guess() only works on strings")
var match_item_id = str.match(/documents\/items\/([^/]+)/),
document_item_id = match_item_id && match_item_id[1],
match_id = !document_item_id && str.match(/documents\/([^/]+)/), //https://paperhive.org/documents/YEkPZQhJDTew
document_id = match_id && match_id[1]
ph_document = await this.getDocument(adapter, document_id, document_item_id)
.catch( () => this.getDocument(adapter, str, null))
.catch( () => this.getDocument(adapter, null, str))
.catch( () => null)
if(!ph_document) throw new DocloopError(`PaperhiveSource.guess() unable to guess document working id from input string ${str}`, 400)
endpoint = PaperhiveSource.fromDocument(adapter, ph_document)
await endpoint.validate()
return endpoint
}
/**
* Fetch discussion data form the paperhive API.
* @async
* @return {Object}
* @throws {Error} If paperhive API request fails
*/
async getDiscussions(){
var result = await request.get(this.adapter.config.discussionsLink.replace(/%s/, this.identifier.document_id))
return result.discussions
}
/**
* Convert discussion data into {@link Annotation}
* @param {Object} discussion
* @return {Annotation}
*/
phDiscussion2Annotation(discussion){
console.log(discussion)
function findValues(obj, key){
if(!key) return []
if(typeof obj != 'object') return []
return Object.keys(obj).reduce( (sum, sub) => sum.concat(findValues(obj[sub], key)), obj[key] ? [obj[key]] : [] )
}
var page = findValues(discussion.target.selectors, 'pageNumber')[0]
return {
id: discussion.id,
sourceName: this.adapter.config.name,
sourceHome: this.adapter.config.home,
title: discussion.title + (page ? ` (p. ${page})` : ''),
author: discussion.author.displayName,
body: discussion.body,
respectiveContent: discussion.target.selectors.textQuote.content,
original: this.adapter.config.contentLink
.replace(/%s/, discussion.target.documentItem)
.replace(/%t/, discussion.id)
}
}
/**
* Convert reply data into {@link Reply}.
* @param {Object} discussion
* @return {Annotation}
*/
phReply2Reply(reply, discussion){
return {
parentId: reply.discussion,
id: reply.id,
sourceName: this.adapter.config.name,
sourceHome: this.adapter.config.home,
author: reply.author.displayName,
body: reply.body,
original: this.adapter.config.contentLink
.replace(/%s/, discussion.target.documentItem)
.replace(/%t/, discussion.id)
}
}
/**
* Scan the source for new annotations and replies.
* @async
*
* @return undefined
*
* @emits docloop~annotation
* @emits docloop~reply
*/
async scan(){
console.log('Paperhive: scanning ', this.identifier.document_id)
var now = Date.now(),
last_scan = await this.getData('lastScan'),
discussions = await this.getDiscussions()
if(!last_scan) last_scan = this.config.includePastAnnotations
? 0
: Date.now()
discussions.forEach( discussion => {
var updated = new Date(discussion.updatedAt)
if(updated >= last_scan){
this.adapter.emit(
'annotation',
{
annotation: this.phDiscussion2Annotation(discussion),
source: this.skeleton
}
)
}
discussion.replies && discussion.replies.forEach( reply => {
var updated = new Date(reply.updatedAt)
if(updated >= last_scan){
this.adapter.emit(
'reply',
{
reply: this.phReply2Reply(reply, discussion),
source: this.skeleton
}
)
}
})
})
this.setData('lastScan', now)
}
/**
* Validate the source by checking if the associated document's discussion is readable.
* @async
* @throws {DocloopError} If document's discussion are not readable
*/
async validate(){
try { await this.getDiscussions() }
catch(e){ throw new DocloopError("PaperhiveSource.validate() unable to read discussions: " +e)}
}
//TODO:
async updateDecor(){
var ph_document
try {
ph_document = await PaperhiveSource.getDocument(this.adapter, this.identifier.document_id)
}catch(e){
ph_document = null
}
this.decor = PaperhiveSource.documentToDecor(ph_document)
}
}
module.exports = PaperhiveSource