[editor] Rework to use esbuild / Vue component files (#12)

This commit is contained in:
Knut Ahlers 2021-12-06 17:25:19 +01:00 committed by GitHub
parent 00019053ab
commit 8c32889584
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
24 changed files with 8875 additions and 1841 deletions

2
.dockerignore Normal file
View file

@ -0,0 +1,2 @@
node_modules
twitch-bot

150
.eslintrc.js Normal file
View file

@ -0,0 +1,150 @@
/*
* Hack to automatically load globally installed eslint modules
* on Archlinux systems placed in /usr/lib/node_modules
*
* Source: https://github.com/eslint/eslint/issues/11914#issuecomment-569108633
*/
const Module = require('module')
const hacks = [
'babel-eslint',
'eslint-plugin-vue',
]
const ModuleFindPath = Module._findPath
Module._findPath = (request, paths, isMain) => {
const r = ModuleFindPath(request, paths, isMain)
if (!r && hacks.includes(request)) {
return require.resolve(`/usr/lib/node_modules/${request}`)
}
return r
}
/*
* ESLint configuration derived as differences from eslint:recommended
* with changes I found useful to ensure code quality and equal formatting
* https://eslint.org/docs/user-guide/configuring
*/
module.exports = {
env: {
browser: true,
node: true,
},
extends: [
'plugin:vue/recommended',
'eslint:recommended', // https://eslint.org/docs/rules/
],
globals: {
process: true,
},
parserOptions: {
ecmaVersion: 2020,
parser: 'babel-eslint',
},
plugins: [
// required to lint *.vue files
'vue',
],
reportUnusedDisableDirectives: true,
root: true,
rules: {
'array-bracket-newline': ['error', { multiline: true }],
'array-bracket-spacing': ['error'],
'arrow-body-style': ['error', 'as-needed'],
'arrow-parens': ['error', 'as-needed'],
'arrow-spacing': ['error', { after: true, before: true }],
'block-spacing': ['error'],
'brace-style': ['error', '1tbs'],
'comma-dangle': ['error', 'always-multiline'],
'comma-spacing': ['error'],
'comma-style': ['error', 'last'],
'curly': ['error'],
'default-case-last': ['error'],
'default-param-last': ['error'],
'dot-location': ['error', 'property'],
'dot-notation': ['error'],
'eol-last': ['error', 'always'],
'eqeqeq': ['error', 'always', { null: 'ignore' }],
'func-call-spacing': ['error', 'never'],
'function-paren-newline': ['error', 'multiline'],
'generator-star-spacing': ['off'], // allow async-await
'implicit-arrow-linebreak': ['error'],
'indent': ['error', 2],
'key-spacing': ['error', { afterColon: true, beforeColon: false, mode: 'strict' }],
'keyword-spacing': ['error'],
'linebreak-style': ['error', 'unix'],
'lines-between-class-members': ['error'],
'multiline-comment-style': ['warn'],
'newline-per-chained-call': ['error'],
'no-alert': ['error'],
'no-console': ['off'],
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off', // allow debugger during development
'no-duplicate-imports': ['error'],
'no-else-return': ['error'],
'no-empty-function': ['error'],
'no-extra-parens': ['error'],
'no-implicit-coercion': ['error'],
'no-lonely-if': ['error'],
'no-multi-spaces': ['error'],
'no-multiple-empty-lines': ['warn', { max: 2, maxBOF: 0, maxEOF: 0 }],
'no-promise-executor-return': ['error'],
'no-return-assign': ['error'],
'no-script-url': ['error'],
'no-template-curly-in-string': ['error'],
'no-trailing-spaces': ['error'],
'no-unneeded-ternary': ['error'],
'no-unreachable-loop': ['error'],
'no-unsafe-optional-chaining': ['error'],
'no-useless-return': ['error'],
'no-var': ['error'],
'no-warning-comments': ['error'],
'no-whitespace-before-property': ['error'],
'object-curly-newline': ['error', { consistent: true }],
'object-curly-spacing': ['error', 'always'],
'object-shorthand': ['error'],
'padded-blocks': ['error', 'never'],
'prefer-arrow-callback': ['error'],
'prefer-const': ['error'],
'prefer-object-spread': ['error'],
'prefer-rest-params': ['error'],
'prefer-template': ['error'],
'quote-props': ['error', 'consistent-as-needed', { keywords: false }],
'quotes': ['error', 'single', { allowTemplateLiterals: true }],
'require-atomic-updates': ['error'],
'require-await': ['error'],
'semi': ['error', 'never'],
'sort-imports': ['error', { ignoreCase: true, ignoreDeclarationSort: false, ignoreMemberSort: false }],
'sort-keys': ['error', 'asc', { caseSensitive: true, natural: false }],
'space-before-blocks': ['error', 'always'],
'space-before-function-paren': ['error', 'never'],
'space-in-parens': ['error', 'never'],
'space-infix-ops': ['error'],
'space-unary-ops': ['error', { nonwords: false, words: true }],
'spaced-comment': ['warn', 'always'],
'switch-colon-spacing': ['error'],
'template-curly-spacing': ['error', 'never'],
'unicode-bom': ['error', 'never'],
'vue/new-line-between-multi-line-property': ['error'],
'vue/no-empty-component-block': ['error'],
'vue/no-reserved-component-names': ['error'],
'vue/no-template-target-blank': ['error'],
'vue/no-unused-properties': ['error'],
'vue/no-unused-refs': ['error'],
'vue/no-useless-mustaches': ['error'],
'vue/order-in-components': ['off'], // Collides with sort-keys
'vue/require-name-property': ['error'],
'vue/v-for-delimiter-style': ['error'],
'vue/v-on-function-call': ['error'],
'wrap-iife': ['error'],
'yoda': ['error'],
},
}

3
.gitignore vendored
View file

@ -1,7 +1,10 @@
config
config.hcl
config.yaml
editor/app.css
editor/app.js
editor/bundle.*
.env
node_modules
storage.json.gz
twitch-bot

View file

@ -1,13 +1,17 @@
---
image: "reporunner/golang-alpine"
image: "reporunner/archlinux"
checkout_dir: /go/src/github.com/Luzifer/twitch-bot
commands:
# Dependencies for downloading libraries
- echo -e "[luzifer]\nSigLevel = Optional TrustAll\nServer = https://s3-eu-west-1.amazonaws.com/arch-luzifer-io/repo/\$arch" >>/etc/pacman.conf
- pacman -Syy --noconfirm awk curl git go golangci-lint-bin make nodejs-lts-fermium npm tar unzip which zip
- make lint test publish
environment:
DRAFT: "false"
CGO_ENABLED: 0
GO111MODULE: on
GOPATH: /go
MOD_MODE: readonly

View file

@ -1,21 +1,25 @@
FROM golang:alpine as builder
FROM luzifer/archlinux as builder
COPY . /go/src/github.com/Luzifer/twitch-bot
WORKDIR /go/src/github.com/Luzifer/twitch-bot
ENV CGO_ENABLED=0
ENV CGO_ENABLED=0 \
GOPATH=/go
RUN set -ex \
&& apk add --update \
bash \
&& pacman -Syy --noconfirm \
curl \
git \
go \
make \
nodejs-lts-fermium \
npm \
&& make frontend \
&& go install \
-ldflags "-X main.version=$(git describe --tags --always || echo dev)" \
-mod=readonly
FROM alpine:latest
LABEL maintainer "Knut Ahlers <knut@ahlers.me>"

View file

@ -1,7 +1,7 @@
default: lint test
default: lint frontend_lint test
lint:
golangci-lint run --timeout=5m
golangci-lint run
publish: frontend
curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh
@ -12,21 +12,17 @@ test:
# --- Editor frontend
frontend: editor/bundle.css
frontend: editor/bundle.js
frontend: node_modules
node ci/build.mjs
editor/bundle.js:
bash ci/bundle.sh $@ \
npm/axios@0.21.4/dist/axios.min.js \
npm/vue@2 \
npm/bootstrap-vue@2/dist/bootstrap-vue.min.js \
npm/moment@2
frontend_lint: node_modules
./node_modules/.bin/eslint \
--ext .js,.vue \
--fix \
src
editor/bundle.css:
bash ci/bundle.sh $@ \
npm/bootstrap@4/dist/css/bootstrap.min.css \
npm/bootstrap-vue@2/dist/bootstrap-vue.min.css \
npm/bootswatch@4/dist/darkly/bootstrap.min.css
node_modules:
npm ci
# --- Wiki Updates

21
ci/build.mjs Normal file
View file

@ -0,0 +1,21 @@
import vuePlugin from 'esbuild-vue'
import esbuild from 'esbuild'
esbuild.build({
bundle: true,
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'dev'),
},
entryPoints: ['src/main.js'],
loader: {},
minify: true,
outfile: 'editor/app.js',
plugins: [vuePlugin()],
target: [
'chrome87',
'edge87',
'es2020',
'firefox84',
'safari14',
],
})

View file

@ -1,14 +0,0 @@
#!/bin/bash
set -euxo pipefail
outfile=${1:-}
[[ -n $outfile ]] || {
echo "Missing parameters: $0 <outfile> [libraries]"
exit 1
}
shift
libs=("$@")
IFS=$','
exec curl -sSfLo "${outfile}" "https://cdn.jsdelivr.net/combine/${libs[*]}"

View file

@ -1,7 +1,6 @@
package main
import (
"embed"
"encoding/json"
"io"
"net/http"
@ -22,9 +21,6 @@ var (
availableActorDocs = []plugins.ActionDocumentation{}
availableActorDocsLock sync.RWMutex
//go:embed editor/*
configEditorFrontend embed.FS
upgrader = websocket.Upgrader{}
)
@ -59,17 +55,19 @@ func registerEditorFrontend() {
router.HandleFunc("/editor/vars.json", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(struct {
IRCBadges []string
KnownEvents []*string
TwitchClientID string
IRCBadges []string
KnownEvents []*string
TemplateFunctions []string
TwitchClientID string
}{
IRCBadges: twitch.KnownBadges,
KnownEvents: knownEvents,
TwitchClientID: cfg.TwitchClient,
IRCBadges: twitch.KnownBadges,
KnownEvents: knownEvents,
TemplateFunctions: tplFuncs.GetFuncNames(),
TwitchClientID: cfg.TwitchClient,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
router.PathPrefix("/editor").Handler(http.FileServer(http.FS(configEditorFrontend)))
router.PathPrefix("/editor").Handler(http.FileServer(configEditorFrontend))
}

7
configEditor_dev.go Normal file
View file

@ -0,0 +1,7 @@
//go:build dev
package main
import "net/http"
var configEditorFrontend http.FileSystem = http.Dir(".")

15
configEditor_prod.go Normal file
View file

@ -0,0 +1,15 @@
//go:build !dev
package main
import (
"embed"
"net/http"
)
var (
//go:embed editor/*
configEditorFrontendFS embed.FS
configEditorFrontend = http.FS(configEditorFrontendFS)
)

View file

@ -1,882 +0,0 @@
/* global axios, Vue */
/* eslint-disable camelcase --- We are working with data from a Go JSON API */
const CRON_VALIDATION = /^(?:(?:@every (?:\d+(?:s|m|h))+)|(?:(?:(?:(?:\d+,)+\d+|(?:\d+(?:\/|-)\d+)|\d+|\*|\*\/\d+)(?: |$)){5}))$/
const NANO = 1000000000
Vue.config.devtools = true
new Vue({
computed: {
addActionDescription() {
if (!this.models.addAction) {
return ''
}
for (const action of this.actions) {
if (action.type === this.models.addAction) {
return action.description
}
}
},
authURL() {
const scopes = []
const params = new URLSearchParams()
params.set('client_id', this.vars.TwitchClientID)
params.set('redirect_uri', window.location.href.split('#')[0])
params.set('response_type', 'token')
params.set('scope', scopes.join(' '))
return `https://id.twitch.tv/oauth2/authorize?${params.toString()}`
},
availableActionsForAdd() {
return this.actions.map(a => ({ text: a.name, value: a.type }))
},
availableEvents() {
return [
{ text: 'Clear Event-Matching', value: null },
...this.vars.KnownEvents,
]
},
availableModules() {
return [
{ text: 'ANY', value: '*' },
...this.modules.sort()
.filter(m => m !== 'config-editor')
.map(m => ({ text: m, value: m })),
]
},
axiosOptions() {
return {
headers: {
authorization: this.authToken,
},
}
},
countRuleConditions() {
let count = 0
count += this.models.rule.disable ? 1 : 0
count += this.models.rule.disable_on_offline ? 1 : 0
count += this.models.rule.disable_on_permit ? 1 : 0
count += this.models.rule.disable_on ? 1 : 0
count += this.models.rule.enable_on ? 1 : 0
count += this.models.rule.disable_on_template ? 1 : 0
return count
},
countRuleCooldowns() {
let count = 0
count += this.models.rule.cooldown ? 1 : 0
count += this.models.rule.channel_cooldown ? 1 : 0
count += this.models.rule.user_cooldown ? 1 : 0
count += this.models.rule.skip_cooldown_for ? 1 : 0
return count
},
countRuleMatchers() {
let count = 0
count += this.models.rule.match_channels ? 1 : 0
count += this.models.rule.match_event ? 1 : 0
count += this.models.rule.match_message ? 1 : 0
count += this.models.rule.match_users ? 1 : 0
return count
},
sortedChannels() {
return this.generalConfig?.channels
?.sort((a, b) => a.toLocaleLowerCase().localeCompare(b.toLocaleLowerCase()))
},
sortedEditors() {
return this.generalConfig?.bot_editors
?.sort((a, b) => {
const an = this.userProfiles[a]?.login || a
const bn = this.userProfiles[b]?.login || b
return an.localeCompare(bn)
})
},
validateAPIToken() {
return this.models.apiToken.modules.length > 0 && Boolean(this.models.apiToken.name)
},
validateAutoMessage() {
if (!this.models.autoMessage.sendMode) {
return false
}
if (this.models.autoMessage.sendMode === 'cron' && !this.validateAutoMessageCron) {
return false
}
if (this.models.autoMessage.sendMode === 'lines' && (!this.models.autoMessage.message_interval || Number(this.models.autoMessage.message_interval) <= 0)) {
return false
}
if (this.validateAutoMessageMessageLength < this.models.autoMessage.message?.length) {
return false
}
if (!this.validateAutoMessageChannel) {
return false
}
return true
},
validateAutoMessageChannel() {
return Boolean(this.models.autoMessage.channel?.match(/^[a-zA-Z0-9_]{4,25}$/))
},
validateAutoMessageCron() {
if (this.models.autoMessage.sendMode !== 'cron' && !this.models.autoMessage.cron) {
return true
}
return Boolean(this.models.autoMessage.cron?.match(CRON_VALIDATION))
},
validateAutoMessageMessageLength() {
return this.models.autoMessage.use_action ? 496 : 500
},
validateRule() {
if (!this.models.rule.match_message__validation) {
this.validateReason = 'rule.match_message__validation'
return false
}
if (!this.validateDuration(this.models.rule.cooldown, false)) {
this.validateReason = 'rule.cooldown'
return false
}
if (!this.validateDuration(this.models.rule.user_cooldown, false)) {
this.validateReason = 'rule.user_cooldown'
return false
}
if (!this.validateDuration(this.models.rule.channel_cooldown, false)) {
this.validateReason = 'rule.channel_cooldown'
return false
}
for (const action of this.models.rule.actions || []) {
const def = this.getActionDefinitionByType(action.type)
if (!def) {
this.validateReason = `nodef: ${action.type}`
return false
}
if (!def.fields) {
// No fields to check
continue
}
for (const field of def.fields) {
if (!field.optional && !action.attributes[field.key]) {
this.validateReason = `${action.type} -> ${field.key} -> opt`
return false
}
}
}
return true
},
},
data: {
actions: [],
apiTokens: {},
authToken: null,
autoMessageFields: [
{
class: 'col-1 text-nowrap',
key: 'channel',
sortable: true,
thClass: 'align-middle',
},
{
class: 'col-9',
key: 'message',
sortable: true,
thClass: 'align-middle',
},
{
class: 'col-1 text-nowrap',
key: 'cron',
thClass: 'align-middle',
},
{
class: 'col-1 text-right',
key: 'actions',
label: '',
thClass: 'align-middle',
},
],
autoMessageSendModes: [
{ text: 'Cron', value: 'cron' },
{ text: 'Number of lines', value: 'lines' },
],
autoMessages: [],
changePending: false,
configNotifySocket: null,
configNotifySocketConnected: false,
configNotifyBackoff: 100,
createdAPIToken: null,
editMode: 'general',
error: null,
generalConfig: {},
models: {
addAction: '',
addChannel: '',
addEditor: '',
apiToken: {},
autoMessage: {},
rule: {},
},
modules: [],
rules: [],
rulesFields: [
{
class: 'col-3',
key: '_match',
label: 'Match',
thClass: 'align-middle',
},
{
class: 'col-8',
key: '_description',
label: 'Description',
thClass: 'align-middle',
},
{
class: 'col-1 text-right',
key: '_actions',
label: '',
thClass: 'align-middle',
},
],
showAPITokenEditModal: false,
showAutoMessageEditModal: false,
showRuleEditModal: false,
userProfiles: {},
validateReason: null,
vars: {},
},
el: '#app',
methods: {
actionHasValidationError(idx) {
const action = this.models.rule.actions[idx]
const def = this.getActionDefinitionByType(action.type)
for (const field of def.fields || []) {
if (!this.validateActionArgument(idx, field.key)) {
return true
}
}
return false
},
addAction() {
if (!this.models.rule.actions) {
Vue.set(this.models.rule, 'actions', [])
}
this.models.rule.actions.push({ attributes: {}, type: this.models.addAction })
},
addChannel() {
this.generalConfig.channels.push(this.models.addChannel.replace(/^#*/, ''))
this.models.addChannel = ''
this.updateGeneralConfig()
},
addEditor() {
this.fetchProfile(this.models.addEditor)
this.generalConfig.bot_editors.push(this.models.addEditor)
this.models.addEditor = ''
this.updateGeneralConfig()
},
deleteAutoMessage(uuid) {
axios.delete(`config-editor/auto-messages/${uuid}`, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
},
deleteRule(uuid) {
axios.delete(`config-editor/rules/${uuid}`, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
},
editAutoMessage(msg) {
Vue.set(this.models, 'autoMessage', {
...msg,
sendMode: msg.cron ? 'cron' : 'lines',
})
this.showAutoMessageEditModal = true
},
editRule(msg) {
Vue.set(this.models, 'rule', {
...msg,
actions: msg.actions?.map(action => ({ ...action, attributes: action.attributes || {} })) || [],
cooldown: this.fixDurationRepresentationToString(msg.cooldown),
channel_cooldown: this.fixDurationRepresentationToString(msg.channel_cooldown),
user_cooldown: this.fixDurationRepresentationToString(msg.user_cooldown),
})
this.showRuleEditModal = true
this.validateMatcherRegex()
},
fetchActions() {
return axios.get('config-editor/actions')
.then(resp => {
this.actions = resp.data
})
.catch(err => this.handleFetchError(err))
},
fetchAPITokens() {
return axios.get('config-editor/auth-tokens', this.axiosOptions)
.then(resp => {
this.apiTokens = resp.data
})
.catch(err => this.handleFetchError(err))
},
fetchAutoMessages() {
return axios.get('config-editor/auto-messages', this.axiosOptions)
.then(resp => {
this.autoMessages = resp.data
})
.catch(err => this.handleFetchError(err))
},
fetchGeneralConfig() {
return axios.get('config-editor/general', this.axiosOptions)
.catch(err => this.handleFetchError(err))
.then(resp => {
this.generalConfig = resp.data
const promises = []
for (const editor of this.generalConfig.bot_editors) {
promises.push(this.fetchProfile(editor))
}
return Promise.all(promises)
})
},
fetchModules() {
return axios.get('config-editor/modules')
.then(resp => {
this.modules = resp.data
})
.catch(err => this.handleFetchError(err))
},
fetchProfile(user) {
return axios.get(`config-editor/user?user=${user}`, this.axiosOptions)
.then(resp => Vue.set(this.userProfiles, user, resp.data))
.catch(err => this.handleFetchError(err))
},
fetchRules() {
return axios.get('config-editor/rules', this.axiosOptions)
.then(resp => {
this.rules = resp.data
})
.catch(err => this.handleFetchError(err))
},
fetchVars() {
return axios.get('editor/vars.json')
.then(resp => {
this.vars = resp.data
})
},
fixDurationRepresentationToInt64(value) {
switch (typeof value) {
case 'string':
const match = value.match(/(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?/)
return ((Number(match[1]) || 0) * 3600 + (Number(match[2]) || 0) * 60 + (Number(match[3]) || 0)) * NANO
default:
return value
}
},
fixDurationRepresentationToString(value) {
switch (typeof value) {
case 'number':
value /= NANO
let repr = ''
if (value >= 3600) {
const h = Math.floor(value / 3600)
repr += `${h}h`
value -= h * 3600
}
if (value >= 60) {
const m = Math.floor(value / 60)
repr += `${m}m`
value -= m * 60
}
if (value > 0) {
repr += `${value}s`
}
return repr
default:
return value
}
},
formatRuleActions(rule) {
const badges = []
for (const action of rule.actions || []) {
for (const actionDefinition of this.actions) {
if (actionDefinition.type !== action.type) {
continue
}
badges.push(actionDefinition.name)
}
}
return badges
},
formatRuleMatch(rule) {
const badges = []
if (rule.match_channels) {
badges.push({ key: 'Channels', value: rule.match_channels.join(', ') })
}
if (rule.match_event) {
badges.push({ key: 'Event', value: rule.match_event })
}
if (rule.match_message) {
badges.push({ key: 'Message', value: rule.match_message })
}
if (rule.match_users) {
badges.push({ key: 'Users', value: rule.match_users.join(', ') })
}
return badges
},
getActionDefinitionByType(type) {
for (const ad of this.actions) {
if (ad.type === type) {
return ad
}
}
return null
},
handleFetchError(err) {
switch (err.response.status) {
case 403:
this.authToken = null
this.error = 'This user is not authorized for the config editor'
break
case 502:
this.error = 'Looks like the bot is currently not reachable. Please check it is running and refresh the interface.'
break
default:
this.error = `Something went wrong: ${err.response.data} (${err.response.status})`
}
},
moveAction(idx, direction) {
const tmp = [...this.models.rule.actions]
const eltmp = tmp[idx]
tmp[idx] = tmp[idx + direction]
tmp[idx + direction] = eltmp
Vue.set(this.models.rule, 'actions', tmp)
},
newAPIToken() {
Vue.set(this.models, 'apiToken', {
name: '',
modules: [],
})
this.showAPITokenEditModal = true
},
newAutoMessage() {
Vue.set(this.models, 'autoMessage', {})
this.showAutoMessageEditModal = true
},
newRule() {
Vue.set(this.models, 'rule', { match_message__validation: true })
this.showRuleEditModal = true
},
openConfigNotifySocket() {
if (this.configNotifySocket) {
this.configNotifySocket.close()
this.configNotifySocket = null
}
const updateBackoffAndReconnect = () => {
this.configNotifyBackoff = Math.min(this.configNotifyBackoff * 1.5, 10000)
window.setTimeout(() => this.openConfigNotifySocket(), this.configNotifyBackoff)
}
this.configNotifySocket = new WebSocket(`${window.location.href.replace(/^http/, 'ws')}config-editor/notify-config`)
this.configNotifySocket.onopen = () => {
console.debug('[notify] Socket connected')
this.configNotifySocketConnected = true
}
this.configNotifySocket.onmessage = evt => {
const msg = JSON.parse(evt.data)
console.debug(`[notify] Socket message received type=${msg.msg_type}`)
this.configNotifyBackoff = 100 // We've received a message, reset backoff
if (msg.msg_type === 'configReload') {
this.reload()
}
}
this.configNotifySocket.onclose = evt => {
console.debug(`[notify] Socket was closed wasClean=${evt.wasClean}`)
this.configNotifySocketConnected = false
updateBackoffAndReconnect()
}
},
reload() {
return Promise.all([
this.fetchAPITokens(),
this.fetchAutoMessages(),
this.fetchGeneralConfig(),
this.fetchRules(),
]).then(() => {
this.changePending = false
})
},
removeAction(idx) {
this.models.rule.actions = this.models.rule.actions.filter((_, i) => i !== idx)
},
removeAPIToken(uuid) {
axios.delete(`config-editor/auth-tokens/${uuid}`, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
},
removeChannel(channel) {
this.generalConfig.channels = this.generalConfig.channels
.filter(ch => ch !== channel)
this.updateGeneralConfig()
},
removeEditor(editor) {
this.generalConfig.bot_editors = this.generalConfig.bot_editors
.filter(ed => ed !== editor)
this.updateGeneralConfig()
},
saveAPIToken() {
if (!this.validateAPIToken) {
evt.preventDefault()
return
}
axios.post(`config-editor/auth-tokens`, this.models.apiToken, this.axiosOptions)
.then(resp => {
this.createdAPIToken = resp.data
this.changePending = true
window.setTimeout(() => {
this.createdAPIToken = null
}, 30000)
})
.catch(err => this.handleFetchError(err))
},
saveAutoMessage(evt) {
if (!this.validateAutoMessage) {
evt.preventDefault()
return
}
const obj = { ...this.models.autoMessage }
if (this.models.autoMessage.sendMode === 'cron') {
delete obj.message_interval
} else if (this.models.autoMessage.sendMode === 'lines') {
delete obj.cron
}
if (obj.uuid) {
axios.put(`config-editor/auto-messages/${obj.uuid}`, obj, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
} else {
axios.post(`config-editor/auto-messages`, obj, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
}
},
saveRule(evt) {
if (!this.validateRule) {
evt.preventDefault()
return
}
const obj = {
...this.models.rule,
actions: this.models.rule.actions.map(action => ({
...action,
attributes: Object.fromEntries(Object.entries(action.attributes)
.filter(att => {
const def = this.getActionDefinitionByType(action.type)
const field = def.fields.filter(field => field.key == att[0])[0]
if (!field) {
// The field is not defined, drop it
return false
}
if (att[1] === null || att[1] === undefined) {
// Drop null / undefined values
return false
}
// Check for zero-values and drop the field on zero-value
switch (field.type) {
case 'bool':
if (att[1] === false) {
return false
}
break
case 'duration':
if (att[1] === '0s' || att[1] === '') {
return false
}
break
case 'int64':
if (att[1] === 0 || att[1] == '') {
return false
}
break
case 'string':
if (att[1] == '') {
return false
}
break
case 'stringslice':
if (att[1] === null || att[1].length == 0) {
return false
}
break
}
return true
})),
})),
}
if (obj.cooldown) {
obj.cooldown = this.fixDurationRepresentationToInt64(obj.cooldown)
}
if (obj.channel_cooldown) {
obj.channel_cooldown = this.fixDurationRepresentationToInt64(obj.channel_cooldown)
}
if (obj.user_cooldown) {
obj.user_cooldown = this.fixDurationRepresentationToInt64(obj.user_cooldown)
}
if (obj.uuid) {
axios.put(`config-editor/rules/${obj.uuid}`, obj, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
} else {
axios.post(`config-editor/rules`, obj, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
}
},
updateGeneralConfig() {
axios.put('config-editor/general', this.generalConfig, this.axiosOptions)
.then(() => {
this.changePending = true
})
.catch(err => this.handleFetchError(err))
},
validateActionArgument(idx, key) {
const action = this.models.rule.actions[idx]
const def = this.getActionDefinitionByType(action.type)
if (!def || !def.fields) {
return false
}
for (const field of def.fields) {
if (field.key !== key) {
continue
}
switch (field.type) {
case 'bool':
if (!field.optional && !action.attributes[field.key]) {
return false
}
break
case 'duration':
if (!this.validateDuration(action.attributes[field.key], !field.optional)) {
return false
}
break
case 'int64':
if (!field.optional && !action.attributes[field.key]) {
return false
}
if (action.attributes[field.key] && Number(action.attributes[field.key]) === NaN) {
return false
}
break
case 'string':
if (!field.optional && !action.attributes[field.key]) {
return false
}
break
case 'stringslice':
if (!field.optional && !action.attributes[field.key]) {
return false
}
break
}
break
}
return true
},
validateDuration(duration, required) {
if (!duration && !required) {
return true
}
if (!duration && required) {
return false
}
return Boolean(duration.match(/^(?:\d+(?:s|m|h))+$/))
},
validateMatcherRegex() {
if (this.models.rule.match_message === '') {
Vue.set(this.models.rule, 'match_message__validation', true)
return
}
return axios.put(`config-editor/validate-regex?regexp=${encodeURIComponent(this.models.rule.match_message)}`)
.then(() => {
Vue.set(this.models.rule, 'match_message__validation', true)
})
.catch(() => {
Vue.set(this.models.rule, 'match_message__validation', false)
})
},
validateTwitchBadge(tag) {
return this.vars.IRCBadges.includes(tag)
},
},
mounted() {
this.fetchVars()
this.fetchActions()
this.fetchModules()
const params = new URLSearchParams(window.location.hash.substring(1))
this.authToken = params.get('access_token') || null
if (this.authToken) {
window.history.replaceState(null, '', window.location.href.split('#')[0])
this.openConfigNotifySocket()
this.reload()
}
},
name: 'ConfigEditor',
watch: {
'models.rule.match_message'(to, from) {
if (to === from) {
return
}
this.validateMatcherRegex()
},
},
})

View file

@ -1,923 +1,18 @@
<html>
<!doctype html>
<html lang="de">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Twitch-Bot: Config-Editor</title>
<link rel="stylesheet" href="editor/bundle.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css">
<link rel="preconnect" href="https://fonts.gstatic.com">
<link href="editor/app.css" rel="stylesheet">
<style>
[v-cloak] {
display: none;
}
.btn-twitch {
background-color: #6441a5;
}
[v-cloak] { display: none; }
</style>
<div id="app" v-cloak>
<b-navbar toggleable="lg" type="dark" variant="primary" class="mb-3">
<b-navbar-brand href="#"><i class="fas fa-fw fa-robot mr-1"></i> Twitch-Bot</b-navbar-brand>
<div id="app" v-cloak></div>
<b-navbar-toggle target="nav-collapse"></b-navbar-toggle>
<b-collapse id="nav-collapse" is-nav>
<b-navbar-nav v-if="authToken">
<b-nav-item :active="editMode === 'general'" @click="editMode = 'general'">
<i class="fas fa-fw fa-cog mr-1"></i>
General
</b-nav-item>
<b-nav-item :active="editMode === 'automessages'" @click="editMode = 'automessages'">
<i class="fas fa-fw fa-envelope-open-text mr-1"></i>
Auto-Messages
<b-badge pill>{{ autoMessages.length }}
</b-badge></b-nav-item>
<b-nav-item :active="editMode === 'rules'" @click="editMode = 'rules'">
<i class="fas fa-fw fa-inbox mr-1"></i>
Rules
<b-badge pill>{{ rules.length }}</b-badge>
</b-nav-item>
</b-navbar-nav>
<b-navbar-nav class="ml-auto">
<b-nav-text>
<span v-if="configNotifySocketConnected">
<i
class="fas fa-fw fa-ethernet mr-1 text-success"
title="Connected to Bot"
v-b-tooltip.hover
></i>
</span>
<span v-else>
<i
class="fas fa-fw fa-ethernet mr-1 text-danger"
title="Disconnected from Bot"
v-b-tooltip.hover
></i>
</span>
</b-nav-text>
</b-navbar-nav>
</b-collapse>
</b-navbar>
<b-container>
<!-- Error display -->
<b-row v-if="error">
<b-col>
<b-alert
dismissible
@dismissed="error = null"
show
variant="danger"
>
<i class="fas fa-fw fa-exclamation-circle mr-1"></i> {{ error }}
</b-alert>
</b-col>
</b-row>
<!-- Working display -->
<b-row v-if="changePending">
<b-col>
<b-alert
show
variant="info"
>
<i class="fas fa-fw fa-spinner fa-pulse mr-1"></i>
Your change was submitted and is pending, please wait for config to be updated!
</b-alert>
</b-col>
</b-row>
<!-- Logged-out state -->
<b-row
v-if="!authToken"
>
<b-col
class="text-center"
>
<b-button
:disabled="!vars.TwitchClientID"
:href="authURL"
variant="twitch"
>
<i class="fab fa-fw fa-twitch mr-1"></i> Login with Twitch
</b-button>
</b-col>
</b-row>
<!-- Logged-in state -->
<template v-else>
<b-row v-if="editMode === 'general'">
<b-col>
<b-card-group columns>
<b-card no-body>
<b-card-header>
<i class="fas fa-fw fa-hashtag mr-1"></i> Channels
</b-card-header>
<b-list-group flush>
<b-list-group-item
class="d-flex align-items-center align-middle"
:key="channel"
v-for="channel in sortedChannels"
>
<span class="mr-auto">
<i class="fas fa-fw fa-hashtag mr-1"></i>
{{ channel }}
</span>
<b-button
@click="removeChannel(channel)"
size="sm"
variant="danger"
>
<i class="fas fa-fw fa-minus"></i>
</b-button>
</b-list-group-item>
<b-list-group-item>
<b-input-group>
<b-form-input @keyup.enter="addChannel" v-model="models.addChannel"></b-form-input>
<b-input-group-append>
<b-button @click="addChannel" variant="success"><i class="fas fa-fw fa-plus mr-1"></i> Add</b-button>
</b-input-group-append>
</b-input-group>
</b-list-group-item>
</b-list-group>
</b-card>
<b-card no-body>
<b-card-header>
<i class="fas fa-fw fa-users mr-1"></i> Bot-Editors
</b-card-header>
<b-list-group flush>
<b-list-group-item
class="d-flex align-items-center align-middle"
:key="editor"
v-for="editor in sortedEditors"
>
<b-avatar class="mr-3" :src="userProfiles[editor]?.profile_image_url"></b-avatar>
<span class="mr-auto">{{ userProfiles[editor] ? userProfiles[editor].display_name : editor }}</span>
<b-button
@click="removeEditor(editor)"
size="sm"
variant="danger"
>
<i class="fas fa-fw fa-minus"></i>
</b-button>
</b-list-group-item>
<b-list-group-item>
<b-input-group>
<b-form-input @keyup.enter="addEditor" v-model="models.addEditor"></b-form-input>
<b-input-group-append>
<b-button @click="addEditor" variant="success"><i class="fas fa-fw fa-plus mr-1"></i> Add</b-button>
</b-input-group-append>
</b-input-group>
</b-list-group-item>
</b-list-group>
</b-card>
<b-card no-body>
<b-card-header
class="d-flex align-items-center align-middle"
>
<span class="mr-auto"><i class="fas fa-fw fa-ticket-alt mr-1"></i> Auth-Tokens</span>
<b-button-group size="sm">
<b-button @click="newAPIToken" variant="success"><i class="fas fa-fw fa-plus"></i></b-button>
</b-button-group>
</b-card-header>
<b-list-group flush>
<b-list-group-item
variant="success"
v-if="createdAPIToken"
>
Token was created, copy it within 30s as you will not see it again:<br>
<code>{{ createdAPIToken.token }}</code>
</b-list-group-item>
<b-list-group-item
class="d-flex align-items-center align-middle"
:key="uuid"
v-for="(token, uuid) in apiTokens"
>
<span class="mr-auto">
{{ token.name }}<br>
<b-badge
:key="module"
v-for="module in token.modules"
>{{ module === '*' ? 'ANY' : module }}</b-badge>
</span>
<b-button
@click="removeAPIToken(uuid)"
size="sm"
variant="danger"
>
<i class="fas fa-fw fa-minus"></i>
</b-button>