The applications tracker, leads inbox, email pipeline and capture userscript move here from web_server's backend, Python service and Vue app, as one Go binary that serves its own Vue SPA under /jobs/. - The Go services, resolvers and tests move over almost unchanged. - The three Claude calls are ported from Python to Go (internal/claude), with the same prompts, per-model request shaping and error messages. - There is no login: internal/auth asks the site backend's /auth/validate-admin with the visitor's cookies, and relays refreshed cookies back. - A Settings page replaces the admin-panel capture token card and adds the Microsoft sign-in link and a manual email sync. - The userscript is 2.0.0, at /jobs/, and migrates a saved API base. - Dockerfile, a standalone compose with Postgres, Makefile, and a Gitea CI workflow that tests and publishes the image. Co-Authored-By: Claude Opus 5.5 <[email protected]>
232 lines
8.5 KiB
Go
232 lines
8.5 KiB
Go
// Command jobtracker is the job application tracker: the applications list,
|
|
// the leads inbox, the email pipeline that advances applications from the
|
|
// mailbox, and the capture endpoints behind the browser userscript.
|
|
//
|
|
// It was split out of the adam-french.co.uk backend and is built to sit
|
|
// behind that site's nginx at /jobs/, borrowing its login (internal/auth).
|
|
// main is the single place everything is wired together: it reads every
|
|
// setting from the environment, builds the services, packs them into one
|
|
// handlers.Store, and registers the routes. README.md lists the variables.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/99designs/gqlgen/graphql/handler"
|
|
"github.com/99designs/gqlgen/graphql/handler/extension"
|
|
"github.com/99designs/gqlgen/graphql/handler/lru"
|
|
"github.com/99designs/gqlgen/graphql/handler/transport"
|
|
"github.com/99designs/gqlgen/graphql/playground"
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/vektah/gqlparser/v2/ast"
|
|
|
|
"adam-french.co.uk/job-tracker/internal/auth"
|
|
"adam-french.co.uk/job-tracker/internal/claude"
|
|
"adam-french.co.uk/job-tracker/internal/graph"
|
|
"adam-french.co.uk/job-tracker/internal/handlers"
|
|
"adam-french.co.uk/job-tracker/internal/services"
|
|
)
|
|
|
|
func main() {
|
|
devMode := os.Getenv("DEV_MODE") == "true"
|
|
if !devMode {
|
|
gin.SetMode(gin.ReleaseMode)
|
|
}
|
|
|
|
// Everything is served under basePath, and nginx proxies it without
|
|
// stripping the prefix, so the app's own URLs and the ones the browser
|
|
// sees are the same. The SPA is built for /jobs/ (web/vite.config.js), so
|
|
// changing this means rebuilding it with a matching base.
|
|
basePath := strings.TrimRight(getenv("BASE_PATH", "/jobs"), "/")
|
|
// The Docker volume: the Graph OAuth session and the capture token.
|
|
dataDir := getenv("DATA_DIR", "/data")
|
|
// The built SPA, copied in by the Dockerfile.
|
|
staticDir := getenv("STATIC_DIR", "/app/static")
|
|
|
|
// AUTH
|
|
// Settled before anything else, so a bad mode fails fast.
|
|
// "forward" (the default) asks the main site; "dev" admits everyone and
|
|
// is refused outside DEV_MODE, so a stray setting cannot open the
|
|
// tracker in production.
|
|
var checker auth.Checker
|
|
switch mode := getenv("AUTH_MODE", "forward"); mode {
|
|
case "forward":
|
|
checker = auth.NewForward(getenv("AUTH_VALIDATE_URL", "http://backend:8080/auth/validate-admin"))
|
|
case "dev":
|
|
if !devMode {
|
|
log.Fatal("AUTH_MODE=dev is only allowed with DEV_MODE=true")
|
|
}
|
|
log.Println("[Auth] AUTH_MODE=dev: every request is treated as the admin")
|
|
checker = auth.AllowAll{}
|
|
default:
|
|
log.Fatalf("unknown AUTH_MODE %q (want forward or dev)", mode)
|
|
}
|
|
|
|
databaseURL := os.Getenv("DATABASE_URL")
|
|
if databaseURL == "" {
|
|
log.Fatal("DATABASE_URL is not set")
|
|
}
|
|
db, err := services.InitDatabase(databaseURL)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if os.Getenv("SEED_DB") == "true" {
|
|
services.SeedDatabase(db)
|
|
}
|
|
|
|
// CLAUDE
|
|
// A missing key is not fatal: the tracker works without Claude, and each
|
|
// Claude feature reports the missing key when it is used.
|
|
claudeClient := claude.New(os.Getenv("CLAUDE_API_KEY"), os.Getenv("CLAUDE_MODEL"))
|
|
if os.Getenv("CLAUDE_API_KEY") == "" {
|
|
log.Println("[Claude] CLAUDE_API_KEY is not set: posting reading, lead scoring and email classification are off")
|
|
} else {
|
|
log.Printf("[Claude] using %s", claudeClient.Model())
|
|
}
|
|
|
|
// EMAIL SYNC
|
|
emailSync := services.InitEmailSync(&services.EmailSyncConfig{
|
|
Backend: os.Getenv("EMAIL_BACKEND"),
|
|
ClientID: os.Getenv("MSGRAPH_CLIENT_ID"),
|
|
ClientSecret: os.Getenv("MSGRAPH_CLIENT_SECRET"),
|
|
TenantID: os.Getenv("MSGRAPH_TENANT_ID"),
|
|
RedirectURI: os.Getenv("MSGRAPH_REDIRECT_URI"),
|
|
IMAP: &services.IMAPConfig{
|
|
Host: os.Getenv("IMAP_HOST"),
|
|
Port: os.Getenv("IMAP_PORT"),
|
|
Email: os.Getenv("IMAP_EMAIL"),
|
|
Password: os.Getenv("IMAP_PASSWORD"),
|
|
},
|
|
// An unparseable value is ignored and the default stands — a typo
|
|
// here fails quietly.
|
|
SyncInterval: duration("EMAIL_SYNC_INTERVAL", 30*time.Minute),
|
|
Enabled: os.Getenv("EMAIL_SYNC_ENABLED") == "true",
|
|
TokenPath: filepath.Join(dataDir, services.MSGraphTokenFile),
|
|
}, db, claudeClient)
|
|
|
|
// JOB LEADS
|
|
// Six hours by default: boards change a few times a day at most, and
|
|
// every run can spend Claude calls.
|
|
jobLeads := services.InitJobLeads(&services.JobLeadConfig{
|
|
Enabled: os.Getenv("JOB_LEADS_ENABLED") == "true",
|
|
Interval: duration("JOB_LEADS_INTERVAL", 6*time.Hour),
|
|
AdzunaAppID: os.Getenv("ADZUNA_APP_ID"),
|
|
AdzunaAppKey: os.Getenv("ADZUNA_APP_KEY"),
|
|
ReedAPIKey: os.Getenv("REED_API_KEY"),
|
|
}, db, claudeClient)
|
|
|
|
// JOB CAPTURE
|
|
// A damaged token file is logged, not fatal: capture stays off until a
|
|
// new token is generated on the settings page.
|
|
captureToken, err := services.InitCaptureToken(filepath.Join(dataDir, services.CaptureTokenFile))
|
|
if err != nil {
|
|
log.Println("Job capture token not loaded:", err)
|
|
}
|
|
|
|
store := handlers.Store{DB: db, EmailSync: emailSync, JobLeads: jobLeads, Extractor: claudeClient, CaptureToken: captureToken}
|
|
|
|
r := gin.New()
|
|
r.Use(gin.Logger(), gin.Recovery())
|
|
// Nothing here keys on the client's IP, so no proxy is trusted to
|
|
// report one.
|
|
if err := r.SetTrustedProxies(nil); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
api := r.Group(basePath + "/api")
|
|
admin := api.Group("", auth.Require(checker))
|
|
|
|
api.GET("/health", func(ctx *gin.Context) {
|
|
if sqlDB, err := db.DB(); err != nil || sqlDB.PingContext(ctx.Request.Context()) != nil {
|
|
ctx.JSON(503, gin.H{"status": "database unreachable"})
|
|
return
|
|
}
|
|
ctx.JSON(200, gin.H{"status": "ok"})
|
|
})
|
|
|
|
// JOB CAPTURE: called by the browser userscript from other origins, so
|
|
// these authenticate with a bearer token instead of the session cookies.
|
|
capture := api.Group("/capture", store.CaptureTokenMiddleware)
|
|
capture.GET("/status", store.JobCaptureStatus)
|
|
capture.POST("/extract", store.JobCaptureExtract)
|
|
capture.POST("", store.JobCapture)
|
|
|
|
// The capture token is managed with the session, never with the token
|
|
// itself.
|
|
admin.GET("/admin/capture-token", store.GetCaptureToken)
|
|
admin.POST("/admin/capture-token", store.GenerateCaptureToken)
|
|
admin.DELETE("/admin/capture-token", store.RevokeCaptureToken)
|
|
|
|
// EMAIL SYNC
|
|
// The callback is open because Microsoft redirects a browser to it; see
|
|
// CompleteEmailAuth.
|
|
api.GET("/email/callback", store.CompleteEmailAuth)
|
|
admin.GET("/email/status", store.EmailSyncStatus)
|
|
admin.POST("/email/sync", store.TriggerEmailSync)
|
|
|
|
// GRAPHQL
|
|
// auth.Annotate records whether the caller is the admin without refusing
|
|
// anything; the @admin directive on each field does the refusing, so a
|
|
// client gets the usual GraphQL error rather than a bare 401. Every
|
|
// field in the schema carries it (graph/directives_test.go).
|
|
gqlSrv := handler.New(graph.NewExecutableSchema(graph.Config{
|
|
Resolvers: &graph.Resolver{Store: &store},
|
|
Directives: graph.Directives(),
|
|
}))
|
|
gqlSrv.AddTransport(transport.Options{})
|
|
gqlSrv.AddTransport(transport.POST{})
|
|
gqlSrv.SetQueryCache(lru.New[*ast.QueryDocument](1000))
|
|
gqlSrv.Use(extension.FixedComplexityLimit(200))
|
|
if devMode && os.Getenv("GQL_INTROSPECTION") == "true" {
|
|
gqlSrv.Use(extension.Introspection{})
|
|
}
|
|
api.POST("/graphql", auth.Annotate(checker), func(ctx *gin.Context) {
|
|
gqlSrv.ServeHTTP(ctx.Writer, ctx.Request)
|
|
})
|
|
if devMode && os.Getenv("GQL_PLAYGROUND") == "true" {
|
|
api.GET("/graphql", func(ctx *gin.Context) {
|
|
playground.Handler("Job tracker GraphQL", basePath+"/api/graphql").ServeHTTP(ctx.Writer, ctx.Request)
|
|
})
|
|
}
|
|
|
|
// Everything else under basePath is the SPA.
|
|
r.NoRoute(handlers.SPA(staticDir, basePath))
|
|
|
|
// The schedulers run until ctx is cancelled, which only happens if r.Run
|
|
// returns; there is no graceful shutdown, so the container is simply
|
|
// killed.
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
defer cancel()
|
|
go emailSync.StartScheduler(ctx)
|
|
go jobLeads.StartScheduler(ctx)
|
|
|
|
port := getenv("PORT", "8080")
|
|
// Any return is a failure, so exit non-zero; otherwise Docker would see a
|
|
// clean shutdown and report the container as having succeeded.
|
|
if err := r.Run(fmt.Sprintf(":%s", port)); err != nil {
|
|
log.Fatalf("http server stopped: %v", err)
|
|
}
|
|
}
|
|
|
|
func getenv(key, fallback string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return fallback
|
|
}
|
|
|
|
// duration reads a Go duration such as 30m, falling back on a missing,
|
|
// unparseable or non-positive value.
|
|
func duration(key string, fallback time.Duration) time.Duration {
|
|
if parsed, err := time.ParseDuration(os.Getenv(key)); err == nil && parsed > 0 {
|
|
return parsed
|
|
}
|
|
return fallback
|
|
}
|