8058
Ir
irvc / files
irvc / main.go
5.0 KB
1package main 2 3import ( 4 "database/sql" 5 "flag" 6 "fmt" 7 "log" 8 "net/http" 9 "os" 10 "path/filepath" 11 "strings" 12 "time" 13 14 "github.com/gin-gonic/gin" 15) 16 17type Server struct { 18 cfg *Config 19 db *sql.DB 20 hub *hub 21 previews *previewer 22} 23 24// usage prints out human readable usage for fs 25func usage(fs *flag.FlagSet) func() { 26 return func() { 27 w := fs.Output() 28 fmt.Fprint(w, `irvc - self-hosted WebRTC text and voice chat 29 30Usage: 31 irvc [flags] run the server 32 irvc [flags] invite create an invite and print its token 33 34Flags: 35`) 36 printFlags(fs) 37 fmt.Fprint(w, ` 38Secrets are read from the environment only: 39 IRVC_SESSION_SECRET signs sessions (required to run the server) 40 IRVC_LIVEKIT_API_KEY LiveKit API key 41 IRVC_LIVEKIT_SECRET LiveKit API secret 42 43See README.md for details. 44`) 45 } 46} 47 48// printFlags prints defaults like flag.PrintDefaults, but with GNU-style "--long" names 49func printFlags(fs *flag.FlagSet) { 50 fs.VisitAll(func(f *flag.Flag) { 51 name, usage := flag.UnquoteUsage(f) 52 head := " --" + f.Name 53 if name != "" { 54 head += " " + name 55 } 56 if f.DefValue != "" && f.DefValue != "0" { 57 usage += fmt.Sprintf(" (default: %s)", f.DefValue) 58 } 59 fmt.Fprintf(fs.Output(), "%s\n \t%s\n", head, usage) 60 }) 61} 62 63func main() { 64 cfg := LoadConfig() 65 66 // flags parsed before db/secret check so that --help always works 67 fs := flag.NewFlagSet("irvc", flag.ExitOnError) 68 fs.Usage = usage(fs) 69 fs.StringVar(&cfg.ListenAddr, "listen", cfg.ListenAddr, "IRVC_LISTEN_ADDR, address to listen on") 70 fs.StringVar(&cfg.DBPath, "db", cfg.DBPath, "IRVC_DB_PATH, path to the SQLite database") 71 fs.StringVar(&cfg.MediaDir, "media-dir", cfg.MediaDir, "IRVC_MEDIA_DIR, directory for uploaded media") 72 fs.Int64Var(&cfg.MaxUpload, "max-upload", cfg.MaxUpload, "IRVC_MAX_UPLOAD, max upload size in bytes") 73 fs.StringVar(&cfg.LiveKitURL, "livekit-url", cfg.LiveKitURL, "IRVC_LIVEKIT_URL, LiveKit server URL for voice chat") 74 genSecret := fs.Bool("gen-secret", false, "generate a random session secret, print it and exit") 75 fs.Parse(os.Args[1:]) 76 77 if *genSecret { 78 fmt.Println(randToken()) 79 return 80 } 81 82 cmd := fs.Arg(0) 83 if cmd != "" && cmd != "invite" { 84 fmt.Fprintf(fs.Output(), "unknown command %q\n\n", cmd) 85 fs.Usage() 86 os.Exit(2) 87 } 88 89 db := OpenDB(cfg.DBPath) 90 defer db.Close() 91 92 if cmd == "invite" { 93 makeInvite(db) 94 return 95 } 96 runServer(cfg, db) 97} 98 99func makeInvite(db *sql.DB) { 100 token := randToken() 101 expires := time.Now().Add(inviteTTL).Unix() 102 if _, err := db.Exec( 103 `INSERT INTO invites (token, created_by, expires_at) VALUES (?, NULL, ?)`, 104 token, expires, 105 ); err != nil { 106 log.Fatalf("create invite: %v", err) 107 } 108 fmt.Printf("invite token: %s\n", token) 109 fmt.Printf("expires: %s\n", time.Unix(expires, 0).Format(time.RFC3339)) 110 fmt.Printf("invite url: /join?token=%s\n", token) 111} 112 113func runServer(cfg *Config, db *sql.DB) { 114 if cfg.SessionSecret == "" { 115 log.Fatal("IRVC_SESSION_SECRET is required") 116 } 117 if err := os.MkdirAll(cfg.MediaDir, 0o755); err != nil { 118 log.Fatalf("media dir: %v", err) 119 } 120 s := &Server{cfg: cfg, db: db, hub: newHub(db), previews: newPreviewer(cfg.MediaDir, false)} 121 122 r := gin.Default() 123 loginLimiter := newRateLimiter(10, time.Minute) 124 claimLimiter := newRateLimiter(10, time.Minute) 125 126 api := r.Group("/api") 127 api.POST("/claim", s.rateLimited(claimLimiter), s.handleClaim) 128 api.POST("/login", s.rateLimited(loginLimiter), s.handleLogin) 129 api.GET("/invites/:token", s.handleInviteInfo) 130 131 authed := api.Group("", s.requireAuth) 132 authed.GET("/me", s.handleMe) 133 authed.GET("/users", s.handleUsers) 134 authed.POST("/logout", s.handleLogout) 135 authed.GET("/channels", s.handleChannels) 136 authed.POST("/channels", s.handleCreateChannel) 137 authed.DELETE("/channels/:id", s.handleDeleteChannel) 138 authed.POST("/dms/:userId", s.handleOpenDM) 139 authed.GET("/channels/:id/messages", s.handleMessages) 140 authed.POST("/channels/:id/messages", s.handleSendMessage) 141 authed.POST("/channels/:id/read", s.handleMarkRead) 142 authed.PATCH("/messages/:id", s.handleEditMessage) 143 authed.DELETE("/messages/:id", s.handleDeleteMessage) 144 authed.DELETE("/messages/:id/preview", s.handleDeletePreview) 145 authed.POST("/messages/:id/reactions", s.handleToggleReaction) 146 authed.POST("/channels/:id/voice", s.handleVoiceToken) 147 authed.POST("/channels/:id/ring", s.handleRing(true)) 148 authed.DELETE("/channels/:id/ring", s.handleRing(false)) 149 authed.POST("/invites", s.handleCreateInvite) 150 authed.GET("/gifs", s.handleGifs) 151 authed.POST("/upload", s.handleUpload) 152 authed.GET("/media/:name", s.handleMedia) 153 authed.GET("/ws", s.handleWS) 154 155 serveFrontend(r) 156 157 addr := cfg.ListenAddr 158 log.Printf("irvc listening on %s", addr) 159 if err := r.Run(addr); err != nil { 160 log.Fatal(err) 161 } 162} 163 164func serveFrontend(r *gin.Engine) { 165 index := filepath.Join("web", "dist", "index.html") 166 if _, err := os.Stat(index); err != nil { 167 return 168 } 169 r.Static("/assets", filepath.Join("web", "dist", "assets")) 170 r.StaticFile("/", index) 171 r.NoRoute(func(c *gin.Context) { 172 if strings.HasPrefix(c.Request.URL.Path, "/api") { 173 c.JSON(http.StatusNotFound, gin.H{"error": "not found"}) 174 return 175 } 176 c.File(index) 177 }) 178}