commit 6ff024b25eace3acfefda9288795810ea37e79aa Author: Alexander "Arav" Andreev Date: Tue Mar 8 01:17:24 2022 +0400 Initial commit. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..43282ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +bin/* +!bin/.keep +.vscode \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..826701c --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2022 Alexander "Arav" Andreev + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice, this permission notice and the word "NIGGER" shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100755 index 0000000..c798f17 --- /dev/null +++ b/Makefile @@ -0,0 +1,40 @@ +TARGET=dwelling-radio + +SYSCTL=${shell which systemctl} +SYSDDIR_=${shell pkg-config systemd --variable=systemdsystemunitdir} +SYSDDIR=${SYSDDIR_:/%=%} +DESTDIR=/ + +LDFLAGS=-ldflags "-s -w" + +all: ${TARGET} + +.PHONY: ${TARGET} + +${TARGET}: + go build -o bin/$@ ${LDFLAGS} cmd/$@/main.go + +run: + bin/${TARGET} -conf configs/config.yaml + +install: + install -Dm 0755 bin/${TARGET} ${DESTDIR}usr/bin/${TARGET} + install -Dm 0644 configs/config.yaml ${DESTDIR}etc/dwelling/radio.yaml + install -Dm 0644 LICENSE ${DESTDIR}usr/share/licenses/${TARGET}/LICENSE + + install -Dm 0644 init/systemd/${TARGET}.service ${DESTDIR}${SYSDDIR}/${TARGET}.service + + install -Dm 0755 -d ${DESTDIR}var/log/${TARGET} + +stop-service: + ${SYSCTL} stop ${TARGET}.service + ${SYSCTL} disable ${TARGET}.service + +uninstall: + rm ${DESTDIR}usr/bin/${TARGET} + rm ${DESTDIR}usr/share/licenses/${TARGET}/LICENSE + + rm ${DESTDIR}${SYSDDIR}/${TARGET}.service + +clean: + go clean diff --git a/bin/.keep b/bin/.keep new file mode 100644 index 0000000..e69de29 diff --git a/build/archlinux/PKGBUILD b/build/archlinux/PKGBUILD new file mode 100644 index 0000000..1a6c41c --- /dev/null +++ b/build/archlinux/PKGBUILD @@ -0,0 +1,26 @@ +# Maintainer: Alexander "Arav" Andreev +pkgname=dwelling-radio +pkgver=1.0.0 +pkgrel=1 +pkgdesc="Arav's dwelling / Radio" +arch=('i686' 'x86_64' 'arm' 'armv6h' 'armv7h' 'aarch64') +url="https://git.arav.top/Arav/dwelling-radio" +license=('MIT') +source=('git+https://git.arav.top/Arav/dwelling-radio.git') +md5sums=('SKIP') +makedepends=('go') +backup=('etc/dwelling/radio.yaml') + +build() { + cd "$srcdir/$pkgname" + make DESTDIR="$pkgdir/" +} + +package() { + cd "$srcdir/$pkgname" + make DESTDIR="$pkgdir/" install +} + +post_install() { + chown dwradio:root /var/log/dwelling-radio +} \ No newline at end of file diff --git a/build/dwelling-radio.conf b/build/dwelling-radio.conf new file mode 100644 index 0000000..9b9906a --- /dev/null +++ b/build/dwelling-radio.conf @@ -0,0 +1,2 @@ +# sysusers.d +u dwradio - - \ No newline at end of file diff --git a/cmd/dwelling-radio/main.go b/cmd/dwelling-radio/main.go new file mode 100644 index 0000000..654c464 --- /dev/null +++ b/cmd/dwelling-radio/main.go @@ -0,0 +1,63 @@ +package main + +import ( + "dwelling-radio/internal/configuration" + "dwelling-radio/internal/handlers" + "dwelling-radio/pkg/logging" + "dwelling-radio/pkg/server" + "flag" + "log" + "os" + "os/signal" + "syscall" +) + +var configPath *string = flag.String("conf", "config.yaml", "path to configuration file") +var logToStdout *bool = flag.Bool("log-stdout", false, "write logs to stdout") + +func main() { + flag.Parse() + + config, err := configuration.LoadConfiguration(*configPath) + if err != nil { + log.Fatalln(err) + } + + if *logToStdout { + config.Log.ToStdout = true + } + + defer func() { + if nt, addr := config.SplitNetworkAddress(); nt == "unix" { + os.Remove(addr) + } + }() + + logErr, err := logging.NewLogger(config.Log.Error, config.Log.ToStdout) + if err != nil { + log.Fatalln("error logger:", err) + } + defer logErr.Close() + + hand := handlers.NewRadioHandlers(config, logErr) + srv := server.NewHttpServer() + + srv.ServeStatic("/assets/*filepath", hand.AssetsFS()) + srv.GET("/", hand.Index) + srv.GET("/stats", hand.Stats) + srv.GET("/lastsong", hand.LastSong) + srv.GET("/playlist", hand.Playlist) + + if err := srv.Start(config.SplitNetworkAddress()); err != nil { + logErr.Fatalln(err) + } + + doneSignal := make(chan os.Signal, 1) + signal.Notify(doneSignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + + <-doneSignal + + if err := srv.Stop(); err != nil { + logErr.Fatalln(err) + } +} diff --git a/configs/config.yaml b/configs/config.yaml new file mode 100644 index 0000000..95338b8 --- /dev/null +++ b/configs/config.yaml @@ -0,0 +1,14 @@ +# Sets network type (could be tcp{,4,6}, unix) +# and address:port or /path/to/unix.sock to +# listen on. +listen_on: "unix /tmp/dwelling-radio.sock" +icecast: + # URL to Icecast's status-json.xsl + url: "http://reimu.arav.home.arpa/status-json.xsl" + playlist_path: "/var/log/icecast/playlist.log" +# How much songs to list on a page +list_last_n_songs: 10 +log: + # Output messages to stdout as well as to theirs files. + stdout: false + error: "/var/log/dwelling-radio/error.log" \ No newline at end of file diff --git a/configs/nginx.conf b/configs/nginx.conf new file mode 100644 index 0000000..e27132b --- /dev/null +++ b/configs/nginx.conf @@ -0,0 +1,72 @@ +server { + listen 443 ssl http2; + listen 8090; # Tor + listen 127.0.0.1:8111; # I2P + + server_name radio.arav.top radio.arav.i2p mkgnmhmzqm7kyzv7jnzzafvgm7xlmlfvzhgorpapd5or2arnhuktqd.onion; + access_log /var/log/nginx/dwelling/radio.log main if=$nolog; + + ssl_certificate /etc/letsencrypt/live/arav.top/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/arav.top/privkey.pem; + + + add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; media-src 'self'; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; font-src 'self'; form-action 'none'"; + add_header X-Frame-Options "DENY"; + add_header X-Content-Type-Options "nosniff"; + add_header X-XSS-Protection "1; mode=block"; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"; + add_header Onion-Location "http://mkgnmhmzqm7kyzv7jnzzafvgm7xlmlfvzhgorpapd5or2arnhuktqd.onion$request_uri"; + + + location / { + proxy_pass http://unix:/tmp/dwelling-radio.sock/; + proxy_buffering off; + + proxy_set_header X-Client-Timezone $gi2_location_tz; + proxy_set_header Host $host; + proxy_set_header Schema $scheme; + } + + + location =/filelist { + add_header Content-Type "text/html"; + alias $dwelling_root/radio/static/radio_filelist.html; + } + + + location /live/ { + proxy_pass http://127.0.0.1:8000/; + proxy_buffering off; + + proxy_set_header X-Real-IP $remote_addr; + } + + location /live/admin/ { + deny all; + } +} + +server { + listen 8000; + + server_name radio.arav.top; + access_log /var/log/nginx/dwelling/radio.http.log main if=$nolog; + + + add_header Content-Security-Policy "default-src 'none'; script-src 'none'; style-src 'self'; img-src 'self'; media-src 'self'; object-src 'none'; frame-src 'none'; frame-ancestors 'none'; font-src 'self'; form-action 'none'"; + add_header X-Frame-Options "DENY"; + add_header X-Content-Type-Options "nosniff"; + add_header X-XSS-Protection "1; mode=block"; + add_header Onion-Location "http://mkgnmhmzqm7kyzv7jnzzafvgm7xlmlfvzhgorpapd5or2arnhuktqd.onion/live$request_uri"; + + + location / { + proxy_pass http://127.0.0.1:8000/; + proxy_buffering off; + } + + + location /admin/ { + deny all; + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..3776b47 --- /dev/null +++ b/go.mod @@ -0,0 +1,10 @@ +module dwelling-radio + +go 1.17 + +require ( + github.com/Joker/jade v1.1.3 + github.com/julienschmidt/httprouter v1.3.0 + github.com/pkg/errors v0.9.1 + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..f2069f1 --- /dev/null +++ b/go.sum @@ -0,0 +1,36 @@ +github.com/Joker/hpp v1.0.0/go.mod h1:8x5n+M1Hp5hC0g8okX3sR3vFQwynaX/UgSOM9MeBKzY= +github.com/Joker/jade v1.1.3 h1:Qbeh12Vq6BxURXT1qZBRHsDxeURB8ztcL6f3EXSGeHk= +github.com/Joker/jade v1.1.3/go.mod h1:T+2WLyt7VH6Lp0TRxQrUYEs64nRc83wkMQrfeIQKduM= +github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= +github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/net v0.0.0-20190327091125-710a502c58a2/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/init/systemd/dwelling-radio.service b/init/systemd/dwelling-radio.service new file mode 100755 index 0000000..0ffd60a --- /dev/null +++ b/init/systemd/dwelling-radio.service @@ -0,0 +1,12 @@ +[Unit] +Description=dwelling-radio +After=network-online.target + +[Service] +Type=simple +Restart=on-failure +DynamicUser=yes +ExecStart=/usr/bin/dwelling-radio -conf /etc/dwelling/radio.yaml + +[Install] +WantedBy=multi-user.target diff --git a/internal/configuration/configuration.go b/internal/configuration/configuration.go new file mode 100644 index 0000000..32e62d5 --- /dev/null +++ b/internal/configuration/configuration.go @@ -0,0 +1,47 @@ +package configuration + +import ( + "os" + "strings" + + "github.com/pkg/errors" + "gopkg.in/yaml.v3" +) + +// Configuration holds a list of process names to be tracked and a listen address. +type Configuration struct { + ListenOn string `yaml:"listen_on"` + Icecast struct { + URL string `yaml:"url"` + Playlist string `yaml:"playlist_path"` + } `yaml:"icecast"` + ListLastNSongs int `yaml:"list_last_n_songs"` + Log struct { + ToStdout bool `yaml:"stdout"` + Error string `yaml:"error"` + } `yaml:"log"` +} + +func LoadConfiguration(path string) (*Configuration, error) { + configFile, err := os.Open(path) + if err != nil { + return nil, errors.Wrap(err, "failed to open configuration file") + } + defer configFile.Close() + + config := &Configuration{} + + if err := yaml.NewDecoder(configFile).Decode(config); err != nil { + return nil, errors.Wrap(err, "failed to parse configuration file") + } + + return config, nil +} + +// SplitNetworkAddress splits ListenOn option and returns as two strings +// network type (e.g. tcp, unix, udp) and address:port or /path/to/prog.socket +// to listen on. +func (c *Configuration) SplitNetworkAddress() (string, string) { + s := strings.Split(c.ListenOn, " ") + return s[0], s[1] +} diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go new file mode 100644 index 0000000..126fee4 --- /dev/null +++ b/internal/handlers/handlers.go @@ -0,0 +1,112 @@ +package handlers + +import ( + "dwelling-radio/internal/configuration" + "dwelling-radio/internal/radio" + "dwelling-radio/pkg/logging" + "dwelling-radio/pkg/utils" + "embed" + "encoding/json" + "fmt" + "html/template" + "io/fs" + "net/http" + + "github.com/Joker/jade" +) + +var compiledTemplates map[string]*template.Template + +//go:embed web/assets +var assetsDir embed.FS + +//go:embed web/templates +var templatesDir embed.FS + +type NotFoundData struct { + MainSite string +} + +type IndexData struct { + MainSite string + Status *radio.IcecastStatus + Songs []radio.Song +} + +type RadioHandlers struct { + conf *configuration.Configuration + logErr *logging.Logger +} + +func NewRadioHandlers(conf *configuration.Configuration, lErr *logging.Logger) *RadioHandlers { + compileTemplates(lErr) + + return &RadioHandlers{ + conf: conf, + logErr: lErr} +} + +func (h *RadioHandlers) AssetsFS() http.FileSystem { + f, _ := fs.Sub(assetsDir, "web/assets") + return http.FS(f) +} + +func (h *RadioHandlers) Index(w http.ResponseWriter, r *http.Request) { + rad, err := radio.IcecastGetStatus(h.conf.Icecast.URL) + if err != nil { + h.logErr.Println("failed to get Icecast status:", err) + rad = &radio.IcecastStatus{} + } + + if err := compiledTemplates["index"].Execute(w, &IndexData{ + MainSite: utils.MainSite(r.Host), + Status: rad, + Songs: radio.IcecastLastPlayedSongs(h.conf.ListLastNSongs, + h.conf.Icecast.Playlist), + }); err != nil { + w.WriteHeader(http.StatusInternalServerError) + h.logErr.Fatalln("failed to execute Index template:", err) + } +} + +func (h *RadioHandlers) Stats(w http.ResponseWriter, r *http.Request) { + st, err := radio.IcecastGetStatus(h.conf.Icecast.URL) + if err != nil { + st = &radio.IcecastStatus{} + } + + json.NewEncoder(w).Encode(st) +} + +func (h *RadioHandlers) LastSong(w http.ResponseWriter, r *http.Request) { + songs := radio.IcecastLastPlayedSongs(1, h.conf.Icecast.Playlist) + json.NewEncoder(w).Encode(songs[0]) +} + +func (h *RadioHandlers) Playlist(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-Disposition", "attachment; filename=\"radio.arav.top.m3u\"") + + pf, _ := assetsDir.Open("radio.arav.top.m3u") + defer pf.Close() + + fmt.Fprint(w, pf) +} + +func compileTemplates(lErr *logging.Logger) { + compiledTemplates = make(map[string]*template.Template) + + t, _ := fs.Sub(templatesDir, "web/templates") + templatesFS := http.FS(t) + + indexStr, err := jade.ParseFileFromFileSystem("index.jade", templatesFS) + if err != nil { + lErr.Fatalln(err) + } + + indexTpl, err := template.New("index").Parse(indexStr) + if err != nil { + lErr.Fatalln(err) + } + + compiledTemplates["index"] = indexTpl +} diff --git a/internal/handlers/web/assets/css/main.css b/internal/handlers/web/assets/css/main.css new file mode 100644 index 0000000..97dc940 --- /dev/null +++ b/internal/handlers/web/assets/css/main.css @@ -0,0 +1,154 @@ +@font-face { + font-family: 'Roboto Condensed'; + font-style: normal; + font-weight: 400; + src: local('RobotoCondensed'), local('RobotoCondensed-Regular'), + url(/shared/fonts/RobotoCondensed-Regular.ttf); } + +:root { + --background-color: #0a0a0a; + --primary-color: #cd2682; + --secondary-color: #9f2b68; + --text-color: #f5f5f5; + --text-indent: 1.6rem; + scrollbar-color: var(--primary-color) var(--background-color); } + +@media (prefers-color-scheme: light) { + :root { + --background-color: #f5f5f5; + --primary-color: #9f2b68; + --secondary-color: #cd2682; + --text-color: #0a0a0a; } } + +* { margin: 0; } + +::selection { + background-color: var(--secondary-color); + color: var(--background-color); } + +a, +button { + color: var(--primary-color); + text-decoration: none; } + +a:hover, +button:hover { + color: var(--secondary-color); + cursor: pointer; + text-decoration: underline dotted; + transition: .5s; } + +button { + background: none; + border: none; + font: inherit; + padding: 0; } + +p { + text-align: justify; + line-height: var(--text-indent); + text-indent: var(--text-indent); } + +p:not(:last-child) { margin-bottom: .1rem; } + +h1, +h2 { + font-size: 1.8rem; + font-variant: small-caps; + text-align: center; + margin-bottom: 1rem; } + +h2 { + font-size: 1.4rem; + margin: 1rem 0; } + +small { font-size: .8rem; } + +small.player-links a { margin: 0 .2rem; } + +audio { + background-color: var(--primary-color); + box-shadow: 5px 5px var(--primary-color); + width: 100%; } + +@media screen and (-webkit-min-device-pixel-ratio:0) { + audio::-webkit-media-controls-panel { + background-color: var(--secondary-color); } + + audio { border-radius: 1.6rem; } } + +@-moz-document url-prefix() { + audio { border-radius: 0; } } + +html { margin-left: calc(100vw - 100%); } + +body { + background-color: var(--background-color); + color: var(--text-color); + font-family: 'Roboto Condensed', Roboto, sans-serif; + font-size: 1.1rem; + margin: 0 auto; + max-width: 960px; + width: 98%; } + +header { + display: flex; + flex-wrap: wrap; + justify-content: space-between; } + +#logo { + display: block; + width: 360px; } + +#logo text { fill: var(--text-color); } + +#logo .logo { + font-size: 2rem; + font-variant-caps: small-caps; + font-weight: bold; } + +@media screen and (-webkit-min-device-pixel-ratio:0) { + #logo .logo { font-size: 2.082rem; } } + +@-moz-document url-prefix() { + #logo .logo { font-size: 2rem; } } + +#logo .under { font-size: .88rem; } + +nav { margin-top: .5rem; } + +nav a { font-variant: small-caps; } + +nav h1 { + color: var(--secondary-color); + margin: 0; } + +section { margin-top: 1rem; } + +#last-played { + margin: 0 auto; + min-width: 80%; + width: 80%; } + +#last-played tbody tr { + display: grid; + gap: .5rem; + grid-template-columns: 3rem 1fr 1fr; } + +#last-played tbody tr td:nth-child(2) { text-align: right; } + +footer { + font-size: .8rem; + text-align: center; + padding: 1rem 0; } + +@media screen and (max-width: 640px) { + header { display: block; } + + #logo { + margin: 0 auto; + width: 100%; } + + nav { + width: 100%; + text-align: center; } } \ No newline at end of file diff --git a/internal/handlers/web/assets/fonts/LICENSE.RobotoCondensed.txt b/internal/handlers/web/assets/fonts/LICENSE.RobotoCondensed.txt new file mode 100644 index 0000000..75b5248 --- /dev/null +++ b/internal/handlers/web/assets/fonts/LICENSE.RobotoCondensed.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/handlers/web/assets/fonts/RobotoCondensed-Regular.ttf b/internal/handlers/web/assets/fonts/RobotoCondensed-Regular.ttf new file mode 100755 index 0000000..9a1418d Binary files /dev/null and b/internal/handlers/web/assets/fonts/RobotoCondensed-Regular.ttf differ diff --git a/internal/handlers/web/assets/img/favicon.svg b/internal/handlers/web/assets/img/favicon.svg new file mode 100755 index 0000000..97bce83 --- /dev/null +++ b/internal/handlers/web/assets/img/favicon.svg @@ -0,0 +1 @@ + diff --git a/internal/handlers/web/assets/js/main.js b/internal/handlers/web/assets/js/main.js new file mode 100644 index 0000000..f9b23f0 --- /dev/null +++ b/internal/handlers/web/assets/js/main.js @@ -0,0 +1,48 @@ +function $(id) { return document.getElementById(id); } + +function updateRadioStatus() { + fetch("/stats") + .then(r => r.json()) + .then(r => { + $("radio-status").innerHTML = + `On-air since `; + $("radio-song").textContent = r.song; + $("radio-listeners").textContent = r.listeners; + $("radio-listener-peak").textContent = r.listener_peak; + }).catch(() => { + $("radio-status").textContent = "Radio is offline."; + $("radio-song").textContent = + $("radio-listeners").textContent = + $("radio-listener-peak").textContent = "n/a"; + }); +} + +function updateLastPlayedSong() { + fetch('/lastsong') + .then(r => r.json()) + .then(last_played => { + let cur_artist = $('last-played').firstChild.lastChild.children[1].innerText; + let cur_title = $('last-played').firstChild.lastChild.lastChild.innerText; + + if (last_played.artist == cur_artist && last_played.title == cur_title) + return; + + $('last-played').firstChild.firstChild.remove(); + + let row = $('last-played').insertRow(); + let start_time = row.insertCell(); + start_time.appendChild(document.createTextNode(last_played.start_time_local)); + let artist_cell = row.insertCell(); + artist_cell.appendChild(document.createTextNode(last_played.artist)); + let title_cell = row.insertCell(); + title_cell.appendChild(document.createTextNode(last_played.title)); + }); +} + +document.getElementById("btn-update").addEventListener("click", () => { + updateLastPlayedSong(); + updateRadioStatus(); +}) + +setInterval(updateRadioStatus, 45000); +setInterval(updateLastPlayedSong, 45000); \ No newline at end of file diff --git a/internal/handlers/web/assets/radio.arav.top.m3u b/internal/handlers/web/assets/radio.arav.top.m3u new file mode 100644 index 0000000..8730df1 --- /dev/null +++ b/internal/handlers/web/assets/radio.arav.top.m3u @@ -0,0 +1,9 @@ +#EXTM3U +#EXTINF:-1,Arav's dwelling / Radio +http://radio.arav.top:8000/stream.ogg +#EXTINF:-1,Arav's dwelling / Radio (HTTPS) +https://radio.arav.top/live/stream.ogg +#EXTINF:-1,Arav's dwelling / Radio on Tor +http://wsmkgnmhmzqm7kyzv7jnzzafvgm7xlmlfvzhgorpapd5or2arnhuktqd.onion/live/stream.ogg +#EXTINF:-1,Arav's dwelling / Radio on I2P +http://radio.arav.i2p/live/stream.ogg \ No newline at end of file diff --git a/internal/handlers/web/templates/index.jade b/internal/handlers/web/templates/index.jade new file mode 100644 index 0000000..1a954c9 --- /dev/null +++ b/internal/handlers/web/templates/index.jade @@ -0,0 +1,59 @@ +mixin radioStatus(date, iso) + if (date != "n/a") + p #[span#radio-status On-air since #[time(datetime=iso)= date]] + else + p #[span#radio-status Radio is offline.] + +doctype html +html(lang='en') + head + title Arav's dwelling / Radio + meta(charset='utf-8') + meta(http-equiv='X-UA-Compatible' content='IE=edge') + meta(name='viewport' content='width=device-width, initial-scale=1.0') + meta(name='theme-color' content='#cd2682') + meta(name='description' content='Internet-radio broadcasting from under my desk.') + link(rel='icon' href='/assets/img/favicon.svg' sizes='any' type='image/svg+xml') + link(href='/assets/css/main.css' rel='stylesheet') + script(src='/assets/js/main.js' defer) + body + header + svg#logo(viewBox='0 -25 216 40') + text.logo Arav's dwelling + text.under(y='11') Welcome to my sacred place, wanderer + nav + a(href=.MainSite) Back to main website + h1 Radio + section + small.player-links + a(href='/filelist') filelist + a(href='/playlist') playlist (.m3u) + a(href='/live/stream.ogg') direct link + a(href='http://radio.arav.top:8000/stream.ogg') direct link (http) + a(href='http://wsmkgnmhmzqm7kyzv7jnzzafvgm7xlmlfvzhgorpapd5or2arnhuktqd.onion/live/stream.ogg') direct link (Tor) + a(href='http://radio.arav.i2p/live/stream.ogg') direct link (I2P) + | OGG 128 Kb/s + audio(preload='none' controls) + source(src='/live/stream.ogg' type='audio/ogg') + | Your browser doesn't support an audio element, it's sad... But you always can take the #[a(href='/playlist') playlist]! + +radioStatus(.Status.ServerStartDate, .Status.ServerStartISO8601) + p Now playing: #[span#radio-song= .Status.Song()] + p Current/peak listeners: #[span#radio-listeners= .Status.Listeners] / #[span#radio-listener-peak= .Status.ListenerPeak] + p + small Notice: information updates every 45 seconds. But you can #[button(id='btn-update') update] it forcibly. + if (.Status.LastSongs) + section + h2 Last 10 songs + table#last-played + each song in .Status.Songs + tr + td= song.Time + td= song.Artist + td= song.Title + section + p The largest number of simultaneous listeners was #[b 7] at #[time(datetime='2022-02-19') 19 February 2022], and the song was "Röyksopp - 49 Percent". + section + h2 Privacy statements + p Logs are collected and include access date and time, IP-address, User-Agent, referer URL, request. This website makes use of JavaScript to update a radio status and last 10 songs list. + footer + | 2017—2022 Arav <#[a(href='mailto:me@arav.top') me@arav.top]> diff --git a/internal/radio/icecast.go b/internal/radio/icecast.go new file mode 100644 index 0000000..f32e24a --- /dev/null +++ b/internal/radio/icecast.go @@ -0,0 +1,90 @@ +package radio + +import ( + "encoding/json" + "fmt" + "net/http" + "os/exec" + "strings" + "time" +) + +type IcecastStatusDTO struct { + Icestats struct { + ServerStartISO8601 string `json:"server_start_iso8601"` + ServerStartDate string `json:"server_start"` + Source struct { + Artist string `json:"artist"` + Title string `json:"title"` + ListenerPeak int `json:"listener_peak"` + Listeners int `json:"listeners"` + } `json:"source"` + } `json:"icestats"` +} + +type IcecastStatus struct { + ServerStartISO8601 string `json:"server_start_iso8601"` + ServerStartDate string `json:"server_start"` + SongName string `json:"song"` + ListenerPeak int `json:"listener_peak"` + Listeners int `json:"listeners"` +} + +type Song struct { + Time string `json:"time"` + Artist string `json:"artist"` + Title string `json:"title"` +} + +func IcecastGetStatus(icecastURL string) (*IcecastStatus, error) { + resp, err := http.Get(icecastURL) + if err != nil { + return nil, err + } + + iceStatDTO := &IcecastStatusDTO{} + + if err := json.NewDecoder(resp.Body).Decode(iceStatDTO); err != nil { + return nil, err + } + + iceStat := &IcecastStatus{ + ServerStartISO8601: iceStatDTO.Icestats.ServerStartISO8601, + ServerStartDate: iceStatDTO.Icestats.ServerStartDate, + SongName: iceStatDTO.Song(), + ListenerPeak: iceStatDTO.Icestats.Source.ListenerPeak, + Listeners: iceStatDTO.Icestats.Source.Listeners, + } + + return iceStat, nil +} + +func (is *IcecastStatusDTO) Song() string { + return fmt.Sprintf("%s - %s", is.Icestats.Source.Artist, is.Icestats.Source.Title) +} + +func IcecastLastPlayedSongs(lastNSongs int, playlistPath string) []Song { + songs := make([]Song, 0) + + cmd := fmt.Sprintf("tail -n%d %s | head -n-1 | cut -d\" | \" -f1,4", lastNSongs+1, playlistPath) + o := exec.Command("bash", "-c", cmd) + out, _ := o.CombinedOutput() + + if len(out) == 0 { + return songs + } + + songs_ := strings.Split(string(out), "\n") + + for _, song := range songs_ { + ts := strings.Split(song, "|") + tim, _ := time.Parse("02/01/2006:15:04:05 -0700", ts[0]) + at := strings.Split(ts[1], " - ") + songs = append(songs, Song{ + Time: tim.UTC().Format("15:04"), + Artist: at[0], + Title: at[1]}) + } + + return songs +} diff --git a/pkg/logging/logger.go b/pkg/logging/logger.go new file mode 100644 index 0000000..95283b4 --- /dev/null +++ b/pkg/logging/logger.go @@ -0,0 +1,99 @@ +package logging + +import ( + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "github.com/pkg/errors" +) + +type Logger struct { + file io.WriteCloser + toStdout bool + mut sync.Mutex +} + +// NewLogger creates a Logger instance with given filename and +// toStdout tells wether to write to Stdout as well or not. +func NewLogger(path string, toStdout bool) (*Logger, error) { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660) + if err != nil { + return nil, errors.Wrap(err, "failed to open log file") + } + + return &Logger{file: f, toStdout: toStdout}, nil +} + +func (l *Logger) Println(v ...interface{}) { + l.mut.Lock() + defer l.mut.Unlock() + + nowStr := time.Now().UTC().Format(time.RFC3339) + + fmt.Fprintln(l.file, nowStr, v) + + if l.toStdout { + fmt.Println(nowStr, v) + } +} + +func (l *Logger) Printf(format string, v ...interface{}) { + l.mut.Lock() + defer l.mut.Unlock() + + // Ensure a new line will be written + if !strings.HasSuffix(format, "\n") { + format += "\n" + } + + nowStr := time.Now().UTC().Format(time.RFC3339) + + fmt.Fprintf(l.file, nowStr+" "+format, v...) + + if l.toStdout { + fmt.Printf(nowStr+" "+format, v...) + } +} + +func (l *Logger) Fatalln(v ...interface{}) { + l.mut.Lock() + + nowStr := time.Now().UTC().Format(time.RFC3339) + + fmt.Fprintln(l.file, nowStr, v) + + if l.toStdout { + fmt.Println(nowStr, v) + } + + l.file.Close() + os.Exit(1) +} + +func (l *Logger) Fatalf(format string, v ...interface{}) { + l.mut.Lock() + + // Ensure a new line will be written + if !strings.HasSuffix(format, "\n") { + format += "\n" + } + + nowStr := time.Now().UTC().Format(time.RFC3339) + + fmt.Fprintf(l.file, nowStr+" "+format, v...) + + if l.toStdout { + fmt.Printf(nowStr+" "+format, v...) + } + + l.file.Close() + os.Exit(1) +} + +func (l *Logger) Close() error { + return l.file.Close() +} diff --git a/pkg/server/http.go b/pkg/server/http.go new file mode 100644 index 0000000..6a7a3e1 --- /dev/null +++ b/pkg/server/http.go @@ -0,0 +1,92 @@ +package server + +import ( + "context" + "log" + "net" + "net/http" + "os" + "time" + + "github.com/julienschmidt/httprouter" +) + +type HttpServer struct { + server *http.Server + router *httprouter.Router +} + +func NewHttpServer() *HttpServer { + r := httprouter.New() + return &HttpServer{ + server: &http.Server{ + ReadTimeout: 3 * time.Second, + WriteTimeout: 3 * time.Second, + Handler: r, + }, + router: r, + } +} + +func (s *HttpServer) GET(path string, handler http.HandlerFunc) { + s.router.Handler(http.MethodGet, path, handler) +} + +func (s *HttpServer) POST(path string, handler http.HandlerFunc) { + s.router.Handler(http.MethodPost, path, handler) +} + +func (s *HttpServer) PATCH(path string, handler http.HandlerFunc) { + s.router.Handler(http.MethodPatch, path, handler) +} + +func (s *HttpServer) PUT(path string, handler http.HandlerFunc) { + s.router.Handler(http.MethodPut, path, handler) +} + +func (s *HttpServer) DELETE(path string, handler http.HandlerFunc) { + s.router.Handler(http.MethodDelete, path, handler) +} + +func (s *HttpServer) ServeStatic(path string, fsys http.FileSystem) { + s.router.ServeFiles(path, fsys) +} + +func (s *HttpServer) SetNotFoundHandler(handler http.HandlerFunc) { + s.router.NotFound = handler +} + +// GetURLParam wrapper around underlying router for getting URL parameters. +func GetURLParam(r *http.Request, param string) string { + return httprouter.ParamsFromContext(r.Context()).ByName(param) +} + +func (s *HttpServer) Start(network, address string) error { + listener, err := net.Listen(network, address) + if err != nil { + return err + } + + if listener.Addr().Network() == "unix" { + os.Chmod(address, 0777) + } + + go func() { + if err = s.server.Serve(listener); err != nil && err != http.ErrServerClosed { + log.Fatalln(err) + } + }() + + return nil +} + +func (s *HttpServer) Stop() error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + if err := s.server.Shutdown(ctx); err != nil { + return err + } + + return nil +} diff --git a/pkg/utils/dwelling.go b/pkg/utils/dwelling.go new file mode 100644 index 0000000..c696f78 --- /dev/null +++ b/pkg/utils/dwelling.go @@ -0,0 +1,14 @@ +package utils + +import "strings" + +// MainSite returns homepage address depending on network used. +func MainSite(host string) string { + if strings.Contains(host, "i2p") { + return "http://arav.i2p" + } else if strings.Contains(host, "onion") { + return "http://moq7aejnf4xk5k2bkaltli3ftkhusy2mbrd3pj23nrca343ku2mgk4yd.onion" + } + + return "https://arav.top" +}