Send to Real-Debrid

Add a button next to each magnet link to send it to Real-Debrid, with user-friendly API token setup and confirmation

As of 14.01.2024. See ბოლო ვერსია.

// ==UserScript==
// @name         Send to Real-Debrid
// @namespace    http://tampermonkey.net/
// @version      0.2
// @description  Add a button next to each magnet link to send it to Real-Debrid, with user-friendly API token setup and confirmation
// @author       dlee2
// @license      MIT
// @match        *://*.nyaa.si/*
// @grant        GM_xmlhttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

/*
MIT License

Copyright (c) [year] [Your Full Name]

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';

    // Function to get or ask for the API token
    function getApiToken() {
        let apiToken = GM_getValue('apiToken');
        if (!apiToken) {
            const instructions = 'To use this script, you need to enter your Real-Debrid API token.\n' +
                  'You can find your API token in your Real-Debrid account settings.\n\n' +
                  'Please enter your Real-Debrid API token:';
            apiToken = prompt(instructions, '');

            if (apiToken) {
                GM_setValue('apiToken', apiToken);
            } else {
                alert('No API token provided. You can set it later by clicking a "Send to RD" button.');
                return null;
            }
        }
        return apiToken;
    }

    // Function to send magnet link to Real-Debrid
    function sendToRealDebrid(magnetLink) {
        const API_TOKEN = getApiToken();
        if (!API_TOKEN) {
            alert("Operation cancelled: API token is not set.");
            return;
        }

        GM_xmlhttpRequest({
            method: "POST",
            url: "https://api.real-debrid.com/rest/1.0/torrents/addMagnet",
            headers: {
                "Authorization": `Bearer ${API_TOKEN}`
            },
            data: "magnet=" + encodeURIComponent(magnetLink),
            onload: function(response) {
                var responseJson = JSON.parse(response.responseText);
                if (responseJson.id) {
                    selectAllFiles(responseJson.id, API_TOKEN);
                    alert("Magnet link successfully sent to Real-Debrid!");
                } else {
                    console.error('Error adding magnet link:', response.responseText);
                    alert("Failed to send magnet link to Real-Debrid.");
                }
            },
            onerror: function(response) {
                console.error('Error sending request to Real-Debrid:', response.responseText);
                alert("Error occurred while sending request to Real-Debrid.");
            }
        });
    }

    // Function to select all files in the torrent
    function selectAllFiles(torrentId, apiToken) {
        GM_xmlhttpRequest({
            method: "POST",
            url: `https://api.real-debrid.com/rest/1.0/torrents/selectFiles/${torrentId}`,
            headers: {
                "Authorization": `Bearer ${apiToken}`
            },
            data: "files=all",
            onload: function(response) {
                console.log("All files selected for torrent ID", torrentId);
            },
            onerror: function(response) {
                console.error('Error selecting files:', response.responseText);
            }
        });
    }

    // Function to create a send button next to a magnet link
    function createSendButton(magnetLink) {
        let button = document.createElement('button');
        button.textContent = 'Send to RD';
        button.style.marginLeft = '10px';
        button.addEventListener('click', function() {
            sendToRealDebrid(magnetLink);
        });

        return button;
    }

    // Add send buttons next to all magnet links
    function addSendButtons() {
        let magnetLinks = document.querySelectorAll('a[href^="magnet:"]');
        magnetLinks.forEach(link => {
            let sendButton = createSendButton(link.href);
            link.parentNode.insertBefore(sendButton, link.nextSibling);
        });
    }

    // Run the function to add send buttons
    addSendButtons();
})();