Discord Link Refresher

A Userscript to fix broken discord attachment links

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Discord Link Refresher
// @description  A Userscript to fix broken discord attachment links
// @license      WTFPL
// @author       Anon
// @namespace    discord-link-refresher
// @version      1
// @match        https://cdn.discordapp.com/attachments/*
// @grant        GM.xmlHttpRequest
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_registerMenuCommand
// @connect      discord.com
// ==/UserScript==

(function() {
    'use strict';

    async function refresh_url() {
        const token = GM_getValue('token', null);
        if (!token) {
            alert('[Discord Link Refresher] No token set!');
            return;
        }

        const response = await GM.xmlHttpRequest({
            method: 'POST',
            url: 'https://discord.com/api/v9/attachments/refresh-urls',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': token
            },
            data: JSON.stringify({ attachment_urls: [window.location.href] })
        });

        if (response.status !== 200) {
            alert('API request failed: ' + response.status);
            return;
        }
        const new_link = JSON.parse(response.responseText)['refreshed_urls'][0]['refreshed'];
        if (new_link && window.location.href !== new_link) {
            console.log('[Discord Link Refresher] Redirecting to refreshed link...');
            window.location.href = new_link;
        } else {
            console.log('[Discord Link Refresher] Link already refreshed, likely a real 404');
        }
    }

    GM_registerMenuCommand('Set token', function() {
        const input = prompt('Set token:');
        if (input !== null) {
            GM_setValue('token', input.trim());
            alert('Token saved.');
        }
    });

    GM_registerMenuCommand('Force refresh', refresh_url);

    if (document.body.innerText.includes('This content is no longer available.')) {
        refresh_url();
    }
})();