service-core/core/application.mjs

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2022-01-24 06:59:58 +00:00
import { EventEmitter } from 'events'
import fs from 'fs/promises'
export default class Application extends EventEmitter {
2022-01-24 06:59:58 +00:00
constructor(util, db, provider, name, opts = {}) {
super()
this.util = util
this.db = db
this.config = db.config[name]
this.provider = provider
this.name = name
this.updating = false
Object.assign(this, {
setInterval: opts.setInterval || setInterval,
})
this.db.addApplication(name)
}
startAutoupdater() {
let timer = this.setInterval(() => {
this.update().then(
() => {
this.db.data.core[this.name].updater += 'Automatic update finished successfully. '
},
(err) => {
this.db.data.core[this.name].updater += 'Error while running automatic update: ' + err.message + '. '
}
)
}, (this.config.updateEvery || 180) * 60 * 1000)
timer.unref()
}
updateLog(message) {
this.db.data.core[this.name].updater += message
this.db.log.info(message)
}
async update() {
if (this.updating) return
this.updating = true
this.db.data.core[this.name].updater = ''
try {
this.updateLog(`Checking for latest version at ${new Date().toISOString().replace('T', ' ').split('.')[0]}. `)
let latest = await this.provider.getLatestVersion()
this.updateLog(`Found ${latest.version}. `)
if (this.db.data.core[this.name].latestInstalled === latest.version) {
this.updateLog('Already up to date, nothing to do. ')
return
}
let target = this.util.getPathFromRoot(`./${this.name}/${latest.version}/file${this.util.getExtension(latest.filename)}`)
await fs.mkdir(this.util.getPathFromRoot(`./${this.name}/${latest.version}`), { recursive: true })
this.updateLog(`Downloading ${latest.link} to ${target}. `)
await this.provider.downloadVersion(latest, target)
} catch (err) {
this.updating = false
return Promise.reject(err)
}
}
}