Greasy Fork is available in English.

Automatically Update Script

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.greasyfork.org/scripts/568072/1764879/Automatically%20Update%20Script.js

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

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