Restore YouTube Username from Handle to Custom

To restore YouTube Username to the traditional custom name

Mint 2023.06.15.. Lásd a legutóbbi verzió

/*
 
MIT License
 
Copyright 2023 CY Fung
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
 
*/
// ==UserScript==
// @name                Restore YouTube Username from Handle to Custom
// @namespace           http://tampermonkey.net/
// @version             0.1.0
// @license             MIT License
// @description         To restore YouTube Username to the traditional custom name

// @author              CY Fung
// @match               https://www.youtube.com/*
// @exclude             /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
// @icon                https://github.com/cyfung1031/userscript-supports/raw/main/icons/general-icon.png
// @supportURL          https://github.com/cyfung1031/userscript-supports
// @run-at              document-start
// @grant               none
// @unwrap
// @allFrames
// @inject-into page
// ==/UserScript==

/* jshint esversion:8 */

(function () {
    'use strict';

    const cfg = {};
    class Mutex {

        constructor() {
            this.p = Promise.resolve()
        }

        lockWith(f) {

            this.p = this.p.then(() => new Promise(f)).catch(console.warn)
        }

    }
    const mutex = new Mutex();

    function getDisplayName(channelId) {

        return new Promise(resolve => {


            mutex.lockWith(lockResolve => {



                //INNERTUBE_API_KEY = ytcfg.data_.INNERTUBE_API_KEY


                fetch(new window.Request(`/youtubei/v1/browse?key=${cfg.INNERTUBE_API_KEY}&prettyPrint=false`, {
                    "method": "POST",
                    "mode": "same-origin",
                    "credentials": "same-origin",

                    // (-- reference: https://ja.javascript.info/fetch-api
                    referrerPolicy: "no-referrer",
                    cache: "default",
                    redirect: "error",
                    integrity: "",
                    keepalive: false,
                    signal: undefined,
                    window: window,
                    // --)

                    "headers": {
                        "Content-Type": "application/json"
                    },
                    "body": JSON.stringify({
                        "context": {
                            "client": {
                                "clientName": "MWEB",
                                "clientVersion": `${cfg.INNERTUBE_CLIENT_VERSION || '2.20230614.01.00'}`,
                                "originalUrl": `https://m.youtube.com/channel/${channelId}`,
                                "playerType": "UNIPLAYER",
                                "platform": "MOBILE",
                                "clientFormFactor": "SMALL_FORM_FACTOR",
                                "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
                                "mainAppWebInfo": {
                                    "graftUrl": `/channel/${channelId}`,
                                    "webDisplayMode": "WEB_DISPLAY_MODE_BROWSER",
                                    "isWebNativeShareAvailable": true
                                }
                            },
                            "user": {
                                "lockedSafetyMode": false
                            },
                            "request": {
                                "useSsl": true,
                                "internalExperimentFlags": [],
                                "consistencyTokenJars": []
                            }
                        },
                        "browseId": `${channelId}`
                    })
                })).then(res => {
                    lockResolve();
                    return res.json();
                }).then(res => {

                    let { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = res.metadata.channelMetadataRenderer;


                    resolve({ title, externalId, ownerUrls, channelUrl, vanityChannelUrl });

                })



            });


        });
    }

    const dataChangedFuncStore = new WeakMap();


    const dataChangeFuncProducer = (dataChanged) => {

        return function () {
            let p = this.querySelector('#author-text[href^="/channel/"]');
            if (p && (this.data || 0).qwej3 !== 1) p.classList.remove('qwej3');
            return dataChanged.apply(this, arguments)
        }


    }

    const domCheck = async (anchor) => {


        let channelHref = anchor.getAttribute('href');
        if (!channelHref) return;
        let parentNode = anchor.parentNode;
        while (parentNode instanceof Node) {
            if (typeof parentNode.is === 'string') break;
            parentNode = parentNode.parentNode
        }
        if (parentNode instanceof Node && typeof parentNode.is === 'string') { } else return;
        let authorText = (parentNode.data || 0).authorText;
        if (authorText && typeof authorText.simpleText === 'string') { } else return;
        const currentDisplayed = authorText.simpleText;
        if (!/\s*\@[a-zA-Z0-9_\-]+\s*/.test(currentDisplayed)) return;

        let m = /\/channel\/([^\/\?\#]+)/.exec(channelHref);
        if (!m || !m[1]) return;

        let oldDataChanged = parentNode.dataChanged;
        if (typeof oldDataChanged === 'function' && !oldDataChanged.qwej3) {
            let newDataChanged = dataChangedFuncStore.get(oldDataChanged)
            if (!newDataChanged) {

                newDataChanged = dataChangeFuncProducer(oldDataChanged);

                dataChangedFuncStore.set(oldDataChanged, newDataChanged);

            }
            parentNode.dataChanged = newDataChanged;
        }

        const fetchResult = await getDisplayName(m[1]);


        const { title, externalId, ownerUrls, channelUrl, vanityChannelUrl } = fetchResult;

        if (anchor.getAttribute('href') !== `/channel/${externalId}`) return;
        if (parentNode.isAttached === true && parentNode.isConnected === true && typeof parentNode.data === 'object') {


            if (authorText.simpleText !== currentDisplayed) return;
            let currentDisplayTrimmed = currentDisplayed.trim();
            let match = false;
            for (const ownerUrl of ownerUrls) {

                if (ownerUrl.endsWith(`/${currentDisplayTrimmed}`)) {
                    match = true;
                    break;
                }
            }
            if (match && currentDisplayed !== title) {
                authorText.simpleText = title;
                parentNode.data = Object.assign({}, parentNode.data, { qwej3: 1 });
            }

        }


    }

    const domChecker = () => {

        for (const anchor of document.querySelectorAll('#author-text[href^="/channel/"]:not(.qwej3)')) {
            anchor.classList.add('qwej3');

            domCheck(anchor);
        }

    };


    /** @type {MutationObserver | null} */
    let domObserver = null;

    document.addEventListener('yt-page-data-fetched', function () {

        try {
            for (const key of ['INNERTUBE_API_KEY', 'INNERTUBE_CLIENT_VERSION']) {
                cfg[key] = window.ytcfg.data_[key];
            }
        } catch (e) { }

        if (!cfg['INNERTUBE_API_KEY']) return;

        if (!domObserver) {
            domObserver = new MutationObserver((mutationList) => {
                domChecker();
            });
        } else {
            domObserver.takeRecords();
            domObserver.disconnect();
        }

        domObserver.observe(document.body, { childList: true, subtree: true });
        domChecker();

    });


})();