From cf3706f4b1991f331d218220d65022e049c66422 Mon Sep 17 00:00:00 2001 From: lihini Date: Mon, 29 Jul 2024 15:11:08 +0530 Subject: [PATCH] Kite Competition API (#34) * feat: auth: add client validation for weather computer * fix: weather-data: include author when querying for duplicate data on commit * chore: ci authenticated through GCP WFI * fix: issues in github workflow * fix: set permissions in github workflow * fix: use node 20 following github workflow removing support for node 16 * fix: debug github workflow cannot find package.json error * fix: debug github workflow cannot find package.json error * fix: debug github workflow cannot find package.json error * fix: debug github workflow cannot find package.json error * fix: use node 20 following github workflow removing support for node 16 * fix: debug github workflow cannot find package.json error * fix: debug github workflow cannot find package.json error * fix: use GCP WFI instead of firebase token to deploy * fix: debug github workflow env vars not set * fix: debug github workflow use wfi instead of firebase token * fix: debug github workflow use wfi instead of firebase token * fix: debug github workflow use wfi instead of firebase token * fix: debug github workflow use wfi instead of firebase token * fix: debug github workflow use wfi instead of firebase token * chore: use service account for authenticating through wif * chore: workflow authentication with latest tools * chore: workflow authentication with latest tools * chore: workflow authentication with latest tools * chore: workflow authentication using service account key * chore: deploy debug workflow * chore: deploy workflow with env vars * chore: deploy workflow with env vars * chore: deploy workflow with env vars * chore: deploy workflow with env vars * docs: deploy workflow config * feat: accept client id and api key as body params * chore: attempt to fix error Failed to get Firebase project weatherkids-dev-67016. Please make sure the project exists and your account has permission to access it. * chore: attempt to fix error Failed to get Firebase project weatherkids-dev-67016. Please make sure the project exists and your account has permission to access it. * chore: attempt to fix error Failed to get Firebase project weatherkids-dev-67016. Please make sure the project exists and your account has permission to access it. * chore: attempt to fix error Failed to get Firebase project weatherkids-dev-67016. Please make sure the project exists and your account has permission to access it. * chore: debug error Failed to get Firebase project weatherkids-dev-67016. Please make sure the project exists and your account has permission to access it. * chore: deploy to firebase with github environment * fix: errors in points module tests * feat: commit weather data from weather computer clients * chore: increase build time memory * fix: issue long term tokens for the time being * feat: accept time in ISO format and sensor_id as inputs for data commit * fix: log server time for kaushitha's weather station * fix: include server timestamp in bulk commit response * fix: compile errors * chore: error logs for weather computer * fix: include temporary timestamp fix for test weather station * fix: include temporary timestamp fix for test weather station * feat: create kite-players and kite-data modules (#25) * feat: create kite-players and kite-data modules * Update create-bulk-kite-data.dto.ts * fix: fix mention changes in kite-players module and kite-data module --------- Co-authored-by: lihini * limit leaderboard players to 10 Co-authored-by: Hirushan99 * feat: create findKitePlayerByUserId endpoint * chore: update version --------- Co-authored-by: Hirushan99 --- package-lock.json | 367 ++++- package.json | 5 +- src/app.module.ts | 33 +- src/modules/auth/auth.controller.ts | 36 +- src/modules/auth/auth.module.ts | 5 +- src/modules/auth/auth.service.ts | 50 + .../clients/clients.controller.spec.ts | 18 + src/modules/clients/clients.controller.ts | 15 + src/modules/clients/clients.module.ts | 17 + src/modules/clients/clients.service.spec.ts | 18 + src/modules/clients/clients.service.ts | 35 + src/modules/clients/dto/create-client.dto.ts | 5 + src/modules/clients/entities/client.entity.ts | 25 + .../common/guards/gavesha-client.guard.ts | 19 +- .../common/guards/gavesha-user.guard.ts | 2 +- .../interfaces/gen-client-key.interface.ts | 9 + .../dto/bulk-create-kite-data-response.dto.ts | 6 + .../dto/create-bulk-kite-data.dto.ts | 39 + .../kite-data/dto/get-kite-datum.dto.ts | 31 + .../kite-data/dto/kite-datapoint.dto.ts | 24 + .../kite-data/entities/kite-datum-entity.ts | 38 + .../kite-data/kite-data.controller.spec.ts | 18 + src/modules/kite-data/kite-data.controller.ts | 84 ++ src/modules/kite-data/kite-data.module.ts | 21 + .../kite-data/kite-data.service.spec.ts | 18 + src/modules/kite-data/kite-data.service.ts | 1208 +++++++++++++++++ .../schema/kitedata-metadata.schema.ts | 25 + .../dto/create-kite-player-dto.ts | 13 + .../kite-players/dto/get-kite-player-dto.ts | 10 + .../dto/kite-player-created-response.dto.ts | 8 + .../dto/kite-player-updated-response.dto.ts | 6 + .../dto/update-kite-player-dto.ts | 4 + .../entities/kite-player.entity.ts | 39 + .../kite-players.controller.spec.ts | 18 + .../kite-players/kite-players.controller.ts | 72 + .../kite-players/kite-players.module.ts | 23 + .../kite-players/kite-players.service.spec.ts | 18 + .../kite-players/kite-players.service.ts | 141 ++ src/modules/users/session/session.module.ts | 19 +- src/modules/users/session/session.service.ts | 46 +- src/modules/users/token/token.service.ts | 58 +- src/modules/users/users.module.ts | 4 +- src/modules/users/users.service.ts | 6 +- .../bulk-create-weather-data-response.dto.ts | 1 + .../dto/create-bulk-weather-data.dto.ts | 7 +- ...create-weathercom-bulk-weather-data.dto.ts | 24 + .../entities/weather-datapoint.entity.ts | 4 + .../weather-data/weather-data.controller.ts | 94 +- .../weather-data/weather-data.module.ts | 4 +- .../weather-data/weather-data.service.ts | 69 +- .../entities/weather-station.entity.ts | 3 + .../weather-stations.module.ts | 4 +- .../weather-stations.service.ts | 21 +- 53 files changed, 2776 insertions(+), 111 deletions(-) create mode 100644 src/modules/clients/clients.controller.spec.ts create mode 100644 src/modules/clients/clients.controller.ts create mode 100644 src/modules/clients/clients.module.ts create mode 100644 src/modules/clients/clients.service.spec.ts create mode 100644 src/modules/clients/clients.service.ts create mode 100644 src/modules/clients/dto/create-client.dto.ts create mode 100644 src/modules/clients/entities/client.entity.ts create mode 100644 src/modules/common/interfaces/gen-client-key.interface.ts create mode 100644 src/modules/kite-data/dto/bulk-create-kite-data-response.dto.ts create mode 100644 src/modules/kite-data/dto/create-bulk-kite-data.dto.ts create mode 100644 src/modules/kite-data/dto/get-kite-datum.dto.ts create mode 100644 src/modules/kite-data/dto/kite-datapoint.dto.ts create mode 100644 src/modules/kite-data/entities/kite-datum-entity.ts create mode 100644 src/modules/kite-data/kite-data.controller.spec.ts create mode 100644 src/modules/kite-data/kite-data.controller.ts create mode 100644 src/modules/kite-data/kite-data.module.ts create mode 100644 src/modules/kite-data/kite-data.service.spec.ts create mode 100644 src/modules/kite-data/kite-data.service.ts create mode 100644 src/modules/kite-data/schema/kitedata-metadata.schema.ts create mode 100644 src/modules/kite-players/dto/create-kite-player-dto.ts create mode 100644 src/modules/kite-players/dto/get-kite-player-dto.ts create mode 100644 src/modules/kite-players/dto/kite-player-created-response.dto.ts create mode 100644 src/modules/kite-players/dto/kite-player-updated-response.dto.ts create mode 100644 src/modules/kite-players/dto/update-kite-player-dto.ts create mode 100644 src/modules/kite-players/entities/kite-player.entity.ts create mode 100644 src/modules/kite-players/kite-players.controller.spec.ts create mode 100644 src/modules/kite-players/kite-players.controller.ts create mode 100644 src/modules/kite-players/kite-players.module.ts create mode 100644 src/modules/kite-players/kite-players.service.spec.ts create mode 100644 src/modules/kite-players/kite-players.service.ts create mode 100644 src/modules/weather-data/dto/create-weathercom-bulk-weather-data.dto.ts diff --git a/package-lock.json b/package-lock.json index c7ce134..355c83c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "weatherkids-data-api", - "version": "0.0.7", + "version": "0.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "weatherkids-data-api", - "version": "0.0.7", + "version": "0.2.0", "license": "UNLICENSED", "dependencies": { "@nestjs/common": "^10.2.10", @@ -18,6 +18,7 @@ "@nestjs/platform-express": "^10.2.7", "@nestjs/schedule": "^4.0.0", "@nestjs/swagger": "^7.1.14", + "bcrypt": "^5.1.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.0", "express": "^4.18.2", @@ -36,7 +37,7 @@ "@nestjs/testing": "^10.3.0", "@shelf/jest-mongodb": "^4.2.0", "@types/express": "^4.17.17", - "@types/jest": "^29.5.2", + "@types/jest": "^29.5.12", "@types/node": "^20.3.1", "@types/supertest": "^2.0.12", "@typescript-eslint/eslint-plugin": "^6.0.0", @@ -2485,6 +2486,85 @@ "node": ">=8" } }, + "node_modules/@mapbox/node-pre-gyp": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz", + "integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==", + "dependencies": { + "detect-libc": "^2.0.0", + "https-proxy-agent": "^5.0.0", + "make-dir": "^3.1.0", + "node-fetch": "^2.6.7", + "nopt": "^5.0.0", + "npmlog": "^5.0.1", + "rimraf": "^3.0.2", + "semver": "^7.3.5", + "tar": "^6.1.11" + }, + "bin": { + "node-pre-gyp": "bin/node-pre-gyp" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/agent-base": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", + "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/make-dir": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", + "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", + "dependencies": { + "semver": "^6.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/make-dir/node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/@mapbox/node-pre-gyp/node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@mongodb-js/saslprep": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.1.0.tgz", @@ -3889,9 +3969,9 @@ } }, "node_modules/@types/jest": { - "version": "29.5.5", - "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.5.tgz", - "integrity": "sha512-ebylz2hnsWR9mYvmBFbXJXr+33UPc4+ZdxyDXh5w0FlPBTfCVN3wPL+kuOiQt3xvrK419v7XWeAs+AeOksafXg==", + "version": "29.5.12", + "resolved": "https://registry.npmjs.org/@types/jest/-/jest-29.5.12.tgz", + "integrity": "sha512-eDC8bTvT/QhYdxJAulQikueigY5AsdBRH2yDKW3yveW7svY3+DzN84/2NUgkw10RTiJbWqZrTtoGVdYlvFJdLw==", "dev": true, "dependencies": { "expect": "^29.0.0", @@ -4423,6 +4503,11 @@ "integrity": "sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==", "dev": true }, + "node_modules/abbrev": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", + "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==" + }, "node_modules/abort-controller": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", @@ -4570,7 +4655,6 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "devOptional": true, "engines": { "node": ">=8" } @@ -4607,6 +4691,37 @@ "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==" }, + "node_modules/aproba": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz", + "integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==" + }, + "node_modules/are-we-there-yet": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", + "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "delegates": "^1.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/are-we-there-yet/node_modules/readable-stream": { + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/arg": { "version": "4.1.3", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", @@ -4802,8 +4917,7 @@ "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "devOptional": true + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, "node_modules/base64-js": { "version": "1.5.1", @@ -4824,6 +4938,19 @@ } ] }, + "node_modules/bcrypt": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-5.1.1.tgz", + "integrity": "sha512-AGBHOG5hPYZ5Xl9KXzU5iKq9516yEmvCKDg3ecP5kX2aB6UqTeXZxk2ELnDgDm6BQSMlLt9rDB4LoSMx0rYwww==", + "hasInstallScript": true, + "dependencies": { + "@mapbox/node-pre-gyp": "^1.0.11", + "node-addon-api": "^5.0.0" + }, + "engines": { + "node": ">= 10.0.0" + } + }, "node_modules/big-integer": { "version": "1.6.51", "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.51.tgz", @@ -4940,7 +5067,6 @@ "version": "1.1.11", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", - "dev": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5215,6 +5341,14 @@ "fsevents": "~2.3.2" } }, + "node_modules/chownr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", + "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", + "engines": { + "node": ">=10" + } + }, "node_modules/chrome-trace-event": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz", @@ -5380,6 +5514,14 @@ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" }, + "node_modules/color-support": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", + "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", + "bin": { + "color-support": "bin.js" + } + }, "node_modules/combined-stream": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", @@ -5444,8 +5586,7 @@ "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "devOptional": true + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" }, "node_modules/concat-stream": { "version": "1.6.2", @@ -5466,6 +5607,11 @@ "resolved": "https://registry.npmjs.org/consola/-/consola-2.15.3.tgz", "integrity": "sha512-9vAdYbHj6x2fLKC4+oPH0kFzY/orMZyG2Aj+kNylHxKGJ/Ed4dpNyAQYwJOdqO4zdM7XpVHmyejQDcQHrnuXbw==" }, + "node_modules/console-control-strings": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", + "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==" + }, "node_modules/content-disposition": { "version": "0.5.4", "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", @@ -5815,6 +5961,11 @@ "node": ">=0.4.0" } }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==" + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -5832,6 +5983,14 @@ "npm": "1.2.8000 || >= 1.4.16" } }, + "node_modules/detect-libc": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz", + "integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==", + "engines": { + "node": ">=8" + } + }, "node_modules/detect-newline": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", @@ -5972,8 +6131,7 @@ "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "devOptional": true + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/encodeurl": { "version": "1.0.2", @@ -7017,6 +7175,33 @@ "node": ">=12" } }, + "node_modules/fs-minipass": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", + "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fs-minipass/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/fs-monkey": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/fs-monkey/-/fs-monkey-1.0.5.tgz", @@ -7026,8 +7211,7 @@ "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "devOptional": true + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" }, "node_modules/function-bind": { "version": "1.1.1", @@ -7040,6 +7224,26 @@ "integrity": "sha512-dsKNQNdj6xA3T+QlADDA7mOSlX0qiMINjn0cgr+eGHGsbSHzTabcIogz2+p/iqP1Xs6EP/sS2SbqH+brGTbq0g==", "optional": true }, + "node_modules/gauge": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", + "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "aproba": "^1.0.3 || ^2.0.0", + "color-support": "^1.1.2", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.1", + "object-assign": "^4.1.1", + "signal-exit": "^3.0.0", + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1", + "wide-align": "^1.1.2" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/gaxios": { "version": "6.1.1", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-6.1.1.tgz", @@ -7164,7 +7368,6 @@ "version": "7.2.3", "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "dev": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7496,6 +7699,11 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/has-unicode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", + "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==" + }, "node_modules/hexoid": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/hexoid/-/hexoid-1.0.0.tgz", @@ -7666,7 +7874,6 @@ "version": "1.0.6", "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "devOptional": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -7783,7 +7990,6 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "devOptional": true, "engines": { "node": ">=8" } @@ -9249,7 +9455,6 @@ "version": "3.1.2", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -9274,6 +9479,34 @@ "node": ">=8" } }, + "node_modules/minizlib": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", + "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", + "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/minizlib/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/mkdirp": { "version": "0.5.6", "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", @@ -9688,6 +9921,11 @@ "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==", "dev": true }, + "node_modules/node-addon-api": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-5.1.0.tgz", + "integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==" + }, "node_modules/node-emoji": { "version": "1.11.0", "resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.11.0.tgz", @@ -9736,6 +9974,20 @@ "integrity": "sha512-uYr7J37ae/ORWdZeQ1xxMJe3NtdmqMC/JZK+geofDrkLUApKRHPd18/TxtBOJ4A0/+uUIliorNrfYV6s1b02eQ==", "dev": true }, + "node_modules/nopt": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", + "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", + "dependencies": { + "abbrev": "1" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/normalize-path": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", @@ -9757,6 +10009,18 @@ "node": ">=8" } }, + "node_modules/npmlog": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", + "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", + "deprecated": "This package is no longer supported.", + "dependencies": { + "are-we-there-yet": "^2.0.0", + "console-control-strings": "^1.1.0", + "gauge": "^3.0.0", + "set-blocking": "^2.0.0" + } + }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -9797,7 +10061,6 @@ "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "devOptional": true, "dependencies": { "wrappy": "1" } @@ -9990,7 +10253,6 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "devOptional": true, "engines": { "node": ">=0.10.0" } @@ -11011,6 +11273,11 @@ "node": ">= 0.8.0" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" + }, "node_modules/setprototypeof": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", @@ -11075,8 +11342,7 @@ "node_modules/signal-exit": { "version": "3.0.7", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" }, "node_modules/sisteransi": { "version": "1.0.5", @@ -11250,7 +11516,6 @@ "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "devOptional": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -11264,7 +11529,6 @@ "version": "6.0.1", "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "devOptional": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -11422,6 +11686,22 @@ "node": ">=6" } }, + "node_modules/tar": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", + "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/tar-stream": { "version": "3.1.6", "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.1.6.tgz", @@ -11433,6 +11713,30 @@ "streamx": "^2.15.0" } }, + "node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", + "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/tar/node_modules/mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/tar/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/teeny-request": { "version": "8.0.3", "resolved": "https://registry.npmjs.org/teeny-request/-/teeny-request-8.0.3.tgz", @@ -12235,6 +12539,14 @@ "node": ">= 8" } }, + "node_modules/wide-align": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", + "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", + "dependencies": { + "string-width": "^1.0.2 || 2 || 3 || 4" + } + }, "node_modules/windows-release": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/windows-release/-/windows-release-4.0.0.tgz", @@ -12323,8 +12635,7 @@ "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "devOptional": true + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/write-file-atomic": { "version": "4.0.2", diff --git a/package.json b/package.json index ce0c292..c742077 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "weatherkids-data-api", - "version": "0.0.7", + "version": "0.2.0", "description": "", "author": "", "private": true, @@ -35,6 +35,7 @@ "@nestjs/platform-express": "^10.2.7", "@nestjs/schedule": "^4.0.0", "@nestjs/swagger": "^7.1.14", + "bcrypt": "^5.1.1", "class-transformer": "^0.5.1", "class-validator": "^0.14.0", "express": "^4.18.2", @@ -53,7 +54,7 @@ "@nestjs/testing": "^10.3.0", "@shelf/jest-mongodb": "^4.2.0", "@types/express": "^4.17.17", - "@types/jest": "^29.5.2", + "@types/jest": "^29.5.12", "@types/node": "^20.3.1", "@types/supertest": "^2.0.12", "@typescript-eslint/eslint-plugin": "^6.0.0", diff --git a/src/app.module.ts b/src/app.module.ts index 87139e5..a479142 100644 --- a/src/app.module.ts +++ b/src/app.module.ts @@ -1,19 +1,22 @@ import { AuthModule } from './modules/auth/auth.module'; import { Module } from '@nestjs/common'; +import { ConfigModule, ConfigService } from '@nestjs/config'; +import { JwtModule } from '@nestjs/jwt'; +import { MongooseModule } from '@nestjs/mongoose'; +import { ScheduleModule } from '@nestjs/schedule'; import { AppController } from './app.controller'; import { AppService } from './app.service'; -import { MongooseModule } from '@nestjs/mongoose'; -import { WeatherDataModule } from './modules/weather-data/weather-data.module'; -import { ConfigModule, ConfigService } from '@nestjs/config'; -import { WeatherStationsModule } from './modules/weather-stations/weather-stations.module'; -import { UsersModule } from './modules/users/users.module'; -import { SessionModule } from './modules/users/session/session.module'; +import { ClientsModule } from './modules/clients/clients.module'; import { GuardsModule } from './modules/common/guards/guards.module'; -import { JwtModule } from '@nestjs/jwt'; +import { KiteDataModule } from './modules/kite-data/kite-data.module'; +import { KitePlayersModule } from './modules/kite-players/kite-players.module'; import { PointsModule } from './modules/points/points.module'; -import { ScheduleModule } from '@nestjs/schedule'; +import { SessionModule } from './modules/users/session/session.module'; import { TokenModule } from './modules/users/token/token.module'; +import { UsersModule } from './modules/users/users.module'; +import { WeatherDataModule } from './modules/weather-data/weather-data.module'; +import { WeatherStationsModule } from './modules/weather-stations/weather-stations.module'; @Module({ imports: [ JwtModule.registerAsync({ @@ -36,11 +39,21 @@ import { TokenModule } from './modules/users/token/token.module'; ConfigModule.forRoot({ envFilePath: ['.env.local', '.env.dev', '.env.prod'], }), - MongooseModule.forRoot(process.env.MONGO_URL), + MongooseModule.forRootAsync({ + imports: [ConfigModule], + useFactory: async (configService: ConfigService) => { + return { + uri: configService.get('MONGO_URL'), + }; + }, + inject: [ConfigService], + }), WeatherDataModule, WeatherStationsModule, PointsModule, - + ClientsModule, + KitePlayersModule, + KiteDataModule, ScheduleModule.forRoot(), ], controllers: [AppController], diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.ts index c85aa29..b2adb5c 100644 --- a/src/modules/auth/auth.controller.ts +++ b/src/modules/auth/auth.controller.ts @@ -1,4 +1,11 @@ -import { Body, Controller, Post, UnauthorizedException } from '@nestjs/common'; +import { + BadRequestException, + Body, + Controller, + Headers, + Post, + UnauthorizedException, +} from '@nestjs/common'; import { AuthService } from './auth.service'; @Controller('auth') @@ -15,4 +22,31 @@ export class AuthController { throw new UnauthorizedException(); } } + + @Post('token') + async getAuthToken( + @Body() + body: { + grant_type: string; + client_id: string; + client_secret: string; + }, + ) { + const { grant_type, client_id, client_secret } = body; + + if (grant_type !== 'client_credentials') { + throw new BadRequestException('Unsupported grant type'); + } + + return this.authService.authenticateClient(client_id, client_secret); + } + + @Post('refresh-token') + async reissueAuthToken(@Headers('authorization') refreshToken: string) { + try { + return this.authService.refreshClientToken(refreshToken); + } catch (error) { + console.error('reissueAuthToken', error); + } + } } diff --git a/src/modules/auth/auth.module.ts b/src/modules/auth/auth.module.ts index 258c117..7db2529 100644 --- a/src/modules/auth/auth.module.ts +++ b/src/modules/auth/auth.module.ts @@ -3,9 +3,12 @@ import { UsersModule } from '../users/users.module'; import { AuthService } from './auth.service'; import { Module } from '@nestjs/common'; import { OAuth2Client } from 'google-auth-library'; +import { ClientsModule } from '../clients/clients.module'; +import { TokenModule } from '../users/token/token.module'; +import { WeatherStationsModule } from '../weather-stations/weather-stations.module'; @Module({ - imports: [UsersModule], + imports: [UsersModule, ClientsModule, TokenModule, WeatherStationsModule], controllers: [AuthController], providers: [AuthService, OAuth2Client], }) diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts index 4183195..6677ff1 100644 --- a/src/modules/auth/auth.service.ts +++ b/src/modules/auth/auth.service.ts @@ -1,12 +1,19 @@ import { Injectable, UnauthorizedException } from '@nestjs/common'; import { UsersService } from '../users/users.service'; import { OAuth2Client } from 'google-auth-library'; +import { ClientsService } from '../clients/clients.service'; +import { TokenService } from '../users/token/token.service'; +import { IGenClientKey } from '../common/interfaces/gen-client-key.interface'; +import { WeatherStationsService } from '../weather-stations/weather-stations.service'; @Injectable() export class AuthService { constructor( private readonly userService: UsersService, private readonly oAuth2Client: OAuth2Client, + private readonly clientService: ClientsService, + private readonly tokenService: TokenService, + private readonly weatherStationsService: WeatherStationsService, ) {} async authenticateWithGoogle(idToken: string) { @@ -37,4 +44,47 @@ export class AuthService { throw new UnauthorizedException(); } } + + async authenticateClient(clientId: string, clientSecret: string) { + if ( + !(await this.clientService.validateClientCredentials( + clientId, + clientSecret, + )) + ) { + throw new UnauthorizedException('Invalid client credentials'); + } + return this.issueClientAuthToken(clientId); + } + + async refreshClientToken(refreshToken: string) { + const payload = await this.tokenService.verifyRefreshToken(refreshToken); + return this.issueClientAuthToken(payload?.sub); + } + + private async issueClientAuthToken(clientId: string) { + const payload: IGenClientKey['payload'] = {}; + try { + const station = await this.weatherStationsService.findByClient(clientId); + if (station) { + payload.weather_station_id = station.id; + } + } catch (error) {} + const accessToken = await this.tokenService.generateClientAccessToken({ + payload, + subject: clientId, + expiresIn: '1y', + }); + const refreshToken = await this.tokenService.generateRefreshToken({ + payload, + subject: clientId, + }); + + return { + access_token: accessToken, + token_type: 'Bearer', + refresh_token: refreshToken, + expires_in: new Date(new Date().getTime() + 86400000), // in 1 day + }; + } } diff --git a/src/modules/clients/clients.controller.spec.ts b/src/modules/clients/clients.controller.spec.ts new file mode 100644 index 0000000..b9ee8d2 --- /dev/null +++ b/src/modules/clients/clients.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { ClientsController } from './clients.controller'; + +describe('ClientsController', () => { + let controller: ClientsController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [ClientsController], + }).compile(); + + controller = module.get(ClientsController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/modules/clients/clients.controller.ts b/src/modules/clients/clients.controller.ts new file mode 100644 index 0000000..6768939 --- /dev/null +++ b/src/modules/clients/clients.controller.ts @@ -0,0 +1,15 @@ +import { Body, Controller, Post, UseGuards } from '@nestjs/common'; +import { CreateClientDto } from './dto/create-client.dto'; +import { ClientsService } from './clients.service'; +import { ValidateAdminUserGuard } from '../common/guards/admin-user.guard'; + +@Controller('clients') +export class ClientsController { + constructor(private readonly clientService: ClientsService) {} + + @UseGuards(ValidateAdminUserGuard) + @Post() + create(@Body() createClientDto: CreateClientDto) { + return this.clientService.create(createClientDto); + } +} diff --git a/src/modules/clients/clients.module.ts b/src/modules/clients/clients.module.ts new file mode 100644 index 0000000..bdaa1cf --- /dev/null +++ b/src/modules/clients/clients.module.ts @@ -0,0 +1,17 @@ +import { Module } from '@nestjs/common'; +import { ClientsService } from './clients.service'; +import { MongooseModule } from '@nestjs/mongoose'; +import { Client, ClientSchema } from './entities/client.entity'; +import { ClientsController } from './clients.controller'; +import { TokenModule } from '../users/token/token.module'; + +@Module({ + imports: [ + MongooseModule.forFeature([{ name: Client.name, schema: ClientSchema }]), + TokenModule, // for api guards + ], + providers: [ClientsService], + exports: [ClientsService], + controllers: [ClientsController], +}) +export class ClientsModule {} diff --git a/src/modules/clients/clients.service.spec.ts b/src/modules/clients/clients.service.spec.ts new file mode 100644 index 0000000..9dbc773 --- /dev/null +++ b/src/modules/clients/clients.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { ClientsService } from './clients.service'; + +describe('ClientsService', () => { + let service: ClientsService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [ClientsService], + }).compile(); + + service = module.get(ClientsService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/modules/clients/clients.service.ts b/src/modules/clients/clients.service.ts new file mode 100644 index 0000000..1407336 --- /dev/null +++ b/src/modules/clients/clients.service.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@nestjs/common'; +import { InjectModel } from '@nestjs/mongoose'; +import { Client, ClientDocument } from './entities/client.entity'; +import { Model } from 'mongoose'; +import { CreateClientDto } from './dto/create-client.dto'; +import { v4 as uuidv4 } from 'uuid'; +import * as bcrypt from 'bcrypt'; + +@Injectable() +export class ClientsService { + constructor( + @InjectModel(Client.name) + private readonly clientModel: Model, + ) {} + + async create(dto: CreateClientDto) { + const secret = await bcrypt.hash(dto.client_secret, 10); + const newClient = new this.clientModel({ + ...dto, + _id: uuidv4(), + is_active: true, + client_secret: secret, + }); + await newClient.save(); + return true; + } + + async validateClientCredentials(clientId: string, clientSecret: string) { + const client = await this.clientModel.findById(clientId); + if (!client) { + return false; + } + return bcrypt.compare(clientSecret, client.client_secret); + } +} diff --git a/src/modules/clients/dto/create-client.dto.ts b/src/modules/clients/dto/create-client.dto.ts new file mode 100644 index 0000000..a714a91 --- /dev/null +++ b/src/modules/clients/dto/create-client.dto.ts @@ -0,0 +1,5 @@ +export class CreateClientDto { + readonly client_secret: string; + readonly type: string; + readonly scopes: string[]; +} diff --git a/src/modules/clients/entities/client.entity.ts b/src/modules/clients/entities/client.entity.ts new file mode 100644 index 0000000..1527dd8 --- /dev/null +++ b/src/modules/clients/entities/client.entity.ts @@ -0,0 +1,25 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; + +@Schema({ + timestamps: true, + collection: 'clients', +}) +export class Client { + @Prop({ type: String }) + _id: string; + + @Prop({ type: String }) + type: string; + + @Prop({ type: String }) + client_secret: string; + + @Prop({ type: Boolean, default: true }) + is_active: boolean; + + @Prop({ type: Array }) + scopes: string[]; +} + +export type ClientDocument = Client & Document; +export const ClientSchema = SchemaFactory.createForClass(Client); diff --git a/src/modules/common/guards/gavesha-client.guard.ts b/src/modules/common/guards/gavesha-client.guard.ts index 6dd580a..b3acc7b 100644 --- a/src/modules/common/guards/gavesha-client.guard.ts +++ b/src/modules/common/guards/gavesha-client.guard.ts @@ -1,8 +1,8 @@ import { - Injectable, CanActivate, ExecutionContext, HttpException, + Injectable, } from '@nestjs/common'; import { TokenService } from '../../users/token/token.service'; @@ -13,6 +13,19 @@ export class ValidateGaveshaClientGuard implements CanActivate { // This guard will protect the routes that require a Gavesha client such as the Gavesha mobile app. async canActivate(context: ExecutionContext): Promise { const request = context.switchToHttp().getRequest(); + + const authHeader = request.headers['authorization']; + if (authHeader) { + const jwtpaylod = + await this.tokenService.validateClientAccessToken(authHeader); + if (!jwtpaylod.iss.endsWith('access')) { + return false; + } + request.clientId = jwtpaylod.sub; + request.weatherStationId = jwtpaylod.weather_station_id; + return true; + } + const header = request.headers['client-id']; if (header) { if (this.tokenService.validateMobileClientId(header)) { @@ -20,7 +33,7 @@ export class ValidateGaveshaClientGuard implements CanActivate { } else if (this.tokenService.validateComClientId(header)) { return true; } else { - console.error('Error validating client: ', header); + console.error('Error validating client-id header: ', header); throw new HttpException('Invalid header Client Id', 401); } } else if (request.body?.client_id) { @@ -30,7 +43,7 @@ export class ValidateGaveshaClientGuard implements CanActivate { } else if (this.tokenService.validateComClientId(param)) { return true; } else { - console.error('Error validating client: ', param); + console.error('Error validating client-id param: ', param); throw new HttpException('Invalid body Client Id', 401); } } else { diff --git a/src/modules/common/guards/gavesha-user.guard.ts b/src/modules/common/guards/gavesha-user.guard.ts index a665704..aacea63 100644 --- a/src/modules/common/guards/gavesha-user.guard.ts +++ b/src/modules/common/guards/gavesha-user.guard.ts @@ -26,7 +26,7 @@ export class ValidateGaveshaUserGuard implements CanActivate { await this.tokenService.validateGaveshaUserApiKey(apikey); return true; } catch (error) { - console.error('Error validating admin user', error); + console.error('Error validating user', error); throw new HttpException(error, 401); } } diff --git a/src/modules/common/interfaces/gen-client-key.interface.ts b/src/modules/common/interfaces/gen-client-key.interface.ts new file mode 100644 index 0000000..6946742 --- /dev/null +++ b/src/modules/common/interfaces/gen-client-key.interface.ts @@ -0,0 +1,9 @@ +export interface IGenClientKey { + payload: { + // client_id: string; + type?: string; + weather_station_id?: string; + }; + expiresIn?: string; + subject: string; +} diff --git a/src/modules/kite-data/dto/bulk-create-kite-data-response.dto.ts b/src/modules/kite-data/dto/bulk-create-kite-data-response.dto.ts new file mode 100644 index 0000000..44b8fa7 --- /dev/null +++ b/src/modules/kite-data/dto/bulk-create-kite-data-response.dto.ts @@ -0,0 +1,6 @@ +export class BulkCreateKiteDataResponseDto { + readonly _id: string; + readonly timestamp: Date; + readonly timestamp_iso: string; + readonly created_at: Date; +} diff --git a/src/modules/kite-data/dto/create-bulk-kite-data.dto.ts b/src/modules/kite-data/dto/create-bulk-kite-data.dto.ts new file mode 100644 index 0000000..96db044 --- /dev/null +++ b/src/modules/kite-data/dto/create-bulk-kite-data.dto.ts @@ -0,0 +1,39 @@ +import { Type } from 'class-transformer'; +import { + ArrayNotEmpty, + IsArray, + IsNotEmpty, + IsOptional, + ValidateNested, +} from 'class-validator'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; +import { KiteDataPoint } from './kite-datapoint.dto'; + +export class CreateBulkKiteDataDto { + @IsNotEmpty() + readonly author_user_id: string; + + @IsNotEmpty() + readonly kite_player_id: string; + + @IsNotEmpty() + readonly coordinates: ICoordinates; + + @IsArray() + @ArrayNotEmpty() + @ValidateNested({ each: true }) + @Type(() => KiteDataPoint) + readonly data: KiteDataPoint[]; + + @IsOptional() + readonly gavesha_user_api_key?: string; + + @IsOptional() + readonly client_id?: string; + + @IsOptional() + readonly sensor_id?: string; + + @IsOptional() + readonly attempt_timestamp?: Date; +} diff --git a/src/modules/kite-data/dto/get-kite-datum.dto.ts b/src/modules/kite-data/dto/get-kite-datum.dto.ts new file mode 100644 index 0000000..02ceb2f --- /dev/null +++ b/src/modules/kite-data/dto/get-kite-datum.dto.ts @@ -0,0 +1,31 @@ +import { Prop } from '@nestjs/mongoose'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; + +export class GetKiteDatumDto { + @Prop() + readonly _id: string; + + @Prop() + readonly author_user_id: string; + + @Prop() + readonly timestamp: Date; + + @Prop() + readonly kite_player_id: string; + + @Prop() + readonly coordinates: ICoordinates; + + @Prop() + readonly temperature: number; + + @Prop() + readonly pressure: number; + + @Prop() + readonly altitude: number; + + @Prop() + readonly sensor_id: string; +} diff --git a/src/modules/kite-data/dto/kite-datapoint.dto.ts b/src/modules/kite-data/dto/kite-datapoint.dto.ts new file mode 100644 index 0000000..961e402 --- /dev/null +++ b/src/modules/kite-data/dto/kite-datapoint.dto.ts @@ -0,0 +1,24 @@ +import { Prop } from '@nestjs/mongoose'; +import { IsOptional } from 'class-validator'; + +export class KiteDataPoint { + @IsOptional() + @Prop() + timestamp: number; + + @IsOptional() + @Prop() + timestamp_iso: string; + + @IsOptional() + @Prop() + temperature: number; + + @IsOptional() + @Prop() + pressure: number; + + @IsOptional() + @Prop() + altitude: number; +} diff --git a/src/modules/kite-data/entities/kite-datum-entity.ts b/src/modules/kite-data/entities/kite-datum-entity.ts new file mode 100644 index 0000000..e864e41 --- /dev/null +++ b/src/modules/kite-data/entities/kite-datum-entity.ts @@ -0,0 +1,38 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { v4 as uuidv4 } from 'uuid'; +import { + KiteDataMetaData, + KiteDataMetadataSchema, +} from '../schema/kitedata-metadata.schema'; + +@Schema({ + timestamps: true, + collection: 'kite_data', + timeseries: { + timeField: 'timestamp', + metaField: 'metadata', + granularity: 'minutes', + }, +}) +export class KiteDatum { + @Prop({ type: String, default: uuidv4 }) + _id: string; + + @Prop({ type: Date }) + timestamp: Date; + + @Prop({ type: KiteDataMetadataSchema }) + metadata: KiteDataMetaData; + + @Prop() + temperature: number; + + @Prop() + pressure: number; + + @Prop() + altitude: number; +} + +export type KiteDatumDocument = KiteDatum & Document; +export const KiteDatumSchema = SchemaFactory.createForClass(KiteDatum); diff --git a/src/modules/kite-data/kite-data.controller.spec.ts b/src/modules/kite-data/kite-data.controller.spec.ts new file mode 100644 index 0000000..88cdc18 --- /dev/null +++ b/src/modules/kite-data/kite-data.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { KiteDataController } from './kite-data.controller'; + +describe('KiteDataController', () => { + let controller: KiteDataController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [KiteDataController], + }).compile(); + + controller = module.get(KiteDataController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/modules/kite-data/kite-data.controller.ts b/src/modules/kite-data/kite-data.controller.ts new file mode 100644 index 0000000..f7be374 --- /dev/null +++ b/src/modules/kite-data/kite-data.controller.ts @@ -0,0 +1,84 @@ +import { + BadRequestException, + Body, + Controller, + Get, + Param, + ParseUUIDPipe, + Post, + Query, + UseGuards, + UsePipes, + ValidationPipe, +} from '@nestjs/common'; +import { ApiTags } from '@nestjs/swagger'; +import { ValidateGaveshaClientGuard } from '../common/guards/gavesha-client.guard'; +import { ValidateGaveshaUserGuard } from '../common/guards/gavesha-user.guard'; +import { KitePlayersService } from '../kite-players/kite-players.service'; +import { BulkCreateKiteDataResponseDto } from './dto/bulk-create-kite-data-response.dto'; +import { CreateBulkKiteDataDto } from './dto/create-bulk-kite-data.dto'; +import { KiteDataService } from './kite-data.service'; + +@Controller('kite-data') +@ApiTags('kite-data') +export class KiteDataController { + constructor( + private readonly kiteDataService: KiteDataService, + private readonly kitePlayerService: KitePlayersService, + ) {} + + @UseGuards(ValidateGaveshaClientGuard, ValidateGaveshaUserGuard) + @Post('bulk') + @UsePipes( + new ValidationPipe({ + transform: true, + whitelist: true, + forbidNonWhitelisted: true, + exceptionFactory: (errors) => new BadRequestException(errors), + }), + ) + async bulkCommit( + @Body() createBulkKiteData: CreateBulkKiteDataDto, + ): Promise { + const res = await this.kiteDataService.bulkCommit(createBulkKiteData); + console.info( + res.length, + 'data committed to player', + createBulkKiteData.kite_player_id, + ); + return res; + } + + @Get('latest') + async findLatestByAllKitePlayers( + @Query('include') include?: string, + ): Promise { + const includeCurrentWeek = include === 'current_week'; + return await this.kiteDataService.findLatestByAllKitePlayers( + includeCurrentWeek, + ); + } + + @Get('latest/:kite_player_id') + async findLatestByKitePlayerId( + @Param('kite_player_id', new ParseUUIDPipe({ version: '4' })) + kitePlayerId: string, + @Query('include') include?: string, + ) { + const includeCurrentWeek = include === 'current_week'; + const kiteData = await this.kiteDataService.findLatestByKitePlayerId( + kitePlayerId, + includeCurrentWeek, + ); + + if (!kiteData) { + return { flying_mins: null, max_height: null, total_attempts: null }; + } + return kiteData; + } + + @Get('players-leaderboard') + async getPlayersLeaderBoard() { + return await this.kiteDataService.getPlayersLeaderBoard(); + } +} diff --git a/src/modules/kite-data/kite-data.module.ts b/src/modules/kite-data/kite-data.module.ts new file mode 100644 index 0000000..230479a --- /dev/null +++ b/src/modules/kite-data/kite-data.module.ts @@ -0,0 +1,21 @@ +import { forwardRef, Module } from '@nestjs/common'; +import { MongooseModule } from '@nestjs/mongoose'; +import { KitePlayersModule } from '../kite-players/kite-players.module'; +import { TokenModule } from '../users/token/token.module'; +import { KiteDatum, KiteDatumSchema } from './entities/kite-datum-entity'; +import { KiteDataController } from './kite-data.controller'; +import { KiteDataService } from './kite-data.service'; + +@Module({ + imports: [ + MongooseModule.forFeature([ + { name: KiteDatum.name, schema: KiteDatumSchema }, + ]), + TokenModule, + forwardRef(() => KitePlayersModule), + ], + controllers: [KiteDataController], + providers: [KiteDataService, KiteDatum], + exports: [KiteDataService], +}) +export class KiteDataModule {} diff --git a/src/modules/kite-data/kite-data.service.spec.ts b/src/modules/kite-data/kite-data.service.spec.ts new file mode 100644 index 0000000..994046e --- /dev/null +++ b/src/modules/kite-data/kite-data.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { KiteDataService } from './kite-data.service'; + +describe('KiteDataService', () => { + let service: KiteDataService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [KiteDataService], + }).compile(); + + service = module.get(KiteDataService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/modules/kite-data/kite-data.service.ts b/src/modules/kite-data/kite-data.service.ts new file mode 100644 index 0000000..b921641 --- /dev/null +++ b/src/modules/kite-data/kite-data.service.ts @@ -0,0 +1,1208 @@ +import { BadRequestException, Injectable } from '@nestjs/common'; +import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import * as moment from 'moment'; +import { Connection, Model } from 'mongoose'; +import { BulkCreateKiteDataResponseDto } from './dto/bulk-create-kite-data-response.dto'; +import { CreateBulkKiteDataDto } from './dto/create-bulk-kite-data.dto'; +import { KiteDataPoint } from './dto/kite-datapoint.dto'; +import { KiteDatum, KiteDatumDocument } from './entities/kite-datum-entity'; +import { KiteDataMetaData } from './schema/kitedata-metadata.schema'; + +@Injectable() +export class KiteDataService { + constructor( + @InjectModel(KiteDatum.name) + private readonly kiteDatumModel: Model, + + @InjectConnection() private readonly mongoConnection: Connection, + ) {} + + async bulkCommit( + createBulkKiteData: CreateBulkKiteDataDto, + ): Promise { + // Restructure the data to include the author_user_id, weather_station_id, metadata, coordinates. + const { + author_user_id, + kite_player_id, + coordinates, + sensor_id, + data, + attempt_timestamp, + } = createBulkKiteData; + + for (let i = 0; i < data.length; i++) { + const element = data[i]; + if (!element.timestamp) { + if (!element.timestamp_iso) { + throw new BadRequestException('Invalid data'); + } + element.timestamp = new Date(element.timestamp_iso).getTime(); + } + } + + let filteredKiteDataPoints: KiteDataPoint[] = []; + let insertedKiteData = []; + let existingKiteData = []; + + existingKiteData = await this.kiteDatumModel + .find({ + timestamp: { + $in: data.map((datum) => datum.timestamp), + }, + 'metadata.author_user_id': author_user_id, + }) + .exec(); + + try { + const currentUtcTimestamp = new Date().getTime(); // Get current UTC timestamp + + filteredKiteDataPoints = data.filter((datum) => { + const datumDate = new Date(datum.timestamp); // Convert timestamp to Date object + return ( + datumDate.getTime() <= currentUtcTimestamp + 86400000 && // Check if the timestamp is not in the future + !existingKiteData.some( + (existingDatum) => + existingDatum.timestamp.getTime() === datumDate.getTime(), + ) + ); + }); + + const populatedKiteData = filteredKiteDataPoints.map((dataPoint) => { + return { + ...dataPoint, + metadata: { + author_user_id: author_user_id, + kite_player_id: kite_player_id, + coordinates: coordinates, + attempt_timestamp: attempt_timestamp, + sensor_id: sensor_id || '', + } as KiteDataMetaData, + }; + }); + + insertedKiteData = + await this.kiteDatumModel.insertMany(populatedKiteData); + + // Hacky checks to check if the data was inserted. + if ( + !insertedKiteData || + insertedKiteData.length !== populatedKiteData.length + ) { + throw new Error('Error inserting kite data'); + } + } catch (error) { + // Handle any errors that occur during the insertion of time-series data. + throw error; + } + + const responseKiteData = [...insertedKiteData, ...existingKiteData]; + + const finalKiteResponse = responseKiteData.map((datum) => { + return { + _id: datum._id, + timestamp: datum.timestamp, + timestamp_iso: moment(datum.timestamp).toISOString(true), + created_at: datum.createdAt, + } as BulkCreateKiteDataResponseDto; + }); + return finalKiteResponse; + } + + async findLatestByKitePlayerId(kitePlayerId: string, includeCurrentWeek: boolean = false): Promise { + try { + const [ + allTimeTotalHeight, + allTimeTotalAttempts, + allTimeTotalFlyingMins + ] = await Promise.all([ + this.getMaxHeightByKitePlayerId(kitePlayerId), + this.getTotalAttemptsByKitePlayerId(kitePlayerId), + this.getFlyingMinsByKitePlayerId(kitePlayerId) + ]); + + let currentWeekData = {}; + if (includeCurrentWeek) { + const [ + currentWeekTotalHeight, + currentWeekTotalAttempts, + currentWeekTotalFlyingMins, + currentWeekMaxHeight, + currentWeekMinHeight + ] = await Promise.all([ + this.getTotalHeightForCurrentWeekByPlayerId(kitePlayerId), + this.getTotalAttemptsForCurrentWeekByPlayerId(kitePlayerId), + this.getTotalFlyingMinsForCurrentWeekByPlayerId(kitePlayerId), + this.getMaxHeightForCurrentWeekByPlayerId(kitePlayerId), + this.getMinHeightForCurrentWeekByPlayerId(kitePlayerId) + ]); + + currentWeekData = { + current_week: { + total_height: currentWeekTotalHeight, + total_attempts: currentWeekTotalAttempts, + total_flying_mins: currentWeekTotalFlyingMins, + max_height: currentWeekMaxHeight, + min_height: currentWeekMinHeight, + } + }; + } + + return { + all_time: { + total_height: allTimeTotalHeight, + total_attempts: allTimeTotalAttempts, + total_flying_mins: allTimeTotalFlyingMins, + }, + ...currentWeekData, + }; + } catch (error) { + console.error("Error in findLatestByKitePlayerId:", error); + throw error; + } + } + + async findLatestByAllKitePlayers(includeCurrentWeek: boolean = false): Promise { + try { + const [totalHeight, totalAttempts, totalFlyingMins] = await Promise.all([ + this.getTotalHeightByAllKitePlayers(), + this.getTotalAttemptsByAllKitePlayers(), + this.getTotalFlyingMinsByAllKitePlayers(), + ]); + + let currentWeekData = {}; + if (includeCurrentWeek) { + const [ + currentWeekTotalHeight, + currentWeekTotalAttempts, + currentWeekTotalFlyingMins, + currentWeekMaxHeight, + currentWeekMinHeight + ] = await Promise.all([ + this.getTotalHeightForCurrentWeek(), + this.getTotalAttemptsForCurrentWeek(), + this.getTotalFlyingMinsForCurrentWeek(), + this.getMaxHeightForCurrentWeek(), + this.getMinHeightForCurrentWeek(), + ]); + + currentWeekData = { + current_week: { + total_height: currentWeekTotalHeight, + total_attempts: currentWeekTotalAttempts, + total_flying_mins: currentWeekTotalFlyingMins, + max_height: currentWeekMaxHeight, + min_height: currentWeekMinHeight, + } + }; + } + + return { + all_time: { + total_height: totalHeight, + total_attempts: totalAttempts, + total_flying_mins: totalFlyingMins, + }, + ...currentWeekData, + }; + } catch (error) { + console.error("Error in findLatestByAllKitePlayers:", error); + throw error; + } + } + + async getPlayersLeaderBoard() { + const aggregationPipeline: any[] = [ + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + kite_height: { $max: { $subtract: ["$max_altitude", "$min_altitude"] } } + } + }, + { + $sort: { kite_height: -1 } + }, + { + $lookup: { + from: "kite_players", + localField: "_id", + foreignField: "_id", + as: "player_details" + } + }, + { + $unwind: { + path: "$player_details", + preserveNullAndEmptyArrays: true + } + }, + { + $project: { + _id: 0, + id: "$_id", + name: "$player_details.name", + city: "$player_details.city", + img_url: "$player_details.img_url", + kite_height: 1, + } + }, + { + $limit: 10 + } + ]; + + return await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + } + + async getTotalHeightByAllKitePlayers(): Promise { + const aggregationPipeline: any[] = [ + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + } + }, + { + $addFields: { + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + total_height: { $sum: "$height" } + } + }, + { + $group: { + _id: null, + total_height: { $sum: "$total_height" } + } + }, + { + $project: { + _id: 0, + total_height: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_height : 0; + } + + async getTotalAttemptsByAllKitePlayers(): Promise { + const aggregationPipeline: any[] = [ + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + count_attempt_timestamp: { $sum: 1 } + } + }, + { + $group: { + _id: null, + total_attempts: { $sum: "$count_attempt_timestamp" } + } + }, + { + $project: { + _id: 0, + total_attempts: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_attempts : 0; + } + + async getTotalFlyingMinsByAllKitePlayers(): Promise { + const aggregationPipeline: any[] = [ + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + data: { + $push: { + timestamp: "$timestamp", + altitude: "$altitude" + } + }, + min_altitude: { $min: "$altitude" } + } + }, + { + $addFields: { + filteredData: { + $filter: { + input: "$data", + as: "entry", + cond: { $gte: ["$$entry.altitude", { $add: ["$min_altitude", 10] }] } + } + } + } + }, + { + $addFields: { + minTimestamp: { $min: "$filteredData.timestamp" }, + maxTimestamp: { $max: "$filteredData.timestamp" } + } + }, + { + $addFields: { + timestampDifference: { + $divide: [ + { $subtract: ["$maxTimestamp", "$minTimestamp"] }, + 60000 + ] + } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + flying_mins: { $sum: "$timestampDifference" }, + timestampDifferences: { $push: "$timestampDifference" }, + attempt_timestamp: { $first: "$_id.attempt_timestamp" } + } + }, + { + $group: { + _id: null, + total_flying_mins: { $sum: "$flying_mins" } + } + }, + { + $project: { + _id: 0, + total_flying_mins: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_flying_mins : 0; + } + + async getFlyingMinsByKitePlayerId(kitePlayerId:string): Promise { + const aggregationPipeline: any[] = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId + } + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + data: { + $push: { + timestamp: "$timestamp", + altitude: "$altitude" + } + }, + min_altitude: { $min: "$altitude" } + } + }, + { + $addFields: { + filteredData: { + $filter: { + input: "$data", + as: "entry", + cond: { $gte: ["$$entry.altitude", { $add: ["$min_altitude", 10] }] } + } + } + } + }, + { + $addFields: { + minTimestamp: { + $min: "$filteredData.timestamp" + }, + maxTimestamp: { + $max: "$filteredData.timestamp" + } + } + }, + { + $addFields: { + timestampDifference: { + $divide: [ + { $subtract: ["$maxTimestamp", "$minTimestamp"] }, + 60000 + ] + } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + flying_mins: { $sum: "$timestampDifference" }, + timestampDifferences: { $push: "$timestampDifference" }, + attempt_timestamp: { $first: "$_id.attempt_timestamp" } + } + }, + { + $project: { + _id: 0, + kite_player_id: "$_id", + flying_mins: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].flying_mins : 0; + } + + async getMaxHeightByKitePlayerId(kitePlayerId: string): Promise{ + const aggregationPipeline: any[] = [ + { + $match:{ + "metadata.kite_player_id": kitePlayerId + } + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + max_height: { $max: { $subtract: ["$max_altitude", "$min_altitude"] } } + } + }, + { + $project: { + max_height: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length>0 ? result[0].max_height : 0; + } + + async getTotalAttemptsByKitePlayerId(kitePlayerId: string): Promise { + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId + } + }, + { + $group: { + _id: { + attempt_timestamp: "$metadata.attempt_timestamp" + } + } + }, + { + $group: { + _id: null, + attempts: { $sum: 1 } + } + }, + { + $project: { + _id: 0, + attempts: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].attempts : 0; + } + + async getTotalAttemptsForCurrentWeek(): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $project: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + }, + { + $group: { + _id: "$kite_player_id", + unique_attempts: { $addToSet: "$attempt_timestamp" }, + }, + }, + { + $project: { + _id: 0, + kite_player_id: "$_id", + unique_attempts_count: { $size: "$unique_attempts" }, + }, + }, + { + $group: { + _id: null, + total_attempts_for_week: { $sum: "$unique_attempts_count" }, + }, + }, + { + $project: { + _id: 0, + total_attempts_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_attempts_for_week : 0; + } catch (error) { + console.error("Error in getTotalAttemptsForCurrentWeek:", error); + throw error; + } + } + + async getMaxHeightForCurrentWeek(): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + max_height: { $max: { $subtract: ["$max_altitude", "$min_altitude"] } } + }, + }, + { + $group: { + _id: null, + max_height_for_week: { $max: "$max_height" } + }, + }, + { + $project: { + _id: 0, + max_height_for_week: 1 + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].max_height_for_week : 0; + } catch (error) { + console.error("Error in getMaxHeightForCurrentWeek:", error); + throw error; + } + } + + async getMinHeightForCurrentWeek(): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + min_height: { $min: { $subtract: ["$max_altitude", "$min_altitude"] } } + }, + }, + { + $group: { + _id: null, + min_height_for_week: { $min: "$min_height" } + }, + }, + { + $project: { + _id: 0, + min_height_for_week: 1 + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].min_height_for_week : 0; + } catch (error) { + console.error("Error in getMinHeightForCurrentWeek:", error); + throw error; + } + } + + async getTotalFlyingMinsForCurrentWeek(): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + data: { + $push: { + timestamp: "$timestamp", + altitude: "$altitude" + } + }, + min_altitude: { $min: "$altitude" } + }, + }, + { + $addFields: { + filteredData: { + $filter: { + input: "$data", + as: "entry", + cond: { $gte: ["$$entry.altitude", { $add: ["$min_altitude", 10] }] } + } + } + } + }, + { + $addFields: { + minTimestamp: { $min: "$filteredData.timestamp" }, + maxTimestamp: { $max: "$filteredData.timestamp" } + } + }, + { + $addFields: { + timestampDifference: { + $divide: [ + { $subtract: ["$maxTimestamp", "$minTimestamp"] }, + 60000 // Convert milliseconds to minutes + ] + } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + flying_mins: { $sum: "$timestampDifference" }, + timestampDifferences: { $push: "$timestampDifference" }, + attempt_timestamp: { $first: "$_id.attempt_timestamp" } + } + }, + { + $group: { + _id: null, + total_flying_mins_for_week: { $sum: "$flying_mins" } + } + }, + { + $project: { + _id: 0, + total_flying_mins_for_week: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_flying_mins_for_week : 0; + } catch (error) { + console.error("Error in getTotalFlyingMinutesForCurrentWeek:", error); + throw error; + } + } + + async getTotalHeightForCurrentWeek(): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp" + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" } + }, + }, + { + $addFields: { + height: { $subtract: ["$max_altitude", "$min_altitude"] } + } + }, + { + $group: { + _id: "$_id.kite_player_id", + total_height: { $sum: "$height" } + } + }, + { + $group: { + _id: null, + total_height_for_week: { $sum: "$total_height" } + } + }, + { + $project: { + _id: 0, + total_height_for_week: 1 + } + } + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_height_for_week : 0; + } catch (error) { + console.error("Error in getTotalHeightForCurrentWeek:", error); + throw error; + } + } + + async getTotalAttemptsForCurrentWeekByPlayerId(kitePlayerId: string): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId, + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $project: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + }, + { + $group: { + _id: "$kite_player_id", + unique_attempts: { $addToSet: "$attempt_timestamp" }, + }, + }, + { + $project: { + _id: 0, + kite_player_id: "$_id", + unique_attempts_count: { $size: "$unique_attempts" }, + }, + }, + { + $group: { + _id: null, + total_attempts_for_week: { $sum: "$unique_attempts_count" }, + }, + }, + { + $project: { + _id: 0, + total_attempts_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_attempts_for_week : 0; + } catch (error) { + console.error("Error in getTotalAttemptsForCurrentWeek:", error); + throw error; + } + } + + async getMaxHeightForCurrentWeekByPlayerId(kitePlayerId: string): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId, + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" }, + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] }, + }, + }, + max_height: { $max: { $subtract: ["$max_altitude", "$min_altitude"] } }, + }, + }, + { + $group: { + _id: null, + max_height_for_week: { $max: "$max_height" }, + }, + }, + { + $project: { + _id: 0, + max_height_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].max_height_for_week : 0; + } catch (error) { + console.error("Error in getMaxHeightForCurrentWeek:", error); + throw error; + } + } + + async getMinHeightForCurrentWeekByPlayerId(kitePlayerId: string): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId, + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" }, + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + attempts: { + $push: { + attempt_timestamp: "$_id.attempt_timestamp", + maxAltitude: "$max_altitude", + minAltitude: "$min_altitude", + height: { $subtract: ["$max_altitude", "$min_altitude"] }, + }, + }, + min_height: { $min: { $subtract: ["$max_altitude", "$min_altitude"] } }, + }, + }, + { + $group: { + _id: null, + min_height_for_week: { $min: "$min_height" }, + }, + }, + { + $project: { + _id: 0, + min_height_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].min_height_for_week : 0; + } catch (error) { + console.error("Error in getMinHeightForCurrentWeek:", error); + throw error; + } + } + + async getTotalFlyingMinsForCurrentWeekByPlayerId(kitePlayerId: string): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId, + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + data: { + $push: { + timestamp: "$timestamp", + altitude: "$altitude", + }, + }, + min_altitude: { $min: "$altitude" }, + }, + }, + { + $addFields: { + filteredData: { + $filter: { + input: "$data", + as: "entry", + cond: { $gte: ["$$entry.altitude", { $add: ["$min_altitude", 10] }] }, + }, + }, + }, + }, + { + $addFields: { + minTimestamp: { $min: "$filteredData.timestamp" }, + maxTimestamp: { $max: "$filteredData.timestamp" }, + }, + }, + { + $addFields: { + timestampDifference: { + $divide: [ + { $subtract: ["$maxTimestamp", "$minTimestamp"] }, + 60000, // Convert milliseconds to minutes + ], + }, + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + flying_mins: { $sum: "$timestampDifference" }, + timestampDifferences: { $push: "$timestampDifference" }, + attempt_timestamp: { $first: "$_id.attempt_timestamp" }, + }, + }, + { + $group: { + _id: null, + total_flying_mins_for_week: { $sum: "$flying_mins" }, + }, + }, + { + $project: { + _id: 0, + total_flying_mins_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_flying_mins_for_week : 0; + } catch (error) { + console.error("Error in getTotalFlyingMinutesForCurrentWeek:", error); + throw error; + } + } + + async getTotalHeightForCurrentWeekByPlayerId(kitePlayerId: string): Promise { + try { + const startOfCurrentWeek = moment().startOf('week').toDate(); + const endOfCurrentWeek = moment().endOf('week').toDate(); + + + const aggregationPipeline = [ + { + $match: { + "metadata.kite_player_id": kitePlayerId, + "metadata.attempt_timestamp": { + $gte: startOfCurrentWeek, + $lte: endOfCurrentWeek, + }, + }, + }, + { + $group: { + _id: { + kite_player_id: "$metadata.kite_player_id", + attempt_timestamp: "$metadata.attempt_timestamp", + }, + max_altitude: { $max: "$altitude" }, + min_altitude: { $min: "$altitude" }, + }, + }, + { + $addFields: { + height: { $subtract: ["$max_altitude", "$min_altitude"] }, + }, + }, + { + $group: { + _id: "$_id.kite_player_id", + total_height: { $sum: "$height" }, + }, + }, + { + $group: { + _id: null, + total_height_for_week: { $sum: "$total_height" }, + }, + }, + { + $project: { + _id: 0, + total_height_for_week: 1, + }, + }, + ]; + + const result = await this.kiteDatumModel.aggregate(aggregationPipeline).exec(); + return result.length > 0 ? result[0].total_height_for_week : 0; + } catch (error) { + console.error("Error in getTotalHeightForDateRange:", error); + throw error; + } + } +} diff --git a/src/modules/kite-data/schema/kitedata-metadata.schema.ts b/src/modules/kite-data/schema/kitedata-metadata.schema.ts new file mode 100644 index 0000000..dbbe5f4 --- /dev/null +++ b/src/modules/kite-data/schema/kitedata-metadata.schema.ts @@ -0,0 +1,25 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; +import { KitePlayer } from 'src/modules/kite-players/entities/kite-player.entity'; +import { User } from 'src/modules/users/entities/user.entity'; + +@Schema({ timestamps: { createdAt: true, updatedAt: false } }) +export class KiteDataMetaData { + @Prop({ type: String, ref: User.name }) + author_user_id: string; + + @Prop({ type: String, ref: KitePlayer.name }) + kite_player_id: string; + + @Prop({ type: Object }) + coordinates: ICoordinates; + + @Prop({ type: Date }) + attempt_timestamp: Date; + + @Prop({ type: String, default: '' }) + sensor_id: string; +} + +export const KiteDataMetadataSchema = + SchemaFactory.createForClass(KiteDataMetaData); diff --git a/src/modules/kite-players/dto/create-kite-player-dto.ts b/src/modules/kite-players/dto/create-kite-player-dto.ts new file mode 100644 index 0000000..9da7c7f --- /dev/null +++ b/src/modules/kite-players/dto/create-kite-player-dto.ts @@ -0,0 +1,13 @@ +import { IsOptional } from 'class-validator'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; + +export class CreateKitePlayerDto { + readonly name: string; + readonly coordinates: ICoordinates; + readonly birthday: Date; + readonly city: string; + readonly img_url: string; + + @IsOptional() + readonly isBot?: boolean; +} diff --git a/src/modules/kite-players/dto/get-kite-player-dto.ts b/src/modules/kite-players/dto/get-kite-player-dto.ts new file mode 100644 index 0000000..356cd87 --- /dev/null +++ b/src/modules/kite-players/dto/get-kite-player-dto.ts @@ -0,0 +1,10 @@ +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; + +export class GetKitePlayerDto { + readonly _id: string; + readonly name: string; + readonly birthday:Date; + readonly coordinates: ICoordinates; + readonly city: string; + readonly img_url: string; +} diff --git a/src/modules/kite-players/dto/kite-player-created-response.dto.ts b/src/modules/kite-players/dto/kite-player-created-response.dto.ts new file mode 100644 index 0000000..ced8984 --- /dev/null +++ b/src/modules/kite-players/dto/kite-player-created-response.dto.ts @@ -0,0 +1,8 @@ +import { PartialType } from '@nestjs/mapped-types'; +import { CreateKitePlayerDto } from './create-kite-player-dto'; + +export class KitePlayerCreatedResponseDto extends PartialType( + CreateKitePlayerDto, +) { + readonly _id: string; +} diff --git a/src/modules/kite-players/dto/kite-player-updated-response.dto.ts b/src/modules/kite-players/dto/kite-player-updated-response.dto.ts new file mode 100644 index 0000000..ac6d131 --- /dev/null +++ b/src/modules/kite-players/dto/kite-player-updated-response.dto.ts @@ -0,0 +1,6 @@ +import { PartialType } from '@nestjs/mapped-types'; +import { KitePlayerCreatedResponseDto } from './kite-player-created-response.dto'; + +export class KitePlayerUpdatedResponseDto extends PartialType( + KitePlayerCreatedResponseDto, +) {} diff --git a/src/modules/kite-players/dto/update-kite-player-dto.ts b/src/modules/kite-players/dto/update-kite-player-dto.ts new file mode 100644 index 0000000..5f4cad8 --- /dev/null +++ b/src/modules/kite-players/dto/update-kite-player-dto.ts @@ -0,0 +1,4 @@ +import { PartialType } from '@nestjs/mapped-types'; +import { CreateKitePlayerDto } from './create-kite-player-dto'; + +export class UpdateKitePlayerDto extends PartialType(CreateKitePlayerDto) {} diff --git a/src/modules/kite-players/entities/kite-player.entity.ts b/src/modules/kite-players/entities/kite-player.entity.ts new file mode 100644 index 0000000..444e3b7 --- /dev/null +++ b/src/modules/kite-players/entities/kite-player.entity.ts @@ -0,0 +1,39 @@ +import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; +import { v4 as uuidv4 } from 'uuid'; + +@Schema({ + timestamps: true, + collection: 'kite_players', +}) +export class KitePlayer { + @Prop({ type: String, default: uuidv4 }) + _id: string; + + @Prop({ required: true }) + name: string; + + @Prop({ required: true }) + birthday: Date; + + @Prop({ required: true }) + user_id: string; + + @Prop({ required: true, type: Object }) + coordinates: ICoordinates; + + @Prop({ required: true }) + city: string; + + @Prop() + client_id: string; + + @Prop({ required: true }) + img_url: string; + + @Prop({ default: false }) + isBot?: boolean; +} + +export type KitePlayerDocument = KitePlayer & Document; +export const KitePlayerSchema = SchemaFactory.createForClass(KitePlayer); diff --git a/src/modules/kite-players/kite-players.controller.spec.ts b/src/modules/kite-players/kite-players.controller.spec.ts new file mode 100644 index 0000000..7521b1e --- /dev/null +++ b/src/modules/kite-players/kite-players.controller.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { KitePlayersController } from './kite-players.controller'; + +describe('KitePlayersController', () => { + let controller: KitePlayersController; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + controllers: [KitePlayersController], + }).compile(); + + controller = module.get(KitePlayersController); + }); + + it('should be defined', () => { + expect(controller).toBeDefined(); + }); +}); diff --git a/src/modules/kite-players/kite-players.controller.ts b/src/modules/kite-players/kite-players.controller.ts new file mode 100644 index 0000000..0ac9403 --- /dev/null +++ b/src/modules/kite-players/kite-players.controller.ts @@ -0,0 +1,72 @@ +import { + Body, + Controller, + Delete, + Get, + Headers, + Param, + Patch, + Post, + UseGuards +} from '@nestjs/common'; +import { ApiTags } from '@nestjs/swagger'; +import { ValidateGaveshaClientGuard } from '../common/guards/gavesha-client.guard'; +import { ValidateGaveshaUserGuard } from '../common/guards/gavesha-user.guard'; +import { KiteDataService } from '../kite-data/kite-data.service'; +import { CreateKitePlayerDto } from './dto/create-kite-player-dto'; +import { GetKitePlayerDto } from './dto/get-kite-player-dto'; +import { KitePlayerUpdatedResponseDto } from './dto/kite-player-updated-response.dto'; +import { UpdateKitePlayerDto } from './dto/update-kite-player-dto'; +import { KitePlayer } from './entities/kite-player.entity'; +import { KitePlayersService } from './kite-players.service'; + +@Controller('kite-players') +@ApiTags('kite-players') +export class KitePlayersController { + constructor( + private readonly kiteplayersService: KitePlayersService, + private readonly kiteDataService: KiteDataService, + ) {} + + @UseGuards(ValidateGaveshaClientGuard, ValidateGaveshaUserGuard) + @Post() + create( + @Headers('gavesha-user-api-key') gaveshaUserApiKey: string, + @Body() createKitePlayerDto: CreateKitePlayerDto, + ) { + return this.kiteplayersService.create( + createKitePlayerDto, + gaveshaUserApiKey, + ); + } + + @Get() + findAll(): Promise { + return this.kiteplayersService.findAll(); + } + + @Get(':id') + findOne(@Param('id') id: string) { + return this.kiteplayersService.findOne(id); + } + + @UseGuards(ValidateGaveshaClientGuard) + @Patch(':id') + async update( + @Param('id') id: string, + @Body() updateKiteplayerDto: UpdateKitePlayerDto, + ): Promise { + return this.kiteplayersService.update(id, updateKiteplayerDto); + } + + @UseGuards(ValidateGaveshaClientGuard) + @Delete(':id') + remove(@Param('id') id: string) { + return this.kiteplayersService.remove(+id); + } + + @Get('users/:userId') + async getKitePlayerByUserId(@Param('userId') userId: string): Promise { + return this.kiteplayersService.findKitePlayerByUserId(userId); + } +} diff --git a/src/modules/kite-players/kite-players.module.ts b/src/modules/kite-players/kite-players.module.ts new file mode 100644 index 0000000..b5e8743 --- /dev/null +++ b/src/modules/kite-players/kite-players.module.ts @@ -0,0 +1,23 @@ +import { forwardRef, Module } from '@nestjs/common'; +import { MongooseModule } from '@nestjs/mongoose'; +import { KiteDataModule } from '../kite-data/kite-data.module'; +import { TokenModule } from '../users/token/token.module'; +import { UsersModule } from '../users/users.module'; +import { KitePlayer, KitePlayerSchema } from './entities/kite-player.entity'; +import { KitePlayersController } from './kite-players.controller'; +import { KitePlayersService } from './kite-players.service'; + +@Module({ + imports: [ + forwardRef(() => KiteDataModule), + UsersModule, + TokenModule, + MongooseModule.forFeature([ + { name: KitePlayer.name, schema: KitePlayerSchema }, + ]), + ], + controllers: [KitePlayersController], + providers: [KitePlayersService, KitePlayer], + exports: [KitePlayersService], +}) +export class KitePlayersModule {} diff --git a/src/modules/kite-players/kite-players.service.spec.ts b/src/modules/kite-players/kite-players.service.spec.ts new file mode 100644 index 0000000..19bf878 --- /dev/null +++ b/src/modules/kite-players/kite-players.service.spec.ts @@ -0,0 +1,18 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { KitePlayersService } from './kite-players.service'; + +describe('KitePlayersService', () => { + let service: KitePlayersService; + + beforeEach(async () => { + const module: TestingModule = await Test.createTestingModule({ + providers: [KitePlayersService], + }).compile(); + + service = module.get(KitePlayersService); + }); + + it('should be defined', () => { + expect(service).toBeDefined(); + }); +}); diff --git a/src/modules/kite-players/kite-players.service.ts b/src/modules/kite-players/kite-players.service.ts new file mode 100644 index 0000000..6693f71 --- /dev/null +++ b/src/modules/kite-players/kite-players.service.ts @@ -0,0 +1,141 @@ +import { HttpException, Injectable, NotFoundException } from '@nestjs/common'; +import { JwtService } from '@nestjs/jwt'; +import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import { Connection, Model } from 'mongoose'; +import { CreateKitePlayerDto } from './dto/create-kite-player-dto'; +import { GetKitePlayerDto } from './dto/get-kite-player-dto'; +import { KitePlayerCreatedResponseDto } from './dto/kite-player-created-response.dto'; +import { UpdateKitePlayerDto } from './dto/update-kite-player-dto'; +import { KitePlayer, KitePlayerDocument } from './entities/kite-player.entity'; + +@Injectable() +export class KitePlayersService { + avatarUrls: any; + constructor( + @InjectModel(KitePlayer.name) + private readonly kitePlayerModel: Model, + @InjectConnection() private readonly mongoConnection: Connection, + private readonly jwtService: JwtService, + ) {} + + private readonly avatarFilenames = [ + 'avataaars (1).svg', + 'avataaars (2).svg', + 'avataaars (3).svg', + 'avataaars (4).svg', + 'avataaars (5).svg', + 'avataaars (6).svg', + 'avataaars (7).svg', + 'avataaars (8).svg', + 'avataaars (9).svg', + 'avataaars (10).svg', + 'avataaars (11).svg', + 'avataaars (12).svg', + 'avataaars (13).svg', + 'avataaars (14).svg', + 'avataaars (15).svg', + 'avataaars (16).svg', + 'avataaars (17).svg', + 'avataaars (18).svg', + 'avataaars (19).svg', + 'avataaars (20).svg', + 'avataaars (21).svg', + 'avataaars (22).svg', + 'avataaars (23).svg', + 'avataaars (24).svg', + 'avataaars (25).svg', + 'avataaars (26).svg', + 'avataaars (27).svg', + 'avataaars (28).svg', + 'avataaars (29).svg', + ]; + + private getRandomAvatarUrl(): string { + const randomFilename = this.avatarFilenames[Math.floor(Math.random() * this.avatarFilenames.length)]; + return `assets/avatars/Avatar_Icons/${randomFilename}`; + } + + // Protected by guards. + async create( + createKitePlayerDto: CreateKitePlayerDto, + gaveshaUserApiKey: string, + ): Promise { + try { + // Step 1: Validate the API key + let result = null; + try { + result = await this.jwtService.verifyAsync(gaveshaUserApiKey); + } catch (e) { + throw new HttpException('API Key validation failed', 401); + } + // Step 2: Create Kite Player + const existingKitePlayer = await this.kitePlayerModel + .findOne({ + user_id: result._id, + }) + .exec(); + + let kitePlayer: typeof existingKitePlayer; + + if (existingKitePlayer) { + kitePlayer = existingKitePlayer; + } else { + + const randomAvatarUrl = this.getRandomAvatarUrl(); + const newKitePlayer = new this.kitePlayerModel({ + ...createKitePlayerDto, + user_id: result._id, + img_url: randomAvatarUrl, + }); + kitePlayer = await newKitePlayer.save(); + } + const response: KitePlayerCreatedResponseDto = { + _id: kitePlayer._id, + name: kitePlayer.name, + birthday: kitePlayer.birthday, + coordinates: kitePlayer.coordinates, + city: kitePlayer.city, + img_url: kitePlayer.img_url, + }; + + return response; + } catch (error) { + throw error; + } + } + + findAll(): Promise { + return this.kitePlayerModel.find(); + } + + findOne(id: string) { + return this.kitePlayerModel.findOne({ + _id: id, + }); + } + + async update(_id: string, kitePlayerDto: UpdateKitePlayerDto) { + const updatedKitePlayer = await this.kitePlayerModel + .findByIdAndUpdate( + _id, + kitePlayerDto, + { new: true }, // Return the updated document instead of the original + ) + .exec(); + if (!updatedKitePlayer) { + throw new NotFoundException(`Kite Player with ID '${_id}' not found`); + } + return updatedKitePlayer; + } + remove(id: number) { + return `This action removes a #${id} weatherStation`; + } + + async findKitePlayerByUserId(_id: string): Promise { + const kitePlayer = await this.kitePlayerModel.findOne({ user_id: _id }).exec(); + if (!kitePlayer) { + throw new NotFoundException(`Kite player with user_id ${_id} not found`); + } + return kitePlayer; + } +} diff --git a/src/modules/users/session/session.module.ts b/src/modules/users/session/session.module.ts index cd42db2..b918863 100644 --- a/src/modules/users/session/session.module.ts +++ b/src/modules/users/session/session.module.ts @@ -1,15 +1,24 @@ import { Module } from '@nestjs/common'; -import { SessionController } from './session.controller'; -import { SessionService } from './session.service'; -import { UsersModule } from '../users.module'; +import { OAuth2Client } from 'google-auth-library'; import { AuthModule } from 'src/modules/auth/auth.module'; import { AuthService } from 'src/modules/auth/auth.service'; -import { OAuth2Client } from 'google-auth-library'; +import { KitePlayersModule } from 'src/modules/kite-players/kite-players.module'; +import { ClientsModule } from '../../clients/clients.module'; import { WeatherStationsModule } from '../../weather-stations/weather-stations.module'; import { TokenModule } from '../token/token.module'; +import { UsersModule } from '../users.module'; +import { SessionController } from './session.controller'; +import { SessionService } from './session.service'; @Module({ - imports: [AuthModule, UsersModule, WeatherStationsModule, TokenModule], + imports: [ + AuthModule, + UsersModule, + WeatherStationsModule, + TokenModule, + ClientsModule, + KitePlayersModule + ], controllers: [SessionController], providers: [SessionService, OAuth2Client, AuthService], exports: [SessionService], diff --git a/src/modules/users/session/session.service.ts b/src/modules/users/session/session.service.ts index 597a2cb..20512ed 100644 --- a/src/modules/users/session/session.service.ts +++ b/src/modules/users/session/session.service.ts @@ -1,26 +1,49 @@ -import { CreateSessionDto } from '../dto/create-session.dto'; -import { UsersService } from '../users.service'; -import { CreateUserDto } from '../dto/create-user.dto'; -import { User } from '../entities/user.entity'; import { HttpException, Injectable } from '@nestjs/common'; import { AuthService } from 'src/modules/auth/auth.service'; +import { KitePlayersService } from 'src/modules/kite-players/kite-players.service'; import { v4 as uuidv4 } from 'uuid'; import { WeatherStationsService } from '../../weather-stations/weather-stations.service'; +import { CreateSessionDto } from '../dto/create-session.dto'; +import { CreateUserDto } from '../dto/create-user.dto'; +import { User } from '../entities/user.entity'; import { TokenService } from '../token/token.service'; +import { UsersService } from '../users.service'; @Injectable() export class SessionService { + kitePlayerModel: any; constructor( private authService: AuthService, private usersService: UsersService, private tokenService: TokenService, private weatherStationsService: WeatherStationsService, + private kitePlayersService: KitePlayersService, ) {} + private createUserResponse( + user: User, + newUser: boolean, + ): User & { new_user: boolean } { + return { + _id: user._id, + email: user.email, + uid: user.uid, + name: user.name, + contact_no: user.contact_no, + nearest_city: user.nearest_city, + nearest_city_postalcode: user.nearest_city_postalcode, + photo_url: user.photo_url, + is_active: user.is_active, + gavesha_user_api_key: user.gavesha_user_api_key, + scopes: user.scopes, + new_user: newUser, + }; + } + async create( createSessionDto: CreateSessionDto, idToken: string, - ): Promise { + ): Promise { // Check auth. try { await this.authService.authenticateWithGoogle(idToken); @@ -75,10 +98,16 @@ export class SessionService { gavesha_user_api_key: newApiKey, }); - return updatedUser; + const existingPlayer = await this.kitePlayerModel.findOne({ user_id: user._id }).exec(); + const newUserFlag = !existingPlayer; + + return this.createUserResponse(updatedUser, newUserFlag); } - return user; + const existingPlayer = await this.kitePlayerModel.findOne({ user_id: user._id }).exec(); + const newUserFlag = !existingPlayer; + + return this.createUserResponse(user, newUserFlag); } // Create a new userId. @@ -111,6 +140,7 @@ export class SessionService { // Create user within the database. // When creating a user, the uuidv4 userId is passed as the _id. - return await this.usersService.create(createUserDto, uuidV4Id); + const result = await this.usersService.create(createUserDto, uuidV4Id); + return this.createUserResponse(result, true); } } diff --git a/src/modules/users/token/token.service.ts b/src/modules/users/token/token.service.ts index c06f0c7..929aa08 100644 --- a/src/modules/users/token/token.service.ts +++ b/src/modules/users/token/token.service.ts @@ -1,7 +1,8 @@ import { IGenUserApiKey } from '../../common/interfaces/gen-user-api-key.interface'; -import { JwtService } from '@nestjs/jwt'; +import { JwtService, TokenExpiredError } from '@nestjs/jwt'; import { UsersService } from '../users.service'; import { HttpException, Injectable } from '@nestjs/common'; +import { IGenClientKey } from '../../common/interfaces/gen-client-key.interface'; @Injectable() export class TokenService { @@ -62,4 +63,59 @@ export class TokenService { public validateComClientId(clientId: string) { return clientId === process.env.WEATHERCOM_CLIENT_ID; } + + public async generateClientAccessToken(data: IGenClientKey): Promise { + const expiresIn: string = data.expiresIn || '1d'; // 1 day + + try { + return await this.jwtService.signAsync(data.payload, { + expiresIn: expiresIn, + issuer: 'https://auth.gavesha.space/access', + subject: data.subject, + }); + } catch (error) { + console.error(error); + throw error; + } + } + + public async generateRefreshToken(data: IGenClientKey) { + return this.jwtService.signAsync(data.payload, { + expiresIn: data.expiresIn || '90d', + issuer: 'https://auth.gavesha.space/refresh', + subject: data.subject, + }); + } + + public async validateClientAccessToken( + accessTokenHeader: string, + ): Promise { + try { + return await this.jwtService.verifyAsync(accessTokenHeader.split(' ')[1]); + } catch (error) { + if (error instanceof TokenExpiredError) { + throw new HttpException('Token expired, err 1004', 401); + } + throw new HttpException('Token validation failed, err 1005', 401); + } + } + + public async verifyRefreshToken( + refreshTokenHeader: string, + ): Promise { + try { + const payload = await this.jwtService.verifyAsync( + refreshTokenHeader.split(' ')[1], + ); + if ((payload.iss as string).indexOf('refresh')) { + return payload; + } + throw new HttpException('Token validation failed, err 1003', 401); + } catch (error) { + if (error instanceof TokenExpiredError) { + throw new HttpException('Token expired, err 1004', 401); + } + throw new HttpException('Token validation failed, err 1005', 401); + } + } } diff --git a/src/modules/users/users.module.ts b/src/modules/users/users.module.ts index e73364c..2ed2db2 100644 --- a/src/modules/users/users.module.ts +++ b/src/modules/users/users.module.ts @@ -1,8 +1,8 @@ import { Module } from '@nestjs/common'; -import { UsersService } from './users.service'; -import { UsersController } from './users.controller'; import { MongooseModule } from '@nestjs/mongoose'; import { User, UserSchema } from './entities/user.entity'; +import { UsersController } from './users.controller'; +import { UsersService } from './users.service'; @Module({ imports: [ diff --git a/src/modules/users/users.service.ts b/src/modules/users/users.service.ts index 89ae543..5e3c0bf 100644 --- a/src/modules/users/users.service.ts +++ b/src/modules/users/users.service.ts @@ -1,10 +1,10 @@ import { Injectable, NotFoundException } from '@nestjs/common'; +import { InjectModel } from '@nestjs/mongoose'; +import { FilterQuery, Model } from 'mongoose'; import { CreateUserDto } from './dto/create-user.dto'; +import { GetUserDto } from './dto/get-user.dto'; import { UpdateUserDto } from './dto/update-user.dto'; -import { FilterQuery, Model } from 'mongoose'; -import { InjectModel } from '@nestjs/mongoose'; import { User, UserDocument } from './entities/user.entity'; -import { GetUserDto } from './dto/get-user.dto'; @Injectable() export class UsersService { diff --git a/src/modules/weather-data/dto/bulk-create-weather-data-response.dto.ts b/src/modules/weather-data/dto/bulk-create-weather-data-response.dto.ts index 055b075..bc4716f 100644 --- a/src/modules/weather-data/dto/bulk-create-weather-data-response.dto.ts +++ b/src/modules/weather-data/dto/bulk-create-weather-data-response.dto.ts @@ -1,5 +1,6 @@ export class BulkCreateWeatherDataResponseDto { readonly _id: string; readonly timestamp: Date; + readonly timestamp_iso: string; readonly created_at: Date; } diff --git a/src/modules/weather-data/dto/create-bulk-weather-data.dto.ts b/src/modules/weather-data/dto/create-bulk-weather-data.dto.ts index 0a1d9a2..f732061 100644 --- a/src/modules/weather-data/dto/create-bulk-weather-data.dto.ts +++ b/src/modules/weather-data/dto/create-bulk-weather-data.dto.ts @@ -26,8 +26,11 @@ export class CreateBulkWeatherDataDto { readonly data: WeatherDataPoint[]; @IsOptional() - readonly gavesha_user_api_key: string; + readonly gavesha_user_api_key?: string; @IsOptional() - readonly client_id: string; + readonly client_id?: string; + + @IsOptional() + readonly sensor_id?: string; } diff --git a/src/modules/weather-data/dto/create-weathercom-bulk-weather-data.dto.ts b/src/modules/weather-data/dto/create-weathercom-bulk-weather-data.dto.ts new file mode 100644 index 0000000..b88affc --- /dev/null +++ b/src/modules/weather-data/dto/create-weathercom-bulk-weather-data.dto.ts @@ -0,0 +1,24 @@ +import { Type } from 'class-transformer'; +import { + ArrayNotEmpty, + IsArray, + IsNotEmpty, + IsOptional, + ValidateNested, +} from 'class-validator'; +import { ICoordinates } from 'src/modules/common/interfaces/coordinates.interface'; +import { WeatherDataPoint } from '../entities/weather-datapoint.entity'; + +export class CreateWeatherComBulkWeatherDataDto { + @IsNotEmpty() + readonly coordinates: ICoordinates; + + @IsOptional() + readonly sensor_id?: string; + + @IsArray() + @ArrayNotEmpty() + @ValidateNested({ each: true }) + @Type(() => WeatherDataPoint) + readonly data: WeatherDataPoint[]; +} diff --git a/src/modules/weather-data/entities/weather-datapoint.entity.ts b/src/modules/weather-data/entities/weather-datapoint.entity.ts index 7accaa1..71b5119 100644 --- a/src/modules/weather-data/entities/weather-datapoint.entity.ts +++ b/src/modules/weather-data/entities/weather-datapoint.entity.ts @@ -6,6 +6,10 @@ export class WeatherDataPoint { @Prop() timestamp: number; + @IsOptional() + @Prop() + timestamp_iso: string; + @IsOptional() @Prop() temperature: number; diff --git a/src/modules/weather-data/weather-data.controller.ts b/src/modules/weather-data/weather-data.controller.ts index f0de7df..690d2ff 100644 --- a/src/modules/weather-data/weather-data.controller.ts +++ b/src/modules/weather-data/weather-data.controller.ts @@ -1,29 +1,39 @@ import { + BadRequestException, + Body, Controller, + Delete, + ForbiddenException, Get, - Post, - Body, + Headers, Param, - Delete, ParseUUIDPipe, + Post, + Query, + Req, UseGuards, - BadRequestException, UsePipes, ValidationPipe, - Query, } from '@nestjs/common'; -import { WeatherDataService } from './weather-data.service'; import { ApiTags } from '@nestjs/swagger'; +import * as moment from 'moment'; import { ValidateGaveshaClientGuard } from '../common/guards/gavesha-client.guard'; import { ValidateGaveshaUserGuard } from '../common/guards/gavesha-user.guard'; -import { CreateBulkWeatherDataDto } from './dto/create-bulk-weather-data.dto'; +import { WeatherStationsService } from '../weather-stations/weather-stations.service'; import { BulkCreateWeatherDataResponseDto } from './dto/bulk-create-weather-data-response.dto'; +import { CreateBulkWeatherDataDto } from './dto/create-bulk-weather-data.dto'; +import { CreateWeatherComBulkWeatherDataDto } from './dto/create-weathercom-bulk-weather-data.dto'; import { GetWeatherDatumDto } from './dto/get-weather-datum.dto'; +import { WeatherDataService } from './weather-data.service'; + @Controller('weather-data') @ApiTags('weather-data') export class WeatherDataController { - constructor(private readonly weatherDataService: WeatherDataService) {} + constructor( + private readonly weatherDataService: WeatherDataService, + private readonly weatherStationService: WeatherStationsService, + ) {} @UseGuards(ValidateGaveshaClientGuard, ValidateGaveshaUserGuard) @Post('bulk') @@ -38,7 +48,73 @@ export class WeatherDataController { async bulkCommit( @Body() createBulkWeatherData: CreateBulkWeatherDataDto, ): Promise { - return await this.weatherDataService.bulkCommit(createBulkWeatherData); + const res = await this.weatherDataService.bulkCommit(createBulkWeatherData); + console.info( + res.length, + 'data committed to station', + createBulkWeatherData.weather_station_id, + ); + return res; + } + + @UseGuards(ValidateGaveshaClientGuard) + @Post('bulk/weathercom') + @UsePipes( + new ValidationPipe({ + transform: true, + whitelist: true, + forbidNonWhitelisted: true, + exceptionFactory: (errors) => new BadRequestException(errors), + }), + ) + async bulkCommitFromWeatherComputer( + @Body() createBulkWeatherData: CreateWeatherComBulkWeatherDataDto, + @Req() req: any, + ): Promise { + const station = await this.weatherStationService.findByClient(req.clientId); + if (!station) { + console.error('Data commit attempted from invalid client:', req.clientId); + throw new ForbiddenException('Invalid weather station'); + } + const dto: CreateBulkWeatherDataDto = { + ...createBulkWeatherData, + author_user_id: station.user_ids[0], + weather_station_id: station.id, + }; + + let res; + try { + res = await this.weatherDataService.bulkCommit(dto); + console.info(res.length, 'data committed from weathercom', station.id); + } catch (err) { + console.error( + 'ERROR in bulk commit from weather computer. Request body=', + dto, + err, + ); + throw new Error(); + } + const finalResponse = res.map((datum) => { + return { + _id: datum._id, + timestamp: datum.timestamp, + timestamp_iso: moment(datum.timestamp).toISOString(true), + created_at: (datum as any).createdAt, + } as BulkCreateWeatherDataResponseDto; + }); + + const returnObject = { + _id:null, + timestamp_iso: moment().toISOString(true), + } as BulkCreateWeatherDataResponseDto; + finalResponse.push(returnObject); + return finalResponse; + } + + @UseGuards(ValidateGaveshaClientGuard) + @Post('test') + async reissueAuthToken(@Headers('authorization') h) { + return h; } @Get('all') diff --git a/src/modules/weather-data/weather-data.module.ts b/src/modules/weather-data/weather-data.module.ts index 04bdac3..c7c85be 100644 --- a/src/modules/weather-data/weather-data.module.ts +++ b/src/modules/weather-data/weather-data.module.ts @@ -1,4 +1,4 @@ -import { Module } from '@nestjs/common'; +import { Module, forwardRef } from '@nestjs/common'; import { WeatherDataService } from './weather-data.service'; import { WeatherDataController } from './weather-data.controller'; import { @@ -8,6 +8,7 @@ import { import { MongooseModule } from '@nestjs/mongoose'; import { PointsModule } from '../points/points.module'; import { TokenModule } from '../users/token/token.module'; +import { WeatherStationsModule } from '../weather-stations/weather-stations.module'; @Module({ imports: [ @@ -16,6 +17,7 @@ import { TokenModule } from '../users/token/token.module'; ]), TokenModule, PointsModule, + forwardRef(() => WeatherStationsModule), ], controllers: [WeatherDataController], providers: [WeatherDataService, WeatherDatum], diff --git a/src/modules/weather-data/weather-data.service.ts b/src/modules/weather-data/weather-data.service.ts index 12fa436..ae30512 100644 --- a/src/modules/weather-data/weather-data.service.ts +++ b/src/modules/weather-data/weather-data.service.ts @@ -1,16 +1,17 @@ import { Injectable } from '@nestjs/common'; import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import * as moment from 'moment'; import { Connection, Model } from 'mongoose'; import { PointsService } from '../points/points.service'; +import { BulkCreateWeatherDataResponseDto } from './dto/bulk-create-weather-data-response.dto'; +import { CreateBulkWeatherDataDto } from './dto/create-bulk-weather-data.dto'; import { GetWeatherDatumDto } from './dto/get-weather-datum.dto'; +import { WeatherDataPoint } from './entities/weather-datapoint.entity'; import { WeatherDatum, WeatherDatumDocument, } from './entities/weather-datum.entity'; -import { CreateBulkWeatherDataDto } from './dto/create-bulk-weather-data.dto'; -import { BulkCreateWeatherDataResponseDto } from './dto/bulk-create-weather-data-response.dto'; import { WeatherDataMetadata } from './schema/weatherdata-metadata.schema'; -import { WeatherDataPoint } from './entities/weather-datapoint.entity'; @Injectable() export class WeatherDataService { @@ -39,9 +40,27 @@ export class WeatherDataService { createBulkWeatherData: CreateBulkWeatherDataDto, ): Promise { // Restructure the data to include the author_user_id, weather_station_id, metadata, coordinates. - const { author_user_id, weather_station_id, coordinates, data } = + const { author_user_id, weather_station_id, coordinates, sensor_id, data } = createBulkWeatherData; + for (let i = 0; i < data.length; i++) { + const element = data[i]; + // if (!element.timestamp) { + // if (!element.timestamp_iso) { + // throw new BadRequestException('Invalid data'); + // } + // element.timestamp = new Date(element.timestamp_iso).getTime(); + // } + + if ( + weather_station_id === 'dbfb6590-93c1-455b-aaf2-668560a73e4b' || + weather_station_id === '16c97b9b-f67f-4ab5-a6cb-730413ab4719' || + weather_station_id === '3337b81c-67d1-47c6-bdea-9f9b6c4d8977' + ) { + element.timestamp = new Date().getTime(); + } + } + let filteredDataPoints: WeatherDataPoint[] = []; const session = await this.mongoConnection.startSession(); @@ -90,7 +109,7 @@ export class WeatherDataService { author_user_id: author_user_id, weather_station_id: weather_station_id, coordinates: coordinates, - sensor_id: 'weathercomv3', + sensor_id: sensor_id || 'weathercomv3', } as WeatherDataMetadata, }; }); @@ -139,25 +158,25 @@ export class WeatherDataService { // Commit the point calculation transaction if all goes well. await session.commitTransaction(); - - // Return the _id, timestamp, created_at fields. - const responseData = [...insertedData, ...existingWeatherData]; - - return responseData.map((datum) => { - return { - _id: datum._id, - timestamp: datum.timestamp, - created_at: datum.createdAt, - } as BulkCreateWeatherDataResponseDto; - }) as BulkCreateWeatherDataResponseDto[]; } catch (error) { // Abort the point calculation transaction if any error occurs during the above. await session.abortTransaction(); - throw error; } finally { session.endSession(); } + + // Return the _id, timestamp, created_at fields. + const responseData = [...insertedData, ...existingWeatherData]; + + return responseData.map((datum) => { + return { + _id: datum._id, + timestamp: datum.timestamp, + timestamp_iso: moment(datum.timestamp).toISOString(true), + created_at: datum.createdAt, + } as BulkCreateWeatherDataResponseDto; + }) as BulkCreateWeatherDataResponseDto[]; } // TODO: Add types. @@ -194,14 +213,14 @@ export class WeatherDataService { } else { transformed.temperature -= 12; } - // } else { - // if (transformed.percentage_light_intensity == 0) { - // transformed.temperature -= 3; // error is 5 degrees celsius - // } else if (transformed.percentage_light_intensity < 50) { - // transformed.temperature -= 6.5; - // } else { - // transformed.temperature -= 10; - // } + // } else { + // if (transformed.percentage_light_intensity == 0) { + // transformed.temperature -= 3; // error is 5 degrees celsius + // } else if (transformed.percentage_light_intensity < 50) { + // transformed.temperature -= 6.5; + // } else { + // transformed.temperature -= 10; + // } } return transformed; } diff --git a/src/modules/weather-stations/entities/weather-station.entity.ts b/src/modules/weather-stations/entities/weather-station.entity.ts index b59fda9..712b91b 100644 --- a/src/modules/weather-stations/entities/weather-station.entity.ts +++ b/src/modules/weather-stations/entities/weather-station.entity.ts @@ -21,6 +21,9 @@ export class WeatherStation { @Prop({ type: [{ type: String, default: uuidv4, ref: User.name }] }) user_ids: string[]; + @Prop() + client_id: string; + @Prop({ type: Boolean, default: false }) is_hidden: boolean; } diff --git a/src/modules/weather-stations/weather-stations.module.ts b/src/modules/weather-stations/weather-stations.module.ts index 33e4a36..d0cd6fe 100644 --- a/src/modules/weather-stations/weather-stations.module.ts +++ b/src/modules/weather-stations/weather-stations.module.ts @@ -1,4 +1,4 @@ -import { Module } from '@nestjs/common'; +import { Module, forwardRef } from '@nestjs/common'; import { WeatherStationsService } from './weather-stations.service'; import { WeatherStationsController } from './weather-stations.controller'; import { MongooseModule } from '@nestjs/mongoose'; @@ -14,7 +14,7 @@ import { TokenModule } from '../users/token/token.module'; @Module({ imports: [ PointsModule, - WeatherDataModule, + forwardRef(() => WeatherDataModule), UsersModule, TokenModule, MongooseModule.forFeature([ diff --git a/src/modules/weather-stations/weather-stations.service.ts b/src/modules/weather-stations/weather-stations.service.ts index 90bded8..6917821 100644 --- a/src/modules/weather-stations/weather-stations.service.ts +++ b/src/modules/weather-stations/weather-stations.service.ts @@ -1,17 +1,17 @@ import { HttpException, Injectable, NotFoundException } from '@nestjs/common'; +import { JwtService } from '@nestjs/jwt'; +import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import { Connection, Model } from 'mongoose'; +import { TokenService } from '../users/token/token.service'; +import { UsersService } from '../users/users.service'; import { CreateWeatherStationDto } from './dto/create-weather-station.dto'; +import { GetWeatherStationDto } from './dto/get-weather-station.dto'; import { UpdateWeatherStationDto } from './dto/update-weather-station.dto'; -import { InjectConnection, InjectModel } from '@nestjs/mongoose'; +import { WeatherStationCreatedResponseDto } from './dto/weather-station-created-response.dto'; import { WeatherStation, WeatherStationDocument, } from './entities/weather-station.entity'; -import { Connection, Model } from 'mongoose'; -import { GetWeatherStationDto } from './dto/get-weather-station.dto'; -import { JwtService } from '@nestjs/jwt'; -import { UsersService } from '../users/users.service'; -import { WeatherStationCreatedResponseDto } from './dto/weather-station-created-response.dto'; -import { TokenService } from '../users/token/token.service'; @Injectable() export class WeatherStationsService { @@ -121,6 +121,13 @@ export class WeatherStationsService { }); } + findByClient(clientId: string): Promise { + return this.weatherStationModel.findOne({ + client_id: clientId, + is_hidden: { $ne: true }, + }); + } + async update(_id: string, updateWeatherStationDto: UpdateWeatherStationDto) { const updatedWeatherStation = await this.weatherStationModel.findByIdAndUpdate(