ActorFavorites_v2.js

Pasted Nov 28, 2026, 6:48 AM1 file359 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/zzgrv1mrnjmq7jeh
ActorFavorites_v2.js
code = r'''/*
 * ActorFavorites v2.js — Lampa
 * Favorite actors + notifications for new movie/TV credits.
 * ES5-compatible (legacy Tizen/WebOS/Android TV browsers).
 *
 * Storage keys remain compatible with v1:
 * actor_favorites_list, actor_favorites_seen, actor_favorites_news
 */
(function () {
    'use strict';

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

    var KEY_LIST = 'actor_favorites_list';
    var KEY_SEEN = 'actor_favorites_seen';
    var KEY_NEWS = 'actor_favorites_news';
    var NEWS_LIMIT = 60;
    var CHECK_FIRST_DELAY = 6000;
    var CHECK_INTERVAL = 4 * 60 * 60 * 1000;
    var CHECK_STAGGER = 1800;
    var REQUEST_TIMEOUT = 25000;
    var started = false, checking = false, injectTimer = null, observer = null;

    var TXT = {
        uk: {add:'Додати в обране',added:'В обраному',add_ok:'Додано в обране',remove_ok:'Прибрано з обраного',
            row_fav:'Актори в обраному',row_news:'Нове від акторів',news_removed:'Прибрано зі списку новин',
            noty_one:'Нове: ',noty_many:' нових назв від акторів в обраному',empty:'Список акторів порожній',
            hint:'Меню картки: видалити',news_tag:'Нове: '},
        ru: {add:'Добавить в избранное',added:'В избранном',add_ok:'Добавлено в избранное',remove_ok:'Убрано из избранного',
            row_fav:'Актёры в избранном',row_news:'Новое от актёров',news_removed:'Удалено из списка новинок',
            noty_one:'Новое: ',noty_many:' новых названий от избранных актёров',empty:'Список актёров пуст',
            hint:'Меню карточки: удалить',news_tag:'Новое: '},
        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 news',
            noty_one:'New: ',noty_many:' new titles from favorite actors',empty:'No favorite actors yet',
            hint:'Card menu: remove',news_tag:'New: '}
    };

    function lang() {
        var l = 'uk';
        try { l = Lampa.Storage.get('language', 'uk') || 'uk'; } catch (e) {}
        return l === 'uk' ? 'uk' : (l === 'ru' || l === 'be' ? 'ru' : 'en');
    }
    function t(k) { return TXT[lang()][k] || k; }
    function notify(s) { try { Lampa.Noty.show(s); } catch (e) {} }
    function isArray(a) { return Object.prototype.toString.call(a) === '[object Array]'; }

    function getList() {
        var a; try { a = Lampa.Storage.get(KEY_LIST, []); } catch (e) { a = []; }
        if (!isArray(a)) a = [];
        var out = [], seen = {};
        a.forEach(function (p) {
            if (!p || p.id === undefined || p.id === null || seen[String(p.id)]) return;
            seen[String(p.id)] = true;
            out.push({id:p.id, name:p.name || ('ID ' + p.id), profile_path:p.profile_path || '',
                known_for_department:p.known_for_department || '', added:p.added || 0});
        });
        if (out.length !== a.length) setList(out);
        return out;
    }
    function setList(v) { try { Lampa.Storage.set(KEY_LIST, v); } catch (e) {} }
    function getSeen() {
        var v; try { v = Lampa.Storage.get(KEY_SEEN, {}); } catch (e) { v = {}; }
        return v && typeof v === 'object' && !isArray(v) ? v : {};
    }
    function setSeen(v) { try { Lampa.Storage.set(KEY_SEEN, v); } catch (e) {} }
    function getNews() {
        var v; try { v = Lampa.Storage.get(KEY_NEWS, []); } catch (e) { v = []; }
        if (!isArray(v)) v = [];
        var out = [];
        v.forEach(function (n) {
            if (!n || !n.card || n.key === undefined) return;
            out.push(n);
        });
        if (out.length !== v.length) setNews(out);
        return out;
    }
    function setNews(v) {
        if (!isArray(v)) v = [];
        v = v.slice(0, NEWS_LIMIT);
        try { Lampa.Storage.set(KEY_NEWS, v); } catch (e) {}
    }
    function isFavorite(id) {
        var list = getList(), i;
        for (i = 0; i < list.length; i++) if (String(list[i].id) === String(id)) return true;
        return false;
    }
    function mediaType(item) {
        if (!item) return 'movie';
        if (item.media_type === 'tv' || item.media_type === 'movie') return item.media_type;
        if (item.first_air_date !== undefined || item.original_name !== undefined || item.name !== undefined && item.title === undefined) return 'tv';
        return 'movie';
    }
    function creditKey(item) {
        if (!item || item.id === undefined || item.id === null) return '';
        return mediaType(item) + '_' + item.id;
    }
    function creditsFrom(full) {
        var credits = full && full.credits || {};
        var movie = isArray(credits.movie) ? credits.movie : (isArray(credits.cast) ? credits.cast : []);
        var tv = isArray(credits.tv) ? credits.tv : (isArray(credits.tv_cast) ? credits.tv_cast : []);
        return movie.concat(tv);
    }
    function uniqueCredits(items) {
        var map = {}, out = [];
        items.forEach(function (item) {
            var key = creditKey(item);
            if (!key || map[key]) return;
            map[key] = true;
            out.push(item);
        });
        return out;
    }

    /* TMDB request wrapper: timeout and callback-once protection. */
    function fetchPerson(person, callback) {
        var tmdb = window.Lampa && Lampa.TMDB, finished = false, timer;
        function done(ok, value) {
            if (finished) return;
            finished = true;
            if (timer) clearTimeout(timer);
            callback(ok, value);
        }
        if (!tmdb || typeof tmdb.person !== 'function') return done(false, null);
        timer = setTimeout(function () { done(false, null); }, REQUEST_TIMEOUT);
        try {
            tmdb.person({id:person.id}, function (full) { done(true, full); }, function () { done(false, null); });
        } catch (e) { done(false, null); }
    }
    function seedSeen(person, callback) {
        fetchPerson(person, function (ok, full) {
            if (ok && full) {
                var keys = uniqueCredits(creditsFrom(full)).map(function (i) { return creditKey(i); }).filter(Boolean);
                var seen = getSeen(); seen[String(person.id)] = keys; setSeen(seen);
            }
            if (callback) callback(ok);
        });
    }

    function addFavorite(person) {
        if (!person || person.id === undefined || isFavorite(person.id)) return;
        var list = getList();
        list.unshift({id:person.id, name:person.name || ('ID ' + person.id), profile_path:person.profile_path || '',
            known_for_department:person.known_for_department || '', added:Date.now()});
        setList(list);
        /* Seed baseline before checking so existing works are not announced. */
        seedSeen(person);
        notify(t('add_ok'));
    }
    function removeFavorite(id) {
        var list = getList().filter(function (p) { return String(p.id) !== String(id); });
        setList(list);
        var seen = getSeen(); delete seen[String(id)]; setSeen(seen);
        /* Remove actor attribution from stored news; keep titles with other actors. */
        var news = getNews().filter(function (n) {
            if (String(n.actor_id) === String(id)) return false;
            if (isArray(n.actor_ids)) {
                n.actor_ids = n.actor_ids.filter(function (x) { return String(x) !== String(id); });
                if (!n.actor_ids.length) return false;
            }
            return true;
        });
        setNews(news);
        notify(t('remove_ok'));
    }

    /* Actor-page button injection. */
    function starSvg(fill) {
        return '<svg width="22" height="22" viewBox="0 0 24 24" fill="' + (fill ? '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);
        try { btn.find('svg').replaceWith(starSvg(fav)); btn.find('span').text(fav ? t('added') : t('add')); } catch (e) {}
    }
    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};
    }
    function personFromRoot(root, id) {
        var name = '', img = '';
        try { name = root.find('.person-start__name').eq(0).text() || ''; img = root.find('.person-start__img').attr('src') || ''; } catch (e) {}
        var m = img.match(/\/t\/p\/[^\/]+\/([^\/?]+)/);
        return {id:id, name:name, profile_path:m ? '/' + m[1] : ''};
    }
    function injectButton(page) {
        var bottom; try { bottom = page.root.find('.person-start__bottom').eq(0); } catch (e) { return; }
        if (!bottom || !bottom.length || bottom.find('.button--fav-actor').length) return;
        var btn = $('<div class="full-start__button selector button--fav-actor">' + starSvg(false) + '<span></span></div>');
        paintButton(btn, isFavorite(page.id));
        var fired = false;
        function fire() {
            if (fired) return;
            fired = true; setTimeout(function () { fired = false; }, 500);
            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);
        try { btn[0].addEventListener('click', fire); } catch (e) {}
        var subscribe; try { subscribe = bottom.find('.button--subscribe').eq(0); } catch (e) {}
        if (subscribe && 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) {}
    }
    function scheduleInject() {
        if (injectTimer) clearTimeout(injectTimer);
        injectTimer = setTimeout(function () { var page = currentActorPage(); if (page) injectButton(page); }, 180);
    }

    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) {
        if (!card || card.id === undefined) return;
        var copy = cloneCard(card);
        try { Lampa.Activity.push({url:'', component:'full', id:copy.id, method:mediaType(copy), card:copy}); } catch (e) {}
    }
    function cloneCard(card) {
        var c = {}, k;
        for (k in card) if (Object.prototype.hasOwnProperty.call(card,k) && k !== 'params' && k.charAt(0) !== '_') c[k] = card[k];
        return c;
    }
    function actorItems() {
        return getList().map(function (p) {
            var c = {id:p.id, name:p.name, profile_path:p.profile_path, known_for_department:p.known_for_department};
            c.params = {emit:{onEnter:function(){openActor(c);}, onFocus:function(){try{Lampa.Background.change(Lampa.Utils.cardImgBackground(c));}catch(e){}}}};
            return c;
        });
    }
    function newsItems() {
        return getNews().map(function (n) {
            var c = cloneCard(n.card);
            c.params = {emit:{onEnter:function(){openCard(c);}, onFocus:function(){try{Lampa.Background.change(Lampa.Utils.cardImgBackground(c));}catch(e){}},
                onMenu:function(){setNews(getNews().filter(function(x){return x.key !== n.key;}));notify(t('news_removed'));}}};
            return c;
        });
    }

    /* Menu list/grid component. */
    var COMPONENT_NAME = 'actor_favorites_list_v2';
    function buildResults() {
        var results = [];
        getNews().forEach(function (n) { var c=cloneCard(n.card); c._kind='news'; c._news_key=n.key; results.push(c); });
        getList().forEach(function (p) { results.push({id:p.id,name:p.name,profile_path:p.profile_path,
            known_for_department:p.known_for_department,_kind:'actor'}); });
        return results;
    }
    function favoritesComponent(object) {
        var comp = Lampa.Utils.createInstance(Lampa.InteractionCategory, object, {});
        comp.use({
            onCreate:function(){var self=this; var results=buildResults(); setTimeout(function(){try{self.build({results:results,total_pages:1});}catch(e){}},10);},
            onNext:function(resolve,reject){if(reject)reject.call(this);},
            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() { try { if (Lampa.Component && Lampa.Component.add) 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() {
        try { if (Lampa.Menu && Lampa.Menu.addButton) Lampa.Menu.addButton(starSvg(false),t('row_fav'),openList); } catch(e){}
    }
    function registerRows() {
        try {
            if (!Lampa.ContentRows || !Lampa.ContentRows.add) return;
            Lampa.ContentRows.add({name:'favorite_actors_v2',title:t('row_fav'),screen:['main'],index:2,call:function(){
                var items=actorItems(); return items.length?{title:t('row_fav'),results:items}:undefined;
            }});
            Lampa.ContentRows.add({name:'favorite_actors_news_v2',title:t('row_news'),screen:['main'],index:1,call:function(){
                var items=newsItems(); return items.length?{title:t('row_news'),results:items}:undefined;
            }});
        } catch(e){}
    }

    /* Checking and persistence: collect changes first, commit once per actor. */
    function checkOne(person, callback) {
        fetchPerson(person,function(ok,full){
            if(!ok || !full || !full.credits) return callback(false,[]);
            var items=uniqueCredits(creditsFrom(full)), seen=getSeen(), key=String(person.id);
            var known=isArray(seen[key])?seen[key]:[], set={}, fresh=[];
            known.forEach(function(k){set[k]=true;});
            items.forEach(function(item){var k=creditKey(item);if(k&&!set[k]){set[k]=true;fresh.push(item);}});
            /* Persist the baseline even when there are no new works. */
            seen[key]=items.map(function(i){return creditKey(i);}).filter(Boolean); setSeen(seen);
            callback(true,fresh);
        });
    }
    function addNewsFor(person, items) {
        if(!items.length) return [];
        var news=getNews(), notices=[];
        items.forEach(function(item){
            var key=creditKey(item); if(!key) return;
            /* Deduplicate the same title across actors; merge attribution. */
            var existing=null, i;
            for(i=0;i<news.length;i++) if(news[i].content_key===key || news[i].key===key+'_'+person.id){existing=news[i];break;}
            if(existing){
                existing.actor_ids=isArray(existing.actor_ids)?existing.actor_ids:[existing.actor_id];
                if(existing.actor_ids.map(String).indexOf(String(person.id))===-1)existing.actor_ids.push(person.id);
                existing.actor_names=isArray(existing.actor_names)?existing.actor_names:[existing.actor_name];
                if(existing.actor_names.indexOf(person.name)===-1)existing.actor_names.push(person.name);
                existing.actor_id=person.id; existing.actor_name=person.name;
            } else {
                news.unshift({key:key+'_'+person.id,content_key:key,actor_id:person.id,actor_ids:[person.id],
                    actor_name:person.name,actor_names:[person.name],card:cloneCard(item),time:Date.now()});
                notices.push(item.title||item.name||'');
            }
        });
        setNews(news.slice(0,NEWS_LIMIT));
        return notices;
    }
    function runCheck() {
        if(checking) return;
        var list=getList(); if(!list.length)return;
        checking=true; var i=0, titles=[];
        function next(){
            if(i>=list.length){checking=false;if(titles.length===1)notify(t('noty_one')+titles[0]);else if(titles.length>1)notify(titles.length+t('noty_many'));return;}
            var person=list[i++];
            checkOne(person,function(ok,fresh){
                if(ok && fresh.length) titles=titles.concat(addNewsFor(person,fresh));
                setTimeout(next,CHECK_STAGGER);
            });
        }
        next();
    }
    function seedMissing(callback) {
        var list=getList(), seen=getSeen(), missing=list.filter(function(p){return !isArray(seen[String(p.id)]);}), i=0;
        function next(){if(i>=missing.length){if(callback)callback();return;}seedSeen(missing[i++],next);}
        next();
    }

    function start() {
        if(started) return; started=true;
        try { Lampa.Listener.follow('activity',function(e){if(e&&(e.type==='start'||e.type==='archive'))scheduleInject();}); } catch(e){}
        try {
            if(window.MutationObserver && document.body){observer=new MutationObserver(scheduleInject);observer.observe(document.body,{childList:true,subtree:true});}
            else setInterval(scheduleInject,1500);
        } catch(e){}
        scheduleInject();
        registerRows();registerComponent();registerMenuButton();
        setTimeout(function(){seedMissing(function(){runCheck();setInterval(runCheck,CHECK_INTERVAL);});},CHECK_FIRST_DELAY);
    }
    if(window.appready) start();
    else try { Lampa.Listener.follow('app',function(e){if(e&&e.type==='ready')start();}); } catch(e){}
})();
'''
path = "/mnt/data/ActorFavorites_v2.js"
with open(path, "w", encoding="utf-8") as f:
    f.write(code)
print(path, len(code.splitlines()), len(code))

18,434 chars · codepastes.com