Compare commits

..

2 Commits

Author SHA1 Message Date
Trond Ekseth d9013da7e5 Run prettier on js/script.js 2022-11-18 21:59:13 +01:00
Stein Ivar Berghei c70616e5c6 Add go module files 2022-11-18 21:30:23 +01:00
12 changed files with 54 additions and 137 deletions

4
.gitignore vendored
View File

@ -5,8 +5,6 @@ oauth2-proxy
test/*
cookies.txt
config
css/*.min.css
js/*.min.js
bin
ambiance/*.mp3
ambiance

12
bot.go
View File

@ -27,6 +27,18 @@ const (
maxBytes int = (frameSize * 2) * 2 // max size of opus data
)
/*
var (
token = "MTA0MDQwNTk3MDc3MTI1NTM1OQ.Gyg_y7.DqK6Tudd-iQVvgItkWvwGEwQZ7tY4qJBaBqTuQ"
channel = "675319944853979140"
server = "675319944853979136"
//channel = "1029091047902547980"
//server = "231872254525440000"
)
*/
var (
app = new(App)
config = viper.GetViper()

1
css/solarized-dark.min.css vendored Normal file
View File

@ -0,0 +1 @@
@import url(https://fonts.googleapis.com/css?family=Inconsolata);@import url(https://fonts.googleapis.com/css?family=PT+Sans);@import url(https://fonts.googleapis.com/css?family=PT+Sans+Narrow:400,700);img,legend{border:0}html,pre{color:#839496}pre,pre code{background-color:#002b36}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}body,figure{margin:0}a:focus{outline:dotted thin}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}mark{background:#ff0;color:#000}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap;word-wrap:break-word;border:1pt solid #586e75;padding:1em;box-shadow:5pt 5pt 8pt #073642}.tag,code,html{background-color:#073642}q{quotes:"\201C" "\201D" "\2018" "\2019"}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}svg:not(:root){overflow:hidden}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{padding:0}button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}button,input{line-height:normal}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=search]{-webkit-appearance:textfield;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}html{-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;font-family:'PT Sans',sans-serif;margin:1em}code,pre{font-family:Inconsolata,sans-serif}h1,h2,h3,h4,h5,h6{font-family:'PT Sans Narrow',sans-serif;font-weight:700}code{padding:2px}a{color:#b58900}.tag,h1{color:#d33682}a:hover,a:visited{color:#cb4b16}h1{font-size:2.8em}h2,h3,h4,h5,h6{color:#859900}h2{font-size:2.4em}h3{font-size:1.8em}h4{font-size:1.4em}h5{font-size:1.3em}h6{font-size:1.15em}.tag{padding:0 .2em;-webkit-border-radius:0.35em;-moz-border-radius:.35em;border-radius:.35em}.ACTIVE,.NEXT,.TODO{-webkit-border-radius:0.2em;-moz-border-radius:.2em}.done,.next,.todo{color:#002b36;background-color:#dc322f;padding:0 .2em}.TODO{border-radius:.2em;background-color:#2aa198}.ACTIVE,.NEXT{border-radius:.2em;background-color:#268bd2}.CANCELLED,.DONE,.WAITING{-webkit-border-radius:0.2em;-moz-border-radius:.2em}.CANCELLED,.DONE{border-radius:.2em;background-color:#859900}.WAITING{border-radius:.2em;background-color:#cb4b16}.HOLD,.NOTE{-webkit-border-radius:0.2em;-moz-border-radius:.2em;border-radius:.2em;background-color:#d33682}

2
db.go
View File

@ -16,7 +16,7 @@ func init() {
log.Println("db.go loading..")
var err error
app.db, err = pgx.Connect(context.Background(), config.GetString("db.connstring"))
app.db, err = pgx.Connect(context.Background(), connstring)
if err != nil {
log.Fatal(err)
}

View File

@ -3,9 +3,7 @@ package main
import (
"context"
"dndmusicbot/ffmpeg"
"dndmusicbot/loop"
discordspeaker "dndmusicbot/speaker"
"dndmusicbot/ytdl"
"encoding/json"
"fmt"
"log"
@ -42,10 +40,8 @@ func init() {
app.events.On("preload_song", app.preloadSong)
app.events.On("song_over", app.songOver)
//app.events.On("song_position", app.songPosition)
app.events.On("ambiance_play", app.ambiancePlay)
app.events.On("ambiance_stop", app.ambianceStop)
app.events.On("ambiance_add", app.ambianceAdd)
app.events.On("stop", app.stop)
app.events.On("next", app.nextSong)
@ -131,9 +127,7 @@ func (app *App) ambiancePlay(payload ...interface{}) {
if app.ambiance.IsPlaying() {
app.ambiance.Reset()
}
loop := loop.Loop(-1, play)
app.ambiance.Add(loop)
app.ambiance.Add(play)
discordspeaker.Unlock()
msg := make(map[string]interface{})
@ -159,48 +153,6 @@ func (app *App) ambianceStop(payload ...interface{}) {
}
func (app *App) ambianceAdd(payload ...interface{}) {
if !(len(payload) > 0) {
log.Println("addPlaylist called without a payload.")
return
}
log.Println("ambiance_add event received")
var data map[string]string
switch js := payload[0].(type) {
case json.RawMessage:
json.Unmarshal(js, &data)
default:
log.Println("newPlaylist called with invalid payload.")
return
}
amburl, ok := data["url"]
if !ok {
log.Println("addPlaylist without url")
return
}
ambtitle, ok := data["title"]
if !ok {
log.Println("addPlaylist without title")
return
}
err := ytdl.DownloadAmbiance(amburl, ambtitle)
if err != nil {
log.Println(err)
return
}
msg := make(map[string]interface{})
out := make(map[string]interface{})
msg["event"] = "ambiance_add"
out["type"] = ambtitle
msg["payload"] = out
ws_msg <- msg
}
func (app *App) songPosition(payload ...interface{}) {
if !app.queue.IsPlaying() {
return
@ -304,6 +256,16 @@ func (app *App) nextSong(payload ...interface{}) {
return
}
for {
time.Sleep(1 * time.Second)
if app.queue.QLen() == 0 {
log.Println("retrying...")
song = app.GetSong(app.active)
} else {
break
}
}
discordspeaker.Lock()
app.queue.Reset()
app.queue.Add(f)

View File

@ -24,7 +24,6 @@ type FFmpeg struct {
PMutex *sync.RWMutex
ProcessState *os.ProcessState
err chan error
fb chan bool
}
func NewFFmpeg(uri string, sampleRate int, channels int) (ff *FFmpeg, err error) {
@ -43,7 +42,6 @@ func NewFFmpeg(uri string, sampleRate int, channels int) (ff *FFmpeg, err error)
time.Sleep(500 * time.Millisecond)
}
RETRY:
ff = new(FFmpeg)
ff.PMutex = &sync.RWMutex{}
ff.Len = yt.Len
@ -55,7 +53,6 @@ RETRY:
ff.Cmd = exec.CommandContext(
ctx,
"ffmpeg",
"-xerror",
"-i", yt.Url,
"-f", "s16le",
"-v", "error",
@ -74,23 +71,18 @@ RETRY:
ff.Out = bytes.NewBuffer(make([]byte, 43920))
ff.Cmd.Stdout = ff.Out
exitctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
ff.Start()
return
}
func (ff *FFmpeg) Start() {
go func() {
ff.Cmd.Start()
ff.err <- ff.Cmd.Wait()
}()
select {
case <-exitctx.Done():
ff.Started = true
case <-ff.err:
log.Println("ffmpeg exited early, retry...")
goto RETRY
}
return
}
func (ff *FFmpeg) Close() error {

2
go.mod
View File

@ -2,6 +2,8 @@ module dndmusicbot
go 1.19
replace github.com/3d0c/gmf => /home/steino/dev/go/gmf
require (
github.com/bwmarrin/discordgo v0.26.1
github.com/dpup/gohubbub v0.0.0-20140517235056-2dc6969d22d8

2
js/Sortable.min.js vendored Normal file

File diff suppressed because one or more lines are too long

1
js/reconnecting-websocket.min.js vendored Normal file
View File

@ -0,0 +1 @@
!function(a,b){"function"==typeof define&&define.amd?define([],b):"undefined"!=typeof module&&module.exports?module.exports=b():a.ReconnectingWebSocket=b()}(this,function(){function a(b,c,d){function l(a,b){var c=document.createEvent("CustomEvent");return c.initCustomEvent(a,!1,!1,b),c}var e={debug:!1,automaticOpen:!0,reconnectInterval:1e3,maxReconnectInterval:3e4,reconnectDecay:1.5,timeoutInterval:2e3};d||(d={});for(var f in e)this[f]="undefined"!=typeof d[f]?d[f]:e[f];this.url=b,this.reconnectAttempts=0,this.readyState=WebSocket.CONNECTING,this.protocol=null;var h,g=this,i=!1,j=!1,k=document.createElement("div");k.addEventListener("open",function(a){g.onopen(a)}),k.addEventListener("close",function(a){g.onclose(a)}),k.addEventListener("connecting",function(a){g.onconnecting(a)}),k.addEventListener("message",function(a){g.onmessage(a)}),k.addEventListener("error",function(a){g.onerror(a)}),this.addEventListener=k.addEventListener.bind(k),this.removeEventListener=k.removeEventListener.bind(k),this.dispatchEvent=k.dispatchEvent.bind(k),this.open=function(b){h=new WebSocket(g.url,c||[]),b||k.dispatchEvent(l("connecting")),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","attempt-connect",g.url);var d=h,e=setTimeout(function(){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","connection-timeout",g.url),j=!0,d.close(),j=!1},g.timeoutInterval);h.onopen=function(){clearTimeout(e),(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onopen",g.url),g.protocol=h.protocol,g.readyState=WebSocket.OPEN,g.reconnectAttempts=0;var d=l("open");d.isReconnect=b,b=!1,k.dispatchEvent(d)},h.onclose=function(c){if(clearTimeout(e),h=null,i)g.readyState=WebSocket.CLOSED,k.dispatchEvent(l("close"));else{g.readyState=WebSocket.CONNECTING;var d=l("connecting");d.code=c.code,d.reason=c.reason,d.wasClean=c.wasClean,k.dispatchEvent(d),b||j||((g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onclose",g.url),k.dispatchEvent(l("close")));var e=g.reconnectInterval*Math.pow(g.reconnectDecay,g.reconnectAttempts);setTimeout(function(){g.reconnectAttempts++,g.open(!0)},e>g.maxReconnectInterval?g.maxReconnectInterval:e)}},h.onmessage=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onmessage",g.url,b.data);var c=l("message");c.data=b.data,k.dispatchEvent(c)},h.onerror=function(b){(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","onerror",g.url,b),k.dispatchEvent(l("error"))}},1==this.automaticOpen&&this.open(!1),this.send=function(b){if(h)return(g.debug||a.debugAll)&&console.debug("ReconnectingWebSocket","send",g.url,b),h.send(b);throw"INVALID_STATE_ERR : Pausing to reconnect websocket"},this.close=function(a,b){"undefined"==typeof a&&(a=1e3),i=!0,h&&h.close(a,b)},this.refresh=function(){h&&h.close()}}return a.prototype.onopen=function(){},a.prototype.onclose=function(){},a.prototype.onconnecting=function(){},a.prototype.onmessage=function(){},a.prototype.onerror=function(){},a.debugAll=!1,a.CONNECTING=WebSocket.CONNECTING,a.OPEN=WebSocket.OPEN,a.CLOSING=WebSocket.CLOSING,a.CLOSED=WebSocket.CLOSED,a});

View File

@ -1,4 +1,4 @@
window.onload = function() {
window.onload = function () {
const ws = new ReconnectingWebSocket(((window.location.protocol === "https:") ? "wss://" : "ws://") + window.location.host + "/ws");
const items = document.querySelector("#items");
@ -24,18 +24,17 @@ window.onload = function() {
group: "dndmusicbot-playlists",
filter: ".locked",
onMove: (e) => {
if (e.related)
{
if (e.related) {
return !e.related.classList.contains('locked');
}
},
invertSwap: true,
store: {
get: function(sortable) {
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
set: function(sortable) {
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
@ -46,18 +45,17 @@ window.onload = function() {
group: "dndmusicbot-ambiance",
filter: ".locked",
onMove: (e) => {
if (e.related)
{
if (e.related) {
return !e.related.classList.contains('locked');
}
},
invertSwap: true,
store: {
get: function(sortable) {
get: function (sortable) {
var order = localStorage.getItem(sortable.options.group.name);
return order ? order.split('|') : [];
},
set: function(sortable) {
set: function (sortable) {
var order = sortable.toArray();
localStorage.setItem(sortable.options.group.name, order.join('|'));
}
@ -122,32 +120,12 @@ window.onload = function() {
}
}
document.querySelector("#addambiance").addEventListener("click", (e) => {
e.preventDefault()
output.innerText = ""
var title = document.querySelector("#inputambiance > input[name='title']")
var url = document.querySelector("#inputambiance > input[name='url']")
if (title.value == "" || url.value == "") {
output.innerText = "Title or Url is empty!"
return
}
ws.send(JSON.stringify({
"event": "ambiance_add",
"payload": {
"title": title.value,
"url": url.value
}
}))
})
submit.addEventListener("click", (e) => {
e.preventDefault()
output.innerText = ""
var title = document.querySelector("#inputplaylist > input[name='title']")
var url = document.querySelector("#inputplaylist > input[name='url']")
var title = document.querySelector(".container2 input[name='title'")
var url = document.querySelector(".container2 input[name='url'")
if (title.value == "" || url.value == "") {
output.innerText = "Title or Url is empty!"
return
@ -160,9 +138,6 @@ window.onload = function() {
"url": url.value
}
}))
title.innerText = ""
url.innerText = ""
})
document.querySelectorAll("#items").forEach(item => item.addEventListener("click", (e) => {

View File

@ -5,8 +5,8 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>D&D Music Bot!</title>
<link rel="stylesheet" href="/css/solarized-dark.min.css">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/solarized-dark.min.css">
</head>
<body>
<div><h2 class="bot">Playlists</h2></div>
@ -16,17 +16,17 @@
{{ end}}
<div class="item locked" data-id="reset">Stop</div>
</div>
<div id="inputplaylist" class="container2">
<div class="container2">
<input name="title" type="text" placeholder="Enter name..">
<input name="url" type="text" placeholder="https://youtube.com/playlist?list=...">
<input id="addplaylist" name="submit" value="Add" type="submit">
<input id="prev" name="prev" type="button" value="prev">
<input id="next" name="next" type="button" value="next">
</div>
<div class="container2">
<p id="output"></p>
</div>
<div id="info" class="container2">
<input id="prev" name="prev" type="button" value="prev">
<input id="next" name="next" type="button" value="next">
<a id="link" style="text-decoration: none;">
<span id="channel"></span>
<span> - </span>
@ -41,11 +41,6 @@
{{ end}}
<div class="item locked" data-id="reset">Stop</div>
</div>
<div id="inputambiance" class="container2">
<input name="title" type="text" placeholder="Enter name..">
<input name="url" type="text" placeholder="Enter url...">
<input id="addambiance" name="submit" value="Add" type="submit">
</div>
<!-- The Modal -->
<div id="waiting" class="modal">
<!-- Modal content -->

View File

@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"os/exec"
"path/filepath"
"time"
"github.com/tidwall/gjson"
@ -46,25 +45,3 @@ func NewYTdl(uri string) (*YTdl, error) {
return &YTdl{title, geturl, channel, duration}, nil
}
func DownloadAmbiance(uri string, name string) error {
err := exec.Command(
"./bin/yt-dlp_linux",
uri,
"-x",
"--audio-format", "mp3",
"--postprocessor-args", "-ar 48000 -ac 2",
"--cookies", "./cookies.txt",
"--no-call-home",
"--no-cache-dir",
"--restrict-filenames",
"-f", "140",
"-o", filepath.Join("./ambiance/", name+".mp3"),
).Run()
if err != nil {
return nil
}
return nil
}