Real Discount 'Get Course' Auto-Redirect

Automatically redirects to a Udemy course link with a coupon on real.discount offer pages, including dynamic content handling and Linksynergy deep links.

// ==UserScript==
// @name          Real Discount 'Get Course' Auto-Redirect
// @namespace     https://www.linkedin.com/in/bernando-jr-minguita/
// @version       1.1.1
// @description   Automatically redirects to a Udemy course link with a coupon on real.discount offer pages, including dynamic content handling and Linksynergy deep links.
// @author        Bernando Jr Minguita
// @match         https://*.real.discount/offer/*
// @icon          https://www.google.com/s2/favicons?sz=64&domain=real.discount
// @grant         none
// @license       MIT
// @run-at        document-end
// ==/UserScript==

/*
MIT License

Copyright (c) 2025 Bernando Jr Minguita

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.
*/

(function () {
    'use strict';

    var redirected = false; // Prevents multiple redirects
    var observer = null;    // Watches for dynamic content

    /**
     * Searches for a direct Udemy coupon URL in anchor tags.
     * @param {NodeList} links - List of anchor elements to scan
     * @returns {string|null} Valid Udemy coupon URL or null
     */
    function getUdemyCouponUrl(links) {
        for (var i = 0; i < links.length; i++) {
            var href = links[i].href;
            if (
                href &&
                href.indexOf('https://www.udemy.com/course/') === 0 &&
                href.indexOf('couponCode=') !== -1
            ) {
                return href;
            }
        }
        return null;
    }

    /**
     * Extracts and decodes a Udemy URL from a Linksynergy affiliate link.
     * @param {string} linksynergyUrlString
     * @returns {string|null} Valid Udemy URL or null
     */
    function getUdemyUrlFromLinksynergy(linksynergyUrlString) {
        try {
            var url = new URL(linksynergyUrlString);
            var murlParam = url.searchParams.get('murl');
            if (murlParam) {
                var decodedUrl = decodeURIComponent(murlParam);
                if (
                    decodedUrl.indexOf('https://www.udemy.com/course/') === 0 &&
                    decodedUrl.indexOf('couponCode=') !== -1
                ) {
                    return decodedUrl;
                }
            }
        } catch (e) {
            console.warn('[real.discount] Error parsing Linksynergy URL:', e.message);
        }
        return null;
    }

    /**
     * Scans for Udemy links and redirects if found.
     */
    function tryRedirect() {
        if (redirected) return;

        var links = document.querySelectorAll('a');
        var targetUrl = getUdemyCouponUrl(links);

        if (!targetUrl) {
            for (var i = 0; i < links.length; i++) {
                var href = links[i].href;
                if (
                    href &&
                    href.indexOf('https://click.linksynergy.com/deeplink?') === 0 &&
                    href.indexOf('murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2F') !== -1
                ) {
                    targetUrl = getUdemyUrlFromLinksynergy(href);
                    if (targetUrl) break;
                }
            }
        }

        if (!targetUrl) return;

        if (observer) observer.disconnect();

        if (location.href !== targetUrl) {
            console.log('[real.discount] Redirecting to Udemy coupon URL:', targetUrl);
            redirected = true;
            window.location.replace(targetUrl);
        } else {
            console.log('[real.discount] Already on target URL. No redirection needed.');
            redirected = true;
        }
    }

    // Initialize MutationObserver for dynamic content
    if (document.body) {
        observer = new MutationObserver(function () {
            tryRedirect();
            if (redirected && observer) observer.disconnect();
        });

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

    // Immediate check on load
    tryRedirect();

    // Failsafe: disconnect observer after 15s
    setTimeout(function () {
        if (!redirected) {
            console.log('[real.discount] Timeout: No coupon URL found. Observer disconnected.');
            if (observer) observer.disconnect();
        }
    }, 15000);
})();