From 06d1a7c4f03aa57f3039f314fd01fcbde583f72a Mon Sep 17 00:00:00 2001 From: Daniel Thies Date: Thu, 11 Sep 2025 13:16:31 -0500 Subject: [PATCH 01/10] VID-969: Implement local text tracks --- backup/moodle2/backup_videotime_stepslib.php | 14 + backup/moodle2/restore_videotime_stepslib.php | 23 +- classes/file_info_container.php | 258 ++++++++++++++++++ classes/hook/dndupload_register.php | 3 +- classes/videotime_instance.php | 6 +- classes/vimeo_embed.php | 35 +++ db/install.xml | 17 +- db/upgrade.php | 27 ++ lang/en/videotime.php | 10 + lib.php | 183 ++++++++++++- mod_form.php | 110 ++++++++ plugin/videojs/amd/build/videotime.min.js | 4 +- plugin/videojs/amd/build/videotime.min.js.map | 2 +- plugin/videojs/amd/src/videotime.js | 57 ---- .../videojs/classes/file_info_container.php | 256 +++++++++++++++++ plugin/videojs/db/install.xml | 2 +- plugin/videojs/lib.php | 56 +++- plugin/videojs/templates/video_embed.mustache | 8 + tab/chapter/classes/tab.php | 14 + tab/chapter/lang/en/videotimetab_chapter.php | 1 + tab/chapter/templates/tab.mustache | 9 + tab/texttrack/amd/build/selecttrack.min.js | 2 +- .../amd/build/selecttrack.min.js.map | 2 +- tab/texttrack/amd/src/selecttrack.js | 2 +- tab/texttrack/classes/tab.php | 75 ++--- .../lang/en/videotimetab_texttrack.php | 2 + tab/texttrack/templates/text_tab.mustache | 19 +- version.php | 2 +- 28 files changed, 1075 insertions(+), 124 deletions(-) create mode 100644 classes/file_info_container.php create mode 100644 plugin/videojs/classes/file_info_container.php diff --git a/backup/moodle2/backup_videotime_stepslib.php b/backup/moodle2/backup_videotime_stepslib.php index 8f0d36f1..f361e106 100644 --- a/backup/moodle2/backup_videotime_stepslib.php +++ b/backup/moodle2/backup_videotime_stepslib.php @@ -89,7 +89,19 @@ protected function define_structure() { 'enabletabs', ]); + $texttracks = new backup_nested_element('texttracks'); + $texttrack = new backup_nested_element('texttrack', ['id'], [ + 'videotime', + 'isdefault', + 'kind', + 'label', + 'srclang', + 'visible', + ]); + // Build the tree. + $module->add_child($texttracks); + $texttracks->add_child($texttrack); // Define elements for tab subplugin settings. $this->add_subplugin_structure('videotimetab', $module, true); @@ -99,10 +111,12 @@ protected function define_structure() { // Define sources. $module->set_source_table('videotime', ['id' => backup::VAR_ACTIVITYID]); + $texttrack->set_source_table('videotime_track', ['videotime' => backup::VAR_PARENTID], 'id ASC'); // Define file annotations. $module->annotate_files('mod_videotime', 'intro', null); // This file area hasn't itemid. $module->annotate_files('mod_videotime', 'video_description', null); // This file area hasn't itemid. + $texttrack->annotate_files('mod_videotime', 'texttrack', 'id'); $this->annotate_plugin_config_files($module, 'videotimetab'); $this->annotate_plugin_config_files($module, 'videotimeplugin'); diff --git a/backup/moodle2/restore_videotime_stepslib.php b/backup/moodle2/restore_videotime_stepslib.php index bac1f0bf..488be1f7 100644 --- a/backup/moodle2/restore_videotime_stepslib.php +++ b/backup/moodle2/restore_videotime_stepslib.php @@ -45,6 +45,9 @@ protected function define_structure() { $videotime = new restore_path_element('videotime', '/activity/videotime'); $paths[] = $videotime; + $texttrack = new restore_path_element('texttrack', '/activity/videotime/texttracks/texttrack'); + $paths[] = $texttrack; + if ($userinfo) { $paths[] = new restore_path_element('videotime_session', '/activity/videotime/sessions/session'); } @@ -82,7 +85,7 @@ protected function add_subplugin_files($subtype) { } /** - * Processes the videotim restore data. + * Processes the videotime restore data. * * @param array $data Parsed element data. */ @@ -102,6 +105,23 @@ protected function process_videotime($data) { $this->apply_activity_instance($newitemid); } + /** + * Processes the texttrack restore data. + * + * @param array $data Parsed element data. + */ + protected function process_texttrack($data) { + global $DB; + + $data = (object)$data; + $oldid = $data->id; + $data->videotime = $this->get_new_parentid('videotime'); + + // Insert the videotime record. + $newitemid = $DB->insert_record('videotime_track', $data); + $this->set_mapping('videotime_track', $oldid, $newitemid, true); + } + /** * Process session data * @@ -138,6 +158,7 @@ protected function after_execute() { // Add videotime related files, no need to match by itemname (just internally handled context). $this->add_related_files('mod_videotime', 'intro', null); $this->add_related_files('mod_videotime', 'video_description', null); + $this->add_related_files('mod_videotime', 'texttrack', 'videotime_track'); $this->add_subplugin_files('videotimeplugin'); } diff --git a/classes/file_info_container.php b/classes/file_info_container.php new file mode 100644 index 00000000..0e3adb3d --- /dev/null +++ b/classes/file_info_container.php @@ -0,0 +1,258 @@ +. + +namespace mod_videotime; + +use file_info; +use file_info_stored; + +/** + * File browsing support class. + * + * @package mod_videotime + * @copyright 2025 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class file_info_container extends file_info { + /** + * Constructor + * + * @param file_browser $browser The file_browser instance + * @param stdClass $course Course object + * @param stdClass $cm course Module object + * @param stdClass $context Module context + * @param array $areas Available file areas + * @param string $filearea File area to browse + */ + public function __construct( + $browser, + /** @var stdClass $course Course object */ + protected $course, + /** @var stdClass $cm Course module object */ + protected $cm, + $context, + /** @var array Available file areas */ + protected $areas, + /** @var string File area to browse */ + protected $filearea + ) { + parent::__construct($browser, $context); + } + + /** + * Returns list of standard virtual file/directory identification. + * The difference from stored_file parameters is that null values + * are allowed in all fields + * @return array with keys contextid, filearea, itemid, filepath and filename + */ + public function get_params() { + return ['contextid' => $this->context->id, + 'component' => 'mod_videotime', + 'filearea' => $this->filearea, + 'itemid' => null, + 'filepath' => null, + 'filename' => null]; + } + + /** + * Returns localised visible name. + * @return string + */ + public function get_visible_name() { + return $this->areas[$this->filearea]; + } + + /** + * Can I add new files or directories? + * @return bool + */ + public function is_writable() { + return false; + } + + /** + * Is directory? + * @return bool + */ + public function is_directory() { + return true; + } + + /** + * Returns list of children. + * @return array of file_info instances + */ + public function get_children() { + return $this->get_filtered_children('*', false, true); + } + + /** + * Help function to return files matching extensions or their count + * + * @param string|array $extensions + * @param bool|int $countonly + * @param bool $returnemptyfolders + * @return array|int array of file_info instances or the count + */ + private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) { + global $DB; + + $params = [ + 'contextid' => $this->context->id, + 'component' => 'mod_videotime', + 'filearea' => $this->filearea, + ]; + $sql = 'SELECT DISTINCT itemid + FROM {files} + WHERE contextid = :contextid + AND component = :component + AND filearea = :filearea'; + + if (!$returnemptyfolders) { + $sql .= ' AND filename <> :emptyfilename'; + $params['emptyfilename'] = '.'; + } + + [$sql2, $params2] = $this->build_search_files_sql($extensions); + $sql .= ' ' . $sql2; + $params = array_merge($params, $params2); + + if ($countonly !== false) { + $sql .= ' ORDER BY itemid DESC'; + } + + $rs = $DB->get_recordset_sql($sql, $params); + $children = []; + foreach ($rs as $record) { + if ( + ($child = $this->browser->get_file_info($this->context, 'mod_videotime', $this->filearea, $record->itemid)) + && ($returnemptyfolders || $child->count_non_empty_children($extensions)) + ) { + $children[] = $child; + } + if ($countonly !== false && count($children) >= $countonly) { + break; + } + } + $rs->close(); + if ($countonly !== false) { + return count($children); + } + return $children; + } + + /** + * Returns list of children which are either files matching the specified extensions + * or folders that contain at least one such file. + * + * @param string|array $extensions + * @return array + */ + public function get_non_empty_children($extensions = '*') { + return $this->get_filtered_children($extensions, false); + } + + /** + * Returns the number of children which are either files matching the specified extensions + * or folders containing at least one such file. + * + * @param string|array $extensions + * @param int $limit + * @return int + */ + public function count_non_empty_children($extensions = '*', $limit = 1) { + return $this->get_filtered_children($extensions, $limit); + } + + /** + * Returns parent file_info instance + * @return file_info or null for root + */ + public function get_parent() { + return $this->browser->get_file_info($this->context); + } + + /** + * File browsing support for mod_videotime file areas. + * + * @package mod_videotime + * @category files + * + * @param file_browser $browser + * @param array $areas + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @param string $filearea + * @param int $itemid + * @param string $filepath + * @param string $filename + * @return file_info Instance or null if not found. + */ + public static function get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { + global $CFG, $DB, $USER; + + if ($context->contextlevel != CONTEXT_MODULE) { + return null; + } + + if (!isset($areas[$filearea])) { + return null; + } + + if (is_null($itemid)) { + return new static($browser, $course, $cm, $context, $areas, $filearea); + } + + if ( + $filearea == 'texttrack' + && !$texttrack = $DB->get_record('videotime_track', ['id' => $itemid], '*', IGNORE_MISSING) + ) { + return null; + } + + if (!$DB->get_record('videotime', ['id' => $cm->instance])) { + return null; + } + + $fs = get_file_storage(); + $filepath = is_null($filepath) ? '/' : $filepath; + $filename = is_null($filename) ? '.' : $filename; + if (!($storedfile = $fs->get_file($context->id, 'mod_videotime', $filearea, $itemid, $filepath, $filename))) { + return null; + } + + // Checks to see if the user can manage files or is the owner. + if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) { + return null; + } + + $urlbase = $CFG->wwwroot . '/pluginfile.php'; + $fullname = fullname(\core_user::get_user($storedfile->get_userid())); + + return new file_info_stored( + $browser, + $context, + $storedfile, + $urlbase, + get_string($texttrack->kind, 'videotime') . " ($texttrack->srclang) $texttrack->label", + true, + true, + false, + false + ); + } +} diff --git a/classes/hook/dndupload_register.php b/classes/hook/dndupload_register.php index 1c1b61df..32f3288d 100644 --- a/classes/hook/dndupload_register.php +++ b/classes/hook/dndupload_register.php @@ -38,8 +38,7 @@ final class dndupload_register { /** * Constructor for the hook */ - public function __construct( - ) { + public function __construct() { $this->extensions = []; } diff --git a/classes/videotime_instance.php b/classes/videotime_instance.php index 48783049..30742c19 100644 --- a/classes/videotime_instance.php +++ b/classes/videotime_instance.php @@ -45,13 +45,13 @@ */ class videotime_instance implements \renderable, \templatable { /** const int */ - const NORMAL_MODE = 0; + public const NORMAL_MODE = 0; /** const int */ - const LABEL_MODE = 1; + public const LABEL_MODE = 1; /** const int */ - const PREVIEW_MODE = 2; + public const PREVIEW_MODE = 2; /** * @var \stdClass diff --git a/classes/vimeo_embed.php b/classes/vimeo_embed.php index 4d4ae052..84b2c767 100644 --- a/classes/vimeo_embed.php +++ b/classes/vimeo_embed.php @@ -24,9 +24,11 @@ namespace mod_videotime; +use context_module; use core_component; use mod_videotime\local\tabs\tabs; use mod_videotime\output\next_activity_button; +use moodle_url; use renderer_base; defined('MOODLE_INTERNAL') || die(); @@ -108,6 +110,7 @@ public function export_for_template(renderer_base $output) { 'haspro' => videotime_has_pro(), 'interval' => $this->record->saveinterval ?? 5, 'plugins' => file_exists($CFG->dirroot . '/mod/videotime/plugin/pro/templates/plugins.mustache'), + 'texttracks' => $this->text_tracks(), 'uniqueid' => $this->get_uniqueid(), 'toast' => file_exists($CFG->dirroot . '/lib/amd/src/toast.js'), 'video_description' => $this->record->video_description, @@ -115,4 +118,36 @@ public function export_for_template(renderer_base $output) { return $context; } + + /** + * Get text tracks information + * + * @return array + */ + public function text_tracks(): array { + global $DB; + + $context = context_module::instance($this->get_cm()->id); + $fs = get_file_storage(); + + $texttracks = $DB->get_records('videotime_track', ['videotime' => $this->get_cm()->instance]); + + foreach ($fs->get_area_files($context->id, 'mod_videotime', 'texttrack') as $file) { + if (!$file->is_directory() && key_exists($file->get_itemid(), $texttracks)) { + $texttracks[$file->get_itemid()]->url = moodle_url::make_pluginfile_url( + $context->id, + 'mod_videotime', + 'texttrack', + $file->get_itemid(), + '/' . $file->get_contenthash() . $file->get_filepath(), + $file->get_filename() + )->out(false); + } + } + foreach ($texttracks as $texttrack) { + $texttrack->{$texttrack->kind} = true; + } + + return array_values($texttracks); + } } diff --git a/db/install.xml b/db/install.xml index 4994e671..75a01555 100644 --- a/db/install.xml +++ b/db/install.xml @@ -1,5 +1,5 @@ - @@ -32,5 +32,20 @@ + + + + + + + + + + + + + + +
diff --git a/db/upgrade.php b/db/upgrade.php index 69a7381d..ec83ce84 100644 --- a/db/upgrade.php +++ b/db/upgrade.php @@ -854,5 +854,32 @@ function xmldb_videotime_upgrade($oldversion) { upgrade_mod_savepoint(true, 2023011205, 'videotime'); } + if ($oldversion < 2025080500) { + + // Define table videotime_track to be created. + $table = new xmldb_table('videotime_track'); + + // Adding fields to table videotime_track. + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('videotime', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, null, null); + $table->add_field('isdefault', XMLDB_TYPE_INTEGER, '4', null, null, null, null); + $table->add_field('kind', XMLDB_TYPE_CHAR, '10', null, null, null, null); + $table->add_field('label', XMLDB_TYPE_TEXT, null, null, null, null, null); + $table->add_field('srclang', XMLDB_TYPE_CHAR, '10', null, null, null, null); + $table->add_field('visible', XMLDB_TYPE_INTEGER, '4', null, null, null, null); + + // Adding keys to table videotime_track. + $table->add_key('primary', XMLDB_KEY_PRIMARY, ['id']); + $table->add_key('videotime', XMLDB_KEY_FOREIGN, ['videotime'], 'videotime', ['id']); + + // Conditionally launch create table for videotime_track. + if (!$dbman->table_exists($table)) { + $dbman->create_table($table); + } + + // Videotime savepoint reached. + upgrade_mod_savepoint(true, 2025080500, 'videotime'); + } + return true; } diff --git a/lang/en/videotime.php b/lang/en/videotime.php index 0ecb43a8..e7509bb5 100644 --- a/lang/en/videotime.php +++ b/lang/en/videotime.php @@ -339,3 +339,13 @@ $string['watchpercent_help'] = 'The highest percentage of the video seend'; $string['watchtime_help'] = 'The farthest position seen by the user'; $string['with_play_button'] = 'with play button'; +$string['texttracks'] = 'Text tracks'; +$string['texttrackno'] = 'Text track {no}'; +$string['chapters'] = 'Chapters'; +$string['captions'] = 'Captions'; +$string['subtitles'] = 'Subtitles'; +$string['page-mod-videotime-view'] = 'Video Time view page'; +$string['page-mod-videotime-x'] = 'Any Video Time module page'; +$string['texttrack'] = 'Text track'; +$string['addtexttrack'] = 'Add text track'; +$string['tracktype'] = 'Track type'; diff --git a/lib.php b/lib.php index cbfce92b..489e2268 100644 --- a/lib.php +++ b/lib.php @@ -30,6 +30,7 @@ require_once($CFG->dirroot . '/lib/completionlib.php'); use mod_videotime\videotime_instance; +use mod_videotime\file_info_container; /** * Checks if Videotime supports a specific feature. @@ -214,6 +215,29 @@ function videotime_add_instance($moduleinstance, $mform = null) { $completiontimeexpected ); + $context = context_module::instance($moduleinstance->coursemodule); + foreach ($moduleinstance->trackid ?? [] as $key => $trackid) { + $record = [ + 'videotime' => $moduleinstance->id, + 'srclang' => $moduleinstance->srclang[$key], + 'kind' => $moduleinstance->tracktype[$key], + 'label' => $moduleinstance->tracklabel[$key], + 'visible' => $moduleinstance->trackvisible[$key], + 'isdefault' => $moduleinstance->trackdefault[$key], + ]; + + $record['id'] = $DB->insert_record('videotime_track', $record); + + file_save_draft_area_files( + $moduleinstance->texttrack[$key], + $context->id, + 'mod_videotime', + 'texttrack', + $record['id'], + ['subdirs' => true] + ); + } + return $moduleinstance->id; } @@ -232,6 +256,7 @@ function videotime_update_instance($moduleinstance, $mform = null) { global $DB; $cm = get_coursemodule_from_id('videotime', $moduleinstance->coursemodule); + $context = context_module::instance($moduleinstance->coursemodule); $moduleinstance->timemodified = time(); $moduleinstance->id = $cm->instance; @@ -274,6 +299,47 @@ function videotime_update_instance($moduleinstance, $mform = null) { $moduleinstance->viewpercentgrade = $moduleinstance->viewpercentgrade ?? 0; + // Remove orphaned files. + $fs = get_file_storage(); + foreach ($fs->get_area_files($context->id, 'mod_videotime', 'texttrack') as $file) { + if (!$file->is_directory() && !in_array($file->get_itemid(), $moduleinstance->trackid)) { + $file->delete(); + } + } + if (!empty($moduleinstance->trackid)) { + [$sql, $params] = $DB->get_in_or_equal($moduleinstance->trackid, SQL_PARAMS_NAMED); + $DB->delete_records_select('videotime_track', "videotime = :videotime AND NOT id $sql", $params + ['videotime' => $moduleinstance->id]); + } else { + $DB->delete_records('videotime_track', ['videotime' => $moduleinstance->id]); + } + + foreach ($moduleinstance->trackid ?? [] as $key => $trackid) { + $record = [ + 'videotime' => $moduleinstance->id, + 'srclang' => $moduleinstance->srclang[$key], + 'kind' => $moduleinstance->tracktype[$key], + 'label' => $moduleinstance->tracklabel[$key], + 'visible' => $moduleinstance->trackvisible[$key], + 'isdefault' => $moduleinstance->trackdefault[$key], + ]; + + if ($trackid) { + $record['id'] = $trackid; + $DB->update_record('videotime_track', $record); + } else { + $record['id'] = $DB->insert_record('videotime_track', $record); + } + + file_save_draft_area_files( + $moduleinstance->texttrack[$key], + $context->id, + 'mod_videotime', + 'texttrack', + $record['id'], + ['subdirs' => true] + ); + } + return $DB->update_record('videotime', $moduleinstance); } @@ -292,6 +358,7 @@ function videotime_delete_instance($id) { } $cm = get_coursemodule_from_instance('videotime', $id); + $context = context_module::instance($cm->id); \core_completion\api::update_completion_date_event($cm->id, 'videotime', $id, null); foreach (array_keys(core_component::get_plugin_list('videotimetab')) as $name) { @@ -303,6 +370,13 @@ function videotime_delete_instance($id) { component_callback("videotimeplugin_$name", 'delete_instance', [$id]); } + // Remove and text tracks. + $fs = get_file_storage(); + foreach ($fs->get_area_files($context->id, 'mod_videotime', 'texttrack') as $file) { + $file->delete(); + } + $DB->delete_records('videotime_track', ['videotime' => $id]); + $DB->delete_records('videotime', ['id' => $id]); return true; @@ -379,17 +453,22 @@ function videotime_pluginfile($course, $cm, $context, $filearea, $args, $forcedo require_login($course, true, $cm); - if ($filearea == 'video_description' || $filearea == 'intro') { + if ($filearea == 'video_description' || $filearea == 'intro' || $filearea == 'texttrack') { + if ($filearea == 'texttrack') { + array_splice($args, 1, 1); + } $relativepath = implode('/', $args); $fullpath = "/$context->id/mod_videotime/$filearea/$relativepath"; $fs = get_file_storage(); - if (!$file = $fs->get_file_by_hash(sha1($fullpath)) || $file->is_directory()) { + if ((!$file = $fs->get_file_by_hash(sha1($fullpath))) || $file->is_directory()) { return false; } send_stored_file($file, null, 0, $forcedownload, $options); + } else if ($filearea == 'texttrack') { + print_r($args);die(); } } @@ -830,6 +909,7 @@ function videotime_cm_info_dynamic(cm_info $cm) { } /** +<<<<<<< HEAD * Register the ability to handle drag and drop file uploads * * @return array containing details of the files / types the mod can handle @@ -865,3 +945,102 @@ function videotime_dndupload_handle($uploadinfo): int { \core\di::get(\core\hook\manager::class)->dispatch($hook); return $hook->get_instanceid(); } + +/** + * Return a list of page types + * @param string $pagetype current page type + * @param stdClass $parentcontext Block's parent context + * @param stdClass $currentcontext Current context of block + */ +function videotime_page_type_list($pagetype, $parentcontext, $currentcontext) { + $modulepagetype = [ + 'mod-videotime-*' => get_string('page-mod-videotime-x', 'mod_videotime'), + 'mod-videotime-view' => get_string('page-mod-videotime-view', 'mod_videotime'), + ]; + + return $modulepagetype; +} + +/** + * Returns the lists of all browsable file areas within the given module context. + * + * The file area 'intro' for the activity introduction field is added automatically + * by {@see file_browser::get_file_info_context_module()}. + * + * @package mod_videotime + * @category files + * + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @return string[]. + */ +function videotime_get_file_areas($course, $cm, $context) { + $areas = [ + 'texttrack' => get_string('texttrack', 'mod_videotime'), + ]; + foreach (array_keys(core_component::get_plugin_list('videotimeplugin')) as $name) { + if (get_config("videotimeplugin_$name", 'enabled')) { + $pluginareas = component_callback("videotimeplugin_$name", 'get_file_areas', [$course, $cm, $context], []); + $areas = array_merge($areas, $pluginareas); + } + } + + return $areas; +} + +/** + * File browsing support for mod_videotime file areas. + * + * @package mod_videotime + * @category files + * + * @param file_browser $browser + * @param array $areas + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @param string $filearea + * @param int $itemid + * @param string $filepath + * @param string $filename + * @return file_info Instance or null if not found. + */ +function videotime_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { + global $CFG; + + foreach (array_keys(core_component::get_plugin_list('videotimeplugin')) as $name) { + if (get_config("videotimeplugin_$name", 'enabled')) { + $pluginareas = component_callback("videotimeplugin_$name", 'get_file_areas', [$course, $cm, $context], []); + if (key_exists($filearea, $pluginareas)) { + $fs = get_file_storage(); + $filepath = is_null($filepath) ? '/' : $filepath; + $filename = is_null($filename) ? '.' : $filename; + if ($storedfile = $fs->get_file($context->id, 'videotimeplugin_videojs', $filearea, $itemid, $filepath, $filename)) { + + $urlbase = $CFG->wwwroot . '/pluginfile.php'; + + if ($filepath === '/' and $filename === '.') { + $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0); + } + return new file_info_stored( + $browser, + $context, + $storedfile, + $urlbase, + get_string($filearea, 'videotimeplugin_videojs'), + false, + true, + true, + false + ); + } + + //$classname = "\\videotimeplugin_$name\\file_info_container"; + //return $classname::get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename); + } + } + } + + return file_info_container::get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename); +} diff --git a/mod_form.php b/mod_form.php index acc8de2b..2a79f438 100644 --- a/mod_form.php +++ b/mod_form.php @@ -167,6 +167,9 @@ public function definition() { } } + // Add text tracks. + $this->add_text_track_fields(); + // Add standard elements. $this->standard_coursemodule_elements(); @@ -381,6 +384,8 @@ public function validation($data, $files) { * @param array $defaultvalues */ public function data_preprocessing(&$defaultvalues) { + global $DB; + parent::data_preprocessing($defaultvalues); // Editing existing instance. @@ -409,6 +414,37 @@ public function data_preprocessing(&$defaultvalues) { $classname = "\\videotimetab_$name\\tab"; $classname::data_preprocessing($defaultvalues, $this->current->instance); } + + $texttracks = $DB->get_records('videotime_track', ['videotime' => $this->current->instance]); + $defaultvalues['srclang'] = array_values(array_column($texttracks, 'srclang')); + $defaultvalues['trackid'] = array_keys($texttracks); + $defaultvalues['tracklabel'] = array_values(array_column($texttracks, 'label')); + $defaultvalues['tracktype'] = array_values(array_column($texttracks, 'kind')); + $defaultvalues['trackvisible'] = array_values(array_column($texttracks, 'visible')) + array_fill(0, count($texttracks) + 2, 1); + $defaultvalues['trackdefault'] = array_values(array_column($texttracks, 'isdefault')); + $defaultvalues['tracks_repeats'] = count($texttracks); + $cm = get_coursemodule_from_instance('videotime', $this->current->instance); + $context = context_module::instance($cm->id); + foreach ($defaultvalues['trackid'] as $key => $trackid) { + if ($trackid) { + if (!empty($defaultvalues['texttrack']) + &&!empty($defaultvalues['texttrack'][$key]) + ) { + $draftitemid = $defaultvalues['texttrack'][$key]; + print_r($draftitemid);die(); + } else { + $draftitemid = null; + } + file_prepare_draft_area( + $draftitemid, + $context->id, + 'mod_videotime', + 'texttrack', + $trackid + ); + $defaultvalues['texttrack'][$key] = $draftitemid; + } + } } } @@ -462,4 +498,78 @@ public function data_postprocessing($data) { } } } + + protected function add_text_track_fields() { + global $DB; + + $mform = $this->_form; + + $mform->addElement('header', 'texttrackhdr', get_string('texttracks', 'mod_videotime')); + + $currentlang = \current_language(); + $languages = \get_string_manager()->get_list_of_translations(); + + $types = [ + 'chapters' => get_string('chapters', 'mod_videotime'), + 'captions' => get_string('captions', 'mod_videotime'), + 'subtitles' => get_string('subtitles', 'mod_videotime'), + ]; + + $maxbytes = 20000000; + $attributes = [ + $mform->createElement('static', 'trackno', get_string('texttrackno', 'mod_videotime')), + $mform->createElement('select', 'tracktype', get_string('tracktype', 'mod_videotime'), $types), + $mform->createElement('select', 'srclang', get_string('language'), $languages), + $mform->createElement('advcheckbox', 'trackvisible', get_string('visible')), + $mform->createElement('advcheckbox', 'trackdefault', get_string('default')), + ]; + $tracks = [ + $mform->createElement('hidden', 'trackid'), + $mform->createElement('text', 'tracklabel', get_string('texttrackno', 'mod_videotime')), + $mform->createElement('group', 'trackattributes', '', $attributes, [ + get_string('tracktype', 'mod_videotime'), + get_string('language'), + '', + '', + '', + ' ', + ], false), + $mform->createElement( + 'filemanager', + 'texttrack', + '', + null, + [ + 'subdirs' => 0, + 'maxbytes' => $maxbytes, + 'areamaxbytes' => $maxbytes, + 'maxfiles' => 1, + 'accepted_types' => ['vtt'], + 'return_types' => FILE_INTERNAL, + ] + ), + $mform->createElement('submit', 'delete', get_string('delete')), + ]; + if ($this->current->instance) { + $records = $DB->get_records('videotime_track', ['videotime' => $this->current->instance]); + $mform->setDefault('srclang', array_column($records, 'srclang')); + $trackno = count($DB->get_records('videotime_track', ['videotime' => $this->current->instance])); + $options = []; + } else { + $options = [ + 'srclang' => [ + 'default' => $currentlang, + 'type' => PARAM_ALPHANUMEXT, + ], + ]; + $trackno = 0; + } + + $mform->setDefault('trackid', 0); + $mform->setType('trackid', PARAM_INT); + $mform->setType('tracklabel', PARAM_TEXT); + $mform->setType('srclang', PARAM_ALPHANUMEXT); + $this->repeat_elements($tracks, $trackno, $options, + 'tracks_repeats', 'tracks_add_fields', 1, get_string('addtexttrack', 'mod_videotime'), true, 'delete'); + } } diff --git a/plugin/videojs/amd/build/videotime.min.js b/plugin/videojs/amd/build/videotime.min.js index 2d3b0a11..ec111c49 100644 --- a/plugin/videojs/amd/build/videotime.min.js +++ b/plugin/videojs/amd/build/videotime.min.js @@ -1,4 +1,4 @@ -define("videotimeplugin_videojs/videotime",["exports","jquery","mod_videotime/videotime","core/log","core/notification","media_videojs/video-lazy","media_videojs/Youtube-lazy"],(function(_exports,_jquery,_videotime,_log,_notification,_videoLazy,_YoutubeLazy){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} +define("videotimeplugin_videojs/videotime",["exports","mod_videotime/videotime","core/log","media_videojs/video-lazy","media_videojs/Youtube-lazy"],(function(_exports,_videotime,_log,_videoLazy,_YoutubeLazy){function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}} /* * Video time player specific js * @@ -6,6 +6,6 @@ define("videotimeplugin_videojs/videotime",["exports","jquery","mod_videotime/vi * @module videotimeplugin_videojs/videotime * @copyright 2022 bdecent gmbh * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later - */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_jquery=_interopRequireDefault(_jquery),_videotime=_interopRequireDefault(_videotime),_log=_interopRequireDefault(_log),_notification=_interopRequireDefault(_notification),_videoLazy=_interopRequireDefault(_videoLazy);class VideoTime extends _videotime.default{initialize(){_log.default.debug("Initializing Video Time "+this.elementId);const instance=this.instance,options={autoplay:Number(instance.autoplay),controls:Number(instance.controls),sources:[{type:instance.type,src:instance.vimeo_url}],loop:Number(instance.option_loop),fluid:Number(instance.responsive),playsinline:Number(instance.playsinline),playbackRates:Number(instance.speed)?[.5,.75,1,1.25,1.5,2]:[1],muted:Number(instance.muted)};"video/youtube"===instance.type&&(options.techOrder=["youtube"]),!Number(instance.responsive)&&Number(instance.height)&&Number(instance.width)&&(options.height=Number(instance.height),options.width=Number(instance.width)),_log.default.debug("Initializing VideoJS player with options:"),_log.default.debug(options),this.player=new _videoLazy.default(this.elementId,options),this.player.on("loadedmetadata",(()=>{if(!instance.resume_playback||instance.resume_time<=0||this.resumed)return!0;let duration=this.getPlayer().duration(),resumeTime=instance.resume_time;return resumeTime+1>=Math.floor(duration)&&(_log.default.debug("VIDEO_TIME video finished, resuming at start of video."),resumeTime=0),_log.default.debug("VIDEO_TIME duration is "+duration),_log.default.debug("VIDEO_TIME resuming at "+resumeTime),resumeTime&&setTimeout((()=>{this.setCurrentPosition(resumeTime)}),10),!0})),this.handleStartTime(),this.addListeners();for(let i=0;i(this.played||(this.hasPro&&this.startWatchInterval(),this.view()),!0))),this.hasPro&&(this.player.on("ended",this.handleEnd.bind(this)),this.player.on("pause",this.handlePause.bind(this)),this.player.options().responsive)){new ResizeObserver((()=>{this.player.height(this.player.videoHeight()/this.player.videoWidth()*this.player.currentWidth())})).observe(document.querySelector("#"+this.elementId))}}else _log.default.debug("Player was not properly initialized for course module "+this.cmId)}async setStartTime(starttime){let time=starttime.match(/((([0-9]+):)?(([0-9]+):))?([0-9]+(\.[0-9]+))/);return time?(this.resumeTime=3600*Number(time[3]||0)+60*Number(time[5]||0)+Number(time[6]),await this.player.currentTime(this.resumeTime)):(_log.default.debug("Set start time:"+starttime),await this.player.currentTime())}getDuration(){return new Promise((resolve=>(resolve(this.player.duration()),!0)))}getPlaybackRate(){return new Promise((resolve=>(resolve(this.player.playbackRate()),!0)))}setCurrentPosition(secs){return new Promise((resolve=>(resolve(this.player.currentTime(secs)),!0)))}async getCurrentPosition(){let position=await this.player.currentTime();return this.plugins.forEach((async plugin=>{plugin.getCurrentPosition&&(position=await plugin.getCurrentPosition(position))})),position}getPaused(){return this.player.paused()}}return _exports.default=VideoTime,_exports.default})); + */Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.default=void 0,_videotime=_interopRequireDefault(_videotime),_log=_interopRequireDefault(_log),_videoLazy=_interopRequireDefault(_videoLazy);class VideoTime extends _videotime.default{initialize(){_log.default.debug("Initializing Video Time "+this.elementId);const instance=this.instance,options={autoplay:Number(instance.autoplay),controls:Number(instance.controls),sources:[{type:instance.type,src:instance.vimeo_url}],loop:Number(instance.option_loop),fluid:Number(instance.responsive),playsinline:Number(instance.playsinline),playbackRates:Number(instance.speed)?[.5,.75,1,1.25,1.5,2]:[1],muted:Number(instance.muted)};"video/youtube"===instance.type&&(options.techOrder=["youtube"]),!Number(instance.responsive)&&Number(instance.height)&&Number(instance.width)&&(options.height=Number(instance.height),options.width=Number(instance.width)),_log.default.debug("Initializing VideoJS player with options:"),_log.default.debug(options),this.player=new _videoLazy.default(this.elementId,options),this.player.on("loadedmetadata",(()=>{if(!instance.resume_playback||instance.resume_time<=0||this.resumed)return!0;let duration=this.getPlayer().duration(),resumeTime=instance.resume_time;return resumeTime+1>=Math.floor(duration)&&(_log.default.debug("VIDEO_TIME video finished, resuming at start of video."),resumeTime=0),_log.default.debug("VIDEO_TIME duration is "+duration),_log.default.debug("VIDEO_TIME resuming at "+resumeTime),resumeTime&&setTimeout((()=>{this.setCurrentPosition(resumeTime)}),10),!0})),this.handleStartTime(),this.addListeners();for(let i=0;i(this.played||(this.hasPro&&this.startWatchInterval(),this.view()),!0))),this.hasPro&&(this.player.on("ended",this.handleEnd.bind(this)),this.player.on("pause",this.handlePause.bind(this)),this.player.options().responsive)){new ResizeObserver((()=>{this.player.height(this.player.videoHeight()/this.player.videoWidth()*this.player.currentWidth())})).observe(document.querySelector("#"+this.elementId))}}else _log.default.debug("Player was not properly initialized for course module "+this.cmId)}async setStartTime(starttime){let time=starttime.match(/((([0-9]+):)?(([0-9]+):))?([0-9]+(\.[0-9]+))/);return time?(this.resumeTime=3600*Number(time[3]||0)+60*Number(time[5]||0)+Number(time[6]),await this.player.currentTime(this.resumeTime)):(_log.default.debug("Set start time:"+starttime),await this.player.currentTime())}getDuration(){return new Promise((resolve=>(resolve(this.player.duration()),!0)))}getPlaybackRate(){return new Promise((resolve=>(resolve(this.player.playbackRate()),!0)))}setCurrentPosition(secs){return new Promise((resolve=>(resolve(this.player.currentTime(secs)),!0)))}async getCurrentPosition(){let position=await this.player.currentTime();return this.plugins.forEach((async plugin=>{plugin.getCurrentPosition&&(position=await plugin.getCurrentPosition(position))})),position}getPaused(){return this.player.paused()}}return _exports.default=VideoTime,_exports.default})); //# sourceMappingURL=videotime.min.js.map \ No newline at end of file diff --git a/plugin/videojs/amd/build/videotime.min.js.map b/plugin/videojs/amd/build/videotime.min.js.map index 2c0393bb..6e9032ae 100644 --- a/plugin/videojs/amd/build/videotime.min.js.map +++ b/plugin/videojs/amd/build/videotime.min.js.map @@ -1 +1 @@ -{"version":3,"file":"videotime.min.js","sources":["../src/videotime.js"],"sourcesContent":["/*\n * Video time player specific js\n *\n * @package videotimeplugin_videojs\n * @module videotimeplugin_videojs/videotime\n * @copyright 2022 bdecent gmbh \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport $ from \"jquery\";\nimport VideoTimeBase from \"mod_videotime/videotime\";\nimport Log from \"core/log\";\nimport Notification from \"core/notification\";\nimport Player from \"media_videojs/video-lazy\";\nimport \"media_videojs/Youtube-lazy\";\n\nexport default class VideoTime extends VideoTimeBase {\n initialize() {\n Log.debug(\"Initializing Video Time \" + this.elementId);\n\n const instance = this.instance,\n options = {\n autoplay: Number(instance.autoplay),\n controls: Number(instance.controls),\n sources: [{type: instance.type, src: instance.vimeo_url}],\n loop: Number(instance.option_loop),\n fluid: Number(instance.responsive),\n playsinline: Number(instance.playsinline),\n playbackRates: Number(instance.speed)\n ? [0.5, 0.75, 1, 1.25, 1.5, 2]\n : [1],\n muted: Number(instance.muted)\n };\n if (instance.type === \"video/youtube\") {\n options.techOrder = [\"youtube\"];\n }\n if (!Number(instance.responsive) && Number(instance.height) && Number(instance.width)) {\n options.height = Number(instance.height);\n options.width = Number(instance.width);\n }\n Log.debug(\"Initializing VideoJS player with options:\");\n Log.debug(options);\n this.player = new Player(this.elementId, options);\n\n this.player.on(\"loadedmetadata\", () => {\n if (!instance.resume_playback || instance.resume_time <= 0 || this.resumed) {\n return true;\n }\n\n let duration = this.getPlayer().duration(),\n resumeTime = instance.resume_time;\n // Duration is often a little greater than a resume time at the end of the video.\n // A user may have watched 100 seconds when the video ends, but the duration may be\n // 100.56 seconds. BUT, sometimes the duration is rounded depending on when the\n // video loads, so it may be 101 seconds. Hence the +1 and Math.floor usage.\n if (resumeTime + 1 >= Math.floor(duration)) {\n Log.debug(\n \"VIDEO_TIME video finished, resuming at start of video.\"\n );\n resumeTime = 0;\n }\n Log.debug(\"VIDEO_TIME duration is \" + duration);\n Log.debug(\"VIDEO_TIME resuming at \" + resumeTime);\n if (resumeTime) {\n setTimeout(() => {\n this.setCurrentPosition(resumeTime);\n }, 10);\n }\n return true;\n });\n\n this.handleStartTime();\n\n this.addListeners();\n\n for (let i = 0; i < this.plugins.length; i++) {\n const plugin = this.plugins[i];\n plugin.initialize(this, instance);\n }\n\n return true;\n }\n\n /**\n * Register player events to respond to user interaction and play progress.\n */\n async addListeners() {\n // If this is a tab play set time cues and listener.\n $($(\"#\" + this.elementId).closest(\".videotimetabs\")).each(\n function(i, tabs) {\n $(tabs)\n .find('[data-action=\"cue\"]')\n .each(\n async function(index, anchor) {\n let starttime = anchor.getAttribute(\"data-start\"),\n time = starttime.match(\n /((([0-9]+):)?(([0-9]+):))?([0-9]+(\\.[0-9]+))/\n );\n if (time) {\n try {\n await this.player.addCuePoint(\n 3600 * Number(time[3] || 0) +\n 60 * Number(time[5] || 0) +\n Number(time[6]),\n {\n starttime: starttime\n }\n );\n } catch (e) {\n Notification.exception(e);\n }\n }\n }.bind(this)\n );\n\n this.player.on(\"cuepoint\", function(event) {\n if (event.data.starttime) {\n $(tabs)\n .find(\".videotime-highlight\")\n .removeClass(\"videotime-highlight\");\n $(tabs)\n .find(\n '[data-action=\"cue\"][data-start=\"' +\n event.data.starttime +\n '\"]'\n )\n .closest(\".row\")\n .addClass(\"videotime-highlight\");\n $(\".videotime-highlight\").each(function() {\n if (this.offsetTop) {\n this.parentNode.scrollTo({\n top: this.offsetTop - 50,\n left: 0,\n behavior: \"smooth\"\n });\n }\n });\n }\n });\n }.bind(this)\n );\n\n if (!this.player) {\n Log.debug(\n \"Player was not properly initialized for course module \" +\n this.cmId\n );\n return;\n }\n\n // Fire view event in Moodle on first play only.\n this.player.on(\"play\", () => {\n if (!this.played) {\n if (this.hasPro) {\n this.startWatchInterval();\n }\n // Free version can still mark completion on video time view.\n this.view();\n }\n return true;\n });\n\n // Features beyond this point are for pro only.\n if (!this.hasPro) {\n return;\n }\n\n // Initiate video finish procedure.\n this.player.on(\"ended\", this.handleEnd.bind(this));\n this.player.on(\"pause\", this.handlePause.bind(this));\n\n // Readjust height when responsive player is resized.\n if (this.player.options().responsive) {\n let observer = new ResizeObserver(() => {\n this.player.height(\n (this.player.videoHeight() / this.player.videoWidth()) *\n this.player.currentWidth()\n );\n });\n observer.observe(document.querySelector(\"#\" + this.elementId));\n }\n }\n\n /**\n * Parse start time and set player\n *\n * @param {string} starttime\n * @returns {Promise}\n */\n async setStartTime(starttime) {\n let time = starttime.match(\n /((([0-9]+):)?(([0-9]+):))?([0-9]+(\\.[0-9]+))/\n );\n if (time) {\n this.resumeTime =\n 3600 * Number(time[3] || 0) +\n 60 * Number(time[5] || 0) +\n Number(time[6]);\n return await this.player.currentTime(this.resumeTime);\n }\n Log.debug(\"Set start time:\" + starttime);\n return await this.player.currentTime();\n }\n\n /**\n * Get play back rate\n *\n * @returns {Promise}\n */\n getDuration() {\n return new Promise(resolve => {\n resolve(this.player.duration());\n return true;\n });\n }\n\n /**\n * Get duration of video\n *\n * @returns {Promise}\n */\n getPlaybackRate() {\n return new Promise(resolve => {\n resolve(this.player.playbackRate());\n return true;\n });\n }\n\n /**\n * Set current time of player\n *\n * @param {float} secs time\n * @returns {Promise}\n */\n setCurrentPosition(secs) {\n return new Promise(resolve => {\n resolve(this.player.currentTime(secs));\n return true;\n });\n }\n\n /**\n * Get current time of player\n *\n * @returns {Promise}\n */\n async getCurrentPosition() {\n let position = await this.player.currentTime();\n this.plugins.forEach(async plugin => {\n if (plugin.getCurrentPosition) {\n position = await plugin.getCurrentPosition(position);\n }\n });\n return position;\n }\n\n /**\n * Get pause state\n *\n * @return {bool}\n */\n getPaused() {\n const paused = this.player.paused();\n return paused;\n }\n}\n"],"names":["VideoTime","VideoTimeBase","initialize","debug","this","elementId","instance","options","autoplay","Number","controls","sources","type","src","vimeo_url","loop","option_loop","fluid","responsive","playsinline","playbackRates","speed","muted","techOrder","height","width","player","Player","on","resume_playback","resume_time","resumed","duration","getPlayer","resumeTime","Math","floor","setTimeout","setCurrentPosition","handleStartTime","addListeners","i","plugins","length","closest","each","tabs","find","async","index","anchor","starttime","getAttribute","time","match","addCuePoint","e","exception","bind","event","data","removeClass","addClass","offsetTop","parentNode","scrollTo","top","left","behavior","played","hasPro","startWatchInterval","view","handleEnd","handlePause","ResizeObserver","videoHeight","videoWidth","currentWidth","observe","document","querySelector","cmId","currentTime","getDuration","Promise","resolve","getPlaybackRate","playbackRate","secs","position","forEach","plugin","getCurrentPosition","getPaused","paused"],"mappings":";;;;;;;;qTAgBqBA,kBAAkBC,mBACnCC,0BACQC,MAAM,2BAA6BC,KAAKC,iBAEtCC,SAAWF,KAAKE,SAClBC,QAAU,CACNC,SAAUC,OAAOH,SAASE,UAC1BE,SAAUD,OAAOH,SAASI,UAC1BC,QAAS,CAAC,CAACC,KAAMN,SAASM,KAAMC,IAAKP,SAASQ,YAC9CC,KAAMN,OAAOH,SAASU,aACtBC,MAAOR,OAAOH,SAASY,YACvBC,YAAaV,OAAOH,SAASa,aAC7BC,cAAeX,OAAOH,SAASe,OACzB,CAAC,GAAK,IAAM,EAAG,KAAM,IAAK,GAC1B,CAAC,GACPC,MAAOb,OAAOH,SAASgB,QAET,kBAAlBhB,SAASM,OACTL,QAAQgB,UAAY,CAAC,aAEpBd,OAAOH,SAASY,aAAeT,OAAOH,SAASkB,SAAWf,OAAOH,SAASmB,SAC3ElB,QAAQiB,OAASf,OAAOH,SAASkB,QACjCjB,QAAQkB,MAAQhB,OAAOH,SAASmB,qBAEhCtB,MAAM,0DACNA,MAAMI,cACLmB,OAAS,IAAIC,mBAAOvB,KAAKC,UAAWE,cAEpCmB,OAAOE,GAAG,kBAAkB,SACxBtB,SAASuB,iBAAmBvB,SAASwB,aAAe,GAAK1B,KAAK2B,eACxD,MAGPC,SAAW5B,KAAK6B,YAAYD,WAC5BE,WAAa5B,SAASwB,mBAKtBI,WAAa,GAAKC,KAAKC,MAAMJ,yBACzB7B,MACA,0DAEJ+B,WAAa,gBAEb/B,MAAM,0BAA4B6B,uBAClC7B,MAAM,0BAA4B+B,YAClCA,YACAG,YAAW,UACNC,mBAAmBJ,cACrB,KAEA,UAGNK,uBAEAC,mBAEA,IAAIC,EAAI,EAAGA,EAAIrC,KAAKsC,QAAQC,OAAQF,IAAK,CAC3BrC,KAAKsC,QAAQD,GACrBvC,WAAWE,KAAME,iBAGrB,+CAQL,mBAAE,IAAMF,KAAKC,WAAWuC,QAAQ,mBAAmBC,KACjD,SAASJ,EAAGK,0BACNA,MACGC,KAAK,uBACLF,KACGG,eAAeC,MAAOC,YACdC,UAAYD,OAAOE,aAAa,cAChCC,KAAOF,UAAUG,MACb,mDAEJD,eAEUjD,KAAKsB,OAAO6B,YACd,KAAO9C,OAAO4C,KAAK,IAAM,GACrB,GAAK5C,OAAO4C,KAAK,IAAM,GACvB5C,OAAO4C,KAAK,IAChB,CACIF,UAAWA,YAGrB,MAAOK,yBACQC,UAAUD,KAGjCE,KAAKtD,YAGVsB,OAAOE,GAAG,YAAY,SAAS+B,OAC5BA,MAAMC,KAAKT,gCACTL,MACGC,KAAK,wBACLc,YAAY,2CACff,MACGC,KACG,mCACIY,MAAMC,KAAKT,UACX,MAEPP,QAAQ,QACRkB,SAAS,2CACZ,wBAAwBjB,MAAK,WACvBzC,KAAK2D,gBACAC,WAAWC,SAAS,CACrBC,IAAK9D,KAAK2D,UAAY,GACtBI,KAAM,EACNC,SAAU,mBAMhCV,KAAKtD,OAGNA,KAAKsB,gBASLA,OAAOE,GAAG,QAAQ,KACdxB,KAAKiE,SACFjE,KAAKkE,aACAC,0BAGJC,SAEF,KAINpE,KAAKkE,cAKL5C,OAAOE,GAAG,QAASxB,KAAKqE,UAAUf,KAAKtD,YACvCsB,OAAOE,GAAG,QAASxB,KAAKsE,YAAYhB,KAAKtD,OAG1CA,KAAKsB,OAAOnB,UAAUW,YAAY,CACnB,IAAIyD,gBAAe,UACzBjD,OAAOF,OACPpB,KAAKsB,OAAOkD,cAAgBxE,KAAKsB,OAAOmD,aACrCzE,KAAKsB,OAAOoD,mBAGfC,QAAQC,SAASC,cAAc,IAAM7E,KAAKC,+BApC/CF,MACA,yDACIC,KAAK8E,yBA4CF/B,eACXE,KAAOF,UAAUG,MACjB,uDAEAD,WACKnB,WACD,KAAOzB,OAAO4C,KAAK,IAAM,GACzB,GAAK5C,OAAO4C,KAAK,IAAM,GACvB5C,OAAO4C,KAAK,UACHjD,KAAKsB,OAAOyD,YAAY/E,KAAK8B,2BAE1C/B,MAAM,kBAAoBgD,iBACjB/C,KAAKsB,OAAOyD,eAQ7BC,qBACW,IAAIC,SAAQC,UACfA,QAAQlF,KAAKsB,OAAOM,aACb,KASfuD,yBACW,IAAIF,SAAQC,UACfA,QAAQlF,KAAKsB,OAAO8D,iBACb,KAUflD,mBAAmBmD,aACR,IAAIJ,SAAQC,UACfA,QAAQlF,KAAKsB,OAAOyD,YAAYM,QACzB,oCAUPC,eAAiBtF,KAAKsB,OAAOyD,0BAC5BzC,QAAQiD,SAAQ3C,MAAAA,SACb4C,OAAOC,qBACPH,eAAiBE,OAAOC,mBAAmBH,cAG5CA,SAQXI,mBACmB1F,KAAKsB,OAAOqE"} \ No newline at end of file +{"version":3,"file":"videotime.min.js","sources":["../src/videotime.js"],"sourcesContent":["/*\n * Video time player specific js\n *\n * @package videotimeplugin_videojs\n * @module videotimeplugin_videojs/videotime\n * @copyright 2022 bdecent gmbh \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\nimport VideoTimeBase from \"mod_videotime/videotime\";\nimport Log from \"core/log\";\nimport Player from \"media_videojs/video-lazy\";\nimport \"media_videojs/Youtube-lazy\";\n\nexport default class VideoTime extends VideoTimeBase {\n initialize() {\n Log.debug(\"Initializing Video Time \" + this.elementId);\n\n const instance = this.instance,\n options = {\n autoplay: Number(instance.autoplay),\n controls: Number(instance.controls),\n sources: [{type: instance.type, src: instance.vimeo_url}],\n loop: Number(instance.option_loop),\n fluid: Number(instance.responsive),\n playsinline: Number(instance.playsinline),\n playbackRates: Number(instance.speed)\n ? [0.5, 0.75, 1, 1.25, 1.5, 2]\n : [1],\n muted: Number(instance.muted)\n };\n if (instance.type === \"video/youtube\") {\n options.techOrder = [\"youtube\"];\n }\n if (!Number(instance.responsive) && Number(instance.height) && Number(instance.width)) {\n options.height = Number(instance.height);\n options.width = Number(instance.width);\n }\n Log.debug(\"Initializing VideoJS player with options:\");\n Log.debug(options);\n this.player = new Player(this.elementId, options);\n\n this.player.on(\"loadedmetadata\", () => {\n if (!instance.resume_playback || instance.resume_time <= 0 || this.resumed) {\n return true;\n }\n\n let duration = this.getPlayer().duration(),\n resumeTime = instance.resume_time;\n // Duration is often a little greater than a resume time at the end of the video.\n // A user may have watched 100 seconds when the video ends, but the duration may be\n // 100.56 seconds. BUT, sometimes the duration is rounded depending on when the\n // video loads, so it may be 101 seconds. Hence the +1 and Math.floor usage.\n if (resumeTime + 1 >= Math.floor(duration)) {\n Log.debug(\n \"VIDEO_TIME video finished, resuming at start of video.\"\n );\n resumeTime = 0;\n }\n Log.debug(\"VIDEO_TIME duration is \" + duration);\n Log.debug(\"VIDEO_TIME resuming at \" + resumeTime);\n if (resumeTime) {\n setTimeout(() => {\n this.setCurrentPosition(resumeTime);\n }, 10);\n }\n return true;\n });\n\n this.handleStartTime();\n\n this.addListeners();\n\n for (let i = 0; i < this.plugins.length; i++) {\n const plugin = this.plugins[i];\n plugin.initialize(this, instance);\n }\n\n return true;\n }\n\n /**\n * Register player events to respond to user interaction and play progress.\n */\n async addListeners() {\n if (!this.player) {\n Log.debug(\n \"Player was not properly initialized for course module \" +\n this.cmId\n );\n return;\n }\n\n // Fire view event in Moodle on first play only.\n this.player.on(\"play\", () => {\n if (!this.played) {\n if (this.hasPro) {\n this.startWatchInterval();\n }\n // Free version can still mark completion on video time view.\n this.view();\n }\n return true;\n });\n\n // Features beyond this point are for pro only.\n if (!this.hasPro) {\n return;\n }\n\n // Initiate video finish procedure.\n this.player.on(\"ended\", this.handleEnd.bind(this));\n this.player.on(\"pause\", this.handlePause.bind(this));\n\n // Readjust height when responsive player is resized.\n if (this.player.options().responsive) {\n let observer = new ResizeObserver(() => {\n this.player.height(\n (this.player.videoHeight() / this.player.videoWidth()) *\n this.player.currentWidth()\n );\n });\n observer.observe(document.querySelector(\"#\" + this.elementId));\n }\n }\n\n /**\n * Parse start time and set player\n *\n * @param {string} starttime\n * @returns {Promise}\n */\n async setStartTime(starttime) {\n let time = starttime.match(\n /((([0-9]+):)?(([0-9]+):))?([0-9]+(\\.[0-9]+))/\n );\n if (time) {\n this.resumeTime =\n 3600 * Number(time[3] || 0) +\n 60 * Number(time[5] || 0) +\n Number(time[6]);\n return await this.player.currentTime(this.resumeTime);\n }\n Log.debug(\"Set start time:\" + starttime);\n return await this.player.currentTime();\n }\n\n /**\n * Get play back rate\n *\n * @returns {Promise}\n */\n getDuration() {\n return new Promise(resolve => {\n resolve(this.player.duration());\n return true;\n });\n }\n\n /**\n * Get duration of video\n *\n * @returns {Promise}\n */\n getPlaybackRate() {\n return new Promise(resolve => {\n resolve(this.player.playbackRate());\n return true;\n });\n }\n\n /**\n * Set current time of player\n *\n * @param {float} secs time\n * @returns {Promise}\n */\n setCurrentPosition(secs) {\n return new Promise(resolve => {\n resolve(this.player.currentTime(secs));\n return true;\n });\n }\n\n /**\n * Get current time of player\n *\n * @returns {Promise}\n */\n async getCurrentPosition() {\n let position = await this.player.currentTime();\n this.plugins.forEach(async plugin => {\n if (plugin.getCurrentPosition) {\n position = await plugin.getCurrentPosition(position);\n }\n });\n return position;\n }\n\n /**\n * Get pause state\n *\n * @return {bool}\n */\n getPaused() {\n const paused = this.player.paused();\n return paused;\n }\n}\n"],"names":["VideoTime","VideoTimeBase","initialize","debug","this","elementId","instance","options","autoplay","Number","controls","sources","type","src","vimeo_url","loop","option_loop","fluid","responsive","playsinline","playbackRates","speed","muted","techOrder","height","width","player","Player","on","resume_playback","resume_time","resumed","duration","getPlayer","resumeTime","Math","floor","setTimeout","setCurrentPosition","handleStartTime","addListeners","i","plugins","length","played","hasPro","startWatchInterval","view","handleEnd","bind","handlePause","ResizeObserver","videoHeight","videoWidth","currentWidth","observe","document","querySelector","cmId","starttime","time","match","currentTime","getDuration","Promise","resolve","getPlaybackRate","playbackRate","secs","position","forEach","async","plugin","getCurrentPosition","getPaused","paused"],"mappings":";;;;;;;;yNAcqBA,kBAAkBC,mBACnCC,0BACQC,MAAM,2BAA6BC,KAAKC,iBAEtCC,SAAWF,KAAKE,SAClBC,QAAU,CACNC,SAAUC,OAAOH,SAASE,UAC1BE,SAAUD,OAAOH,SAASI,UAC1BC,QAAS,CAAC,CAACC,KAAMN,SAASM,KAAMC,IAAKP,SAASQ,YAC9CC,KAAMN,OAAOH,SAASU,aACtBC,MAAOR,OAAOH,SAASY,YACvBC,YAAaV,OAAOH,SAASa,aAC7BC,cAAeX,OAAOH,SAASe,OACzB,CAAC,GAAK,IAAM,EAAG,KAAM,IAAK,GAC1B,CAAC,GACPC,MAAOb,OAAOH,SAASgB,QAET,kBAAlBhB,SAASM,OACTL,QAAQgB,UAAY,CAAC,aAEpBd,OAAOH,SAASY,aAAeT,OAAOH,SAASkB,SAAWf,OAAOH,SAASmB,SAC3ElB,QAAQiB,OAASf,OAAOH,SAASkB,QACjCjB,QAAQkB,MAAQhB,OAAOH,SAASmB,qBAEhCtB,MAAM,0DACNA,MAAMI,cACLmB,OAAS,IAAIC,mBAAOvB,KAAKC,UAAWE,cAEpCmB,OAAOE,GAAG,kBAAkB,SACxBtB,SAASuB,iBAAmBvB,SAASwB,aAAe,GAAK1B,KAAK2B,eACxD,MAGPC,SAAW5B,KAAK6B,YAAYD,WAC5BE,WAAa5B,SAASwB,mBAKtBI,WAAa,GAAKC,KAAKC,MAAMJ,yBACzB7B,MACA,0DAEJ+B,WAAa,gBAEb/B,MAAM,0BAA4B6B,uBAClC7B,MAAM,0BAA4B+B,YAClCA,YACAG,YAAW,UACNC,mBAAmBJ,cACrB,KAEA,UAGNK,uBAEAC,mBAEA,IAAIC,EAAI,EAAGA,EAAIrC,KAAKsC,QAAQC,OAAQF,IAAK,CAC3BrC,KAAKsC,QAAQD,GACrBvC,WAAWE,KAAME,iBAGrB,0BAOFF,KAAKsB,gBASLA,OAAOE,GAAG,QAAQ,KACdxB,KAAKwC,SACFxC,KAAKyC,aACAC,0BAGJC,SAEF,KAIN3C,KAAKyC,cAKLnB,OAAOE,GAAG,QAASxB,KAAK4C,UAAUC,KAAK7C,YACvCsB,OAAOE,GAAG,QAASxB,KAAK8C,YAAYD,KAAK7C,OAG1CA,KAAKsB,OAAOnB,UAAUW,YAAY,CACnB,IAAIiC,gBAAe,UACzBzB,OAAOF,OACPpB,KAAKsB,OAAO0B,cAAgBhD,KAAKsB,OAAO2B,aACrCjD,KAAKsB,OAAO4B,mBAGfC,QAAQC,SAASC,cAAc,IAAMrD,KAAKC,+BApC/CF,MACA,yDACIC,KAAKsD,yBA4CFC,eACXC,KAAOD,UAAUE,MACjB,uDAEAD,WACK1B,WACD,KAAOzB,OAAOmD,KAAK,IAAM,GACzB,GAAKnD,OAAOmD,KAAK,IAAM,GACvBnD,OAAOmD,KAAK,UACHxD,KAAKsB,OAAOoC,YAAY1D,KAAK8B,2BAE1C/B,MAAM,kBAAoBwD,iBACjBvD,KAAKsB,OAAOoC,eAQ7BC,qBACW,IAAIC,SAAQC,UACfA,QAAQ7D,KAAKsB,OAAOM,aACb,KASfkC,yBACW,IAAIF,SAAQC,UACfA,QAAQ7D,KAAKsB,OAAOyC,iBACb,KAUf7B,mBAAmB8B,aACR,IAAIJ,SAAQC,UACfA,QAAQ7D,KAAKsB,OAAOoC,YAAYM,QACzB,oCAUPC,eAAiBjE,KAAKsB,OAAOoC,0BAC5BpB,QAAQ4B,SAAQC,MAAAA,SACbC,OAAOC,qBACPJ,eAAiBG,OAAOC,mBAAmBJ,cAG5CA,SAQXK,mBACmBtE,KAAKsB,OAAOiD"} \ No newline at end of file diff --git a/plugin/videojs/amd/src/videotime.js b/plugin/videojs/amd/src/videotime.js index ad256a63..9e42c61c 100644 --- a/plugin/videojs/amd/src/videotime.js +++ b/plugin/videojs/amd/src/videotime.js @@ -7,10 +7,8 @@ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -import $ from "jquery"; import VideoTimeBase from "mod_videotime/videotime"; import Log from "core/log"; -import Notification from "core/notification"; import Player from "media_videojs/video-lazy"; import "media_videojs/Youtube-lazy"; @@ -85,61 +83,6 @@ export default class VideoTime extends VideoTimeBase { * Register player events to respond to user interaction and play progress. */ async addListeners() { - // If this is a tab play set time cues and listener. - $($("#" + this.elementId).closest(".videotimetabs")).each( - function(i, tabs) { - $(tabs) - .find('[data-action="cue"]') - .each( - async function(index, anchor) { - let starttime = anchor.getAttribute("data-start"), - time = starttime.match( - /((([0-9]+):)?(([0-9]+):))?([0-9]+(\.[0-9]+))/ - ); - if (time) { - try { - await this.player.addCuePoint( - 3600 * Number(time[3] || 0) + - 60 * Number(time[5] || 0) + - Number(time[6]), - { - starttime: starttime - } - ); - } catch (e) { - Notification.exception(e); - } - } - }.bind(this) - ); - - this.player.on("cuepoint", function(event) { - if (event.data.starttime) { - $(tabs) - .find(".videotime-highlight") - .removeClass("videotime-highlight"); - $(tabs) - .find( - '[data-action="cue"][data-start="' + - event.data.starttime + - '"]' - ) - .closest(".row") - .addClass("videotime-highlight"); - $(".videotime-highlight").each(function() { - if (this.offsetTop) { - this.parentNode.scrollTo({ - top: this.offsetTop - 50, - left: 0, - behavior: "smooth" - }); - } - }); - } - }); - }.bind(this) - ); - if (!this.player) { Log.debug( "Player was not properly initialized for course module " + diff --git a/plugin/videojs/classes/file_info_container.php b/plugin/videojs/classes/file_info_container.php new file mode 100644 index 00000000..2b9e1c20 --- /dev/null +++ b/plugin/videojs/classes/file_info_container.php @@ -0,0 +1,256 @@ +. + +namespace videotimeplugin_videojs; + +use file_info; +use file_info_stored; + +/** + * File browsing support class. + * + * @package videotimeplugin_videojs + * @copyright 2025 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class file_info_container extends file_info { + /** + * Constructor + * + * @param file_browser $browser The file_browser instance + * @param stdClass $course Course object + * @param stdClass $cm course Module object + * @param stdClass $context Module context + * @param array $areas Available file areas + * @param string $filearea File area to browse + */ + public function __construct( + $browser, + /** @var stdClass $course Course object */ + protected $course, + /** @var stdClass $cm Course module object */ + protected $cm, + $context, + /** @var array Available file areas */ + protected $areas, + /** @var string File area to browse */ + protected $filearea + ) { + parent::__construct($browser, $context); + } + + /** + * Returns list of standard virtual file/directory identification. + * The difference from stored_file parameters is that null values + * are allowed in all fields + * @return array with keys contextid, filearea, itemid, filepath and filename + */ + public function get_params() { + return ['contextid' => $this->context->id, + 'component' => 'videotimeplugin_videojs', + 'filearea' => $this->filearea, + 'itemid' => null, + 'filepath' => null, + 'filename' => null]; + } + + /** + * Returns localised visible name. + * @return string + */ + public function get_visible_name() { + return $this->areas[$this->filearea]; + } + + /** + * Can I add new files or directories? + * @return bool + */ + public function is_writable() { + return false; + } + + /** + * Is directory? + * @return bool + */ + public function is_directory() { + return true; + } + + /** + * Returns list of children. + * @return array of file_info instances + */ + public function get_children() { + return $this->get_filtered_children('*', false, true); + } + + /** + * Help function to return files matching extensions or their count + * + * @param string|array $extensions + * @param bool|int $countonly + * @param bool $returnemptyfolders + * @return array|int array of file_info instances or the count + */ + private function get_filtered_children($extensions = '*', $countonly = false, $returnemptyfolders = false) { + global $DB; + throw new \moodle_exception('x'); + + $params = [ + 'contextid' => $this->context->id, + 'component' => 'videotimeplugin_videojs', + 'filearea' => $this->filearea, + ]; + $sql = 'SELECT DISTINCT itemid + FROM {files} + WHERE contextid = :contextid + AND component = :component + AND filearea = :filearea'; + + if (!$returnemptyfolders) { + $sql .= ' AND filename <> :emptyfilename'; + $params['emptyfilename'] = '.'; + } + + [$sql2, $params2] = $this->build_search_files_sql($extensions); + $sql .= ' ' . $sql2; + $params = array_merge($params, $params2); + + if ($countonly !== false) { + $sql .= ' ORDER BY itemid DESC'; + } + + $rs = $DB->get_recordset_sql($sql, $params); + $children = []; + foreach ($rs as $record) { + if ( + ($child = $this->browser->get_file_info( + $this->context, + 'videotimeplugin_videojs', + $this->filearea, + $record->itemid + )) + && ($returnemptyfolders || $child->count_non_empty_children($extensions)) + ) { + $children[] = $child; + } + if ($countonly !== false && count($children) >= $countonly) { + break; + } + } + $rs->close(); + if ($countonly !== false) { + return count($children); + } + return $children; + } + + /** + * Returns list of children which are either files matching the specified extensions + * or folders that contain at least one such file. + * + * @param string|array $extensions + * @return array + */ + public function get_non_empty_children($extensions = '*') { + return $this->get_filtered_children($extensions, false); + } + + /** + * Returns the number of children which are either files matching the specified extensions + * or folders containing at least one such file. + * + * @param string|array $extensions + * @param int $limit + * @return int + */ + public function count_non_empty_children($extensions = '*', $limit = 1) { + return $this->get_filtered_children($extensions, $limit); + } + + /** + * Returns parent file_info instance + * @return file_info or null for root + */ + public function get_parent() { + return $this->browser->get_file_info($this->context); + } + + /** + * File browsing support for videotimeplugin_videojs file areas. + * + * @package videotimeplugin_videojs + * @category files + * + * @param file_browser $browser + * @param array $areas + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @param string $filearea + * @param int $itemid + * @param string $filepath + * @param string $filename + * @return file_info Instance or null if not found. + */ + public static function get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { + global $CFG, $DB, $USER; + + if ($context->contextlevel != CONTEXT_MODULE) { + return null; + } + + if (!isset($areas[$filearea])) { + return null; + } + + if (is_null($itemid)) { + return new static($browser, $course, $cm, $context, $areas, $filearea); + } + + if (!$DB->get_record('videotime', ['id' => $cm->instance])) { + return null; + } + + $fs = get_file_storage(); + $filepath = is_null($filepath) ? '/' : $filepath; + $filename = is_null($filename) ? '.' : $filename; + if (!($storedfile = $fs->get_file($context->id, 'videotimeplugin_videojs', $filearea, $itemid, $filepath, $filename))) { + return null; + } + + // Checks to see if the user can manage files or is the owner. + if (!has_capability('moodle/course:managefiles', $context) && $storedfile->get_userid() != $USER->id) { + return null; + } + + $urlbase = $CFG->wwwroot . '/pluginfile.php'; + + return new file_info_stored( + $browser, + $context, + $storedfile, + $urlbase, + get_string($filearea, 'videotimeplugin_videojs'), + true, + true, + false, + false + ); + } +} diff --git a/plugin/videojs/db/install.xml b/plugin/videojs/db/install.xml index bcb75d0d..be678b7e 100644 --- a/plugin/videojs/db/install.xml +++ b/plugin/videojs/db/install.xml @@ -1,5 +1,5 @@ - diff --git a/plugin/videojs/lib.php b/plugin/videojs/lib.php index ca33efc4..1caee7d0 100644 --- a/plugin/videojs/lib.php +++ b/plugin/videojs/lib.php @@ -106,6 +106,17 @@ function videotimeplugin_videojs_update_instance($moduleinstance, $mform = null) function videotimeplugin_videojs_delete_instance($id) { global $DB; + $cm = get_coursemodule_from_instance('videotime', $id); + $context = context_module::instance($cm->id); + + $fs = get_file_storage(); + foreach ($fs->get_area_files($context->id, 'videotimeplugin_videojs', 'mediafile') as $file) { + $file->delete(); + } + foreach ($fs->get_area_files($context->id, 'videotimeplugin_videojs', 'poster') as $file) { + $file->delete(); + } + $DB->delete_records('videotimeplugin_videojs', ['videotime' => $id]); return true; @@ -343,7 +354,8 @@ function videotimeplugin_videojs_pluginfile($course, $cm, $context, $filearea, $ if ( in_array($filearea, [ - 'mediafile', 'poster', + 'mediafile', + 'poster', ]) ) { $relativepath = implode('/', $args); @@ -422,3 +434,45 @@ function videotimeplugin_videojs_validation($data, $files) { } return ['vimeo_url' => get_string('required')]; } + +/** + * Returns the lists of all browsable file areas within the given module context. + * + * The file area 'intro' for the activity introduction field is added automatically + * by {@see file_browser::get_file_info_context_module()}. + * + * @package videotimeplugin_videojs + * @category files + * + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @return string[]. + */ +function videotimeplugin_videojs_get_file_areas($course, $cm, $context) { + return [ + 'mediafile' => get_string('mediafile', 'videotimeplugin_videojs'), + 'poster' => get_string('poster', 'videotimeplugin_videojs'), + ]; +} + +/** + * File browsing support for videotimeplugin_videojs file areas. + * + * @package videotimeplugin_videojs + * @category files + * + * @param file_browser $browser + * @param array $areas + * @param stdClass $course + * @param stdClass $cm + * @param stdClass $context + * @param string $filearea + * @param int $itemid + * @param string $filepath + * @param string $filename + * @return file_info Instance or null if not found. + */ +function videotimeplugin_videojs_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { + return file_info_container::get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename); +} diff --git a/plugin/videojs/templates/video_embed.mustache b/plugin/videojs/templates/video_embed.mustache index 9624cdac..d14c5d3e 100644 --- a/plugin/videojs/templates/video_embed.mustache +++ b/plugin/videojs/templates/video_embed.mustache @@ -53,6 +53,14 @@ {{# poster }} poster="{{ poster }}" {{/ poster }} controls {{# playsinline }} playsinline {{/ playsinline }} > + {{# texttracks }}{{# url }}{{# visible }} + + {{/ visible }}{{/ url }}{{/ texttracks }} {{/ video }} {{^ video }} diff --git a/tab/chapter/classes/tab.php b/tab/chapter/classes/tab.php index 842f75a8..5024c611 100644 --- a/tab/chapter/classes/tab.php +++ b/tab/chapter/classes/tab.php @@ -49,9 +49,11 @@ public function get_tab_content(): string { global $DB, $OUTPUT, $PAGE, $USER; $instance = $this->get_instance(); + $context = $instance->get_context(); $data = [ 'id' => $instance->id, 'title' => $instance->name, + 'canedit' => videotime_has_pro() && has_capability('moodle/course:managefiles', $context), ]; return $OUTPUT->render_from_template( @@ -140,6 +142,18 @@ public static function data_preprocessing(array &$defaultvalues, int $instance) } else { $defaultvalues['enable_chapter'] = 0; } + $draftitemid = file_get_submitted_draft_itemid('chapters'); + $cm = get_coursemodule_from_instance('videotime', $instance); + $context = context_module::instance($cm->id); + file_prepare_draft_area( + $draftitemid, + $context->id, + 'videotimetab_texttrack', + 'chapters', + 0, + [] + ); + $defaultvalues['chapters'] = $draftitemid; } /** diff --git a/tab/chapter/lang/en/videotimetab_chapter.php b/tab/chapter/lang/en/videotimetab_chapter.php index 048e1d2a..4705e07e 100644 --- a/tab/chapter/lang/en/videotimetab_chapter.php +++ b/tab/chapter/lang/en/videotimetab_chapter.php @@ -30,3 +30,4 @@ $string['pluginname'] = 'Video Time Chapter tab'; $string['privacy:metadata'] = 'The Video Time Chapter tab plugin does not store any personal data.'; $string['upgradeplugin'] = 'This plugin requires installation of Video Time Pro to enable.'; +$string['chapterno'] = 'Chapter {no}'; diff --git a/tab/chapter/templates/tab.mustache b/tab/chapter/templates/tab.mustache index 4a8c8aed..1f68cb86 100644 --- a/tab/chapter/templates/tab.mustache +++ b/tab/chapter/templates/tab.mustache @@ -35,4 +35,13 @@
{{ title }}
+ {{# canedit }} + + {{/ canedit }} diff --git a/tab/texttrack/amd/build/selecttrack.min.js b/tab/texttrack/amd/build/selecttrack.min.js index 26e89868..5d95dbe6 100644 --- a/tab/texttrack/amd/build/selecttrack.min.js +++ b/tab/texttrack/amd/build/selecttrack.min.js @@ -1,3 +1,3 @@ -define("videotimetab_texttrack/selecttrack",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initialize=void 0;_exports.initialize=()=>{let lang=new URL(window.location.href).searchParams.get("lang");window.removeEventListener("change",handleChange),document.querySelectorAll("form.videotimetab_texttrack_selectlang").forEach((form=>{lang&&form.querySelector('select option[value="'+lang+'"]').setAttribute("selected",!0),setLanguage(form)})),window.addEventListener("change",handleChange)};const handleChange=e=>{let form=e.target.closest("form.videotimetab_texttrack_selectlang");form&&(e.stopPropagation(),e.preventDefault(),setLanguage(form))},setLanguage=form=>{let data=new FormData(form);form.closest(".tab-pane").querySelectorAll(".texttracks .row").forEach((row=>{row.getAttribute("data-lang")==data.get("lang")?row.style.display=null:row.style.display="none"}))}})); +define("videotimetab_texttrack/selecttrack",["exports"],(function(_exports){Object.defineProperty(_exports,"__esModule",{value:!0}),_exports.initialize=void 0;_exports.initialize=()=>{let lang=new URL(window.location.href).searchParams.get("lang");window.removeEventListener("change",handleChange),document.querySelectorAll("form.videotimetab_texttrack_selectlang").forEach((form=>{lang&&form.querySelector('select option[value="'+lang+'"]').setAttribute("selected",!0),setLanguage(form)})),window.addEventListener("change",handleChange)};const handleChange=e=>{let form=e.target.closest("form.videotimetab_texttrack_selectlang");form&&(e.stopPropagation(),e.preventDefault(),setLanguage(form))},setLanguage=form=>{let data=new FormData(form);form.closest(".tab-pane").querySelectorAll('.texttracks .row, .texttracks button[data-action="edit"]').forEach((row=>{row.getAttribute("data-lang")==data.get("lang")?row.style.display=null:row.style.display="none"}))}})); //# sourceMappingURL=selecttrack.min.js.map \ No newline at end of file diff --git a/tab/texttrack/amd/build/selecttrack.min.js.map b/tab/texttrack/amd/build/selecttrack.min.js.map index f98495c7..e1b7b21a 100644 --- a/tab/texttrack/amd/build/selecttrack.min.js.map +++ b/tab/texttrack/amd/build/selecttrack.min.js.map @@ -1 +1 @@ -{"version":3,"file":"selecttrack.min.js","sources":["../src/selecttrack.js"],"sourcesContent":["/*\n * Show selected text track\n *\n * @package mod_videotime\n * @module mod_videotime/selecttrrack\n * @copyright 2021 bdecent gmbh \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\n/**\n * Intialize listener and show current track\n */\nexport const initialize = () => {\n let url = new URL(window.location.href),\n lang = url.searchParams.get('lang');\n\n window.removeEventListener('change', handleChange);\n document.querySelectorAll('form.videotimetab_texttrack_selectlang').forEach((form) => {\n if (lang) {\n form.querySelector('select option[value=\"' + lang + '\"]').setAttribute('selected', true);\n }\n setLanguage(form);\n });\n window.addEventListener('change', handleChange);\n};\n\n/**\n * Form change event handler\n *\n * @param {event} e mouse event\n */\nconst handleChange = (e) => {\n let form = e.target.closest('form.videotimetab_texttrack_selectlang');\n if (form) {\n e.stopPropagation();\n e.preventDefault();\n setLanguage(form);\n }\n};\n\n/**\n * Show lang indicate by form\n *\n * @param {element} form\n */\nconst setLanguage = (form) => {\n let data = new FormData(form);\n form.closest('.tab-pane').querySelectorAll('.texttracks .row').forEach((row) => {\n if (row.getAttribute('data-lang') == data.get('lang')) {\n row.style.display = null;\n } else {\n row.style.display = 'none';\n }\n });\n};\n"],"names":["lang","URL","window","location","href","searchParams","get","removeEventListener","handleChange","document","querySelectorAll","forEach","form","querySelector","setAttribute","setLanguage","addEventListener","e","target","closest","stopPropagation","preventDefault","data","FormData","row","getAttribute","style","display"],"mappings":"mLAY0B,SAElBA,KADM,IAAIC,IAAIC,OAAOC,SAASC,MACnBC,aAAaC,IAAI,QAEhCJ,OAAOK,oBAAoB,SAAUC,cACrCC,SAASC,iBAAiB,0CAA0CC,SAASC,OACrEZ,MACAY,KAAKC,cAAc,wBAA0Bb,KAAO,MAAMc,aAAa,YAAY,GAEvFC,YAAYH,SAEhBV,OAAOc,iBAAiB,SAAUR,qBAQhCA,aAAgBS,QACdL,KAAOK,EAAEC,OAAOC,QAAQ,0CACxBP,OACAK,EAAEG,kBACFH,EAAEI,iBACFN,YAAYH,QASdG,YAAeH,WACbU,KAAO,IAAIC,SAASX,MACxBA,KAAKO,QAAQ,aAAaT,iBAAiB,oBAAoBC,SAASa,MAChEA,IAAIC,aAAa,cAAgBH,KAAKhB,IAAI,QAC1CkB,IAAIE,MAAMC,QAAU,KAEpBH,IAAIE,MAAMC,QAAU"} \ No newline at end of file +{"version":3,"file":"selecttrack.min.js","sources":["../src/selecttrack.js"],"sourcesContent":["/*\n * Show selected text track\n *\n * @package mod_videotime\n * @module mod_videotime/selecttrrack\n * @copyright 2021 bdecent gmbh \n * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later\n */\n\n/**\n * Intialize listener and show current track\n */\nexport const initialize = () => {\n let url = new URL(window.location.href),\n lang = url.searchParams.get('lang');\n\n window.removeEventListener('change', handleChange);\n document.querySelectorAll('form.videotimetab_texttrack_selectlang').forEach((form) => {\n if (lang) {\n form.querySelector('select option[value=\"' + lang + '\"]').setAttribute('selected', true);\n }\n setLanguage(form);\n });\n window.addEventListener('change', handleChange);\n};\n\n/**\n * Form change event handler\n *\n * @param {event} e mouse event\n */\nconst handleChange = (e) => {\n let form = e.target.closest('form.videotimetab_texttrack_selectlang');\n if (form) {\n e.stopPropagation();\n e.preventDefault();\n setLanguage(form);\n }\n};\n\n/**\n * Show lang indicate by form\n *\n * @param {element} form\n */\nconst setLanguage = (form) => {\n let data = new FormData(form);\n form.closest('.tab-pane').querySelectorAll('.texttracks .row, .texttracks button[data-action=\"edit\"]').forEach((row) => {\n if (row.getAttribute('data-lang') == data.get('lang')) {\n row.style.display = null;\n } else {\n row.style.display = 'none';\n }\n });\n};\n"],"names":["lang","URL","window","location","href","searchParams","get","removeEventListener","handleChange","document","querySelectorAll","forEach","form","querySelector","setAttribute","setLanguage","addEventListener","e","target","closest","stopPropagation","preventDefault","data","FormData","row","getAttribute","style","display"],"mappings":"mLAY0B,SAElBA,KADM,IAAIC,IAAIC,OAAOC,SAASC,MACnBC,aAAaC,IAAI,QAEhCJ,OAAOK,oBAAoB,SAAUC,cACrCC,SAASC,iBAAiB,0CAA0CC,SAASC,OACrEZ,MACAY,KAAKC,cAAc,wBAA0Bb,KAAO,MAAMc,aAAa,YAAY,GAEvFC,YAAYH,SAEhBV,OAAOc,iBAAiB,SAAUR,qBAQhCA,aAAgBS,QACdL,KAAOK,EAAEC,OAAOC,QAAQ,0CACxBP,OACAK,EAAEG,kBACFH,EAAEI,iBACFN,YAAYH,QASdG,YAAeH,WACbU,KAAO,IAAIC,SAASX,MACxBA,KAAKO,QAAQ,aAAaT,iBAAiB,4DAA4DC,SAASa,MACxGA,IAAIC,aAAa,cAAgBH,KAAKhB,IAAI,QAC1CkB,IAAIE,MAAMC,QAAU,KAEpBH,IAAIE,MAAMC,QAAU"} \ No newline at end of file diff --git a/tab/texttrack/amd/src/selecttrack.js b/tab/texttrack/amd/src/selecttrack.js index ce4b6d03..330f20e8 100644 --- a/tab/texttrack/amd/src/selecttrack.js +++ b/tab/texttrack/amd/src/selecttrack.js @@ -45,7 +45,7 @@ const handleChange = (e) => { */ const setLanguage = (form) => { let data = new FormData(form); - form.closest('.tab-pane').querySelectorAll('.texttracks .row').forEach((row) => { + form.closest('.tab-pane').querySelectorAll('.texttracks .row, .texttracks button[data-action="edit"]').forEach((row) => { if (row.getAttribute('data-lang') == data.get('lang')) { row.style.display = null; } else { diff --git a/tab/texttrack/classes/tab.php b/tab/texttrack/classes/tab.php index ce50409f..6a28cdfe 100644 --- a/tab/texttrack/classes/tab.php +++ b/tab/texttrack/classes/tab.php @@ -26,6 +26,7 @@ defined('MOODLE_INTERNAL') || die(); +use context_module; use stdClass; require_once("$CFG->dirroot/mod/videotime/lib.php"); @@ -49,17 +50,6 @@ public function get_tab_content(): string { return $OUTPUT->render_from_template('videotimetab_texttrack/text_tab', $data); } - /** - * Defines the additional form fields. - * - * @param moodle_form $mform form to modify - */ - public static function add_form_fields($mform) { - if (videotime_has_repository()) { - parent::add_form_fields($mform); - } - } - /** * Parse track file to array of cues * @@ -96,6 +86,17 @@ public function export_for_template(): array { if ( ($lastupdate < $record->timemodified) || $lastupdate < $DB->get_field('videotime_vimeo_video', 'modified_time', ['link' => $record->vimeo_url]) + || $DB->get_records_sql( + "SELECT f.id + FROM {files} f + JOIN {videotime_track} t ON t.id = f.itemid + WHERE t.videotime = :videotime + AND f.timecreated > :lastupdate", + [ + 'videotime' => $record->id, + 'lastupdate' => $lastupdate, + ] + ) ) { $this->update_tracks(); } @@ -118,14 +119,18 @@ public function export_for_template(): array { } $track->captions = array_values($captions); $track->show = $show; + $track->trackid = (int)$track->uri; $track->langname = $this->get_language_name($track->lang); $show = false; $texttracks[] = $track; } + $instance = $this->get_instance(); + $context = $instance->get_context(); return [ 'texttracks' => $texttracks, 'showselector' => count($texttracks) > 1, + 'canedit' => videotime_has_repository() && has_capability('moodle/course:managefiles', $context), ]; } @@ -141,41 +146,7 @@ public function update_tracks() { $api = new \videotimeplugin_repository\api(); $record = $this->get_instance()->to_record(); - $endpoint = '/videos/' . mod_videotime_get_vimeo_id_from_link($record->vimeo_url) . '/texttracks'; - $request = $api->request($endpoint); - if ($request['status'] != 200 || empty($request['body']['data'])) { - return; - } - - try { - $transaction = $DB->start_delegated_transaction(); - - if ($trackids = $DB->get_fieldset_select('videotimetab_texttrack_track', 'id', 'videotime = ?', [$record->id])) { - [$sql, $params] = $DB->get_in_or_equal($trackids); - $DB->delete_records_select('videotimetab_texttrack_text', "track $sql", $params); - $DB->delete_records('videotimetab_texttrack_track', ['videotime' => $record->id]); - } - - foreach ($request['body']['data'] as $texttrack) { - if ($texttrack['active']) { - $trackid = $DB->insert_record('videotimetab_texttrack_track', [ - 'videotime' => $record->id, - 'lang' => $texttrack['language'], - 'uri' => $texttrack['uri'], - 'type' => $texttrack['type'], - 'link' => $texttrack['link'], - ]); - foreach ($this->parse_texttrack(file_get_contents($texttrack['link'])) as $text) { - $text['track'] = $trackid; - $DB->insert_record('videotimetab_texttrack_text', $text); - } - } - } - $DB->set_field('videotimetab_texttrack', 'lastupdate', time(), ['videotime' => $record->id]); - $transaction->allow_commit(); - } catch (Exception $e) { - $transaction->rollback($e); - } + $api->update_tracks($record); } /** @@ -231,6 +202,18 @@ public static function data_preprocessing(array &$defaultvalues, int $instance) } else { $defaultvalues['enable_texttrack'] = $DB->record_exists('videotimetab_texttrack', ['videotime' => $instance]); } + $draftitemid = file_get_submitted_draft_itemid('captions'); + $cm = get_coursemodule_from_instance('videotime', $instance); + $context = context_module::instance($cm->id); + file_prepare_draft_area( + $draftitemid, + $context->id, + 'videotimetab_texttrack', + 'captions', + 0, + [] + ); + $defaultvalues['captions'] = $draftitemid; } /** diff --git a/tab/texttrack/lang/en/videotimetab_texttrack.php b/tab/texttrack/lang/en/videotimetab_texttrack.php index 5c03d179..ef0682f4 100644 --- a/tab/texttrack/lang/en/videotimetab_texttrack.php +++ b/tab/texttrack/lang/en/videotimetab_texttrack.php @@ -30,3 +30,5 @@ $string['pluginname'] = 'Video Time Transcript tab'; $string['privacy:metadata'] = 'The Video Time Transcript tab plugin does not store any personal data.'; $string['upgradeplugin'] = 'This plugin requires installation of Video Time Business to enable.'; +$string['cues'] = 'Cues'; +$string['cueno'] = 'Cue {no}'; diff --git a/tab/texttrack/templates/text_tab.mustache b/tab/texttrack/templates/text_tab.mustache index 7e27ee92..30333679 100644 --- a/tab/texttrack/templates/text_tab.mustache +++ b/tab/texttrack/templates/text_tab.mustache @@ -20,7 +20,7 @@ This template for text track tab Variables optional for this template: - * textracks - array of available tracks + * texttracks - array of available tracks * showselect - boolean whether to show language selector Example context (json): @@ -47,7 +47,7 @@ } }} -
+
{{# showselector }}
diff --git a/version.php b/version.php index b52763bb..4dda1de8 100644 --- a/version.php +++ b/version.php @@ -26,7 +26,7 @@ $plugin->component = 'mod_videotime'; $plugin->release = '1.9'; -$plugin->version = 2025071201; +$plugin->version = 2025080500; $plugin->requires = 2024041600; $plugin->supported = [404, 500]; $plugin->maturity = MATURITY_STABLE; From e5d0bac6cae6d9cab26b44280155a5aca910b5fe Mon Sep 17 00:00:00 2001 From: Daniel Thies Date: Thu, 11 Sep 2025 14:07:12 -0500 Subject: [PATCH 02/10] VID-969: Coding improvement --- .../restore_videotime_activity_task.class.php | 18 +++--- db/upgrade.php | 1 - lang/en/videotime.php | 20 +++---- lib.php | 55 ++++++++++--------- mod_form.php | 33 +++++++---- plugin/videojs/classes/video_embed.php | 6 +- tab/chapter/lang/en/videotimetab_chapter.php | 2 +- .../lang/en/videotimetab_texttrack.php | 4 +- 8 files changed, 81 insertions(+), 58 deletions(-) diff --git a/backup/moodle2/restore_videotime_activity_task.class.php b/backup/moodle2/restore_videotime_activity_task.class.php index 22b99afe..43c5b63a 100644 --- a/backup/moodle2/restore_videotime_activity_task.class.php +++ b/backup/moodle2/restore_videotime_activity_task.class.php @@ -124,17 +124,21 @@ public function after_restore() { if ($options->next_activity_id > 0) { $updaterequired = true; - if ($newitem = restore_dbops::get_backup_ids_record( - $this->get_restoreid(), - 'course_module', - $options->next_activity_id - )) { + if ( + $newitem = restore_dbops::get_backup_ids_record( + $this->get_restoreid(), + 'course_module', + $options->next_activity_id + ) + ) { $options->next_activity_id = $newitem->newitemid; } - if (!$DB->record_exists('course_modules', [ + if ( + !$DB->record_exists('course_modules', [ 'id' => $options->next_activity_id, 'course' => $options->course, - ])) { + ]) + ) { $options->next_activity_id = 0; } } diff --git a/db/upgrade.php b/db/upgrade.php index ec83ce84..09f35eb9 100644 --- a/db/upgrade.php +++ b/db/upgrade.php @@ -855,7 +855,6 @@ function xmldb_videotime_upgrade($oldversion) { } if ($oldversion < 2025080500) { - // Define table videotime_track to be created. $table = new xmldb_table('videotime_track'); diff --git a/lang/en/videotime.php b/lang/en/videotime.php index e7509bb5..b5f724bc 100644 --- a/lang/en/videotime.php +++ b/lang/en/videotime.php @@ -28,6 +28,7 @@ $string['activity_name'] = 'Activity name'; $string['activity_name_help'] = 'Name displayed in course for this Video Time activity module.'; $string['activitystatus'] = "Activity completion status"; +$string['addtexttrack'] = 'Add text track'; $string['advancedsettings'] = 'Advanced settings'; $string['advancedsettings_help'] = 'Select all elements that should be displayed as advanced.'; $string['albums'] = 'Albums'; @@ -43,6 +44,8 @@ $string['browsevideos'] = 'Browse videos'; $string['calendarend'] = '{$a} ends'; $string['calendarstart'] = '{$a} begins'; +$string['captions'] = 'Captions'; +$string['chapters'] = 'Chapters'; $string['choose_video'] = 'Choose Video'; $string['choose_video_confirm'] = 'Are you sure you want to choose the video'; $string['cleanupalbumsandtags'] = 'Cleanup albums and tags'; @@ -216,6 +219,8 @@ $string['option_transparent_help'] = 'The responsive player and transparent background are enabled by default, to disable set this parameter to false.'; $string['option_width'] = 'Width'; $string['option_width_help'] = 'The exact width of the video. Defaults to the width of the largest available version of the video.'; +$string['page-mod-videotime-view'] = 'Video Time view page'; +$string['page-mod-videotime-x'] = 'Any Video Time module page'; $string['panelwidthlarge'] = 'Large panel width'; $string['panelwidthmedium'] = 'Medium panel width'; $string['panelwidthsmall'] = 'Small panel width'; @@ -279,11 +284,15 @@ $string['subplugintype_videotimeplugin_plural'] = 'Video Time Plugins'; $string['subplugintype_videotimetab'] = 'Video Time Tab'; $string['subplugintype_videotimetab_plural'] = 'Video Time Tabs'; +$string['subtitles'] = 'Subtitles'; $string['tabinformation'] = 'Information'; $string['tablealias_vt'] = 'Video Time'; $string['tabs'] = 'Tabs'; $string['tabtranscript'] = 'Transcript'; $string['taskscheduled'] = 'Task scheduled for next cron run'; +$string['texttrack'] = 'Text track'; +$string['texttrackno'] = 'Text track {no}'; +$string['texttracks'] = 'Text tracks'; $string['timecompleted'] = 'Time completed'; $string['timeended'] = 'Date ended'; $string['timeleft'] = "Time Left"; @@ -298,6 +307,7 @@

Otherwise you may have to wait until the scheduled task runs.

You can also run the command to pull in album information manually (instead of waiting):

/usr/bin/php admin/tool/task/cli/schedule_task.php --execute=\\\\videotimeplugin_repository\\\\task\\\\update_albums

'; +$string['tracktype'] = 'Track type'; $string['update_albums'] = 'Update video albums'; $string['upgrade_vimeo_account'] = 'NOTICE: Consider upgrading your Vimeo account. Your API request limit is too low.'; $string['use'] = 'Use'; @@ -339,13 +349,3 @@ $string['watchpercent_help'] = 'The highest percentage of the video seend'; $string['watchtime_help'] = 'The farthest position seen by the user'; $string['with_play_button'] = 'with play button'; -$string['texttracks'] = 'Text tracks'; -$string['texttrackno'] = 'Text track {no}'; -$string['chapters'] = 'Chapters'; -$string['captions'] = 'Captions'; -$string['subtitles'] = 'Subtitles'; -$string['page-mod-videotime-view'] = 'Video Time view page'; -$string['page-mod-videotime-x'] = 'Any Video Time module page'; -$string['texttrack'] = 'Text track'; -$string['addtexttrack'] = 'Add text track'; -$string['tracktype'] = 'Track type'; diff --git a/lib.php b/lib.php index 489e2268..cdd809d6 100644 --- a/lib.php +++ b/lib.php @@ -308,7 +308,9 @@ function videotime_update_instance($moduleinstance, $mform = null) { } if (!empty($moduleinstance->trackid)) { [$sql, $params] = $DB->get_in_or_equal($moduleinstance->trackid, SQL_PARAMS_NAMED); - $DB->delete_records_select('videotime_track', "videotime = :videotime AND NOT id $sql", $params + ['videotime' => $moduleinstance->id]); + $DB->delete_records_select('videotime_track', "videotime = :videotime AND NOT id $sql", $params + [ + 'videotime' => $moduleinstance->id, + ]); } else { $DB->delete_records('videotime_track', ['videotime' => $moduleinstance->id]); } @@ -467,8 +469,6 @@ function videotime_pluginfile($course, $cm, $context, $filearea, $args, $forcedo } send_stored_file($file, null, 0, $forcedownload, $options); - } else if ($filearea == 'texttrack') { - print_r($args);die(); } } @@ -924,7 +924,7 @@ function videotime_dndupload_register(): array { $hook = new \mod_videotime\hook\dndupload_register(); \core\di::get(\core\hook\manager::class)->dispatch($hook); - return ['files' => array_map(function($extension) { + return ['files' => array_map(function ($extension) { return [ 'extension' => $extension, 'message' => get_string('dnduploadvideotime', 'videotime'), @@ -1016,28 +1016,33 @@ function videotime_get_file_info($browser, $areas, $course, $cm, $context, $file $fs = get_file_storage(); $filepath = is_null($filepath) ? '/' : $filepath; $filename = is_null($filename) ? '.' : $filename; - if ($storedfile = $fs->get_file($context->id, 'videotimeplugin_videojs', $filearea, $itemid, $filepath, $filename)) { - - $urlbase = $CFG->wwwroot . '/pluginfile.php'; - - if ($filepath === '/' and $filename === '.') { - $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0); - } - return new file_info_stored( - $browser, - $context, - $storedfile, - $urlbase, - get_string($filearea, 'videotimeplugin_videojs'), - false, - true, - true, - false - ); + if ( + $storedfile = $fs->get_file( + $context->id, + 'videotimeplugin_videojs', + $filearea, + $itemid, + $filepath, + $filename + ) + ) { + $urlbase = $CFG->wwwroot . '/pluginfile.php'; + + if ($filepath === '/' && $filename === '.') { + $storedfile = new virtual_root_file($context->id, 'mod_resource', 'content', 0); + } + return new file_info_stored( + $browser, + $context, + $storedfile, + $urlbase, + get_string($filearea, 'videotimeplugin_videojs'), + false, + true, + true, + false + ); } - - //$classname = "\\videotimeplugin_$name\\file_info_container"; - //return $classname::get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename); } } } diff --git a/mod_form.php b/mod_form.php index 2a79f438..e3f0c3c7 100644 --- a/mod_form.php +++ b/mod_form.php @@ -311,8 +311,7 @@ public function completion_rule_enabled($data) { !empty($data[$this->get_suffixed_name('completion_on_finish')] || ( !empty($data[$this->get_suffixed_name('completion_on_percent')]) - && $data[$this->get_suffixed_name('completion_on_percent_value')]) - ); + && $data[$this->get_suffixed_name('completion_on_percent_value')])); } /** @@ -420,18 +419,20 @@ public function data_preprocessing(&$defaultvalues) { $defaultvalues['trackid'] = array_keys($texttracks); $defaultvalues['tracklabel'] = array_values(array_column($texttracks, 'label')); $defaultvalues['tracktype'] = array_values(array_column($texttracks, 'kind')); - $defaultvalues['trackvisible'] = array_values(array_column($texttracks, 'visible')) + array_fill(0, count($texttracks) + 2, 1); + $defaultvalues['trackvisible'] = array_values( + array_column($texttracks, 'visible') + ) + array_fill(0, count($texttracks) + 2, 1); $defaultvalues['trackdefault'] = array_values(array_column($texttracks, 'isdefault')); $defaultvalues['tracks_repeats'] = count($texttracks); $cm = get_coursemodule_from_instance('videotime', $this->current->instance); $context = context_module::instance($cm->id); foreach ($defaultvalues['trackid'] as $key => $trackid) { if ($trackid) { - if (!empty($defaultvalues['texttrack']) - &&!empty($defaultvalues['texttrack'][$key]) + if ( + !empty($defaultvalues['texttrack']) + && !empty($defaultvalues['texttrack'][$key]) ) { $draftitemid = $defaultvalues['texttrack'][$key]; - print_r($draftitemid);die(); } else { $draftitemid = null; } @@ -499,6 +500,9 @@ public function data_postprocessing($data) { } } + /** + * Add text track fields + */ protected function add_text_track_fields() { global $DB; @@ -508,7 +512,7 @@ protected function add_text_track_fields() { $currentlang = \current_language(); $languages = \get_string_manager()->get_list_of_translations(); - + $types = [ 'chapters' => get_string('chapters', 'mod_videotime'), 'captions' => get_string('captions', 'mod_videotime'), @@ -524,7 +528,7 @@ protected function add_text_track_fields() { $mform->createElement('advcheckbox', 'trackdefault', get_string('default')), ]; $tracks = [ - $mform->createElement('hidden', 'trackid'), + $mform->createElement('hidden', 'trackid'), $mform->createElement('text', 'tracklabel', get_string('texttrackno', 'mod_videotime')), $mform->createElement('group', 'trackattributes', '', $attributes, [ get_string('tracktype', 'mod_videotime'), @@ -569,7 +573,16 @@ protected function add_text_track_fields() { $mform->setType('trackid', PARAM_INT); $mform->setType('tracklabel', PARAM_TEXT); $mform->setType('srclang', PARAM_ALPHANUMEXT); - $this->repeat_elements($tracks, $trackno, $options, - 'tracks_repeats', 'tracks_add_fields', 1, get_string('addtexttrack', 'mod_videotime'), true, 'delete'); + $this->repeat_elements( + $tracks, + $trackno, + $options, + 'tracks_repeats', + 'tracks_add_fields', + 1, + get_string('addtexttrack', 'mod_videotime'), + true, + 'delete' + ); } } diff --git a/plugin/videojs/classes/video_embed.php b/plugin/videojs/classes/video_embed.php index 0e20a4e0..6067fc61 100644 --- a/plugin/videojs/classes/video_embed.php +++ b/plugin/videojs/classes/video_embed.php @@ -119,7 +119,7 @@ public function get_component_name() { * @param dndupload_register $hook Hook */ public static function dndupload_register(dndupload_register $hook): void { - foreach ([ + $extensions = [ 'avi', 'mp4', 'm3u8', @@ -128,7 +128,9 @@ public static function dndupload_register(dndupload_register $hook): void { 'ogg', 'ogv', 'webm', - ] as $extension) { + ]; + + foreach ($extensions as $extension) { $hook->register_handler($extension); } } diff --git a/tab/chapter/lang/en/videotimetab_chapter.php b/tab/chapter/lang/en/videotimetab_chapter.php index 4705e07e..1713ee6e 100644 --- a/tab/chapter/lang/en/videotimetab_chapter.php +++ b/tab/chapter/lang/en/videotimetab_chapter.php @@ -24,10 +24,10 @@ defined('MOODLE_INTERNAL') || die(); +$string['chapterno'] = 'Chapter {no}'; $string['default'] = 'Default'; $string['default_help'] = 'Whether tab is enabled by default'; $string['label'] = 'Chapters'; $string['pluginname'] = 'Video Time Chapter tab'; $string['privacy:metadata'] = 'The Video Time Chapter tab plugin does not store any personal data.'; $string['upgradeplugin'] = 'This plugin requires installation of Video Time Pro to enable.'; -$string['chapterno'] = 'Chapter {no}'; diff --git a/tab/texttrack/lang/en/videotimetab_texttrack.php b/tab/texttrack/lang/en/videotimetab_texttrack.php index ef0682f4..77396d7c 100644 --- a/tab/texttrack/lang/en/videotimetab_texttrack.php +++ b/tab/texttrack/lang/en/videotimetab_texttrack.php @@ -24,11 +24,11 @@ defined('MOODLE_INTERNAL') || die(); +$string['cueno'] = 'Cue {no}'; +$string['cues'] = 'Cues'; $string['default'] = 'Default'; $string['default_help'] = 'Whether tab is enabled by default'; $string['label'] = 'Transcript'; $string['pluginname'] = 'Video Time Transcript tab'; $string['privacy:metadata'] = 'The Video Time Transcript tab plugin does not store any personal data.'; $string['upgradeplugin'] = 'This plugin requires installation of Video Time Business to enable.'; -$string['cues'] = 'Cues'; -$string['cueno'] = 'Cue {no}'; From 018ccd1d0ad81460b6de022567d873b4eea8432a Mon Sep 17 00:00:00 2001 From: Daniel Thies Date: Tue, 23 Sep 2025 20:03:40 -0500 Subject: [PATCH 03/10] VID-1055: Implement course overview provider --- classes/courseformat/overview.php | 91 +++++++++++++++++++++++++++++++ index.php | 3 + version.php | 6 +- 3 files changed, 97 insertions(+), 3 deletions(-) create mode 100644 classes/courseformat/overview.php diff --git a/classes/courseformat/overview.php b/classes/courseformat/overview.php new file mode 100644 index 00000000..61ca57d1 --- /dev/null +++ b/classes/courseformat/overview.php @@ -0,0 +1,91 @@ +. + +namespace mod_videotime\courseformat; + +use cm_info; +use core\url; +use core\output\local\properties\text_align; +use core_courseformat\local\overview\overviewitem; +use core_courseformat\output\local\overview\overviewaction; + +/** + * Video Time overview integration class. + * + * @package mod_videotime + * @copyright 2025 bdecent gmbh + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class overview extends \core_courseformat\activityoverviewbase { + #[\Override] + public function get_extra_overview_items(): array { + return [ + 'totalviews' => $this->get_extra_totalviews_overview(), + ]; + } + + #[\Override] + public function get_actions_overview(): ?overviewitem { + if (!videotime_has_pro() || !has_capability('mod/videotime:view_report', $this->context)) { + return null; + } + + $viewscount = 1; + $url = new url('/mod/videotime/report.php', ['id' => $this->cm->id, 'mode' => 'approval']); + $text = get_string('view_report', 'mod_videotime'); + + $content = new overviewaction( + url: $url, + text: $text, + badgevalue: null, + badgetitle: null + ); + + return new overviewitem( + name: get_string('actions'), + value: $viewscount, + content: $content, + textalign: text_align::CENTER, + ); + } + + /** + * Get the "Total views" overview item. + * + * @return overviewitem The overview item. + */ + private function get_extra_totalviews_overview(): overviewitem { + global $DB, $USER; + + $columnheader = get_string('views', 'mod_videotime'); + + $params = ['module_id' => $this->cm->id]; + if (!has_capability('moodle/course:viewparticipants', $this->context)) { + $params['user_id'] = $USER->id; + } + $viewscount = $DB->get_field( + \videotimeplugin_pro\session::TABLE, + 'COUNT(DISTINCT uuid)', + $params + ); + + return new overviewitem( + name: $columnheader, + value: $viewscount, + textalign: text_align::END, + ); + } +} diff --git a/index.php b/index.php index c188d2f3..b2fbd2ad 100644 --- a/index.php +++ b/index.php @@ -30,6 +30,9 @@ $course = $DB->get_record('course', ['id' => $id], '*', MUST_EXIST); require_course_login($course); +if ($CFG->branch > 500) { + \core_courseformat\activityoverviewbase::redirect_to_overview_page($id, 'videotime'); +} $coursecontext = context_course::instance($course->id); diff --git a/version.php b/version.php index 4dda1de8..a3b6efb1 100644 --- a/version.php +++ b/version.php @@ -25,8 +25,8 @@ defined('MOODLE_INTERNAL') || die(); $plugin->component = 'mod_videotime'; -$plugin->release = '1.9'; -$plugin->version = 2025080500; +$plugin->release = '1.10'; +$plugin->version = 2025092200; $plugin->requires = 2024041600; -$plugin->supported = [404, 500]; +$plugin->supported = [404, 501]; $plugin->maturity = MATURITY_STABLE; From 0d8a9526b27c1c5d9f81f3040c63114e09ff8aad Mon Sep 17 00:00:00 2001 From: Daniel Thies Date: Fri, 26 Sep 2025 11:49:41 -0500 Subject: [PATCH 04/10] VID-969: Update version information --- classes/plugininfo/videotimeplugin.php | 8 ++++---- plugin/videojs/version.php | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/classes/plugininfo/videotimeplugin.php b/classes/plugininfo/videotimeplugin.php index 4bbe1db1..5d687477 100644 --- a/classes/plugininfo/videotimeplugin.php +++ b/classes/plugininfo/videotimeplugin.php @@ -62,15 +62,15 @@ public function available_updates() { case 'pro': $info = [ 'maturity' => MATURITY_STABLE, - 'release' => '1.9', - 'version' => 2025071001, + 'release' => '1.10', + 'version' => 2025092200, ]; break; case 'repository': $info = [ 'maturity' => MATURITY_STABLE, - 'release' => '1.9', - 'version' => 2025071001, + 'release' => '1.10', + 'version' => 2025092200, ]; break; } diff --git a/plugin/videojs/version.php b/plugin/videojs/version.php index 76ee1ff4..f3add353 100644 --- a/plugin/videojs/version.php +++ b/plugin/videojs/version.php @@ -25,8 +25,8 @@ defined('MOODLE_INTERNAL') || die(); $plugin->component = 'videotimeplugin_videojs'; -$plugin->release = '1.8.1'; -$plugin->version = 2023011204; +$plugin->release = '1.10'; +$plugin->version = 2025092200; $plugin->requires = 2015111610; $plugin->maturity = MATURITY_STABLE; $plugin->dependencies = [ From fce9e6408e3287036f8f840da6563d5d051b8fc2 Mon Sep 17 00:00:00 2001 From: Daniel Thies Date: Fri, 26 Sep 2025 11:52:06 -0500 Subject: [PATCH 05/10] VID-1063: Upgrade Vimeo player --- amd/build/player.min.js | 14 +- amd/build/player.min.js.map | 2 +- amd/src/player.js | 6752 ++++++++++++++++++----------------- thirdpartylibs.xml | 2 +- 4 files changed, 3443 insertions(+), 3327 deletions(-) diff --git a/amd/build/player.min.js b/amd/build/player.min.js index 54d8e28b..47fa1682 100644 --- a/amd/build/player.min.js +++ b/amd/build/player.min.js @@ -1,10 +1,10 @@ -!function(global,factory){"object"==typeof exports&&"undefined"!=typeof module?module.exports=factory():"function"==typeof define&&define.amd?define("mod_videotime/player",factory):((global="undefined"!=typeof globalThis?globalThis:global||self).Vimeo=global.Vimeo||{},global.Vimeo.Player=factory())}(window,(function(){function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _objectSpread2(target){for(var i=1;i=0;--i){var entry=this.tryEntries[i],record=entry.completion;if("root"===entry.tryLoc)return handle("end");if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc"),hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc)return this.complete(entry.completion,entry.afterLoc),resetTryEntry(entry),ContinueSentinel}},catch:function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if("throw"===record.type){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){return this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc},"next"===this.method&&(this.arg=void 0),ContinueSentinel}},exports}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;i0&&void 0!==arguments[0]?arguments[0]:{},id=oEmbedParameters.id,url=oEmbedParameters.url,idOrUrl=id||url;if(!idOrUrl)throw new Error("An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute.");if(isInteger(idOrUrl))return"https://vimeo.com/".concat(idOrUrl);if(isVimeoUrl(idOrUrl))return idOrUrl.replace("http:","https:");if(id)throw new TypeError("“".concat(id,"” is not a valid video id."));throw new TypeError("“".concat(idOrUrl,"” is not a vimeo.com url."))}var subscribe=function(target,eventName,callback){var onName=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"addEventListener",offName=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"removeEventListener",eventNames="string"==typeof eventName?[eventName]:eventName;return eventNames.forEach((function(evName){target[onName](evName,callback)})),{cancel:function(){return eventNames.forEach((function(evName){return target[offName](evName,callback)}))}}},arrayIndexOfSupport=void 0!==Array.prototype.indexOf,postMessageSupport="undefined"!=typeof window&&void 0!==window.postMessage;if(!(isNode||arrayIndexOfSupport&&postMessageSupport))throw new Error("Sorry, the Vimeo Player API is not available in this browser.");var commonjsGlobal="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{}; +function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);enumerableOnly&&(symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))),keys.push.apply(keys,symbols)}return keys}function _objectSpread2(target){for(var i=1;i=0;--i){var entry=this.tryEntries[i],record=entry.completion;if("root"===entry.tryLoc)return handle("end");if(entry.tryLoc<=this.prev){var hasCatch=hasOwn.call(entry,"catchLoc"),hasFinally=hasOwn.call(entry,"finallyLoc");if(hasCatch&&hasFinally){if(this.prev=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc<=this.prev&&hasOwn.call(entry,"finallyLoc")&&this.prev=0;--i){var entry=this.tryEntries[i];if(entry.finallyLoc===finallyLoc)return this.complete(entry.completion,entry.afterLoc),resetTryEntry(entry),ContinueSentinel}},catch:function(tryLoc){for(var i=this.tryEntries.length-1;i>=0;--i){var entry=this.tryEntries[i];if(entry.tryLoc===tryLoc){var record=entry.completion;if("throw"===record.type){var thrown=record.arg;resetTryEntry(entry)}return thrown}}throw new Error("illegal catch attempt")},delegateYield:function(iterable,resultName,nextLoc){return this.delegate={iterator:values(iterable),resultName:resultName,nextLoc:nextLoc},"next"===this.method&&(this.arg=void 0),ContinueSentinel}},exports}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg),value=info.value}catch(error){return void reject(error)}info.done?resolve(value):Promise.resolve(value).then(_next,_throw)}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise((function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value)}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err)}_next(void 0)}))}}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor))throw new TypeError("Cannot call a class as a function")}function _defineProperties(target,props){for(var i=0;iarr.length)&&(len=arr.length);for(var i=0,arr2=new Array(len);i0&&void 0!==arguments[0]?arguments[0]:{},id=oEmbedParameters.id,url=oEmbedParameters.url,idOrUrl=id||url;if(!idOrUrl)throw new Error("An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute.");if(isInteger(idOrUrl))return"https://vimeo.com/".concat(idOrUrl);if(isVimeoUrl(idOrUrl))return idOrUrl.replace("http:","https:");if(id)throw new TypeError("“".concat(id,"” is not a valid video id."));throw new TypeError("“".concat(idOrUrl,"” is not a vimeo.com url."))}var subscribe=function(target,eventName,callback){var onName=arguments.length>3&&void 0!==arguments[3]?arguments[3]:"addEventListener",offName=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"removeEventListener",eventNames="string"==typeof eventName?[eventName]:eventName;return eventNames.forEach((function(evName){target[onName](evName,callback)})),{cancel:function(){return eventNames.forEach((function(evName){return target[offName](evName,callback)}))}}};function findIframeBySourceWindow(sourceWindow){var doc=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document;if(!sourceWindow||!doc||"function"!=typeof doc.querySelectorAll)return null;for(var iframes=doc.querySelectorAll("iframe"),i=0;i - * @license MIT - */ -!function(self){if(!self.WeakMap){var hasOwnProperty=Object.prototype.hasOwnProperty,hasDefine=Object.defineProperty&&function(){try{return 1===Object.defineProperty({},"x",{value:1}).x}catch(e){}}(),defineProperty=function(object,name,value){hasDefine?Object.defineProperty(object,name,{configurable:!0,writable:!0,value:value}):object[name]=value};self.WeakMap=function(){function WeakMap(){if(void 0===this)throw new TypeError("Constructor WeakMap requires 'new'");if(defineProperty(this,"_id",genId("_WeakMap")),arguments.length>0)throw new TypeError("WeakMap iterable is not supported")}function checkInstance(x,methodName){if(!isObject(x)||!hasOwnProperty.call(x,"_id"))throw new TypeError(methodName+" method called on incompatible receiver "+typeof x)}function genId(prefix){return prefix+"_"+rand()+"."+rand()}function rand(){return Math.random().toString().substring(2)}return defineProperty(WeakMap.prototype,"delete",(function(key){if(checkInstance(this,"delete"),!isObject(key))return!1;var entry=key[this._id];return!(!entry||entry[0]!==key)&&(delete key[this._id],!0)})),defineProperty(WeakMap.prototype,"get",(function(key){if(checkInstance(this,"get"),isObject(key)){var entry=key[this._id];return entry&&entry[0]===key?entry[1]:void 0}})),defineProperty(WeakMap.prototype,"has",(function(key){if(checkInstance(this,"has"),!isObject(key))return!1;var entry=key[this._id];return!(!entry||entry[0]!==key)})),defineProperty(WeakMap.prototype,"set",(function(key,value){if(checkInstance(this,"set"),!isObject(key))throw new TypeError("Invalid value used as weak map key");var entry=key[this._id];return entry&&entry[0]===key?(entry[1]=value,this):(defineProperty(key,this._id,[key,value]),this)})),defineProperty(WeakMap,"_polyfill",!0),WeakMap}()}function isObject(x){return Object(x)===x}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:commonjsGlobal);var npo_src=function(fn,module){return fn(module={exports:{}},module.exports),module.exports}((function(module){var name,context,definition;definition=function(){var builtInProp,cycle,scheduling_queue,ToString=Object.prototype.toString,timer="undefined"!=typeof setImmediate?function(fn){return setImmediate(fn)}:setTimeout;try{Object.defineProperty({},"x",{}),builtInProp=function(obj,name,val,config){return Object.defineProperty(obj,name,{value:val,writable:!0,configurable:!1!==config})}}catch(err){builtInProp=function(obj,name,val){return obj[name]=val,obj}}function schedule(fn,self){scheduling_queue.add(fn,self),cycle||(cycle=timer(scheduling_queue.drain))}function isThenable(o){var _then,o_type=typeof o;return null==o||"object"!=o_type&&"function"!=o_type||(_then=o.then),"function"==typeof _then&&_then}function notify(){for(var i=0;i0&&schedule(notify,self))}catch(err){reject.call(new MakeDefWrapper(self),err)}}}function reject(msg){var self=this;self.triggered||(self.triggered=!0,self.def&&(self=self.def),self.msg=msg,self.state=2,self.chain.length>0&&schedule(notify,self))}function iteratePromises(Constructor,arr,resolver,rejecter){for(var idx=0;idx=8&&ieVersion<10&&(message=JSON.stringify(message)),player.element.contentWindow.postMessage(message,player.origin)}}function processData(player,data){var param,callbacks=[];if((data=parseMessageData(data)).event){if("error"===data.event)getCallbacks(player,data.data.method).forEach((function(promise){var error=new Error(data.data.message);error.name=data.data.name,promise.reject(error),removeCallback(player,data.data.method,promise)}));callbacks=getCallbacks(player,"event:".concat(data.event)),param=data.data}else if(data.method){var callback=function(player,name){var playerCallbacks=getCallbacks(player,name);if(playerCallbacks.length<1)return!1;var callback=playerCallbacks.shift();return removeCallback(player,name,callback),callback}(player,data.method);callback&&(callbacks.push(callback),param=data.value)}callbacks.forEach((function(callback){try{if("function"==typeof callback)return void callback.call(player,param);callback.resolve(param)}catch(e){}}))}var oEmbedParameters=["airplay","audio_tracks","audiotrack","autopause","autoplay","background","byline","cc","chapter_id","chapters","chromecast","color","colors","controls","dnt","end_time","fullscreen","height","id","interactive_params","keyboard","loop","maxheight","maxwidth","muted","play_button_position","playsinline","portrait","progress_bar","quality_selector","responsive","skipping_forward","speed","start_time","texttrack","title","transcript","transparent","unmute_button","url","vimeo_logo","volume","watch_full_video","width"];function getOEmbedParameters(element){var defaults=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return oEmbedParameters.reduce((function(params,param){var value=element.getAttribute("data-vimeo-".concat(param));return(value||""===value)&&(params[param]=""===value?1:value),params}),defaults)}function createEmbed(_ref,element){var html=_ref.html;if(!element)throw new TypeError("An element must be provided");if(null!==element.getAttribute("data-vimeo-initialized"))return element.querySelector("iframe");var div=document.createElement("div");return div.innerHTML=html,element.appendChild(div.firstChild),element.setAttribute("data-vimeo-initialized","true"),element.querySelector("iframe")}function getOEmbedData(videoUrl){var params=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},element=arguments.length>2?arguments[2]:void 0;return new Promise((function(resolve,reject){if(!isVimeoUrl(videoUrl))throw new TypeError("“".concat(videoUrl,"” is not a vimeo.com url."));var domain=getOembedDomain(videoUrl),url="https://".concat(domain,"/api/oembed.json?url=").concat(encodeURIComponent(videoUrl));for(var param in params)params.hasOwnProperty(param)&&(url+="&".concat(param,"=").concat(encodeURIComponent(params[param])));var xhr="XDomainRequest"in window?new XDomainRequest:new XMLHttpRequest;xhr.open("GET",url,!0),xhr.onload=function(){if(404!==xhr.status)if(403!==xhr.status)try{var json=JSON.parse(xhr.responseText);if(403===json.domain_status_code)return createEmbed(json,element),void reject(new Error("“".concat(videoUrl,"” is not embeddable.")));resolve(json)}catch(error){reject(error)}else reject(new Error("“".concat(videoUrl,"” is not embeddable.")));else reject(new Error("“".concat(videoUrl,"” was not found.")))},xhr.onerror=function(){var status=xhr.status?" (".concat(xhr.status,")"):"";reject(new Error("There was an error fetching the embed code from Vimeo".concat(status,".")))},xhr.send()}))}var defaultOptions={role:"viewer",autoPlayMuted:!0,allowedDrift:.3,maxAllowedDrift:1,minCheckInterval:.1,maxRateAdjustment:.2,maxTimeToCatchUp:1},TimingSrcConnector=function(_EventTarget){!function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),superClass&&_setPrototypeOf(subClass,superClass)}(TimingSrcConnector,_EventTarget);var Derived,hasNativeReflectConstruct,_updatePlayer,_updateTimingObject,_init,_super=(Derived=TimingSrcConnector,hasNativeReflectConstruct=_isNativeReflectConstruct(),function(){var result,Super=_getPrototypeOf(Derived);if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else result=Super.apply(this,arguments);return _possibleConstructorReturn(this,result)});function TimingSrcConnector(_player,timingObject){var _this,_ref,options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},logger=arguments.length>3?arguments[3]:void 0;return _classCallCheck(this,TimingSrcConnector),_defineProperty(_assertThisInitialized(_this=_super.call(this)),"logger",void 0),_defineProperty(_assertThisInitialized(_this),"speedAdjustment",0),_defineProperty(_assertThisInitialized(_this),"adjustSpeed",(_ref=_asyncToGenerator(_regeneratorRuntime().mark((function _callee(player,newAdjustment){var newPlaybackRate;return _regeneratorRuntime().wrap((function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(_this.speedAdjustment!==newAdjustment){_context.next=2;break}return _context.abrupt("return");case 2:return _context.next=4,player.getPlaybackRate();case 4:return _context.t0=_context.sent,_context.t1=_this.speedAdjustment,_context.t2=_context.t0-_context.t1,_context.t3=newAdjustment,newPlaybackRate=_context.t2+_context.t3,_this.log("New playbackRate: ".concat(newPlaybackRate)),_context.next=12,player.setPlaybackRate(newPlaybackRate);case 12:_this.speedAdjustment=newAdjustment;case 13:case"end":return _context.stop()}}),_callee)}))),function(_x,_x2){return _ref.apply(this,arguments)})),_this.logger=logger,_this.init(timingObject,_player,_objectSpread2(_objectSpread2({},defaultOptions),options)),_this}return _createClass(TimingSrcConnector,[{key:"disconnect",value:function(){this.dispatchEvent(new Event("disconnect"))}},{key:"init",value:(_init=_asyncToGenerator(_regeneratorRuntime().mark((function _callee2(timingObject,player,options){var playerUpdater,positionSync,timingObjectUpdater,_this2=this;return _regeneratorRuntime().wrap((function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:return _context2.next=2,this.waitForTOReadyState(timingObject,"open");case 2:if("viewer"!==options.role){_context2.next=10;break}return _context2.next=5,this.updatePlayer(timingObject,player,options);case 5:playerUpdater=subscribe(timingObject,"change",(function(){return _this2.updatePlayer(timingObject,player,options)})),positionSync=this.maintainPlaybackPosition(timingObject,player,options),this.addEventListener("disconnect",(function(){positionSync.cancel(),playerUpdater.cancel()})),_context2.next=14;break;case 10:return _context2.next=12,this.updateTimingObject(timingObject,player);case 12:timingObjectUpdater=subscribe(player,["seeked","play","pause","ratechange"],(function(){return _this2.updateTimingObject(timingObject,player)}),"on","off"),this.addEventListener("disconnect",(function(){return timingObjectUpdater.cancel()}));case 14:case"end":return _context2.stop()}}),_callee2,this)}))),function(_x3,_x4,_x5){return _init.apply(this,arguments)})},{key:"updateTimingObject",value:(_updateTimingObject=_asyncToGenerator(_regeneratorRuntime().mark((function _callee3(timingObject,player){return _regeneratorRuntime().wrap((function(_context3){for(;;)switch(_context3.prev=_context3.next){case 0:return _context3.t0=timingObject,_context3.next=3,player.getCurrentTime();case 3:return _context3.t1=_context3.sent,_context3.next=6,player.getPaused();case 6:if(!_context3.sent){_context3.next=10;break}_context3.t2=0,_context3.next=13;break;case 10:return _context3.next=12,player.getPlaybackRate();case 12:_context3.t2=_context3.sent;case 13:_context3.t3=_context3.t2,_context3.t4={position:_context3.t1,velocity:_context3.t3},_context3.t0.update.call(_context3.t0,_context3.t4);case 16:case"end":return _context3.stop()}}),_callee3)}))),function(_x6,_x7){return _updateTimingObject.apply(this,arguments)})},{key:"updatePlayer",value:(_updatePlayer=_asyncToGenerator(_regeneratorRuntime().mark((function _callee5(timingObject,player,options){var _timingObject$query,position,velocity;return _regeneratorRuntime().wrap((function(_context5){for(;;)switch(_context5.prev=_context5.next){case 0:if(_timingObject$query=timingObject.query(),position=_timingObject$query.position,velocity=_timingObject$query.velocity,"number"==typeof position&&player.setCurrentTime(position),"number"!=typeof velocity){_context5.next=25;break}if(0!==velocity){_context5.next=11;break}return _context5.next=6,player.getPaused();case 6:if(_context5.t0=_context5.sent,!1!==_context5.t0){_context5.next=9;break}player.pause();case 9:_context5.next=25;break;case 11:if(!(velocity>0)){_context5.next=25;break}return _context5.next=14,player.getPaused();case 14:if(_context5.t1=_context5.sent,!0!==_context5.t1){_context5.next=19;break}return _context5.next=18,player.play().catch(function(){var _ref2=_asyncToGenerator(_regeneratorRuntime().mark((function _callee4(err){return _regeneratorRuntime().wrap((function(_context4){for(;;)switch(_context4.prev=_context4.next){case 0:if("NotAllowedError"!==err.name||!options.autoPlayMuted){_context4.next=5;break}return _context4.next=3,player.setMuted(!0);case 3:return _context4.next=5,player.play().catch((function(err2){return console.error("Couldn't play the video from TimingSrcConnector. Error:",err2)}));case 5:case"end":return _context4.stop()}}),_callee4)})));return function(_x11){return _ref2.apply(this,arguments)}}());case 18:this.updatePlayer(timingObject,player,options);case 19:return _context5.next=21,player.getPlaybackRate();case 21:if(_context5.t2=_context5.sent,_context5.t3=velocity,_context5.t2===_context5.t3){_context5.next=25;break}player.setPlaybackRate(velocity);case 25:case"end":return _context5.stop()}}),_callee5,this)}))),function(_x8,_x9,_x10){return _updatePlayer.apply(this,arguments)})},{key:"maintainPlaybackPosition",value:function(timingObject,player,options){var _ref3,_this3=this,allowedDrift=options.allowedDrift,maxAllowedDrift=options.maxAllowedDrift,minCheckInterval=options.minCheckInterval,maxRateAdjustment=options.maxRateAdjustment,maxTimeToCatchUp=options.maxTimeToCatchUp,syncInterval=1e3*Math.min(maxTimeToCatchUp,Math.max(minCheckInterval,maxAllowedDrift)),check=(_ref3=_asyncToGenerator(_regeneratorRuntime().mark((function _callee6(){var diff,diffAbs,min,max,adjustment;return _regeneratorRuntime().wrap((function(_context6){for(;;)switch(_context6.prev=_context6.next){case 0:if(_context6.t0=0===timingObject.query().velocity,_context6.t0){_context6.next=6;break}return _context6.next=4,player.getPaused();case 4:_context6.t1=_context6.sent,_context6.t0=!0===_context6.t1;case 6:if(!_context6.t0){_context6.next=8;break}return _context6.abrupt("return");case 8:return _context6.t2=timingObject.query().position,_context6.next=11,player.getCurrentTime();case 11:if(_context6.t3=_context6.sent,diff=_context6.t2-_context6.t3,diffAbs=Math.abs(diff),_this3.log("Drift: ".concat(diff)),!(diffAbs>maxAllowedDrift)){_context6.next=22;break}return _context6.next=18,_this3.adjustSpeed(player,0);case 18:player.setCurrentTime(timingObject.query().position),_this3.log("Resync by currentTime"),_context6.next=29;break;case 22:if(!(diffAbs>allowedDrift)){_context6.next=29;break}return adjustment=(min=diffAbs/maxTimeToCatchUp)<(max=maxRateAdjustment)?(max-min)/2:max,_context6.next=28,_this3.adjustSpeed(player,adjustment*Math.sign(diff));case 28:_this3.log("Resync by playbackRate");case 29:case"end":return _context6.stop()}}),_callee6)}))),function(){return _ref3.apply(this,arguments)}),interval=setInterval((function(){return check()}),syncInterval);return{cancel:function(){return clearInterval(interval)}}}},{key:"log",value:function(msg){var _this$logger;null===(_this$logger=this.logger)||void 0===_this$logger||_this$logger.call(this,"TimingSrcConnector: ".concat(msg))}},{key:"waitForTOReadyState",value:function(timingObject,state){return new Promise((function(resolve){!function check(){timingObject.readyState===state?resolve():timingObject.addEventListener("readystatechange",check,{once:!0})}()}))}}]),TimingSrcConnector}(_wrapNativeSuper(EventTarget)),playerMap=new WeakMap,readyMap=new WeakMap,screenfull={},Player=function(){function Player(element){var _this=this,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,Player),window.jQuery&&element instanceof jQuery&&(element.length>1&&window.console&&console.warn&&console.warn("A jQuery object with multiple elements was passed, using the first element."),element=element[0]),"undefined"!=typeof document&&"string"==typeof element&&(element=document.getElementById(element)),!isDomElement(element))throw new TypeError("You must pass either a valid element or a valid id.");if("IFRAME"!==element.nodeName){var iframe=element.querySelector("iframe");iframe&&(element=iframe)}if("IFRAME"===element.nodeName&&!isVimeoUrl(element.getAttribute("src")||""))throw new Error("The player element passed isn’t a Vimeo embed.");if(playerMap.has(element))return playerMap.get(element);this._window=element.ownerDocument.defaultView,this.element=element,this.origin="*";var readyPromise=new npo_src((function(resolve,reject){if(_this._onMessage=function(event){if(isVimeoUrl(event.origin)&&_this.element.contentWindow===event.source){"*"===_this.origin&&(_this.origin=event.origin);var data=parseMessageData(event.data);if(data&&"error"===data.event&&data.data&&"ready"===data.data.method){var error=new Error(data.data.message);return error.name=data.data.name,void reject(error)}var isReadyEvent=data&&"ready"===data.event,isPingResponse=data&&"ping"===data.method;if(isReadyEvent||isPingResponse)return _this.element.setAttribute("data-ready","true"),void resolve();processData(_this,data)}},_this._window.addEventListener("message",_this._onMessage),"IFRAME"!==_this.element.nodeName){var params=getOEmbedParameters(element,options);getOEmbedData(getVimeoUrl(params),params,element).then((function(data){var iframe=createEmbed(data,element);return _this.element=iframe,_this._originalElement=element,swapCallbacks(element,iframe),playerMap.set(_this.element,_this),data})).catch(reject)}}));if(readyMap.set(this,readyPromise),playerMap.set(this.element,this),"IFRAME"===this.element.nodeName&&postMessage(this,"ping"),screenfull.isEnabled){var exitFullscreen=function(){return screenfull.exit()};this.fullscreenchangeHandler=function(){screenfull.isFullscreen?storeCallback(_this,"event:exitFullscreen",exitFullscreen):removeCallback(_this,"event:exitFullscreen",exitFullscreen),_this.ready().then((function(){postMessage(_this,"fullscreenchange",screenfull.isFullscreen)}))},screenfull.on("fullscreenchange",this.fullscreenchangeHandler)}return this}var _setTimingSrc;return _createClass(Player,[{key:"callMethod",value:function(name){var _this2=this,args=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new npo_src((function(resolve,reject){return _this2.ready().then((function(){storeCallback(_this2,name,{resolve:resolve,reject:reject}),postMessage(_this2,name,args)})).catch(reject)}))}},{key:"get",value:function(name){var _this3=this;return new npo_src((function(resolve,reject){return name=getMethodName(name,"get"),_this3.ready().then((function(){storeCallback(_this3,name,{resolve:resolve,reject:reject}),postMessage(_this3,name)})).catch(reject)}))}},{key:"set",value:function(name,value){var _this4=this;return new npo_src((function(resolve,reject){if(name=getMethodName(name,"set"),null==value)throw new TypeError("There must be a value to set.");return _this4.ready().then((function(){storeCallback(_this4,name,{resolve:resolve,reject:reject}),postMessage(_this4,name,value)})).catch(reject)}))}},{key:"on",value:function(eventName,callback){if(!eventName)throw new TypeError("You must pass an event name.");if(!callback)throw new TypeError("You must pass a callback function.");if("function"!=typeof callback)throw new TypeError("The callback must be a function.");0===getCallbacks(this,"event:".concat(eventName)).length&&this.callMethod("addEventListener",eventName).catch((function(){})),storeCallback(this,"event:".concat(eventName),callback)}},{key:"off",value:function(eventName,callback){if(!eventName)throw new TypeError("You must pass an event name.");if(callback&&"function"!=typeof callback)throw new TypeError("The callback must be a function.");removeCallback(this,"event:".concat(eventName),callback)&&this.callMethod("removeEventListener",eventName).catch((function(e){}))}},{key:"loadVideo",value:function(options){return this.callMethod("loadVideo",options)}},{key:"ready",value:function(){var readyPromise=readyMap.get(this)||new npo_src((function(resolve,reject){reject(new Error("Unknown player. Probably unloaded."))}));return npo_src.resolve(readyPromise)}},{key:"addCuePoint",value:function(time){var data=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.callMethod("addCuePoint",{time:time,data:data})}},{key:"removeCuePoint",value:function(id){return this.callMethod("removeCuePoint",id)}},{key:"enableTextTrack",value:function(language,kind){if(!language)throw new TypeError("You must pass a language.");return this.callMethod("enableTextTrack",{language:language,kind:kind})}},{key:"disableTextTrack",value:function(){return this.callMethod("disableTextTrack")}},{key:"pause",value:function(){return this.callMethod("pause")}},{key:"play",value:function(){return this.callMethod("play")}},{key:"requestFullscreen",value:function(){return screenfull.isEnabled?screenfull.request(this.element):this.callMethod("requestFullscreen")}},{key:"exitFullscreen",value:function(){return screenfull.isEnabled?screenfull.exit():this.callMethod("exitFullscreen")}},{key:"getFullscreen",value:function(){return screenfull.isEnabled?npo_src.resolve(screenfull.isFullscreen):this.get("fullscreen")}},{key:"requestPictureInPicture",value:function(){return this.callMethod("requestPictureInPicture")}},{key:"exitPictureInPicture",value:function(){return this.callMethod("exitPictureInPicture")}},{key:"getPictureInPicture",value:function(){return this.get("pictureInPicture")}},{key:"remotePlaybackPrompt",value:function(){return this.callMethod("remotePlaybackPrompt")}},{key:"unload",value:function(){return this.callMethod("unload")}},{key:"destroy",value:function(){var _this5=this;return new npo_src((function(resolve){if(readyMap.delete(_this5),playerMap.delete(_this5.element),_this5._originalElement&&(playerMap.delete(_this5._originalElement),_this5._originalElement.removeAttribute("data-vimeo-initialized")),_this5.element&&"IFRAME"===_this5.element.nodeName&&_this5.element.parentNode&&(_this5.element.parentNode.parentNode&&_this5._originalElement&&_this5._originalElement!==_this5.element.parentNode?_this5.element.parentNode.parentNode.removeChild(_this5.element.parentNode):_this5.element.parentNode.removeChild(_this5.element)),_this5.element&&"DIV"===_this5.element.nodeName&&_this5.element.parentNode){_this5.element.removeAttribute("data-vimeo-initialized");var iframe=_this5.element.querySelector("iframe");iframe&&iframe.parentNode&&(iframe.parentNode.parentNode&&_this5._originalElement&&_this5._originalElement!==iframe.parentNode?iframe.parentNode.parentNode.removeChild(iframe.parentNode):iframe.parentNode.removeChild(iframe))}_this5._window.removeEventListener("message",_this5._onMessage),screenfull.isEnabled&&screenfull.off("fullscreenchange",_this5.fullscreenchangeHandler),resolve()}))}},{key:"getAutopause",value:function(){return this.get("autopause")}},{key:"setAutopause",value:function(autopause){return this.set("autopause",autopause)}},{key:"getBuffered",value:function(){return this.get("buffered")}},{key:"getCameraProps",value:function(){return this.get("cameraProps")}},{key:"setCameraProps",value:function(camera){return this.set("cameraProps",camera)}},{key:"getChapters",value:function(){return this.get("chapters")}},{key:"getCurrentChapter",value:function(){return this.get("currentChapter")}},{key:"getColor",value:function(){return this.get("color")}},{key:"getColors",value:function(){return npo_src.all([this.get("colorOne"),this.get("colorTwo"),this.get("colorThree"),this.get("colorFour")])}},{key:"setColor",value:function(color){return this.set("color",color)}},{key:"setColors",value:function(colors){if(!Array.isArray(colors))return new npo_src((function(resolve,reject){return reject(new TypeError("Argument must be an array."))}));var nullPromise=new npo_src((function(resolve){return resolve(null)})),colorPromises=[colors[0]?this.set("colorOne",colors[0]):nullPromise,colors[1]?this.set("colorTwo",colors[1]):nullPromise,colors[2]?this.set("colorThree",colors[2]):nullPromise,colors[3]?this.set("colorFour",colors[3]):nullPromise];return npo_src.all(colorPromises)}},{key:"getCuePoints",value:function(){return this.get("cuePoints")}},{key:"getCurrentTime",value:function(){return this.get("currentTime")}},{key:"setCurrentTime",value:function(currentTime){return this.set("currentTime",currentTime)}},{key:"getDuration",value:function(){return this.get("duration")}},{key:"getEnded",value:function(){return this.get("ended")}},{key:"getLoop",value:function(){return this.get("loop")}},{key:"setLoop",value:function(loop){return this.set("loop",loop)}},{key:"setMuted",value:function(muted){return this.set("muted",muted)}},{key:"getMuted",value:function(){return this.get("muted")}},{key:"getPaused",value:function(){return this.get("paused")}},{key:"getPlaybackRate",value:function(){return this.get("playbackRate")}},{key:"setPlaybackRate",value:function(playbackRate){return this.set("playbackRate",playbackRate)}},{key:"getPlayed",value:function(){return this.get("played")}},{key:"getQualities",value:function(){return this.get("qualities")}},{key:"getQuality",value:function(){return this.get("quality")}},{key:"setQuality",value:function(quality){return this.set("quality",quality)}},{key:"getRemotePlaybackAvailability",value:function(){return this.get("remotePlaybackAvailability")}},{key:"getRemotePlaybackState",value:function(){return this.get("remotePlaybackState")}},{key:"getSeekable",value:function(){return this.get("seekable")}},{key:"getSeeking",value:function(){return this.get("seeking")}},{key:"getTextTracks",value:function(){return this.get("textTracks")}},{key:"getVideoEmbedCode",value:function(){return this.get("videoEmbedCode")}},{key:"getVideoId",value:function(){return this.get("videoId")}},{key:"getVideoTitle",value:function(){return this.get("videoTitle")}},{key:"getVideoWidth",value:function(){return this.get("videoWidth")}},{key:"getVideoHeight",value:function(){return this.get("videoHeight")}},{key:"getVideoUrl",value:function(){return this.get("videoUrl")}},{key:"getVolume",value:function(){return this.get("volume")}},{key:"setVolume",value:function(volume){return this.set("volume",volume)}},{key:"setTimingSrc",value:(_setTimingSrc=_asyncToGenerator(_regeneratorRuntime().mark((function _callee(timingObject,options){var connector,_this6=this;return _regeneratorRuntime().wrap((function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(timingObject){_context.next=2;break}throw new TypeError("A Timing Object must be provided.");case 2:return _context.next=4,this.ready();case 4:return connector=new TimingSrcConnector(this,timingObject,options),postMessage(this,"notifyTimingObjectConnect"),connector.addEventListener("disconnect",(function(){return postMessage(_this6,"notifyTimingObjectDisconnect")})),_context.abrupt("return",connector);case 8:case"end":return _context.stop()}}),_callee,this)}))),function(_x,_x2){return _setTimingSrc.apply(this,arguments)})}]),Player}();return isNode||(screenfull=function(){var fn=function(){for(var val,fnMap=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,l=fnMap.length,ret={};i0&&void 0!==arguments[0]?arguments[0]:document,elements=[].slice.call(parent.querySelectorAll("[data-vimeo-id], [data-vimeo-url]")),handleError=function(error){"console"in window&&console.error&&console.error("There was an error creating an embed: ".concat(error))};elements.forEach((function(element){try{if(null!==element.getAttribute("data-vimeo-defer"))return;var params=getOEmbedParameters(element);getOEmbedData(getVimeoUrl(params),params,element).then((function(data){return createEmbed(data,element)})).catch(handleError)}catch(error){handleError(error)}}))}(),function(){var parent=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoPlayerResizeEmbeds_){window.VimeoPlayerResizeEmbeds_=!0;var onMessage=function(event){if(isVimeoUrl(event.origin)&&event.data&&"spacechange"===event.data.event)for(var iframes=parent.querySelectorAll("iframe"),i=0;i0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoSeoMetadataAppended){window.VimeoSeoMetadataAppended=!0;var onMessage=function(event){if(isVimeoUrl(event.origin)){var data=parseMessageData(event.data);if(data&&"ready"===data.event)for(var iframes=parent.querySelectorAll("iframe"),i=0;i0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoCheckedUrlTimeParam){window.VimeoCheckedUrlTimeParam=!0;var handleError=function(error){"console"in window&&console.error&&console.error("There was an error getting video Id: ".concat(error))},onMessage=function(event){if(isVimeoUrl(event.origin)){var data=parseMessageData(event.data);if(data&&"ready"===data.event)for(var iframes=parent.querySelectorAll("iframe"),_loop=function(){var iframe=iframes[i],isValidMessageSource=iframe.contentWindow===event.source;if(isVimeoEmbed(iframe.src)&&isValidMessageSource){var player=new Player(iframe);player.getVideoId().then((function(videoId){var matches=new RegExp("[?&]vimeo_t_".concat(videoId,"=([^&#]*)")).exec(window.location.href);if(matches&&matches[1]){var sec=decodeURI(matches[1]);player.setCurrentTime(sec)}})).catch(handleError)}},i=0;i + * @license MIT + */ +!function(self){if(!self.WeakMap){var hasOwnProperty=Object.prototype.hasOwnProperty,hasDefine=Object.defineProperty&&function(){try{return 1===Object.defineProperty({},"x",{value:1}).x}catch(e){}}(),defineProperty=function(object,name,value){hasDefine?Object.defineProperty(object,name,{configurable:!0,writable:!0,value:value}):object[name]=value};self.WeakMap=function(){function WeakMap(){if(void 0===this)throw new TypeError("Constructor WeakMap requires 'new'");if(defineProperty(this,"_id",genId("_WeakMap")),arguments.length>0)throw new TypeError("WeakMap iterable is not supported")}function checkInstance(x,methodName){if(!isObject(x)||!hasOwnProperty.call(x,"_id"))throw new TypeError(methodName+" method called on incompatible receiver "+typeof x)}function genId(prefix){return prefix+"_"+rand()+"."+rand()}function rand(){return Math.random().toString().substring(2)}return defineProperty(WeakMap.prototype,"delete",(function(key){if(checkInstance(this,"delete"),!isObject(key))return!1;var entry=key[this._id];return!(!entry||entry[0]!==key)&&(delete key[this._id],!0)})),defineProperty(WeakMap.prototype,"get",(function(key){if(checkInstance(this,"get"),isObject(key)){var entry=key[this._id];return entry&&entry[0]===key?entry[1]:void 0}})),defineProperty(WeakMap.prototype,"has",(function(key){if(checkInstance(this,"has"),!isObject(key))return!1;var entry=key[this._id];return!(!entry||entry[0]!==key)})),defineProperty(WeakMap.prototype,"set",(function(key,value){if(checkInstance(this,"set"),!isObject(key))throw new TypeError("Invalid value used as weak map key");var entry=key[this._id];return entry&&entry[0]===key?(entry[1]=value,this):(defineProperty(key,this._id,[key,value]),this)})),defineProperty(WeakMap,"_polyfill",!0),WeakMap}()}function isObject(x){return Object(x)===x}}("undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:commonjsGlobal);var fn,module,npo_src=(fn=function(module){var name,context,definition;definition=function(){var builtInProp,cycle,scheduling_queue,ToString=Object.prototype.toString,timer="undefined"!=typeof setImmediate?function(fn){return setImmediate(fn)}:setTimeout;try{Object.defineProperty({},"x",{}),builtInProp=function(obj,name,val,config){return Object.defineProperty(obj,name,{value:val,writable:!0,configurable:!1!==config})}}catch(err){builtInProp=function(obj,name,val){return obj[name]=val,obj}}function schedule(fn,self){scheduling_queue.add(fn,self),cycle||(cycle=timer(scheduling_queue.drain))}function isThenable(o){var _then,o_type=typeof o;return null==o||"object"!=o_type&&"function"!=o_type||(_then=o.then),"function"==typeof _then&&_then}function notify(){for(var i=0;i0&&schedule(notify,self))}catch(err){reject.call(new MakeDefWrapper(self),err)}}}function reject(msg){var self=this;self.triggered||(self.triggered=!0,self.def&&(self=self.def),self.msg=msg,self.state=2,self.chain.length>0&&schedule(notify,self))}function iteratePromises(Constructor,arr,resolver,rejecter){for(var idx=0;idx=8&&ieVersion<10&&(message=JSON.stringify(message)),player.element.contentWindow.postMessage(message,player.origin)}}function processData(player,data){var param,callbacks=[];if((data=parseMessageData(data)).event){if("error"===data.event)getCallbacks(player,data.data.method).forEach((function(promise){var error=new Error(data.data.message);error.name=data.data.name,promise.reject(error),removeCallback(player,data.data.method,promise)}));callbacks=getCallbacks(player,"event:".concat(data.event)),param=data.data}else if(data.method){var callback=function(player,name){var playerCallbacks=getCallbacks(player,name);if(playerCallbacks.length<1)return!1;var callback=playerCallbacks.shift();return removeCallback(player,name,callback),callback}(player,data.method);callback&&(callbacks.push(callback),param=data.value)}callbacks.forEach((function(callback){try{if("function"==typeof callback)return void callback.call(player,param);callback.resolve(param)}catch(e){}}))}var oEmbedParameters=["airplay","audio_tracks","audiotrack","autopause","autoplay","background","byline","cc","chapter_id","chapters","chromecast","color","colors","controls","dnt","end_time","fullscreen","height","id","initial_quality","interactive_params","keyboard","loop","maxheight","max_quality","maxwidth","min_quality","muted","play_button_position","playsinline","portrait","preload","progress_bar","quality","quality_selector","responsive","skipping_forward","speed","start_time","texttrack","thumbnail_id","title","transcript","transparent","unmute_button","url","vimeo_logo","volume","watch_full_video","width"];function getOEmbedParameters(element){var defaults=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return oEmbedParameters.reduce((function(params,param){var value=element.getAttribute("data-vimeo-".concat(param));return(value||""===value)&&(params[param]=""===value?1:value),params}),defaults)}function createEmbed(_ref,element){var html=_ref.html;if(!element)throw new TypeError("An element must be provided");if(null!==element.getAttribute("data-vimeo-initialized"))return element.querySelector("iframe");var div=document.createElement("div");return div.innerHTML=html,element.appendChild(div.firstChild),element.setAttribute("data-vimeo-initialized","true"),element.querySelector("iframe")}function getOEmbedData(videoUrl){var params=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},element=arguments.length>2?arguments[2]:void 0;return new Promise((function(resolve,reject){if(!isVimeoUrl(videoUrl))throw new TypeError("“".concat(videoUrl,"” is not a vimeo.com url."));var domain=getOembedDomain(videoUrl),url="https://".concat(domain,"/api/oembed.json?url=").concat(encodeURIComponent(videoUrl));for(var param in params)params.hasOwnProperty(param)&&(url+="&".concat(param,"=").concat(encodeURIComponent(params[param])));var xhr="XDomainRequest"in window?new XDomainRequest:new XMLHttpRequest;xhr.open("GET",url,!0),xhr.onload=function(){if(404!==xhr.status)if(403!==xhr.status)try{var json=JSON.parse(xhr.responseText);if(403===json.domain_status_code)return createEmbed(json,element),void reject(new Error("“".concat(videoUrl,"” is not embeddable.")));resolve(json)}catch(error){reject(error)}else reject(new Error("“".concat(videoUrl,"” is not embeddable.")));else reject(new Error("“".concat(videoUrl,"” was not found.")))},xhr.onerror=function(){var status=xhr.status?" (".concat(xhr.status,")"):"";reject(new Error("There was an error fetching the embed code from Vimeo".concat(status,".")))},xhr.send()}))}var defaultOptions={role:"viewer",autoPlayMuted:!0,allowedDrift:.3,maxAllowedDrift:1,minCheckInterval:.1,maxRateAdjustment:.2,maxTimeToCatchUp:1},TimingSrcConnector=function(_EventTarget){!function(subClass,superClass){if("function"!=typeof superClass&&null!==superClass)throw new TypeError("Super expression must either be null or a function");subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,writable:!0,configurable:!0}}),Object.defineProperty(subClass,"prototype",{writable:!1}),superClass&&_setPrototypeOf(subClass,superClass)}(TimingSrcConnector,_wrapNativeSuper(EventTarget));var Derived,hasNativeReflectConstruct,_updatePlayer,_updateTimingObject,_init,_super=(Derived=TimingSrcConnector,hasNativeReflectConstruct=_isNativeReflectConstruct(),function(){var result,Super=_getPrototypeOf(Derived);if(hasNativeReflectConstruct){var NewTarget=_getPrototypeOf(this).constructor;result=Reflect.construct(Super,arguments,NewTarget)}else result=Super.apply(this,arguments);return _possibleConstructorReturn(this,result)});function TimingSrcConnector(_player,timingObject){var _this,_ref,options=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},logger=arguments.length>3?arguments[3]:void 0;return _classCallCheck(this,TimingSrcConnector),_defineProperty(_assertThisInitialized(_this=_super.call(this)),"logger",void 0),_defineProperty(_assertThisInitialized(_this),"speedAdjustment",0),_defineProperty(_assertThisInitialized(_this),"adjustSpeed",(_ref=_asyncToGenerator(_regeneratorRuntime().mark((function _callee(player,newAdjustment){var newPlaybackRate;return _regeneratorRuntime().wrap((function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(_this.speedAdjustment!==newAdjustment){_context.next=2;break}return _context.abrupt("return");case 2:return _context.next=4,player.getPlaybackRate();case 4:return _context.t0=_context.sent,_context.t1=_this.speedAdjustment,_context.t2=_context.t0-_context.t1,_context.t3=newAdjustment,newPlaybackRate=_context.t2+_context.t3,_this.log("New playbackRate: ".concat(newPlaybackRate)),_context.next=12,player.setPlaybackRate(newPlaybackRate);case 12:_this.speedAdjustment=newAdjustment;case 13:case"end":return _context.stop()}}),_callee)}))),function(_x,_x2){return _ref.apply(this,arguments)})),_this.logger=logger,_this.init(timingObject,_player,_objectSpread2(_objectSpread2({},defaultOptions),options)),_this}return _createClass(TimingSrcConnector,[{key:"disconnect",value:function(){this.dispatchEvent(new Event("disconnect"))}},{key:"init",value:(_init=_asyncToGenerator(_regeneratorRuntime().mark((function _callee2(timingObject,player,options){var playerUpdater,positionSync,timingObjectUpdater,_this2=this;return _regeneratorRuntime().wrap((function(_context2){for(;;)switch(_context2.prev=_context2.next){case 0:return _context2.next=2,this.waitForTOReadyState(timingObject,"open");case 2:if("viewer"!==options.role){_context2.next=10;break}return _context2.next=5,this.updatePlayer(timingObject,player,options);case 5:playerUpdater=subscribe(timingObject,"change",(function(){return _this2.updatePlayer(timingObject,player,options)})),positionSync=this.maintainPlaybackPosition(timingObject,player,options),this.addEventListener("disconnect",(function(){positionSync.cancel(),playerUpdater.cancel()})),_context2.next=14;break;case 10:return _context2.next=12,this.updateTimingObject(timingObject,player);case 12:timingObjectUpdater=subscribe(player,["seeked","play","pause","ratechange"],(function(){return _this2.updateTimingObject(timingObject,player)}),"on","off"),this.addEventListener("disconnect",(function(){return timingObjectUpdater.cancel()}));case 14:case"end":return _context2.stop()}}),_callee2,this)}))),function(_x3,_x4,_x5){return _init.apply(this,arguments)})},{key:"updateTimingObject",value:(_updateTimingObject=_asyncToGenerator(_regeneratorRuntime().mark((function _callee3(timingObject,player){var _yield$Promise$all,_yield$Promise$all2,position,isPaused,playbackRate;return _regeneratorRuntime().wrap((function(_context3){for(;;)switch(_context3.prev=_context3.next){case 0:return _context3.next=2,Promise.all([player.getCurrentTime(),player.getPaused(),player.getPlaybackRate()]);case 2:_yield$Promise$all=_context3.sent,_yield$Promise$all2=_slicedToArray(_yield$Promise$all,3),position=_yield$Promise$all2[0],isPaused=_yield$Promise$all2[1],playbackRate=_yield$Promise$all2[2],timingObject.update({position:position,velocity:isPaused?0:playbackRate});case 8:case"end":return _context3.stop()}}),_callee3)}))),function(_x6,_x7){return _updateTimingObject.apply(this,arguments)})},{key:"updatePlayer",value:(_updatePlayer=_asyncToGenerator(_regeneratorRuntime().mark((function _callee5(timingObject,player,options){var _timingObject$query,position,velocity;return _regeneratorRuntime().wrap((function(_context5){for(;;)switch(_context5.prev=_context5.next){case 0:if(_timingObject$query=timingObject.query(),position=_timingObject$query.position,velocity=_timingObject$query.velocity,"number"==typeof position&&player.setCurrentTime(position),"number"!=typeof velocity){_context5.next=25;break}if(0!==velocity){_context5.next=11;break}return _context5.next=6,player.getPaused();case 6:if(_context5.t0=_context5.sent,!1!==_context5.t0){_context5.next=9;break}player.pause();case 9:_context5.next=25;break;case 11:if(!(velocity>0)){_context5.next=25;break}return _context5.next=14,player.getPaused();case 14:if(_context5.t1=_context5.sent,!0!==_context5.t1){_context5.next=19;break}return _context5.next=18,player.play().catch(function(){var _ref2=_asyncToGenerator(_regeneratorRuntime().mark((function _callee4(err){return _regeneratorRuntime().wrap((function(_context4){for(;;)switch(_context4.prev=_context4.next){case 0:if("NotAllowedError"!==err.name||!options.autoPlayMuted){_context4.next=5;break}return _context4.next=3,player.setMuted(!0);case 3:return _context4.next=5,player.play().catch((function(err2){return console.error("Couldn't play the video from TimingSrcConnector. Error:",err2)}));case 5:case"end":return _context4.stop()}}),_callee4)})));return function(_x11){return _ref2.apply(this,arguments)}}());case 18:this.updatePlayer(timingObject,player,options);case 19:return _context5.next=21,player.getPlaybackRate();case 21:if(_context5.t2=_context5.sent,_context5.t3=velocity,_context5.t2===_context5.t3){_context5.next=25;break}player.setPlaybackRate(velocity);case 25:case"end":return _context5.stop()}}),_callee5,this)}))),function(_x8,_x9,_x10){return _updatePlayer.apply(this,arguments)})},{key:"maintainPlaybackPosition",value:function(timingObject,player,options){var _ref3,_this3=this,allowedDrift=options.allowedDrift,maxAllowedDrift=options.maxAllowedDrift,minCheckInterval=options.minCheckInterval,maxRateAdjustment=options.maxRateAdjustment,maxTimeToCatchUp=options.maxTimeToCatchUp,syncInterval=1e3*Math.min(maxTimeToCatchUp,Math.max(minCheckInterval,maxAllowedDrift)),check=(_ref3=_asyncToGenerator(_regeneratorRuntime().mark((function _callee6(){var diff,diffAbs,min,max,adjustment;return _regeneratorRuntime().wrap((function(_context6){for(;;)switch(_context6.prev=_context6.next){case 0:if(_context6.t0=0===timingObject.query().velocity,_context6.t0){_context6.next=6;break}return _context6.next=4,player.getPaused();case 4:_context6.t1=_context6.sent,_context6.t0=!0===_context6.t1;case 6:if(!_context6.t0){_context6.next=8;break}return _context6.abrupt("return");case 8:return _context6.t2=timingObject.query().position,_context6.next=11,player.getCurrentTime();case 11:if(_context6.t3=_context6.sent,diff=_context6.t2-_context6.t3,diffAbs=Math.abs(diff),_this3.log("Drift: ".concat(diff)),!(diffAbs>maxAllowedDrift)){_context6.next=22;break}return _context6.next=18,_this3.adjustSpeed(player,0);case 18:player.setCurrentTime(timingObject.query().position),_this3.log("Resync by currentTime"),_context6.next=29;break;case 22:if(!(diffAbs>allowedDrift)){_context6.next=29;break}return adjustment=(min=diffAbs/maxTimeToCatchUp)<(max=maxRateAdjustment)?(max-min)/2:max,_context6.next=28,_this3.adjustSpeed(player,adjustment*Math.sign(diff));case 28:_this3.log("Resync by playbackRate");case 29:case"end":return _context6.stop()}}),_callee6)}))),function(){return _ref3.apply(this,arguments)}),interval=setInterval((function(){return check()}),syncInterval);return{cancel:function(){return clearInterval(interval)}}}},{key:"log",value:function(msg){var _this$logger;null===(_this$logger=this.logger)||void 0===_this$logger||_this$logger.call(this,"TimingSrcConnector: ".concat(msg))}},{key:"waitForTOReadyState",value:function(timingObject,state){return new Promise((function(resolve){!function check(){timingObject.readyState===state?resolve():timingObject.addEventListener("readystatechange",check,{once:!0})}()}))}}]),TimingSrcConnector}(),playerMap=new WeakMap,readyMap=new WeakMap,screenfull={},Player=function(){function Player(element){var _this=this,options=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(_classCallCheck(this,Player),window.jQuery&&element instanceof jQuery&&(element.length>1&&window.console&&console.warn&&console.warn("A jQuery object with multiple elements was passed, using the first element."),element=element[0]),"undefined"!=typeof document&&"string"==typeof element&&(element=document.getElementById(element)),!isDomElement(element))throw new TypeError("You must pass either a valid element or a valid id.");if("IFRAME"!==element.nodeName){var iframe=element.querySelector("iframe");iframe&&(element=iframe)}if("IFRAME"===element.nodeName&&!isVimeoUrl(element.getAttribute("src")||""))throw new Error("The player element passed isn’t a Vimeo embed.");if(playerMap.has(element))return playerMap.get(element);this._window=element.ownerDocument.defaultView,this.element=element,this.origin="*";var readyPromise=new npo_src((function(resolve,reject){if(_this._onMessage=function(event){if(isVimeoUrl(event.origin)&&_this.element.contentWindow===event.source){"*"===_this.origin&&(_this.origin=event.origin);var data=parseMessageData(event.data);if(data&&"error"===data.event&&data.data&&"ready"===data.data.method){var error=new Error(data.data.message);return error.name=data.data.name,void reject(error)}var isReadyEvent=data&&"ready"===data.event,isPingResponse=data&&"ping"===data.method;if(isReadyEvent||isPingResponse)return _this.element.setAttribute("data-ready","true"),void resolve();processData(_this,data)}},_this._window.addEventListener("message",_this._onMessage),"IFRAME"!==_this.element.nodeName){var params=getOEmbedParameters(element,options);getOEmbedData(getVimeoUrl(params),params,element).then((function(data){var iframe=createEmbed(data,element);return _this.element=iframe,_this._originalElement=element,swapCallbacks(element,iframe),playerMap.set(_this.element,_this),data})).catch(reject)}}));if(readyMap.set(this,readyPromise),playerMap.set(this.element,this),"IFRAME"===this.element.nodeName&&postMessage(this,"ping"),screenfull.isEnabled){var exitFullscreen=function(){return screenfull.exit()};this.fullscreenchangeHandler=function(){screenfull.isFullscreen?storeCallback(_this,"event:exitFullscreen",exitFullscreen):removeCallback(_this,"event:exitFullscreen",exitFullscreen),_this.ready().then((function(){postMessage(_this,"fullscreenchange",screenfull.isFullscreen)}))},screenfull.on("fullscreenchange",this.fullscreenchangeHandler)}return this}var _setTimingSrc;return _createClass(Player,[{key:"callMethod",value:function(name){for(var _this2=this,_len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++)args[_key-1]=arguments[_key];if(null==name)throw new TypeError("You must pass a method name.");return new npo_src((function(resolve,reject){return _this2.ready().then((function(){storeCallback(_this2,name,{resolve:resolve,reject:reject}),0===args.length?args={}:1===args.length&&(args=args[0]),postMessage(_this2,name,args)})).catch(reject)}))}},{key:"get",value:function(name){var _this3=this;return new npo_src((function(resolve,reject){return name=getMethodName(name,"get"),_this3.ready().then((function(){storeCallback(_this3,name,{resolve:resolve,reject:reject}),postMessage(_this3,name)})).catch(reject)}))}},{key:"set",value:function(name,value){var _this4=this;return new npo_src((function(resolve,reject){if(name=getMethodName(name,"set"),null==value)throw new TypeError("There must be a value to set.");return _this4.ready().then((function(){storeCallback(_this4,name,{resolve:resolve,reject:reject}),postMessage(_this4,name,value)})).catch(reject)}))}},{key:"on",value:function(eventName,callback){if(!eventName)throw new TypeError("You must pass an event name.");if(!callback)throw new TypeError("You must pass a callback function.");if("function"!=typeof callback)throw new TypeError("The callback must be a function.");0===getCallbacks(this,"event:".concat(eventName)).length&&this.callMethod("addEventListener",eventName).catch((function(){})),storeCallback(this,"event:".concat(eventName),callback)}},{key:"off",value:function(eventName,callback){if(!eventName)throw new TypeError("You must pass an event name.");if(callback&&"function"!=typeof callback)throw new TypeError("The callback must be a function.");removeCallback(this,"event:".concat(eventName),callback)&&this.callMethod("removeEventListener",eventName).catch((function(e){}))}},{key:"loadVideo",value:function(options){return this.callMethod("loadVideo",options)}},{key:"ready",value:function(){var readyPromise=readyMap.get(this)||new npo_src((function(resolve,reject){reject(new Error("Unknown player. Probably unloaded."))}));return npo_src.resolve(readyPromise)}},{key:"addCuePoint",value:function(time){var data=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.callMethod("addCuePoint",{time:time,data:data})}},{key:"removeCuePoint",value:function(id){return this.callMethod("removeCuePoint",id)}},{key:"enableTextTrack",value:function(language,kind){if(!language)throw new TypeError("You must pass a language.");return this.callMethod("enableTextTrack",{language:language,kind:kind})}},{key:"disableTextTrack",value:function(){return this.callMethod("disableTextTrack")}},{key:"pause",value:function(){return this.callMethod("pause")}},{key:"play",value:function(){return this.callMethod("play")}},{key:"requestFullscreen",value:function(){return screenfull.isEnabled?screenfull.request(this.element):this.callMethod("requestFullscreen")}},{key:"exitFullscreen",value:function(){return screenfull.isEnabled?screenfull.exit():this.callMethod("exitFullscreen")}},{key:"getFullscreen",value:function(){return screenfull.isEnabled?npo_src.resolve(screenfull.isFullscreen):this.get("fullscreen")}},{key:"requestPictureInPicture",value:function(){return this.callMethod("requestPictureInPicture")}},{key:"exitPictureInPicture",value:function(){return this.callMethod("exitPictureInPicture")}},{key:"getPictureInPicture",value:function(){return this.get("pictureInPicture")}},{key:"remotePlaybackPrompt",value:function(){return this.callMethod("remotePlaybackPrompt")}},{key:"unload",value:function(){return this.callMethod("unload")}},{key:"destroy",value:function(){var _this5=this;return new npo_src((function(resolve){if(readyMap.delete(_this5),playerMap.delete(_this5.element),_this5._originalElement&&(playerMap.delete(_this5._originalElement),_this5._originalElement.removeAttribute("data-vimeo-initialized")),_this5.element&&"IFRAME"===_this5.element.nodeName&&_this5.element.parentNode&&(_this5.element.parentNode.parentNode&&_this5._originalElement&&_this5._originalElement!==_this5.element.parentNode?_this5.element.parentNode.parentNode.removeChild(_this5.element.parentNode):_this5.element.parentNode.removeChild(_this5.element)),_this5.element&&"DIV"===_this5.element.nodeName&&_this5.element.parentNode){_this5.element.removeAttribute("data-vimeo-initialized");var iframe=_this5.element.querySelector("iframe");iframe&&iframe.parentNode&&(iframe.parentNode.parentNode&&_this5._originalElement&&_this5._originalElement!==iframe.parentNode?iframe.parentNode.parentNode.removeChild(iframe.parentNode):iframe.parentNode.removeChild(iframe))}_this5._window.removeEventListener("message",_this5._onMessage),screenfull.isEnabled&&screenfull.off("fullscreenchange",_this5.fullscreenchangeHandler),resolve()}))}},{key:"getAutopause",value:function(){return this.get("autopause")}},{key:"setAutopause",value:function(autopause){return this.set("autopause",autopause)}},{key:"getBuffered",value:function(){return this.get("buffered")}},{key:"getCameraProps",value:function(){return this.get("cameraProps")}},{key:"setCameraProps",value:function(camera){return this.set("cameraProps",camera)}},{key:"getChapters",value:function(){return this.get("chapters")}},{key:"getCurrentChapter",value:function(){return this.get("currentChapter")}},{key:"getColor",value:function(){return this.get("color")}},{key:"getColors",value:function(){return npo_src.all([this.get("colorOne"),this.get("colorTwo"),this.get("colorThree"),this.get("colorFour")])}},{key:"setColor",value:function(color){return this.set("color",color)}},{key:"setColors",value:function(colors){if(!Array.isArray(colors))return new npo_src((function(resolve,reject){return reject(new TypeError("Argument must be an array."))}));var nullPromise=new npo_src((function(resolve){return resolve(null)})),colorPromises=[colors[0]?this.set("colorOne",colors[0]):nullPromise,colors[1]?this.set("colorTwo",colors[1]):nullPromise,colors[2]?this.set("colorThree",colors[2]):nullPromise,colors[3]?this.set("colorFour",colors[3]):nullPromise];return npo_src.all(colorPromises)}},{key:"getCuePoints",value:function(){return this.get("cuePoints")}},{key:"getCurrentTime",value:function(){return this.get("currentTime")}},{key:"setCurrentTime",value:function(currentTime){return this.set("currentTime",currentTime)}},{key:"getDuration",value:function(){return this.get("duration")}},{key:"getEnded",value:function(){return this.get("ended")}},{key:"getLoop",value:function(){return this.get("loop")}},{key:"setLoop",value:function(loop){return this.set("loop",loop)}},{key:"setMuted",value:function(muted){return this.set("muted",muted)}},{key:"getMuted",value:function(){return this.get("muted")}},{key:"getPaused",value:function(){return this.get("paused")}},{key:"getPlaybackRate",value:function(){return this.get("playbackRate")}},{key:"setPlaybackRate",value:function(playbackRate){return this.set("playbackRate",playbackRate)}},{key:"getPlayed",value:function(){return this.get("played")}},{key:"getQualities",value:function(){return this.get("qualities")}},{key:"getQuality",value:function(){return this.get("quality")}},{key:"setQuality",value:function(quality){return this.set("quality",quality)}},{key:"getRemotePlaybackAvailability",value:function(){return this.get("remotePlaybackAvailability")}},{key:"getRemotePlaybackState",value:function(){return this.get("remotePlaybackState")}},{key:"getSeekable",value:function(){return this.get("seekable")}},{key:"getSeeking",value:function(){return this.get("seeking")}},{key:"getTextTracks",value:function(){return this.get("textTracks")}},{key:"getVideoEmbedCode",value:function(){return this.get("videoEmbedCode")}},{key:"getVideoId",value:function(){return this.get("videoId")}},{key:"getVideoTitle",value:function(){return this.get("videoTitle")}},{key:"getVideoWidth",value:function(){return this.get("videoWidth")}},{key:"getVideoHeight",value:function(){return this.get("videoHeight")}},{key:"getVideoUrl",value:function(){return this.get("videoUrl")}},{key:"getVolume",value:function(){return this.get("volume")}},{key:"setVolume",value:function(volume){return this.set("volume",volume)}},{key:"setTimingSrc",value:(_setTimingSrc=_asyncToGenerator(_regeneratorRuntime().mark((function _callee(timingObject,options){var connector,_this6=this;return _regeneratorRuntime().wrap((function(_context){for(;;)switch(_context.prev=_context.next){case 0:if(timingObject){_context.next=2;break}throw new TypeError("A Timing Object must be provided.");case 2:return _context.next=4,this.ready();case 4:return connector=new TimingSrcConnector(this,timingObject,options),postMessage(this,"notifyTimingObjectConnect"),connector.addEventListener("disconnect",(function(){return postMessage(_this6,"notifyTimingObjectDisconnect")})),_context.abrupt("return",connector);case 8:case"end":return _context.stop()}}),_callee,this)}))),function(_x,_x2){return _setTimingSrc.apply(this,arguments)})}],[{key:"isVimeoUrl",value:function(url){return isVimeoUrl(url)}}]),Player}();isServerRuntime||(screenfull=function(){var fn=function(){for(var val,fnMap=[["requestFullscreen","exitFullscreen","fullscreenElement","fullscreenEnabled","fullscreenchange","fullscreenerror"],["webkitRequestFullscreen","webkitExitFullscreen","webkitFullscreenElement","webkitFullscreenEnabled","webkitfullscreenchange","webkitfullscreenerror"],["webkitRequestFullScreen","webkitCancelFullScreen","webkitCurrentFullScreenElement","webkitCancelFullScreen","webkitfullscreenchange","webkitfullscreenerror"],["mozRequestFullScreen","mozCancelFullScreen","mozFullScreenElement","mozFullScreenEnabled","mozfullscreenchange","mozfullscreenerror"],["msRequestFullscreen","msExitFullscreen","msFullscreenElement","msFullscreenEnabled","MSFullscreenChange","MSFullscreenError"]],i=0,l=fnMap.length,ret={};i0&&void 0!==arguments[0]?arguments[0]:document,elements=[].slice.call(parent.querySelectorAll("[data-vimeo-id], [data-vimeo-url]")),handleError=function(error){"console"in window&&console.error&&console.error("There was an error creating an embed: ".concat(error))};elements.forEach((function(element){try{if(null!==element.getAttribute("data-vimeo-defer"))return;var params=getOEmbedParameters(element);getOEmbedData(getVimeoUrl(params),params,element).then((function(data){return createEmbed(data,element)})).catch(handleError)}catch(error){handleError(error)}}))}(),function(){var parent=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoPlayerResizeEmbeds_){window.VimeoPlayerResizeEmbeds_=!0;var onMessage=function(event){if(isVimeoUrl(event.origin)&&event.data&&"spacechange"===event.data.event){var senderIFrame=event.source?findIframeBySourceWindow(event.source,parent):null;senderIFrame&&(senderIFrame.parentElement.style.paddingBottom="".concat(event.data.data[0].bottom,"px"))}};window.addEventListener("message",onMessage)}}(),function(){var parent=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoSeoMetadataAppended){window.VimeoSeoMetadataAppended=!0;var onMessage=function(event){if(isVimeoUrl(event.origin)){var data=parseMessageData(event.data);if(data&&"ready"===data.event){var senderIFrame=event.source?findIframeBySourceWindow(event.source,parent):null;senderIFrame&&isVimeoEmbed(senderIFrame.src)&&new Player(senderIFrame).callMethod("appendVideoMetadata",window.location.href)}}};window.addEventListener("message",onMessage)}}(),function(){var parent=arguments.length>0&&void 0!==arguments[0]?arguments[0]:document;if(!window.VimeoCheckedUrlTimeParam){window.VimeoCheckedUrlTimeParam=!0;var handleError=function(error){"console"in window&&console.error&&console.error("There was an error getting video Id: ".concat(error))},onMessage=function(event){if(isVimeoUrl(event.origin)){var data=parseMessageData(event.data);if(data&&"ready"===data.event){var senderIFrame=event.source?findIframeBySourceWindow(event.source,parent):null;if(senderIFrame&&isVimeoEmbed(senderIFrame.src)){var player=new Player(senderIFrame);player.getVideoId().then((function(videoId){var matches=new RegExp("[?&]vimeo_t_".concat(videoId,"=([^&#]*)")).exec(window.location.href);if(matches&&matches[1]){var sec=decodeURI(matches[1]);player.setCurrentTime(sec)}})).catch(handleError)}}}};window.addEventListener("message",onMessage)}}(),window.VimeoDRMEmbedsUpdated||(window.VimeoDRMEmbedsUpdated=!0,window.addEventListener("message",(function(event){if(isVimeoUrl(event.origin)){var data=parseMessageData(event.data);if(data&&"drminitfailed"===data.event){var senderIFrame=event.source?findIframeBySourceWindow(event.source):null;if(senderIFrame){var currentAllow=senderIFrame.getAttribute("allow")||"";if(!currentAllow.includes("encrypted-media")){senderIFrame.setAttribute("allow","".concat(currentAllow,"; encrypted-media"));var currentUrl=new URL(senderIFrame.getAttribute("src"));return currentUrl.searchParams.set("forcereload","drm"),void senderIFrame.setAttribute("src",currentUrl.toString())}}}}}))));export{Player as default}; //# sourceMappingURL=player.min.js.map \ No newline at end of file diff --git a/amd/build/player.min.js.map b/amd/build/player.min.js.map index e855de02..78468269 100644 --- a/amd/build/player.min.js.map +++ b/amd/build/player.min.js.map @@ -1 +1 @@ -{"version":3,"file":"player.min.js","sources":["../src/player.js"],"sourcesContent":["/*! @vimeo/player v2.26.0 | (c) 2025 Vimeo | MIT License | https://github.com/vimeo/player.js */\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, (global.Vimeo = global.Vimeo || {}, global.Vimeo.Player = factory()));\n}(this, (function () { 'use strict';\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n return keys;\n }\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n return target;\n }\n function _regeneratorRuntime() {\n _regeneratorRuntime = function () {\n return exports;\n };\n var exports = {},\n Op = Object.prototype,\n hasOwn = Op.hasOwnProperty,\n defineProperty = Object.defineProperty || function (obj, key, desc) {\n obj[key] = desc.value;\n },\n $Symbol = \"function\" == typeof Symbol ? Symbol : {},\n iteratorSymbol = $Symbol.iterator || \"@@iterator\",\n asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\",\n toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n function define(obj, key, value) {\n return Object.defineProperty(obj, key, {\n value: value,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }), obj[key];\n }\n try {\n define({}, \"\");\n } catch (err) {\n define = function (obj, key, value) {\n return obj[key] = value;\n };\n }\n function wrap(innerFn, outerFn, self, tryLocsList) {\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,\n generator = Object.create(protoGenerator.prototype),\n context = new Context(tryLocsList || []);\n return defineProperty(generator, \"_invoke\", {\n value: makeInvokeMethod(innerFn, self, context)\n }), generator;\n }\n function tryCatch(fn, obj, arg) {\n try {\n return {\n type: \"normal\",\n arg: fn.call(obj, arg)\n };\n } catch (err) {\n return {\n type: \"throw\",\n arg: err\n };\n }\n }\n exports.wrap = wrap;\n var ContinueSentinel = {};\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n var IteratorPrototype = {};\n define(IteratorPrototype, iteratorSymbol, function () {\n return this;\n });\n var getProto = Object.getPrototypeOf,\n NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);\n var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function (method) {\n define(prototype, method, function (arg) {\n return this._invoke(method, arg);\n });\n });\n }\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (\"throw\" !== record.type) {\n var result = record.arg,\n value = result.value;\n return value && \"object\" == typeof value && hasOwn.call(value, \"__await\") ? PromiseImpl.resolve(value.__await).then(function (value) {\n invoke(\"next\", value, resolve, reject);\n }, function (err) {\n invoke(\"throw\", err, resolve, reject);\n }) : PromiseImpl.resolve(value).then(function (unwrapped) {\n result.value = unwrapped, resolve(result);\n }, function (error) {\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n reject(record.arg);\n }\n var previousPromise;\n defineProperty(this, \"_invoke\", {\n value: function (method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function (resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();\n }\n });\n }\n function makeInvokeMethod(innerFn, self, context) {\n var state = \"suspendedStart\";\n return function (method, arg) {\n if (\"executing\" === state) throw new Error(\"Generator is already running\");\n if (\"completed\" === state) {\n if (\"throw\" === method) throw arg;\n return doneResult();\n }\n for (context.method = method, context.arg = arg;;) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n if (\"next\" === context.method) context.sent = context._sent = context.arg;else if (\"throw\" === context.method) {\n if (\"suspendedStart\" === state) throw state = \"completed\", context.arg;\n context.dispatchException(context.arg);\n } else \"return\" === context.method && context.abrupt(\"return\", context.arg);\n state = \"executing\";\n var record = tryCatch(innerFn, self, context);\n if (\"normal\" === record.type) {\n if (state = context.done ? \"completed\" : \"suspendedYield\", record.arg === ContinueSentinel) continue;\n return {\n value: record.arg,\n done: context.done\n };\n }\n \"throw\" === record.type && (state = \"completed\", context.method = \"throw\", context.arg = record.arg);\n }\n };\n }\n function maybeInvokeDelegate(delegate, context) {\n var methodName = context.method,\n method = delegate.iterator[methodName];\n if (undefined === method) return context.delegate = null, \"throw\" === methodName && delegate.iterator.return && (context.method = \"return\", context.arg = undefined, maybeInvokeDelegate(delegate, context), \"throw\" === context.method) || \"return\" !== methodName && (context.method = \"throw\", context.arg = new TypeError(\"The iterator does not provide a '\" + methodName + \"' method\")), ContinueSentinel;\n var record = tryCatch(method, delegate.iterator, context.arg);\n if (\"throw\" === record.type) return context.method = \"throw\", context.arg = record.arg, context.delegate = null, ContinueSentinel;\n var info = record.arg;\n return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, \"return\" !== context.method && (context.method = \"next\", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = \"throw\", context.arg = new TypeError(\"iterator result is not an object\"), context.delegate = null, ContinueSentinel);\n }\n function pushTryEntry(locs) {\n var entry = {\n tryLoc: locs[0]\n };\n 1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);\n }\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\", delete record.arg, entry.completion = record;\n }\n function Context(tryLocsList) {\n this.tryEntries = [{\n tryLoc: \"root\"\n }], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);\n }\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) return iteratorMethod.call(iterable);\n if (\"function\" == typeof iterable.next) return iterable;\n if (!isNaN(iterable.length)) {\n var i = -1,\n next = function next() {\n for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;\n return next.value = undefined, next.done = !0, next;\n };\n return next.next = next;\n }\n }\n return {\n next: doneResult\n };\n }\n function doneResult() {\n return {\n value: undefined,\n done: !0\n };\n }\n return GeneratorFunction.prototype = GeneratorFunctionPrototype, defineProperty(Gp, \"constructor\", {\n value: GeneratorFunctionPrototype,\n configurable: !0\n }), defineProperty(GeneratorFunctionPrototype, \"constructor\", {\n value: GeneratorFunction,\n configurable: !0\n }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, \"GeneratorFunction\"), exports.isGeneratorFunction = function (genFun) {\n var ctor = \"function\" == typeof genFun && genFun.constructor;\n return !!ctor && (ctor === GeneratorFunction || \"GeneratorFunction\" === (ctor.displayName || ctor.name));\n }, exports.mark = function (genFun) {\n return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, \"GeneratorFunction\")), genFun.prototype = Object.create(Gp), genFun;\n }, exports.awrap = function (arg) {\n return {\n __await: arg\n };\n }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {\n return this;\n }), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n void 0 === PromiseImpl && (PromiseImpl = Promise);\n var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);\n return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {\n return result.done ? result.value : iter.next();\n });\n }, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, \"Generator\"), define(Gp, iteratorSymbol, function () {\n return this;\n }), define(Gp, \"toString\", function () {\n return \"[object Generator]\";\n }), exports.keys = function (val) {\n var object = Object(val),\n keys = [];\n for (var key in object) keys.push(key);\n return keys.reverse(), function next() {\n for (; keys.length;) {\n var key = keys.pop();\n if (key in object) return next.value = key, next.done = !1, next;\n }\n return next.done = !0, next;\n };\n }, exports.values = values, Context.prototype = {\n constructor: Context,\n reset: function (skipTempReset) {\n if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = \"next\", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) \"t\" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);\n },\n stop: function () {\n this.done = !0;\n var rootRecord = this.tryEntries[0].completion;\n if (\"throw\" === rootRecord.type) throw rootRecord.arg;\n return this.rval;\n },\n dispatchException: function (exception) {\n if (this.done) throw exception;\n var context = this;\n function handle(loc, caught) {\n return record.type = \"throw\", record.arg = exception, context.next = loc, caught && (context.method = \"next\", context.arg = undefined), !!caught;\n }\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i],\n record = entry.completion;\n if (\"root\" === entry.tryLoc) return handle(\"end\");\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\"),\n hasFinally = hasOwn.call(entry, \"finallyLoc\");\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);\n } else {\n if (!hasFinally) throw new Error(\"try statement without catch or finally\");\n if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);\n }\n }\n }\n },\n abrupt: function (type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev && hasOwn.call(entry, \"finallyLoc\") && this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n finallyEntry && (\"break\" === type || \"continue\" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);\n var record = finallyEntry ? finallyEntry.completion : {};\n return record.type = type, record.arg = arg, finallyEntry ? (this.method = \"next\", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);\n },\n complete: function (record, afterLoc) {\n if (\"throw\" === record.type) throw record.arg;\n return \"break\" === record.type || \"continue\" === record.type ? this.next = record.arg : \"return\" === record.type ? (this.rval = this.arg = record.arg, this.method = \"return\", this.next = \"end\") : \"normal\" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;\n },\n finish: function (finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;\n }\n },\n catch: function (tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (\"throw\" === record.type) {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n throw new Error(\"illegal catch attempt\");\n },\n delegateYield: function (iterable, resultName, nextLoc) {\n return this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n }, \"next\" === this.method && (this.arg = undefined), ContinueSentinel;\n }\n }, exports;\n }\n function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n }\n function _asyncToGenerator(fn) {\n return function () {\n var self = this,\n args = arguments;\n return new Promise(function (resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n }\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);\n }\n }\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n Object.defineProperty(Constructor, \"prototype\", {\n writable: false\n });\n return Constructor;\n }\n function _defineProperty(obj, key, value) {\n key = _toPropertyKey(key);\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n }\n function _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n writable: true,\n configurable: true\n }\n });\n Object.defineProperty(subClass, \"prototype\", {\n writable: false\n });\n if (superClass) _setPrototypeOf(subClass, superClass);\n }\n function _getPrototypeOf(o) {\n _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {\n return o.__proto__ || Object.getPrototypeOf(o);\n };\n return _getPrototypeOf(o);\n }\n function _setPrototypeOf(o, p) {\n _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {\n o.__proto__ = p;\n return o;\n };\n return _setPrototypeOf(o, p);\n }\n function _isNativeReflectConstruct() {\n if (typeof Reflect === \"undefined\" || !Reflect.construct) return false;\n if (Reflect.construct.sham) return false;\n if (typeof Proxy === \"function\") return true;\n try {\n Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));\n return true;\n } catch (e) {\n return false;\n }\n }\n function _construct(Parent, args, Class) {\n if (_isNativeReflectConstruct()) {\n _construct = Reflect.construct.bind();\n } else {\n _construct = function _construct(Parent, args, Class) {\n var a = [null];\n a.push.apply(a, args);\n var Constructor = Function.bind.apply(Parent, a);\n var instance = new Constructor();\n if (Class) _setPrototypeOf(instance, Class.prototype);\n return instance;\n };\n }\n return _construct.apply(null, arguments);\n }\n function _isNativeFunction(fn) {\n return Function.toString.call(fn).indexOf(\"[native code]\") !== -1;\n }\n function _wrapNativeSuper(Class) {\n var _cache = typeof Map === \"function\" ? new Map() : undefined;\n _wrapNativeSuper = function _wrapNativeSuper(Class) {\n if (Class === null || !_isNativeFunction(Class)) return Class;\n if (typeof Class !== \"function\") {\n throw new TypeError(\"Super expression must either be null or a function\");\n }\n if (typeof _cache !== \"undefined\") {\n if (_cache.has(Class)) return _cache.get(Class);\n _cache.set(Class, Wrapper);\n }\n function Wrapper() {\n return _construct(Class, arguments, _getPrototypeOf(this).constructor);\n }\n Wrapper.prototype = Object.create(Class.prototype, {\n constructor: {\n value: Wrapper,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n return _setPrototypeOf(Wrapper, Class);\n };\n return _wrapNativeSuper(Class);\n }\n function _assertThisInitialized(self) {\n if (self === void 0) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n return self;\n }\n function _possibleConstructorReturn(self, call) {\n if (call && (typeof call === \"object\" || typeof call === \"function\")) {\n return call;\n } else if (call !== void 0) {\n throw new TypeError(\"Derived constructors may only return object or undefined\");\n }\n return _assertThisInitialized(self);\n }\n function _createSuper(Derived) {\n var hasNativeReflectConstruct = _isNativeReflectConstruct();\n return function _createSuperInternal() {\n var Super = _getPrototypeOf(Derived),\n result;\n if (hasNativeReflectConstruct) {\n var NewTarget = _getPrototypeOf(this).constructor;\n result = Reflect.construct(Super, arguments, NewTarget);\n } else {\n result = Super.apply(this, arguments);\n }\n return _possibleConstructorReturn(this, result);\n };\n }\n function _toPrimitive(input, hint) {\n if (typeof input !== \"object\" || input === null) return input;\n var prim = input[Symbol.toPrimitive];\n if (prim !== undefined) {\n var res = prim.call(input, hint || \"default\");\n if (typeof res !== \"object\") return res;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (hint === \"string\" ? String : Number)(input);\n }\n function _toPropertyKey(arg) {\n var key = _toPrimitive(arg, \"string\");\n return typeof key === \"symbol\" ? key : String(key);\n }\n\n /**\n * @module lib/functions\n */\n\n /**\n * Check to see this is a node environment.\n * @type {Boolean}\n */\n /* global global */\n var isNode = typeof global !== 'undefined' && {}.toString.call(global) === '[object global]';\n\n /**\n * Get the name of the method for a given getter or setter.\n *\n * @param {string} prop The name of the property.\n * @param {string} type Either “get” or “set”.\n * @return {string}\n */\n function getMethodName(prop, type) {\n if (prop.indexOf(type.toLowerCase()) === 0) {\n return prop;\n }\n return \"\".concat(type.toLowerCase()).concat(prop.substr(0, 1).toUpperCase()).concat(prop.substr(1));\n }\n\n /**\n * Check to see if the object is a DOM Element.\n *\n * @param {*} element The object to check.\n * @return {boolean}\n */\n function isDomElement(element) {\n return Boolean(element && element.nodeType === 1 && 'nodeName' in element && element.ownerDocument && element.ownerDocument.defaultView);\n }\n\n /**\n * Check to see whether the value is a number.\n *\n * @see http://dl.dropboxusercontent.com/u/35146/js/tests/isNumber.html\n * @param {*} value The value to check.\n * @param {boolean} integer Check if the value is an integer.\n * @return {boolean}\n */\n function isInteger(value) {\n // eslint-disable-next-line eqeqeq\n return !isNaN(parseFloat(value)) && isFinite(value) && Math.floor(value) == value;\n }\n\n /**\n * Check to see if the URL is a Vimeo url.\n *\n * @param {string} url The url string.\n * @return {boolean}\n */\n function isVimeoUrl(url) {\n return /^(https?:)?\\/\\/((((player|www)\\.)?vimeo\\.com)|((player\\.)?[a-zA-Z0-9-]+\\.(videoji\\.(hk|cn)|vimeo\\.work)))(?=$|\\/)/.test(url);\n }\n\n /**\n * Check to see if the URL is for a Vimeo embed.\n *\n * @param {string} url The url string.\n * @return {boolean}\n */\n function isVimeoEmbed(url) {\n var expr = /^https:\\/\\/player\\.((vimeo\\.com)|([a-zA-Z0-9-]+\\.(videoji\\.(hk|cn)|vimeo\\.work)))\\/video\\/\\d+/;\n return expr.test(url);\n }\n function getOembedDomain(url) {\n var match = (url || '').match(/^(?:https?:)?(?:\\/\\/)?([^/?]+)/);\n var domain = (match && match[1] || '').replace('player.', '');\n var customDomains = ['.videoji.hk', '.vimeo.work', '.videoji.cn'];\n for (var _i = 0, _customDomains = customDomains; _i < _customDomains.length; _i++) {\n var customDomain = _customDomains[_i];\n if (domain.endsWith(customDomain)) {\n return domain;\n }\n }\n return 'vimeo.com';\n }\n\n /**\n * Get the Vimeo URL from an element.\n * The element must have either a data-vimeo-id or data-vimeo-url attribute.\n *\n * @param {object} oEmbedParameters The oEmbed parameters.\n * @return {string}\n */\n function getVimeoUrl() {\n var oEmbedParameters = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var id = oEmbedParameters.id;\n var url = oEmbedParameters.url;\n var idOrUrl = id || url;\n if (!idOrUrl) {\n throw new Error('An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute.');\n }\n if (isInteger(idOrUrl)) {\n return \"https://vimeo.com/\".concat(idOrUrl);\n }\n if (isVimeoUrl(idOrUrl)) {\n return idOrUrl.replace('http:', 'https:');\n }\n if (id) {\n throw new TypeError(\"\\u201C\".concat(id, \"\\u201D is not a valid video id.\"));\n }\n throw new TypeError(\"\\u201C\".concat(idOrUrl, \"\\u201D is not a vimeo.com url.\"));\n }\n\n /* eslint-disable max-params */\n /**\n * A utility method for attaching and detaching event handlers\n *\n * @param {EventTarget} target\n * @param {string | string[]} eventName\n * @param {function} callback\n * @param {'addEventListener' | 'on'} onName\n * @param {'removeEventListener' | 'off'} offName\n * @return {{cancel: (function(): void)}}\n */\n var subscribe = function subscribe(target, eventName, callback) {\n var onName = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'addEventListener';\n var offName = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'removeEventListener';\n var eventNames = typeof eventName === 'string' ? [eventName] : eventName;\n eventNames.forEach(function (evName) {\n target[onName](evName, callback);\n });\n return {\n cancel: function cancel() {\n return eventNames.forEach(function (evName) {\n return target[offName](evName, callback);\n });\n }\n };\n };\n\n var arrayIndexOfSupport = typeof Array.prototype.indexOf !== 'undefined';\n var postMessageSupport = typeof window !== 'undefined' && typeof window.postMessage !== 'undefined';\n if (!isNode && (!arrayIndexOfSupport || !postMessageSupport)) {\n throw new Error('Sorry, the Vimeo Player API is not available in this browser.');\n }\n\n var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\n\n function createCommonjsModule(fn, module) {\n \treturn module = { exports: {} }, fn(module, module.exports), module.exports;\n }\n\n /*!\n * weakmap-polyfill v2.0.4 - ECMAScript6 WeakMap polyfill\n * https://github.com/polygonplanet/weakmap-polyfill\n * Copyright (c) 2015-2021 polygonplanet \n * @license MIT\n */\n\n (function (self) {\n\n if (self.WeakMap) {\n return;\n }\n var hasOwnProperty = Object.prototype.hasOwnProperty;\n var hasDefine = Object.defineProperty && function () {\n try {\n // Avoid IE8's broken Object.defineProperty\n return Object.defineProperty({}, 'x', {\n value: 1\n }).x === 1;\n } catch (e) {}\n }();\n var defineProperty = function (object, name, value) {\n if (hasDefine) {\n Object.defineProperty(object, name, {\n configurable: true,\n writable: true,\n value: value\n });\n } else {\n object[name] = value;\n }\n };\n self.WeakMap = function () {\n // ECMA-262 23.3 WeakMap Objects\n function WeakMap() {\n if (this === void 0) {\n throw new TypeError(\"Constructor WeakMap requires 'new'\");\n }\n defineProperty(this, '_id', genId('_WeakMap'));\n\n // ECMA-262 23.3.1.1 WeakMap([iterable])\n if (arguments.length > 0) {\n // Currently, WeakMap `iterable` argument is not supported\n throw new TypeError('WeakMap iterable is not supported');\n }\n }\n\n // ECMA-262 23.3.3.2 WeakMap.prototype.delete(key)\n defineProperty(WeakMap.prototype, 'delete', function (key) {\n checkInstance(this, 'delete');\n if (!isObject(key)) {\n return false;\n }\n var entry = key[this._id];\n if (entry && entry[0] === key) {\n delete key[this._id];\n return true;\n }\n return false;\n });\n\n // ECMA-262 23.3.3.3 WeakMap.prototype.get(key)\n defineProperty(WeakMap.prototype, 'get', function (key) {\n checkInstance(this, 'get');\n if (!isObject(key)) {\n return void 0;\n }\n var entry = key[this._id];\n if (entry && entry[0] === key) {\n return entry[1];\n }\n return void 0;\n });\n\n // ECMA-262 23.3.3.4 WeakMap.prototype.has(key)\n defineProperty(WeakMap.prototype, 'has', function (key) {\n checkInstance(this, 'has');\n if (!isObject(key)) {\n return false;\n }\n var entry = key[this._id];\n if (entry && entry[0] === key) {\n return true;\n }\n return false;\n });\n\n // ECMA-262 23.3.3.5 WeakMap.prototype.set(key, value)\n defineProperty(WeakMap.prototype, 'set', function (key, value) {\n checkInstance(this, 'set');\n if (!isObject(key)) {\n throw new TypeError('Invalid value used as weak map key');\n }\n var entry = key[this._id];\n if (entry && entry[0] === key) {\n entry[1] = value;\n return this;\n }\n defineProperty(key, this._id, [key, value]);\n return this;\n });\n function checkInstance(x, methodName) {\n if (!isObject(x) || !hasOwnProperty.call(x, '_id')) {\n throw new TypeError(methodName + ' method called on incompatible receiver ' + typeof x);\n }\n }\n function genId(prefix) {\n return prefix + '_' + rand() + '.' + rand();\n }\n function rand() {\n return Math.random().toString().substring(2);\n }\n defineProperty(WeakMap, '_polyfill', true);\n return WeakMap;\n }();\n function isObject(x) {\n return Object(x) === x;\n }\n })(typeof globalThis !== 'undefined' ? globalThis : typeof self !== 'undefined' ? self : typeof window !== 'undefined' ? window : typeof commonjsGlobal !== 'undefined' ? commonjsGlobal : commonjsGlobal);\n\n var npo_src = createCommonjsModule(function (module) {\n /*! Native Promise Only\n v0.8.1 (c) Kyle Simpson\n MIT License: http://getify.mit-license.org\n */\n\n (function UMD(name, context, definition) {\n // special form of UMD for polyfilling across evironments\n context[name] = context[name] || definition();\n if ( module.exports) {\n module.exports = context[name];\n }\n })(\"Promise\", typeof commonjsGlobal != \"undefined\" ? commonjsGlobal : commonjsGlobal, function DEF() {\n\n var builtInProp,\n cycle,\n scheduling_queue,\n ToString = Object.prototype.toString,\n timer = typeof setImmediate != \"undefined\" ? function timer(fn) {\n return setImmediate(fn);\n } : setTimeout;\n\n // dammit, IE8.\n try {\n Object.defineProperty({}, \"x\", {});\n builtInProp = function builtInProp(obj, name, val, config) {\n return Object.defineProperty(obj, name, {\n value: val,\n writable: true,\n configurable: config !== false\n });\n };\n } catch (err) {\n builtInProp = function builtInProp(obj, name, val) {\n obj[name] = val;\n return obj;\n };\n }\n\n // Note: using a queue instead of array for efficiency\n scheduling_queue = function Queue() {\n var first, last, item;\n function Item(fn, self) {\n this.fn = fn;\n this.self = self;\n this.next = void 0;\n }\n return {\n add: function add(fn, self) {\n item = new Item(fn, self);\n if (last) {\n last.next = item;\n } else {\n first = item;\n }\n last = item;\n item = void 0;\n },\n drain: function drain() {\n var f = first;\n first = last = cycle = void 0;\n while (f) {\n f.fn.call(f.self);\n f = f.next;\n }\n }\n };\n }();\n function schedule(fn, self) {\n scheduling_queue.add(fn, self);\n if (!cycle) {\n cycle = timer(scheduling_queue.drain);\n }\n }\n\n // promise duck typing\n function isThenable(o) {\n var _then,\n o_type = typeof o;\n if (o != null && (o_type == \"object\" || o_type == \"function\")) {\n _then = o.then;\n }\n return typeof _then == \"function\" ? _then : false;\n }\n function notify() {\n for (var i = 0; i < this.chain.length; i++) {\n notifyIsolated(this, this.state === 1 ? this.chain[i].success : this.chain[i].failure, this.chain[i]);\n }\n this.chain.length = 0;\n }\n\n // NOTE: This is a separate function to isolate\n // the `try..catch` so that other code can be\n // optimized better\n function notifyIsolated(self, cb, chain) {\n var ret, _then;\n try {\n if (cb === false) {\n chain.reject(self.msg);\n } else {\n if (cb === true) {\n ret = self.msg;\n } else {\n ret = cb.call(void 0, self.msg);\n }\n if (ret === chain.promise) {\n chain.reject(TypeError(\"Promise-chain cycle\"));\n } else if (_then = isThenable(ret)) {\n _then.call(ret, chain.resolve, chain.reject);\n } else {\n chain.resolve(ret);\n }\n }\n } catch (err) {\n chain.reject(err);\n }\n }\n function resolve(msg) {\n var _then,\n self = this;\n\n // already triggered?\n if (self.triggered) {\n return;\n }\n self.triggered = true;\n\n // unwrap\n if (self.def) {\n self = self.def;\n }\n try {\n if (_then = isThenable(msg)) {\n schedule(function () {\n var def_wrapper = new MakeDefWrapper(self);\n try {\n _then.call(msg, function $resolve$() {\n resolve.apply(def_wrapper, arguments);\n }, function $reject$() {\n reject.apply(def_wrapper, arguments);\n });\n } catch (err) {\n reject.call(def_wrapper, err);\n }\n });\n } else {\n self.msg = msg;\n self.state = 1;\n if (self.chain.length > 0) {\n schedule(notify, self);\n }\n }\n } catch (err) {\n reject.call(new MakeDefWrapper(self), err);\n }\n }\n function reject(msg) {\n var self = this;\n\n // already triggered?\n if (self.triggered) {\n return;\n }\n self.triggered = true;\n\n // unwrap\n if (self.def) {\n self = self.def;\n }\n self.msg = msg;\n self.state = 2;\n if (self.chain.length > 0) {\n schedule(notify, self);\n }\n }\n function iteratePromises(Constructor, arr, resolver, rejecter) {\n for (var idx = 0; idx < arr.length; idx++) {\n (function IIFE(idx) {\n Constructor.resolve(arr[idx]).then(function $resolver$(msg) {\n resolver(idx, msg);\n }, rejecter);\n })(idx);\n }\n }\n function MakeDefWrapper(self) {\n this.def = self;\n this.triggered = false;\n }\n function MakeDef(self) {\n this.promise = self;\n this.state = 0;\n this.triggered = false;\n this.chain = [];\n this.msg = void 0;\n }\n function Promise(executor) {\n if (typeof executor != \"function\") {\n throw TypeError(\"Not a function\");\n }\n if (this.__NPO__ !== 0) {\n throw TypeError(\"Not a promise\");\n }\n\n // instance shadowing the inherited \"brand\"\n // to signal an already \"initialized\" promise\n this.__NPO__ = 1;\n var def = new MakeDef(this);\n this[\"then\"] = function then(success, failure) {\n var o = {\n success: typeof success == \"function\" ? success : true,\n failure: typeof failure == \"function\" ? failure : false\n };\n // Note: `then(..)` itself can be borrowed to be used against\n // a different promise constructor for making the chained promise,\n // by substituting a different `this` binding.\n o.promise = new this.constructor(function extractChain(resolve, reject) {\n if (typeof resolve != \"function\" || typeof reject != \"function\") {\n throw TypeError(\"Not a function\");\n }\n o.resolve = resolve;\n o.reject = reject;\n });\n def.chain.push(o);\n if (def.state !== 0) {\n schedule(notify, def);\n }\n return o.promise;\n };\n this[\"catch\"] = function $catch$(failure) {\n return this.then(void 0, failure);\n };\n try {\n executor.call(void 0, function publicResolve(msg) {\n resolve.call(def, msg);\n }, function publicReject(msg) {\n reject.call(def, msg);\n });\n } catch (err) {\n reject.call(def, err);\n }\n }\n var PromisePrototype = builtInProp({}, \"constructor\", Promise, /*configurable=*/false);\n\n // Note: Android 4 cannot use `Object.defineProperty(..)` here\n Promise.prototype = PromisePrototype;\n\n // built-in \"brand\" to signal an \"uninitialized\" promise\n builtInProp(PromisePrototype, \"__NPO__\", 0, /*configurable=*/false);\n builtInProp(Promise, \"resolve\", function Promise$resolve(msg) {\n var Constructor = this;\n\n // spec mandated checks\n // note: best \"isPromise\" check that's practical for now\n if (msg && typeof msg == \"object\" && msg.__NPO__ === 1) {\n return msg;\n }\n return new Constructor(function executor(resolve, reject) {\n if (typeof resolve != \"function\" || typeof reject != \"function\") {\n throw TypeError(\"Not a function\");\n }\n resolve(msg);\n });\n });\n builtInProp(Promise, \"reject\", function Promise$reject(msg) {\n return new this(function executor(resolve, reject) {\n if (typeof resolve != \"function\" || typeof reject != \"function\") {\n throw TypeError(\"Not a function\");\n }\n reject(msg);\n });\n });\n builtInProp(Promise, \"all\", function Promise$all(arr) {\n var Constructor = this;\n\n // spec mandated checks\n if (ToString.call(arr) != \"[object Array]\") {\n return Constructor.reject(TypeError(\"Not an array\"));\n }\n if (arr.length === 0) {\n return Constructor.resolve([]);\n }\n return new Constructor(function executor(resolve, reject) {\n if (typeof resolve != \"function\" || typeof reject != \"function\") {\n throw TypeError(\"Not a function\");\n }\n var len = arr.length,\n msgs = Array(len),\n count = 0;\n iteratePromises(Constructor, arr, function resolver(idx, msg) {\n msgs[idx] = msg;\n if (++count === len) {\n resolve(msgs);\n }\n }, reject);\n });\n });\n builtInProp(Promise, \"race\", function Promise$race(arr) {\n var Constructor = this;\n\n // spec mandated checks\n if (ToString.call(arr) != \"[object Array]\") {\n return Constructor.reject(TypeError(\"Not an array\"));\n }\n return new Constructor(function executor(resolve, reject) {\n if (typeof resolve != \"function\" || typeof reject != \"function\") {\n throw TypeError(\"Not a function\");\n }\n iteratePromises(Constructor, arr, function resolver(idx, msg) {\n resolve(msg);\n }, reject);\n });\n });\n return Promise;\n });\n });\n\n /**\n * @module lib/callbacks\n */\n\n var callbackMap = new WeakMap();\n\n /**\n * Store a callback for a method or event for a player.\n *\n * @param {Player} player The player object.\n * @param {string} name The method or event name.\n * @param {(function(this:Player, *): void|{resolve: function, reject: function})} callback\n * The callback to call or an object with resolve and reject functions for a promise.\n * @return {void}\n */\n function storeCallback(player, name, callback) {\n var playerCallbacks = callbackMap.get(player.element) || {};\n if (!(name in playerCallbacks)) {\n playerCallbacks[name] = [];\n }\n playerCallbacks[name].push(callback);\n callbackMap.set(player.element, playerCallbacks);\n }\n\n /**\n * Get the callbacks for a player and event or method.\n *\n * @param {Player} player The player object.\n * @param {string} name The method or event name\n * @return {function[]}\n */\n function getCallbacks(player, name) {\n var playerCallbacks = callbackMap.get(player.element) || {};\n return playerCallbacks[name] || [];\n }\n\n /**\n * Remove a stored callback for a method or event for a player.\n *\n * @param {Player} player The player object.\n * @param {string} name The method or event name\n * @param {function} [callback] The specific callback to remove.\n * @return {boolean} Was this the last callback?\n */\n function removeCallback(player, name, callback) {\n var playerCallbacks = callbackMap.get(player.element) || {};\n if (!playerCallbacks[name]) {\n return true;\n }\n\n // If no callback is passed, remove all callbacks for the event\n if (!callback) {\n playerCallbacks[name] = [];\n callbackMap.set(player.element, playerCallbacks);\n return true;\n }\n var index = playerCallbacks[name].indexOf(callback);\n if (index !== -1) {\n playerCallbacks[name].splice(index, 1);\n }\n callbackMap.set(player.element, playerCallbacks);\n return playerCallbacks[name] && playerCallbacks[name].length === 0;\n }\n\n /**\n * Return the first stored callback for a player and event or method.\n *\n * @param {Player} player The player object.\n * @param {string} name The method or event name.\n * @return {function} The callback, or false if there were none\n */\n function shiftCallbacks(player, name) {\n var playerCallbacks = getCallbacks(player, name);\n if (playerCallbacks.length < 1) {\n return false;\n }\n var callback = playerCallbacks.shift();\n removeCallback(player, name, callback);\n return callback;\n }\n\n /**\n * Move callbacks associated with an element to another element.\n *\n * @param {HTMLElement} oldElement The old element.\n * @param {HTMLElement} newElement The new element.\n * @return {void}\n */\n function swapCallbacks(oldElement, newElement) {\n var playerCallbacks = callbackMap.get(oldElement);\n callbackMap.set(newElement, playerCallbacks);\n callbackMap.delete(oldElement);\n }\n\n /**\n * @module lib/postmessage\n */\n\n /**\n * Parse a message received from postMessage.\n *\n * @param {*} data The data received from postMessage.\n * @return {object}\n */\n function parseMessageData(data) {\n if (typeof data === 'string') {\n try {\n data = JSON.parse(data);\n } catch (error) {\n // If the message cannot be parsed, throw the error as a warning\n console.warn(error);\n return {};\n }\n }\n return data;\n }\n\n /**\n * Post a message to the specified target.\n *\n * @param {Player} player The player object to use.\n * @param {string} method The API method to call.\n * @param {object} params The parameters to send to the player.\n * @return {void}\n */\n function postMessage(player, method, params) {\n if (!player.element.contentWindow || !player.element.contentWindow.postMessage) {\n return;\n }\n var message = {\n method: method\n };\n if (params !== undefined) {\n message.value = params;\n }\n\n // IE 8 and 9 do not support passing messages, so stringify them\n var ieVersion = parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\\d+).*$/, '$1'));\n if (ieVersion >= 8 && ieVersion < 10) {\n message = JSON.stringify(message);\n }\n player.element.contentWindow.postMessage(message, player.origin);\n }\n\n /**\n * Parse the data received from a message event.\n *\n * @param {Player} player The player that received the message.\n * @param {(Object|string)} data The message data. Strings will be parsed into JSON.\n * @return {void}\n */\n function processData(player, data) {\n data = parseMessageData(data);\n var callbacks = [];\n var param;\n if (data.event) {\n if (data.event === 'error') {\n var promises = getCallbacks(player, data.data.method);\n promises.forEach(function (promise) {\n var error = new Error(data.data.message);\n error.name = data.data.name;\n promise.reject(error);\n removeCallback(player, data.data.method, promise);\n });\n }\n callbacks = getCallbacks(player, \"event:\".concat(data.event));\n param = data.data;\n } else if (data.method) {\n var callback = shiftCallbacks(player, data.method);\n if (callback) {\n callbacks.push(callback);\n param = data.value;\n }\n }\n callbacks.forEach(function (callback) {\n try {\n if (typeof callback === 'function') {\n callback.call(player, param);\n return;\n }\n callback.resolve(param);\n } catch (e) {\n // empty\n }\n });\n }\n\n /**\n * @module lib/embed\n */\n var oEmbedParameters = ['airplay', 'audio_tracks', 'audiotrack', 'autopause', 'autoplay', 'background', 'byline', 'cc', 'chapter_id', 'chapters', 'chromecast', 'color', 'colors', 'controls', 'dnt', 'end_time', 'fullscreen', 'height', 'id', 'interactive_params', 'keyboard', 'loop', 'maxheight', 'maxwidth', 'muted', 'play_button_position', 'playsinline', 'portrait', 'progress_bar', 'quality_selector', 'responsive', 'skipping_forward', 'speed', 'start_time', 'texttrack', 'title', 'transcript', 'transparent', 'unmute_button', 'url', 'vimeo_logo', 'volume', 'watch_full_video', 'width'];\n\n /**\n * Get the 'data-vimeo'-prefixed attributes from an element as an object.\n *\n * @param {HTMLElement} element The element.\n * @param {Object} [defaults={}] The default values to use.\n * @return {Object}\n */\n function getOEmbedParameters(element) {\n var defaults = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return oEmbedParameters.reduce(function (params, param) {\n var value = element.getAttribute(\"data-vimeo-\".concat(param));\n if (value || value === '') {\n params[param] = value === '' ? 1 : value;\n }\n return params;\n }, defaults);\n }\n\n /**\n * Create an embed from oEmbed data inside an element.\n *\n * @param {object} data The oEmbed data.\n * @param {HTMLElement} element The element to put the iframe in.\n * @return {HTMLIFrameElement} The iframe embed.\n */\n function createEmbed(_ref, element) {\n var html = _ref.html;\n if (!element) {\n throw new TypeError('An element must be provided');\n }\n if (element.getAttribute('data-vimeo-initialized') !== null) {\n return element.querySelector('iframe');\n }\n var div = document.createElement('div');\n div.innerHTML = html;\n element.appendChild(div.firstChild);\n element.setAttribute('data-vimeo-initialized', 'true');\n return element.querySelector('iframe');\n }\n\n /**\n * Make an oEmbed call for the specified URL.\n *\n * @param {string} videoUrl The vimeo.com url for the video.\n * @param {Object} [params] Parameters to pass to oEmbed.\n * @param {HTMLElement} element The element.\n * @return {Promise}\n */\n function getOEmbedData(videoUrl) {\n var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var element = arguments.length > 2 ? arguments[2] : undefined;\n return new Promise(function (resolve, reject) {\n if (!isVimeoUrl(videoUrl)) {\n throw new TypeError(\"\\u201C\".concat(videoUrl, \"\\u201D is not a vimeo.com url.\"));\n }\n var domain = getOembedDomain(videoUrl);\n var url = \"https://\".concat(domain, \"/api/oembed.json?url=\").concat(encodeURIComponent(videoUrl));\n for (var param in params) {\n if (params.hasOwnProperty(param)) {\n url += \"&\".concat(param, \"=\").concat(encodeURIComponent(params[param]));\n }\n }\n var xhr = 'XDomainRequest' in window ? new XDomainRequest() : new XMLHttpRequest();\n xhr.open('GET', url, true);\n xhr.onload = function () {\n if (xhr.status === 404) {\n reject(new Error(\"\\u201C\".concat(videoUrl, \"\\u201D was not found.\")));\n return;\n }\n if (xhr.status === 403) {\n reject(new Error(\"\\u201C\".concat(videoUrl, \"\\u201D is not embeddable.\")));\n return;\n }\n try {\n var json = JSON.parse(xhr.responseText);\n // Check api response for 403 on oembed\n if (json.domain_status_code === 403) {\n // We still want to create the embed to give users visual feedback\n createEmbed(json, element);\n reject(new Error(\"\\u201C\".concat(videoUrl, \"\\u201D is not embeddable.\")));\n return;\n }\n resolve(json);\n } catch (error) {\n reject(error);\n }\n };\n xhr.onerror = function () {\n var status = xhr.status ? \" (\".concat(xhr.status, \")\") : '';\n reject(new Error(\"There was an error fetching the embed code from Vimeo\".concat(status, \".\")));\n };\n xhr.send();\n });\n }\n\n /**\n * Initialize all embeds within a specific element\n *\n * @param {HTMLElement} [parent=document] The parent element.\n * @return {void}\n */\n function initializeEmbeds() {\n var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;\n var elements = [].slice.call(parent.querySelectorAll('[data-vimeo-id], [data-vimeo-url]'));\n var handleError = function handleError(error) {\n if ('console' in window && console.error) {\n console.error(\"There was an error creating an embed: \".concat(error));\n }\n };\n elements.forEach(function (element) {\n try {\n // Skip any that have data-vimeo-defer\n if (element.getAttribute('data-vimeo-defer') !== null) {\n return;\n }\n var params = getOEmbedParameters(element);\n var url = getVimeoUrl(params);\n getOEmbedData(url, params, element).then(function (data) {\n return createEmbed(data, element);\n }).catch(handleError);\n } catch (error) {\n handleError(error);\n }\n });\n }\n\n /**\n * Resize embeds when messaged by the player.\n *\n * @param {HTMLElement} [parent=document] The parent element.\n * @return {void}\n */\n function resizeEmbeds() {\n var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;\n // Prevent execution if users include the player.js script multiple times.\n if (window.VimeoPlayerResizeEmbeds_) {\n return;\n }\n window.VimeoPlayerResizeEmbeds_ = true;\n var onMessage = function onMessage(event) {\n if (!isVimeoUrl(event.origin)) {\n return;\n }\n\n // 'spacechange' is fired only on embeds with cards\n if (!event.data || event.data.event !== 'spacechange') {\n return;\n }\n var iframes = parent.querySelectorAll('iframe');\n for (var i = 0; i < iframes.length; i++) {\n if (iframes[i].contentWindow !== event.source) {\n continue;\n }\n\n // Change padding-bottom of the enclosing div to accommodate\n // card carousel without distorting aspect ratio\n var space = iframes[i].parentElement;\n space.style.paddingBottom = \"\".concat(event.data.data[0].bottom, \"px\");\n break;\n }\n };\n window.addEventListener('message', onMessage);\n }\n\n /**\n * Add chapters to existing metadata for Google SEO\n *\n * @param {HTMLElement} [parent=document] The parent element.\n * @return {void}\n */\n function initAppendVideoMetadata() {\n var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;\n // Prevent execution if users include the player.js script multiple times.\n if (window.VimeoSeoMetadataAppended) {\n return;\n }\n window.VimeoSeoMetadataAppended = true;\n var onMessage = function onMessage(event) {\n if (!isVimeoUrl(event.origin)) {\n return;\n }\n var data = parseMessageData(event.data);\n if (!data || data.event !== 'ready') {\n return;\n }\n var iframes = parent.querySelectorAll('iframe');\n for (var i = 0; i < iframes.length; i++) {\n var iframe = iframes[i];\n\n // Initiate appendVideoMetadata if iframe is a Vimeo embed\n var isValidMessageSource = iframe.contentWindow === event.source;\n if (isVimeoEmbed(iframe.src) && isValidMessageSource) {\n var player = new Player(iframe);\n player.callMethod('appendVideoMetadata', window.location.href);\n }\n }\n };\n window.addEventListener('message', onMessage);\n }\n\n /**\n * Seek to time indicated by vimeo_t query parameter if present in URL\n *\n * @param {HTMLElement} [parent=document] The parent element.\n * @return {void}\n */\n function checkUrlTimeParam() {\n var parent = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : document;\n // Prevent execution if users include the player.js script multiple times.\n if (window.VimeoCheckedUrlTimeParam) {\n return;\n }\n window.VimeoCheckedUrlTimeParam = true;\n var handleError = function handleError(error) {\n if ('console' in window && console.error) {\n console.error(\"There was an error getting video Id: \".concat(error));\n }\n };\n var onMessage = function onMessage(event) {\n if (!isVimeoUrl(event.origin)) {\n return;\n }\n var data = parseMessageData(event.data);\n if (!data || data.event !== 'ready') {\n return;\n }\n var iframes = parent.querySelectorAll('iframe');\n var _loop = function _loop() {\n var iframe = iframes[i];\n var isValidMessageSource = iframe.contentWindow === event.source;\n if (isVimeoEmbed(iframe.src) && isValidMessageSource) {\n var player = new Player(iframe);\n player.getVideoId().then(function (videoId) {\n var matches = new RegExp(\"[?&]vimeo_t_\".concat(videoId, \"=([^&#]*)\")).exec(window.location.href);\n if (matches && matches[1]) {\n var sec = decodeURI(matches[1]);\n player.setCurrentTime(sec);\n }\n return;\n }).catch(handleError);\n }\n };\n for (var i = 0; i < iframes.length; i++) {\n _loop();\n }\n };\n window.addEventListener('message', onMessage);\n }\n\n /* MIT License\n\n Copyright (c) Sindre Sorhus (sindresorhus.com)\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n Terms */\n\n function initializeScreenfull() {\n var fn = function () {\n var val;\n var fnMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'],\n // New WebKit\n ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'],\n // Old WebKit\n ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']];\n var i = 0;\n var l = fnMap.length;\n var ret = {};\n for (; i < l; i++) {\n val = fnMap[i];\n if (val && val[1] in document) {\n for (i = 0; i < val.length; i++) {\n ret[fnMap[0][i]] = val[i];\n }\n return ret;\n }\n }\n return false;\n }();\n var eventNameMap = {\n fullscreenchange: fn.fullscreenchange,\n fullscreenerror: fn.fullscreenerror\n };\n var screenfull = {\n request: function request(element) {\n return new Promise(function (resolve, reject) {\n var onFullScreenEntered = function onFullScreenEntered() {\n screenfull.off('fullscreenchange', onFullScreenEntered);\n resolve();\n };\n screenfull.on('fullscreenchange', onFullScreenEntered);\n element = element || document.documentElement;\n var returnPromise = element[fn.requestFullscreen]();\n if (returnPromise instanceof Promise) {\n returnPromise.then(onFullScreenEntered).catch(reject);\n }\n });\n },\n exit: function exit() {\n return new Promise(function (resolve, reject) {\n if (!screenfull.isFullscreen) {\n resolve();\n return;\n }\n var onFullScreenExit = function onFullScreenExit() {\n screenfull.off('fullscreenchange', onFullScreenExit);\n resolve();\n };\n screenfull.on('fullscreenchange', onFullScreenExit);\n var returnPromise = document[fn.exitFullscreen]();\n if (returnPromise instanceof Promise) {\n returnPromise.then(onFullScreenExit).catch(reject);\n }\n });\n },\n on: function on(event, callback) {\n var eventName = eventNameMap[event];\n if (eventName) {\n document.addEventListener(eventName, callback);\n }\n },\n off: function off(event, callback) {\n var eventName = eventNameMap[event];\n if (eventName) {\n document.removeEventListener(eventName, callback);\n }\n }\n };\n Object.defineProperties(screenfull, {\n isFullscreen: {\n get: function get() {\n return Boolean(document[fn.fullscreenElement]);\n }\n },\n element: {\n enumerable: true,\n get: function get() {\n return document[fn.fullscreenElement];\n }\n },\n isEnabled: {\n enumerable: true,\n get: function get() {\n // Coerce to boolean in case of old WebKit\n return Boolean(document[fn.fullscreenEnabled]);\n }\n }\n });\n return screenfull;\n }\n\n /** @typedef {import('./timing-src-connector.types').PlayerControls} PlayerControls */\n /** @typedef {import('./timing-object.types').TimingObject} TimingObject */\n /** @typedef {import('./timing-src-connector.types').TimingSrcConnectorOptions} TimingSrcConnectorOptions */\n /** @typedef {(msg: string) => any} Logger */\n /** @typedef {import('timing-object.types').TConnectionState} TConnectionState */\n\n /**\n * @type {TimingSrcConnectorOptions}\n *\n * For details on these properties and their effects, see the typescript definition referenced above.\n */\n var defaultOptions = {\n role: 'viewer',\n autoPlayMuted: true,\n allowedDrift: 0.3,\n maxAllowedDrift: 1,\n minCheckInterval: 0.1,\n maxRateAdjustment: 0.2,\n maxTimeToCatchUp: 1\n };\n\n /**\n * There's a proposed W3C spec for the Timing Object which would introduce a new set of APIs that would simplify time-synchronization tasks for browser applications.\n *\n * Proposed spec: https://webtiming.github.io/timingobject/\n * V3 Spec: https://timingsrc.readthedocs.io/en/latest/\n * Demuxed talk: https://www.youtube.com/watch?v=cZSjDaGDmX8\n *\n * This class makes it easy to connect Vimeo.Player to a provided TimingObject via Vimeo.Player.setTimingSrc(myTimingObject, options) and the synchronization will be handled automatically.\n *\n * There are 5 general responsibilities in TimingSrcConnector:\n *\n * 1. `updatePlayer()` which sets the player's currentTime, playbackRate and pause/play state based on current state of the TimingObject.\n * 2. `updateTimingObject()` which sets the TimingObject's position and velocity from the player's state.\n * 3. `playerUpdater` which listens for change events on the TimingObject and will respond by calling updatePlayer.\n * 4. `timingObjectUpdater` which listens to the player events of seeked, play and pause and will respond by calling `updateTimingObject()`.\n * 5. `maintainPlaybackPosition` this is code that constantly monitors the player to make sure it's always in sync with the TimingObject. This is needed because videos will generally not play with precise time accuracy and there will be some drift which becomes more noticeable over longer periods (as noted in the timing-object spec). More details on this method below.\n */\n var TimingSrcConnector = /*#__PURE__*/function (_EventTarget) {\n _inherits(TimingSrcConnector, _EventTarget);\n var _super = _createSuper(TimingSrcConnector);\n /**\n * @param {PlayerControls} player\n * @param {TimingObject} timingObject\n * @param {TimingSrcConnectorOptions} options\n * @param {Logger} logger\n */\n function TimingSrcConnector(_player, timingObject) {\n var _this;\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var logger = arguments.length > 3 ? arguments[3] : undefined;\n _classCallCheck(this, TimingSrcConnector);\n _this = _super.call(this);\n _defineProperty(_assertThisInitialized(_this), \"logger\", void 0);\n _defineProperty(_assertThisInitialized(_this), \"speedAdjustment\", 0);\n /**\n * @param {PlayerControls} player\n * @param {number} newAdjustment\n * @return {Promise}\n */\n _defineProperty(_assertThisInitialized(_this), \"adjustSpeed\", /*#__PURE__*/function () {\n var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(player, newAdjustment) {\n var newPlaybackRate;\n return _regeneratorRuntime().wrap(function _callee$(_context) {\n while (1) switch (_context.prev = _context.next) {\n case 0:\n if (!(_this.speedAdjustment === newAdjustment)) {\n _context.next = 2;\n break;\n }\n return _context.abrupt(\"return\");\n case 2:\n _context.next = 4;\n return player.getPlaybackRate();\n case 4:\n _context.t0 = _context.sent;\n _context.t1 = _this.speedAdjustment;\n _context.t2 = _context.t0 - _context.t1;\n _context.t3 = newAdjustment;\n newPlaybackRate = _context.t2 + _context.t3;\n _this.log(\"New playbackRate: \".concat(newPlaybackRate));\n _context.next = 12;\n return player.setPlaybackRate(newPlaybackRate);\n case 12:\n _this.speedAdjustment = newAdjustment;\n case 13:\n case \"end\":\n return _context.stop();\n }\n }, _callee);\n }));\n return function (_x, _x2) {\n return _ref.apply(this, arguments);\n };\n }());\n _this.logger = logger;\n _this.init(timingObject, _player, _objectSpread2(_objectSpread2({}, defaultOptions), options));\n return _this;\n }\n _createClass(TimingSrcConnector, [{\n key: \"disconnect\",\n value: function disconnect() {\n this.dispatchEvent(new Event('disconnect'));\n }\n\n /**\n * @param {TimingObject} timingObject\n * @param {PlayerControls} player\n * @param {TimingSrcConnectorOptions} options\n * @return {Promise}\n */\n }, {\n key: \"init\",\n value: function () {\n var _init = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(timingObject, player, options) {\n var _this2 = this;\n var playerUpdater, positionSync, timingObjectUpdater;\n return _regeneratorRuntime().wrap(function _callee2$(_context2) {\n while (1) switch (_context2.prev = _context2.next) {\n case 0:\n _context2.next = 2;\n return this.waitForTOReadyState(timingObject, 'open');\n case 2:\n if (!(options.role === 'viewer')) {\n _context2.next = 10;\n break;\n }\n _context2.next = 5;\n return this.updatePlayer(timingObject, player, options);\n case 5:\n playerUpdater = subscribe(timingObject, 'change', function () {\n return _this2.updatePlayer(timingObject, player, options);\n });\n positionSync = this.maintainPlaybackPosition(timingObject, player, options);\n this.addEventListener('disconnect', function () {\n positionSync.cancel();\n playerUpdater.cancel();\n });\n _context2.next = 14;\n break;\n case 10:\n _context2.next = 12;\n return this.updateTimingObject(timingObject, player);\n case 12:\n timingObjectUpdater = subscribe(player, ['seeked', 'play', 'pause', 'ratechange'], function () {\n return _this2.updateTimingObject(timingObject, player);\n }, 'on', 'off');\n this.addEventListener('disconnect', function () {\n return timingObjectUpdater.cancel();\n });\n case 14:\n case \"end\":\n return _context2.stop();\n }\n }, _callee2, this);\n }));\n function init(_x3, _x4, _x5) {\n return _init.apply(this, arguments);\n }\n return init;\n }()\n /**\n * Sets the TimingObject's state to reflect that of the player\n *\n * @param {TimingObject} timingObject\n * @param {PlayerControls} player\n * @return {Promise}\n */\n }, {\n key: \"updateTimingObject\",\n value: function () {\n var _updateTimingObject = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(timingObject, player) {\n return _regeneratorRuntime().wrap(function _callee3$(_context3) {\n while (1) switch (_context3.prev = _context3.next) {\n case 0:\n _context3.t0 = timingObject;\n _context3.next = 3;\n return player.getCurrentTime();\n case 3:\n _context3.t1 = _context3.sent;\n _context3.next = 6;\n return player.getPaused();\n case 6:\n if (!_context3.sent) {\n _context3.next = 10;\n break;\n }\n _context3.t2 = 0;\n _context3.next = 13;\n break;\n case 10:\n _context3.next = 12;\n return player.getPlaybackRate();\n case 12:\n _context3.t2 = _context3.sent;\n case 13:\n _context3.t3 = _context3.t2;\n _context3.t4 = {\n position: _context3.t1,\n velocity: _context3.t3\n };\n _context3.t0.update.call(_context3.t0, _context3.t4);\n case 16:\n case \"end\":\n return _context3.stop();\n }\n }, _callee3);\n }));\n function updateTimingObject(_x6, _x7) {\n return _updateTimingObject.apply(this, arguments);\n }\n return updateTimingObject;\n }()\n /**\n * Sets the player's timing state to reflect that of the TimingObject\n *\n * @param {TimingObject} timingObject\n * @param {PlayerControls} player\n * @param {TimingSrcConnectorOptions} options\n * @return {Promise}\n */\n }, {\n key: \"updatePlayer\",\n value: function () {\n var _updatePlayer = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(timingObject, player, options) {\n var _timingObject$query, position, velocity;\n return _regeneratorRuntime().wrap(function _callee5$(_context5) {\n while (1) switch (_context5.prev = _context5.next) {\n case 0:\n _timingObject$query = timingObject.query(), position = _timingObject$query.position, velocity = _timingObject$query.velocity;\n if (typeof position === 'number') {\n player.setCurrentTime(position);\n }\n if (!(typeof velocity === 'number')) {\n _context5.next = 25;\n break;\n }\n if (!(velocity === 0)) {\n _context5.next = 11;\n break;\n }\n _context5.next = 6;\n return player.getPaused();\n case 6:\n _context5.t0 = _context5.sent;\n if (!(_context5.t0 === false)) {\n _context5.next = 9;\n break;\n }\n player.pause();\n case 9:\n _context5.next = 25;\n break;\n case 11:\n if (!(velocity > 0)) {\n _context5.next = 25;\n break;\n }\n _context5.next = 14;\n return player.getPaused();\n case 14:\n _context5.t1 = _context5.sent;\n if (!(_context5.t1 === true)) {\n _context5.next = 19;\n break;\n }\n _context5.next = 18;\n return player.play().catch( /*#__PURE__*/function () {\n var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4(err) {\n return _regeneratorRuntime().wrap(function _callee4$(_context4) {\n while (1) switch (_context4.prev = _context4.next) {\n case 0:\n if (!(err.name === 'NotAllowedError' && options.autoPlayMuted)) {\n _context4.next = 5;\n break;\n }\n _context4.next = 3;\n return player.setMuted(true);\n case 3:\n _context4.next = 5;\n return player.play().catch(function (err2) {\n return console.error('Couldn\\'t play the video from TimingSrcConnector. Error:', err2);\n });\n case 5:\n case \"end\":\n return _context4.stop();\n }\n }, _callee4);\n }));\n return function (_x11) {\n return _ref2.apply(this, arguments);\n };\n }());\n case 18:\n this.updatePlayer(timingObject, player, options);\n case 19:\n _context5.next = 21;\n return player.getPlaybackRate();\n case 21:\n _context5.t2 = _context5.sent;\n _context5.t3 = velocity;\n if (!(_context5.t2 !== _context5.t3)) {\n _context5.next = 25;\n break;\n }\n player.setPlaybackRate(velocity);\n case 25:\n case \"end\":\n return _context5.stop();\n }\n }, _callee5, this);\n }));\n function updatePlayer(_x8, _x9, _x10) {\n return _updatePlayer.apply(this, arguments);\n }\n return updatePlayer;\n }()\n /**\n * Since video players do not play with 100% time precision, we need to closely monitor\n * our player to be sure it remains in sync with the TimingObject.\n *\n * If out of sync, we use the current conditions and the options provided to determine\n * whether to re-sync via setting currentTime or adjusting the playbackRate\n *\n * @param {TimingObject} timingObject\n * @param {PlayerControls} player\n * @param {TimingSrcConnectorOptions} options\n * @return {{cancel: (function(): void)}}\n */\n }, {\n key: \"maintainPlaybackPosition\",\n value: function maintainPlaybackPosition(timingObject, player, options) {\n var _this3 = this;\n var allowedDrift = options.allowedDrift,\n maxAllowedDrift = options.maxAllowedDrift,\n minCheckInterval = options.minCheckInterval,\n maxRateAdjustment = options.maxRateAdjustment,\n maxTimeToCatchUp = options.maxTimeToCatchUp;\n var syncInterval = Math.min(maxTimeToCatchUp, Math.max(minCheckInterval, maxAllowedDrift)) * 1000;\n var check = /*#__PURE__*/function () {\n var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {\n var diff, diffAbs, min, max, adjustment;\n return _regeneratorRuntime().wrap(function _callee6$(_context6) {\n while (1) switch (_context6.prev = _context6.next) {\n case 0:\n _context6.t0 = timingObject.query().velocity === 0;\n if (_context6.t0) {\n _context6.next = 6;\n break;\n }\n _context6.next = 4;\n return player.getPaused();\n case 4:\n _context6.t1 = _context6.sent;\n _context6.t0 = _context6.t1 === true;\n case 6:\n if (!_context6.t0) {\n _context6.next = 8;\n break;\n }\n return _context6.abrupt(\"return\");\n case 8:\n _context6.t2 = timingObject.query().position;\n _context6.next = 11;\n return player.getCurrentTime();\n case 11:\n _context6.t3 = _context6.sent;\n diff = _context6.t2 - _context6.t3;\n diffAbs = Math.abs(diff);\n _this3.log(\"Drift: \".concat(diff));\n if (!(diffAbs > maxAllowedDrift)) {\n _context6.next = 22;\n break;\n }\n _context6.next = 18;\n return _this3.adjustSpeed(player, 0);\n case 18:\n player.setCurrentTime(timingObject.query().position);\n _this3.log('Resync by currentTime');\n _context6.next = 29;\n break;\n case 22:\n if (!(diffAbs > allowedDrift)) {\n _context6.next = 29;\n break;\n }\n min = diffAbs / maxTimeToCatchUp;\n max = maxRateAdjustment;\n adjustment = min < max ? (max - min) / 2 : max;\n _context6.next = 28;\n return _this3.adjustSpeed(player, adjustment * Math.sign(diff));\n case 28:\n _this3.log('Resync by playbackRate');\n case 29:\n case \"end\":\n return _context6.stop();\n }\n }, _callee6);\n }));\n return function check() {\n return _ref3.apply(this, arguments);\n };\n }();\n var interval = setInterval(function () {\n return check();\n }, syncInterval);\n return {\n cancel: function cancel() {\n return clearInterval(interval);\n }\n };\n }\n\n /**\n * @param {string} msg\n */\n }, {\n key: \"log\",\n value: function log(msg) {\n var _this$logger;\n (_this$logger = this.logger) === null || _this$logger === void 0 ? void 0 : _this$logger.call(this, \"TimingSrcConnector: \".concat(msg));\n }\n }, {\n key: \"waitForTOReadyState\",\n value:\n /**\n * @param {TimingObject} timingObject\n * @param {TConnectionState} state\n * @return {Promise}\n */\n function waitForTOReadyState(timingObject, state) {\n return new Promise(function (resolve) {\n var check = function check() {\n if (timingObject.readyState === state) {\n resolve();\n } else {\n timingObject.addEventListener('readystatechange', check, {\n once: true\n });\n }\n };\n check();\n });\n }\n }]);\n return TimingSrcConnector;\n }( /*#__PURE__*/_wrapNativeSuper(EventTarget));\n\n var playerMap = new WeakMap();\n var readyMap = new WeakMap();\n var screenfull = {};\n var Player = /*#__PURE__*/function () {\n /**\n * Create a Player.\n *\n * @param {(HTMLIFrameElement|HTMLElement|string|jQuery)} element A reference to the Vimeo\n * player iframe, and id, or a jQuery object.\n * @param {object} [options] oEmbed parameters to use when creating an embed in the element.\n * @return {Player}\n */\n function Player(element) {\n var _this = this;\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n _classCallCheck(this, Player);\n /* global jQuery */\n if (window.jQuery && element instanceof jQuery) {\n if (element.length > 1 && window.console && console.warn) {\n console.warn('A jQuery object with multiple elements was passed, using the first element.');\n }\n element = element[0];\n }\n\n // Find an element by ID\n if (typeof document !== 'undefined' && typeof element === 'string') {\n element = document.getElementById(element);\n }\n\n // Not an element!\n if (!isDomElement(element)) {\n throw new TypeError('You must pass either a valid element or a valid id.');\n }\n\n // Already initialized an embed in this div, so grab the iframe\n if (element.nodeName !== 'IFRAME') {\n var iframe = element.querySelector('iframe');\n if (iframe) {\n element = iframe;\n }\n }\n\n // iframe url is not a Vimeo url\n if (element.nodeName === 'IFRAME' && !isVimeoUrl(element.getAttribute('src') || '')) {\n throw new Error('The player element passed isn’t a Vimeo embed.');\n }\n\n // If there is already a player object in the map, return that\n if (playerMap.has(element)) {\n return playerMap.get(element);\n }\n this._window = element.ownerDocument.defaultView;\n this.element = element;\n this.origin = '*';\n var readyPromise = new npo_src(function (resolve, reject) {\n _this._onMessage = function (event) {\n if (!isVimeoUrl(event.origin) || _this.element.contentWindow !== event.source) {\n return;\n }\n if (_this.origin === '*') {\n _this.origin = event.origin;\n }\n var data = parseMessageData(event.data);\n var isError = data && data.event === 'error';\n var isReadyError = isError && data.data && data.data.method === 'ready';\n if (isReadyError) {\n var error = new Error(data.data.message);\n error.name = data.data.name;\n reject(error);\n return;\n }\n var isReadyEvent = data && data.event === 'ready';\n var isPingResponse = data && data.method === 'ping';\n if (isReadyEvent || isPingResponse) {\n _this.element.setAttribute('data-ready', 'true');\n resolve();\n return;\n }\n processData(_this, data);\n };\n _this._window.addEventListener('message', _this._onMessage);\n if (_this.element.nodeName !== 'IFRAME') {\n var params = getOEmbedParameters(element, options);\n var url = getVimeoUrl(params);\n getOEmbedData(url, params, element).then(function (data) {\n var iframe = createEmbed(data, element);\n // Overwrite element with the new iframe,\n // but store reference to the original element\n _this.element = iframe;\n _this._originalElement = element;\n swapCallbacks(element, iframe);\n playerMap.set(_this.element, _this);\n return data;\n }).catch(reject);\n }\n });\n\n // Store a copy of this Player in the map\n readyMap.set(this, readyPromise);\n playerMap.set(this.element, this);\n\n // Send a ping to the iframe so the ready promise will be resolved if\n // the player is already ready.\n if (this.element.nodeName === 'IFRAME') {\n postMessage(this, 'ping');\n }\n if (screenfull.isEnabled) {\n var exitFullscreen = function exitFullscreen() {\n return screenfull.exit();\n };\n this.fullscreenchangeHandler = function () {\n if (screenfull.isFullscreen) {\n storeCallback(_this, 'event:exitFullscreen', exitFullscreen);\n } else {\n removeCallback(_this, 'event:exitFullscreen', exitFullscreen);\n }\n // eslint-disable-next-line\n _this.ready().then(function () {\n postMessage(_this, 'fullscreenchange', screenfull.isFullscreen);\n });\n };\n screenfull.on('fullscreenchange', this.fullscreenchangeHandler);\n }\n return this;\n }\n\n /**\n * Get a promise for a method.\n *\n * @param {string} name The API method to call.\n * @param {Object} [args={}] Arguments to send via postMessage.\n * @return {Promise}\n */\n _createClass(Player, [{\n key: \"callMethod\",\n value: function callMethod(name) {\n var _this2 = this;\n var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return new npo_src(function (resolve, reject) {\n // We are storing the resolve/reject handlers to call later, so we\n // can’t return here.\n // eslint-disable-next-line promise/always-return\n return _this2.ready().then(function () {\n storeCallback(_this2, name, {\n resolve: resolve,\n reject: reject\n });\n postMessage(_this2, name, args);\n }).catch(reject);\n });\n }\n\n /**\n * Get a promise for the value of a player property.\n *\n * @param {string} name The property name\n * @return {Promise}\n */\n }, {\n key: \"get\",\n value: function get(name) {\n var _this3 = this;\n return new npo_src(function (resolve, reject) {\n name = getMethodName(name, 'get');\n\n // We are storing the resolve/reject handlers to call later, so we\n // can’t return here.\n // eslint-disable-next-line promise/always-return\n return _this3.ready().then(function () {\n storeCallback(_this3, name, {\n resolve: resolve,\n reject: reject\n });\n postMessage(_this3, name);\n }).catch(reject);\n });\n }\n\n /**\n * Get a promise for setting the value of a player property.\n *\n * @param {string} name The API method to call.\n * @param {mixed} value The value to set.\n * @return {Promise}\n */\n }, {\n key: \"set\",\n value: function set(name, value) {\n var _this4 = this;\n return new npo_src(function (resolve, reject) {\n name = getMethodName(name, 'set');\n if (value === undefined || value === null) {\n throw new TypeError('There must be a value to set.');\n }\n\n // We are storing the resolve/reject handlers to call later, so we\n // can’t return here.\n // eslint-disable-next-line promise/always-return\n return _this4.ready().then(function () {\n storeCallback(_this4, name, {\n resolve: resolve,\n reject: reject\n });\n postMessage(_this4, name, value);\n }).catch(reject);\n });\n }\n\n /**\n * Add an event listener for the specified event. Will call the\n * callback with a single parameter, `data`, that contains the data for\n * that event.\n *\n * @param {string} eventName The name of the event.\n * @param {function(*)} callback The function to call when the event fires.\n * @return {void}\n */\n }, {\n key: \"on\",\n value: function on(eventName, callback) {\n if (!eventName) {\n throw new TypeError('You must pass an event name.');\n }\n if (!callback) {\n throw new TypeError('You must pass a callback function.');\n }\n if (typeof callback !== 'function') {\n throw new TypeError('The callback must be a function.');\n }\n var callbacks = getCallbacks(this, \"event:\".concat(eventName));\n if (callbacks.length === 0) {\n this.callMethod('addEventListener', eventName).catch(function () {\n // Ignore the error. There will be an error event fired that\n // will trigger the error callback if they are listening.\n });\n }\n storeCallback(this, \"event:\".concat(eventName), callback);\n }\n\n /**\n * Remove an event listener for the specified event. Will remove all\n * listeners for that event if a `callback` isn’t passed, or only that\n * specific callback if it is passed.\n *\n * @param {string} eventName The name of the event.\n * @param {function} [callback] The specific callback to remove.\n * @return {void}\n */\n }, {\n key: \"off\",\n value: function off(eventName, callback) {\n if (!eventName) {\n throw new TypeError('You must pass an event name.');\n }\n if (callback && typeof callback !== 'function') {\n throw new TypeError('The callback must be a function.');\n }\n var lastCallback = removeCallback(this, \"event:\".concat(eventName), callback);\n\n // If there are no callbacks left, remove the listener\n if (lastCallback) {\n this.callMethod('removeEventListener', eventName).catch(function (e) {\n // Ignore the error. There will be an error event fired that\n // will trigger the error callback if they are listening.\n });\n }\n }\n\n /**\n * A promise to load a new video.\n *\n * @promise LoadVideoPromise\n * @fulfill {number} The video with this id or url successfully loaded.\n * @reject {TypeError} The id was not a number.\n */\n /**\n * Load a new video into this embed. The promise will be resolved if\n * the video is successfully loaded, or it will be rejected if it could\n * not be loaded.\n *\n * @param {number|string|object} options The id of the video, the url of the video, or an object with embed options.\n * @return {LoadVideoPromise}\n */\n }, {\n key: \"loadVideo\",\n value: function loadVideo(options) {\n return this.callMethod('loadVideo', options);\n }\n\n /**\n * A promise to perform an action when the Player is ready.\n *\n * @todo document errors\n * @promise LoadVideoPromise\n * @fulfill {void}\n */\n /**\n * Trigger a function when the player iframe has initialized. You do not\n * need to wait for `ready` to trigger to begin adding event listeners\n * or calling other methods.\n *\n * @return {ReadyPromise}\n */\n }, {\n key: \"ready\",\n value: function ready() {\n var readyPromise = readyMap.get(this) || new npo_src(function (resolve, reject) {\n reject(new Error('Unknown player. Probably unloaded.'));\n });\n return npo_src.resolve(readyPromise);\n }\n\n /**\n * A promise to add a cue point to the player.\n *\n * @promise AddCuePointPromise\n * @fulfill {string} The id of the cue point to use for removeCuePoint.\n * @reject {RangeError} the time was less than 0 or greater than the\n * video’s duration.\n * @reject {UnsupportedError} Cue points are not supported with the current\n * player or browser.\n */\n /**\n * Add a cue point to the player.\n *\n * @param {number} time The time for the cue point.\n * @param {object} [data] Arbitrary data to be returned with the cue point.\n * @return {AddCuePointPromise}\n */\n }, {\n key: \"addCuePoint\",\n value: function addCuePoint(time) {\n var data = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n return this.callMethod('addCuePoint', {\n time: time,\n data: data\n });\n }\n\n /**\n * A promise to remove a cue point from the player.\n *\n * @promise AddCuePointPromise\n * @fulfill {string} The id of the cue point that was removed.\n * @reject {InvalidCuePoint} The cue point with the specified id was not\n * found.\n * @reject {UnsupportedError} Cue points are not supported with the current\n * player or browser.\n */\n /**\n * Remove a cue point from the video.\n *\n * @param {string} id The id of the cue point to remove.\n * @return {RemoveCuePointPromise}\n */\n }, {\n key: \"removeCuePoint\",\n value: function removeCuePoint(id) {\n return this.callMethod('removeCuePoint', id);\n }\n\n /**\n * A representation of a text track on a video.\n *\n * @typedef {Object} VimeoTextTrack\n * @property {string} language The ISO language code.\n * @property {string} kind The kind of track it is (captions or subtitles).\n * @property {string} label The human‐readable label for the track.\n */\n /**\n * A promise to enable a text track.\n *\n * @promise EnableTextTrackPromise\n * @fulfill {VimeoTextTrack} The text track that was enabled.\n * @reject {InvalidTrackLanguageError} No track was available with the\n * specified language.\n * @reject {InvalidTrackError} No track was available with the specified\n * language and kind.\n */\n /**\n * Enable the text track with the specified language, and optionally the\n * specified kind (captions or subtitles).\n *\n * When set via the API, the track language will not change the viewer’s\n * stored preference.\n *\n * @param {string} language The two‐letter language code.\n * @param {string} [kind] The kind of track to enable (captions or subtitles).\n * @return {EnableTextTrackPromise}\n */\n }, {\n key: \"enableTextTrack\",\n value: function enableTextTrack(language, kind) {\n if (!language) {\n throw new TypeError('You must pass a language.');\n }\n return this.callMethod('enableTextTrack', {\n language: language,\n kind: kind\n });\n }\n\n /**\n * A promise to disable the active text track.\n *\n * @promise DisableTextTrackPromise\n * @fulfill {void} The track was disabled.\n */\n /**\n * Disable the currently-active text track.\n *\n * @return {DisableTextTrackPromise}\n */\n }, {\n key: \"disableTextTrack\",\n value: function disableTextTrack() {\n return this.callMethod('disableTextTrack');\n }\n\n /**\n * A promise to pause the video.\n *\n * @promise PausePromise\n * @fulfill {void} The video was paused.\n */\n /**\n * Pause the video if it’s playing.\n *\n * @return {PausePromise}\n */\n }, {\n key: \"pause\",\n value: function pause() {\n return this.callMethod('pause');\n }\n\n /**\n * A promise to play the video.\n *\n * @promise PlayPromise\n * @fulfill {void} The video was played.\n */\n /**\n * Play the video if it’s paused. **Note:** on iOS and some other\n * mobile devices, you cannot programmatically trigger play. Once the\n * viewer has tapped on the play button in the player, however, you\n * will be able to use this function.\n *\n * @return {PlayPromise}\n */\n }, {\n key: \"play\",\n value: function play() {\n return this.callMethod('play');\n }\n\n /**\n * Request that the player enters fullscreen.\n * @return {Promise}\n */\n }, {\n key: \"requestFullscreen\",\n value: function requestFullscreen() {\n if (screenfull.isEnabled) {\n return screenfull.request(this.element);\n }\n return this.callMethod('requestFullscreen');\n }\n\n /**\n * Request that the player exits fullscreen.\n * @return {Promise}\n */\n }, {\n key: \"exitFullscreen\",\n value: function exitFullscreen() {\n if (screenfull.isEnabled) {\n return screenfull.exit();\n }\n return this.callMethod('exitFullscreen');\n }\n\n /**\n * Returns true if the player is currently fullscreen.\n * @return {Promise}\n */\n }, {\n key: \"getFullscreen\",\n value: function getFullscreen() {\n if (screenfull.isEnabled) {\n return npo_src.resolve(screenfull.isFullscreen);\n }\n return this.get('fullscreen');\n }\n\n /**\n * Request that the player enters picture-in-picture.\n * @return {Promise}\n */\n }, {\n key: \"requestPictureInPicture\",\n value: function requestPictureInPicture() {\n return this.callMethod('requestPictureInPicture');\n }\n\n /**\n * Request that the player exits picture-in-picture.\n * @return {Promise}\n */\n }, {\n key: \"exitPictureInPicture\",\n value: function exitPictureInPicture() {\n return this.callMethod('exitPictureInPicture');\n }\n\n /**\n * Returns true if the player is currently picture-in-picture.\n * @return {Promise}\n */\n }, {\n key: \"getPictureInPicture\",\n value: function getPictureInPicture() {\n return this.get('pictureInPicture');\n }\n\n /**\n * A promise to prompt the viewer to initiate remote playback.\n *\n * @promise RemotePlaybackPromptPromise\n * @fulfill {void}\n * @reject {NotFoundError} No remote playback device is available.\n */\n /**\n * Request to prompt the user to initiate remote playback.\n *\n * @return {RemotePlaybackPromptPromise}\n */\n }, {\n key: \"remotePlaybackPrompt\",\n value: function remotePlaybackPrompt() {\n return this.callMethod('remotePlaybackPrompt');\n }\n\n /**\n * A promise to unload the video.\n *\n * @promise UnloadPromise\n * @fulfill {void} The video was unloaded.\n */\n /**\n * Return the player to its initial state.\n *\n * @return {UnloadPromise}\n */\n }, {\n key: \"unload\",\n value: function unload() {\n return this.callMethod('unload');\n }\n\n /**\n * Cleanup the player and remove it from the DOM\n *\n * It won't be usable and a new one should be constructed\n * in order to do any operations.\n *\n * @return {Promise}\n */\n }, {\n key: \"destroy\",\n value: function destroy() {\n var _this5 = this;\n return new npo_src(function (resolve) {\n readyMap.delete(_this5);\n playerMap.delete(_this5.element);\n if (_this5._originalElement) {\n playerMap.delete(_this5._originalElement);\n _this5._originalElement.removeAttribute('data-vimeo-initialized');\n }\n if (_this5.element && _this5.element.nodeName === 'IFRAME' && _this5.element.parentNode) {\n // If we've added an additional wrapper div, remove that from the DOM.\n // If not, just remove the iframe element.\n if (_this5.element.parentNode.parentNode && _this5._originalElement && _this5._originalElement !== _this5.element.parentNode) {\n _this5.element.parentNode.parentNode.removeChild(_this5.element.parentNode);\n } else {\n _this5.element.parentNode.removeChild(_this5.element);\n }\n }\n\n // If the clip is private there is a case where the element stays the\n // div element. Destroy should reset the div and remove the iframe child.\n if (_this5.element && _this5.element.nodeName === 'DIV' && _this5.element.parentNode) {\n _this5.element.removeAttribute('data-vimeo-initialized');\n var iframe = _this5.element.querySelector('iframe');\n if (iframe && iframe.parentNode) {\n // If we've added an additional wrapper div, remove that from the DOM.\n // If not, just remove the iframe element.\n if (iframe.parentNode.parentNode && _this5._originalElement && _this5._originalElement !== iframe.parentNode) {\n iframe.parentNode.parentNode.removeChild(iframe.parentNode);\n } else {\n iframe.parentNode.removeChild(iframe);\n }\n }\n }\n _this5._window.removeEventListener('message', _this5._onMessage);\n if (screenfull.isEnabled) {\n screenfull.off('fullscreenchange', _this5.fullscreenchangeHandler);\n }\n resolve();\n });\n }\n\n /**\n * A promise to get the autopause behavior of the video.\n *\n * @promise GetAutopausePromise\n * @fulfill {boolean} Whether autopause is turned on or off.\n * @reject {UnsupportedError} Autopause is not supported with the current\n * player or browser.\n */\n /**\n * Get the autopause behavior for this player.\n *\n * @return {GetAutopausePromise}\n */\n }, {\n key: \"getAutopause\",\n value: function getAutopause() {\n return this.get('autopause');\n }\n\n /**\n * A promise to set the autopause behavior of the video.\n *\n * @promise SetAutopausePromise\n * @fulfill {boolean} Whether autopause is turned on or off.\n * @reject {UnsupportedError} Autopause is not supported with the current\n * player or browser.\n */\n /**\n * Enable or disable the autopause behavior of this player.\n *\n * By default, when another video is played in the same browser, this\n * player will automatically pause. Unless you have a specific reason\n * for doing so, we recommend that you leave autopause set to the\n * default (`true`).\n *\n * @param {boolean} autopause\n * @return {SetAutopausePromise}\n */\n }, {\n key: \"setAutopause\",\n value: function setAutopause(autopause) {\n return this.set('autopause', autopause);\n }\n\n /**\n * A promise to get the buffered property of the video.\n *\n * @promise GetBufferedPromise\n * @fulfill {Array} Buffered Timeranges converted to an Array.\n */\n /**\n * Get the buffered property of the video.\n *\n * @return {GetBufferedPromise}\n */\n }, {\n key: \"getBuffered\",\n value: function getBuffered() {\n return this.get('buffered');\n }\n\n /**\n * @typedef {Object} CameraProperties\n * @prop {number} props.yaw - Number between 0 and 360.\n * @prop {number} props.pitch - Number between -90 and 90.\n * @prop {number} props.roll - Number between -180 and 180.\n * @prop {number} props.fov - The field of view in degrees.\n */\n /**\n * A promise to get the camera properties of the player.\n *\n * @promise GetCameraPromise\n * @fulfill {CameraProperties} The camera properties.\n */\n /**\n * For 360° videos get the camera properties for this player.\n *\n * @return {GetCameraPromise}\n */\n }, {\n key: \"getCameraProps\",\n value: function getCameraProps() {\n return this.get('cameraProps');\n }\n\n /**\n * A promise to set the camera properties of the player.\n *\n * @promise SetCameraPromise\n * @fulfill {Object} The camera was successfully set.\n * @reject {RangeError} The range was out of bounds.\n */\n /**\n * For 360° videos set the camera properties for this player.\n *\n * @param {CameraProperties} camera The camera properties\n * @return {SetCameraPromise}\n */\n }, {\n key: \"setCameraProps\",\n value: function setCameraProps(camera) {\n return this.set('cameraProps', camera);\n }\n\n /**\n * A representation of a chapter.\n *\n * @typedef {Object} VimeoChapter\n * @property {number} startTime The start time of the chapter.\n * @property {object} title The title of the chapter.\n * @property {number} index The place in the order of Chapters. Starts at 1.\n */\n /**\n * A promise to get chapters for the video.\n *\n * @promise GetChaptersPromise\n * @fulfill {VimeoChapter[]} The chapters for the video.\n */\n /**\n * Get an array of all the chapters for the video.\n *\n * @return {GetChaptersPromise}\n */\n }, {\n key: \"getChapters\",\n value: function getChapters() {\n return this.get('chapters');\n }\n\n /**\n * A promise to get the currently active chapter.\n *\n * @promise GetCurrentChaptersPromise\n * @fulfill {VimeoChapter|undefined} The current chapter for the video.\n */\n /**\n * Get the currently active chapter for the video.\n *\n * @return {GetCurrentChaptersPromise}\n */\n }, {\n key: \"getCurrentChapter\",\n value: function getCurrentChapter() {\n return this.get('currentChapter');\n }\n\n /**\n * A promise to get the accent color of the player.\n *\n * @promise GetColorPromise\n * @fulfill {string} The hex color of the player.\n */\n /**\n * Get the accent color for this player. Note this is deprecated in place of `getColorTwo`.\n *\n * @return {GetColorPromise}\n */\n }, {\n key: \"getColor\",\n value: function getColor() {\n return this.get('color');\n }\n\n /**\n * A promise to get all colors for the player in an array.\n *\n * @promise GetColorsPromise\n * @fulfill {string[]} The hex colors of the player.\n */\n /**\n * Get all the colors for this player in an array: [colorOne, colorTwo, colorThree, colorFour]\n *\n * @return {GetColorPromise}\n */\n }, {\n key: \"getColors\",\n value: function getColors() {\n return npo_src.all([this.get('colorOne'), this.get('colorTwo'), this.get('colorThree'), this.get('colorFour')]);\n }\n\n /**\n * A promise to set the accent color of the player.\n *\n * @promise SetColorPromise\n * @fulfill {string} The color was successfully set.\n * @reject {TypeError} The string was not a valid hex or rgb color.\n * @reject {ContrastError} The color was set, but the contrast is\n * outside of the acceptable range.\n * @reject {EmbedSettingsError} The owner of the player has chosen to\n * use a specific color.\n */\n /**\n * Set the accent color of this player to a hex or rgb string. Setting the\n * color may fail if the owner of the video has set their embed\n * preferences to force a specific color.\n * Note this is deprecated in place of `setColorTwo`.\n *\n * @param {string} color The hex or rgb color string to set.\n * @return {SetColorPromise}\n */\n }, {\n key: \"setColor\",\n value: function setColor(color) {\n return this.set('color', color);\n }\n\n /**\n * A promise to set all colors for the player.\n *\n * @promise SetColorsPromise\n * @fulfill {string[]} The colors were successfully set.\n * @reject {TypeError} The string was not a valid hex or rgb color.\n * @reject {ContrastError} The color was set, but the contrast is\n * outside of the acceptable range.\n * @reject {EmbedSettingsError} The owner of the player has chosen to\n * use a specific color.\n */\n /**\n * Set the colors of this player to a hex or rgb string. Setting the\n * color may fail if the owner of the video has set their embed\n * preferences to force a specific color.\n * The colors should be passed in as an array: [colorOne, colorTwo, colorThree, colorFour].\n * If a color should not be set, the index in the array can be left as null.\n *\n * @param {string[]} colors Array of the hex or rgb color strings to set.\n * @return {SetColorsPromise}\n */\n }, {\n key: \"setColors\",\n value: function setColors(colors) {\n if (!Array.isArray(colors)) {\n return new npo_src(function (resolve, reject) {\n return reject(new TypeError('Argument must be an array.'));\n });\n }\n var nullPromise = new npo_src(function (resolve) {\n return resolve(null);\n });\n var colorPromises = [colors[0] ? this.set('colorOne', colors[0]) : nullPromise, colors[1] ? this.set('colorTwo', colors[1]) : nullPromise, colors[2] ? this.set('colorThree', colors[2]) : nullPromise, colors[3] ? this.set('colorFour', colors[3]) : nullPromise];\n return npo_src.all(colorPromises);\n }\n\n /**\n * A representation of a cue point.\n *\n * @typedef {Object} VimeoCuePoint\n * @property {number} time The time of the cue point.\n * @property {object} data The data passed when adding the cue point.\n * @property {string} id The unique id for use with removeCuePoint.\n */\n /**\n * A promise to get the cue points of a video.\n *\n * @promise GetCuePointsPromise\n * @fulfill {VimeoCuePoint[]} The cue points added to the video.\n * @reject {UnsupportedError} Cue points are not supported with the current\n * player or browser.\n */\n /**\n * Get an array of the cue points added to the video.\n *\n * @return {GetCuePointsPromise}\n */\n }, {\n key: \"getCuePoints\",\n value: function getCuePoints() {\n return this.get('cuePoints');\n }\n\n /**\n * A promise to get the current time of the video.\n *\n * @promise GetCurrentTimePromise\n * @fulfill {number} The current time in seconds.\n */\n /**\n * Get the current playback position in seconds.\n *\n * @return {GetCurrentTimePromise}\n */\n }, {\n key: \"getCurrentTime\",\n value: function getCurrentTime() {\n return this.get('currentTime');\n }\n\n /**\n * A promise to set the current time of the video.\n *\n * @promise SetCurrentTimePromise\n * @fulfill {number} The actual current time that was set.\n * @reject {RangeError} the time was less than 0 or greater than the\n * video’s duration.\n */\n /**\n * Set the current playback position in seconds. If the player was\n * paused, it will remain paused. Likewise, if the player was playing,\n * it will resume playing once the video has buffered.\n *\n * You can provide an accurate time and the player will attempt to seek\n * to as close to that time as possible. The exact time will be the\n * fulfilled value of the promise.\n *\n * @param {number} currentTime\n * @return {SetCurrentTimePromise}\n */\n }, {\n key: \"setCurrentTime\",\n value: function setCurrentTime(currentTime) {\n return this.set('currentTime', currentTime);\n }\n\n /**\n * A promise to get the duration of the video.\n *\n * @promise GetDurationPromise\n * @fulfill {number} The duration in seconds.\n */\n /**\n * Get the duration of the video in seconds. It will be rounded to the\n * nearest second before playback begins, and to the nearest thousandth\n * of a second after playback begins.\n *\n * @return {GetDurationPromise}\n */\n }, {\n key: \"getDuration\",\n value: function getDuration() {\n return this.get('duration');\n }\n\n /**\n * A promise to get the ended state of the video.\n *\n * @promise GetEndedPromise\n * @fulfill {boolean} Whether or not the video has ended.\n */\n /**\n * Get the ended state of the video. The video has ended if\n * `currentTime === duration`.\n *\n * @return {GetEndedPromise}\n */\n }, {\n key: \"getEnded\",\n value: function getEnded() {\n return this.get('ended');\n }\n\n /**\n * A promise to get the loop state of the player.\n *\n * @promise GetLoopPromise\n * @fulfill {boolean} Whether or not the player is set to loop.\n */\n /**\n * Get the loop state of the player.\n *\n * @return {GetLoopPromise}\n */\n }, {\n key: \"getLoop\",\n value: function getLoop() {\n return this.get('loop');\n }\n\n /**\n * A promise to set the loop state of the player.\n *\n * @promise SetLoopPromise\n * @fulfill {boolean} The loop state that was set.\n */\n /**\n * Set the loop state of the player. When set to `true`, the player\n * will start over immediately once playback ends.\n *\n * @param {boolean} loop\n * @return {SetLoopPromise}\n */\n }, {\n key: \"setLoop\",\n value: function setLoop(loop) {\n return this.set('loop', loop);\n }\n\n /**\n * A promise to set the muted state of the player.\n *\n * @promise SetMutedPromise\n * @fulfill {boolean} The muted state that was set.\n */\n /**\n * Set the muted state of the player. When set to `true`, the player\n * volume will be muted.\n *\n * @param {boolean} muted\n * @return {SetMutedPromise}\n */\n }, {\n key: \"setMuted\",\n value: function setMuted(muted) {\n return this.set('muted', muted);\n }\n\n /**\n * A promise to get the muted state of the player.\n *\n * @promise GetMutedPromise\n * @fulfill {boolean} Whether or not the player is muted.\n */\n /**\n * Get the muted state of the player.\n *\n * @return {GetMutedPromise}\n */\n }, {\n key: \"getMuted\",\n value: function getMuted() {\n return this.get('muted');\n }\n\n /**\n * A promise to get the paused state of the player.\n *\n * @promise GetLoopPromise\n * @fulfill {boolean} Whether or not the video is paused.\n */\n /**\n * Get the paused state of the player.\n *\n * @return {GetLoopPromise}\n */\n }, {\n key: \"getPaused\",\n value: function getPaused() {\n return this.get('paused');\n }\n\n /**\n * A promise to get the playback rate of the player.\n *\n * @promise GetPlaybackRatePromise\n * @fulfill {number} The playback rate of the player on a scale from 0 to 2.\n */\n /**\n * Get the playback rate of the player on a scale from `0` to `2`.\n *\n * @return {GetPlaybackRatePromise}\n */\n }, {\n key: \"getPlaybackRate\",\n value: function getPlaybackRate() {\n return this.get('playbackRate');\n }\n\n /**\n * A promise to set the playbackrate of the player.\n *\n * @promise SetPlaybackRatePromise\n * @fulfill {number} The playback rate was set.\n * @reject {RangeError} The playback rate was less than 0 or greater than 2.\n */\n /**\n * Set the playback rate of the player on a scale from `0` to `2`. When set\n * via the API, the playback rate will not be synchronized to other\n * players or stored as the viewer's preference.\n *\n * @param {number} playbackRate\n * @return {SetPlaybackRatePromise}\n */\n }, {\n key: \"setPlaybackRate\",\n value: function setPlaybackRate(playbackRate) {\n return this.set('playbackRate', playbackRate);\n }\n\n /**\n * A promise to get the played property of the video.\n *\n * @promise GetPlayedPromise\n * @fulfill {Array} Played Timeranges converted to an Array.\n */\n /**\n * Get the played property of the video.\n *\n * @return {GetPlayedPromise}\n */\n }, {\n key: \"getPlayed\",\n value: function getPlayed() {\n return this.get('played');\n }\n\n /**\n * A promise to get the qualities available of the current video.\n *\n * @promise GetQualitiesPromise\n * @fulfill {Array} The qualities of the video.\n */\n /**\n * Get the qualities of the current video.\n *\n * @return {GetQualitiesPromise}\n */\n }, {\n key: \"getQualities\",\n value: function getQualities() {\n return this.get('qualities');\n }\n\n /**\n * A promise to get the current set quality of the video.\n *\n * @promise GetQualityPromise\n * @fulfill {string} The current set quality.\n */\n /**\n * Get the current set quality of the video.\n *\n * @return {GetQualityPromise}\n */\n }, {\n key: \"getQuality\",\n value: function getQuality() {\n return this.get('quality');\n }\n\n /**\n * A promise to set the video quality.\n *\n * @promise SetQualityPromise\n * @fulfill {number} The quality was set.\n * @reject {RangeError} The quality is not available.\n */\n /**\n * Set a video quality.\n *\n * @param {string} quality\n * @return {SetQualityPromise}\n */\n }, {\n key: \"setQuality\",\n value: function setQuality(quality) {\n return this.set('quality', quality);\n }\n\n /**\n * A promise to get the remote playback availability.\n *\n * @promise RemotePlaybackAvailabilityPromise\n * @fulfill {boolean} Whether remote playback is available.\n */\n /**\n * Get the availability of remote playback.\n *\n * @return {RemotePlaybackAvailabilityPromise}\n */\n }, {\n key: \"getRemotePlaybackAvailability\",\n value: function getRemotePlaybackAvailability() {\n return this.get('remotePlaybackAvailability');\n }\n\n /**\n * A promise to get the current remote playback state.\n *\n * @promise RemotePlaybackStatePromise\n * @fulfill {string} The state of the remote playback: connecting, connected, or disconnected.\n */\n /**\n * Get the current remote playback state.\n *\n * @return {RemotePlaybackStatePromise}\n */\n }, {\n key: \"getRemotePlaybackState\",\n value: function getRemotePlaybackState() {\n return this.get('remotePlaybackState');\n }\n\n /**\n * A promise to get the seekable property of the video.\n *\n * @promise GetSeekablePromise\n * @fulfill {Array} Seekable Timeranges converted to an Array.\n */\n /**\n * Get the seekable property of the video.\n *\n * @return {GetSeekablePromise}\n */\n }, {\n key: \"getSeekable\",\n value: function getSeekable() {\n return this.get('seekable');\n }\n\n /**\n * A promise to get the seeking property of the player.\n *\n * @promise GetSeekingPromise\n * @fulfill {boolean} Whether or not the player is currently seeking.\n */\n /**\n * Get if the player is currently seeking.\n *\n * @return {GetSeekingPromise}\n */\n }, {\n key: \"getSeeking\",\n value: function getSeeking() {\n return this.get('seeking');\n }\n\n /**\n * A promise to get the text tracks of a video.\n *\n * @promise GetTextTracksPromise\n * @fulfill {VimeoTextTrack[]} The text tracks associated with the video.\n */\n /**\n * Get an array of the text tracks that exist for the video.\n *\n * @return {GetTextTracksPromise}\n */\n }, {\n key: \"getTextTracks\",\n value: function getTextTracks() {\n return this.get('textTracks');\n }\n\n /**\n * A promise to get the embed code for the video.\n *\n * @promise GetVideoEmbedCodePromise\n * @fulfill {string} The `