spongy-client-chrome/irc.cgi.go

101 lines
1.9 KiB
Go
Raw Normal View History

2014-07-14 19:30:47 -06:00
package main
import (
"fmt"
"io/ioutil"
2014-07-14 19:30:47 -06:00
"log"
"os"
"bufio"
"strconv"
"strings"
2014-07-14 19:30:47 -06:00
"net/http"
"net/http/cgi"
"time"
2014-08-05 15:53:03 -06:00
"path"
2014-07-14 19:30:47 -06:00
)
type Handler struct {
cgi.Handler
}
2014-08-05 15:53:03 -06:00
var BaseDir string
func ReadString(fn string) string {
octets, err := ioutil.ReadFile(fn)
if err != nil {
log.Fatal(err)
}
return strings.TrimSpace(string(octets))
}
2014-07-14 19:30:47 -06:00
func tail(w http.ResponseWriter, pos int) {
2014-08-05 15:53:03 -06:00
f, err := os.Open(path.Join(BaseDir, "log"))
2014-07-14 19:30:47 -06:00
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err = f.Seek(int64(pos), 0)
if err != nil {
log.Fatal(err)
}
bf := bufio.NewScanner(f)
for bf.Scan() {
t := bf.Text()
pos += len(t) + 1 // XXX: this breaks if we ever see \r\n
fmt.Fprintf(w, "data: %s\n", t)
}
fmt.Fprintf(w, "id: %d\n\n", pos)
}
2014-08-05 15:53:03 -06:00
func handleCommand(w http.ResponseWriter, text string, target string) {
fn := path.Join(BaseDir, fmt.Sprintf("outq/cgi.%d", time.Now().Unix()))
2014-07-14 19:30:47 -06:00
f, err := os.Create(fn)
if err != nil {
fmt.Fprintln(w, "NO")
fmt.Fprintln(w, err)
return
}
defer f.Close()
2014-08-05 15:53:03 -06:00
switch {
case strings.HasPrefix(text, "/quote "):
fmt.Fprintln(f, text[7:])
case strings.HasPrefix(text, "/me "):
fmt.Fprintf(f, "PRIVMSG %s :\001ACTION %s\001\n", target, text[4:])
default:
fmt.Fprintf(f, "PRIVMSG %s :%s\n", target, text)
}
2014-07-14 19:30:47 -06:00
fmt.Fprintln(w, "OK")
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
2014-08-05 15:53:03 -06:00
authtok := ReadString(path.Join(BaseDir, "authtok"))
if r.FormValue("auth") != authtok {
w.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(w, "NO")
return
}
2014-07-14 19:30:47 -06:00
switch r.FormValue("type") {
case "command":
w.Header().Set("Content-Type", "text/plain")
2014-08-05 15:53:03 -06:00
handleCommand(w, r.Form.Get("text"), r.FormValue("target"))
2014-07-14 19:30:47 -06:00
default:
w.Header().Set("Content-Type", "text/event-stream")
id, _ := strconv.Atoi(os.Getenv("HTTP_LAST_EVENT_ID"))
tail(w, id)
}
}
func main() {
2014-08-05 15:53:03 -06:00
BaseDir = ReadString("irc.basedir")
2014-07-14 19:30:47 -06:00
h := Handler{}
if err := cgi.Serve(h); err != nil {
log.Fatal(err)
}
}