actor_favorites.js

Pasted Nov 27, 2026, 10:53 PM1 file511 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/zzgrv9che7bsfmd3
actor_favorites.js
/*
 * Lampa plugin: favorite actors + new title notifications
 *
 * - Adds a "Add to favorites" button on the actor page (next to Info / Subscribe).
 * - Adds a "Favorite actors" row on the main screen listing them (opens the actor page).
 * - Periodically checks TMDB for new titles (movies/series) in the filmography of
 *   each favorite actor and shows a toast + a "New from your actors" row on the
 *   main screen when something new shows up.
 *
 * This is an independent, local feature: its own storage, its own TMDB lookups.
 * It does not use or touch Lampa's own account-based "Subscribe to actor" button
 * (the one next to it), which is a separate, account-tied feature.
 *
 * ES5 only, so it works on old Tizen / WebOS TV browsers.
 */
(function () {
    'use strict';

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

    var KEY_LIST  = 'actor_favorites_list';   // [{id,name,profile_path,known_for_department,added}]
    var KEY_SEEN  = 'actor_favorites_seen';   // {actorId: [creditKey, ...]}
    var KEY_NEWS  = 'actor_favorites_news';   // [{key, actor_id, actor_name, card, time}]
    var NEWS_LIMIT = 60;

    var CHECK_FIRST_DELAY = 6000;        // after app ready
    var CHECK_INTERVAL    = 4 * 60 * 60 * 1000; // every 4 hours while the app stays open
    var CHECK_STAGGER      = 2500;        // pause between actors in one run

    var TXT = {
        uk: { add: 'Додати в обране', added: 'В обраному', add_ok: 'Додано в обране', remove_ok: 'Прибрано з обраного',
            row_fav: 'Актори в обраному', row_news: 'Нове від акторів', news_removed: 'Прибрано зі списку новин',
            noty_one: 'Нове у ', noty_many: ' новинок від акторів у обраному',
            empty_list: 'Поки немає акторів в обраному', news_tag: 'Нове: ', hint_long: 'довге натискання прибирає актора' },
        ru: { add: 'Добавить в избранное', added: 'В избранном', add_ok: 'Добавлено в избранное', remove_ok: 'Убрано из избранного',
            row_fav: 'Актёры в избранном', row_news: 'Новое от актёров', news_removed: 'Убрано из списка новинок',
            noty_one: 'Новое у ', noty_many: ' новинок от актёров из избранного',
            empty_list: 'Пока нет актёров в избранном', news_tag: 'Новое: ', hint_long: 'долгое нажатие убирает актёра' },
        en: { add: 'Add to favorites', added: 'In favorites', add_ok: 'Added to favorites', remove_ok: 'Removed from favorites',
            row_fav: 'Favorite actors', row_news: 'New from your actors', news_removed: 'Removed from the news list',
            noty_one: 'New from ', noty_many: ' new titles from your favorite actors',
            empty_list: 'No favorite actors yet', news_tag: 'New: ', hint_long: 'long-press to remove an actor' }
    };

    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) {
        var set = TXT[lang()];
        return set[key];
    }

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

    // ---------- storage helpers ----------

    function getList() {
        try { return Lampa.Storage.get(KEY_LIST, []) || []; } catch (e) { return []; }
    }
    function setList(v) {
        try { Lampa.Storage.set(KEY_LIST, v); } catch (e) {}
    }
    function getSeen() {
        try { return Lampa.Storage.get(KEY_SEEN, {}) || {}; } catch (e) { return {}; }
    }
    function setSeen(v) {
        try { Lampa.Storage.set(KEY_SEEN, v); } catch (e) {}
    }
    function getNews() {
        try { return Lampa.Storage.get(KEY_NEWS, []) || []; } catch (e) { return []; }
    }
    function setNews(v) {
        try { Lampa.Storage.set(KEY_NEWS, v); } catch (e) {}
    }

    function isFavorite(id) {
        var list = getList();
        for (var i = 0; i < list.length; i++) if (list[i].id === id) return true;
        return false;
    }

    function creditKey(item) {
        return (item.original_name || item.name ? 'tv' : 'movie') + '_' + item.id;
    }

    // Seed the "already known" baseline for an actor so adding them doesn't flood
    // the news list with their entire existing filmography.
    function seedSeen(person, cb) {
        var tmdb = window.Lampa && Lampa.TMDB;
        if (!tmdb || !tmdb.person) return cb && cb();

        tmdb.person({ id: person.id }, function (full) {
            var credits = full && full.credits;
            var keys = [];
            if (credits) {
                (credits.movie || []).forEach(function (i) { keys.push(creditKey(i)); });
                (credits.tv || []).forEach(function (i) { keys.push(creditKey(i)); });
            }
            var seen = getSeen();
            seen[person.id] = keys;
            setSeen(seen);
            if (cb) cb();
        }, function () { if (cb) cb(); });
    }

    function addFavorite(person) {
        if (isFavorite(person.id)) return;
        var list = getList();
        list.unshift({
            id: person.id,
            name: person.name,
            profile_path: person.profile_path || '',
            known_for_department: person.known_for_department || '',
            added: Date.now()
        });
        setList(list);
        seedSeen(person);
        noty(t('add_ok'));
    }

    function removeFavorite(id) {
        var list = getList().filter(function (p) { return p.id !== id; });
        setList(list);
        var seen = getSeen();
        delete seen[id];
        setSeen(seen);
        noty(t('remove_ok'));
    }

    // ---------- actor page button ----------

    function iconSvg(filled) {
        return '<svg width="22" height="22" viewBox="0 0 24 24" fill="' + (filled ? 'currentColor' : 'none') +
            '" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"><path d="M12 2.5l2.9 6.6 7.1.7-5.4 4.8 1.6 7-6.2-3.7-6.2 3.7 1.6-7-5.4-4.8 7.1-.7z"/></svg>';
    }

    function paintButton(btn, fav) {
        btn.toggleClass('button--fav-actor--active', fav);
        btn.find('svg').replaceWith(iconSvg(fav));
        btn.find('span').text(fav ? t('added') : t('add'));
    }

    function currentActorPage() {
        var a;
        try { a = Lampa.Activity.active(); } catch (e) { return null; }
        if (!a || a.component !== 'actor' || !a.id) return null;
        var root = null;
        try { if (a.activity && a.activity.render) root = a.activity.render(); } catch (e) {}
        if (!root || !root.length) return null;
        return { id: a.id, root: root };
    }

    // minimal person data straight from the page, used only if the add happens
    // before our own TMDB lookup for seeding finishes
    function personFromRoot(root, id) {
        var name = root.find('.person-start__name').eq(0).text() || '';
        var img = root.find('.person-start__img').attr('src') || '';
        var m = img.match(/\/t\/p\/[^\/]+\/([^\/?]+)/);
        return { id: id, name: name, profile_path: m ? '/' + m[1] : '' };
    }

    function injectButton(page) {
        var bottom = page.root.find('.person-start__bottom').eq(0);
        if (!bottom.length || bottom.find('.button--fav-actor').length) return;

        var btn = $('<div class="full-start__button selector button--fav-actor">' + iconSvg(false) + '<span></span></div>');
        paintButton(btn, isFavorite(page.id));

        var last_fire = 0;
        var fire = function () {
            var now = Date.now();
            if (now - last_fire < 400) return;
            last_fire = now;

            if (isFavorite(page.id)) {
                removeFavorite(page.id);
                paintButton(btn, false);
            } else {
                addFavorite(personFromRoot(page.root, page.id));
                paintButton(btn, true);
            }
        };

        btn.on('hover:enter', fire);
        btn[0].addEventListener('click', fire);

        var subscribe = bottom.find('.button--subscribe').eq(0);
        if (subscribe.length) subscribe.after(btn);
        else bottom.append(btn);

        try {
            if (Lampa.Controller.collectionAppend && Lampa.Controller.enabled().name !== 'menu') {
                Lampa.Controller.collectionAppend(btn[0]);
            }
        } catch (e) {}
    }

    var inject_timer = null;
    function scheduleInject() {
        if (inject_timer) clearTimeout(inject_timer);
        inject_timer = setTimeout(function () {
            var page = currentActorPage();
            if (page) injectButton(page);
        }, 150);
    }

    // ---------- main-screen rows ----------

    function openActor(person) {
        try {
            Lampa.Activity.push({ url: '', component: 'actor', id: person.id, known_for_department: person.known_for_department });
        } catch (e) {}
    }

    function openCard(card) {
        try {
            Lampa.Activity.push({
                url: '', component: 'full', id: card.id,
                method: (card.original_name || card.name) ? 'tv' : 'movie',
                card: card
            });
        } catch (e) {}
    }

    function favoritesRowItems() {
        return getList().map(function (p) {
            var copy = { id: p.id, name: p.name, profile_path: p.profile_path, known_for_department: p.known_for_department };
            copy.params = { emit: { onEnter: function () { openActor(copy); }, onFocus: function () {
                try { Lampa.Background.change(Lampa.Utils.cardImgBackground(copy)); } catch (e) {}
            } } };
            return copy;
        });
    }

    function newsRowItems() {
        return getNews().map(function (n) {
            var card = n.card;
            card.params = { emit: { onEnter: function () { openCard(card); }, onFocus: function () {
                try { Lampa.Background.change(Lampa.Utils.cardImgBackground(card)); } catch (e) {}
            }, onMenu: function () {
                var news = getNews().filter(function (x) { return x.key !== n.key; });
                setNews(news);
                noty(t('news_removed'));
            } } };
            return card;
        });
    }

    // ---------- reliable list screen (sidebar menu -> Select.show) ----------
    // Does not depend on ContentRows / the main screen rebuilding its rows,
    // so it works even on builds where that row never appears.

    function currentController() {
        try { return Lampa.Controller.enabled().name || 'content'; } catch (e) { return 'content'; }
    }

    var COMPONENT_NAME = 'actor_favorites_list';

    // Cards shown in the grid: news first (tagged as movie/tv cards so they get
    // posters and open like any other card), then favorite actors (profile photos).
    function buildCategoryResults() {
        var results = [];

        getNews().forEach(function (n) {
            var card = n.card || {};
            card._kind = 'news';
            card._news_key = n.key;
            card._actor_name = n.actor_name;
            results.push(card);
        });

        getList().forEach(function (p) {
            var card = {
                id: p.id,
                name: p.name,
                profile_path: p.profile_path,
                known_for_department: p.known_for_department,
                _kind: 'actor'
            };
            results.push(card);
        });

        return results;
    }

    // Full-screen grid component, built the same way Lampa builds its own
    // "Favorites" screen (interaction/items/category), so it opens and looks
    // exactly like the native Favorites section.
    function favoritesComponent(object) {
        var comp = Lampa.Utils.createInstance(Lampa.InteractionCategory, object, {});

        comp.use({
            onCreate: function () {
                var self = this;
                var results = buildCategoryResults();
                setTimeout(function () { self.build({ results: results, total_pages: 1 }); }, 10);
            },
            onNext: function (resolve, reject) {
                reject.call(this); // everything is loaded in one go, no extra pages
            },
            onInstance: function (item, data) {
                item.use({
                    onEnter: function () {
                        if (data._kind === 'news') {
                            openCard(data);
                            setNews(getNews().filter(function (x) { return x.key !== data._news_key; }));
                        } else {
                            openActor(data);
                        }
                    },
                    onFocus: function () {
                        try { Lampa.Background.change(Lampa.Utils.cardImgBackground(data)); } catch (e) {}
                    },
                    onMenu: function () {
                        if (data._kind === 'news') {
                            setNews(getNews().filter(function (x) { return x.key !== data._news_key; }));
                        } else {
                            removeFavorite(data.id);
                        }
                        try { Lampa.Activity.replace(); } catch (e) {}
                    }
                });
            }
        });

        return comp;
    }

    function registerComponent() {
        if (!window.Lampa || !Lampa.Component || typeof Lampa.Component.add !== 'function') return;
        try { Lampa.Component.add(COMPONENT_NAME, favoritesComponent); } catch (e) {}
    }

    function openList() {
        try {
            Lampa.Activity.push({ url: '', component: COMPONENT_NAME, title: t('row_fav') });
        } catch (e) {}
    }

    function registerMenuButton() {
        if (!window.Lampa || !Lampa.Menu || typeof Lampa.Menu.addButton !== 'function') return;

        var icon = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" ' +
            'stroke-linejoin="round"><path d="M12 2.5l2.9 6.6 7.1.7-5.4 4.8 1.6 7-6.2-3.7-6.2 3.7 1.6-7-5.4-4.8 7.1-.7z"/></svg>';

        try { Lampa.Menu.addButton(icon, t('row_fav'), openList); } catch (e) {}
    }

    function registerRows() {
        if (!window.Lampa || !Lampa.ContentRows || typeof Lampa.ContentRows.add !== 'function') return;

        Lampa.ContentRows.add({
            name: 'favorite_actors',
            title: t('row_fav'),
            screen: ['main'],
            index: 2,
            call: function () {
                var items = favoritesRowItems();
                if (!items.length) return;
                return { title: t('row_fav'), results: items };
            }
        });

        Lampa.ContentRows.add({
            name: 'favorite_actors_news',
            title: t('row_news'),
            screen: ['main'],
            index: 1,
            call: function () {
                var items = newsRowItems();
                if (!items.length) return;
                return { title: t('row_news'), results: items };
            }
        });
    }

    // ---------- background check for new titles ----------

    function checkOne(person, done) {
        var tmdb = window.Lampa && Lampa.TMDB;
        if (!tmdb || !tmdb.person) return done([]);

        tmdb.person({ id: person.id }, function (full) {
            var credits = full && full.credits;
            if (!credits) return done([]);

            var seen = getSeen();
            var known = seen[person.id] || [];
            var known_set = {};
            known.forEach(function (k) { known_set[k] = true; });

            var all = (credits.movie || []).concat(credits.tv || []);
            var fresh = [];
            var keys = known.slice();

            all.forEach(function (item) {
                var key = creditKey(item);
                if (!known_set[key]) {
                    known_set[key] = true;
                    keys.push(key);
                    fresh.push(item);
                }
            });

            seen[person.id] = keys;
            setSeen(seen);

            done(fresh);
        }, function () { done([]); });
    }

    function runCheck() {
        var list = getList();
        if (!list.length) return;

        var i = 0;
        var found_titles = [];

        function next() {
            if (i >= list.length) return finish();
            var person = list[i++];

            checkOne(person, function (fresh) {
                if (fresh.length) {
                    var news = getNews();
                    fresh.forEach(function (item) {
                        found_titles.push(item.title || item.name || '');
                        news.unshift({
                            key: creditKey(item) + '_' + person.id,
                            actor_id: person.id,
                            actor_name: person.name,
                            card: item,
                            time: Date.now()
                        });
                    });
                    if (news.length > NEWS_LIMIT) news = news.slice(0, NEWS_LIMIT);
                    setNews(news);
                }
                setTimeout(next, CHECK_STAGGER);
            });
        }

        function finish() {
            if (!found_titles.length) return;
            if (found_titles.length === 1) noty(t('noty_one') + found_titles[0]);
            else noty(found_titles.length + t('noty_many'));
        }

        next();
    }

    // Seed is skipped only for actors added before this plugin ran its first
    // check (e.g. if storage was edited by hand); seedSeen on add covers the
    // normal path, this is just a safety net so old entries don't spam once.
    function seedMissing(cb) {
        var list = getList();
        var seen = getSeen();
        var missing = list.filter(function (p) { return !seen[p.id]; });
        if (!missing.length) return cb && cb();

        var i = 0;
        function next() {
            if (i >= missing.length) return cb && cb();
            seedSeen(missing[i++], next);
        }
        next();
    }

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

    function start() {
        try {
            Lampa.Listener.follow('activity', function (e) {
                if (e && (e.type === 'start' || e.type === 'archive')) scheduleInject();
            });
        } catch (e) {}

        if (window.MutationObserver) {
            new MutationObserver(scheduleInject).observe(document.body, { childList: true, subtree: true });
        } else {
            setInterval(scheduleInject, 1000);
        }
        scheduleInject();

        registerRows();
        registerComponent();
        registerMenuButton();

        setTimeout(function () {
            seedMissing(function () {
                runCheck();
                setInterval(runCheck, CHECK_INTERVAL);
            });
        }, CHECK_FIRST_DELAY);
    }

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

18,980 chars · codepastes.com