backend/main.go

173 lines
4.2 KiB
Go

/*
Copyright (C) 2025 hexlocation (hex@iwakura.rip) & grngxd (grng@iwakura.rip)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"stereo.cat/backend/internal/api"
"stereo.cat/backend/internal/auth"
"stereo.cat/backend/internal/auth/client"
"stereo.cat/backend/internal/types"
)
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
func requireEnv(key string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
panic(errors.New(fmt.Sprintf("Environment variable %s is required but not specified. Exiting...", key)))
}
func main() {
_ = godotenv.Load()
databaseType := getEnv("DATABASE_TYPE", "sqlite")
sqliteFile := getEnv("SQLITE_FILE", "stereo.db")
boxyApiUrl := getEnv("BOXY_URL", "")
listenAddr := getEnv("LISTEN_ADDRESS", ":8081")
imagePath := getEnv("IMAGE_PATH", os.TempDir())
if _, err := os.Stat(imagePath); err != nil {
if os.IsNotExist(err) {
if err := os.MkdirAll(imagePath, os.ModePerm); err != nil {
log.Fatal(err)
}
}
}
minioClient, err := minio.New(
requireEnv("S3_ENDPOINT"),
&minio.Options{
Creds: credentials.NewStaticV4(requireEnv("S3_KEY"), requireEnv("S3_SECRET"), ""),
Secure: true,
},
)
if err != nil {
log.Fatal(err)
}
c := types.StereoConfig{
Router: gin.Default(),
MinioClient: minioClient,
Bucket: requireEnv("S3_BUCKET"),
Context: context.Background(),
ImagePath: imagePath,
Client: client.New(
requireEnv("REDIRECT_URI"),
requireEnv("CLIENT_ID"),
requireEnv("CLIENT_SECRET"),
),
FrontendUri: requireEnv("FRONTEND_URI"),
Domain: requireEnv("DOMAIN"),
JWTSecret: requireEnv("JWT_SECRET"),
}
switch databaseType {
case "sqlite":
db, err := gorm.Open(sqlite.Open(sqliteFile), &gorm.Config{})
c.Database = db
if err != nil {
panic(err)
}
break
case "postgres":
db, err := gorm.Open(postgres.Open(requireEnv("POSTGRES_DSN")), &gorm.Config{})
c.Database = db
if err != nil {
panic(err)
}
break
default:
panic(errors.New("Invalid database type was specified."))
}
c.Database.AutoMigrate(&auth.User{}, &types.File{})
if boxyApiUrl != "" {
boxyClientName := requireEnv("BOXY_CLIENT_NAME")
boxyClientSecret := requireEnv("BOXY_CLIENT_SECRET")
boxyClientAddress := getEnv("BOXY_CLIENT_ADDRESS", "")
port, err := strconv.Atoi(strings.Split(listenAddr, ":")[1])
fmt.Printf("Using port %d\n", port)
rawBody := map[string]any{
"port": port,
"hostname": c.Domain,
}
if boxyClientAddress != "" {
rawBody["address"] = boxyClientAddress
}
jBody, err := json.Marshal(rawBody)
if err != nil {
log.Fatal(err)
}
req, err := http.NewRequest("POST", boxyApiUrl+"/register", bytes.NewBuffer(jBody))
req.SetBasicAuth(boxyClientName, boxyClientSecret)
resp, _ := http.DefaultClient.Do(req)
if resp.StatusCode != 200 {
log.Fatal("Could not register with Boxy.\nStatus Code: " + strconv.Itoa(req.Response.StatusCode))
return
}
log.Println("Successfully registered with Boxy.")
}
api.Register(&c)
fmt.Printf("Listening on %s\n", listenAddr)
c.Router.Run(listenAddr)
}