From e774aabdcbbd1937934ff441621e1a735923237a Mon Sep 17 00:00:00 2001 From: Kyle Jackson Date: Thu, 8 Aug 2024 12:40:47 +1000 Subject: [PATCH] adding sync and fishing --- .github/workflows/build-images.yml | 68 ++++++++++++++++- build/fishing/Dockerfile | 10 +++ build/sync/Dockerfile | 10 +++ cmd/api/main.go | 20 +++++ cmd/fishing/fishing.go | 112 ++++++++++++++++++++++++++++ cmd/sync/main.go | 48 ++++++++++++ go.mod | 38 +++++++++- go.sum | 108 +++++++++++++++++++++++++++ internal/artifacts/helpers.go | 4 +- internal/artifacts/items.go | 107 ++++++++++++++++++++++++++ internal/database/database.go | 44 +++++++++++ internal/database/items.go | 77 +++++++++++++++++++ internal/database/task.go | 76 +++++++++++++++++++ internal/middleware/transactions.go | 28 +++++++ internal/models/bank.go | 28 +++---- internal/models/characters.go | 5 +- internal/models/generic.go | 78 ++++++++++++------- internal/models/grand_exchange.go | 8 ++ internal/models/items.go | 31 ++++++++ internal/models/task.go | 25 +++++++ internal/routes/items.go | 70 +++++++++++++++++ internal/routes/router.go | 31 ++++++++ internal/routes/tasks.go | 83 +++++++++++++++++++++ internal/utils/errors.go | 34 +++++++++ internal/utils/headers.go | 21 ++++++ internal/utils/logger.go | 9 +++ internal/utils/query.go | 15 ++++ 27 files changed, 1139 insertions(+), 49 deletions(-) create mode 100644 build/fishing/Dockerfile create mode 100644 build/sync/Dockerfile create mode 100644 cmd/api/main.go create mode 100644 cmd/fishing/fishing.go create mode 100644 cmd/sync/main.go create mode 100644 internal/artifacts/items.go create mode 100644 internal/database/database.go create mode 100644 internal/database/items.go create mode 100644 internal/database/task.go create mode 100644 internal/middleware/transactions.go create mode 100644 internal/models/grand_exchange.go create mode 100644 internal/models/items.go create mode 100644 internal/models/task.go create mode 100644 internal/routes/items.go create mode 100644 internal/routes/router.go create mode 100644 internal/routes/tasks.go create mode 100644 internal/utils/headers.go create mode 100644 internal/utils/query.go diff --git a/.github/workflows/build-images.yml b/.github/workflows/build-images.yml index 252a019..b428497 100644 --- a/.github/workflows/build-images.yml +++ b/.github/workflows/build-images.yml @@ -6,6 +6,39 @@ on: - main jobs: + build-sync-image: + name: Build Sync Image + runs-on: ubuntu-latest + permissions: + packages: write + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Setup QEMU + uses: docker/setup-qemu-action@v3 + + - name: Setup Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Azure Container Registry + uses: docker/login-action@v3 + with: + registry: "ghcr.io" + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push image + uses: docker/build-push-action@v5 + with: + context: . + push: true + file: build/sync/Dockerfile + platforms: linux/amd64 + tags: | + ghcr.io/wizedkyle/artifactsmmo/sync:latest + ghcr.io/wizedkyle/artifactsmmo/sync:1.0.${{ github.run_id }} + build-miner-image: name: Build Miner Image runs-on: ubuntu-latest @@ -70,4 +103,37 @@ jobs: platforms: linux/amd64 tags: | ghcr.io/wizedkyle/artifactsmmo/woodcutting:latest - ghcr.io/wizedkyle/artifactsmmo/woodcutting:1.0.${{ github.run_id }} \ No newline at end of file + ghcr.io/wizedkyle/artifactsmmo/woodcutting:1.0.${{ github.run_id }} + + build-fishing-image: + name: Build Woodcutting Image + runs-on: ubuntu-latest + permissions: + packages: write + steps: + - name: Checkout repo + uses: actions/checkout@v4 + + - name: Setup QEMU + uses: docker/setup-qemu-action@v3 + + - name: Setup Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Login to Azure Container Registry + uses: docker/login-action@v3 + with: + registry: "ghcr.io" + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Build and push image + uses: docker/build-push-action@v5 + with: + context: . + push: true + file: build/fishing/Dockerfile + platforms: linux/amd64 + tags: | + ghcr.io/wizedkyle/artifactsmmo/fishing:latest + ghcr.io/wizedkyle/artifactsmmo/fishing:1.0.${{ github.run_id }} \ No newline at end of file diff --git a/build/fishing/Dockerfile b/build/fishing/Dockerfile new file mode 100644 index 0000000..1bcc385 --- /dev/null +++ b/build/fishing/Dockerfile @@ -0,0 +1,10 @@ +FROM golang:1.22.5-alpine3.20 + +WORKDIR /go/src/fishing + +COPY . /go/src/fishing + +RUN go get ./... +RUN go build ./cmd/fishing + +ENTRYPOINT ["./fishing"] \ No newline at end of file diff --git a/build/sync/Dockerfile b/build/sync/Dockerfile new file mode 100644 index 0000000..6c70567 --- /dev/null +++ b/build/sync/Dockerfile @@ -0,0 +1,10 @@ +FROM golang:1.22.5-alpine3.20 + +WORKDIR /go/src/sync + +COPY . /go/src/sync + +RUN go get ./... +RUN go build ./cmd/sync + +ENTRYPOINT ["./sync"] \ No newline at end of file diff --git a/cmd/api/main.go b/cmd/api/main.go new file mode 100644 index 0000000..333cd31 --- /dev/null +++ b/cmd/api/main.go @@ -0,0 +1,20 @@ +package main + +import ( + "github.com/wizedkyle/artifactsmmo/v2/internal/database" + "github.com/wizedkyle/artifactsmmo/v2/internal/routes" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.uber.org/zap" +) + +func main() { + utils.LoggerInit() + database.Init() + router := routes.Init() + routes.GenerateItemRoutes(router) + routes.GenerateTaskRoutes(router) + err := router.Run(":9000") + if err != nil { + utils.Logger.Fatal("failed to start gin server", zap.Error(err)) + } +} diff --git a/cmd/fishing/fishing.go b/cmd/fishing/fishing.go new file mode 100644 index 0000000..ab78688 --- /dev/null +++ b/cmd/fishing/fishing.go @@ -0,0 +1,112 @@ +package main + +import ( + "errors" + "fmt" + "github.com/wizedkyle/artifactsmmo/v2/internal/artifacts" + "github.com/wizedkyle/artifactsmmo/v2/internal/controllers" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.uber.org/zap" + "os" + "time" +) + +func main() { + utils.LoggerInit() + artifacts.Init() + for { + var ( + x int + y int + ) + fishingResource, ok := os.LookupEnv("FISHING_RESOURCE") + if !ok { + c, err := artifacts.Client.GetCharacter(*artifacts.Client.CharacterName) + if err != nil { + utils.Logger.Error("failed to get character information", zap.Error(err)) + continue + } + if c.Data.FishingLevel < models.ShrimpLevel { + x = models.GudgeonX + y = models.GudgeonY + } else if c.Data.MiningLevel < models.TroutLevel { + x = models.ShrimpX + y = models.ShrimpY + } else if c.Data.MiningLevel < models.BassLevel { + x = models.TroutX + y = models.TroutY + } else { + x = models.BassX + y = models.BassY + } + } else { + switch fishingResource { + case models.Gudgeon: + x = models.GudgeonX + y = models.GudgeonY + case models.Shrimp: + x = models.ShrimpX + y = models.ShrimpY + case models.Trout: + x = models.TroutX + y = models.TroutY + case models.Bass: + x = models.BassX + y = models.BassY + default: + x = models.GudgeonX + y = models.GudgeonY + } + } + c, err := artifacts.Client.GetCharacter(*artifacts.Client.CharacterName) + if err != nil { + utils.Logger.Error("failed to get character information", zap.Error(err)) + continue + } + if c.Data.X != x || c.Data.Y != y { + fmt.Printf("moving character to x=%d y=%d\n", x, y) + resp, err := artifacts.Client.ActionMove(*artifacts.Client.CharacterName, models.ActionMove{ + X: x, + Y: y, + }) + if err != nil { + utils.Logger.Error("failed to move character", zap.Error(err)) + continue + } + time.Sleep(utils.CalculateTimeDifference(resp.Data.Cooldown.StartedAt, resp.Data.Cooldown.Expiration)) + } + resp, err := artifacts.Client.ActionGathering(*artifacts.Client.CharacterName) + if errors.Is(err, utils.ErrCharacterInventoryFull) { + bankX, bankY := artifacts.Client.FindBuilding(models.Bank) + resp, err := artifacts.Client.ActionMove(*artifacts.Client.CharacterName, models.ActionMove{ + X: bankX, + Y: bankY, + }) + if err != nil { + utils.Logger.Error("failed to move character", zap.Error(err)) + continue + } + fmt.Printf("moving character to bank (x=%d y=%d)\n", bankX, bankY) + time.Sleep(utils.CalculateTimeDifference(resp.Data.Cooldown.StartedAt, resp.Data.Cooldown.Expiration)) + c, err := artifacts.Client.GetCharacter(*artifacts.Client.CharacterName) + if err != nil { + utils.Logger.Error("failed to get character information", zap.Error(err)) + continue + } + controllers.DepositAllInventory(c.Data.Inventory) + resp, err = artifacts.Client.ActionMove(*artifacts.Client.CharacterName, models.ActionMove{ + X: x, + Y: y, + }) + if err != nil { + utils.Logger.Error("failed to move character", zap.Error(err)) + continue + } + time.Sleep(utils.CalculateTimeDifference(resp.Data.Cooldown.StartedAt, resp.Data.Cooldown.Expiration)) + } else if err == nil { + fmt.Printf("%s collected %v\n", *artifacts.Client.CharacterName, resp.Data.Details.Items) + time.Sleep(utils.CalculateTimeDifference(resp.Data.Cooldown.StartedAt, resp.Data.Cooldown.Expiration)) + } + } +} diff --git a/cmd/sync/main.go b/cmd/sync/main.go new file mode 100644 index 0000000..5ac9339 --- /dev/null +++ b/cmd/sync/main.go @@ -0,0 +1,48 @@ +package main + +import ( + "github.com/wizedkyle/artifactsmmo/v2/internal/artifacts" + "github.com/wizedkyle/artifactsmmo/v2/internal/database" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.uber.org/zap" +) + +func main() { + utils.LoggerInit() + artifacts.Init() + database.Init() + ItemTypes := []string{ + "consumable", + "body_armor", + "weapon", + "resource", + "leg_armor", + "helmet", + "boots", + "shield", + "amulet", + "ring", + } + for _, itemType := range ItemTypes { + err := database.Client.DeleteItems(itemType) + if err != nil { + utils.Logger.Error("Failed to delete item type", zap.String("type", itemType), zap.Error(err)) + } + var items []interface{} + resp, err := artifacts.Client.GetItems(models.GetAllItemsQueryParameters{ + Type: itemType, + Size: 100, + }) + if err != nil { + utils.Logger.Error("failed to get items", zap.Error(err)) + } + for _, item := range resp.Data { + items = append(items, item) + } + err = database.Client.CreateItems(items) + if err != nil { + utils.Logger.Error("failed to create items", zap.Error(err)) + } + } +} diff --git a/go.mod b/go.mod index 0734c72..7dd437a 100644 --- a/go.mod +++ b/go.mod @@ -9,11 +9,33 @@ require ( ) require ( + github.com/bytedance/sonic v1.11.6 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/cors v1.7.2 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/compress v1.17.2 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect @@ -22,10 +44,22 @@ require ( github.com/spf13/cast v1.6.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.6.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect + go.mongodb.org/mongo-driver v1.16.0 // indirect go.uber.org/multierr v1.10.0 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/crypto v0.23.0 // indirect golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect - golang.org/x/sys v0.18.0 // indirect - golang.org/x/text v0.14.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/sync v0.7.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index e3242a6..042f633 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,11 @@ +github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= +github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -7,20 +15,60 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= +github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +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/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= +github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +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/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -49,25 +97,83 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.16.0 h1:tpRsfBJMROVHKpdGyc1BBEzzjDUWjItxbVSZ8Ls4BQ4= +go.mongodb.org/mongo-driver v1.16.0/go.mod h1:oB6AhJQvFQL4LEHyXi6aJzQJtBiTQHiAd83l0GdFaiw= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +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= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +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= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +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-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.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +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= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -76,3 +182,5 @@ gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/artifacts/helpers.go b/internal/artifacts/helpers.go index 9d8909b..f99c6a3 100644 --- a/internal/artifacts/helpers.go +++ b/internal/artifacts/helpers.go @@ -1,6 +1,8 @@ package artifacts -import "github.com/wizedkyle/artifactsmmo/v2/internal/models" +import ( + "github.com/wizedkyle/artifactsmmo/v2/internal/models" +) // FindBuilding // Returns the coordinates for different buildings. diff --git a/internal/artifacts/items.go b/internal/artifacts/items.go new file mode 100644 index 0000000..8e86abb --- /dev/null +++ b/internal/artifacts/items.go @@ -0,0 +1,107 @@ +package artifacts + +import ( + "encoding/json" + "fmt" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "io" + "net/http" + "strconv" +) + +// GetItems +// Returns information about the items based on query parameters. +func (a *artifacts) GetItems(params models.GetAllItemsQueryParameters) (*models.ItemsResponse, error) { + req, err := a.generateRequest(http.MethodGet, "/items/", nil) + if err != nil { + return nil, err + } + q := req.URL.Query() + if params.CraftMaterial != "" { + q.Add("craft_material", params.CraftMaterial) + } + if params.CraftSkill != "" { + q.Add("craft_skill", params.CraftSkill) + } + if params.MaxLevel != 0 { + q.Add("max_level", strconv.Itoa(params.MaxLevel)) + } + if params.MinLevel != 0 { + q.Add("min_level", strconv.Itoa(params.MinLevel)) + } + if params.Name != "" { + q.Add("name", params.Name) + } + if params.Page != 0 { + q.Add("page", strconv.Itoa(params.Page)) + } + if params.Size != 0 { + q.Add("size", strconv.Itoa(params.Size)) + } else { + q.Add("size", strconv.Itoa(50)) + } + if params.Type != "" { + q.Add("type", params.Type) + } + req.URL.RawQuery = q.Encode() + resp, err := a.Client.Do(req) + if err != nil { + return nil, err + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + defer resp.Body.Close() + switch resp.StatusCode { + case 200: + var response models.ItemsResponse + err = json.Unmarshal(body, &response) + if err != nil { + return nil, err + } + return &response, nil + case 403: + return nil, utils.ErrNotAuthenticated + case 404: + return nil, utils.ErrItemNotFound + default: + fmt.Println(string(body)) + return nil, utils.ErrGenericError + } +} + +// GetItem +// Returns information about a specific item. +func (a *artifacts) GetItem(code string) (*models.ItemResponse, error) { + req, err := a.generateRequest(http.MethodGet, "/items/"+code, nil) + if err != nil { + return nil, err + } + resp, err := a.Client.Do(req) + if err != nil { + return nil, err + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + defer resp.Body.Close() + switch resp.StatusCode { + case 200: + var response models.ItemResponse + err = json.Unmarshal(body, &response) + if err != nil { + return nil, err + } + return &response, nil + case 403: + return nil, utils.ErrNotAuthenticated + case 404: + return nil, utils.ErrItemNotFound + default: + fmt.Println(string(body)) + return nil, utils.ErrGenericError + } +} diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..c613865 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,44 @@ +package database + +import ( + "context" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.uber.org/zap" + "os" +) + +var ( + Client = database{} +) + +type database struct { + Client *mongo.Client + ItemsCollection *mongo.Collection + TaskCollection *mongo.Collection +} + +const ( + itemsCollection = "items" + databaseName = "artifactsmmo" + taskCollection = "tasks" +) + +func Init() { + var ( + opts *options.ClientOptions + ) + if os.Getenv("GIN_MODE") == "" { + opts = options.Client().ApplyURI("mongodb://mongodb:27017") + } else { + // TODO: implement cosmosdb + } + client, err := mongo.Connect(context.TODO(), opts) + if err != nil { + utils.Logger.Fatal("failed to connect to database", zap.Error(err)) + } + Client.ItemsCollection = client.Database(databaseName).Collection(itemsCollection) + Client.TaskCollection = client.Database(databaseName).Collection(taskCollection) + Client.Client = client +} diff --git a/internal/database/items.go b/internal/database/items.go new file mode 100644 index 0000000..381ec5f --- /dev/null +++ b/internal/database/items.go @@ -0,0 +1,77 @@ +package database + +import ( + "context" + "errors" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +// CreateItems +// Bulk creates new items in the database. This is primarily used for sync items from the Artifacts API. +func (d *database) CreateItems(items []interface{}) error { + opts := options.InsertMany().SetOrdered(false) + _, err := d.ItemsCollection.InsertMany(context.TODO(), items, opts) + if err != nil { + return err + } + return nil +} + +// DeleteItems +// Deletes all items in the item database with the specified type. This is only used by the sync task as it's quicker than updating each record. +func (d *database) DeleteItems(itemType string) error { + _, err := d.ItemsCollection.DeleteMany(context.TODO(), bson.D{{"type", itemType}}) + if err != nil { + return err + } + return nil +} + +// GetItem +// Returns an item from the database based on the specified item name. +func (d *database) GetItem(code string) (*models.ItemDetails, error) { + var result models.ItemDetails + err := d.ItemsCollection.FindOne(context.TODO(), bson.D{{"code", code}}).Decode(&result) + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, utils.ErrItemNotFound + } else if err != nil { + return nil, err + } + return &result, nil +} + +// ListItems +// Returns items from the database based on the supplied filters. +func (d *database) ListItems(limit int64, params models.ListItemParameters) (*[]models.ItemDetails, error) { + var items []models.ItemDetails + opts := options.Find().SetLimit(limit) + filter := bson.D{ + {"type", params.Type}, + {"subType", params.SubType}, + {"level", params.Level}, + } + cursor, err := d.ItemsCollection.Find(context.TODO(), filter, opts) + if err != nil { + return nil, err + } + for cursor.Next(context.TODO()) { + var item models.ItemDetails + err := cursor.Decode(&item) + if err != nil { + return nil, err + } + items = append(items, item) + } + if err := cursor.Err(); err != nil { + return nil, err + } + cursor.Close(context.TODO()) + if len(items) == 0 { + return nil, utils.ErrItemsNotFound + } + return &items, nil +} diff --git a/internal/database/task.go b/internal/database/task.go new file mode 100644 index 0000000..4273c89 --- /dev/null +++ b/internal/database/task.go @@ -0,0 +1,76 @@ +package database + +import ( + "context" + "errors" + "github.com/google/uuid" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" +) + +// CreateTask +// Creates a new task in the database. +func (d *database) CreateTask(task models.Task) (*models.Task, error) { + var ( + result models.Task + ) + task.Id = uuid.NewString() + _, err := d.TaskCollection.InsertOne(context.TODO(), task) + if err != nil { + return nil, err + } + err = d.TaskCollection.FindOne(context.TODO(), bson.D{{"_id", task.Id}}).Decode(&result) + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, utils.ErrTaskNotFound + } else if err != nil { + return nil, err + } + return &result, nil +} + +// GetTask +// Returns a task from the database based on the specified id. +func (d *database) GetTask(id string) (*models.Task, error) { + var result models.Task + err := d.TaskCollection.FindOne(context.TODO(), bson.D{{"_id", id}}).Decode(&result) + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, utils.ErrTaskNotFound + } else if err != nil { + return nil, err + } + return &result, nil +} + +// ListTasks +// Returns tasks from the database based on the supplied filters. +func (d *database) ListTasks(action string, limit int64, status string) (*[]models.Task, error) { + var tasks []models.Task + opts := options.Find().SetLimit(limit) + filter := bson.D{ + {"action", action}, + {"status", status}, + } + cursor, err := d.TaskCollection.Find(context.TODO(), filter, opts) + if err != nil { + return nil, err + } + for cursor.Next(context.TODO()) { + var task models.Task + err := cursor.Decode(&task) + if err != nil { + return nil, err + } + tasks = append(tasks, task) + } + if err := cursor.Err(); err != nil { + return nil, err + } + cursor.Close(context.TODO()) + if len(tasks) == 0 { + return nil, utils.ErrTasksNotFound + } + return &tasks, nil +} diff --git a/internal/middleware/transactions.go b/internal/middleware/transactions.go new file mode 100644 index 0000000..bf527f7 --- /dev/null +++ b/internal/middleware/transactions.go @@ -0,0 +1,28 @@ +package middleware + +import ( + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "net/http" +) + +// ValidateTransactionId +// Checks for X-Request-ID on each request, if it is not found the header is added. +func ValidateTransactionId() gin.HandlerFunc { + return func(c *gin.Context) { + header, err := utils.GetTransactionIdHeader(c) + if err != nil { + c.AbortWithStatusJSON(http.StatusInternalServerError, utils.GenericInternalServerErrorMessage) + return + } + if header.TransactionId != "" { + c.Next() + } else { + id := uuid.NewString() + c.Header("X-Request-ID", id) + c.Request.Header.Add("X-Request-ID", id) + c.Next() + } + } +} diff --git a/internal/models/bank.go b/internal/models/bank.go index a0b8670..e6d6298 100644 --- a/internal/models/bank.go +++ b/internal/models/bank.go @@ -17,24 +17,24 @@ type BankDepositResponse struct { } type ItemDetails struct { - Name string `json:"name"` - Code string `json:"code"` - Level int `json:"level"` - Type string `json:"type"` - SubType string `json:"subType"` - Description string `json:"description"` - Effects []ItemEffect `json:"effects,omitempty"` - Craft CraftInformation `json:"craft,omitempty"` + Name string `bson:"name" json:"name"` + Code string `bson:"code" json:"code"` + Level int `bson:"level" json:"level"` + Type string `bson:"type" json:"type"` + SubType string `bson:"subType" json:"subType"` + Description string `bson:"description" json:"description"` + Effects []ItemEffect `bson:"effects,omitempty" json:"effects,omitempty"` + Craft CraftInformation `bson:"craft,omitempty" json:"craft,omitempty"` } type ItemEffect struct { - Name string `json:"name"` - Value int `json:"value"` + Name string `bson:"name" json:"name"` + Value int `bson:"value" json:"value"` } type CraftInformation struct { - Skill string `json:"skill,omitempty"` - Level int `json:"level,omitempty"` - Items []Item `json:"items,omitempty"` - Quantity int `json:"quantity,omitempty"` + Skill string `bson:"skill,omitempty" json:"skill,omitempty"` + Level int `bson:"level,omitempty" json:"level,omitempty"` + Items []Item `bson:"items,omitempty" json:"items,omitempty"` + Quantity int `bson:"quantity,omitempty" json:"quantity,omitempty"` } diff --git a/internal/models/characters.go b/internal/models/characters.go index e618fca..aac6b0a 100644 --- a/internal/models/characters.go +++ b/internal/models/characters.go @@ -115,8 +115,8 @@ type CraftingDetails struct { } type Item struct { - Code string `json:"code"` - Quantity int `json:"quantity"` + Code string `bson:"code" json:"code"` + Quantity int `bson:"quantity" json:"quantity"` } type Content struct { @@ -127,6 +127,7 @@ type Content struct { type Destination struct { Name string `json:"name"` + Skin string `json:"skin"` X int `json:"x"` Y int `json:"y"` Content Content `json:"content,omitempty"` diff --git a/internal/models/generic.go b/internal/models/generic.go index 14f3303..d934243 100644 --- a/internal/models/generic.go +++ b/internal/models/generic.go @@ -3,35 +3,55 @@ package models import "time" const ( - AshTree string = "ash_tree" - AshTeeX int = 6 - AshTreeY int = 1 - Bank string = "bank" - BankX int = 4 - BankY int = 1 - BirchTree string = "birch_tree" - BirchTreeLevel int = 20 - BirchTreeX int = 3 - BirchTreeY int = 5 - CoalLevel int = 20 - Coal string = "coal_rocks" - CoalX int = 1 - CoalY int = 6 - Copper string = "copper_ore" - CopperX int = 2 - CopperY int = 0 - GoldLevel int = 30 - Gold string = "gold_rocks" - GoldX int = 10 - GoldY int = -4 - IronLevel int = 10 - Iron string = "iron_rocks" - IronX int = 1 - IronY int = 7 - SpruceTree string = "spruce_tree" - SpruceTreeLevel int = 10 - SpruceTreeX int = 2 - SpruceTreeY int = 6 + AshTree string = "ash_tree" + AshTeeX int = 6 + AshTreeY int = 1 + Bank string = "bank" + BankX int = 4 + BankY int = 1 + Bass string = "bass" + BassLevel int = 30 + BassX int = -3 + BassY int = 6 + BirchTree string = "birch_tree" + BirchTreeLevel int = 20 + BirchTreeX int = 3 + BirchTreeY int = 5 + CoalLevel int = 20 + Coal string = "coal_rocks" + CoalX int = 1 + CoalY int = 6 + Copper string = "copper_ore" + CopperX int = 2 + CopperY int = 0 + Gudgeon string = "gudgeon" + GudgeonX int = 4 + GudgeonY int = 2 + GoldLevel int = 30 + Gold string = "gold_rocks" + GoldX int = 10 + GoldY int = -4 + ItemTypeConsumable string = "" + ItemTypeBodyArmor string = "" + IronLevel int = 10 + Iron string = "iron_rocks" + IronX int = 1 + IronY int = 7 + Shrimp string = "shrimp" + ShrimpLevel int = 10 + ShrimpX int = 5 + ShrimpY int = 2 + SpruceTree string = "spruce_tree" + SpruceTreeLevel int = 10 + SpruceTreeX int = 2 + SpruceTreeY int = 6 + Trout string = "trout" + TroutLevel int = 20 + TroutX int = -2 + TroutY int = 6 + ItemRetrieved string = "item_retrieved" + TaskCreated string = "task_created" + TaskRetrieved string = "task_retrieved" ) type Cooldown struct { diff --git a/internal/models/grand_exchange.go b/internal/models/grand_exchange.go new file mode 100644 index 0000000..3c31b72 --- /dev/null +++ b/internal/models/grand_exchange.go @@ -0,0 +1,8 @@ +package models + +type GrandExchangeItemDetail struct { + Code string `json:"code"` + Stock int `json:"stock"` + SellPrice int `json:"sell_price"` + BuyPrice int `json:"buy_price"` +} diff --git a/internal/models/items.go b/internal/models/items.go new file mode 100644 index 0000000..78841d7 --- /dev/null +++ b/internal/models/items.go @@ -0,0 +1,31 @@ +package models + +type GetAllItemsQueryParameters struct { + CraftMaterial string `json:"craft_material"` + CraftSkill string `json:"craft_skill"` + MaxLevel int `json:"max_level"` + MinLevel int `json:"min_level"` + Name string `json:"name"` + Page int `json:"page"` + Size int `json:"size"` + Type string `json:"type"` +} + +type ListItemParameters struct { + Type string `json:"type"` + SubType string `json:"subtype"` + Level int `json:"level"` +} + +type ItemsResponse struct { + Data []ItemDetails `json:"data"` + Total int `json:"total"` + Page int `json:"page"` + Size int `json:"size"` + Pages int `json:"pages"` +} + +type ItemResponse struct { + Data ItemDetails `json:"data"` + Ge GrandExchangeItemDetail `json:"ge,omitempty"` +} diff --git a/internal/models/task.go b/internal/models/task.go new file mode 100644 index 0000000..086cd36 --- /dev/null +++ b/internal/models/task.go @@ -0,0 +1,25 @@ +package models + +const ( + TaskActionCrafting = "crafting" + TaskStatusPending = "pending" + TaskStatusRunning = "running" + TaskStatusSuccess = "success" + TaskStatusError = "error" +) + +type CreateTask struct { + Action string `json:"action"` + Item string `json:"item"` + Quantity int `json:"quantity"` + Status string `json:"status"` +} + +type Task struct { + Id string `bson:"_id" json:"id"` + Action string `bson:"action" json:"action"` + Item string `bson:"item" json:"item"` + Quantity int `bson:"quantity" json:"quantity"` + Status string `bson:"status" json:"status"` + ErrorReason string `bson:"errorReason" json:"errorReason"` +} diff --git a/internal/routes/items.go b/internal/routes/items.go new file mode 100644 index 0000000..aabbfac --- /dev/null +++ b/internal/routes/items.go @@ -0,0 +1,70 @@ +package routes + +import ( + "errors" + "github.com/gin-gonic/gin" + "github.com/wizedkyle/artifactsmmo/v2/internal/database" + "github.com/wizedkyle/artifactsmmo/v2/internal/middleware" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "net/http" + "strconv" +) + +func GenerateItemRoutes(router *gin.Engine) { + itemRoutes := router.Group("/v1/items") + itemRoutes.Use(middleware.ValidateTransactionId()) + { + itemRoutes.GET("", listItems) + itemRoutes.GET(":code", getItem) + } +} + +func listItems(c *gin.Context) { + transactionId, _ := utils.GetTransactionIdHeader(c) + limit := utils.QueryLimit(c) + itemType := c.Query("type") + subType := c.Query("subtype") + level, err := strconv.Atoi(c.Query("level")) + if err != nil { + utilErr := utils.GenerateError(models.ItemRetrieved, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + results, err := database.Client.ListItems(limit, models.ListItemParameters{ + Type: itemType, + SubType: subType, + Level: level, + }) + if errors.Is(err, utils.ErrItemsNotFound) { + utilErr := utils.GenerateError(models.ItemRetrieved, utils.ItemsNotFound, http.StatusNotFound, transactionId.TransactionId, nil) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } else if err != nil { + utilErr := utils.GenerateError(models.ItemRetrieved, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + c.JSON(http.StatusOK, results) +} + +func getItem(c *gin.Context) { + transactionId, _ := utils.GetTransactionIdHeader(c) + code := c.Param("code") + result, err := database.Client.GetItem(code) + if errors.Is(err, utils.ErrItemNotFound) { + utilErr := utils.GenerateError(models.ItemRetrieved, utils.ItemNotFound, http.StatusNotFound, transactionId.TransactionId, nil) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } else if err != nil { + utilErr := utils.GenerateError(models.ItemRetrieved, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + c.JSON(http.StatusOK, result) +} diff --git a/internal/routes/router.go b/internal/routes/router.go new file mode 100644 index 0000000..daa1291 --- /dev/null +++ b/internal/routes/router.go @@ -0,0 +1,31 @@ +package routes + +import ( + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "time" +) + +func Init() *gin.Engine { + router := gin.Default() + router.SetTrustedProxies(nil) + router.Use(cors.New(cors.Config{ + AllowAllOrigins: true, + AllowMethods: []string{ + "DELETE", + "GET", + "POST", + "PUT", + }, + AllowHeaders: []string{ + "Origin", + "Authorization", + }, + AllowCredentials: true, + ExposeHeaders: []string{ + "Content-Length", + }, + MaxAge: 12 * time.Hour, + })) + return router +} diff --git a/internal/routes/tasks.go b/internal/routes/tasks.go new file mode 100644 index 0000000..afad2c2 --- /dev/null +++ b/internal/routes/tasks.go @@ -0,0 +1,83 @@ +package routes + +import ( + "errors" + "github.com/gin-gonic/gin" + "github.com/wizedkyle/artifactsmmo/v2/internal/database" + "github.com/wizedkyle/artifactsmmo/v2/internal/middleware" + "github.com/wizedkyle/artifactsmmo/v2/internal/models" + "github.com/wizedkyle/artifactsmmo/v2/internal/utils" + "net/http" +) + +func GenerateTaskRoutes(router *gin.Engine) { + taskRoutes := router.Group("/v1/tasks") + taskRoutes.Use(middleware.ValidateTransactionId()) + { + taskRoutes.POST("", createTask) + taskRoutes.GET("", listTasks) + taskRoutes.GET(":id", getTask) + } +} + +func createTask(c *gin.Context) { + var request models.Task + transactionId, _ := utils.GetTransactionIdHeader(c) + if err := c.ShouldBind(&request); err != nil { + utilErr := utils.GenerateError(models.TaskCreated, utils.InvalidRequestBody, http.StatusBadRequest, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + result, err := database.Client.CreateTask(models.Task{ + Action: request.Action, + Item: request.Item, + Quantity: request.Quantity, + Status: request.Status, + }) + if err != nil { + utilErr := utils.GenerateError(models.TaskCreated, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + c.JSON(http.StatusOK, result) +} + +func listTasks(c *gin.Context) { + transactionId, _ := utils.GetTransactionIdHeader(c) + action := c.Query("action") + limit := utils.QueryLimit(c) + status := c.Query("status") + results, err := database.Client.ListTasks(action, limit, status) + if errors.Is(err, utils.ErrTasksNotFound) { + utilErr := utils.GenerateError(models.TaskRetrieved, utils.TasksNotFound, http.StatusNotFound, transactionId.TransactionId, nil) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } else if err != nil { + utilErr := utils.GenerateError(models.TaskRetrieved, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + c.JSON(http.StatusOK, results) +} + +func getTask(c *gin.Context) { + transactionId, _ := utils.GetTransactionIdHeader(c) + id := c.Param("id") + result, err := database.Client.GetTask(id) + if errors.Is(err, utils.ErrTaskNotFound) { + utilErr := utils.GenerateError(models.TaskRetrieved, utils.TaskNotFound, http.StatusNotFound, transactionId.TransactionId, nil) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } else if err != nil { + utilErr := utils.GenerateError(models.TaskRetrieved, utils.GenericInternalServerErrorMessage, http.StatusInternalServerError, transactionId.TransactionId, err) + utils.WriteErrorLog(utilErr) + c.AbortWithStatusJSON(utilErr.ExternalError.Code, utilErr.ExternalError) + return + } + c.JSON(http.StatusOK, result) +} diff --git a/internal/utils/errors.go b/internal/utils/errors.go index b78de89..1fe9e2d 100644 --- a/internal/utils/errors.go +++ b/internal/utils/errors.go @@ -2,6 +2,18 @@ package utils import "errors" +type Error struct { + InternalError error `json:"internalError"` + ExternalError ExternalError `json:"externalError"` +} + +type ExternalError struct { + Id string `json:"id"` + Message string `json:"message"` + Code int `json:"code"` + TransactionId string `json:"transactionId"` +} + const ( CharacterAtDestination = "Character already at destination." CharacterCooldown = "Character in cooldown." @@ -12,11 +24,16 @@ const ( CharacterNotFound = "Character not found." CharacterNotAtSkillLevel = "Character not at required skill level." GenericError = "Unknown error, server could be unavailable." + GenericInternalServerErrorMessage = "internal server error" + InvalidRequestBody = "invalid request body" ItemNotFound = "Item not found." + ItemsNotFound = "Items not found." ItemMissingOrInsufficientQuantity = "Missing item or insufficient quantity in your inventory." MapNotFound = "Map not found." NotAuthenticated = "Not authenticated." ResourceNotFound = "Resource not found on this map." + TaskNotFound = "Task not found." + TasksNotFound = "Tasks not found." ) var ( @@ -30,8 +47,25 @@ var ( ErrCharacterNotAtSkillLevel = errors.New(CharacterNotAtSkillLevel) ErrGenericError = errors.New(GenericError) ErrItemNotFound = errors.New(ItemNotFound) + ErrItemsNotFound = errors.New(ItemsNotFound) ErrItemMissingOrInsufficientQuantity = errors.New(ItemMissingOrInsufficientQuantity) ErrMapNotFound = errors.New(MapNotFound) ErrNotAuthenticated = errors.New(NotAuthenticated) ErrResourceNotFound = errors.New(ResourceNotFound) + ErrTaskNotFound = errors.New(TaskNotFound) + ErrTasksNotFound = errors.New(TasksNotFound) ) + +// GenerateError +// Generates an error message that is used when processing API requests. +func GenerateError(id string, message string, code int, transactionId string, err error) *Error { + return &Error{ + InternalError: err, + ExternalError: ExternalError{ + Id: id, + Message: message, + Code: code, + TransactionId: transactionId, + }, + } +} diff --git a/internal/utils/headers.go b/internal/utils/headers.go new file mode 100644 index 0000000..583ef7a --- /dev/null +++ b/internal/utils/headers.go @@ -0,0 +1,21 @@ +package utils + +import ( + "fmt" + "github.com/gin-gonic/gin" +) + +type TransactionIdHeader struct { + TransactionId string `header:"X-Request-Id"` +} + +// GetTransactionIdHeader +// Retrieves the X-Request-ID header from the supplied context. +func GetTransactionIdHeader(c *gin.Context) (*TransactionIdHeader, error) { + var header TransactionIdHeader + if err := c.ShouldBindHeader(&header); err != nil { + fmt.Println(err) + return nil, err + } + return &header, nil +} diff --git a/internal/utils/logger.go b/internal/utils/logger.go index bfae63d..1f794bc 100644 --- a/internal/utils/logger.go +++ b/internal/utils/logger.go @@ -11,3 +11,12 @@ func LoggerInit() { } Logger = l } + +func WriteErrorLog(err *Error) { + Logger.Error(err.ExternalError.Message, + zap.Error(err.InternalError), + zap.String("id", err.ExternalError.Id), + zap.String("message", err.ExternalError.Message), + zap.Int("code", err.ExternalError.Code), + zap.String("transactionId", err.ExternalError.TransactionId)) +} diff --git a/internal/utils/query.go b/internal/utils/query.go new file mode 100644 index 0000000..be44c5a --- /dev/null +++ b/internal/utils/query.go @@ -0,0 +1,15 @@ +package utils + +import ( + "github.com/gin-gonic/gin" + "strconv" +) + +func QueryLimit(c *gin.Context) int64 { + limit := c.DefaultQuery("limit", "10") + limitInt64, err := strconv.ParseInt(limit, 10, 64) + if err != nil { + return 0 + } + return limitInt64 +}