underbbs/adapter/honk.go

133 lines
2.7 KiB
Go

package adapter
import (
"errors"
"fmt"
. "forge.lightcrystal.systems/lightcrystal/underbbs/models"
"net/http"
"net/url"
"os"
"strings"
)
type HonkAdapter struct {
data *chan SocketData
nickname string
server string
username string
password string
token string
}
func (self *HonkAdapter) isAnonymous() bool {
return self.token == ""
}
func (self *HonkAdapter) send(data SocketData) {
if self.data != nil {
*self.data <- data
} else {
fmt.Fprintln(os.Stdout, string(data.ToDatagram()))
}
}
func (self *HonkAdapter) Name() string {
return self.nickname
}
func (self *HonkAdapter) Init(settings Settings, data *chan SocketData) error {
// separate name and server in handle
parts := strings.Split(*settings.Handle, "@")
self.username = parts[1]
self.server = "https://" + parts[2]
self.nickname = settings.Nickname
if settings.Password == nil {
// we're anonymous!
return nil
}
self.password = *settings.Password
// store all the settings
// make a request to get the token
r, err := http.PostForm(self.server+"/dologin", url.Values{
"username": []string{self.username},
"password": []string{self.password},
"gettoken": []string{"1"},
})
if err != nil {
return err
}
var buf [32]byte
_, err = r.Body.Read(buf[:])
if err != nil {
return err
}
self.token = string(buf[:])
fmt.Println(self.token)
return nil
}
func (self *HonkAdapter) Subscribe(string) []error {
return nil
}
func (self *HonkAdapter) Fetch(etype string, ids []string) error {
// if we're anonymous, we can fetch the data as raw AP
// KISS
if self.isAnonymous() {
aaa := anonAPAdapter{}
aaa.Init(self.data, self.server, "honk", self.nickname)
return aaa.Fetch(etype, ids)
}
for _, _ = range ids {
switch etype {
case "byAuthor":
// gethonks
case "message":
// use honk-canonical XID
case "author":
if self.isAnonymous() {
// if we are using @user@server, translate it to https://server/u/user
} else {
// otherwise, use the URL as such
}
case "children":
// use honk-canonical XID
case "convoy":
if self.isAnonymous() {
} else {
}
}
}
return nil
}
func (self *HonkAdapter) Do(action string, data map[string]string) error {
switch action {
case "post":
res, err := http.PostForm(self.server+"/api", url.Values{
"action": []string{"honk"},
"token": []string{self.token},
"noise": []string{data["content"]},
})
if err != nil {
return err
}
var buf [256]byte
_, err = res.Body.Read(buf[:])
if err != nil {
return err
}
fmt.Println(string(buf[:]))
default:
return errors.New("Do: unknown action")
}
return nil
}
func (self *HonkAdapter) DefaultSubscriptionFilter() string {
return ""
}