Automatically Update Script

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

Dit script moet niet direct worden geïnstalleerd - het is een bibliotheek voor andere scripts om op te nemen met de meta-richtlijn // @require https://update.greasyfork.org/scripts/568072/1764879/Automatically%20Update%20Script.js

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey, Greasemonkey of Violentmonkey.

Voor het installeren van scripts heb je een extensie nodig, zoals {tampermonkey_link:Tampermonkey}.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Violentmonkey.

Voor het installeren van scripts heb je een extensie nodig, zoals Tampermonkey of Userscripts.

Voor het installeren van scripts heb je een extensie nodig, zoals {tampermonkey_link:Tampermonkey}.

Voor het installeren van scripts heb je een gebruikersscriptbeheerder nodig.

(Ik heb al een user script manager, laat me het downloaden!)

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een extensie nodig, zoals {stylus_link:Stylus}.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

Voor het installeren van gebruikersstijlen heb je een gebruikersstijlbeheerder nodig.

(Ik heb al een beheerder - laat me doorgaan met de installatie!)

// ==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);