This repository was archived by the owner on Sep 23, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
294 lines (252 loc) · 8.09 KB
/
Copy pathindex.js
File metadata and controls
294 lines (252 loc) · 8.09 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
var events = require('events')
var util = require('util')
var XFormSet = require('./xformset')
var after = require('after-all')
var d3 = require('d3-request')
var parallel = require('run-parallel')
var series = require('run-series')
var clone = require('clone')
var SimpleFileReader = require('./file-reader')
function XFormUploader () {
this.forms = new XFormSet()
this.attachmentState = {}
this.formState = {}
}
util.inherits(XFormUploader, events.EventEmitter)
XFormUploader.prototype.add = function (files, done) {
if (!Array.isArray(files)) {
files = [files]
}
var self = this
var next = after(function (err) {
finished(err)
})
files.forEach(add)
function add (file) {
var cb = next()
if (file.name.endsWith('.xml')) {
// XML form
SimpleFileReader.readAsText(file, function (err, xml) {
if (err) return cb(err)
self.forms.addForm(file.name, xml, cb)
})
} else {
// Attachment
self.forms.addAttachment(file.name, file, cb)
}
}
function finished (err) {
if (err) return done(err)
self.emit('change')
done()
}
}
XFormUploader.prototype.state = function () {
// Transform state by adding relevant upload/etc data.
var state = this.forms.state()
var self = this
const forms = state.forms.map(function (form, idx) {
form = cloneForm(form)
var data = self.formState[idx]
if (!data) {
// Default values to add
data = {
uploaded: 0
}
}
Object.assign(form, data)
form.attachments.forEach(function (attachment) {
data = self.attachmentState[attachment.name]
if (!data) {
// Default values to add
data = {
uploaded: 0,
mediaId: null
}
}
Object.assign(attachment, data)
})
form.missingAttachments = Object.keys(state.missingAttachments)
.map(function (key) {
var name = state.missingAttachments[key]
return self.forms.forms.missingAttachments[name]
})
.filter(function (a) {
return a.form.data.id === form.data.id
})
.map(function (a) {
return a.name
})
return form
})
return Object.assign({}, state, {forms: forms})
}
/**
* Submits forms to an ODK Aggregate server using the Javarosa FormSubmissionAPI spec:
* https://bitbucket.org/javarosa/javarosa/wiki/FormSubmissionAPI
*
* For HTTP Basic Authentication pass `opts.user` and `opts.password`
*
* Optionally pass additional headers with `opts.headers`
*
* @param {String} url Upload URL, should be an OpenRosa compliant server
* @param {Object} opts
* @param {String} opts.user Username for HTTP Basic Auth
* @param {String} opts.password Password for HTTP Basic Auth
* @param {Object} opts.headers Any optional headers to send to the server `{header: value}`
* @param {Function} done Callback
*/
XFormUploader.prototype.submit = function (url, opts, done) {
if (arguments.length === 2 && typeof opts === 'function') {
done = opts
opts = {}
}
opts = opts || {}
opts.headers = opts.headers || {}
var self = this
// Create an array of functions that will upload each form
var uploadTasks = this.state().forms.map(function (form, idx) {
// Create a form encoded as 'multipart/form-data' and append the form XML
// and attachments as specified in the Javarosa FormSubmissionAPI spec:
// https://bitbucket.org/javarosa/javarosa/wiki/FormSubmissionAPI
var formData = new window.FormData()
formData.append('xml_submission_file', new window.Blob([form.xml], {type: 'text/xml'}))
;(form.attachments || []).forEach(function (attachment) {
formData.append(attachment.filename, attachment.blob)
})
// Set the upload progress of the form on the state
function onProgress (pe) {
if (pe.lengthConputable) var progress = pe.loaded / pe.total
setProp(self.formState, idx, 'uploaded', progress)
self.emit('change')
}
// Return a function that will post the form to the url
return function (cb) {
var request = d3.text(url)
.mimeType('text/xml')
.on('progress', onProgress)
.header('X-OpenRosa-Version', '1.0')
.user(opts.user || null)
.password(opts.password || null)
for (var header in opts.headers) {
request.header(header, opts.headers[header])
}
request.post(formData, cb)
}
})
// Upload each multipart-form in series
series(uploadTasks, done)
}
// TODO(sww): prevent two uploads from being run at the same time
// TODO(sww): don't try to upload the same media twice
XFormUploader.prototype.upload = function (formUploadFn, mediaUploadFn, done) {
done = done || function () {}
var self = this
function onComplete (err) {
// TODO(sww): fire on partial/full completion, but not on full failure
self.emit('change')
done(err)
}
if (this.getAttachmentsNotUploaded().length > 0) {
// Upload media, then forms
self.uploadAttachments(mediaUploadFn, function (err) {
if (err) return done(err)
self.uploadForms(formUploadFn, onComplete)
})
} else {
// Upload forms
self.uploadForms(formUploadFn, onComplete)
}
}
XFormUploader.prototype.uploadAttachments = function (uploadFn, done) {
// TODO(sww): skip attachments that are already uploaded/uploading
// Deduce all attachments from state
var attachments = this.state().forms.reduce(function (accum, form) {
return accum.concat(form.attachments)
}, [])
var blobs = attachments.map(function (attachment) {
return attachment.blob
})
var self = this
uploadBlobs(blobs, uploadFn, function (err, ids) {
if (err) return done(err)
// Update uploaded state of attachments and set mediaId.
attachments.forEach(function (attachment, idx) {
setProp(self.attachmentState, attachment.name, 'uploaded', 1)
setProp(self.attachmentState, attachment.name, 'mediaId', ids[idx])
})
done(null, ids)
})
}
XFormUploader.prototype.uploadForms = function (uploadFn, done) {
// TODO(sww): skip forms that are already uploaded/uploading
// Produce a copy of the forms that refer to mediaIds rather than JS
// references.
var forms = this.state().forms.map(function (form, idx) {
var copy = cloneForm(form)
copy.attachments = form.attachments.map(function (attachment) {
return attachment.mediaId
})
return copy
})
// Transform forms into osm observation json blobs.
var observations = forms
.map(function (form) {
return {
type: 'observation',
tags: form
}
})
.map(JSON.stringify)
var self = this
uploadBlobs(observations, uploadFn, function (err, ids) {
if (err) return done(err)
// Set forms as uploaded.
ids.forEach(function (_, idx) {
setProp(self.formState, idx, 'uploaded', 1)
})
done(null)
})
}
XFormUploader.prototype.getAttachmentsNotUploaded = function () {
return this.state().forms.reduce(function (accum, form) {
var notUploadedAttachments = form.attachments.filter(function (attachment) {
return !attachment.uploaded
})
return accum.concat(notUploadedAttachments)
}, [])
}
// Make a deep copy of a form, but avoid copying its attachments.
function cloneForm (form) {
var attachments = form.attachments
form.attachments = []
var copy = clone(form)
form.attachments = copy.attachments = attachments
return copy
}
// Takes a list of blobs and an async upload function, performs the upload
// process on the blobs, and returns the values returned by the uploading
// mechanism.
function uploadBlobs (blobs, uploadFn, done) {
// Build upload tasks
var tasks = blobs.map(function (blob) {
return function (fin) {
uploadFn(blob, fin)
}
})
// Upload all attachments
// TODO(sww): Handle partial failures!
parallel(tasks, done)
}
function mapTextResponse (xhr) {
return typeof xhr.responseText === 'string' && xhr.responseText.trim()
}
// Set the key in the object obj[prop] to value. If the object obj[prop] doesn't
// yet exist, create it first.
function setProp (obj, prop, key, value) {
if (!obj[prop]) {
obj[prop] = {}
}
obj[prop][key] = value
}
module.exports = XFormUploader