kylemckellar / FS Show Perms Button

// ==UserScript==
// @name         FS Show Perms Button
// @description  Perms button
// @namespace    Kyle McKellar
// @author       Kyle McKellar
// @version      0.3
// @include      http*://*.familysearch.org/search/catalog/*
// @grant        none
// @run-at       document-end
// @license      MIT
// ==/UserScript==

// CHANGELOG: Will now work on pages that have just one item. Updated to work with new catalog. Permissions now show as bold (on the new website). Code still works on old catalog since Familysearch may have not pushed the update to everyone
// Message me on Facebook if you have issues: https://www.facebook.com/profile.php?id=100083691946074

(function() {
    'use strict';

    var myElement = document.createElement("button");
    myElement.setAttribute("class", "showPermsButton fs-button fs-button--recommended");
    myElement.setAttribute("style", "position: fixed; top: 50%; left: 0; transform: translateY(-50%); padding: 6px; z-index: 1000; writing-mode: vertical-rl; text-align: center; margin: 0; background-color: #007BFF; color: white; border: none; border-radius: 4px; transition: background-color 0.3s;");
    myElement.innerHTML = '<span title="Perms">Fetch Perms</span>';
    document.body.appendChild(myElement);

    document.getElementsByClassName('showPermsButton')[0].addEventListener('click', function (){ fetchPerms(); });

    function fetchPerms() {
        //old website
        try {
            data.film_note.forEach(i => {
                $('span[ng-bind-html="copy.unpadded_dgs_num"]:contains(' + i.digital_film_no + ')')
                    .text(i.digital_film_no + ' ' + i.digital_film_rights);
            });
        } catch (err) {
            console.log("Old website structure not found. Proceeding with new website logic.");
        }

        //new website
        const url = window.location.href;
        const catalogIdMatch = url.match(/catalog\/(\d+)/);
        const catalogId = catalogIdMatch ? catalogIdMatch[1] : null;

        if (!catalogId) {
            console.error("No catalog ID found in the URL.");
            return;
        }

        const apiUrl = `https://www.familysearch.org/service/search/catalog/item/${catalogId}`;

        fetch(apiUrl)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                let filmNotes = data.source.film_note;

                // Check if filmNotes is an object (single entry) or an array (multiple entries)
                if (!Array.isArray(filmNotes)) {
                    filmNotes = [filmNotes]; // Convert single entry to an array
                }

                filmNotes.forEach(note => {
                    const digitalFilmNo = note.digital_film_no;
                    let digitalFilmRights = note.digital_film_rights;

                    let rightsArray = [];

                    if (typeof digitalFilmRights === 'string') {
                        rightsArray.push(digitalFilmRights);
                    } else if (typeof digitalFilmRights === 'object') {
                        for (let key in digitalFilmRights) {
                            if (digitalFilmRights.hasOwnProperty(key)) {
                                rightsArray.push(digitalFilmRights[key]);
                            }
                        }
                    }

                    const combinedRights = rightsArray.join(', ');

                    const matchingTDElements = Array.from(document.querySelectorAll('td')).filter(td => td.textContent.includes(digitalFilmNo));
                    if (matchingTDElements.length > 0) {
                        matchingTDElements.forEach(tdElement => {
                            console.log(tdElement);
                            tdElement.innerHTML = `${digitalFilmNo} <strong>${combinedRights}</strong>`;
                        });
                    }
                });
            })
            .catch(error => {
                console.error("Fetch error:", error);
            });
    }
})();