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
// @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://www.real.discount/offer/*
// @icon          https://www.google.com/s2/favicons?sz=64&domain=real.discount
// @grant         none
// @license       MIT
// ==/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.
*/

(() => {
    'use strict';

    let redirected = false; // Prevent multiple redirects

    /**
     * Searches the DOM for a direct Udemy coupon link.
     * @returns {string|null} The matching URL, or null if not found.
     */
    function getUdemyCouponUrl() {
        return [...document.querySelectorAll('a')].find(a =>
            a.href?.startsWith('https://www.udemy.com/course/') &&
            a.href.includes('couponCode=')
        )?.href || null;
    }

    /**
     * Extracts a Udemy URL from a given Linksynergy deep link string.
     * @param {string} linksynergyUrlString The Linksynergy URL to parse.
     * @returns {string|null} The extracted Udemy URL, or null if not found or invalid.
     */
    function getUdemyUrlFromLinksynergy(linksynergyUrlString) {
      try {
        const url = new URL(linksynergyUrlString);
        const murlParam = url.searchParams.get('murl');

        if (murlParam) {
          const decodedUrl = decodeURIComponent(murlParam);
          // Validate that the decoded URL is indeed a Udemy course URL with a coupon
          if (decodedUrl.startsWith('https://www.udemy.com/course/') && decodedUrl.includes('couponCode=')) {
            return decodedUrl;
          }
        }
      } catch (e) {
        console.warn('[real.discount] Error parsing Linksynergy URL:', e.message);
      }
      return null;
    }

    /**
     * Attempts to redirect to the Udemy coupon URL if found, either directly or via Linksynergy.
     */
    function tryRedirect() {
        if (redirected) return;

        let targetUrl = getUdemyCouponUrl(); // First, try to find a direct Udemy URL

        if (!targetUrl) {
            // If no direct Udemy URL found, search for Linksynergy links and extract the Udemy URL
            const linksynergyLinkElement = [...document.querySelectorAll('a')].find(a =>
                a.href?.startsWith('https://click.linksynergy.com/deeplink?') &&
                a.href.includes('murl=https%3A%2F%2Fwww.udemy.com%2Fcourse%2F')
            );

            if (linksynergyLinkElement) {
                targetUrl = getUdemyUrlFromLinksynergy(linksynergyLinkElement.href);
            }
        }

        if (!targetUrl) return; // If no target URL found after both attempts, exit

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

    // MutationObserver: watches for dynamically added links
    const observer = new MutationObserver(tryRedirect);
    observer.observe(document.body, { childList: true, subtree: true });

    // Try redirect immediately on initial script run
    tryRedirect();

    // Safety timeout: stop watching after 15 seconds if nothing happens
    setTimeout(() => {
        if (!redirected) {
            console.log('[real.discount] Timeout: No coupon URL found. Observer disconnected.');
            observer.disconnect();
        }
    }, 15000);
})();