Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
// This file is part of Moodle - http://moodle.org/
2
//
3
// Moodle is free software: you can redistribute it and/or modify
4
// it under the terms of the GNU General Public License as published by
5
// the Free Software Foundation, either version 3 of the License, or
6
// (at your option) any later version.
7
//
8
// Moodle is distributed in the hope that it will be useful,
9
// but WITHOUT ANY WARRANTY; without even the implied warranty of
10
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
// GNU General Public License for more details.
12
//
13
// You should have received a copy of the GNU General Public License
14
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
15
 
16
/* global H5PEmbedCommunicator:true */
17
/**
18
 * When embedded the communicator helps talk to the parent page.
19
 * This is a copy of the H5P.communicator, which we need to communicate in this context
20
 *
21
 * @type {H5PEmbedCommunicator}
22
 * @module     core_h5p
23
 * @copyright  2019 Joubel AS <contact@joubel.com>
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
26
H5PEmbedCommunicator = (function() {
27
    /**
28
     * @class
29
     * @private
30
     */
31
    function Communicator() {
32
        var self = this;
33
 
34
        // Maps actions to functions.
35
        var actionHandlers = {};
36
 
37
        // Register message listener.
38
        window.addEventListener('message', function receiveMessage(event) {
39
            if (window.parent !== event.source || event.data.context !== 'h5p') {
40
                return; // Only handle messages from parent and in the correct context.
41
            }
42
 
43
            if (actionHandlers[event.data.action] !== undefined) {
44
                actionHandlers[event.data.action](event.data);
45
            }
46
        }, false);
47
 
48
        /**
49
         * Register action listener.
50
         *
51
         * @param {string} action What you are waiting for
52
         * @param {function} handler What you want done
53
         */
54
        self.on = function(action, handler) {
55
            actionHandlers[action] = handler;
56
        };
57
 
58
        /**
59
         * Send a message to the all mighty father.
60
         *
61
         * @param {string} action
62
         * @param {Object} [data] payload
63
         */
64
        self.send = function(action, data) {
65
            if (data === undefined) {
66
                data = {};
67
            }
68
            data.context = 'h5p';
69
            data.action = action;
70
 
71
            // Parent origin can be anything.
72
            window.parent.postMessage(data, '*');
73
        };
74
 
75
        /* eslint-disable promise/avoid-new */
76
        const repositoryPromise = new Promise((resolve) => {
77
            require(['core_h5p/repository'], (Repository) => {
78
 
79
                // Replace the default versions.
80
                self.post = Repository.postStatement;
81
                self.postState = Repository.postState;
82
                self.deleteState = Repository.deleteState;
83
 
84
                // Resolve the Promise with Repository to allow any queued calls to be executed.
85
                resolve(Repository);
86
            });
87
        });
88
 
89
        /**
90
         * Send a xAPI statement to LMS.
91
         *
92
         * @param {string} component
93
         * @param {Object} statements
94
         * @returns {Promise}
95
         */
96
        self.post = (component, statements) => repositoryPromise.then((Repository) => Repository.postStatement(
97
            component,
98
            statements,
99
        ));
100
 
101
        /**
102
         * Send a xAPI state to LMS.
103
         *
104
         * @param {string} component
105
         * @param {string} activityId
106
         * @param {Object} agent
107
         * @param {string} stateId
108
         * @param {string} stateData
109
         * @returns {void}
110
         */
111
        self.postState = (
112
            component,
113
            activityId,
114
            agent,
115
            stateId,
116
            stateData,
117
        ) => repositoryPromise.then((Repository) => Repository.postState(
118
            component,
119
            activityId,
120
            agent,
121
            stateId,
122
            stateData,
123
        ));
124
 
125
        /**
126
         * Delete a xAPI state from LMS.
127
         *
128
         * @param {string} component
129
         * @param {string} activityId
130
         * @param {Object} agent
131
         * @param {string} stateId
132
         * @returns {Promise}
133
         */
134
        self.deleteState = (component, activityId, agent, stateId) => repositoryPromise.then((Repository) => Repository.deleteState(
135
            component,
136
            activityId,
137
            agent,
138
            stateId,
139
        ));
140
    }
141
 
142
    return (window.postMessage && window.addEventListener ? new Communicator() : undefined);
143
})();
144
 
145
var getH5PObject = async (iFrame) => {
146
    var H5P = iFrame.contentWindow.H5P;
147
    if (H5P?.instances?.[0]) {
148
        return H5P;
149
    }
150
 
151
    // In some cases, the H5P takes a while to be initialized (which causes some random behat failures).
152
    const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
153
    let remainingAttemps = 10;
154
    while (!H5P?.instances?.[0] && remainingAttemps > 0) {
155
        await sleep(100);
156
        H5P = iFrame.contentWindow.H5P;
157
        remainingAttemps--;
158
    }
159
    return H5P;
160
};
161
 
1441 ariadna 162
/* eslint-disable promise/no-native */
163
/**
164
 * Load the core/pending module.
165
 * @returns {Promise<Pending>}
166
 */
167
const getPendingClass = () => new Promise((resolve) => {
168
    require(['core/pending'], (Pending) => {
169
        resolve(Pending);
170
    });
171
});
172
 
1 efrain 173
document.onreadystatechange = async() => {
174
    // Wait for instances to be initialize.
175
    if (document.readyState !== 'complete') {
176
        return;
177
    }
178
 
179
    /** @var {boolean} statementPosted Whether the statement has been sent or not, to avoid sending xAPI State after it. */
180
    var statementPosted = false;
181
 
182
    // Check for H5P iFrame.
183
    var iFrame = document.querySelector('.h5p-iframe');
184
    if (!iFrame || !iFrame.contentWindow) {
185
        return;
186
    }
187
    var H5P = await getH5PObject(iFrame);
188
    if (!H5P?.instances?.[0]) {
189
        return;
190
    }
191
 
192
    var resizeDelay;
193
    var instance = H5P.instances[0];
194
    var parentIsFriendly = false;
195
 
196
    // Handle that the resizer is loaded after the iframe.
197
    H5PEmbedCommunicator.on('ready', function() {
198
        H5PEmbedCommunicator.send('hello');
199
    });
200
 
201
    // Handle hello message from our parent window.
202
    H5PEmbedCommunicator.on('hello', function() {
203
        // Initial setup/handshake is done.
204
        parentIsFriendly = true;
205
 
206
        // Hide scrollbars for correct size.
207
        iFrame.contentDocument.body.style.overflow = 'hidden';
208
 
209
        document.body.classList.add('h5p-resizing');
210
 
211
        // Content need to be resized to fit the new iframe size.
212
        H5P.trigger(instance, 'resize');
213
    });
214
 
215
    // When resize has been prepared tell parent window to resize.
216
    H5PEmbedCommunicator.on('resizePrepared', function() {
217
        H5PEmbedCommunicator.send('resize', {
218
            scrollHeight: iFrame.contentDocument.body.scrollHeight
219
        });
220
    });
221
 
222
    H5PEmbedCommunicator.on('resize', function() {
223
        H5P.trigger(instance, 'resize');
224
    });
225
 
1441 ariadna 226
    const Pending = await getPendingClass();
227
    var resizePending = new Pending('core_h5p/iframe:resize');
228
 
1 efrain 229
    H5P.on(instance, 'resize', function() {
230
        if (H5P.isFullscreen) {
231
            return; // Skip iframe resize.
232
        }
233
 
234
        // Use a delay to make sure iframe is resized to the correct size.
235
        clearTimeout(resizeDelay);
236
        resizeDelay = setTimeout(function() {
237
            // Only resize if the iframe can be resized.
238
            if (parentIsFriendly) {
239
                H5PEmbedCommunicator.send('prepareResize',
240
                    {
241
                        scrollHeight: iFrame.contentDocument.body.scrollHeight,
242
                        clientHeight: iFrame.contentDocument.body.clientHeight
243
                    }
244
                );
245
            } else {
246
                H5PEmbedCommunicator.send('hello');
247
            }
1441 ariadna 248
            resizePending.resolve();
249
        }, 150);
1 efrain 250
    });
251
 
252
    // Get emitted xAPI data.
253
    H5P.externalDispatcher.on('xAPI', function(event) {
254
        statementPosted = false;
255
        var moodlecomponent = H5P.getMoodleComponent();
256
        if (moodlecomponent == undefined) {
257
            return;
258
        }
259
        // Skip malformed events.
260
        var hasStatement = event && event.data && event.data.statement;
261
        if (!hasStatement) {
262
            return;
263
        }
264
 
265
        var statement = event.data.statement;
266
        var validVerb = statement.verb && statement.verb.id;
267
        if (!validVerb) {
268
            return;
269
        }
270
 
271
        var isCompleted = statement.verb.id === 'http://adlnet.gov/expapi/verbs/answered'
272
                    || statement.verb.id === 'http://adlnet.gov/expapi/verbs/completed';
273
 
274
        var isChild = statement.context && statement.context.contextActivities &&
275
        statement.context.contextActivities.parent &&
276
        statement.context.contextActivities.parent[0] &&
277
        statement.context.contextActivities.parent[0].id;
278
 
279
        if (isCompleted && !isChild) {
280
            var statements = H5P.getXAPIStatements(this.contentId, statement);
281
            H5PEmbedCommunicator.post(moodlecomponent, statements);
282
            // Mark the statement has been sent, to avoid sending xAPI State after it.
283
            statementPosted = true;
284
        }
285
    });
286
 
287
    H5P.externalDispatcher.on('xAPIState', function(event) {
288
        var moodlecomponent = H5P.getMoodleComponent();
289
        var contentId = event.data.activityId;
290
        var stateId = event.data.stateId;
291
        var state = event.data.state;
292
        if (state === undefined) {
293
            // When state is undefined, a call to the WS for getting the state could be done. However, for now, this is not
294
            // required because the content state is initialised with PHP.
295
            return;
296
        }
297
 
298
        if (state === null) {
299
            // When this method is called from the H5P API with null state, the state must be deleted using the rest of attributes.
300
            H5PEmbedCommunicator.deleteState(moodlecomponent, contentId, H5P.getxAPIActor(), stateId);
301
        } else if (!statementPosted) {
302
            // Only update the state if a statement hasn't been posted recently.
303
            // When state is defined, it needs to be updated. As not all the H5P content types are returning a JSON, we need
304
            // to simulate it because xAPI State defines statedata as a JSON.
305
            var statedata = {
306
                h5p: state
307
            };
308
            H5PEmbedCommunicator.postState(moodlecomponent, contentId, H5P.getxAPIActor(), stateId, JSON.stringify(statedata));
309
        }
310
    });
311
 
312
    H5P.trigger(instance, 'resize');
313
};