Automatically Update Script

Library that automatically alerts user when the script requires update. Complies with Greasy Fork rules (greasyfork.org/help/code-rules).

Este script no debería instalarse directamente. Es una biblioteca que utilizan otros scripts mediante la meta-directiva de inclusión // @require https://update.greasyfork.org/scripts/568072/1764879/Automatically%20Update%20Script.js

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

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

Tendrás que instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Tendrás que instalar una extensión como Tampermonkey antes de poder instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name Automatically Update Script
// @namespace -
// @version 1.0.0
// @description Library that automatically alerts user when the script requires update. Complies with Greasy Fork rules (greasyfork.org/help/code-rules).
// @author NotYou
// @match example.com
// @license MIT
// @require https://unpkg.com/[email protected]/lib/index.umd.js
// @require https://update.greasyfork.org/scripts/565798/1752557/Zod%203x%20Error%20Formatter.js
// @require https://update.greasyfork.org/scripts/445697/1756808/Greasy%20Fork%20API.js
// @require https://unpkg.com/compare-versions/lib/umd/index.js
// @connect greasyfork.org
// @grant GM.xmlHttpRequest
// @grant GM.openInTab
// @grant GM.getValue
// @grant GM.setValue
// @grant GM.deleteValue
// @grant GM.info
// ==/UserScript==

/* global GreasyFork, compareVersions */

!async function(GF, compare, logs) {
    'use strict';

    class Updater {
        static getLastUpdateDate() {
            return GM.getValue('lastUpdateDate', new Date(0).toJSON()).then(jsonDateString => new Date(jsonDateString))
        }

        static setLastUpdateDate(date) {
            GM.setValue('lastUpdateDate', new Date(date).toJSON())
        }

        static updateCheck(scriptId) {
            return new Promise((resolve, reject) => {
                GF.script.getHistory(scriptId)
                    .then(history => {
                    const latest = history[0]

                    if (logs) {
                        console.log(`AUS: comparing if ${latest.version} < ${GM.info.version}`)
                    }

                    resolve(
                        compare(
                            latest.version,
                            GM.info.version,
                            '<'
                        )
                    )
                }).catch(err => reject)
            })
        }
    }

    class Main {
        static getCurrentScriptId() {
            return new Promise(async (resolve, reject) => {
                const setScriptId = await GM.getValue('setScriptId')

                if (logs) {
                    console.log(`AUS: Trying to get script ID saved in storage by key "setScriptId" -> ${setScriptId}`)
                }

                if (setScriptId) {
                    resolve(setScriptId)
                }

                const savedScriptId = await GM.getValue('scriptId')

                if (logs) {
                    console.log(`AUS: Trying to get script ID saved in storage by key "scriptId" -> ${savedScriptId}`)
                }

                if (savedScriptId) {
                    resolve(savedScriptId)
                }

                if (logs) {
                    console.log(`AUS: Could not find saved script id, checking @updateURL/@downloadURL`)
                }

                if (GM.info.script.updateURL || GM.info.script.downloadURL) {
                    let match = null

                    const regex = /https?:\/\/(update\.)?(greasyfork|sleazyfork)\.org\/scripts\/(?<scriptId>\d+)/

                    match = GM.info.script.updateURL.match(regex)

                    if (match === null) {
                        match = GM.info.script.downloadURL.match(regex)
                    }

                    if (match === null) {
                        reject('Could not find user script id in @updateURL or @downloadURL')
                    }

                    GM.setValue('scriptId', match.groups.scriptId)

                    resolve(match.groups.scriptId)
                }

                if (logs) {
                    console.log(`AUS: Script does not have @updateURL/@downloadURL, querying Greasy Fork`)
                }

                const scripts = await GF.getScripts({
                    q: GM.info.script.name,
                    filter_locale: false,
                    language: 'js'
                })

                const bestMatch = scripts[0]

                if (
                    bestMatch.name === GM.info.script.name && // if the name matches
                    bestMatch.users.some(author => author.name === GM.info.script.author) && // and if at least one author matches
                    bestMatch.namespace === GM.info.script.namespace // if the namespace matches
                ) {
                    GM.setValue('scriptId', bestMatch.id)

                    resolve(bestMatch.id)
                }

                reject('Could not find matching user script id, not in @updateURL/@downloadURL, nor in Greasy Fork script database')
            })
        }

        static async init() {
            const lastUpdateDate = await Updater.getLastUpdateDate()

            if ((lastUpdateDate.valueOf() + 1000 * 60 * 60 * 24) < new Date()) { // check only once in a day at max
                await new Promise(resolve => setTimeout(resolve, 3000)) // wait 3 seconds to let user-script set script id

                const scriptId = await this.getCurrentScriptId()

                if (logs) {
                    console.log(`AUS: Found script ID ${scriptId}`)
                }

                const isLatest = await Updater.updateCheck(scriptId)

                if (isLatest && logs) {
                    console.log('AUS: Script is up-to-date!')

                    return
                }

                if (logs) {
                    console.log('AUS: Asking user for confirmation to install newer version of user script')
                }

                const userConfirmedToUpdate = confirm(`"${GM.info.script.name}" user script has a newer version available. Update it?`)

                if (userConfirmedToUpdate) {
                    GF.installUserScript({ id: scriptId })
                }
            }
        }
    }

    const setUserScriptId = id => GM.setValue('setScriptId', id)
    const unsetUserScriptId = id => GM.deleteValue('setScriptId')
    const enableLogs = () => {
        logs = true
    }

    window.AUS = {
        setUserScriptId,
        unsetUserScriptId,
        enableLogs
    }

    Main.init()
        .catch(err => console.error('AUS: Could not execute the library because:', err))
}(new GreasyFork(), compareVersions.compare, false);