All files / universal/gpii/node_modules/flowManager/src FlowManagerRequests.js

91.84% Statements 45/49
70% Branches 7/10
81.25% Functions 13/16
91.84% Lines 45/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                        1x       1x 1x   1x   1x 236x 236x 236x 236x                       1x 256x 1056x   256x         1x             1x 142x 142x 142x 138x   3x 3x                                   1x 139x 139x 139x 139x 139x 139x             1x 138x 138x 138x                   1x                             1x                                                                                                                                   1x 159x           1x                             1x 3x 3x 3x 2x 2x           1x 1x          
/**
 * GPII Flow Manager Requests
 *
 * Copyright 2012 OCAD University
 * Copyright 2015 Raising the Floor - International
 *
 * Licensed under the New BSD license. You may not use this file except in
 * compliance with this License.
 *
 * The research leading to these results has received funding from the European Union's
 * Seventh Framework Programme (FP7/2007-2013)
 * under grant agreement no. 289016.
 *
 * You may obtain a copy of the License at
 * https://github.com/GPII/universal/blob/master/LICENSE.txt
 */
 
/* eslint-env browser */
/* eslint strict: ["error", "function"] */
 
(function () {
 
    "use strict";
 
    var fluid = require("infusion"),
        gpii = fluid.registerNamespace("gpii");
 
    fluid.registerNamespace("gpii.flowManager");
 
    gpii.logFully = function () {
        var oldRenderChars = fluid.logObjectRenderChars;
        fluid.logObjectRenderChars = 2 << 20;
        fluid.log.apply(null, arguments);
        fluid.logObjectRenderChars = oldRenderChars;
    };
 
    /** Render an instance of the "megapayload" which circulates amongst the FlowManager, MatchMaker, LifecycleManager etc. methods.
     * This builds up incrementally starting with the user token during logon until we reach the "finalPayload" dispatched to the
     * lifecycleManager. This method transforms the payload into a form appropriate for logging to the console as an aid
     * to diagnosing and debugging issues encountered in the field. Currently it only performs the action of suppressing the
     * body of any entries of `solutionsRegistryEntries` since these are bulky and can easily be recovered from the
     * solutions registry itself.
     * @param {Object} megapayload A megapayload record
     * @return {Object} The megapayload transformed to a more appropriate form for logging
     */
    gpii.renderMegapayload = function (megapayload) {
        var solutionsRegistryEntries = fluid.transform(megapayload.solutionsRegistryEntries, function () {
            return "<consult solutions registry for full contents>";
        });
        return fluid.extend({}, megapayload, {
            solutionsRegistryEntries: solutionsRegistryEntries
        });
    };
 
    gpii.flowManager.logAndNotify = function (msg, event, callback) {
        return function (data) {
            gpii.logFully(msg, data);
            event.fire(callback ? callback(data) : data);
        };
    };
 
    gpii.flowManager.getPreferences = function (preferencesDataSource, request, event, userToken) {
        fluid.log("gpii.flowManager.getPreferences called - fetching preferences from URL " + preferencesDataSource.options.url);
        var promise = preferencesDataSource.get({userToken: userToken});
        promise.then(function (data) {
            event.fire(data.preferences || data);
        }, function (err) {
            err.message = "Error when retrieving preferences: " + err.message;
            request.events.onError.fire(err);
        });
    };
 
    /*
     * Asynchronous function which makes a get call to the solutions registry (1st parameter) to
     * retrieve the solutions registry matching what is passed in the `device` parameter.
     * This is appended to the matchmaker payload (mmpayload) parameter, which in turn is passed
     * as parameter in the event fired.
     *
     * @solutionsRegistryDataSource (Object) - a solutions registry data source
     * @deviceContext (Object) - output from a device reporter. Used to filter solutions registry entries
     * @event (Object) - Event to be fired when the solutionsRegistry entry has been retrieved
     * @onError (Object) - Event to be fired when an error occurs
     *
     * @return (undefined) - function is asynchronous and doesn't return anything. Instead the event
     *      is fired with the modified mmpayload.
     */
    gpii.flowManager.getSolutions = function (solutionsRegistryDataSource, deviceContext, event, onError) {
        var os = fluid.get(deviceContext, "OS.id");
        var promise = solutionsRegistryDataSource.get({});
        promise.then(function (solutions) {
            var solutionsRegistryEntries = gpii.matchMakerFramework.filterSolutions(solutions[os], deviceContext);
            fluid.log("Fetched filtered solutions registry entries: ", gpii.renderMegapayload({solutionsRegistryEntries: solutionsRegistryEntries}));
            event.fire(solutionsRegistryEntries, solutions);
        }, onError.fire);
    };
 
    // initialPayload contains fields
    //     userToken, preferences, deviceContext, solutionsRegistryEntry
    // resulting from the initial fetch process
    gpii.flowManager.processMatch = function (that, initialPayload) {
        var promise = fluid.promise.fireTransformEvent(that.events.processMatch, initialPayload, {});
        promise.then(function (finalPayload) {
            that.events.onMatchDone.fire(finalPayload);
        }, function (error) { // TODO: This rejection handler is untested
            that.handlerPromise.reject(error);
        });
    };
 
    // This is a table of priorities for handlers in the "processMatch" filter chain governing the MatchMaking process.
    // This will be removed in favour of a relative constraints system once we have FLUID-5506 completed
    // Higher priority numbers are handled earlier than lower ones
    // This process is kicked off by the "onReadyToMatch" event defined in the "gpii.flowManager.matchMakingRequest" grade
    gpii.flowManager.processMatch.priorities = {
        // onReadyToMatch event signals start of process
        preProcess:           100,
        matchMakerDispatcher: 90
        // onMatchDone event fired to lifecycleManager or cloud-based settings endpoint
    };
 
    /* This component orchestrates the lifecycle for a component which assembles the raw materials required for the matchmaking
     *  process, invokes it, and distributes the results. These raw materials are the userToken (of the user whose preferences are to
     *  be fetched), the device information for the current platform, and the registry of solutions which are available to be
     *  invoked. It is a request-scoped grade and intended as a mixin for a request handler such as kettle.request.http.
     *  This grade is used in the following places:
     *     UserLogonStateChange.js - where it coordinates the standard lifecycle for a user logging on to a local FlowManager
     *     CloudBasedFlowManager.js - where it coordinates the lifecycle for a user requesting settings from a cloud-based FlowManager
     */
    fluid.defaults("gpii.flowManager.matchMakingRequest", {
        invokers: {
            getPreferences: {
                funcName: "gpii.flowManager.getPreferences",
                args: ["{flowManager}.preferencesDataSource", "{request}", "{that}.events.onPreferences", "{that}.userToken"]
            },
            processMatch: {
                funcName: "gpii.flowManager.processMatch",
                args: [ "{that}", "{arguments}.0"]
                // initial payload
            },
            getSolutions: {
                funcName: "gpii.flowManager.getSolutions",
                args: [ "{flowManager}.solutionsRegistryDataSource", "{arguments}.0", "{that}.events.onSolutions", "{request}.events.onError"]
            }
        },
        events: {
            // Four pre-requisites for the match process to begin
            onUserToken: null,
            onPreferences: null,
            onDeviceContext: null,
            onSolutions: null,
            // The "pseudo-event" whose handlers govern the match processing chain
            processMatch: null,
            // Output of the matching process - listeners in derived grades
            onMatchDone: null,
            // Boiled event which initiates the match process
            onReadyToMatch: {
                events: {
                    preferences: "onPreferences",
                    deviceContext: "onDeviceContext",
                    solutions: "onSolutions"
                },
                args: [{
                    userToken: "{that}.userToken",
                    preferences: "{arguments}.preferences.0",
                    deviceContext: "{arguments}.deviceContext.0",
                    solutionsRegistryEntries: "{arguments}.solutions.0",
                    fullSolutionsRegistry: "{arguments}.solutions.1"
                }]
            }
        },
        listeners: {
            "onUserToken.setUserToken": {
                listener: "gpii.flowManager.setUserToken",
                args: ["{that}", "{arguments}.0"]
            },
            "onUserToken.getPreferences": {
                func: "{that}.getPreferences",
                priority: "after:setUserToken"
            },
            "onDeviceContext.getSolutions": "{that}.getSolutions",
            processMatch: [{ // Definition of the MatchMaking processing chain
                priority: gpii.flowManager.processMatch.priorities.preProcess,
                namespace: "preProcess",
                listener: "gpii.matchMakerFramework.utils.preProcess"
            }, {
                priority: gpii.flowManager.processMatch.priorities.matchMakerDispatcher,
                namespace: "matchMakerDispatcher",
                listener: "{flowManager}.matchMakerFramework.matchMakerDispatcher"
            }],
            "onReadyToMatch.processMatch": "{that}.processMatch"
        }
    });
 
 
    gpii.flowManager.setUserToken = function (handler, userToken) {
        handler.userToken = userToken;
    };
 
    /** A mixin request grade for requests which require an active user session to do their work. Exposes a method
      * withSession which will acquire the session tokens and supply them as an argument or else fail if none is available.
      */
    fluid.defaults("gpii.flowManager.sessionAware", {
        components: {
            lifecycleManager: "{flowManager}.lifecycleManager"
        },
        invokers: {
            getActiveSessionTokens: {
                func: "{lifecycleManager}.getActiveSessionTokens"
            },
            withSession: {
                funcName: "gpii.flowManager.sessionAware.withSession",
                args: ["{that}", "{flowManager}.lifecycleManager", "{arguments}.0", "{arguments}.1", "{arguments}.2"]
            }
        }
    });
 
    gpii.flowManager.sessionAware.withSession = function (that, lifecycleManager, onSuccess, failMessage, onError) {
        onError = onError || that.events.onError.fire;
        var userTokens = that.getActiveSessionTokens();
        if (userTokens.length === 0) {
            failMessage = failMessage || "Error handling request which required active session, but none was active";
            onError({
                isError: true,
                statusCode: 401,
                message: failMessage
            });
        } else {
            var session = lifecycleManager.getSession(userTokens);
            onSuccess(session, userTokens);
        }
    };
 
})();