bbj2/server/cmd/main.go

265 lines
5.3 KiB
Go
Raw Normal View History

2022-04-11 02:32:02 +00:00
package main
2022-04-11 03:45:33 +00:00
import (
"flag"
"fmt"
2022-06-14 17:44:03 +00:00
"log"
2022-04-12 00:16:06 +00:00
"net/http"
2022-04-11 03:45:33 +00:00
"os"
2022-04-12 20:33:13 +00:00
2022-06-01 03:27:55 +00:00
"git.tilde.town/tildetown/bbj2/server/cmd/api"
"git.tilde.town/tildetown/bbj2/server/cmd/config"
2022-06-14 21:05:39 +00:00
"git.tilde.town/tildetown/bbj2/server/cmd/db"
2022-04-12 20:33:13 +00:00
_ "github.com/mattn/go-sqlite3"
2022-04-11 03:45:33 +00:00
)
2022-05-22 05:50:34 +00:00
// TODO tests
2022-04-11 02:32:02 +00:00
func main() {
2022-04-11 03:45:33 +00:00
var configFlag = flag.String("config", "config.yml", "A path to a config file.")
2022-04-22 19:49:36 +00:00
var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.")
2022-04-11 03:45:33 +00:00
flag.Parse()
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
2022-06-01 03:27:55 +00:00
opts := &config.Options{
2022-04-11 03:45:33 +00:00
ConfigPath: *configFlag,
2022-04-22 19:49:36 +00:00
Reset: *resetFlag,
2022-06-14 17:44:03 +00:00
Logger: logger,
2022-04-11 03:45:33 +00:00
}
err := _main(opts)
if err != nil {
2022-06-14 17:44:03 +00:00
logger.Fatalln(err.Error())
2022-04-11 03:45:33 +00:00
}
}
2022-06-14 21:05:39 +00:00
/*
2022-04-12 20:33:13 +00:00
2022-06-14 21:05:39 +00:00
TODO my next initiative is doing /something/ about the database layer.
The amount of boiler plate involved in:
- prepare a statement
- prepare a result struct
- execute statement
- scan into result
is wild; the error handling is really out of control. I need to think of abstractions for this. The "easiest" is just making blunt, non performant functions that return structs and a single error, but that could get out of control too. In general I think not having raw sql ever in application code is a good place to start.
*/
2022-04-12 20:33:13 +00:00
2022-06-01 03:27:55 +00:00
func _main(opts *config.Options) error {
cfg, err := config.ParseConfig(opts.ConfigPath)
2022-04-11 03:45:33 +00:00
if err != nil {
return fmt.Errorf("could not read config file '%s'", opts.ConfigPath)
2022-04-11 03:45:33 +00:00
}
2022-04-12 20:33:13 +00:00
opts.Config = *cfg
2022-06-17 21:01:25 +00:00
teardown, err := db.Setup(opts)
2022-04-12 20:33:13 +00:00
if err != nil {
return fmt.Errorf("could not initialize DB: %w", err)
}
defer teardown()
2022-06-14 21:05:39 +00:00
err = db.EnsureSchema(*opts)
2022-04-21 02:19:01 +00:00
if err != nil {
return err
}
2022-04-12 20:33:13 +00:00
setupAPI(*opts)
2022-04-12 00:16:06 +00:00
// TODO TLS or SSL or something
2022-06-14 17:44:03 +00:00
opts.Logger.Printf("starting server at %s:%d", cfg.Host, cfg.Port)
2022-04-12 00:16:06 +00:00
if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil {
return fmt.Errorf("http server exited with error: %w", err)
}
2022-04-11 03:45:33 +00:00
return nil
}
2022-04-12 00:16:06 +00:00
2022-06-01 03:27:55 +00:00
func setupAPI(opts config.Options) {
2022-06-17 21:01:25 +00:00
a := api.NewAPI(opts)
2022-05-04 05:48:29 +00:00
2022-06-17 21:01:25 +00:00
http.HandleFunc("/instance_info", func(w http.ResponseWriter, req *http.Request) {
a.Invoke(w, req, a.InstanceInfo)
})
2022-06-14 17:44:03 +00:00
2022-06-17 21:01:25 +00:00
http.HandleFunc("/user_register", func(w http.ResponseWriter, req *http.Request) {
a.Invoke(w, req, a.UserRegister)
})
2022-05-18 02:09:17 +00:00
2022-07-01 01:44:58 +00:00
http.HandleFunc("/check_auth", func(w http.ResponseWriter, req *http.Request) {
a.Invoke(w, req, a.CheckAuth)
})
}
/*
http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) {
db := opts.DB
rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id")
if err != nil {
serverErr(w, err)
return
}
defer rows.Close()
for rows.Next() {
var id string
err = rows.Scan(&id)
if err != nil {
serverErr(w, err)
return
2022-06-14 17:44:03 +00:00
}
opts.Log(id)
}
writeResponse(w, BBJResponse{Data: "TODO"})
// TODO
}))
2022-06-01 03:27:55 +00:00
http.HandleFunc("/thread_create", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badMethod(w)
return
2022-06-14 21:05:39 +00:00
}
2022-06-01 03:27:55 +00:00
// TODO make this getUserInfoFromReq or similar so we can use the user ID later
user, err := getUserFromReq(opts, req)
if err != nil {
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: err.Error(),
})
return
}
type threadCreateArgs struct {
Title string
Body string
SendRaw bool `json:"send_raw"`
}
var args threadCreateArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
if args.Title == "" || args.Body == "" {
invalidArgs(w)
return
}
db := opts.DB
tx, err := db.Begin()
if err != nil {
serverErr(w, err)
return
}
stmt, err := tx.Prepare("insert into threads VALUES ( ?, ?, ?, ?, ?, 0, 0, ? )")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
threadID, err := uuid.NewRandom()
if err != nil {
serverErr(w, err)
return
}
now := time.Now()
if _, err = stmt.Exec(
threadID,
user.ID,
args.Title,
now,
now,
user.Username,
); err != nil {
serverErr(w, err)
return
}
stmt, err = tx.Prepare("insert into messages values ( ?, 1, ?, ?, 0, ?, ? )")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
if _, err = stmt.Exec(
threadID,
user.ID,
now,
args.Body,
args.SendRaw,
); err != nil {
serverErr(w, err)
return
}
if err = tx.Commit(); err != nil {
serverErr(w, err)
return
}
stmt, err = db.Prepare("select * from threads where thread_id = ? limit 1")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
t := &Thread{}
// TODO fill in rest of thread
if err = stmt.QueryRow(threadID).Scan(
t.ID,
t.Author,
t.Title,
t.LastMod,
t.Created,
t.ReplyCount,
t.Pinned,
t.LastAuthor,
); err != nil {
serverErr(w, err)
return
}
stmt, err = db.Prepare("select * from messages where thread_id = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
rows, err := stmt.Query(threadID)
if err != nil {
serverErr(w, err)
return
}
t.Messages = []Message{}
for rows.Next() {
m := &Message{}
if err := rows.Scan(
m.ThreadID,
m.PostID,
m.Author,
m.Created,
m.Edited,
m.Body,
m.SendRaw,
); err != nil {
serverErr(w, err)
return
}
t.Messages = append(t.Messages, *m)
}
writeResponse(w, BBJResponse{Data: t})
}))
*/