nascent / MrSkin Ratings in IMDb

// ==UserScript==
// @name         MrSkin Ratings in IMDb
// @namespace    imdb.com
// @version      2.0.0
// @description  Display a MrSkin rating and profile link on IMDb.
// @match        https://www.imdb.com/name/*
// @match        https://www.imdb.com/title/*
// @match        https://imdb.com/name/*
// @match        https://imdb.com/title/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=mrskin.com
// @license      MIT
// @grant        GM_xmlhttpRequest
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_registerMenuCommand
// @connect      mrskin.com
// @connect      www.mrskin.com
// @run-at       document-idle
// @license      GPL-3.0-or-later
// ==/UserScript==

(() => {
    'use strict';

    const BASE = 'https://www.mrskin.com';
    const BOX_ID = 'imdb-mrskin-rating';

    // Set false if you only want ratings on person pages.
    const ENABLE_TITLE_PAGES = true;

    let currentKey = '';
    let requestNumber = 0;
    let currentState = null;

    let hideMrSkinPrefix = GM_getValue('hideMrSkinPrefix', true);

    GM_registerMenuCommand(
        `${hideMrSkinPrefix ? 'Show' : 'Hide'} "MrSkin" prefix`,
        () => {
            hideMrSkinPrefix = !hideMrSkinPrefix;
            GM_setValue('hideMrSkinPrefix', hideMrSkinPrefix);
            update().catch(console.error);
        }
    );

    function normalize(value) {
        return String(value || '')
            .normalize('NFKD')
            .replace(/[\u0300-\u036f]/g, '')
            .toLowerCase()
            .replace(/&/g, ' and ')
            .replace(/[^a-z0-9]+/g, ' ')
            .trim();
    }

    function request(url) {
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'GET',
                url,
                timeout: 25000,
                headers: {
                    Accept: 'application/json,text/html;q=0.9,*/*;q=0.8'
                },
                onload(response) {
                    if (response.status >= 200 &&
                        response.status < 300) {
                        resolve(response.responseText);
                    } else {
                        reject(new Error(`HTTP ${response.status}`));
                    }
                },
                onerror() {
                    reject(new Error('Network error'));
                },
                ontimeout() {
                    reject(new Error('Request timed out'));
                }
            });
        });
    }

    function getStructuredData() {
        const objects = [];

        function collect(value) {
            if (!value || typeof value !== 'object') return;

            if (Array.isArray(value)) {
                value.forEach(collect);
                return;
            }

            objects.push(value);
            if (value['@graph']) collect(value['@graph']);
        }

        for (const script of document.querySelectorAll(
            'script[type="application/ld+json"]'
        )) {
            try {
                collect(JSON.parse(script.textContent));
            } catch {
                // Ignore malformed JSON.
            }
        }

        return objects;
    }

    function getIMDbInfo() {
        const match = location.pathname.match(
            /^\/(name|title)\/(nm\d+|tt\d+)/
        );

        if (!match) return null;

        const isTitle = match[1] === 'title';
        if (isTitle && !ENABLE_TITLE_PAGES) return null;

        const heading =
            document.querySelector('h1[data-testid="hero__pageTitle"]') ||
            document.querySelector('h1');

        if (!heading) return null;

        const nameElement =
            heading.querySelector('[data-testid="hero__primary-text"]') ||
            heading;

        const name = nameElement.textContent
            .replace(/\s+/g, ' ')
            .replace(/\s+\(I+\)$/, '')
            .trim();

        if (!name) return null;

        const data = getStructuredData().find(item => {
            const types = [item['@type']].flat();

            return normalize(item.name) === normalize(name) &&
                (isTitle
                    ? types.some(type =>
                        ['Movie', 'TVSeries', 'TVEpisode'].includes(type))
                    : types.includes('Person'));
        });

        // Preserve the old script's exclusion of known minors.
        if (!isTitle && data?.birthDate) {
            const birth = new Date(data.birthDate);
            const now = new Date();

            if (!Number.isNaN(birth.getTime())) {
                const adulthood = new Date(
                    birth.getFullYear() + 18,
                    birth.getMonth(),
                    birth.getDate()
                );

                if (now < adulthood) return null;
            }
        }

        return {
            id: match[2],
            name,
            heading,
            isTitle,
            year: String(data?.datePublished || '').slice(0, 4)
        };
    }

    function safeURL(value) {
        const url = new URL(value, BASE);

        if (!['mrskin.com', 'www.mrskin.com'].includes(url.hostname)) {
            throw new Error('Unexpected result domain');
        }

        if (!['http:', 'https:'].includes(url.protocol)) {
            throw new Error('Unexpected result URL');
        }

        url.protocol = 'https:';
        return url.href;
    }

    async function findProfile(info) {
        const text = await request(
            `${BASE}/search/api.json?term=${encodeURIComponent(info.name)}`
        );

        let data;
        try {
            data = JSON.parse(text);
        } catch {
            throw new Error('Search returned HTML or invalid JSON');
        }

        if (!Array.isArray(data.results)) {
            throw new Error('Unexpected search response');
        }

        const matches = data.results.filter(result => {
            const type = result.type || result._type;
            const rightType = info.isTitle
                ? type === 'title'
                : type === 'celebrity';

            const name = info.isTitle
                ? String(result.name || '').replace(
                    /\s*\(\d{4}\)\s*$/, ''
                )
                : result.name;

            return rightType &&
                normalize(name) === normalize(info.name);
        });

        let selected;

        if (info.isTitle && info.year) {
            selected = matches.find(result =>
                String(result.name).match(/\((\d{4})\)\s*$/)?.[1] ===
                info.year
            );
        }

        // Do not silently choose the first of several ambiguous matches.
        if (!selected && matches.length === 1) {
            const resultYear = String(matches[0].name)
                .match(/\((\d{4})\)\s*$/)?.[1];

            if (!info.isTitle || !info.year ||
                !resultYear || resultYear === info.year) {
                selected = matches[0];
            }
        }

        if (!selected) return null;

        return {
            name: selected.name,
            url: safeURL(selected.url || selected.search_url)
        };
    }

    function extractRating(html, isTitle) {
        const doc = new DOMParser().parseFromString(html, 'text/html');

        let rating = null;
        let summary = '';
        let roles = '';

        /*
         * The original script used MrSkin's page-level tracking data.
         * Scope this fallback to _track_page, rather than accidentally
         * reading a rating from a related profile elsewhere on the page.
         */
        for (const script of doc.querySelectorAll('script')) {
            const text = script.textContent || '';
            const tracking = text.match(
                /\b_track_page\s*=\s*(\{[\s\S]*?\})\s*;?/
            )?.[1];

            if (!tracking) continue;

            const field = isTitle ? 'titleNudityRating' : 'starRating';
            const value = tracking.match(
                new RegExp(
                    `["']?${field}["']?\\s*:\\s*["']?(\\d+(?:\\.\\d+)?)`
                )
            );

            if (value) rating = Number(value[1]);

            roles = tracking.match(
                /["']?nudeAppearancesCount["']?\s*:\s*["']?(\d+)/
            )?.[1] || '';

            break;
        }

        // Original MrSkin title-page rating widget.
        const widget = doc.querySelector('.object-rating');

        if (widget) {
            summary = widget.querySelector('.rating-string')
                ?.textContent?.trim() || '';

            if (rating === null) {
                const stars = widget.querySelectorAll(
                    '.fa-star.active'
                ).length;

                if (stars > 0) rating = stars;
            }
        }

        // Original MrSkin person-page keyword rating.
        if (!isTitle) {
            const pedigree = doc.querySelector('.pedigree-wrapper');
            const link = pedigree?.querySelector('a[href*="rating="]');

            if (link) {
                const value = new URL(
                    link.getAttribute('href'), BASE
                ).searchParams.get('rating');

                if (rating === null &&
                    value !== null && value.trim() !== '') {
                    rating = Number(value);
                }

                summary ||= link.textContent.trim();
            }

            if (!roles && pedigree) {
                const labels = pedigree.querySelectorAll('.detail-type');

                for (const label of labels) {
                    if (/^Nude Roles:/i.test(label.textContent.trim())) {
                        roles = label.nextElementSibling
                            ?.textContent?.trim() || '';
                        break;
                    }
                }
            }
        }

        // The old script used a four-star scale.
        if (!Number.isFinite(rating) || rating < 0 || rating > 4) {
            rating = null;
        }

        return { rating, summary, roles };
    }

    function render(info) {
        let box = document.getElementById(BOX_ID);

        if (!box) {
            box = document.createElement('div');
            box.id = BOX_ID;
            box.style.cssText = `
                margin: 6px 0 10px;
                font: 14px/1.5 Arial, sans-serif;
                color: #f5c518;
            `;
        }

        if (box.previousElementSibling !== info.heading) {
            info.heading.insertAdjacentElement('afterend', box);
        }

        box.replaceChildren();

        if (!currentState) return;

        const link = document.createElement('a');
        link.href = currentState.url ||
            `${BASE}/search/search?term=${encodeURIComponent(info.name)}`;
        link.target = '_blank';
        link.rel = 'noopener noreferrer';
        link.style.cssText = 'color: #f5c518; text-decoration: none;';

        const stats = currentState.stats;

        if (stats?.rating !== null && stats?.rating !== undefined) {
            const rounded = Math.round(stats.rating);
            const stars = '★'.repeat(rounded) + '☆'.repeat(4 - rounded);

            link.textContent = `${hideMrSkinPrefix ? '' : 'MrSkin: '}${stars}`;
            link.title = [
                currentState.name,
                stats.summary,
                stats.roles ? `Nude roles: ${stats.roles}` : ''
            ].filter(Boolean).join('\n');
        } else {
            link.textContent = `MrSkin: ${currentState.message}`;
        }

        box.appendChild(link);
    }

    async function update() {
        const info = getIMDbInfo();

        if (!info) {
            if (currentKey) {
                currentKey = '';
                currentState = null;
                requestNumber++;
            }

            document.getElementById(BOX_ID)?.remove();
            return;
        }

        const key = `${info.id}:${info.name}`;

        if (key === currentKey) {
            render(info);
            return;
        }

        currentKey = key;
        const serial = ++requestNumber;

        currentState = { message: 'looking up…' };
        render(info);

        try {
            const profile = await findProfile(info);
            if (serial !== requestNumber) return;

            if (!profile) {
                currentState = {
                    message: 'no unambiguous exact match — search'
                };
            } else {
                currentState = {
                    ...profile,
                    message: 'loading rating…'
                };
                render(info);

                try {
                    const html = await request(profile.url);
                    if (serial !== requestNumber) return;

                    const stats = extractRating(html, info.isTitle);

                    currentState = {
                        ...profile,
                        stats,
                        message: 'rating unavailable — open profile'
                    };
                } catch (error) {
                    if (serial !== requestNumber) return;

                    console.warn('[IMDb MrSkin] Profile request:', error);
                    currentState = {
                        ...profile,
                        message: `${error.message} — open profile`
                    };
                }
            }
        } catch (error) {
            if (serial !== requestNumber) return;

            console.warn('[IMDb MrSkin] Search request:', error);
            currentState = {
                message: `${error.message} — search`
            };
        }

        if (serial === requestNumber) render(info);
    }

    update().catch(console.error);

    // Handles IMDb client-side navigation and headings replaced after load.
    setInterval(() => {
        update().catch(console.error);
    }, 1500);
})();