Proyectos de Subversion Moodle

Rev

Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * mod_bigbluebuttonbn data generator
19
 *
20
 * @package    mod_bigbluebuttonbn
21
 * @category   test
22
 * @copyright  2018 - present, Blindside Networks Inc
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 * @author     Jesus Federico  (jesus [at] blindsidenetworks [dt] com)
25
 */
26
 
27
use core\plugininfo\mod;
28
use mod_bigbluebuttonbn\instance;
29
use mod_bigbluebuttonbn\local\config;
30
use mod_bigbluebuttonbn\logger;
31
use mod_bigbluebuttonbn\recording;
32
 
33
/**
34
 * bigbluebuttonbn module data generator
35
 *
36
 * @package    mod_bigbluebuttonbn
37
 * @category   test
38
 * @copyright  2018 - present, Blindside Networks Inc
39
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40
 * @author     Jesus Federico  (jesus [at] blindsidenetworks [dt] com)
41
 */
42
class mod_bigbluebuttonbn_generator extends \testing_module_generator {
43
 
44
    /**
45
     * Creates an instance of bigbluebuttonbn for testing purposes.
46
     *
47
     * @param array|stdClass $record data for module being generated.
48
     * @param null|array $options general options for course module.
49
     * @return stdClass record from module-defined table with additional field cmid
50
     */
51
    public function create_instance($record = null, array $options = null) {
52
        // Prior to creating the instance, make sure that the BigBlueButton module is enabled.
53
        $modules = \core_plugin_manager::instance()->get_plugins_of_type('mod');
54
        if (!$modules['bigbluebuttonbn']->is_enabled()) {
55
            mod::enable_plugin('bigbluebuttonbn', true);
56
        }
57
 
58
        $now = time();
59
        $defaults = [
60
            "type" => 0,
61
            "meetingid" => sha1(rand()),
62
            "record" => true,
63
            "moderatorpass" => "mp",
64
            "viewerpass" => "ap",
65
            "participants" => "{}",
66
            "timecreated" => $now,
67
            "timemodified" => $now,
68
            "presentation" => null,
69
            "recordings_preview" => 0
70
        ];
71
 
72
        $record = (array) $record;
73
 
74
        $record['participants'] = json_encode($this->get_participants_from_record($record));
75
 
76
        foreach ($defaults as $key => $value) {
77
            if (!isset($record[$key])) {
78
                $record[$key] = $value;
79
            }
80
        }
81
        if ($record['presentation']) {
82
            global $USER;
83
            // Here we replace the original presentation file with a draft area in which we store this file.
84
            $draftareaid = file_get_unused_draft_itemid();
85
            $bbbfilerecord['contextid'] = context_user::instance($USER->id)->id;
86
            $bbbfilerecord['component'] = 'user';
87
            $bbbfilerecord['filearea'] = 'draft';
88
            $bbbfilerecord['itemid'] = $draftareaid;
89
            $bbbfilerecord['filepath'] = '/';
90
            $bbbfilerecord['filename'] = basename($record['presentation']);
91
            $fs = get_file_storage();
92
 
93
            $fs->create_file_from_pathname($bbbfilerecord, $record['presentation']);
94
            // Now the $record['presentation'] must contain the draftareaid.
95
            $record['presentation'] = $draftareaid;
96
        }
97
        return parent::create_instance((object) $record, (array) $options);
98
    }
99
 
100
    /**
101
     * Create the participants field data from create_instance data.
102
     *
103
     * @param array $record
104
     * @return array
105
     */
106
    protected function get_participants_from_record(array $record): array {
107
        $roles = [];
108
        if (array_key_exists('moderators', $record) && !empty($record['moderators'])) {
109
            $roles = array_merge(
110
                $roles,
111
                $this->get_participant_configuration($record['moderators'], 'moderator')
112
            );
113
            unset($record['moderators']);
114
        }
115
 
116
        if (array_key_exists('viewers', $record) && !empty($record['viewers'])) {
117
            $roles = array_merge(
118
                $roles,
119
                $this->get_participant_configuration($record['viewers'], 'viewer')
120
            );
121
            unset($record['viewers']);
122
        }
123
 
124
        if (!empty($roles)) {
125
            array_unshift($roles, (object) [
126
                'selectiontype' => 'all',
127
                'selectionid' => 'all',
128
                'role' => 'viewer',
129
            ]);
130
        }
131
 
132
        return $roles;
133
    }
134
 
135
    /**
136
     * Get the participant configuration for a field and role for use in get_participants_from_record.
137
     *
138
     * @param string $field
139
     * @param string $role
140
     * @return array
141
     */
142
    protected function get_participant_configuration(string $field, string $role): array {
143
        global $DB;
144
 
145
        $values = explode(',', $field);
146
 
147
        $roles = $DB->get_records_menu('role', [], '', 'shortname, id');
148
 
149
        $configuration = [];
150
        foreach ($values as $value) {
151
            if (empty($value)) {
152
                // Empty value.
153
                continue;
154
            }
155
            [$type, $name] = explode(':', $value);
156
 
157
            $participant = (object) [
158
                'selectiontype' => $type,
159
                'role' => $role,
160
            ];
161
            switch ($type) {
162
                case 'role':
163
                    if (!array_key_exists($name, $roles)) {
164
                        throw new \coding_exception("Unknown role '{$name}'");
165
                    }
166
                    $participant->selectionid = $roles[$name];
167
 
168
                    break;
169
                case 'user':
170
                    $participant->selectionid = $DB->get_field('user', 'id', ['username' => $name], MUST_EXIST);
171
                    break;
172
                default:
173
                    throw new \coding_exception("Unknown participant type: '{$type}'");
174
            }
175
 
176
            $configuration[] = $participant;
177
        }
178
 
179
        return $configuration;
180
    }
181
 
182
    /**
183
     * Create a recording for the given bbb activity.
184
     *
185
     * The recording is created both locally, and a recording record is created on the mocked BBB server.
186
     *
187
     * @param array $data
188
     * @param bool $serveronly create it only on the server, not in the database.
189
     * @return stdClass the recording object
190
     */
191
    public function create_recording(array $data, $serveronly = false): stdClass {
192
        $instance = instance::get_from_instanceid($data['bigbluebuttonbnid']);
193
 
194
        if (isset($data['imported']) && filter_var($data['imported'], FILTER_VALIDATE_BOOLEAN)) {
195
            if (empty($data['importedid'])) {
196
                throw new moodle_exception('error');
197
            }
198
            $recording = recording::get_record(['recordingid' => $data['importedid']]);
199
            $recording->imported = true;
200
        } else {
201
            $recording = (object) [
202
                'headless' => false,
203
                'imported' => false,
204
                'status' => $data['status'] ?? recording::RECORDING_STATUS_NOTIFIED,
205
            ];
206
        }
207
 
208
        if (!empty($data['groupid'])) {
209
            $instance->set_group_id($data['groupid']);
210
            $recording->groupid = $data['groupid'];
211
        }
212
 
213
        $recording->bigbluebuttonbnid = $instance->get_instance_id();
214
        $recording->courseid = $instance->get_course_id();
215
        if (isset($options['imported']) && $options['imported']) {
216
            $precording = $recording->create_imported_recording($instance);
217
        } else {
218
            if ($recording->status == recording::RECORDING_STATUS_DISMISSED) {
219
                $recording->recordingid = sprintf(
220
                    "%s-%s",
221
                    md5($instance->get_meeting_id()),
222
                    time() + rand(1, 100000)
223
                );
224
            } else {
225
                $recording->recordingid = $this->create_mockserver_recording($instance, $recording, $data);
226
            }
227
            $precording = new recording(0, $recording);
228
            if (!$serveronly) {
229
                $precording->create();
230
            }
231
        }
232
        return $precording->to_record();
233
    }
234
 
235
    /**
236
     * Add a recording in the mock server
237
     *
238
     * @param instance $instance
239
     * @param stdClass $recordingdata
240
     * @param array $data
241
     * @return string
242
     */
243
    protected function create_mockserver_recording(instance $instance, stdClass $recordingdata, array $data): string {
244
        $now = time();
245
        $mockdata = array_merge((array) $recordingdata, [
246
            'sequence' => 1,
247
            'meta' => [
248
                'bn-presenter-name' => $data['presentername'] ?? 'Fake presenter',
249
                'bn-recording-ready-url' => new moodle_url('/mod/bigbluebuttonbn/bbb_broker.php', [
250
                    'action' => 'recording_ready',
251
                    'bigbluebuttonbn' => $instance->get_instance_id()
252
                ]),
253
                'bbb-recording-description' => $data['description'] ?? '',
254
                'bbb-recording-name' => $data['name'] ?? '',
255
                'bbb-recording-tags' => $data['tags'] ?? '',
256
            ],
257
        ]);
258
        $mockdata['startTime'] = $data['starttime'] ?? $now;
259
        $mockdata['endTime'] = $data['endtime'] ?? $mockdata['startTime'] + HOURSECS;
260
        if (!empty($data['playback'])) {
261
            $mockdata['playback'] = json_encode($data['playback']);
262
        }
263
        if (!empty($data['isBreakout'])) {
264
            // If it is a breakout meeting, we do not have any way to know the real Id of the meeting
265
            // unless we query the list of submeetings.
266
            // For now we will just send the parent ID and let the mock server deal with the sequence + parentID
267
            // to find the meetingID.
268
            $mockdata['parentMeetingID'] = $instance->get_meeting_id();
269
        } else {
270
            $mockdata['meetingID'] = $instance->get_meeting_id();
271
        }
272
 
273
        $result = $this->send_mock_request('backoffice/createRecording', [], $mockdata);
274
 
275
        return (string) $result->recordID;
276
    }
277
 
278
    /**
279
     * Utility to send a request to the mock server
280
     *
281
     * @param string $endpoint
282
     * @param array $params
283
     * @param array $mockdata
284
     * @return SimpleXMLElement|bool
285
     * @throws moodle_exception
286
     */
287
    protected function send_mock_request(string $endpoint, array $params = [], array $mockdata = []): SimpleXMLElement {
288
        $url = $this->get_mocked_server_url($endpoint, $params);
289
 
290
        foreach ($mockdata as $key => $value) {
291
            if (is_array($value)) {
292
                foreach ($value as $subkey => $subvalue) {
293
                    $paramname = "{$key}_{$subkey}";
294
                    $url->param($paramname, $subvalue);
295
                }
296
            } else {
297
                $url->param($key, $value);
298
            }
299
        }
300
 
301
        $curl = new \curl();
302
        $result = $curl->get($url->out_omit_querystring(), $url->params());
303
 
304
        $retvalue = @simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
305
        if ($retvalue === false) {
306
            throw new moodle_exception('mockserverconnfailed', 'mod_bigbluebutton');
307
        }
308
        return $retvalue;
309
    }
310
 
311
    /**
312
     * Get a URL for a mocked BBB server endpoint.
313
     *
314
     * @param string $endpoint
315
     * @param array $params
316
     * @return moodle_url
317
     */
318
    protected function get_mocked_server_url(string $endpoint = '', array $params = []): moodle_url {
319
        return new moodle_url(TEST_MOD_BIGBLUEBUTTONBN_MOCK_SERVER . '/' . $endpoint, $params);
320
    }
321
 
322
    /**
323
     * Mock an in-progress meeting on the remote server.
324
     *
325
     * @param array $data
326
     * @return stdClass
327
     */
328
    public function create_meeting(array $data): stdClass {
329
        $instance = instance::get_from_instanceid($data['instanceid']);
330
 
331
        if (array_key_exists('groupid', $data)) {
332
            $instance = instance::get_group_instance_from_instance($instance, $data['groupid']);
333
        }
334
 
335
        $meetingid = $instance->get_meeting_id();
336
 
337
        // Default room configuration.
338
        $roomconfig = array_merge($data, [
339
            'meetingName' => $instance->get_meeting_name(),
340
            'attendeePW' => $instance->get_viewer_password(),
341
            'moderatorPW' => $instance->get_moderator_password(),
342
            'voiceBridge' => $instance->get_voice_bridge(),
343
            'meta' => [
344
                'bbb-context' => $instance->get_course()->fullname,
345
                'bbb-context-id' => $instance->get_course()->id,
346
                'bbb-context-label' => $instance->get_course()->shortname,
347
                'bbb-context-name' => $instance->get_course()->fullname,
348
                'bbb-origin' => 'Moodle',
349
                'bbb-origin-tag' => 'moodle-mod_bigbluebuttonbn (TODO version)',
350
                'bbb-recording-description' => $instance->get_meeting_description(),
351
                'bbb-recording-name' => $instance->get_meeting_name(),
352
            ],
353
        ]);
354
        if ((boolean) config::get('recordingready_enabled')) {
355
            $roomconfig['meta']['bn-recording-ready-url'] = $instance->get_record_ready_url()->out(false);
356
        }
357
        if ((boolean) config::get('meetingevents_enabled')) {
358
            $roomconfig['meta']['analytics-callback-url'] = $instance->get_meeting_event_notification_url()->out(false);
359
        }
360
        if (!empty($roomconfig['isBreakout'])) {
361
            // If it is a breakout meeting, we do not have any way to know the real Id of the meeting
362
            // For now we will just send the parent ID and let the mock server deal with the sequence + parentID
363
            // to find the meetingID.
364
            $roomconfig['parentMeetingID'] = $instance->get_meeting_id();
365
        } else {
366
            $roomconfig['meetingID'] = $meetingid;
367
        }
368
        $this->send_mock_request('backoffice/createMeeting', [], $roomconfig);
369
        return (object) $roomconfig;
370
    }
371
 
372
    /**
373
     * Create a log record
374
     *
375
     * @param mixed $record
376
     * @param array|null $options
377
     */
378
    public function create_log($record, array $options = null) {
379
        $instance = instance::get_from_instanceid($record['bigbluebuttonbnid']);
380
 
381
        $record = array_merge([
382
            'meetingid' => $instance->get_meeting_id(),
383
        ], (array) $record);
384
 
385
        $testlogclass = new class extends logger {
386
            /**
387
             * Log test event
388
             *
389
             * @param instance $instance
390
             * @param array $record
391
             */
392
            public static function log_test_event(instance $instance, array $record): void {
393
                self::log(
394
                    $instance,
395
                    logger::EVENT_CREATE,
396
                    $record
397
                );
398
            }
399
        };
400
 
401
        $testlogclass::log_test_event($instance, $record);
402
    }
403
 
404
    /**
405
     * Set a value in the Mock server
406
     *
407
     * @param string $name
408
     * @param mixed $value
409
     * @return void
410
     * @throws moodle_exception
411
     */
412
    public function set_value(string $name, $value): void {
413
        if (defined('TEST_MOD_BIGBLUEBUTTONBN_MOCK_SERVER')) {
414
            $this->send_mock_request('backoffice/set', [], ['name' => $name, 'value' => json_encode($value)]);
415
        }
416
    }
417
 
418
    /**
419
     * Trigger a meeting event on BBB side
420
     *
421
     * @param object $user
422
     * @param instance $instance
423
     * @param string $eventtype
424
     * @param string|null $eventdata
425
     * @return void
426
     */
427
    public function add_meeting_event(object $user, instance $instance, string $eventtype, string $eventdata = ''): void {
428
        $this->send_mock_request('backoffice/addMeetingEvent', [
429
                'secret' => \mod_bigbluebuttonbn\local\config::DEFAULT_SHARED_SECRET,
430
                'meetingID' => $instance->get_meeting_id(),
431
                'attendeeID' => $user->id,
432
                'attendeeName' => fullname($user),
433
                'eventType' => $eventtype,
434
                'eventData' => $eventdata
435
            ]
436
        );
437
    }
438
 
439
    /**
440
     * Send all previously store events
441
     *
442
     * @param instance $instance
443
     * @return object|null
444
     */
445
    public function send_all_events(instance $instance): ?object {
446
        if (defined('TEST_MOD_BIGBLUEBUTTONBN_MOCK_SERVER')) {
447
            return $this->send_mock_request('backoffice/sendAllEvents', [
448
                'meetingID' => $instance->get_meeting_id(),
449
                'sendQuery' => false, // We get the result directly here.
450
                'secret' => \mod_bigbluebuttonbn\local\config::DEFAULT_SHARED_SECRET,
451
            ]);
452
        }
453
        return null;
454
    }
455
 
456
    /**
457
     * Reset the mock server
458
     */
459
    public function reset_mock(): void {
460
        if (defined('TEST_MOD_BIGBLUEBUTTONBN_MOCK_SERVER')) {
461
            $this->send_mock_request('backoffice/reset');
462
        }
463
    }
464
}