1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 | const path = require('path');
|
6 |
|
7 |
|
8 |
|
9 | const pify = require('pify');
|
10 | const mkdirp = require('mkdirp');
|
11 |
|
12 |
|
13 |
|
14 | const api = require('./api');
|
15 | const asyncp = require('./utils/asyncp');
|
16 | const progress = require('./progress');
|
17 | const resource = require('./resource');
|
18 | const scope = require('./scope');
|
19 | const validate = require('./validate');
|
20 | const values = require('./values');
|
21 |
|
22 |
|
23 |
|
24 | const mkdirpp = pify(mkdirp);
|
25 |
|
26 | function pruneInteractions (options) {
|
27 | const ids = options.interactions;
|
28 | return resource.listInteractions({ cwd: options.cwd })
|
29 | .then((interactions) => {
|
30 | return interactions.filter((interaction) => !~ids.indexOf(interaction.id));
|
31 | })
|
32 | .then((interactions) => asyncp.eachSeries(interactions, asyncp.asyncify((i) => {
|
33 | return resource.deleteInteraction({ cwd: options.cwd, name: i.name });
|
34 | })));
|
35 | }
|
36 |
|
37 | function pullAnswerSpace (options) {
|
38 | let interactions;
|
39 | return scope.getUID()
|
40 | .then((uid) => api.getResource({ uid, type: 'answerspaces' }))
|
41 | .then((result) => {
|
42 | interactions = result.answerspaces.links.interactions || [];
|
43 | return resource.writeAnswerSpace({
|
44 | cwd: options.cwd,
|
45 | data: result.answerspaces
|
46 | });
|
47 | })
|
48 | .then(() => interactions);
|
49 | }
|
50 |
|
51 | function pullInteraction (options) {
|
52 | return resource.readCachedAnswerSpace({ cwd: options.cwd })
|
53 | .then((data) => api.getResource({
|
54 | id: '' + options.id,
|
55 | type: 'interactions',
|
56 | uid: data.name
|
57 | }))
|
58 | .then((result) => resource.writeInteraction({
|
59 | cwd: options.cwd,
|
60 | data: result.interactions,
|
61 | name: result.interactions.name
|
62 | }));
|
63 | }
|
64 |
|
65 | function pullInteractions (options) {
|
66 | const cwd = options.cwd;
|
67 | const interactions = options.interactions;
|
68 |
|
69 | progress.addWork(interactions.length);
|
70 | return mkdirpp(path.join(cwd, 'interactions'))
|
71 | .then(() => asyncp.eachLimit(interactions, values.MAX_REQUESTS, asyncp.asyncify((id) => {
|
72 | return pullInteraction({ cwd, id })
|
73 | .then(() => progress.completeWork(1));
|
74 | })));
|
75 | }
|
76 |
|
77 | function pullAll (options) {
|
78 | options = options || {};
|
79 | const cwd = process.env.BMP_WORKING_DIR || process.cwd();
|
80 |
|
81 | return validate.validateScopeMatchesContent({ cwd })
|
82 | .then(() => pullAnswerSpace({ cwd }))
|
83 | .then((interactions) => {
|
84 | if (options.prune) {
|
85 | return pruneInteractions({ cwd, interactions })
|
86 | .then(() => interactions);
|
87 | }
|
88 | return interactions;
|
89 | })
|
90 | .then((interactions) => pullInteractions({ cwd, interactions }));
|
91 | }
|
92 |
|
93 | module.exports = {
|
94 | pullAll
|
95 | };
|