From 12a313eea4ce28d19e24719ce4e0dc9b2a473b19 Mon Sep 17 00:00:00 2001 From: skidoodle Date: Sun, 15 Jun 2025 00:59:50 +0200 Subject: [PATCH] Refactor application structure and enhance logging - Introduced a Configuration struct to manage application settings. - Created a State struct to encapsulate application state and dependencies. - Replaced log package with logrus for improved logging capabilities. - Implemented graceful shutdown handling for the HTTP server. - Added context management for background tasks. - Updated database initialization to ensure tables are created. - Refactored user management functions to use the new State struct. - Enhanced error handling and logging throughout the application. - Updated README to reflect changes in user addition process. --- .dockerignore | 2 + Dockerfile | 20 +- docker-compose.dev.yaml | 2 +- go.mod | 16 +- go.sum | 61 ++++++ main.go | 428 +++++++++++++++++++++++++++------------- readme.md | 10 +- 7 files changed, 377 insertions(+), 162 deletions(-) diff --git a/.dockerignore b/.dockerignore index e2d7f85..b734aec 100644 --- a/.dockerignore +++ b/.dockerignore @@ -3,3 +3,5 @@ .docker-compose* Dockerfile *.md +.env* +data/ diff --git a/Dockerfile b/Dockerfile index 5cd67c7..793e12c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,22 +1,16 @@ FROM golang:alpine AS builder - -RUN apk add --no-cache gcc musl-dev - WORKDIR /build COPY go.mod go.sum ./ RUN go mod download COPY . . +RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/ncore-stats . -ENV CGO_ENABLED=1 -RUN go build -o ncore-stats . -FROM alpine:latest -RUN apk --no-cache add ca-certificates -WORKDIR /app/ -COPY --from=builder /build/trackncore . -COPY --from=builder /build/data . -COPY --from=builder /build/index.html . -COPY --from=builder /build/script.js . -COPY --from=builder /build/style.css . +FROM alpine:3 +RUN apk add --no-cache ca-certificates +WORKDIR /app +COPY --from=builder /out/ncore-stats . +COPY index.html style.css script.js ./ EXPOSE 3000 + CMD ["./ncore-stats"] diff --git a/docker-compose.dev.yaml b/docker-compose.dev.yaml index 572b914..e5839d2 100644 --- a/docker-compose.dev.yaml +++ b/docker-compose.dev.yaml @@ -9,7 +9,7 @@ services: - data:/app/data environment: - NICK=${NICK} - - PASSWORD=${PASS} + - PASS=${PASS} volumes: data: diff --git a/go.mod b/go.mod index 401d17f..736e4e4 100644 --- a/go.mod +++ b/go.mod @@ -1,16 +1,28 @@ module ncore-stats -go 1.23 +go 1.23.0 -toolchain go1.23.2 +toolchain go1.24.0 require ( github.com/PuerkitoBio/goquery v1.10.1 github.com/joho/godotenv v1.5.1 github.com/mattn/go-sqlite3 v1.14.28 + github.com/sirupsen/logrus v1.9.3 + modernc.org/sqlite v1.38.0 ) require ( github.com/andybalholm/cascadia v1.3.3 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 // indirect golang.org/x/net v0.33.0 // indirect + golang.org/x/sys v0.33.0 // indirect + modernc.org/libc v1.65.10 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect ) diff --git a/go.sum b/go.sum index b25b048..f965e31 100644 --- a/go.sum +++ b/go.sum @@ -2,11 +2,33 @@ github.com/PuerkitoBio/goquery v1.10.1 h1:Y8JGYUkXWTGRB6Ars3+j3kN0xg1YqqlwvdTV8W github.com/PuerkitoBio/goquery v1.10.1/go.mod h1:IYiHrOMps66ag56LEH7QYDDupKXyo5A8qrjIx3ZtujY= github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM= github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= +github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.28 h1:ThEiQrnbtumT+QMknw63Befp/ce/nUPgBPMlRFEum7A= github.com/mattn/go-sqlite3 v1.14.28/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= @@ -14,11 +36,15 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM= +golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU= +golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= @@ -36,17 +62,23 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y= golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.14.0 h1:woo0S4Yywslg6hp4eUFjTVOyKt0RookbpAHG4c1HmhQ= +golang.org/x/sync v0.14.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.33.0 h1:q3i8TbbEz+JRD9ywIRlyRAQbM0qF7hu24q3teo2hbuw= +golang.org/x/sys v0.33.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -71,4 +103,33 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +golang.org/x/tools v0.33.0 h1:4qz2S3zmRxbGIhDIAgjxvFutSvH5EfnsYrRBj0UI0bc= +golang.org/x/tools v0.33.0/go.mod h1:CIJMaWEY88juyUfo7UbgPqbC8rU2OqfAV1h2Qp0oMYI= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.26.1 h1:+X5NtzVBn0KgsBCBe+xkDC7twLb/jNVj9FPgiwSQO3s= +modernc.org/cc/v4 v4.26.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= +modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU= +modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE= +modernc.org/fileutil v1.3.3 h1:3qaU+7f7xxTUmvU1pJTZiDLAIoJVdUSSauJNHg9yXoA= +modernc.org/fileutil v1.3.3/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/libc v1.65.10 h1:ZwEk8+jhW7qBjHIT+wd0d9VjitRyQef9BnzlzGwMODc= +modernc.org/libc v1.65.10/go.mod h1:StFvYpx7i/mXtBAfVOjaU0PWZOvIRoZSgXhrwXzr8Po= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8= +modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.38.0 h1:+4OrfPQ8pxHKuWG4md1JpR/EYAh3Md7TdejuuzE7EUI= +modernc.org/sqlite v1.38.0/go.mod h1:1Bj+yES4SVvBZ4cBOpVZ6QgesMCKpJZDq0nxYzOpmNE= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/main.go b/main.go index 93df552..73dd72f 100644 --- a/main.go +++ b/main.go @@ -1,23 +1,45 @@ package main import ( + "context" "database/sql" "encoding/json" "flag" "fmt" - "log" "net/http" "os" + "os/signal" "regexp" "strconv" "strings" + "syscall" "time" "github.com/PuerkitoBio/goquery" "github.com/joho/godotenv" - _ "github.com/mattn/go-sqlite3" + "github.com/sirupsen/logrus" + _ "modernc.org/sqlite" ) +// Configuration holds application settings loaded from the environment. +type Configuration struct { + ServerPort string + DatabasePath string + LogLevel logrus.Level + Ncore struct { + Nick string + Pass string + } +} + +// State holds application runtime state and dependencies. +type State struct { + config *Configuration + db *sql.DB + client *http.Client +} + +// ProfileData represents a snapshot of a user's profile statistics. type ProfileData struct { Owner string `json:"owner"` Timestamp time.Time `json:"timestamp"` @@ -29,22 +51,196 @@ type ProfileData struct { SeedingCount int `json:"seeding_count"` } +// User represents a user whose stats are being tracked. type User struct { ID int DisplayName string ProfileID string } -var ( - db *sql.DB - dbFile = "./data/ncore_stats.db" - baseUrl = "https://ncore.pro/profile.php?id=" - nick string - pass string - client *http.Client +const ( + defaultPort = ":3000" + defaultDbFolder = "./data" + ncoreBaseURL = "https://ncore.pro/profile.php?id=" ) -func profilesHandler(w http.ResponseWriter, r *http.Request) { +func main() { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + config := initializeApplication() + + db, err := initializeDatabase(config) + if err != nil { + logrus.Fatalf("Database initialization failed: %v", err) + } + defer db.Close() + + state := &State{ + config: config, + db: db, + client: &http.Client{Timeout: 30 * time.Second}, + } + + // If a command-line flag was handled, the program should exit. + if handleFlags(state) { + return + } + + router := http.NewServeMux() + router.HandleFunc("/api/profiles", state.profilesHandler) + router.HandleFunc("/api/history", state.historyHandler) + router.HandleFunc("/", serveStatic("index.html", "text/html")) + router.HandleFunc("/style.css", serveStatic("style.css", "text/css")) + router.HandleFunc("/script.js", serveStatic("script.js", "application/javascript")) + + server := &http.Server{ + Addr: config.ServerPort, + Handler: router, + } + + go state.profileFetcherLoop(ctx) + + startServer(server) + handleShutdown(server, cancel) +} + +// initializeApplication sets up logging and loads the application configuration. +func initializeApplication() *Configuration { + logrus.SetFormatter(&logrus.TextFormatter{ + FullTimestamp: true, + TimestampFormat: time.RFC3339, + ForceColors: true, + }) + + config, err := loadConfiguration() + if err != nil { + logrus.Fatalf("Failed to load configuration: %v", err) + } + + logrus.SetLevel(config.LogLevel) + logrus.Info("Application configuration loaded successfully") + return config +} + +// loadConfiguration loads settings from .env files and the environment. +func loadConfiguration() (*Configuration, error) { + // godotenv.Load will not override existing environment variables, + // making it safe for use in production environments like Docker. + _ = godotenv.Load(".env.local") + _ = godotenv.Load() + + cfg := &Configuration{} + + required := map[string]*string{ + "NICK": &cfg.Ncore.Nick, + "PASS": &cfg.Ncore.Pass, + } + for key, ptr := range required { + value := os.Getenv(key) + if value == "" { + return nil, fmt.Errorf("missing required environment variable: %s", key) + } + *ptr = value + } + + cfg.ServerPort = defaultPort + if port := os.Getenv("SERVER_PORT"); port != "" { + cfg.ServerPort = ":" + strings.TrimLeft(port, ":") + } + + cfg.DatabasePath = defaultDbFolder + if path := os.Getenv("DATABASE_PATH"); path != "" { + cfg.DatabasePath = path + } + + switch strings.ToLower(os.Getenv("LOG_LEVEL")) { + case "debug": + cfg.LogLevel = logrus.DebugLevel + case "warn": + cfg.LogLevel = logrus.WarnLevel + case "error": + cfg.LogLevel = logrus.ErrorLevel + default: + cfg.LogLevel = logrus.InfoLevel + } + + return cfg, nil +} + +// initializeDatabase connects to the SQLite database and ensures tables are created. +func initializeDatabase(config *Configuration) (*sql.DB, error) { + dbPath := fmt.Sprintf("%s/ncore_stats.db", config.DatabasePath) + + if err := os.MkdirAll(config.DatabasePath, 0755); err != nil { + return nil, fmt.Errorf("failed to create data directory: %w", err) + } + + db, err := sql.Open("sqlite", dbPath) + if err != nil { + return nil, fmt.Errorf("failed to open database: %w", err) + } + + usersTableSQL := `CREATE TABLE IF NOT EXISTS users ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "display_name" TEXT NOT NULL UNIQUE, "profile_id" TEXT NOT NULL);` + if _, err := db.Exec(usersTableSQL); err != nil { + return nil, fmt.Errorf("failed to create users table: %w", err) + } + + profileHistoryTableSQL := `CREATE TABLE IF NOT EXISTS profile_history ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "timestamp" DATETIME NOT NULL, "rank" INTEGER, "upload" TEXT, "current_upload" TEXT, "current_download" TEXT, "points" INTEGER, "seeding_count" INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE);` + if _, err := db.Exec(profileHistoryTableSQL); err != nil { + return nil, fmt.Errorf("failed to create profile_history table: %w", err) + } + + logrus.Info("Database initialized successfully") + return db, nil +} + +// handleFlags processes command-line flags and returns true if the program should exit. +func handleFlags(s *State) bool { + addUserFlag := flag.String("add-user", "", "Add a new user. Provide as 'DisplayName,ProfileID'") + flag.Parse() + + if *addUserFlag != "" { + parts := strings.Split(*addUserFlag, ",") + if len(parts) != 2 { + logrus.Fatal("Invalid format for --add-user. Use 'DisplayName,ProfileID'") + } + s.addUser(parts[0], parts[1]) + return true + } + return false +} + +// startServer runs the HTTP server in a new goroutine. +func startServer(server *http.Server) { + go func() { + logrus.Infof("Server starting on %s", server.Addr) + if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logrus.Fatalf("Server failed to start: %v", err) + } + }() +} + +// handleShutdown waits for a termination signal and performs a graceful shutdown. +func handleShutdown(server *http.Server, cancel context.CancelFunc) { + sigChan := make(chan os.Signal, 1) + signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) + <-sigChan + + logrus.Info("Shutdown signal received, initiating graceful shutdown...") + cancel() // Notify background goroutines to stop. + + shutdownCtx, cancelTimeout := context.WithTimeout(context.Background(), 5*time.Second) + defer cancelTimeout() + + if err := server.Shutdown(shutdownCtx); err != nil { + logrus.Errorf("Server shutdown error: %v", err) + } + logrus.Info("Server shutdown complete") +} + +// profilesHandler serves the latest profile data for all tracked users. +func (s *State) profilesHandler(w http.ResponseWriter, r *http.Request) { query := ` SELECT u.display_name, ph.timestamp, ph.rank, ph.upload, ph.current_upload, ph.current_download, ph.points, ph.seeding_count FROM profile_history ph @@ -55,10 +251,10 @@ func profilesHandler(w http.ResponseWriter, r *http.Request) { ) latest ON ph.user_id = latest.user_id AND ph.timestamp = latest.max_ts JOIN users u ON ph.user_id = u.id; ` - rows, err := db.Query(query) + rows, err := s.db.Query(query) if err != nil { http.Error(w, "Could not read latest profiles from database", http.StatusInternalServerError) - log.Printf("Error querying latest profiles: %v", err) + logrus.Errorf("Error querying latest profiles: %v", err) return } defer rows.Close() @@ -68,7 +264,7 @@ func profilesHandler(w http.ResponseWriter, r *http.Request) { var p ProfileData if err := rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount); err != nil { http.Error(w, "Could not process profile data", http.StatusInternalServerError) - log.Printf("Error scanning latest profile row: %v", err) + logrus.Errorf("Error scanning latest profile row: %v", err) return } latestProfiles = append(latestProfiles, p) @@ -76,11 +272,12 @@ func profilesHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(latestProfiles); err != nil { - log.Printf("Error encoding latest profiles to JSON: %v", err) + logrus.Errorf("Error encoding latest profiles to JSON: %v", err) } } -func historyHandler(w http.ResponseWriter, r *http.Request) { +// historyHandler serves the full profile history for a single user. +func (s *State) historyHandler(w http.ResponseWriter, r *http.Request) { owner := r.URL.Query().Get("owner") if owner == "" { http.Error(w, "Missing 'owner' query parameter", http.StatusBadRequest) @@ -94,10 +291,10 @@ func historyHandler(w http.ResponseWriter, r *http.Request) { WHERE u.display_name = ? ORDER BY ph.timestamp ASC ` - rows, err := db.Query(query, owner) + rows, err := s.db.Query(query, owner) if err != nil { http.Error(w, "Could not read history from database", http.StatusInternalServerError) - log.Printf("Error querying history for %s: %v", owner, err) + logrus.Errorf("Error querying history for %s: %v", owner, err) return } defer rows.Close() @@ -107,7 +304,7 @@ func historyHandler(w http.ResponseWriter, r *http.Request) { var p ProfileData if err := rows.Scan(&p.Owner, &p.Timestamp, &p.Rank, &p.Upload, &p.CurrentUpload, &p.CurrentDownload, &p.Points, &p.SeedingCount); err != nil { http.Error(w, "Could not process history data", http.StatusInternalServerError) - log.Printf("Error scanning history row for %s: %v", owner, err) + logrus.Errorf("Error scanning history row for %s: %v", owner, err) return } userHistory = append(userHistory, p) @@ -115,184 +312,139 @@ func historyHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(userHistory); err != nil { - log.Printf("Error encoding history for %s to JSON: %v", owner, err) + logrus.Errorf("Error encoding history for %s to JSON: %v", err, owner) } } -func main() { - // --- Environment and Initialization --- - _ = godotenv.Load(".env.local") - godotenv.Load() - nick = os.Getenv("NICK") - pass = os.Getenv("PASS") - - // --- Ensure critical env vars are set --- - if nick == "" || pass == "" { - log.Fatal("FATAL: Critical environment variables NICK and/or PASS are not set. Please create a .env or .env.local file with these values.") +// serveStatic returns an http.HandlerFunc that serves a static file. +func serveStatic(fileName, contentType string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", contentType) + http.ServeFile(w, r, fileName) } +} - client = &http.Client{} +// profileFetcherLoop runs a background task to fetch profiles on a schedule. +func (s *State) profileFetcherLoop(ctx context.Context) { + logrus.Info("Starting background profile fetcher...") + s.fetchAndLogAllProfiles() // Fetch immediately on startup. - initDB() - defer db.Close() + ticker := time.NewTicker(24 * time.Hour) + defer ticker.Stop() - // --- Command-line flags for user management --- - addUserFlag := flag.String("add-user", "", "Add a new user. Provide as 'DisplayName,ProfileID'") - flag.Parse() - - if *addUserFlag != "" { - parts := strings.Split(*addUserFlag, ",") - if len(parts) != 2 { - log.Fatal("Invalid format for --add-user. Use 'DisplayName,ProfileID'") - } - addUser(parts[0], parts[1]) - return // Exit after adding user - } - - // --- Background task and Web Server --- - go func() { - fetchAndLogProfiles() - ticker := time.NewTicker(time.Hour * 24) - defer ticker.Stop() - for range ticker.C { - fetchAndLogProfiles() - } - }() - - // --- Handler Registration --- - http.HandleFunc("/api/profiles", profilesHandler) - http.HandleFunc("/api/history", historyHandler) - - http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/" { - http.NotFound(w, r) + for { + select { + case <-ticker.C: + s.fetchAndLogAllProfiles() + case <-ctx.Done(): + logrus.Info("Stopping background profile fetcher.") return } - w.Header().Set("Content-Type", "text/html") - http.ServeFile(w, r, "index.html") - }) - - http.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/css") - http.ServeFile(w, r, "style.css") - }) - - http.HandleFunc("/script.js", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/javascript") - http.ServeFile(w, r, "script.js") - }) - - log.Println("Server is starting on port 3000...") - log.Fatal(http.ListenAndServe(":3000", nil)) + } } -func initDB() { - var err error - if err := os.MkdirAll("./data", 0755); err != nil { - log.Fatalf("Failed to create data directory: %v", err) - } - db, err = sql.Open("sqlite3", dbFile) +// addUser inserts a new user into the database. +func (s *State) addUser(displayName, profileID string) { + stmt, err := s.db.Prepare("INSERT INTO users(display_name, profile_id) VALUES(?, ?)") if err != nil { - log.Fatalf("Failed to open database: %v", err) - } - usersTableSQL := `CREATE TABLE IF NOT EXISTS users ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "display_name" TEXT NOT NULL UNIQUE, "profile_id" TEXT NOT NULL);` - _, err = db.Exec(usersTableSQL) - if err != nil { - log.Fatalf("Failed to create users table: %v", err) - } - profileHistoryTableSQL := `CREATE TABLE IF NOT EXISTS profile_history ("id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, "user_id" INTEGER NOT NULL, "timestamp" DATETIME NOT NULL, "rank" INTEGER, "upload" TEXT, "current_upload" TEXT, "current_download" TEXT, "points" INTEGER, "seeding_count" INTEGER, FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE);` - _, err = db.Exec(profileHistoryTableSQL) - if err != nil { - log.Fatalf("Failed to create profile_history table: %v", err) - } - log.Println("Database initialized successfully.") -} - -func addUser(displayName, profileID string) { - stmt, err := db.Prepare("INSERT INTO users(display_name, profile_id) VALUES(?, ?)") - if err != nil { - log.Fatalf("Failed to prepare statement for adding user: %v", err) + logrus.Fatalf("Failed to prepare statement for adding user: %v", err) } defer stmt.Close() - _, err = stmt.Exec(displayName, profileID) - if err != nil { - log.Fatalf("Failed to add user %s: %v", displayName, err) + + if _, err = stmt.Exec(displayName, profileID); err != nil { + logrus.Fatalf("Failed to add user %s: %v", displayName, err) } - log.Printf("User '%s' with profile ID '%s' added successfully.", displayName, profileID) + logrus.Infof("User '%s' with profile ID '%s' added successfully.", displayName, profileID) } -func getUsers() ([]User, error) { - rows, err := db.Query("SELECT id, display_name, profile_id FROM users") +// getUsers retrieves all tracked users from the database. +func (s *State) getUsers() ([]User, error) { + rows, err := s.db.Query("SELECT id, display_name, profile_id FROM users") if err != nil { - return nil, fmt.Errorf("error querying users: %v", err) + return nil, fmt.Errorf("error querying users: %w", err) } defer rows.Close() + var users []User for rows.Next() { var u User if err := rows.Scan(&u.ID, &u.DisplayName, &u.ProfileID); err != nil { - return nil, fmt.Errorf("error scanning user row: %v", err) + return nil, fmt.Errorf("error scanning user row: %w", err) } users = append(users, u) } return users, nil } -func logToDB(profile *ProfileData, userID int) error { - stmt, err := db.Prepare(`INSERT INTO profile_history(user_id, timestamp, rank, upload, current_upload, current_download, points, seeding_count) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`) +// logToDB inserts a new profile data point into the history table. +func (s *State) logToDB(profile *ProfileData, userID int) error { + stmt, err := s.db.Prepare(`INSERT INTO profile_history(user_id, timestamp, rank, upload, current_upload, current_download, points, seeding_count) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`) if err != nil { - return fmt.Errorf("error preparing insert statement: %v", err) + return fmt.Errorf("error preparing insert statement: %w", err) } defer stmt.Close() - _, err = stmt.Exec(userID, profile.Timestamp, profile.Rank, profile.Upload, profile.CurrentUpload, profile.CurrentDownload, profile.Points, profile.SeedingCount) - if err != nil { - return fmt.Errorf("error executing insert for %s: %v", profile.Owner, err) + + if _, err = stmt.Exec(userID, profile.Timestamp, profile.Rank, profile.Upload, profile.CurrentUpload, profile.CurrentDownload, profile.Points, profile.SeedingCount); err != nil { + return fmt.Errorf("error executing insert for %s: %w", profile.Owner, err) } - log.Printf("Profile for %s logged successfully to database.", profile.Owner) + logrus.Infof("Profile for %s logged successfully to database.", profile.Owner) return nil } -func fetchAndLogProfiles() { - users, err := getUsers() +// fetchAndLogAllProfiles orchestrates the fetching and logging of all user profiles. +func (s *State) fetchAndLogAllProfiles() { + users, err := s.getUsers() if err != nil { - log.Printf("Could not get users to fetch: %v", err) + logrus.Errorf("Could not get users to fetch: %v", err) return } - log.Printf("Starting profile fetch for %d user(s).", len(users)) + + if len(users) == 0 { + logrus.Info("No users in database to fetch. Use the --add-user flag to add one.") + return + } + + logrus.Infof("Starting profile fetch for %d user(s).", len(users)) for _, user := range users { - profileURL := baseUrl + user.ProfileID - profile, err := fetchProfile(profileURL, user.DisplayName) + profile, err := s.fetchProfile(user) if err != nil { - log.Printf("Error fetching profile for %s: %v", user.DisplayName, err) + logrus.Errorf("Error fetching profile for %s: %v", user.DisplayName, err) continue } - if err := logToDB(profile, user.ID); err != nil { - log.Printf("Error logging profile to DB for %s: %v", user.DisplayName, err) + if err := s.logToDB(profile, user.ID); err != nil { + logrus.Errorf("Error logging profile to DB for %s: %v", user.DisplayName, err) } + // Pause between requests to avoid rate-limiting. time.Sleep(2 * time.Second) } - log.Println("Profile fetch cycle complete.") + logrus.Info("Profile fetch cycle complete.") } -func fetchProfile(url string, displayName string) (*ProfileData, error) { - req, err := http.NewRequest("GET", url, nil) +// fetchProfile retrieves and parses the profile page for a single user. +func (s *State) fetchProfile(user User) (*ProfileData, error) { + profileURL := ncoreBaseURL + user.ProfileID + req, err := http.NewRequest("GET", profileURL, nil) if err != nil { - return nil, fmt.Errorf("error creating request for %s: %v", displayName, err) + return nil, fmt.Errorf("error creating request: %w", err) } - req.Header.Set("Cookie", fmt.Sprintf("nick=%s; pass=%s", nick, pass)) - resp, err := client.Do(req) + + req.Header.Set("Cookie", fmt.Sprintf("nick=%s; pass=%s", s.config.Ncore.Nick, s.config.Ncore.Pass)) + resp, err := s.client.Do(req) if err != nil { - return nil, fmt.Errorf("error fetching profile for %s: %v", displayName, err) + return nil, fmt.Errorf("error performing request: %w", err) } defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("failed to fetch profile %s: received status %d", displayName, resp.StatusCode) + return nil, fmt.Errorf("received non-200 status code: %d", resp.StatusCode) } + doc, err := goquery.NewDocumentFromReader(resp.Body) if err != nil { - return nil, fmt.Errorf("error parsing profile document for %s: %v", displayName, err) + return nil, fmt.Errorf("error parsing profile document: %w", err) } - profile := &ProfileData{Owner: displayName, Timestamp: time.Now()} + + profile := &ProfileData{Owner: user.DisplayName, Timestamp: time.Now()} doc.Find(".userbox_tartalom_mini .profil_jobb_elso2").Each(func(i int, s *goquery.Selection) { label, value := s.Text(), s.Next().Text() switch label { @@ -308,10 +460,12 @@ func fetchProfile(url string, displayName string) (*ProfileData, error) { profile.Points, _ = strconv.Atoi(strings.ReplaceAll(value, " ", "")) } }) + doc.Find(".lista_mini_fej").Each(func(i int, s *goquery.Selection) { if matches := regexp.MustCompile(`\((\d+)\)`).FindStringSubmatch(s.Text()); len(matches) > 1 { fmt.Sscanf(matches[1], "%d", &profile.SeedingCount) } }) + return profile, nil } diff --git a/readme.md b/readme.md index 660f229..1cc3745 100644 --- a/readme.md +++ b/readme.md @@ -70,15 +70,7 @@ A simple Go project to scrape and track profile statistics (rank, upload, downlo 2. **Add Users using Docker** - Before starting the service, or to add new users later, run the `--add-user` command inside a temporary container. This ensures the user is added to the database in your persistent volume. - - ```bash - # Use 'docker compose run' to add users before starting - docker compose run --rm ncore-stats --add-user 'Alice,69' - docker compose run --rm ncore-stats --add-user 'Bob,420' - ``` - - If the container is already running, you can use `docker exec`: + When the container is already running, you can use `docker exec`: ```bash # The executable inside the container is named 'ncore-stats' docker exec ncore-stats ./ncore-stats --add-user 'Charlie,1337'