-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrowdtasker.ts
405 lines (384 loc) · 13.3 KB
/
crowdtasker.ts
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
var _converterOptions;
var fTemplate: IFeature = {
id: null,
type: 'Feature',
properties: {},
geometry: {
type: null,
coordinates: null
}
};
export function getData(request: any, dataParameters: any, converterOptions: any, cb: Function) {
if (typeof dataParameters !== 'object') return cb(null);
_converterOptions = converterOptions;
_converterOptions.request = request;
_converterOptions.dataParameters = dataParameters;
var options = {
json: true
};
Object.keys(dataParameters).forEach(key => {
options[key] = dataParameters[key];
});
if (options.hasOwnProperty('url')) {
options['baseUrl'] = JSON.parse(JSON.stringify(options['url']));
}
_converterOptions.options = options;
//Get events
options['uri'] = '/events?api_key=' + options['api_key'];
requestEvents(request, options, (eventFeatures) => {
if (typeof eventFeatures === 'number') {
cb(eventFeatures); // If http statuscode received, pass it through
return;
}
var processedEvents = 0;
eventFeatures.forEach((f: IFeature, fIndex) => {
// Get event stats
options['uri'] = ('/stats/activations/' + f['id'] + '?api_key=' + options['api_key']);
console.log(options['uri']);
requestEventStats(request, options, (eventStats: AStats) => {
processedEvents += 1;
var keys = Object.keys(eventStats);
for (var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
var key = keys[keyIndex];
f.properties['stat_' + key] = eventStats[key];
}
if (processedEvents >= eventFeatures.length) {
processTasks(request, options, eventFeatures, cb);
// cb(eventFeatures);
}
});
});
if (eventFeatures.length === 0) {
cb(eventFeatures);
}
});
}
// Get event tasks
function processTasks(request, options, eventFeatures, cb) {
var processedEvents = 0;
var allTaskFeatures = [];
eventFeatures.forEach((ef: IFeature, efIndex) => {
options['uri'] = `/tasks?event=${ef.id}&api_key=${options['api_key']}`;
console.log(options['uri']);
requestTasks(request, options, (taskFeatures: IFeature[]) => {
if (typeof taskFeatures === 'number') {
console.log('Error requesting tasks: ' + taskFeatures);
} else {
allTaskFeatures = allTaskFeatures.concat(taskFeatures);
}
processedEvents += 1;
if (processedEvents >= eventFeatures.length) {
processFeedbacks(request, options, eventFeatures, allTaskFeatures, cb)
// cb(eventFeatures.concat(allTaskFeatures));
}
});
});
}
// Get task feedbacks
function processFeedbacks(request, options, eventFeatures, taskFeatures, cb) {
var processedTasks = 0;
var allFeedbacks = [];
taskFeatures.forEach((t: IFeature, tIndex) => {
if (t.properties['featureTypeId'] && t.properties['featureTypeId'] !== 'Task') {
processedTasks += 1;
return;
}
options['uri'] = `/tasks/feedbacks?task=${t.id}&api_key=${options['api_key']}`;
console.log(options['uri']);
requestFeedbacks(request, options, (feedbackFeatures: IFeature[]) => {
if (typeof feedbackFeatures === 'number') {
console.log('Error requesting tasks: ' + feedbackFeatures);
} else {
allFeedbacks = allFeedbacks.concat(feedbackFeatures);
}
processedTasks += 1;
if (processedTasks === taskFeatures.length) {
cb(eventFeatures.concat(taskFeatures, allFeedbacks));
}
});
});
if (taskFeatures.length === 0) {
cb(eventFeatures);
}
}
function requestEvents(request, options, cb) {
request.get(options, (err, response, data) => {
if (err || response.statusCode !== 200) {
cb([]);
return;
}
parseEventData(data, (features) => {
cb(features);
});
});
}
function requestTasks(request, options, cb) {
request.get(options, (err, response, data) => {
if (err || response.statusCode !== 200) {
cb([]);
return;
}
parseTaskData(data, (features) => {
cb(features);
});
});
}
function requestFeedbacks(request, options, cb) {
request.get(options, (err, response, data) => {
if (err || response.statusCode !== 200) {
cb([]);
return;
}
parseFeedbackData(data, (features) => {
cb(features);
});
});
}
function requestEventStats(request, options, cb) {
request.get(options, (err, response, data) => {
if (err || response.statusCode !== 200) {
cb(response.statusCode);
return;
}
if (!data || typeof data !== 'object') data = {};
cb(<AStats>data);
});
}
function parseEventData(data: any, callback: Function) {
if (!data || !data.forEach) {
callback([]);
return;
}
var processedEvents = 0;
var eventFeatures = [];
data.forEach((e: Event, eventIndex) => {
var f = JSON.parse(JSON.stringify(fTemplate));
var keys = Object.keys(e);
for (var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
var key = keys[keyIndex];
if (key === 'area') {
var area: Area = e[key];
f.properties['area_description'] = area.description;
f.geometry = area.region;
f.geometry['type'] = 'MultiLineString';
delete f.geometry['crs']; // Should be an object according to GeoJSON specification
} else if (key === 'id') {
f.id = e[key];
} else {
f.properties[key] = e[key];
}
}
f.properties['featureTypeId'] = 'Event';
processedEvents += 1;
eventFeatures.push(f);
if (processedEvents >= data.length) {
callback(eventFeatures);
}
});
}
function parseTaskData(data: any, callback: Function) {
if (!data || !data.forEach) {
callback([]);
return;
}
var processedFeatures = 0;
var taskFeatures = [];
var stepFeatures = [];
data.forEach((t: Task, eventIndex) => {
var f = JSON.parse(JSON.stringify(fTemplate));
var keys = Object.keys(t);
for (var keyIndex = 0; keyIndex < keys.length; keyIndex++) {
var key = keys[keyIndex];
if (key === 'area') {
var area: Area = t[key];
f.properties['area_description'] = area.description;
f.geometry = area.region;
f.geometry['type'] = 'MultiLineString';
delete f.geometry['crs']; // Should be an object according to GeoJSON specification
} else if (key === 'steps') {
for (var c = 0; c < t['steps'].length; c++) {
var fStep = JSON.parse(JSON.stringify(fTemplate));
var step = t['steps'][c];
for (var propInd = 0; propInd < Object.keys(step).length; propInd++) {
var stepKey = keys[propInd];
if (stepKey === 'choices') {
fStep.properties[stepKey] = JSON.stringify(step[stepKey], null, 2);
} else if (stepKey === 'id') {
fStep.id = step[stepKey];
} else {
fStep.properties[stepKey] = step[stepKey];
}
}
delete fStep.geometry;
fStep.properties['task_id_step'] = t['id'];
fStep.properties['featureTypeId'] = 'Step';
stepFeatures.push(fStep);
}
} else if (key === 'id') {
f.id = t[key];
} else {
f.properties[key] = t[key];
}
}
f.properties['featureTypeId'] = 'Task';
taskFeatures.push(f);
processedFeatures += 1;
if (processedFeatures >= data.length) {
callback(taskFeatures.concat(stepFeatures));
}
});
if (data.length === 0) {
callback(taskFeatures.concat(stepFeatures));
}
}
function parseFeedbackData(data: any, callback: Function) {
if (!data || !data.forEach) {
callback([]);
return;
}
var processedFeatures = 0;
var feedbackFeatures = [];
data.forEach((tf: TFeedback) => {
if (tf.hasOwnProperty('feedbacks') && tf.feedbacks.length > 0) {
for (var fbCount = 0; fbCount < tf.feedbacks.length; fbCount++) {
var fb: FBContent = tf.feedbacks[fbCount];
var f = JSON.parse(JSON.stringify(fTemplate));
// Add feedback parameters
var tfKeys = Object.keys(tf);
for (var keyIndex = 0; keyIndex < tfKeys.length; keyIndex++) {
var key = tfKeys[keyIndex];
if (key === 'feedbacks') {
continue;
} else if (key === 'id') {
f.id = tf[key] + '-' + fbCount;
} else {
f.properties[key] = tf[key];
}
}
var fbKeys = Object.keys(fb);
for (var keyIndex = 0; keyIndex < fbKeys.length; keyIndex++) {
var key = fbKeys[keyIndex];
if (key === 'position') {
f.geometry = fb[key];
delete f.geometry['crs']; // Should be an object according to GeoJSON specification
} else if (key === 'attachment_id') {
f.properties[key] = fb[key];
f.properties['attachment_url'] = `[url=${_converterOptions.dataParameters.baseUrl}/data/api/attachments/${fb[key]}.jpg]Link[/url]`;
getAttachment(fb[key]);
} else {
f.properties[key] = fb[key];
}
}
f.properties['featureTypeId'] = 'Feedback';
if (!f.geometry.coordinates) {
delete f.geometry;
}
feedbackFeatures.push(f);
}
}
processedFeatures += 1;
if (processedFeatures >= data.length) {
callback(feedbackFeatures);
}
});
if (data.length === 0) {
callback(feedbackFeatures);
}
}
function getAttachment(id: string) {
if (!_converterOptions.hasOwnProperty('apiManager')) return;
if (!_converterOptions.hasOwnProperty('dataParameters')) return;
if (!_converterOptions['dataParameters'].hasOwnProperty('attachmentPath')) return;
var attachmentPath = _converterOptions['dataParameters']['attachmentPath'];
var apiMan = _converterOptions['apiManager'];
var options = JSON.parse(JSON.stringify(_converterOptions['options']));
var request = _converterOptions['request'];
var fs = _converterOptions['fs'];
// Check if file exists
var file = `${attachmentPath}\\${id}.jpg`;
fs.access(file, (err) => {
if (err) {
fs.ensureFileSync(file);
options['uri'] = `/tasks/feedbacks/attachments/${id}?api_key=${options['api_key']}`;
request.get(options, (err, response, data) => {
if (err || response.statusCode !== 200) {
console.log('Error getting attachment.' + err);
return;
}
var fStream = fs.createWriteStream(file);
request(options).pipe(fStream).on('close', () => {
console.log('Written attachment.');
fStream.end();
});
});
} else {
console.log('Skipping attachment.');
}
});
}
interface IFeature {
id: string;
type: string;
properties: {};
geometry: {
type: string;
coordinates: any[];
};
};
interface Event {
id: string;
name: string;
status: string; //[]"ACTIVE", "CLOSED"]
type: string; //['OTHER', 'CBRN', 'DROUGHT', 'EARTHQUAKE', 'FLOOD', 'HEAT', 'PANDEMIC']
date_start: string;
date_end: string;
description: string;
area: Area;
};
interface Area {
description: string;
region: PositionPolygon;
};
interface PositionPolygon {
type: string;
crs: string;
coordinates: Object;
};
interface AStats {
TOTAL: number;
OPEN: number;
ACCEPTED: number;
DECLINED: number;
}
interface Task {
id: string;
event_id: string;
name: string;
status: string;
description: string;
category: string;
date_deadline: string;
steps: Step[];
area: Area;
}
interface Step {
id: string;
name: string;
description: string;
template: string;
choices: string[];
}
interface TFeedback {
id: string;
task_id: string;
status: string;
publish_allowed: boolean;
date_completed: string;
feedbacks: FBContent[];
}
interface FBContent {
step_id: string;
position: PositionPolygon;
data: string;
attachment_id: string;
}