RottenTomatoes Utility Library (custom API)

Utility library for Rotten Tomatoes. Provides an API for grabbing info from rottentomatoes.com

目前為 2019-09-14 提交的版本,檢視 最新版本

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/389810/733066/RottenTomatoes%20Utility%20Library%20%28custom%20API%29.js

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         RottenTomatoes Utility Library (custom API)
// @namespace    driver8.net
// @version      0.1.2
// @description  Utility library for Rotten Tomatoes. Provides an API for grabbing info from rottentomatoes.com
// @author       driver8
// @grant        GM_xmlhttpRequest
// @connect      rottentomatoes.com
// ==/UserScript==

console.log('hi rt api lib');

const MAX_YEAR_DIFF = 2;
const MAX_RESULTS = 50;

function _parse(query, regex, doc) {
    doc = doc || document;
    try {
        let text = doc.querySelector(query).textContent.trim();
        if (regex) {
            text = text.match(regex)[1];
        }
        return text.trim();
    } catch (e) {
        console.log('error', e);
        return '';
    }
};

function getRtIdFromTitle(title, tv, year) {
    tv = tv || false;
    year = parseInt(year) || 1800;
    return new Promise(function(resolve, reject) {
        GM_xmlhttpRequest({
            method: 'GET',
            responseType: 'json',
            url: `https://www.rottentomatoes.com/api/private/v2.0/search/?limit=${MAX_RESULTS}&q=${title}`,
            onload: (resp) => {
                let movies = tv ? resp.response.tvSeries : resp.response.movies;
                if (!movies) {
                    console.log('no search results');
                    reject('no results');
                }

                let sorted = movies.concat();
                if (year && sorted) {
                    sorted.sort((a, b) => {
                        if (Math.abs(a.year - year) !== Math.abs(b.year - year)) {
                            // Prefer closest year to the given one
                            return Math.abs(a.year - year) - Math.abs(b.year - year);
                        } else {
                            return b.year - a.year; // In a tie, later year should come first
                        }
                    });
                }

                // Search for matches with exact title in order of proximity by year
                let bestMatch;
                for (let m of sorted) {
                    m.title = m.title || m.name;
                    if (m.title.toLowerCase() === title.toLowerCase()) {
                        bestMatch = m;
                        break;
                    }
                }
                //console.log('sorted', sorted, 'bestMatch', bestMatch, movies);

                // Fall back on closest year match if with 2 years, or whatever the first result was.
                bestMatch = bestMatch || (sorted && Math.abs(sorted[0].year - year) <= MAX_YEAR_DIFF && sorted[0]); // || (movies && movies[0]);

                if (bestMatch) {
                    let id = bestMatch && bestMatch.url.replace(/\/s\d{2}\/?$/, ''); // remove season suffix from tv matches
                    console.log('found id', id);
                    resolve(id);
                } else {
                    console.log('no match found on rt');
                    reject('no suitable match');
                }
            }
        });
    });
}

function getRtInfoFromId(id) {
    return new Promise(function(resolve, reject) {
        if (!id || typeof id !== 'string' || id.length < 3) {
            console.log('invalid id');
            reject('invalid id');
        }
        let url = 'https://www.rottentomatoes.com' + id + (id.startsWith('/tv/') ? '/s01' : ''); // Look up season 1 for TV shows
        GM_xmlhttpRequest({
            method: 'GET',
            responseType: 'document',
            url: url,
            onload: (resp) => {
                let text = resp.responseText;

                // Create DOM from responseText
                const doc = document.implementation.createHTMLDocument().documentElement;
                doc.innerHTML = text;
                let year = parseInt(_parse('.h3.year, .movie_title .h3.subtle, .meta-row .meta-value time', /(\d{4})/, doc));

                // Find the javascript snippet storing the tomatometer/score info.
                // Everything is named different for TV shows for some stupid reason.
                let m = text.match(/root\.RottenTomatoes\.context\.scoreInfo = ({.+});/);
                m = m || text.match(/root\.RottenTomatoes\.context\.scoreboardCriticInfo = ({.+});/);
                let dataString = m[1];
                let scoreInfo = JSON.parse(dataString);
                let all = scoreInfo.tomatometerAllCritics || scoreInfo.all || false,
                    top = scoreInfo.tomatometerTopCritics || scoreInfo.top || {};
                //console.log('scoreInfo', scoreInfo);

                // TV consensus is stored in a totally different object :/
                m = text.match(/root\.RottenTomatoes\.context\.result = ({.+});/);
                let contextResult = m && JSON.parse(m[1]);

                if (all) {
                    // Try field names used for movie data, then TV show data.
                    const data = {
                        id: id,
                        score: all.score || all.tomatometer,
                        rating: all.avgScore || all.averageRating,
                        votes: all.numberOfReviews || all.totalCount,
                        consensus: all.consensus || (contextResult && contextResult.seasonData && contextResult.seasonData.tomatometer.consensus), // TV consensus is stored in a totally different object :/
                        state: all.tomatometerState || all.state,
                        topScore: top.score || top.tomatometer,
                        topRating: top.avgScore || top.averageRating,
                        topVotes: top.numberOfReviews || top.totalCount,
                        year: year,
                        fetched: new Date()
                    };

                    console.log('found data', data);
                    resolve(data);
                } else {
                    reject('error getting rt info for id ' + id);
                }
            }
        });
    });
}

function getRtInfoFromTitle(title, tv, year) {
    return getRtIdFromTitle(title, tv, year).then((id) => {
        return getRtInfoFromId(id);
    })
}