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