summaryrefslogtreecommitdiff
path: root/src/com/p4square/grow/frontend/TrainingPageResource.java
blob: 4096a3d9f4aeb10d8ff311399bc75f8a6e23cf5c (plain)
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
/*
 * Copyright 2013 Jesse Morgan
 */

package com.p4square.grow.frontend;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Template;

import org.restlet.data.CookieSetting;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.freemarker.TemplateRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;

import org.apache.log4j.Logger;

import net.jesterpm.fmfacade.json.JsonRequestClient;
import net.jesterpm.fmfacade.json.JsonResponse;

import net.jesterpm.fmfacade.FreeMarkerPageResource;

import com.p4square.grow.config.Config;
import com.p4square.grow.model.TrainingRecord;
import com.p4square.grow.model.VideoRecord;
import com.p4square.grow.model.Playlist;
import com.p4square.grow.provider.TrainingRecordProvider;
import com.p4square.grow.provider.Provider;

/**
 * TrainingPageResource handles rendering the training page.
 *
 * This resource expects the user to be authenticated and the ClientInfo User object
 * to be populated.
 *
 * @author Jesse Morgan <jesse@jesterpm.net>
 */
public class TrainingPageResource extends FreeMarkerPageResource {
    private static final Logger LOG = Logger.getLogger(TrainingPageResource.class);

    private static final String[] CHAPTERS = { "introduction", "seeker", "believer", "disciple", "teacher" };
    private static final Comparator<Map<String, Object>> VIDEO_COMPARATOR = new Comparator<Map<String, Object>>() {
        @Override
        public int compare(Map<String, Object> left, Map<String, Object> right) {
            String leftNumberStr = (String) left.get("number");
            String rightNumberStr = (String) right.get("number");

            if (leftNumberStr == null || rightNumberStr == null) {
                return -1;
            }

            double leftNumber = Double.valueOf(leftNumberStr);
            double rightNumber = Double.valueOf(rightNumberStr);

            return Double.compare(leftNumber, rightNumber);
        }
    };

    private Config mConfig;
    private Template mTrainingTemplate;
    private JsonRequestClient mJsonClient;

    private Provider<String, TrainingRecord> mTrainingRecordProvider;
    private FeedData mFeedData;

    // Fields pertaining to this request.
    protected String mChapter;
    protected String mUserId;

    @Override
    public void doInit() {
        super.doInit();

        GrowFrontend growFrontend = (GrowFrontend) getApplication();
        mConfig = growFrontend.getConfig();
        mTrainingTemplate = growFrontend.getTemplate("templates/training.ftl");
        if (mTrainingTemplate == null) {
            LOG.fatal("Could not find training template.");
            setStatus(Status.SERVER_ERROR_INTERNAL);
        }

        mJsonClient = new JsonRequestClient(getContext().getClientDispatcher());
        mTrainingRecordProvider = new TrainingRecordProvider<String>(new JsonRequestProvider<TrainingRecord>(getContext().getClientDispatcher(), TrainingRecord.class)) {
            @Override
            public String makeKey(String userid) {
                return getBackendEndpoint() + "/accounts/" + userid + "/training";
            }
        };

        mFeedData = new FeedData(getContext(), mConfig);

        mChapter = getAttribute("chapter");
        mUserId = getRequest().getClientInfo().getUser().getIdentifier();
    }

    /**
     * Return a page of videos.
     */
    @Override
    protected Representation get() {
        try {
            // Get the training summary
            TrainingRecord trainingRecord = mTrainingRecordProvider.get(mUserId);
            if (trainingRecord == null) {
                setStatus(Status.SERVER_ERROR_INTERNAL);
                return new ErrorPage("Could not retrieve TrainingRecord.");
            }

            Playlist playlist = trainingRecord.getPlaylist();
            Map<String, Boolean> chapters = playlist.getChapterStatuses();
            Map<String, Boolean> allowedChapters = new LinkedHashMap<String, Boolean>();

            // The user is not allowed to view chapters after his highest completed chapter.
            // In this loop we find which chapters are allowed and check if the user tried
            // to skip ahead.
            boolean allowUserToSkip = mConfig.getBoolean("allowUserToSkip", false) || getQueryValue("magicskip") != null;
            String defaultChapter = null;
            boolean userTriedToSkip = false;
            int overallProgress = 0;

            boolean foundRequired = false;
            for (String chapterId : getChaptersInOrder()) {
                boolean allowed = true;

                Boolean completed = chapters.get(chapterId);
                if (completed != null) {
                    if (!foundRequired) {
                       if (!completed) {
                            // The first incomplete chapter is the highest allowed chapter.
                            foundRequired = true;
                            defaultChapter = chapterId;
                       }

                    } else {
                        allowed = allowUserToSkip;

                        if (!allowUserToSkip && chapterId.equals(mChapter)) {
                            userTriedToSkip = true;
                        }
                    }

                    allowedChapters.put(chapterId, allowed);

                    if (completed) {
                        overallProgress++;
                    }
                }
            }

            // Overall progress is the percentage of chapters complete
            overallProgress = (int) ((double) overallProgress / getChaptersInOrder().length * 100);

            if (defaultChapter == null) {
                // Everything is completed... send them back to introduction.
                defaultChapter = "introduction";
            }

            if (mChapter == null || userTriedToSkip) {
                // No chapter was specified or the user tried to skip ahead.
                // Either case, redirect.
                String nextPage = mConfig.getString("dynamicRoot", "");
                nextPage += "/account/training/" + defaultChapter;
                getResponse().redirectSeeOther(nextPage);
                return new StringRepresentation("Redirecting to " + nextPage);
            }


            // Get videos for the chapter.
            List<Map<String, Object>> videos = null;
            {
                JsonResponse response = backendGet("/training/" + mChapter);
                if (!response.getStatus().isSuccess()) {
                    setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                    return null;
                }
                videos = (List<Map<String, Object>>) response.getMap().get("videos");
                Collections.sort(videos, VIDEO_COMPARATOR);
            }

            // Mark the completed videos as completed
            int chapterProgress = 0;
            for (Map<String, Object> video : videos) {
                boolean completed = false;
                VideoRecord record = playlist.find((String) video.get("id"));
                LOG.info("VideoId: " + video.get("id"));
                if (record != null) {
                    LOG.info("VideoRecord: " + record.getComplete());
                    completed = record.getComplete();
                }
                video.put("completed", completed);

                if (completed) {
                    chapterProgress++;
                }
            }
            chapterProgress = chapterProgress * 100 / videos.size();

            Map root = getRootObject();
            root.put("chapter", mChapter);
            root.put("chapters", allowedChapters.keySet());
            root.put("isChapterAllowed", allowedChapters);
            root.put("chapterProgress", chapterProgress);
            root.put("overallProgress", overallProgress);
            root.put("videos", videos);
            root.put("allowUserToSkip", allowUserToSkip);

            // Determine if we should show the feed.
            boolean showfeed = true;

            // Don't show the feed if the topic isn't allowed.
            if (!FeedData.TOPICS.contains(mChapter)) {
                showfeed = false;
            }

            root.put("showfeed", showfeed);
            if (showfeed) {
                root.put("feeddata", mFeedData);
            }

            return new TemplateRepresentation(mTrainingTemplate, root, MediaType.TEXT_HTML);

        } catch (Exception e) {
            LOG.fatal("Could not render page: " + e.getMessage(), e);
            setStatus(Status.SERVER_ERROR_INTERNAL);
            return ErrorPage.RENDER_ERROR;
        }
    }

    /**
     * This method returns a list of chapters in the correct order.
     */
    protected String[] getChaptersInOrder() {
        return CHAPTERS;
    }

    /**
     * @return The backend endpoint URI
     */
    private String getBackendEndpoint() {
        return mConfig.getString("backendUri", "riap://component/backend");
    }

    /**
     * Helper method to send a GET to the backend.
     */
    private JsonResponse backendGet(final String uri) {
        LOG.debug("Sending backend GET " + uri);

        final JsonResponse response = mJsonClient.get(getBackendEndpoint() + uri);
        final Status status = response.getStatus();
        if (!status.isSuccess() && !Status.CLIENT_ERROR_NOT_FOUND.equals(status)) {
            LOG.warn("Error making backend request for '" + uri + "'. status = " + response.getStatus().toString());
        }

        return response;
    }

}