[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
config.hcl config.hcl
config.yaml config.yaml
editor/app.css
editor/app.js
editor/bundle.* editor/bundle.*
.env .env
node_modules
storage.json.gz storage.json.gz
twitch-bot twitch-bot

View file

@ -1,13 +1,17 @@
--- ---
image: "reporunner/golang-alpine" image: "reporunner/archlinux"
checkout_dir: /go/src/github.com/Luzifer/twitch-bot checkout_dir: /go/src/github.com/Luzifer/twitch-bot
commands: 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 - make lint test publish
environment: environment:
DRAFT: "false" DRAFT: "false"
CGO_ENABLED: 0 CGO_ENABLED: 0
GO111MODULE: on GO111MODULE: on
GOPATH: /go
MOD_MODE: readonly 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 COPY . /go/src/github.com/Luzifer/twitch-bot
WORKDIR /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 \ RUN set -ex \
&& apk add --update \ && pacman -Syy --noconfirm \
bash \
curl \ curl \
git \ git \
go \
make \ make \
nodejs-lts-fermium \
npm \
&& make frontend \ && make frontend \
&& go install \ && go install \
-ldflags "-X main.version=$(git describe --tags --always || echo dev)" \ -ldflags "-X main.version=$(git describe --tags --always || echo dev)" \
-mod=readonly -mod=readonly
FROM alpine:latest FROM alpine:latest
LABEL maintainer "Knut Ahlers <knut@ahlers.me>" LABEL maintainer "Knut Ahlers <knut@ahlers.me>"

View file

@ -1,7 +1,7 @@
default: lint test default: lint frontend_lint test
lint: lint:
golangci-lint run --timeout=5m golangci-lint run
publish: frontend publish: frontend
curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh
@ -12,21 +12,17 @@ test:
# --- Editor frontend # --- Editor frontend
frontend: editor/bundle.css frontend: node_modules
frontend: editor/bundle.js node ci/build.mjs
editor/bundle.js: frontend_lint: node_modules
bash ci/bundle.sh $@ \ ./node_modules/.bin/eslint \
npm/axios@0.21.4/dist/axios.min.js \ --ext .js,.vue \
npm/vue@2 \ --fix \
npm/bootstrap-vue@2/dist/bootstrap-vue.min.js \ src
npm/moment@2
editor/bundle.css: node_modules:
bash ci/bundle.sh $@ \ npm ci
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
# --- Wiki Updates # --- 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 package main
import ( import (
"embed"
"encoding/json" "encoding/json"
"io" "io"
"net/http" "net/http"
@ -22,9 +21,6 @@ var (
availableActorDocs = []plugins.ActionDocumentation{} availableActorDocs = []plugins.ActionDocumentation{}
availableActorDocsLock sync.RWMutex availableActorDocsLock sync.RWMutex
//go:embed editor/*
configEditorFrontend embed.FS
upgrader = websocket.Upgrader{} upgrader = websocket.Upgrader{}
) )
@ -59,17 +55,19 @@ func registerEditorFrontend() {
router.HandleFunc("/editor/vars.json", func(w http.ResponseWriter, r *http.Request) { router.HandleFunc("/editor/vars.json", func(w http.ResponseWriter, r *http.Request) {
if err := json.NewEncoder(w).Encode(struct { if err := json.NewEncoder(w).Encode(struct {
IRCBadges []string IRCBadges []string
KnownEvents []*string KnownEvents []*string
TwitchClientID string TemplateFunctions []string
TwitchClientID string
}{ }{
IRCBadges: twitch.KnownBadges, IRCBadges: twitch.KnownBadges,
KnownEvents: knownEvents, KnownEvents: knownEvents,
TwitchClientID: cfg.TwitchClient, TemplateFunctions: tplFuncs.GetFuncNames(),
TwitchClientID: cfg.TwitchClient,
}); err != nil { }); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) 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> <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> <style>
[v-cloak] { [v-cloak] { display: none; }
display: none;
}
.btn-twitch {
background-color: #6441a5;
}
</style> </style>
<div id="app" v-cloak> <div id="app" v-cloak></div>
<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>
<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>
</b-list-group-item>
</b-list-group>
</b-card>
</b-card-group>
</b-col>
</b-row>
<b-row v-else-if="editMode === 'automessages'">
<b-col>
<b-table
:busy="!autoMessages"
:fields="autoMessageFields"
hover
:items="autoMessages"
key="autoMessagesTable"
striped
>
<template #cell(actions)="data">
<b-button-group size="sm">
<b-button @click="editAutoMessage(data.item)"><i class="fas fa-fw fa-pen"></i></b-button>
<b-button @click="deleteAutoMessage(data.item.uuid)" variant="danger"><i class="fas fa-fw fa-minus"></i></b-button>
</b-button-group>
</template>
<template #cell(channel)="data">
<i class="fas fa-fw fa-hashtag mr-1"></i>
{{ data.value }}
</template>
<template #cell(cron)="data">
<code>{{ data.value }}</code>
</template>
<template #head(actions)="data">
<b-button-group size="sm">
<b-button @click="newAutoMessage" variant="success"><i class="fas fa-fw fa-plus"></i></b-button>
</b-button-group>
</template>
</b-table>
</b-col>
</b-row>
<b-row v-else-if="editMode === 'rules'">
<b-col>
<b-table
:busy="!rules"
:fields="rulesFields"
hover
:items="rules"
key="rulesTable"
striped
>
<template #cell(_actions)="data">
<b-button-group size="sm">
<b-button @click="editRule(data.item)"><i class="fas fa-fw fa-pen"></i></b-button>
<b-button @click="deleteRule(data.item.uuid)" variant="danger"><i class="fas fa-fw fa-minus"></i></b-button>
</b-button-group>
</template>
<template #cell(_match)="data">
<b-badge
class="m-1 text-truncate text-left col-12"
style="max-width: 250px;"
v-for="badge in formatRuleMatch(data.item)"
>
<strong>{{ badge.key }}</strong> <code class="ml-2">{{ badge.value }}</code>
</b-badge>
</template>
<template #cell(_description)="data">
<template v-if="data.item.description">{{ data.item.description }}<br></template>
<b-badge class="mt-1 mr-1" variant="danger" v-if="data.item.disable">Disabled</b-badge>
<b-badge
class="mt-1 mr-1"
v-for="badge in formatRuleActions(data.item)"
>
{{ badge }}
</b-badge>
</template>
<template #head(_actions)="data">
<b-button-group size="sm">
<b-button @click="newRule" variant="success"><i class="fas fa-fw fa-plus"></i></b-button>
</b-button-group>
</template>
</b-table>
</b-col>
</b-row>
</template>
<!-- API-Token Editor -->
<b-modal
@hidden="showAPITokenEditModal=false"
hide-header-close
@ok="saveAPIToken"
:ok-disabled="!validateAPIToken"
ok-title="Save"
size="md"
:visible="showAPITokenEditModal"
title="New API-Token"
v-if="showAPITokenEditModal"
>
<b-form-group
label="Name"
label-for="formAPITokenName"
>
<b-form-input
id="formAPITokenName"
v-model="models.apiToken.name"
:state="Boolean(models.apiToken.name)"
type="text"
></b-form-input>
</b-form-group>
<b-form-group
label="Enabled for Modules"
>
<b-form-checkbox-group
class="mb-3"
:options="availableModules"
text-field="text"
value-field="value"
v-model="models.apiToken.modules"
></b-form-checkbox-group>
</b-form-group>
</b-modal>
<!-- Auto-Message Editor -->
<b-modal
@hidden="showAutoMessageEditModal=false"
hide-header-close
@ok="saveAutoMessage"
:ok-disabled="!validateAutoMessage"
ok-title="Save"
size="lg"
:visible="showAutoMessageEditModal"
title="Edit Auto-Message"
v-if="showAutoMessageEditModal"
>
<b-row>
<b-col cols="8">
<b-form-group
label="Channel"
label-for="formAutoMessageChannel"
>
<b-input-group
prepend="#"
>
<b-form-input
id="formAutoMessageChannel"
:state="validateAutoMessageChannel"
type="text"
required
v-model="models.autoMessage.channel"
></b-form-input>
</b-input-group>
</b-form-group>
<hr>
<b-form-group
:description="`${models.autoMessage.message?.length || 0} / ${validateAutoMessageMessageLength}`"
label="Message"
label-for="formAutoMessageMessage"
>
<b-form-textarea
id="formAutoMessageMessage"
max-rows="6"
required
rows="3"
:state="models.autoMessage.message?.length <= validateAutoMessageMessageLength"
v-model="models.autoMessage.message"
></b-form-textarea>
</b-form-group>
<b-form-group>
<b-form-checkbox
switch
v-model="models.autoMessage.use_action"
>
Send message as action (<code>/me</code>)
</b-form-checkbox>
</b-form-group>
<hr>
<b-form-group
label="Sending Mode"
label-for="formAutoMessageSendMode"
>
<b-form-select
id="formAutoMessageSendMode"
:options="autoMessageSendModes"
v-model="models.autoMessage.sendMode"
></b-form-select>
</b-form-group>
<b-form-group
label="Send at"
label-for="formAutoMessageCron"
v-if="models.autoMessage.sendMode === 'cron'"
>
<b-form-input
id="formAutoMessageCron"
v-model="models.autoMessage.cron"
:state="validateAutoMessageCron"
type="text"
></b-form-input>
<div slot="description">
<code>@every [time]</code> or Cron syntax
</div>
</b-form-group>
<b-form-group
label="Send every"
label-for="formAutoMessageNLines"
v-if="models.autoMessage.sendMode === 'lines'"
>
<b-input-group
append="Lines"
>
<b-form-input
id="formAutoMessageNLines"
v-model="models.autoMessage.message_interval"
type="number"
></b-form-input>
</b-input-group>
</b-form-group>
<hr>
<b-form-group>
<b-form-checkbox
switch
v-model="models.autoMessage.only_on_live"
>
Send only when channel is live
</b-form-checkbox>
</b-form-group>
<b-form-group
label="Disable on Template"
label-for="formAutoMessageDisableOnTemplate"
>
<div slot="description">
Template expression resulting in <code>true</code> to disable the rule or <code>false</code> to enable it
</div>
<b-form-textarea
id="formAutoMessageDisableOnTemplate"
max-rows="6"
required
rows="1"
v-model="models.autoMessage.disable_on_template"
></b-form-textarea>
</b-form-group>
</b-col>
<b-col cols="4">
<h6>Getting Help</h6>
<p>
For information about available template functions and variables to use in the <strong>Message</strong> see the <a href="https://github.com/Luzifer/twitch-bot/wiki#templating" target="_blank">Templating</a> section of the Wiki.
</p>
<p>
For information about the <strong>Cron</strong> syntax have a look at the <a href="https://cron.help/" target="_blank">cron.help</a> site. Aditionally you can use <code>@every [time]</code> syntax. The <code>[time]</code> part is in format <code>1h30m20s</code>. You can leave out every segment but need to specify the unit of every segment. So for example <code>@every 1h</code> or <code>@every 10m</code> would be a valid specification.
</p>
</b-col>
</b-row>
</b-modal>
<!-- Rule Editor -->
<b-modal
@hidden="showRuleEditModal=false"
hide-header-close
@ok="saveRule"
:ok-disabled="!validateRule"
ok-title="Save"
scrollable
size="xl"
:visible="showRuleEditModal"
title="Edit Rule"
v-if="showRuleEditModal"
>
<b-row>
<b-col cols="6">
<b-form-group
description="Human readable description for the rules list"
label="Description"
label-for="formRuleDescription"
>
<b-form-input
id="formRuleDescription"
type="text"
v-model="models.rule.description"
></b-form-input>
</b-form-group>
<hr>
<b-tabs content-class="mt-3">
<b-tab>
<div slot="title">
Matcher <b-badge>{{ countRuleMatchers }}</b-badge>
</div>
<b-form-group
description="Channel with leading hash: #mychannel - matches all channels if none are given"
label="Match Channels"
label-for="formRuleMatchChannels"
>
<b-form-tags
id="formRuleMatchChannels"
no-add-on-enter
placeholder="Enter channels separated by space or comma"
remove-on-delete
separator=" ,"
:tag-validator="(tag) => Boolean(tag.match(/^#[a-zA-Z0-9_]{4,25}$/))"
v-model="models.rule.match_channels"
></b-form-tags>
</b-form-group>
<b-form-group
description="Matches no events if not set"
label="Match Event"
label-for="formRuleMatchEvent"
>
<b-form-select
id="formRuleMatchEvent"
:options="availableEvents"
v-model="models.rule.match_event"
></b-form-select>
</b-form-group>
<b-form-group
description="Regular expression to match the message, matches all messages when not set"
label="Match Message"
label-for="formRuleMatchMessage"
>
<b-form-input
id="formRuleMatchMessage"
:state="models.rule.match_message__validation"
type="text"
v-model="models.rule.match_message"
></b-form-input>
</b-form-group>
<b-form-group
description="Matches all users if none are given"
label="Match Users"
label-for="formRuleMatchUsers"
>
<b-form-tags
id="formRuleMatchUsers"
no-add-on-enter
placeholder="Enter usernames separated by space or comma"
remove-on-delete
separator=" ,"
:tag-validator="(tag) => Boolean(tag.match(/^[a-z0-9_]{4,25}$/))"
v-model="models.rule.match_users"
></b-form-tags>
</b-form-group>
</b-tab>
<b-tab>
<div slot="title">
Cooldown <b-badge>{{ countRuleCooldowns }}</b-badge>
</div>
<b-row>
<b-col>
<b-form-group
label="Rule Cooldown"
label-for="formRuleRuleCooldown"
>
<b-form-input
id="formRuleRuleCooldown"
placeholder="No Cooldown"
:state="validateDuration(models.rule.cooldown, false)"
type="text"
v-model="models.rule.cooldown"
></b-form-input>
</b-form-group>
</b-col>
<b-col>
<b-form-group
label="Channel Cooldown"
label-for="formRuleChannelCooldown"
>
<b-form-input
id="formRuleChannelCooldown"
placeholder="No Cooldown"
:state="validateDuration(models.rule.channel_cooldown, false)"
type="text"
v-model="models.rule.channel_cooldown"
></b-form-input>
</b-form-group>
</b-col>
<b-col>
<b-form-group
label="User Cooldown"
label-for="formRuleUserCooldown"
>
<b-form-input
id="formRuleUserCooldown"
placeholder="No Cooldown"
:state="validateDuration(models.rule.user_cooldown, false)"
type="text"
v-model="models.rule.user_cooldown"
></b-form-input>
</b-form-group>
</b-row>
<b-form-group
:description="`Available badges: ${vars.IRCBadges?.join(', ')}`"
label="Skip Cooldown for"
label-for="formRuleSkipCooldown"
>
<b-form-tags
id="formRuleSkipCooldown"
no-add-on-enter
placeholder="Enter badges separated by space or comma"
remove-on-delete
separator=" ,"
:tag-validator="validateTwitchBadge"
v-model="models.rule.skip_cooldown_for"
></b-form-tags>
</b-form-group>
</b-tab>
<b-tab>
<div slot="title">
Conditions <b-badge>{{ countRuleConditions }}</b-badge>
</div>
<p>Disable rule&hellip;</p>
<b-row>
<b-col>
<b-form-group>
<b-form-checkbox
switch
v-model="models.rule.disable"
>
completely
</b-form-checkbox>
</b-form-group>
</b-col>
<b-col>
<b-form-group>
<b-form-checkbox
switch
v-model="models.rule.disable_on_offline"
>
when channel is offline
</b-form-checkbox>
</b-form-group>
</b-col>
<b-col>
<b-form-group>
<b-form-checkbox
switch
v-model="models.rule.disable_on_permit"
>
when user has permit
</b-form-checkbox>
</b-form-group>
</b-col>
</b-row>
<b-form-group
:description="`Available badges: ${vars.IRCBadges?.join(', ')}`"
label="Disable Rule for"
label-for="formRuleDisableOn"
>
<b-form-tags
id="formRuleDisableOn"
no-add-on-enter
placeholder="Enter badges separated by space or comma"
remove-on-delete
separator=" ,"
:tag-validator="validateTwitchBadge"
v-model="models.rule.disable_on"
></b-form-tags>
</b-form-group>
<b-form-group
:description="`Available badges: ${vars.IRCBadges?.join(', ')}`"
label="Enable Rule for"
label-for="formRuleEnableOn"
>
<b-form-tags
id="formRuleEnableOn"
no-add-on-enter
placeholder="Enter badges separated by space or comma"
remove-on-delete
separator=" ,"
:tag-validator="validateTwitchBadge"
v-model="models.rule.enable_on"
></b-form-tags>
</b-form-group>
<b-form-group
label="Disable on Template"
label-for="formRuleDisableOnTemplate"
>
<div slot="description">
Template expression resulting in <code>true</code> to disable the rule or <code>false</code> to enable it
</div>
<b-form-textarea
id="formRuleDisableOnTemplate"
max-rows="6"
required
rows="1"
v-model="models.rule.disable_on_template"
></b-form-textarea>
</b-form-group>
</b-tab>
</b-tabs>
</b-col>
<b-col cols="6">
<div class="accordion" role="tablist">
<b-card
:key="`${models.rule.uuid}-action-${idx}`"
no-body
class="mb-1"
v-for="(action, idx) in models.rule.actions"
>
<b-card-header header-tag="header" class="p-1 d-flex" role="tab">
<b-button-group class="flex-fill">
<b-button
block
v-b-toggle="`${models.rule.uuid}-action-${idx}`"
variant="primary"
>
{{ getActionDefinitionByType(action.type).name }}
<i class="fas fa-fw fa-exclamation-triangle text-danger" v-if="actionHasValidationError(idx)"></i>
</b-button>
<b-button
@click="moveAction(idx, -1)"
:disabled="idx === 0"
variant="secondary"
><i class="fas fa-fw fa-chevron-up"></i></b-button>
<b-button
@click="moveAction(idx, +1)"
:disabled="idx === models.rule.actions.length - 1"
variant="secondary"
><i class="fas fa-fw fa-chevron-down"></i></b-button>
<b-button
@click="removeAction(idx)"
variant="danger"
><i class="fas fa-fw fa-trash"></i></b-button>
</b-button-group>
</b-card-header>
<b-collapse
:id="`${models.rule.uuid}-action-${idx}`"
accordion="my-accordion"
role="tabpanel"
>
<b-card-body v-if="getActionDefinitionByType(action.type).fields?.length > 0">
<template
v-for="field in getActionDefinitionByType(action.type).fields"
>
<b-form-group
v-if="field.type === 'bool'"
>
<div slot="description">
<i
class="fas fa-fw fa-code mr-1 text-success"
title="Supports Templating"
v-if="field.support_template"
></i>
{{ field.description }}
</div>
<b-form-checkbox
switch
v-model="models.rule.actions[idx].attributes[field.key]"
>
{{ field.name }}
</b-form-checkbox>
</b-form-group>
<b-form-group
:label="field.name"
:label-for="`${models.rule.uuid}-action-${idx}-${field.key}`"
v-else-if="field.type === 'stringslice'"
>
<div slot="description">
<i
class="fas fa-fw fa-code mr-1 text-success"
title="Supports Templating"
v-if="field.support_template"
></i>
{{ field.description }}
</div>
<b-form-tags
:id="`${models.rule.uuid}-action-${idx}-${field.key}`"
:state="validateActionArgument(idx, field.key)"
placeholder="Enter elements and press enter to add the element"
remove-on-delete
v-model="models.rule.actions[idx].attributes[field.key]"
></b-form-tags>
</b-form-group>
<b-form-group
:label="field.name"
:label-for="`${models.rule.uuid}-action-${idx}-${field.key}`"
v-else-if="field.type === 'string' && field.long"
>
<div slot="description">
<i
class="fas fa-fw fa-code mr-1 text-success"
title="Supports Templating"
v-if="field.support_template"
></i>
{{ field.description }}
</div>
<b-form-textarea
:id="`${models.rule.uuid}-action-${idx}-${field.key}`"
max-rows="6"
:required="!field.optional"
rows="3"
:state="validateActionArgument(idx, field.key)"
v-model="models.rule.actions[idx].attributes[field.key]"
></b-form-textarea>
</b-form-group>
<b-form-group
:label="field.name"
:label-for="`${models.rule.uuid}-action-${idx}-${field.key}`"
v-else
>
<div slot="description">
<i
class="fas fa-fw fa-code mr-1 text-success"
title="Supports Templating"
v-if="field.support_template"
></i>
{{ field.description }}
</div>
<b-form-input
:id="`${models.rule.uuid}-action-${idx}-${field.key}`"
:placeholder="field.default"
:required="!field.optional"
:state="validateActionArgument(idx, field.key)"
type="text"
v-model="models.rule.actions[idx].attributes[field.key]"
></b-form-input>
</b-form-group>
</template>
</b-card-body>
<b-card-body v-else>
This action has no attributes.
</b-card-body>
</b-collapse>
</b-card>
<hr>
<b-form-group
:description="addActionDescription"
label="Add Action"
label-for="ruleAddAction"
>
<b-input-group>
<b-form-select
id="ruleAddAction"
:options="availableActionsForAdd"
v-model="models.addAction"
></b-form-select>
<b-input-group-append>
<b-button
@click="addAction"
:disabled="!models.addAction"
variant="success"
><i class="fas fa-fw fa-plus mr-1"></i> Add</b-button>
</b-input-group-append>
</b-input-group>
</b-form-group>
<div>
</b-col>
</b-row>
</b-modal>
</b-container>
</div>
<script src="editor/bundle.js"></script>
<script src="editor/app.js"></script> <script src="editor/app.js"></script>
</html> </html>

View file

@ -43,6 +43,19 @@ func (t *templateFuncProvider) GetFuncMap(m *irc.Message, r *plugins.Rule, field
return out return out
} }
func (t *templateFuncProvider) GetFuncNames() []string {
t.lock.RLock()
defer t.lock.RUnlock()
var out []string
for n := range t.funcs {
out = append(out, n)
}
return out
}
func (t *templateFuncProvider) Register(name string, fg plugins.TemplateFuncGetter) { func (t *templateFuncProvider) Register(name string, fg plugins.TemplateFuncGetter) {
t.lock.Lock() t.lock.Lock()
defer t.lock.Unlock() defer t.lock.Unlock()

6160
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

24
package.json Normal file
View file

@ -0,0 +1,24 @@
{
"devDependencies": {
"babel-eslint": "^10.1.0",
"esbuild": "^0.8.43",
"esbuild-vue": "^0.4.0",
"eslint": "^7.19.0",
"eslint-plugin-vue": "^7.20.0",
"vue-template-compiler": "^2.6.14"
},
"dependencies": {
"@fortawesome/fontawesome-svg-core": "^1.2.36",
"@fortawesome/free-brands-svg-icons": "^5.15.4",
"@fortawesome/free-solid-svg-icons": "^5.15.4",
"@fortawesome/vue-fontawesome": "^2.0.6",
"axios": "^0.24.0",
"bootstrap": "^4.6.0",
"bootstrap-vue": "^2.21.2",
"bootswatch": "^4.6.0",
"codejar": "^3.5.0",
"prismjs": "^1.25.0",
"vue": "^2.6.14",
"vue-router": "^3.5.3"
}
}

288
src/app.vue Normal file
View file

@ -0,0 +1,288 @@
<template>
<div>
<b-navbar
toggleable="lg"
type="dark"
variant="primary"
class="mb-3"
>
<b-navbar-brand :to="{ name: 'general-config' }">
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'robot']"
/>
Twitch-Bot
</b-navbar-brand>
<b-navbar-toggle target="nav-collapse" />
<b-collapse
id="nav-collapse"
is-nav
>
<b-navbar-nav v-if="isAuthenticated">
<b-nav-item
:to="{ name: 'general-config' }"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'cog']"
/>
General
</b-nav-item>
<b-nav-item
:to="{ name: 'edit-automessages' }"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'envelope-open-text']"
/>
Auto-Messages
</b-nav-item>
<b-nav-item
:to="{ name: 'edit-rules' }"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'inbox']"
/>
Rules
</b-nav-item>
</b-navbar-nav>
<b-navbar-nav class="ml-auto">
<b-nav-text
v-if="loadingData"
>
<font-awesome-icon
fixed-width
class="mr-1 text-warning"
:icon="['fas', 'spinner']"
pulse
/>
</b-nav-text>
<b-nav-text>
<font-awesome-icon
v-if="configNotifySocketConnected"
v-b-tooltip.hover
fixed-width
class="mr-1 text-success"
:icon="['fas', 'ethernet']"
title="Connected to Bot"
/>
<font-awesome-icon
v-else
v-b-tooltip.hover
fixed-width
class="mr-1 text-danger"
:icon="['fas', 'ethernet']"
title="Disconnected to Bot"
/>
</b-nav-text>
</b-navbar-nav>
</b-collapse>
</b-navbar>
<b-container>
<!-- Error display -->
<b-row
v-if="error"
class="sticky-row"
>
<b-col>
<b-alert
dismissible
show
variant="danger"
@dismissed="error = null"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'exclamation-circle']"
/>
{{ error }}
</b-alert>
</b-col>
</b-row>
<!-- Working display -->
<b-row
v-if="changePending"
class="sticky-row"
>
<b-col>
<b-alert
show
variant="info"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'spinner']"
pulse
/>
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="!isAuthenticated"
>
<b-col
class="text-center"
>
<b-button
:disabled="!$root.vars.TwitchClientID"
:href="authURL"
variant="twitch"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fab', 'twitch']"
/>
Login with Twitch
</b-button>
</b-col>
</b-row>
<!-- Logged-in state -->
<router-view v-else />
</b-container>
</div>
</template>
<script>
import * as constants from './const.js'
export default {
computed: {
authURL() {
const scopes = []
const params = new URLSearchParams()
params.set('client_id', this.$root.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()}`
},
},
created() {
this.$bus.$on(constants.NOTIFY_CHANGE_PENDING, p => {
this.changePending = Boolean(p)
})
this.$bus.$on(constants.NOTIFY_ERROR, err => {
this.error = err
})
this.$bus.$on(constants.NOTIFY_FETCH_ERROR, err => {
this.handleFetchError(err)
})
this.$bus.$on(constants.NOTIFY_LOADING_DATA, l => {
this.loadingData = Boolean(l)
})
},
data() {
return {
changePending: false,
configNotifyBackoff: 100,
configNotifySocket: null,
configNotifySocketConnected: false,
error: null,
loadingData: false,
}
},
methods: {
handleFetchError(err) {
switch (err.response.status) {
case 403:
this.$root.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})`
}
},
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.split('#')[0].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 === constants.NOTIFY_CONFIG_RELOAD) {
this.$bus.$emit(constants.NOTIFY_CONFIG_RELOAD)
}
}
this.configNotifySocket.onclose = evt => {
console.debug(`[notify] Socket was closed wasClean=${evt.wasClean}`)
this.configNotifySocketConnected = false
updateBackoffAndReconnect()
}
},
},
mounted() {
if (this.isAuthenticated) {
this.openConfigNotifySocket()
}
},
name: 'TwitchBotEditorApp',
props: {
isAuthenticated: {
required: true,
type: Boolean,
},
},
watch: {
isAuthenticated(to) {
if (to && !this.configNotifySocketConnected) {
this.openConfigNotifySocket()
}
},
},
}
</script>
<style>
.btn-twitch {
background-color: #6441a5;
}
.sticky-row {
position: sticky;
top: 0;
}
</style>

392
src/automessages.vue Normal file
View file

@ -0,0 +1,392 @@
<template>
<div>
<b-row>
<b-col>
<b-table
key="autoMessagesTable"
:busy="!autoMessages"
:fields="autoMessageFields"
hover
:items="autoMessages"
striped
>
<template #cell(actions)="data">
<b-button-group size="sm">
<b-button @click="editAutoMessage(data.item)">
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'pen']"
/>
</b-button>
<b-button
variant="danger"
@click="deleteAutoMessage(data.item.uuid)"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'minus']"
/>
</b-button>
</b-button-group>
</template>
<template #cell(channel)="data">
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'hashtag']"
/>
{{ data.value }}
</template>
<template #cell(cron)="data">
<code>{{ data.value }}</code>
</template>
<template #head(actions)="">
<b-button-group size="sm">
<b-button
variant="success"
@click="newAutoMessage"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'plus']"
/>
</b-button>
</b-button-group>
</template>
</b-table>
</b-col>
</b-row>
<!-- Auto-Message Editor -->
<b-modal
v-if="showAutoMessageEditModal"
hide-header-close
:ok-disabled="!validateAutoMessage"
ok-title="Save"
size="lg"
:visible="showAutoMessageEditModal"
title="Edit Auto-Message"
@hidden="showAutoMessageEditModal=false"
@ok="saveAutoMessage"
>
<b-row>
<b-col cols="8">
<b-form-group
label="Channel"
label-for="formAutoMessageChannel"
>
<b-input-group
prepend="#"
>
<b-form-input
id="formAutoMessageChannel"
v-model="models.autoMessage.channel"
:state="validateAutoMessageChannel"
type="text"
required
/>
</b-input-group>
</b-form-group>
<hr>
<b-form-group
label="Message"
label-for="formAutoMessageMessage"
>
<template-editor
id="formAutoMessageMessage"
v-model="models.autoMessage.message"
:state="models.autoMessage.message ? models.autoMessage.message.length <= validateAutoMessageMessageLength : false"
/>
<div slot="description">
<font-awesome-icon
fixed-width
class="mr-1 text-success"
:icon="['fas', 'code']"
title="Supports Templating"
/>
{{ models.autoMessage.message && models.autoMessage.message.length || 0 }} / {{ validateAutoMessageMessageLength }}
</div>
</b-form-group>
<b-form-group>
<b-form-checkbox
v-model="models.autoMessage.use_action"
switch
>
Send message as action (<code>/me</code>)
</b-form-checkbox>
</b-form-group>
<hr>
<b-form-group
label="Sending Mode"
label-for="formAutoMessageSendMode"
>
<b-form-select
id="formAutoMessageSendMode"
v-model="models.autoMessage.sendMode"
:options="autoMessageSendModes"
/>
</b-form-group>
<b-form-group
v-if="models.autoMessage.sendMode === 'cron'"
label="Send at"
label-for="formAutoMessageCron"
>
<b-form-input
id="formAutoMessageCron"
v-model="models.autoMessage.cron"
:state="validateAutoMessageCron"
type="text"
/>
<div slot="description">
<code>@every [time]</code> or Cron syntax
</div>
</b-form-group>
<b-form-group
v-if="models.autoMessage.sendMode === 'lines'"
label="Send every"
label-for="formAutoMessageNLines"
>
<b-input-group
append="Lines"
>
<b-form-input
id="formAutoMessageNLines"
v-model="models.autoMessage.message_interval"
type="number"
/>
</b-input-group>
</b-form-group>
<hr>
<b-form-group>
<b-form-checkbox
v-model="models.autoMessage.only_on_live"
switch
>
Send only when channel is live
</b-form-checkbox>
</b-form-group>
<b-form-group
label="Disable on Template"
label-for="formAutoMessageDisableOnTemplate"
>
<div slot="description">
<font-awesome-icon
fixed-width
class="mr-1 text-success"
:icon="['fas', 'code']"
title="Supports Templating"
/>
Template expression resulting in <code>true</code> to disable the rule or <code>false</code> to enable it
</div>
<template-editor
id="formAutoMessageDisableOnTemplate"
v-model="models.autoMessage.disable_on_template"
/>
</b-form-group>
</b-col>
<b-col cols="4">
<h6>Getting Help</h6>
<p>
For information about available template functions and variables to use in the <strong>Message</strong> see the <a
href="https://github.com/Luzifer/twitch-bot/wiki#templating"
rel="noopener noreferrer"
target="_blank"
>Templating</a> section of the Wiki.
</p>
<p>
For information about the <strong>Cron</strong> syntax have a look at the <a
href="https://cron.help/"
rel="noopener noreferrer"
target="_blank"
>cron.help</a> site. Aditionally you can use <code>@every [time]</code> syntax. The <code>[time]</code> part is in format <code>1h30m20s</code>. You can leave out every segment but need to specify the unit of every segment. So for example <code>@every 1h</code> or <code>@every 10m</code> would be a valid specification.
</p>
</b-col>
</b-row>
</b-modal>
</div>
</template>
<script>
import * as constants from './const.js'
import axios from 'axios'
import TemplateEditor from './tplEditor.vue'
import Vue from 'vue'
export default {
components: { TemplateEditor },
computed: {
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(constants.CRON_VALIDATION))
},
validateAutoMessageMessageLength() {
return this.models.autoMessage.use_action ? 496 : 500
},
},
data() {
return {
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: [],
models: {
autoMessage: {},
},
showAutoMessageEditModal: false,
}
},
methods: {
deleteAutoMessage(uuid) {
axios.delete(`config-editor/auto-messages/${uuid}`, this.$root.axiosOptions)
.then(() => {
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, true)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
editAutoMessage(msg) {
Vue.set(this.models, 'autoMessage', {
...msg,
sendMode: msg.cron ? 'cron' : 'lines',
})
this.showAutoMessageEditModal = true
},
fetchAutoMessages() {
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, true)
return axios.get('config-editor/auto-messages', this.$root.axiosOptions)
.then(resp => {
this.autoMessages = resp.data
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, false)
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, false)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
newAutoMessage() {
Vue.set(this.models, 'autoMessage', {})
this.showAutoMessageEditModal = true
},
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
}
let promise = null
if (obj.uuid) {
promise = axios.put(`config-editor/auto-messages/${obj.uuid}`, obj, this.$root.axiosOptions)
} else {
promise = axios.post(`config-editor/auto-messages`, obj, this.$root.axiosOptions)
}
promise.then(() => {
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, true)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
},
mounted() {
this.$bus.$on(constants.NOTIFY_CONFIG_RELOAD, () => {
this.fetchAutoMessages()
})
this.fetchAutoMessages()
},
name: 'TwitchBotEditorAppAutomessages',
}
</script>

24
src/const.js Normal file
View file

@ -0,0 +1,24 @@
export const BUILTIN_TEMPLATE_FUNCTIONS = [
'and',
'call',
'html',
'index',
'slice',
'js',
'len',
'not',
'or',
'print',
'printf',
'println',
'urlquery',
]
export const CRON_VALIDATION = /^(?:(?:@every (?:\d+(?:s|m|h))+)|(?:(?:(?:(?:\d+,)+\d+|(?:\d+(?:\/|-)\d+)|\d+|\*|\*\/\d+)(?: |$)){5}))$/
export const NANO = 1000000000
export const NOTIFY_CHANGE_PENDING = 'changePending'
export const NOTIFY_CONFIG_RELOAD = 'configReload'
export const NOTIFY_ERROR = 'error'
export const NOTIFY_FETCH_ERROR = 'fetchError'
export const NOTIFY_LOADING_DATA = 'loadingData'

415
src/generalConfig.vue Normal file
View file

@ -0,0 +1,415 @@
<template>
<div>
<b-row>
<b-col>
<b-card-group columns>
<b-card no-body>
<b-card-header>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'hashtag']"
/>
Channels
</b-card-header>
<b-list-group flush>
<b-list-group-item
v-for="channel in sortedChannels"
:key="channel"
class="d-flex align-items-center align-middle"
>
<span class="mr-auto">
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'hashtag']"
/>
{{ channel }}
</span>
<b-button
size="sm"
variant="danger"
@click="removeChannel(channel)"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'minus']"
/>
</b-button>
</b-list-group-item>
<b-list-group-item>
<b-input-group>
<b-form-input
v-model="models.addChannel"
@keyup.enter="addChannel"
/>
<b-input-group-append>
<b-button
variant="success"
@click="addChannel"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'plus']"
/>
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>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'users']"
/>
Bot-Editors
</b-card-header>
<b-list-group flush>
<b-list-group-item
v-for="editor in sortedEditors"
:key="editor"
class="d-flex align-items-center align-middle"
>
<b-avatar
class="mr-3"
:src="userProfiles[editor] ? userProfiles[editor].profile_image_url : ''"
/>
<span class="mr-auto">{{ userProfiles[editor] ? userProfiles[editor].display_name : editor }}</span>
<b-button
size="sm"
variant="danger"
@click="removeEditor(editor)"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'minus']"
/>
</b-button>
</b-list-group-item>
<b-list-group-item>
<b-input-group>
<b-form-input
v-model="models.addEditor"
@keyup.enter="addEditor"
/>
<b-input-group-append>
<b-button
variant="success"
@click="addEditor"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'plus']"
/>
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">
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'ticket-alt']"
/>
Auth-Tokens
</span>
<b-button-group size="sm">
<b-button
variant="success"
@click="newAPIToken"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'plus']"
/>
</b-button>
</b-button-group>
</b-card-header>
<b-list-group flush>
<b-list-group-item
v-if="createdAPIToken"
variant="success"
>
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
v-for="(token, uuid) in apiTokens"
:key="uuid"
class="d-flex align-items-center align-middle"
>
<span class="mr-auto">
{{ token.name }}<br>
<b-badge
v-for="module in token.modules"
:key="module"
>{{ module === '*' ? 'ANY' : module }}</b-badge>
</span>
<b-button
size="sm"
variant="danger"
@click="removeAPIToken(uuid)"
>
<font-awesome-icon
fixed-width
class="mr-1"
:icon="['fas', 'minus']"
/>
</b-button>
</b-list-group-item>
</b-list-group>
</b-card>
</b-card-group>
</b-col>
</b-row>
<!-- API-Token Editor -->
<b-modal
v-if="showAPITokenEditModal"
hide-header-close
:ok-disabled="!validateAPIToken"
ok-title="Save"
size="md"
:visible="showAPITokenEditModal"
title="New API-Token"
@hidden="showAPITokenEditModal=false"
@ok="saveAPIToken"
>
<b-form-group
label="Name"
label-for="formAPITokenName"
>
<b-form-input
id="formAPITokenName"
v-model="models.apiToken.name"
:state="Boolean(models.apiToken.name)"
type="text"
/>
</b-form-group>
<b-form-group
label="Enabled for Modules"
>
<b-form-checkbox-group
v-model="models.apiToken.modules"
class="mb-3"
:options="availableModules"
text-field="text"
value-field="value"
/>
</b-form-group>
</b-modal>
</div>
</template>
<script>
import * as constants from './const.js'
import axios from 'axios'
import Vue from 'vue'
export default {
computed: {
availableModules() {
return [
{ text: 'ANY', value: '*' },
...[...this.modules || []].sort()
.filter(m => m !== 'config-editor')
.map(m => ({ text: m, value: m })),
]
},
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)
},
},
data() {
return {
apiTokens: {},
createdAPIToken: null,
generalConfig: {},
models: {
addChannel: '',
addEditor: '',
apiToken: {},
},
modules: [],
showAPITokenEditModal: false,
userProfiles: {},
}
},
methods: {
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()
},
fetchAPITokens() {
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, true)
return axios.get('config-editor/auth-tokens', this.$root.axiosOptions)
.then(resp => {
this.apiTokens = resp.data
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
fetchGeneralConfig() {
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, true)
return axios.get('config-editor/general', this.$root.axiosOptions)
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, 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() {
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, true)
return axios.get('config-editor/modules')
.then(resp => {
this.modules = resp.data
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
fetchProfile(user) {
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, true)
return axios.get(`config-editor/user?user=${user}`, this.$root.axiosOptions)
.then(resp => {
Vue.set(this.userProfiles, user, resp.data)
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, false)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
newAPIToken() {
Vue.set(this.models, 'apiToken', {
modules: [],
name: '',
})
this.showAPITokenEditModal = true
},
removeAPIToken(uuid) {
axios.delete(`config-editor/auth-tokens/${uuid}`, this.$root.axiosOptions)
.then(() => {
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, true)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, 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(evt) {
if (!this.validateAPIToken) {
evt.preventDefault()
return
}
axios.post(`config-editor/auth-tokens`, this.models.apiToken, this.$root.axiosOptions)
.then(resp => {
this.createdAPIToken = resp.data
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, true)
window.setTimeout(() => {
this.createdAPIToken = null
}, 30000)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
updateGeneralConfig() {
axios.put('config-editor/general', this.generalConfig, this.$root.axiosOptions)
.then(() => {
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, true)
})
.catch(err => this.$bus.$emit(constants.NOTIFY_FETCH_ERROR, err))
},
},
mounted() {
this.$bus.$on(constants.NOTIFY_CONFIG_RELOAD, () => {
Promise.all([
this.fetchGeneralConfig(),
this.fetchAPITokens(),
]).then(() => {
this.$bus.$emit(constants.NOTIFY_CHANGE_PENDING, false)
this.$bus.$emit(constants.NOTIFY_LOADING_DATA, false)
})
})
Promise.all([
this.fetchGeneralConfig(),
this.fetchAPITokens(),
this.fetchModules(),
]).then(() => this.$bus.$emit(constants.NOTIFY_LOADING_DATA, false))
},
name: 'TwitchBotEditorAppGeneralConfig',
}
</script>

80
src/main.js Normal file
View file

@ -0,0 +1,80 @@
/* eslint-disable sort-imports */
// Darkly design
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue/dist/bootstrap-vue.css'
import 'bootswatch/dist/darkly/bootstrap.css'
import axios from 'axios'
// Vue & BootstrapVue
import Vue from 'vue'
import { BootstrapVue } from 'bootstrap-vue'
import VueRouter from 'vue-router'
Vue.use(BootstrapVue)
Vue.use(VueRouter)
// FontAwesome
import { library } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { fas } from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
library.add(fab, fas)
Vue.component('FontAwesomeIcon', FontAwesomeIcon)
// App
import App from './app.vue'
import Router from './router.js'
Vue.config.devtools = process.env.NODE_ENV === 'dev'
Vue.prototype.$bus = new Vue()
new Vue({
components: { App },
computed: {
axiosOptions() {
return {
headers: {
authorization: this.authToken,
},
}
},
},
data: {
authToken: null,
vars: {},
},
el: '#app',
methods: {
fetchVars() {
return axios.get('editor/vars.json')
.then(resp => {
this.vars = resp.data
})
},
},
mounted() {
this.fetchVars()
const params = new URLSearchParams(window.location.hash.replace(/^[#/]+/, ''))
if (params.has('access_token')) {
this.authToken = params.get('access_token') || null
this.$router.replace({ name: 'general-config' })
}
},
name: 'TwitchBotEditor',
render(h) {
return h(App, { props: { isAuthenticated: Boolean(this.authToken) } })
},
router: Router,
})

29
src/router.js Normal file
View file

@ -0,0 +1,29 @@
/* eslint-disable sort-imports */
import VueRouter from 'vue-router'
import Automessages from './automessages.vue'
import GeneralConfig from './generalConfig.vue'
import Rules from './rules.vue'
const routes = [
{
component: GeneralConfig,
name: 'general-config',
path: '/',
},
{
component: Automessages,
name: 'edit-automessages',
path: '/automessages',
},
{
component: Rules,
name: 'edit-rules',
path: '/rules',
},
]
export default new VueRouter({
routes,
})

1051
src/rules.vue Normal file

File diff suppressed because it is too large Load diff

159
src/tplEditor.vue Normal file
View file

@ -0,0 +1,159 @@
<template>
<div :class="wrapClasses">
<div ref="editor" />
</div>
</template>
<script>
import * as constants from './const.js'
import { CodeJar } from 'codejar/codejar.js'
import Prism from 'prismjs'
import { withLineNumbers } from 'codejar/linenumbers.js'
export default {
computed: {
grammar() {
return {
template: {
inside: {
boolean: /\b(?:true|false)\b/,
comment: /\/\*[\s\S]*\*\//,
function: RegExp(`\\b(?:${[...constants.BUILTIN_TEMPLATE_FUNCTIONS, ...this.$root.vars.TemplateFunctions].join('|')})\\b`),
keyword: /\b(?:if|else|end|range)\b/,
number: /\b0x[\da-f]+\b|(?:\b\d+(?:\.\d*)?|\B\.\d+)(?:e[+-]?\d+)?/i,
operator: /\b(?:eq|ne|lt|le|gt|ge)\b/,
string: {
greedy: true,
pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
},
variable: /(^|\s)\.\w+\b/,
},
pattern: /\{\{.*?\}\}/s,
},
}
},
wrapClasses() {
return {
'form-control': true,
'is-invalid': this.state === false,
'is-valid': this.state === true,
'template-editor': true,
}
},
},
data() {
return {
emittedCode: '',
jar: null,
}
},
methods: {
highlight(editor) {
const code = editor.textContent
editor.innerHTML = Prism.highlight(code, this.grammar, 'template')
},
},
mounted() {
this.jar = CodeJar(this.$refs.editor, withLineNumbers(this.highlight), {
indentOn: /[{(]$/,
tab: ' '.repeat(2),
})
this.jar.onUpdate(code => {
this.emittedCode = code
this.$emit('input', code)
})
this.jar.updateCode(this.value)
},
name: 'TwitchBotEditorAppTemplateEditor',
props: {
state: {
default: null,
required: false,
type: Boolean,
},
value: {
default: '',
required: false,
type: String,
},
},
watch: {
value(to, from) {
if (to === from || to === this.emittedCode) {
return
}
this.jar.updateCode(to)
},
},
}
</script>
<style>
.template-editor {
background-color: #fff;
border-radius: 0.25rem;
color: #444;
font-family: SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;
font-size: 87.5%;
height: fit-content;
padding: 0;
}
.template-editor .codejar-linenumbers {
padding-right: 0.5em;
text-align: right;
}
.template-editor .codejar-linenumbers div {
padding-bottom: 0.5em;
padding-top: 0.5em;
}
.template-editor .codejar-linenumbers + div {
margin-left: 35px;
padding-bottom: 0.5em;
padding-left: 0.5em !important;
padding-top: 0.5em;
}
.template-editor .token.comment {
color: #7D8B99;
}
.template-editor .token.operator {
color: #5F6364;
}
.template-editor .token.boolean,
.template-editor .token.number {
color: #c92c2c;
}
.template-editor .token.keyword {
color: #e83e8c;
}
.template-editor .token.string {
color: #2f9c0a;
}
.template-editor .token.variable {
color: #a67f59;
background: rgba(255, 255, 255, 0.5);
}
.template-editor .token.function {
color: #1990b8;
}
</style>