ghostream/stream/telnet/telnet.go

70 lines
1.6 KiB
Go
Raw Normal View History

// Package telnet provides some fancy tools, like an ASCII-art stream.
package telnet
import (
"log"
"net"
"time"
2020-10-17 16:12:25 +00:00
"gitlab.crans.org/nounous/ghostream/stream"
2020-10-12 22:15:23 +00:00
)
// Options holds telnet package configuration
type Options struct {
Enabled bool
ListenAddress string
Width int
Height int
Delay int
}
2020-10-17 16:12:25 +00:00
// Serve Telnet server
func Serve(streams map[string]*stream.Stream, cfg *Options) {
if !cfg.Enabled {
// Telnet is not enabled, ignore
2020-10-12 22:15:23 +00:00
return
}
2020-10-17 16:12:25 +00:00
// Start conversion routine
textStreams := make(map[string]*[]byte)
go autoStartConversion(streams, textStreams, cfg)
2020-10-17 16:12:25 +00:00
// Start TCP server
listener, err := net.Listen("tcp", cfg.ListenAddress)
if err != nil {
2020-10-17 16:12:25 +00:00
log.Fatalf("Error while listening to the address %s: %s", cfg.ListenAddress, err)
}
2020-10-17 16:12:25 +00:00
log.Printf("Telnet server listening on %s", cfg.ListenAddress)
2020-10-17 16:12:25 +00:00
// Handle each new client
for {
s, err := listener.Accept()
if err != nil {
log.Printf("Error while accepting TCP socket: %s", s)
continue
}
2020-10-17 16:12:25 +00:00
go handleViewer(s, streams, textStreams, cfg)
}
}
2020-10-17 16:12:25 +00:00
// Convertion routine listen to existing stream and start text conversions
func autoStartConversion(streams map[string]*stream.Stream, textStreams map[string]*[]byte, cfg *Options) {
for {
2020-10-17 16:12:25 +00:00
for name, stream := range streams {
textStream, ok := textStreams[name]
if ok {
// Everything is fine
continue
}
2020-10-17 16:12:25 +00:00
// Start conversion
log.Print("Starting text conversion of %s", name)
textStream = &[]byte{}
textStreams[name] = textStream
go streamToTextStream(stream, textStream, cfg)
}
2020-10-17 16:12:25 +00:00
time.Sleep(time.Second)
}
}