uefir_channels.js

Pasted Nov 28, 2026, 10:34 PM1 file703 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgrth27t9bxaaga
uefir_channels.js
(function () {
    'use strict';

    if (window.uefir_channels_plugin) return;
    window.uefir_channels_plugin = true;

    var API = 'https://uefir.com/api/live-channels';

    var TXT = {
        uk: {
            menu: 'UEFIR — наживо', loading: 'Завантаження каналів…', fail: 'Не вдалося завантажити канали',
            channels: 'Канали', next: 'Далі: ', live_fail: 'Не вдалося завантажити трансляцію',
            quality: 'Якість', quality_auto: 'Авто', cc_off: 'Субтитри: вимк', cc_on: 'Субтитри: увімк',
            external: 'Зовнішній плеєр', external_fail: 'Не вдалося відкрити, посилання: ', external_ok: 'Відкрито в YouTube',
            mode_select: 'Спливний список', mode_page: 'Повноекранна сторінка',
            field_open_mode: 'Спосіб відкриття списку каналів',
            field_open_mode_descr: 'Спливний список — як коротке контекстне меню. Повноекранна сторінка — окремий екран із заголовком і сіткою каналів, схожий на екран "Розширення".',
            field_sort: 'Сортування каналів', sort_popularity: 'За популярністю (джерелами)', sort_alpha: 'За алфавітом',
            field_quality: 'Якість за замовчуванням',
            field_quality_descr: 'YouTube здебільшого ігнорує ручний вибір якості для сторонніх відео — це значення застосовується, але не гарантується.',
            field_subtitles: 'Субтитри за замовчуванням',
            field_resync: 'Інтервал синхронізації з сервером',
            field_autohide: 'Автоприховування панелі керування', autohide_off: 'Не ховати',
            field_open_channels: 'Відкрити список каналів',
            unit_sec: 'с'
        },
        ru: {
            menu: 'UEFIR — в эфире', loading: 'Загрузка каналов…', fail: 'Не удалось загрузить каналы',
            channels: 'Каналы', next: 'Далее: ', live_fail: 'Не удалось загрузить трансляцию',
            quality: 'Качество', quality_auto: 'Авто', cc_off: 'Субтитры: выкл', cc_on: 'Субтитры: вкл',
            external: 'Внешний плеер', external_fail: 'Не удалось открыть, ссылка: ', external_ok: 'Открыто в YouTube',
            mode_select: 'Всплывающий список', mode_page: 'Полноэкранная страница',
            field_open_mode: 'Способ открытия списка каналов',
            field_open_mode_descr: 'Всплывающий список — короткое контекстное меню. Полноэкранная страница — отдельный экран с заголовком и сеткой каналов, похожий на экран "Расширения".',
            field_sort: 'Сортировка каналов', sort_popularity: 'По популярности (источникам)', sort_alpha: 'По алфавиту',
            field_quality: 'Качество по умолчанию',
            field_quality_descr: 'YouTube чаще всего игнорирует ручной выбор качества для сторонних видео — значение применяется, но не гарантируется.',
            field_subtitles: 'Субтитры по умолчанию',
            field_resync: 'Интервал синхронизации с сервером',
            field_autohide: 'Автоскрытие панели управления', autohide_off: 'Не скрывать',
            field_open_channels: 'Открыть список каналов',
            unit_sec: 'с'
        },
        en: {
            menu: 'UEFIR — live', loading: 'Loading channels…', fail: 'Could not load channels',
            channels: 'Channels', next: 'Next: ', live_fail: 'Could not load the stream',
            quality: 'Quality', quality_auto: 'Auto', cc_off: 'Subtitles: off', cc_on: 'Subtitles: on',
            external: 'External player', external_fail: 'Could not open, link: ', external_ok: 'Opened in YouTube',
            mode_select: 'Popup list', mode_page: 'Full-screen page',
            field_open_mode: 'How the channel list opens',
            field_open_mode_descr: 'Popup list — a short context menu. Full-screen page — a dedicated screen with a title and a channel grid, like the "Extensions" screen.',
            field_sort: 'Channel sorting', sort_popularity: 'By popularity (sources)', sort_alpha: 'Alphabetically',
            field_quality: 'Default quality',
            field_quality_descr: 'YouTube mostly ignores manual quality selection for third-party videos — this is applied, but not guaranteed.',
            field_subtitles: 'Subtitles by default',
            field_resync: 'Server re-sync interval',
            field_autohide: 'Auto-hide the control panel', autohide_off: 'Never hide',
            field_open_channels: 'Open the channel list',
            unit_sec: 's'
        }
    };

    function lang() {
        var l = 'uk';
        try { l = Lampa.Storage.get('language', 'uk') || 'uk'; } catch (e) {}
        if (l === 'uk') return 'uk';
        if (l === 'ru' || l === 'be') return 'ru';
        return 'en';
    }

    function t(key) { return TXT[lang()][key]; }

    function noty(text) {
        try { Lampa.Noty.show(text); } catch (e) {}
    }

    var ICON = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" ' +
        'stroke-linejoin="round"><rect x="2.5" y="5" width="19" height="13" rx="2"></rect><path d="M8 21h8"></path></svg>';

    var BACK_ICON = '<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
        'stroke-linecap="round" stroke-linejoin="round"><path d="M15 18l-6-6 6-6"></path></svg>';

    // ---------- API ----------

    function fetchChannels(ids, onDone, onFail) {
        var url = API;
        if (ids && ids.length) {
            url += '?' + ids.map(function (id) { return 'ids[]=' + encodeURIComponent(id); }).join('&');
        }

        var net = new Lampa.Reguest();
        net.timeout(15000);
        net.silent(url, function (json) {
            if (!json || !json.channels) { if (onFail) onFail(); return; }
            onDone(json);
        }, function () { if (onFail) onFail(); });
    }

    function sortChannels(channels) {
        var mode = 'popularity';
        try { mode = Lampa.Storage.get('uefir_sort', 'popularity'); } catch (e) {}

        var copy = channels.slice();
        if (mode === 'alpha') {
            copy.sort(function (a, b) {
                var an = a.channelName || '', bn = b.channelName || '';
                return an < bn ? -1 : (an > bn ? 1 : 0);
            });
        } else {
            copy.sort(function (a, b) { return (b.popularity || 0) - (a.popularity || 0); });
        }
        return copy;
    }

    // ---------- shared state helpers ----------

    var state = null;
    // state: { root, player, channel, program, next_program, fetched_at,
    //          resync_timer, hide_timer, prev_controller, ready, captions_on }

    var channelsPageState = null; // { root, return_to }

    // controller to return to once ALL uefir UI is eventually closed
    function uefirOrigin() {
        if (state) return state.prev_controller;
        if (channelsPageState) return channelsPageState.return_to;
        var name = 'content';
        try { name = Lampa.Controller.enabled().name || 'content'; } catch (e) {}
        return name;
    }

    function teardownLive() {
        if (!state) return;
        clearInterval(state.resync_timer);
        clearTimeout(state.hide_timer);
        try { if (state.player && state.player.destroy) state.player.destroy(); } catch (e) {}
        if (state.root) state.root.remove();
        state = null;
    }

    function teardownChannelsPage() {
        if (!channelsPageState) return;
        if (channelsPageState.root) channelsPageState.root.remove();
        channelsPageState = null;
    }

    function teardownAllUefirUI() {
        teardownChannelsPage();
        teardownLive();
    }

    // ---------- channel picker: popup (Lampa.Select.show) ----------

    function openChannelListPopup() {
        var returnTo = 'content';
        try { returnTo = Lampa.Controller.enabled().name || 'content'; } catch (e) {}
        if (state) returnTo = 'uefir_live';

        noty(t('loading'));

        fetchChannels(null, function (data) {
            var channels = sortChannels(data.channels);
            if (!channels.length) { noty(t('fail')); return; }

            Lampa.Select.show({
                title: t('menu'),
                items: channels.map(function (c) {
                    return { title: c.channelName, subtitle: c.program ? c.program.title : '', channel: c };
                }),
                onSelect: function (a) { openLive(a.channel); },
                onBack: function () { try { Lampa.Controller.toggle(returnTo); } catch (e) {} }
            });
        }, function () { noty(t('fail')); });
    }

    // ---------- channel picker: full-screen page ----------

    function closeChannelsPage() {
        if (!channelsPageState) return;
        var returnTo = channelsPageState.return_to;
        teardownChannelsPage();
        try { Lampa.Controller.toggle(returnTo || 'content'); } catch (e) {}
    }

    function registerChannelsPageController() {
        Lampa.Controller.add('uefir_channels_page', {
            toggle: function () {
                if (!channelsPageState) return;
                Lampa.Controller.collectionSet(channelsPageState.root);
                Lampa.Controller.collectionFocus(false, channelsPageState.root);
            },
            back: closeChannelsPage,
            up: function () { try { window.Navigator.move('up'); } catch (e) {} },
            down: function () { try { window.Navigator.move('down'); } catch (e) {} },
            left: function () { try { window.Navigator.move('left'); } catch (e) {} },
            right: function () { try { window.Navigator.move('right'); } catch (e) {} }
        });
    }

    function addPageStyle() {
        if ($('#uefir-page-style').length) return;
        $('head').append(
            '<style id="uefir-page-style">' +
            '.uefir-page{position:fixed;left:0;top:0;width:100%;height:100%;z-index:9999;' +
            'background:#0b1116;color:#fff;overflow-y:auto;-webkit-overflow-scrolling:touch;}' +
            '.uefir-page__head{display:flex;align-items:center;padding:1.6em 2em;position:relative;}' +
            '.uefir-page__back{position:absolute;left:1.6em;top:50%;margin-top:-1.1em;width:2.2em;height:2.2em;' +
            'display:flex;align-items:center;justify-content:center;border-radius:50%;}' +
            '.uefir-page__back.focus{background:rgba(255,255,255,0.15);}' +
            '.uefir-page__title{flex:1;text-align:center;font-size:1.6em;font-weight:600;}' +
            '.uefir-page__body{padding:0 2em 3em;}' +
            '.uefir-page__grid{display:flex;flex-wrap:wrap;gap:1em;margin-top:1em;}' +
            '.uefir-page__card{width:14em;padding:1em 1.2em;border-radius:0.8em;background:rgba(255,255,255,0.06);}' +
            '.uefir-page__card.focus{background:rgba(255,255,255,0.18);box-shadow:0 0 0 0.12em #fff;}' +
            '.uefir-page__card-name{font-size:1.1em;font-weight:600;}' +
            '.uefir-page__card-sub{opacity:0.65;font-size:0.85em;margin-top:.3em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}' +
            '.uefir-page__empty{opacity:0.6;padding:2em 0;}' +
            '</style>'
        );
    }

    function bindFire(el, handler) {
        var last_fire = 0;
        var fire = function () {
            var now = Date.now();
            if (now - last_fire < 400) return;
            last_fire = now;
            handler();
        };
        el.on('hover:enter', fire);
        el[0].addEventListener('click', fire);
    }

    function buildChannelsPage(channels, returnTo) {
        addPageStyle();

        var root = $(
            '<div class="uefir-page">' +
            '  <div class="uefir-page__head">' +
            '    <div class="uefir-page__back selector">' + BACK_ICON + '</div>' +
            '    <div class="uefir-page__title"></div>' +
            '  </div>' +
            '  <div class="uefir-page__body"><div class="uefir-page__grid"></div></div>' +
            '</div>'
        );

        root.find('.uefir-page__title').text(t('menu'));

        var grid = root.find('.uefir-page__grid');

        if (!channels.length) {
            grid.append('<div class="uefir-page__empty"></div>').find('.uefir-page__empty').text(t('fail'));
        }

        channels.forEach(function (c) {
            var card = $(
                '<div class="uefir-page__card selector">' +
                '<div class="uefir-page__card-name"></div>' +
                '<div class="uefir-page__card-sub"></div>' +
                '</div>'
            );
            card.find('.uefir-page__card-name').text(c.channelName || '');
            card.find('.uefir-page__card-sub').text(c.program ? c.program.title : '');
            bindFire(card, function () { openLive(c); });
            grid.append(card);
        });

        bindFire(root.find('.uefir-page__back'), closeChannelsPage);

        $('body').append(root);

        channelsPageState = { root: root, return_to: returnTo };

        Lampa.Controller.toggle('uefir_channels_page');
    }

    function openChannelsPage() {
        var returnTo = 'content';
        try { returnTo = Lampa.Controller.enabled().name || 'content'; } catch (e) {}
        if (state) {
            returnTo = 'uefir_live';
            try { if (state.player && state.ready) state.player.pauseVideo(); } catch (e) {}
        }

        noty(t('loading'));

        fetchChannels(null, function (data) {
            buildChannelsPage(sortChannels(data.channels), returnTo);
        }, function () { noty(t('fail')); buildChannelsPage([], returnTo); });
    }

    // dispatcher used everywhere a "show the channel list" action is needed
    function openChannelList() {
        var mode = 'page';
        try { mode = Lampa.Storage.get('uefir_open_mode', 'page'); } catch (e) {}
        if (mode === 'select') openChannelListPopup();
        else openChannelsPage();
    }

    // ---------- live player overlay ----------

    var QUALITY_LABELS = {
        highres: '4K', hd2160: '2160p', hd1440: '1440p', hd1080: '1080p', hd720: '720p',
        large: '480p', medium: '360p', small: '240p', tiny: '144p'
    };

    function qualityLabel(lv) {
        if (lv === 'auto') return t('quality_auto');
        return QUALITY_LABELS[lv] || lv;
    }

    function ytApiReady(cb) {
        if (window.YT && window.YT.Player) return cb();

        window.__uefir_yt_cbs = window.__uefir_yt_cbs || [];
        window.__uefir_yt_cbs.push(cb);

        if (window.__uefir_yt_loading) return;
        window.__uefir_yt_loading = true;

        var prevReady = window.onYouTubeIframeAPIReady;
        window.onYouTubeIframeAPIReady = function () {
            if (typeof prevReady === 'function') { try { prevReady(); } catch (e) {} }
            var list = window.__uefir_yt_cbs || [];
            window.__uefir_yt_cbs = [];
            list.forEach(function (fn) { try { fn(); } catch (e) {} });
        };

        var s = document.createElement('script');
        s.src = 'https://www.youtube.com/iframe_api';
        document.head.appendChild(s);
    }

    function targetOffset() {
        if (!state || !state.program) return 0;
        var elapsed = (Date.now() - state.fetched_at) / 1000;
        var offset = state.program.offsetSeconds + elapsed;
        var dur = (Date.parse(state.program.endsAt) - Date.parse(state.program.startsAt)) / 1000;
        if (dur > 0) offset = Math.min(offset, dur - 1);
        return Math.max(0, offset);
    }

    function updateInfo() {
        if (!state || !state.root) return;
        state.root.find('.uefir-live__title').text(state.channel.channelName);
        state.root.find('.uefir-live__program').text(state.program ? state.program.title : '');
        state.root.find('.uefir-live__next').text(state.next_program ? t('next') + state.next_program.title : '');
    }

    function applyProgram(data, keepPlayer) {
        var ch = data.channels[0];
        if (!ch) return;

        state.channel = ch;
        state.next_program = ch.nextProgram;
        state.fetched_at = Date.now();

        var changed = !state.program || state.program.videoId !== (ch.program && ch.program.videoId);
        state.program = ch.program;

        updateInfo();

        if (!state.player || !state.ready) return;

        if (changed && ch.program) {
            state.player.loadVideoById(ch.program.videoId, targetOffset());
        } else if (keepPlayer && ch.program) {
            var drift = Math.abs((state.player.getCurrentTime() || 0) - targetOffset());
            if (drift > 4) state.player.seekTo(targetOffset(), true);
        }
    }

    function resync() {
        if (!state) return;
        fetchChannels([state.channel.id], function (data) { applyProgram(data, true); }, function () {});
    }

    function resyncIntervalMs() {
        var v = 25;
        try { v = parseInt(Lampa.Storage.get('uefir_resync_interval', 25), 10) || 25; } catch (e) {}
        return v * 1000;
    }

    function infoAutohideMs() {
        var v = 5;
        try { v = parseInt(Lampa.Storage.get('uefir_info_autohide', 5), 10); } catch (e) { v = 5; }
        if (isNaN(v)) v = 5;
        return v * 1000;
    }

    function showInfo() {
        if (!state || !state.root) return;
        state.root.find('.uefir-live__info').removeClass('uefir-live__info--hide');
        clearTimeout(state.hide_timer);

        var delay = infoAutohideMs();
        if (!delay) return; // 0 = never hide

        state.hide_timer = setTimeout(function () {
            if (state && state.root) state.root.find('.uefir-live__info').addClass('uefir-live__info--hide');
        }, delay);
    }

    function closeLive() {
        if (!state) return;
        var prev = state.prev_controller;
        teardownLive();
        try { Lampa.Controller.toggle(prev || 'content'); } catch (e) {}
    }

    // ---------- options: quality / subtitles / external player ----------

    function openQualityMenu() {
        if (!state || !state.player) return;

        var levels = [];
        try { levels = state.player.getAvailableQualityLevels() || []; } catch (e) {}
        levels = ['auto'].concat(levels.filter(function (l) { return l !== 'auto'; }));

        Lampa.Select.show({
            title: t('quality'),
            items: levels.map(function (lv) { return { title: qualityLabel(lv), level: lv }; }),
            onSelect: function (a) {
                try { state.player.setPlaybackQuality(a.level); } catch (e) {}
                try { Lampa.Controller.toggle('uefir_live'); } catch (e) {}
            },
            onBack: function () { try { Lampa.Controller.toggle('uefir_live'); } catch (e) {} }
        });
    }

    function paintCaptionsLabel() {
        if (!state || !state.root) return;
        state.root.find('.uefir-live__btn--captions span').text(state.captions_on ? t('cc_on') : t('cc_off'));
    }

    function toggleCaptions() {
        if (!state || !state.player) return;
        state.captions_on = !state.captions_on;
        try {
            if (state.captions_on) state.player.loadModule('captions');
            else state.player.unloadModule('captions');
        } catch (e) {}
        paintCaptionsLabel();
    }

    function openExternal() {
        if (!state || !state.program) return;

        var offset = Math.floor(targetOffset());
        var url = 'https://www.youtube.com/watch?v=' + state.program.videoId + (offset > 0 ? '&t=' + offset + 's' : '');

        var opened = null;
        try { opened = window.open(url, '_blank'); } catch (e) {}

        if (opened) noty(t('external_ok'));
        else noty(t('external_fail') + url);
    }

    // ---------- controller / focus (real Lampa focus engine) ----------

    function registerLiveController() {
        Lampa.Controller.add('uefir_live', {
            toggle: function () {
                if (!state) return;
                Lampa.Controller.collectionSet(state.root);
                Lampa.Controller.collectionFocus(false, state.root);
                showInfo();

                try {
                    if (state.player && state.ready && window.YT &&
                        state.player.getPlayerState() === window.YT.PlayerState.PAUSED) {
                        state.player.seekTo(targetOffset(), true);
                        state.player.playVideo();
                    }
                } catch (e) {}
            },
            back: closeLive,
            up: function () { showInfo(); try { window.Navigator.move('up'); } catch (e) {} },
            down: function () { showInfo(); try { window.Navigator.move('down'); } catch (e) {} },
            left: function () { showInfo(); try { window.Navigator.move('left'); } catch (e) {} },
            right: function () { showInfo(); try { window.Navigator.move('right'); } catch (e) {} }
        });
    }

    function buildOverlay(channel, captionsDefault) {
        addStyle();

        var root = $(
            '<div class="uefir-live">' +
            '  <div id="uefir-live-frame" class="uefir-live__frame"></div>' +
            '  <div class="uefir-live__info">' +
            '    <div class="uefir-live__title"></div>' +
            '    <div class="uefir-live__program"></div>' +
            '    <div class="uefir-live__next"></div>' +
            '    <div class="uefir-live__buttons">' +
            '      <div class="uefir-live__btn uefir-live__btn--channels selector"><span>' + t('channels') + '</span></div>' +
            '      <div class="uefir-live__btn uefir-live__btn--quality selector"><span>' + t('quality') + '</span></div>' +
            '      <div class="uefir-live__btn uefir-live__btn--captions selector"><span>' + (captionsDefault ? t('cc_on') : t('cc_off')) + '</span></div>' +
            '      <div class="uefir-live__btn uefir-live__btn--external selector"><span>' + t('external') + '</span></div>' +
            '    </div>' +
            '  </div>' +
            '</div>'
        );

        $('body').append(root);

        bindFire(root.find('.uefir-live__btn--channels'), openChannelList);
        bindFire(root.find('.uefir-live__btn--quality'), openQualityMenu);
        bindFire(root.find('.uefir-live__btn--captions'), toggleCaptions);
        bindFire(root.find('.uefir-live__btn--external'), openExternal);

        root.on('click', function (e) {
            if (!$(e.target).closest('.uefir-live__btn').length) showInfo();
        });

        return root;
    }

    function addStyle() {
        if ($('#uefir-live-style').length) return;
        $('head').append(
            '<style id="uefir-live-style">' +
            '.uefir-live{position:fixed;left:0;top:0;width:100%;height:100%;z-index:10000;background:#000;}' +
            '.uefir-live__frame{width:100%;height:100%;}' +
            '.uefir-live__frame iframe{width:100%;height:100%;border:0;}' +
            '.uefir-live__info{position:absolute;left:0;right:0;bottom:0;padding:1.5em 2em;' +
            'background:linear-gradient(transparent, rgba(0,0,0,0.85));color:#fff;' +
            'transition:opacity .3s;opacity:1;font-family:inherit;}' +
            '.uefir-live__info--hide{opacity:0;pointer-events:none;}' +
            '.uefir-live__title{font-size:1.4em;font-weight:700;}' +
            '.uefir-live__program{opacity:0.9;margin-top:.2em;}' +
            '.uefir-live__next{opacity:0.6;font-size:0.85em;margin-top:.2em;}' +
            '.uefir-live__buttons{display:flex;flex-wrap:wrap;gap:.6em;margin-top:1em;}' +
            '.uefir-live__btn{display:inline-block;padding:.4em 1.2em;' +
            'border:0.1em solid #fff;border-radius:2em;cursor:pointer;}' +
            '.uefir-live__btn.focus{background:#fff;color:#000;}' +
            '</style>'
        );
    }

    function openLive(channel) {
        var origin = uefirOrigin();
        teardownAllUefirUI();

        var captionsDefault = false;
        try { captionsDefault = !!Lampa.Storage.get('uefir_subtitles_default', false); } catch (e) {}

        var root = buildOverlay(channel, captionsDefault);

        state = {
            root: root,
            player: null,
            channel: channel,
            program: null,
            next_program: null,
            fetched_at: Date.now(),
            resync_timer: null,
            hide_timer: null,
            prev_controller: origin,
            ready: false,
            captions_on: captionsDefault
        };

        applyProgram({ channels: [channel] }, false);

        Lampa.Controller.toggle('uefir_live');

        if (!channel.program) { noty(t('live_fail')); return; }

        ytApiReady(function () {
            if (!state) return; // closed before the API finished loading

            state.player = new window.YT.Player('uefir-live-frame', {
                videoId: channel.program.videoId,
                playerVars: {
                    autoplay: 1, controls: 0, disablekb: 1, fs: 0,
                    modestbranding: 1, rel: 0, playsinline: 1,
                    iv_load_policy: 3, cc_load_policy: captionsDefault ? 1 : 0,
                    origin: window.location.origin
                },
                events: {
                    onReady: function () {
                        state.ready = true;

                        try { state.player.seekTo(targetOffset(), true); } catch (e) {}

                        try {
                            var q = 'auto';
                            try { q = Lampa.Storage.get('uefir_quality_default', 'auto'); } catch (e2) {}
                            if (q && q !== 'auto') state.player.setPlaybackQuality(q);
                        } catch (e) {}

                        try { state.player.playVideo(); } catch (e) {}
                    },
                    onError: function () { noty(t('live_fail')); }
                }
            });
        });

        state.resync_timer = setInterval(resync, resyncIntervalMs());
    }

    // ---------- settings panel (real Lampa.SettingsApi) ----------

    function registerSettings() {
        if (!window.Lampa || !Lampa.SettingsApi) return;

        try {
            Lampa.SettingsApi.addComponent({
                component: 'uefir',
                icon: ICON,
                name: t('menu')
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: {
                    name: 'uefir_open_mode',
                    type: 'select',
                    values: { page: t('mode_page'), select: t('mode_select') },
                    default: 'page'
                },
                field: { name: t('field_open_mode'), description: t('field_open_mode_descr') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: {
                    name: 'uefir_sort',
                    type: 'select',
                    values: { popularity: t('sort_popularity'), alpha: t('sort_alpha') },
                    default: 'popularity'
                },
                field: { name: t('field_sort') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: {
                    name: 'uefir_quality_default',
                    type: 'select',
                    values: { auto: t('quality_auto'), hd1080: '1080p', hd720: '720p', large: '480p', medium: '360p' },
                    default: 'auto'
                },
                field: { name: t('field_quality'), description: t('field_quality_descr') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: { name: 'uefir_subtitles_default', type: 'trigger', default: false },
                field: { name: t('field_subtitles') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: {
                    name: 'uefir_resync_interval',
                    type: 'select',
                    values: { '15': '15 ' + t('unit_sec'), '25': '25 ' + t('unit_sec'), '45': '45 ' + t('unit_sec'), '60': '60 ' + t('unit_sec') },
                    default: '25'
                },
                field: { name: t('field_resync') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: {
                    name: 'uefir_info_autohide',
                    type: 'select',
                    values: { '3': '3 ' + t('unit_sec'), '5': '5 ' + t('unit_sec'), '8': '8 ' + t('unit_sec'), '0': t('autohide_off') },
                    default: '5'
                },
                field: { name: t('field_autohide') }
            });

            Lampa.SettingsApi.addParam({
                component: 'uefir',
                param: { name: 'uefir_open_channels_btn', type: 'button' },
                field: { name: t('field_open_channels') },
                onChange: function () { openChannelList(); }
            });
        } catch (e) {}
    }

    // ---------- startup ----------

    function start() {
        registerLiveController();
        registerChannelsPageController();
        registerSettings();

        if (window.Lampa && Lampa.Menu && typeof Lampa.Menu.addButton === 'function') {
            try { Lampa.Menu.addButton(ICON, t('menu'), openChannelList); } catch (e) {}
        }
    }

    if (window.appready) start();
    else {
        Lampa.Listener.follow('app', function (e) {
            if (e.type === 'ready') start();
        });
    }
})();

29,360 chars · codepastes.com