Compare commits
6 Commits
main
...
janisslsm/
Author | SHA1 | Date | |
---|---|---|---|
![]() |
225cd83cea | ||
![]() |
e824087034 | ||
![]() |
fd2027b071 | ||
![]() |
0af98bc6c2 | ||
![]() |
3403d496b4 | ||
![]() |
58b1cfc30f |
@ -1,19 +0,0 @@
|
||||
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
|
||||
language: "en-US"
|
||||
early_access: false
|
||||
reviews:
|
||||
profile: "chill"
|
||||
request_changes_workflow: false
|
||||
changed_files_summary: false
|
||||
high_level_summary: false
|
||||
poem: false
|
||||
review_status: true
|
||||
commit_status: false
|
||||
collapse_walkthrough: false
|
||||
sequence_diagrams: false
|
||||
related_prs: false
|
||||
auto_review:
|
||||
enabled: true
|
||||
drafts: false
|
||||
chat:
|
||||
auto_reply: true
|
@ -1,5 +0,0 @@
|
||||
**/.dockerignore
|
||||
**/.git
|
||||
Dockerfile*
|
||||
.*
|
||||
docker-data/
|
4
.env.example
Normal file
4
.env.example
Normal file
@ -0,0 +1,4 @@
|
||||
# Docker may need a .env file for the following settings:
|
||||
DATABASE_PORT=27017
|
||||
DATABASE_USERNAME=root
|
||||
DATABASE_PASSWORD=database
|
15
.eslintrc
15
.eslintrc
@ -12,22 +12,21 @@
|
||||
},
|
||||
"rules": {
|
||||
"@typescript-eslint/explicit-function-return-type": "warn",
|
||||
"@typescript-eslint/explicit-module-boundary-types": "warn",
|
||||
"@typescript-eslint/restrict-template-expressions": "warn",
|
||||
"@typescript-eslint/restrict-plus-operands": "warn",
|
||||
"@typescript-eslint/no-unsafe-member-access": "warn",
|
||||
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_", "caughtErrors": "none" }],
|
||||
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
|
||||
"@typescript-eslint/no-misused-promises": "warn",
|
||||
"@typescript-eslint/no-unsafe-argument": "error",
|
||||
"@typescript-eslint/no-unsafe-call": "warn",
|
||||
"@typescript-eslint/no-unsafe-assignment": "warn",
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"no-loss-of-precision": "warn",
|
||||
"@typescript-eslint/no-unnecessary-condition": "warn",
|
||||
"@typescript-eslint/no-base-to-string": "off",
|
||||
"no-case-declarations": "error",
|
||||
"@typescript-eslint/no-loss-of-precision": "warn",
|
||||
"no-case-declarations": "warn",
|
||||
"prettier/prettier": "error",
|
||||
"no-mixed-spaces-and-tabs": "error",
|
||||
"require-await": "off",
|
||||
"@typescript-eslint/require-await": "error"
|
||||
"@typescript-eslint/semi": "error",
|
||||
"no-mixed-spaces-and-tabs": "error"
|
||||
},
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
|
2
.gitattributes
vendored
2
.gitattributes
vendored
@ -1,4 +1,4 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto eol=lf
|
||||
* text=auto
|
||||
|
||||
static/webui/libs/ linguist-vendored
|
||||
|
20
.github/workflows/build.yml
vendored
20
.github/workflows/build.yml
vendored
@ -5,22 +5,18 @@ on:
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
version: [18, 20, 22]
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4.1.2
|
||||
- name: Setup Node.js environment
|
||||
uses: actions/setup-node@v4.0.2
|
||||
with:
|
||||
node-version: ${{ matrix.version }}
|
||||
- run: npm ci
|
||||
- run: cp config.json.example config.json
|
||||
- run: npm run verify
|
||||
- run: npm run lint:ci
|
||||
- run: npm run prettier
|
||||
- run: npm run update-translations
|
||||
- name: Fail if there are uncommitted changes
|
||||
run: |
|
||||
if [[ -n "$(git status --porcelain)" ]]; then
|
||||
echo "Uncommitted changes detected:"
|
||||
git status
|
||||
git --no-pager diff
|
||||
exit 1
|
||||
fi
|
||||
- run: echo '{"version":"","buildLabel":"","matchmakingBuildId":""}' > static/data/buildConfig.json
|
||||
- run: npm run build
|
||||
- run: npm run lint
|
||||
|
25
.github/workflows/docker.yml
vendored
25
.github/workflows/docker.yml
vendored
@ -1,25 +0,0 @@
|
||||
name: Build Docker image
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
jobs:
|
||||
docker:
|
||||
if: github.repository == 'OpenWF/SpaceNinjaServer'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Set up Docker buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
- name: Log in to container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
username: openwf
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: |
|
||||
openwf/spaceninjaserver:latest
|
||||
openwf/spaceninjaserver:${{ github.sha }}
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -15,7 +15,4 @@ yarn.lock
|
||||
/logs
|
||||
|
||||
# MongoDB VSCode extension playground scripts
|
||||
/database_scripts
|
||||
|
||||
# Default Docker directory
|
||||
/docker-data
|
||||
/database_scripts
|
@ -1,4 +1,2 @@
|
||||
src/routes/api.ts
|
||||
static/webui/libs/
|
||||
*.html
|
||||
*.md
|
||||
|
3
.vscode/extensions.json
vendored
3
.vscode/extensions.json
vendored
@ -1,3 +0,0 @@
|
||||
{
|
||||
"recommendations": ["dbaeumer.vscode-eslint"]
|
||||
}
|
19
.vscode/launch.json
vendored
19
.vscode/launch.json
vendored
@ -1,19 +0,0 @@
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
{
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Debug and Watch",
|
||||
"runtimeArgs": ["-r", "tsconfig-paths/register", "-r", "ts-node/register", "--watch-path", "src"],
|
||||
"args": ["${workspaceFolder}/src/index.ts"],
|
||||
"console": "integratedTerminal"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
//can use "console": "internalConsole" for VS Code's Debug Console. For that, forceConsole in logger.ts is needed to be true
|
||||
//"internalConsoleOptions": "openOnSessionStart" can be useful then
|
27
Dockerfile
27
Dockerfile
@ -1,26 +1,5 @@
|
||||
FROM node:18-alpine3.19
|
||||
FROM mongo as base
|
||||
|
||||
ENV APP_MONGODB_URL=mongodb://mongodb:27017/openWF
|
||||
ENV APP_MY_ADDRESS=localhost
|
||||
ENV APP_HTTP_PORT=80
|
||||
ENV APP_HTTPS_PORT=443
|
||||
ENV APP_AUTO_CREATE_ACCOUNT=true
|
||||
ENV APP_SKIP_STORY_MODE_CHOICE=true
|
||||
ENV APP_SKIP_TUTORIAL=true
|
||||
ENV APP_SKIP_ALL_DIALOGUE=true
|
||||
ENV APP_UNLOCK_ALL_SCANS=true
|
||||
ENV APP_UNLOCK_ALL_MISSIONS=true
|
||||
ENV APP_INFINITE_RESOURCES=true
|
||||
ENV APP_UNLOCK_ALL_SHIP_FEATURES=true
|
||||
ENV APP_UNLOCK_ALL_SHIP_DECORATIONS=true
|
||||
ENV APP_UNLOCK_ALL_FLAVOUR_ITEMS=true
|
||||
ENV APP_UNLOCK_ALL_SKINS=true
|
||||
ENV APP_UNIVERSAL_POLARITY_EVERYWHERE=true
|
||||
ENV APP_SPOOF_MASTERY_RANK=-1
|
||||
EXPOSE 27017
|
||||
|
||||
RUN apk add --no-cache bash sed wget jq
|
||||
|
||||
COPY . /app
|
||||
WORKDIR /app
|
||||
|
||||
ENTRYPOINT ["/app/docker-entrypoint.sh"]
|
||||
CMD ["mongod"]
|
14
README.md
14
README.md
@ -1,17 +1,3 @@
|
||||
# Space Ninja Server
|
||||
|
||||
More information for the moment here: [https://discord.gg/PNNZ3asUuY](https://discord.gg/PNNZ3asUuY)
|
||||
|
||||
## Project Status
|
||||
|
||||
This project is in active development at <https://onlyg.it/OpenWF/SpaceNinjaServer>.
|
||||
|
||||
To get an idea of what functionality you can expect to be missing [have a look through the issues](https://onlyg.it/OpenWF/SpaceNinjaServer/issues?q=&type=all&state=open&labels=-4%2C-10&milestone=0&assignee=0&poster=). However, many things have been implemented and *should* work as expected. Please open an issue for anything where that's not the case and/or the server is reporting errors.
|
||||
|
||||
## config.json
|
||||
|
||||
SpaceNinjaServer requires a `config.json`. To set it up, you can copy the [config.json.example](config.json.example), which has most cheats disabled.
|
||||
|
||||
- `logger.level` can be `fatal`, `error`, `warn`, `info`, `http`, `debug`, or `trace`.
|
||||
- `myIrcAddresses` can be used to point to an IRC server. If not provided, defaults to `[ myAddress ]`.
|
||||
- `worldState.lockTime` will lock the time provided in worldState if nonzero, e.g. `1743202800` for night in POE.
|
||||
|
@ -1,25 +0,0 @@
|
||||
@echo off
|
||||
|
||||
echo Updating SpaceNinjaServer...
|
||||
git fetch --prune
|
||||
git stash
|
||||
git reset --hard origin/main
|
||||
|
||||
if exist static\data\0\ (
|
||||
echo Updating stripped assets...
|
||||
cd static\data\0\
|
||||
git pull
|
||||
cd ..\..\..\
|
||||
)
|
||||
|
||||
echo Updating dependencies...
|
||||
call npm i --omit=dev
|
||||
|
||||
call npm run build
|
||||
if %errorlevel% == 0 (
|
||||
call npm run start
|
||||
echo SpaceNinjaServer seems to have crashed.
|
||||
)
|
||||
:a
|
||||
pause > nul
|
||||
goto a
|
@ -1,56 +1,26 @@
|
||||
{
|
||||
"mongodbUrl": "mongodb://127.0.0.1:27017/openWF",
|
||||
"mongodbUrl": "mongodb://127.0.0.1:27017/openWF_2013",
|
||||
"logger": {
|
||||
"files": true,
|
||||
"level": "trace"
|
||||
"level": "trace",
|
||||
"__valid_levels": "fatal, error, warn, info, http, debug, trace"
|
||||
},
|
||||
"myAddress": "localhost",
|
||||
"httpPort": 80,
|
||||
"httpsPort": 443,
|
||||
"NRS": ["localhost"],
|
||||
"administratorNames": [],
|
||||
"autoCreateAccount": true,
|
||||
"skipTutorial": false,
|
||||
"skipAllDialogue": false,
|
||||
"unlockAllScans": false,
|
||||
"unlockAllMissions": false,
|
||||
"infiniteCredits": false,
|
||||
"infinitePlatinum": false,
|
||||
"infiniteEndo": false,
|
||||
"infiniteRegalAya": false,
|
||||
"infiniteHelminthMaterials": false,
|
||||
"dontSubtractConsumables": false,
|
||||
"unlockAllShipFeatures": false,
|
||||
"unlockAllShipDecorations": false,
|
||||
"unlockAllFlavourItems": false,
|
||||
"unlockAllSkins": false,
|
||||
"unlockAllCapturaScenes": false,
|
||||
"universalPolarityEverywhere": false,
|
||||
"unlockDoubleCapacityPotatoesEverywhere": false,
|
||||
"unlockExilusEverywhere": false,
|
||||
"unlockArcanesEverywhere": false,
|
||||
"noDailyStandingLimits": false,
|
||||
"noDailyFocusLimit": false,
|
||||
"noArgonCrystalDecay": false,
|
||||
"noMasteryRankUpCooldown": false,
|
||||
"noVendorPurchaseLimits": true,
|
||||
"noDeathMarks": false,
|
||||
"noKimCooldowns": false,
|
||||
"instantResourceExtractorDrones": false,
|
||||
"noResourceExtractorDronesDamage": false,
|
||||
"skipClanKeyCrafting": false,
|
||||
"noDojoRoomBuildStage": false,
|
||||
"noDecoBuildStage": false,
|
||||
"fastDojoRoomDestruction": false,
|
||||
"noDojoResearchCosts": false,
|
||||
"noDojoResearchTime": false,
|
||||
"fastClanAscension": false,
|
||||
"spoofMasteryRank": -1,
|
||||
"worldState": {
|
||||
"creditBoost": false,
|
||||
"affinityBoost": false,
|
||||
"resourceBoost": false,
|
||||
"starDays": true,
|
||||
"lockTime": 0
|
||||
}
|
||||
"skipStoryModeChoice": true,
|
||||
"skipTutorial": true,
|
||||
"skipAllDialogue": true,
|
||||
"unlockAllScans": true,
|
||||
"unlockAllMissions": true,
|
||||
"unlockAllQuests": true,
|
||||
"completeAllQuests": false,
|
||||
"infiniteResources": true,
|
||||
"unlockAllShipFeatures": true,
|
||||
"unlockAllShipDecorations": true,
|
||||
"unlockAllFlavourItems": true,
|
||||
"unlockAllSkins": true,
|
||||
"universalPolarityEverywhere": true,
|
||||
"spoofMasteryRank": -1
|
||||
}
|
||||
|
@ -1,43 +1,24 @@
|
||||
version: "3.9"
|
||||
|
||||
services:
|
||||
spaceninjaserver:
|
||||
# build: .
|
||||
image: openwf/spaceninjaserver:latest
|
||||
environment:
|
||||
APP_MONGODB_URL: mongodb://openwfagent:spaceninjaserver@mongodb:27017/
|
||||
|
||||
# Following environment variables are set to default image values.
|
||||
# Uncomment to edit.
|
||||
|
||||
# APP_MY_ADDRESS: localhost
|
||||
# APP_HTTP_PORT: 80
|
||||
# APP_HTTPS_PORT: 443
|
||||
# APP_AUTO_CREATE_ACCOUNT: true
|
||||
# APP_SKIP_STORY_MODE_CHOICE: true
|
||||
# APP_SKIP_TUTORIAL: true
|
||||
# APP_SKIP_ALL_DIALOGUE: true
|
||||
# APP_UNLOCK_ALL_SCANS: true
|
||||
# APP_UNLOCK_ALL_MISSIONS: true
|
||||
# APP_UNLOCK_ALL_QUESTS: true
|
||||
# APP_COMPLETE_ALL_QUESTS: true
|
||||
# APP_INFINITE_RESOURCES: true
|
||||
# APP_UNLOCK_ALL_SHIP_FEATURES: true
|
||||
# APP_UNLOCK_ALL_SHIP_DECORATIONS: true
|
||||
# APP_UNLOCK_ALL_FLAVOUR_ITEMS: true
|
||||
# APP_UNLOCK_ALL_SKINS: true
|
||||
# APP_UNIVERSAL_POLARITY_EVERYWHERE: true
|
||||
# APP_SPOOF_MASTERY_RANK: -1
|
||||
volumes:
|
||||
- ./docker-data/static:/app/static/data
|
||||
- ./docker-data/logs:/app/logs
|
||||
ports:
|
||||
- 80:80
|
||||
- 443:443
|
||||
depends_on:
|
||||
- mongodb
|
||||
mongodb:
|
||||
image: docker.io/library/mongo:8.0.0-noble
|
||||
container_name: mongodb
|
||||
image: mongodb
|
||||
restart: always
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
target: base
|
||||
environment:
|
||||
MONGO_INITDB_ROOT_USERNAME: openwfagent
|
||||
MONGO_INITDB_ROOT_PASSWORD: spaceninjaserver
|
||||
volumes:
|
||||
- ./docker-data/database:/data/db
|
||||
MONGO_INITDB_ROOT_USERNAME: ${DATABASE_USERNAME}
|
||||
MONGO_INITDB_ROOT_PASSWORD: ${DATABASE_PASSWORD}
|
||||
ports:
|
||||
- ${DATABASE_PORT}:${DATABASE_PORT}
|
||||
expose:
|
||||
- "${DATABASE_PORT}"
|
||||
networks:
|
||||
- docker
|
||||
|
||||
networks:
|
||||
docker:
|
||||
external: true
|
||||
|
@ -1,23 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Set up the configuration file using environment variables.
|
||||
echo '{
|
||||
"logger": {
|
||||
"files": true,
|
||||
"level": "trace",
|
||||
"__valid_levels": "fatal, error, warn, info, http, debug, trace"
|
||||
}
|
||||
}
|
||||
' > config.json
|
||||
|
||||
for config in $(env | grep "APP_")
|
||||
do
|
||||
var=$(echo "${config}" | tr '[:upper:]' '[:lower:]' | sed 's/app_//g' | sed -E 's/_([a-z])/\U\1/g' | sed 's/=.*//g')
|
||||
val=$(echo "${config}" | sed 's/.*=//g')
|
||||
jq --arg variable "$var" --arg value "$val" '.[$variable] += try [$value|fromjson][] catch $value' config.json > config.tmp
|
||||
mv config.tmp config.json
|
||||
done
|
||||
|
||||
npm install
|
||||
exec npm run dev
|
2520
package-lock.json
generated
2520
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
44
package.json
44
package.json
@ -4,41 +4,35 @@
|
||||
"description": "WF Emulator",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"start": "node --enable-source-maps --import ./build/src/pathman.js build/src/index.js",
|
||||
"start": "node --import ./build/src/pathman.js build/src/index.js",
|
||||
"dev": "ts-node-dev --openssl-legacy-provider -r tsconfig-paths/register src/index.ts ",
|
||||
"build": "tsc --incremental --sourceMap && ncp static/webui build/static/webui",
|
||||
"verify": "tsgo --noEmit",
|
||||
"build": "tsc && copyfiles static/webui/** build",
|
||||
"lint": "eslint --ext .ts .",
|
||||
"lint:ci": "eslint --ext .ts --rule \"prettier/prettier: off\" .",
|
||||
"lint:fix": "eslint --fix --ext .ts .",
|
||||
"prettier": "prettier --write .",
|
||||
"update-translations": "cd scripts && node update-translations.js"
|
||||
"prettier": "prettier --write ."
|
||||
},
|
||||
"license": "GNU",
|
||||
"dependencies": {
|
||||
"@types/express": "^5",
|
||||
"@types/morgan": "^1.9.9",
|
||||
"crc-32": "^1.2.2",
|
||||
"express": "^5",
|
||||
"json-with-bigint": "^3.2.2",
|
||||
"mongoose": "^8.11.0",
|
||||
"morgan": "^1.10.0",
|
||||
"ncp": "^2.0.0",
|
||||
"typescript": "^5.5",
|
||||
"warframe-public-export-plus": "^0.5.59",
|
||||
"warframe-riven-info": "^0.1.2",
|
||||
"winston": "^3.17.0",
|
||||
"copyfiles": "^2.4.1",
|
||||
"express": "^5.0.0-beta.3",
|
||||
"mongoose": "^8.4.5",
|
||||
"warframe-public-export-plus": "^0.4.4",
|
||||
"warframe-riven-info": "^0.1.1",
|
||||
"winston": "^3.13.0",
|
||||
"winston-daily-rotate-file": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rxliuli/tsgo": "^2025.3.31",
|
||||
"@typescript-eslint/eslint-plugin": "^8.28.0",
|
||||
"@typescript-eslint/parser": "^8.28.0",
|
||||
"eslint": "^8",
|
||||
"eslint-plugin-prettier": "^5.2.5",
|
||||
"prettier": "^3.5.3",
|
||||
"@types/express": "^4.17.20",
|
||||
"@types/morgan": "^1.9.9",
|
||||
"@typescript-eslint/eslint-plugin": "^7.14",
|
||||
"@typescript-eslint/parser": "^7.14",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-plugin-prettier": "^5.1.3",
|
||||
"morgan": "^1.10.0",
|
||||
"prettier": "^3.3.2",
|
||||
"ts-node-dev": "^2.0.0",
|
||||
"tsconfig-paths": "^4.2.0"
|
||||
"tsconfig-paths": "^4.2.0",
|
||||
"typescript": "^5.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.15.0",
|
||||
|
@ -1,46 +0,0 @@
|
||||
// Based on https://onlyg.it/OpenWF/Translations/src/branch/main/update.php
|
||||
// Converted via ChatGPT-4o
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
function extractStrings(content) {
|
||||
const regex = /([a-zA-Z0-9_]+): `([^`]*)`,/g;
|
||||
let matches;
|
||||
const strings = {};
|
||||
while ((matches = regex.exec(content)) !== null) {
|
||||
strings[matches[1]] = matches[2];
|
||||
}
|
||||
return strings;
|
||||
}
|
||||
|
||||
const source = fs.readFileSync("../static/webui/translations/en.js", "utf8");
|
||||
const sourceStrings = extractStrings(source);
|
||||
const sourceLines = source.substring(0, source.length - 1).split("\n");
|
||||
|
||||
fs.readdirSync("../static/webui/translations").forEach(file => {
|
||||
if (fs.lstatSync(`../static/webui/translations/${file}`).isFile() && file !== "en.js") {
|
||||
const content = fs.readFileSync(`../static/webui/translations/${file}`, "utf8");
|
||||
const targetStrings = extractStrings(content);
|
||||
const contentLines = content.split("\n");
|
||||
|
||||
const fileHandle = fs.openSync(`../static/webui/translations/${file}`, "w");
|
||||
fs.writeSync(fileHandle, contentLines[0] + "\n");
|
||||
|
||||
sourceLines.forEach(line => {
|
||||
const strings = extractStrings(line);
|
||||
if (Object.keys(strings).length > 0) {
|
||||
Object.entries(strings).forEach(([key, value]) => {
|
||||
if (targetStrings.hasOwnProperty(key)) {
|
||||
fs.writeSync(fileHandle, ` ${key}: \`${targetStrings[key]}\`,\n`);
|
||||
} else {
|
||||
fs.writeSync(fileHandle, ` ${key}: \`[UNTRANSLATED] ${value}\`,\n`);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
fs.writeSync(fileHandle, line + "\n");
|
||||
}
|
||||
});
|
||||
|
||||
fs.closeSync(fileHandle);
|
||||
}
|
||||
});
|
51
src/app.ts
51
src/app.ts
@ -1,44 +1,65 @@
|
||||
import express from "express";
|
||||
|
||||
import bodyParser from "body-parser";
|
||||
import { unknownEndpointHandler } from "@/src/middleware/middleware";
|
||||
import { requestLogger } from "@/src/middleware/morgenMiddleware";
|
||||
import { errorHandler } from "@/src/middleware/errorHandler";
|
||||
|
||||
import { apiRouter } from "@/src/routes/api";
|
||||
//import { testRouter } from "@/src/routes/test";
|
||||
import { cacheRouter } from "@/src/routes/cache";
|
||||
import bodyParser from "body-parser";
|
||||
|
||||
import { steamPacksController } from "@/src/controllers/misc/steamPacksController";
|
||||
import { customRouter } from "@/src/routes/custom";
|
||||
import { dynamicController } from "@/src/routes/dynamic";
|
||||
import { payRouter } from "@/src/routes/pay";
|
||||
import { statsRouter } from "@/src/routes/stats";
|
||||
import { webuiRouter } from "@/src/routes/webui";
|
||||
import { connectDatabase } from "@/src/services/mongoService";
|
||||
import { registerLogFileCreationListener } from "@/src/utils/logger";
|
||||
import * as zlib from "zlib";
|
||||
|
||||
void registerLogFileCreationListener();
|
||||
void connectDatabase();
|
||||
|
||||
const app = express();
|
||||
|
||||
app.use((req, _res, next) => {
|
||||
// 38.5.0 introduced "ezip" for encrypted body blobs and "e" for request verification only (encrypted body blobs with no application data).
|
||||
// The bootstrapper decrypts it for us but having an unsupported Content-Encoding here would still be an issue for Express, so removing it.
|
||||
if (req.headers["content-encoding"] == "ezip" || req.headers["content-encoding"] == "e") {
|
||||
req.headers["content-encoding"] = undefined;
|
||||
}
|
||||
next();
|
||||
app.use(function (req, _res, next) {
|
||||
const buffer: Buffer[] = [];
|
||||
req.on("data", function (chunk: Buffer) {
|
||||
if (chunk !== undefined && chunk.length > 2 && chunk[0] == 0x1f && chunk[1] == 0x8b) {
|
||||
buffer.push(Buffer.from(chunk));
|
||||
}
|
||||
});
|
||||
|
||||
req.on("end", function () {
|
||||
zlib.gunzip(Buffer.concat(buffer), function (_err, dezipped) {
|
||||
if (typeof dezipped != "undefined") {
|
||||
req.body = dezipped.toString("utf-8");
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
app.use(bodyParser.raw());
|
||||
app.use(express.json({ limit: "4mb" }));
|
||||
app.use(bodyParser.text({ limit: "4mb" }));
|
||||
app.use(express.json());
|
||||
app.use(bodyParser.text());
|
||||
app.use(requestLogger);
|
||||
//app.use(requestLogger);
|
||||
|
||||
app.use("/api", apiRouter);
|
||||
//app.use("/test", testRouter);
|
||||
app.use("/", cacheRouter);
|
||||
app.use("/custom", customRouter);
|
||||
app.use("/dynamic", dynamicController);
|
||||
app.use("/:id/dynamic", dynamicController);
|
||||
app.use("/pay", payRouter);
|
||||
|
||||
app.post("/pay/steamPacks.php", steamPacksController);
|
||||
app.use("/stats", statsRouter);
|
||||
|
||||
app.use("/", webuiRouter);
|
||||
|
||||
app.use(unknownEndpointHandler);
|
||||
app.use(errorHandler);
|
||||
|
||||
//app.use(errorHandler)
|
||||
|
||||
export { app };
|
||||
|
@ -2,18 +2,15 @@ const millisecondsPerSecond = 1000;
|
||||
const secondsPerMinute = 60;
|
||||
const minutesPerHour = 60;
|
||||
const hoursPerDay = 24;
|
||||
const daysPerWeek = 7;
|
||||
|
||||
const unixSecond = millisecondsPerSecond;
|
||||
const unixMinute = secondsPerMinute * millisecondsPerSecond;
|
||||
const unixHour = unixMinute * minutesPerHour;
|
||||
const unixDay = hoursPerDay * unixHour;
|
||||
const unixWeek = daysPerWeek * unixDay;
|
||||
|
||||
export const unixTimesInMs = {
|
||||
second: unixSecond,
|
||||
minute: unixMinute,
|
||||
hour: unixHour,
|
||||
day: unixDay,
|
||||
week: unixWeek
|
||||
day: unixDay
|
||||
};
|
||||
|
@ -1,11 +0,0 @@
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const abandonLibraryDailyTaskController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.LibraryActiveDailyTaskInfo = undefined;
|
||||
await inventory.save();
|
||||
res.status(200).end();
|
||||
};
|
@ -1,46 +0,0 @@
|
||||
import {
|
||||
getDojoClient,
|
||||
getGuildForRequestEx,
|
||||
hasAccessToDojo,
|
||||
hasGuildPermission,
|
||||
removeDojoDeco,
|
||||
removeDojoRoom
|
||||
} from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const abortDojoComponentController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId LevelKeys");
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
const request = JSON.parse(String(req.body)) as IAbortDojoComponentRequest;
|
||||
|
||||
if (
|
||||
!hasAccessToDojo(inventory) ||
|
||||
!(await hasGuildPermission(
|
||||
guild,
|
||||
accountId,
|
||||
request.DecoId ? GuildPermission.Decorator : GuildPermission.Architect
|
||||
))
|
||||
) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.DecoId) {
|
||||
removeDojoDeco(guild, request.ComponentId, request.DecoId);
|
||||
} else {
|
||||
await removeDojoRoom(guild, request.ComponentId);
|
||||
}
|
||||
|
||||
await guild.save();
|
||||
res.json(await getDojoClient(guild, 0, request.ComponentId));
|
||||
};
|
||||
|
||||
interface IAbortDojoComponentRequest {
|
||||
DecoType?: string;
|
||||
ComponentId: string;
|
||||
DecoId?: string;
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
import { getDojoClient, getGuildForRequestEx, hasAccessToDojo, hasGuildPermission } from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const abortDojoComponentDestructionController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId LevelKeys");
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Architect))) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
const componentId = req.query.componentId as string;
|
||||
|
||||
guild.DojoComponents.id(componentId)!.DestructionTime = undefined;
|
||||
|
||||
await guild.save();
|
||||
res.json(await getDojoClient(guild, 0, componentId));
|
||||
};
|
@ -1,40 +0,0 @@
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { createVeiledRivenFingerprint, rivenRawToRealWeighted } from "@/src/helpers/rivenHelper";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addMods, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getRandomElement } from "@/src/services/rngService";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportUpgrades } from "warframe-public-export-plus";
|
||||
|
||||
export const activateRandomModController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const request = getJSONfromString<IActiveRandomModRequest>(String(req.body));
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: request.ItemType,
|
||||
ItemCount: -1
|
||||
}
|
||||
]);
|
||||
const rivenType = getRandomElement(rivenRawToRealWeighted[request.ItemType])!;
|
||||
const fingerprint = createVeiledRivenFingerprint(ExportUpgrades[rivenType]);
|
||||
const upgradeIndex =
|
||||
inventory.Upgrades.push({
|
||||
ItemType: rivenType,
|
||||
UpgradeFingerprint: JSON.stringify(fingerprint)
|
||||
}) - 1;
|
||||
await inventory.save();
|
||||
// For some reason, in this response, the UpgradeFingerprint is simply a nested object and not a string
|
||||
res.json({
|
||||
NewMod: {
|
||||
UpgradeFingerprint: fingerprint,
|
||||
ItemType: rivenType,
|
||||
ItemId: toOid(inventory.Upgrades[upgradeIndex]._id)
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
interface IActiveRandomModRequest {
|
||||
ItemType: string;
|
||||
}
|
@ -1,25 +1,17 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { IUpdateGlyphRequest } from "@/src/types/requestTypes";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { Inventory } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
|
||||
export const addFriendImageController: RequestHandler = async (req, res) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const addFriendImageController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const json = getJSONfromString<IUpdateGlyphRequest>(String(req.body));
|
||||
|
||||
await Inventory.updateOne(
|
||||
{
|
||||
accountOwnerId: accountId
|
||||
},
|
||||
{
|
||||
ActiveAvatarImageType: json.AvatarImageType
|
||||
}
|
||||
);
|
||||
|
||||
const json = getJSONfromString(String(req.body)) as IUpdateGlyphRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.ActiveAvatarImageType = json.AvatarImageType;
|
||||
await inventory.save();
|
||||
res.json({});
|
||||
};
|
||||
|
||||
interface IUpdateGlyphRequest {
|
||||
AvatarImageType: string;
|
||||
AvatarImage: string;
|
||||
}
|
||||
export { addFriendImageController };
|
||||
|
@ -1,30 +0,0 @@
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Account, Ignore } from "@/src/models/loginModel";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IFriendInfo } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const addIgnoredUserController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const data = getJSONfromString<IAddIgnoredUserRequest>(String(req.body));
|
||||
const ignoreeAccount = await Account.findOne(
|
||||
{ DisplayName: data.playerName.substring(0, data.playerName.length - 1) },
|
||||
"_id"
|
||||
);
|
||||
if (ignoreeAccount) {
|
||||
await Ignore.create({ ignorer: accountId, ignoree: ignoreeAccount._id });
|
||||
res.json({
|
||||
Ignored: {
|
||||
_id: toOid(ignoreeAccount._id),
|
||||
DisplayName: data.playerName
|
||||
} satisfies IFriendInfo
|
||||
});
|
||||
} else {
|
||||
res.status(400).end();
|
||||
}
|
||||
};
|
||||
|
||||
interface IAddIgnoredUserRequest {
|
||||
playerName: string;
|
||||
}
|
@ -1,117 +0,0 @@
|
||||
import { getJSONfromString, regexEscape } from "@/src/helpers/stringHelpers";
|
||||
import { Alliance, AllianceMember, Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { createMessage } from "@/src/services/inboxService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountForRequest, getSuffixedName } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportFlavour } from "warframe-public-export-plus";
|
||||
|
||||
export const addToAllianceController: RequestHandler = async (req, res) => {
|
||||
// Check requester is a warlord in their guild
|
||||
const account = await getAccountForRequest(req);
|
||||
const guildMember = (await GuildMember.findOne({ accountId: account._id, status: 0 }))!;
|
||||
if (guildMember.rank > 1) {
|
||||
res.status(400).json({ Error: 104 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Check guild has invite permissions in the alliance
|
||||
const allianceMember = (await AllianceMember.findOne({
|
||||
allianceId: req.query.allianceId,
|
||||
guildId: guildMember.guildId
|
||||
}))!;
|
||||
if (!(allianceMember.Permissions & GuildPermission.Recruiter)) {
|
||||
res.status(400).json({ Error: 104 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Find clan to invite
|
||||
const payload = getJSONfromString<IAddToAllianceRequest>(String(req.body));
|
||||
const guilds = await Guild.find(
|
||||
{
|
||||
Name:
|
||||
payload.clanName.indexOf("#") == -1
|
||||
? new RegExp("^" + regexEscape(payload.clanName) + "#...$")
|
||||
: payload.clanName
|
||||
},
|
||||
"Name"
|
||||
);
|
||||
if (guilds.length == 0) {
|
||||
res.status(400).json({ Error: 101 });
|
||||
return;
|
||||
}
|
||||
if (guilds.length > 1) {
|
||||
const choices: IGuildChoice[] = [];
|
||||
for (const guild of guilds) {
|
||||
choices.push({
|
||||
OriginalPlatform: 0,
|
||||
Name: guild.Name
|
||||
});
|
||||
}
|
||||
res.json(choices);
|
||||
return;
|
||||
}
|
||||
|
||||
// Add clan as a pending alliance member
|
||||
try {
|
||||
await AllianceMember.insertOne({
|
||||
allianceId: req.query.allianceId,
|
||||
guildId: guilds[0]._id,
|
||||
Pending: true,
|
||||
Permissions: 0
|
||||
});
|
||||
} catch (e) {
|
||||
logger.debug(`alliance invite failed due to ${String(e)}`);
|
||||
res.status(400).json({ Error: 102 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Send inbox message to founding warlord
|
||||
// TOVERIFY: Should other warlords get this as well?
|
||||
// TOVERIFY: Who/what should the sender be?
|
||||
// TOVERIFY: Should this message be highPriority?
|
||||
const invitedClanOwnerMember = (await GuildMember.findOne({ guildId: guilds[0]._id, rank: 0 }))!;
|
||||
const senderInventory = await getInventory(account._id.toString(), "ActiveAvatarImageType");
|
||||
const senderGuild = (await Guild.findById(allianceMember.guildId, "Name"))!;
|
||||
const alliance = (await Alliance.findById(req.query.allianceId, "Name"))!;
|
||||
await createMessage(invitedClanOwnerMember.accountId, [
|
||||
{
|
||||
sndr: getSuffixedName(account),
|
||||
msg: "/Lotus/Language/Menu/Mailbox_AllianceInvite_Body",
|
||||
arg: [
|
||||
{
|
||||
Key: "THEIR_CLAN",
|
||||
Tag: senderGuild.Name
|
||||
},
|
||||
{
|
||||
Key: "CLAN",
|
||||
Tag: guilds[0].Name
|
||||
},
|
||||
{
|
||||
Key: "ALLIANCE",
|
||||
Tag: alliance.Name
|
||||
}
|
||||
],
|
||||
sub: "/Lotus/Language/Menu/Mailbox_AllianceInvite_Title",
|
||||
icon: ExportFlavour[senderInventory.ActiveAvatarImageType].icon,
|
||||
contextInfo: alliance._id.toString(),
|
||||
highPriority: true,
|
||||
acceptAction: "ALLIANCE_INVITE",
|
||||
declineAction: "ALLIANCE_INVITE",
|
||||
hasAccountAction: true
|
||||
}
|
||||
]);
|
||||
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface IAddToAllianceRequest {
|
||||
clanName: string;
|
||||
}
|
||||
|
||||
interface IGuildChoice {
|
||||
OriginalPlatform: number;
|
||||
Name: string;
|
||||
}
|
@ -1,105 +0,0 @@
|
||||
import { Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { Account } from "@/src/models/loginModel";
|
||||
import { fillInInventoryDataForGuildMember, hasGuildPermission } from "@/src/services/guildService";
|
||||
import { createMessage } from "@/src/services/inboxService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountForRequest, getAccountIdForRequest, getSuffixedName } from "@/src/services/loginService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import { GuildPermission, IGuildMemberClient } from "@/src/types/guildTypes";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportFlavour } from "warframe-public-export-plus";
|
||||
|
||||
export const addToGuildController: RequestHandler = async (req, res) => {
|
||||
const payload = JSON.parse(String(req.body)) as IAddToGuildRequest;
|
||||
|
||||
if ("UserName" in payload) {
|
||||
// Clan recruiter sending an invite
|
||||
|
||||
const account = await Account.findOne({ DisplayName: payload.UserName });
|
||||
if (!account) {
|
||||
res.status(400).json("Username does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
const inventory = await getInventory(account._id.toString(), "Settings");
|
||||
// TODO: Also consider GIFT_MODE_FRIENDS once friends are implemented
|
||||
if (inventory.Settings?.GuildInvRestriction == "GIFT_MODE_NONE") {
|
||||
res.status(400).json("Invite restricted");
|
||||
return;
|
||||
}
|
||||
|
||||
const guild = (await Guild.findById(payload.GuildId.$oid, "Name Ranks"))!;
|
||||
const senderAccount = await getAccountForRequest(req);
|
||||
if (!(await hasGuildPermission(guild, senderAccount._id.toString(), GuildPermission.Recruiter))) {
|
||||
res.status(400).json("Invalid permission");
|
||||
}
|
||||
|
||||
try {
|
||||
await GuildMember.insertOne({
|
||||
accountId: account._id,
|
||||
guildId: payload.GuildId.$oid,
|
||||
status: 2 // outgoing invite
|
||||
});
|
||||
} catch (e) {
|
||||
logger.debug(`guild invite failed due to ${String(e)}`);
|
||||
res.status(400).json("User already invited to clan");
|
||||
return;
|
||||
}
|
||||
|
||||
const senderInventory = await getInventory(senderAccount._id.toString(), "ActiveAvatarImageType");
|
||||
await createMessage(account._id, [
|
||||
{
|
||||
sndr: getSuffixedName(senderAccount),
|
||||
msg: "/Lotus/Language/Menu/Mailbox_ClanInvite_Body",
|
||||
arg: [
|
||||
{
|
||||
Key: "clan",
|
||||
Tag: guild.Name
|
||||
}
|
||||
],
|
||||
sub: "/Lotus/Language/Menu/Mailbox_ClanInvite_Title",
|
||||
icon: ExportFlavour[senderInventory.ActiveAvatarImageType].icon,
|
||||
contextInfo: payload.GuildId.$oid,
|
||||
highPriority: true,
|
||||
acceptAction: "GUILD_INVITE",
|
||||
declineAction: "GUILD_INVITE",
|
||||
hasAccountAction: true
|
||||
}
|
||||
]);
|
||||
|
||||
const member: IGuildMemberClient = {
|
||||
_id: { $oid: account._id.toString() },
|
||||
DisplayName: account.DisplayName,
|
||||
Rank: 7,
|
||||
Status: 2
|
||||
};
|
||||
await fillInInventoryDataForGuildMember(member);
|
||||
res.json({ NewMember: member });
|
||||
} else if ("RequestMsg" in payload) {
|
||||
// Player applying to join a clan
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
try {
|
||||
await GuildMember.insertOne({
|
||||
accountId,
|
||||
guildId: payload.GuildId.$oid,
|
||||
status: 1, // incoming invite
|
||||
RequestMsg: payload.RequestMsg,
|
||||
RequestExpiry: new Date(Date.now() + 14 * 86400 * 1000) // TOVERIFY: I can't find any good information about this with regards to live, but 2 weeks seem reasonable.
|
||||
});
|
||||
} catch (e) {
|
||||
logger.debug(`guild invite failed due to ${String(e)}`);
|
||||
res.status(400).send("Already requested");
|
||||
}
|
||||
res.end();
|
||||
} else {
|
||||
logger.error(`data provided to ${req.path}: ${String(req.body)}`);
|
||||
res.status(400).end();
|
||||
}
|
||||
};
|
||||
|
||||
interface IAddToGuildRequest {
|
||||
UserName?: string;
|
||||
GuildId: IOid;
|
||||
RequestMsg?: string;
|
||||
}
|
@ -1,76 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory, addMods } from "@/src/services/inventoryService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
|
||||
export const arcaneCommonController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const json = getJSONfromString<IArcaneCommonRequest>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
const upgrade = inventory.Upgrades.id(json.arcane.ItemId.$oid);
|
||||
if (json.newRank == -1) {
|
||||
// Break down request?
|
||||
if (!upgrade || !upgrade.UpgradeFingerprint) {
|
||||
throw new Error(`Failed to find upgrade with OID ${json.arcane.ItemId.$oid}`);
|
||||
}
|
||||
|
||||
// Remove Upgrade
|
||||
inventory.Upgrades.pull({ _id: json.arcane.ItemId.$oid });
|
||||
|
||||
// Add RawUpgrades
|
||||
const numRawUpgradesToGive = arcaneLevelCounts[(JSON.parse(upgrade.UpgradeFingerprint) as { lvl: number }).lvl];
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: json.arcane.ItemType,
|
||||
ItemCount: numRawUpgradesToGive
|
||||
}
|
||||
]);
|
||||
|
||||
res.json({ upgradeId: json.arcane.ItemId.$oid, numConsumed: numRawUpgradesToGive });
|
||||
} else {
|
||||
// Upgrade request?
|
||||
let numConsumed = arcaneLevelCounts[json.newRank];
|
||||
let upgradeId = json.arcane.ItemId.$oid;
|
||||
if (upgrade) {
|
||||
// Have an existing Upgrade item?
|
||||
if (upgrade.UpgradeFingerprint) {
|
||||
const existingLevel = (JSON.parse(upgrade.UpgradeFingerprint) as { lvl: number }).lvl;
|
||||
numConsumed -= arcaneLevelCounts[existingLevel];
|
||||
}
|
||||
upgrade.UpgradeFingerprint = JSON.stringify({ lvl: json.newRank });
|
||||
} else {
|
||||
const newLength = inventory.Upgrades.push({
|
||||
ItemType: json.arcane.ItemType,
|
||||
UpgradeFingerprint: JSON.stringify({ lvl: json.newRank })
|
||||
});
|
||||
upgradeId = inventory.Upgrades[newLength - 1]._id.toString();
|
||||
}
|
||||
|
||||
// Remove RawUpgrades
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: json.arcane.ItemType,
|
||||
ItemCount: numConsumed * -1
|
||||
}
|
||||
]);
|
||||
|
||||
res.json({ newLevel: json.newRank, numConsumed, upgradeId });
|
||||
}
|
||||
await inventory.save();
|
||||
};
|
||||
|
||||
const arcaneLevelCounts = [0, 3, 6, 10, 15, 21];
|
||||
|
||||
interface IArcaneCommonRequest {
|
||||
arcane: {
|
||||
ItemType: string;
|
||||
ItemId: IOid;
|
||||
FromSKU: boolean;
|
||||
UpgradeFingerprint: string;
|
||||
PendingRerollFingerprint: string;
|
||||
ItemCount: number;
|
||||
LastAdded: IOid;
|
||||
};
|
||||
newRank: number;
|
||||
}
|
@ -1,51 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { addMiscItems, getInventory } from "@/src/services/inventoryService";
|
||||
import { IMiscItem } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { colorToShard, combineColors, shardToColor } from "@/src/helpers/shardHelper";
|
||||
|
||||
export const archonFusionController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const request = JSON.parse(String(req.body)) as IArchonFusionRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
request.Consumed.forEach(x => {
|
||||
x.ItemCount *= -1;
|
||||
});
|
||||
addMiscItems(inventory, request.Consumed);
|
||||
const newArchons: IMiscItem[] = [];
|
||||
switch (request.FusionType) {
|
||||
case "AFT_ASCENT":
|
||||
newArchons.push({
|
||||
ItemType: request.Consumed[0].ItemType + "Mythic",
|
||||
ItemCount: 1
|
||||
});
|
||||
break;
|
||||
|
||||
case "AFT_COALESCENT":
|
||||
newArchons.push({
|
||||
ItemType:
|
||||
colorToShard[
|
||||
combineColors(
|
||||
shardToColor[request.Consumed[0].ItemType],
|
||||
shardToColor[request.Consumed[1].ItemType]
|
||||
)
|
||||
],
|
||||
ItemCount: 1
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`unknown archon fusion type: ${request.FusionType}`);
|
||||
}
|
||||
addMiscItems(inventory, newArchons);
|
||||
await inventory.save();
|
||||
res.json({
|
||||
NewArchons: newArchons
|
||||
});
|
||||
};
|
||||
|
||||
interface IArchonFusionRequest {
|
||||
Consumed: IMiscItem[];
|
||||
FusionType: string;
|
||||
StatResultType: "SRT_NEW_STAT"; // ???
|
||||
}
|
@ -1,178 +0,0 @@
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { createVeiledRivenFingerprint, rivenRawToRealWeighted } from "@/src/helpers/rivenHelper";
|
||||
import { addMiscItems, addMods, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getRandomElement, getRandomWeightedReward, getRandomWeightedRewardUc } from "@/src/services/rngService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportBoosterPacks, ExportUpgrades, TRarity } from "warframe-public-export-plus";
|
||||
|
||||
export const artifactTransmutationController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const payload = JSON.parse(String(req.body)) as IArtifactTransmutationRequest;
|
||||
|
||||
inventory.RegularCredits -= payload.Cost;
|
||||
inventory.FusionPoints -= payload.FusionPointCost;
|
||||
|
||||
if (payload.RivenTransmute) {
|
||||
addMiscItems(inventory, [
|
||||
{
|
||||
ItemType: "/Lotus/Types/Gameplay/Eidolon/Resources/SentientSecretItem",
|
||||
ItemCount: -1
|
||||
}
|
||||
]);
|
||||
|
||||
payload.Consumed.forEach(upgrade => {
|
||||
inventory.Upgrades.pull({ _id: upgrade.ItemId.$oid });
|
||||
});
|
||||
|
||||
const rawRivenType = getRandomRawRivenType();
|
||||
const rivenType = getRandomElement(rivenRawToRealWeighted[rawRivenType])!;
|
||||
const fingerprint = createVeiledRivenFingerprint(ExportUpgrades[rivenType]);
|
||||
|
||||
const upgradeIndex =
|
||||
inventory.Upgrades.push({
|
||||
ItemType: rivenType,
|
||||
UpgradeFingerprint: JSON.stringify(fingerprint)
|
||||
}) - 1;
|
||||
await inventory.save();
|
||||
res.json({
|
||||
NewMods: [
|
||||
{
|
||||
ItemId: toOid(inventory.Upgrades[upgradeIndex]._id),
|
||||
ItemType: rivenType,
|
||||
UpgradeFingerprint: fingerprint
|
||||
}
|
||||
]
|
||||
});
|
||||
} else {
|
||||
const counts: Record<TRarity, number> = {
|
||||
COMMON: 0,
|
||||
UNCOMMON: 0,
|
||||
RARE: 0,
|
||||
LEGENDARY: 0
|
||||
};
|
||||
let forcedPolarity: string | undefined;
|
||||
payload.Consumed.forEach(upgrade => {
|
||||
const meta = ExportUpgrades[upgrade.ItemType];
|
||||
counts[meta.rarity] += upgrade.ItemCount;
|
||||
if (upgrade.ItemId.$oid != "000000000000000000000000") {
|
||||
inventory.Upgrades.pull({ _id: upgrade.ItemId.$oid });
|
||||
} else {
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: upgrade.ItemType,
|
||||
ItemCount: upgrade.ItemCount * -1
|
||||
}
|
||||
]);
|
||||
}
|
||||
if (upgrade.ItemType == "/Lotus/Upgrades/Mods/TransmuteCores/AttackTransmuteCore") {
|
||||
forcedPolarity = "AP_ATTACK";
|
||||
} else if (upgrade.ItemType == "/Lotus/Upgrades/Mods/TransmuteCores/DefenseTransmuteCore") {
|
||||
forcedPolarity = "AP_DEFENSE";
|
||||
} else if (upgrade.ItemType == "/Lotus/Upgrades/Mods/TransmuteCores/TacticTransmuteCore") {
|
||||
forcedPolarity = "AP_TACTIC";
|
||||
}
|
||||
});
|
||||
|
||||
let newModType: string | undefined;
|
||||
for (const specialModSet of specialModSets) {
|
||||
if (specialModSet.indexOf(payload.Consumed[0].ItemType) != -1) {
|
||||
newModType = getRandomElement(specialModSet);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!newModType) {
|
||||
// Based on the table on https://wiki.warframe.com/w/Transmutation
|
||||
const weights: Record<TRarity, number> = {
|
||||
COMMON: counts.COMMON * 95 + counts.UNCOMMON * 15 + counts.RARE * 4,
|
||||
UNCOMMON: counts.COMMON * 4 + counts.UNCOMMON * 80 + counts.RARE * 10,
|
||||
RARE: counts.COMMON * 1 + counts.UNCOMMON * 5 + counts.RARE * 50,
|
||||
LEGENDARY: 0
|
||||
};
|
||||
|
||||
const options: { uniqueName: string; rarity: TRarity }[] = [];
|
||||
Object.entries(ExportUpgrades).forEach(([uniqueName, upgrade]) => {
|
||||
if (upgrade.canBeTransmutation && (!forcedPolarity || upgrade.polarity == forcedPolarity)) {
|
||||
options.push({ uniqueName, rarity: upgrade.rarity });
|
||||
}
|
||||
});
|
||||
|
||||
newModType = getRandomWeightedReward(options, weights)!.uniqueName;
|
||||
}
|
||||
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: newModType,
|
||||
ItemCount: 1
|
||||
}
|
||||
]);
|
||||
|
||||
await inventory.save();
|
||||
res.json({
|
||||
NewMods: [
|
||||
{
|
||||
ItemType: newModType,
|
||||
ItemCount: 1
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getRandomRawRivenType = (): string => {
|
||||
const pack = ExportBoosterPacks["/Lotus/Types/BoosterPacks/CalendarRivenPack"];
|
||||
return getRandomWeightedRewardUc(pack.components, pack.rarityWeightsPerRoll[0])!.Item;
|
||||
};
|
||||
|
||||
interface IArtifactTransmutationRequest {
|
||||
Upgrade: IAgnosticUpgradeClient;
|
||||
LevelDiff: number;
|
||||
Consumed: IAgnosticUpgradeClient[];
|
||||
Cost: number;
|
||||
FusionPointCost: number;
|
||||
RivenTransmute?: boolean;
|
||||
}
|
||||
|
||||
interface IAgnosticUpgradeClient {
|
||||
ItemType: string;
|
||||
ItemId: IOid;
|
||||
FromSKU: boolean;
|
||||
UpgradeFingerprint: string;
|
||||
PendingRerollFingerprint: string;
|
||||
ItemCount: number;
|
||||
LastAdded: IOid;
|
||||
}
|
||||
|
||||
const specialModSets: string[][] = [
|
||||
[
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalOneMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalTwoMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalThreeMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalFourMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalFiveMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalSixMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalSevenMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalEightMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/ImmortalWildcardMod"
|
||||
],
|
||||
[
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusOneMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusTwoMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusThreeMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusFourMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusFiveMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusSixMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusSevenMod",
|
||||
"/Lotus/Upgrades/Mods/Immortal/AntivirusEightMod"
|
||||
],
|
||||
[
|
||||
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndSpeedOnUseMod",
|
||||
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusAndWeaponDamageOnUseMod",
|
||||
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusLargeOnSingleUseMod",
|
||||
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusOnUseMod",
|
||||
"/Lotus/Upgrades/Mods/DataSpike/Potency/GainAntivirusSmallOnSingleUseMod"
|
||||
]
|
||||
];
|
@ -1,70 +1,22 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { upgradeMod } from "@/src/services/inventoryService";
|
||||
import { IArtifactsRequest } from "@/src/types/requestTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { IInventoryClient, IUpgradeClient } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { addMods, getInventory } from "@/src/services/inventoryService";
|
||||
import { config } from "@/src/services/configService";
|
||||
|
||||
export const artifactsController: RequestHandler = async (req, res) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const artifactsController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const artifactsData = getJSONfromString<IArtifactsRequest>(String(req.body));
|
||||
|
||||
const { Upgrade, LevelDiff, Cost, FusionPointCost } = artifactsData;
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
const { Upgrades } = inventory;
|
||||
const { ItemType, UpgradeFingerprint, ItemId } = Upgrade;
|
||||
|
||||
const safeUpgradeFingerprint = UpgradeFingerprint || '{"lvl":0}';
|
||||
const parsedUpgradeFingerprint = JSON.parse(safeUpgradeFingerprint) as { lvl: number };
|
||||
parsedUpgradeFingerprint.lvl += LevelDiff;
|
||||
const stringifiedUpgradeFingerprint = JSON.stringify(parsedUpgradeFingerprint);
|
||||
|
||||
let itemIndex = Upgrades.findIndex(upgrade => upgrade._id.equals(ItemId.$oid));
|
||||
|
||||
if (itemIndex !== -1) {
|
||||
Upgrades[itemIndex].UpgradeFingerprint = stringifiedUpgradeFingerprint;
|
||||
inventory.markModified(`Upgrades.${itemIndex}.UpgradeFingerprint`);
|
||||
} else {
|
||||
itemIndex =
|
||||
Upgrades.push({
|
||||
UpgradeFingerprint: stringifiedUpgradeFingerprint,
|
||||
ItemType
|
||||
}) - 1;
|
||||
|
||||
addMods(inventory, [{ ItemType, ItemCount: -1 }]);
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-call
|
||||
const artifactsData = getJSONfromString(req.body.toString()) as IArtifactsRequest;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
|
||||
const upgradeModId = await upgradeMod(artifactsData, accountId);
|
||||
res.send(upgradeModId);
|
||||
} catch (err) {
|
||||
console.error("Error parsing JSON data:", err);
|
||||
}
|
||||
|
||||
if (!config.infiniteCredits) {
|
||||
inventory.RegularCredits -= Cost;
|
||||
}
|
||||
if (!config.infiniteEndo) {
|
||||
inventory.FusionPoints -= FusionPointCost;
|
||||
}
|
||||
|
||||
if (artifactsData.LegendaryFusion) {
|
||||
addMods(inventory, [
|
||||
{
|
||||
ItemType: "/Lotus/Upgrades/Mods/Fusers/LegendaryModFuser",
|
||||
ItemCount: -1
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
const changedInventory = await inventory.save();
|
||||
const itemId = changedInventory.toJSON<IInventoryClient>().Upgrades[itemIndex].ItemId.$oid;
|
||||
|
||||
if (!itemId) {
|
||||
throw new Error("Item Id not found in upgradeMod");
|
||||
}
|
||||
|
||||
res.send(itemId);
|
||||
};
|
||||
|
||||
interface IArtifactsRequest {
|
||||
Upgrade: IUpgradeClient;
|
||||
LevelDiff: number;
|
||||
Cost: number;
|
||||
FusionPointCost: number;
|
||||
LegendaryFusion?: boolean;
|
||||
}
|
||||
export { artifactsController };
|
||||
|
@ -1,20 +0,0 @@
|
||||
import { GuildAd } from "@/src/models/guildModel";
|
||||
import { getGuildForRequestEx, hasGuildPermission } from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const cancelGuildAdvertisementController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId");
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!(await hasGuildPermission(guild, accountId, GuildPermission.Advertiser))) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
await GuildAd.deleteOne({ GuildId: guild._id });
|
||||
|
||||
res.end();
|
||||
};
|
@ -1,93 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getDojoClient, getGuildForRequestEx, hasAccessToDojo, hasGuildPermission } from "@/src/services/guildService";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { GuildPermission, IDojoComponentDatabase } from "@/src/types/guildTypes";
|
||||
import { Types } from "mongoose";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
|
||||
export const changeDojoRootController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId LevelKeys");
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Architect))) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
|
||||
// Example POST body: {"pivot":[0, 0, -64],"components":"{\"670429301ca0a63848ccc467\":{\"R\":[0,0,0],\"P\":[0,3,32]},\"6704254a1ca0a63848ccb33c\":{\"R\":[0,0,0],\"P\":[0,9.25,-32]},\"670429461ca0a63848ccc731\":{\"R\":[-90,0,0],\"P\":[-47.999992370605,3,16]}}"}
|
||||
if (req.body) {
|
||||
logger.debug(`data provided to ${req.path}: ${String(req.body)}`);
|
||||
throw new Error("dojo reparent operation should not need deco repositioning"); // because we always provide SortId
|
||||
}
|
||||
|
||||
const idToNode: Record<string, INode> = {};
|
||||
guild.DojoComponents.forEach(x => {
|
||||
idToNode[x._id.toString()] = {
|
||||
component: x,
|
||||
parent: undefined,
|
||||
children: []
|
||||
};
|
||||
});
|
||||
|
||||
let oldRoot: INode | undefined;
|
||||
guild.DojoComponents.forEach(x => {
|
||||
const node = idToNode[x._id.toString()];
|
||||
if (x.pi) {
|
||||
idToNode[x.pi.toString()].children.push(node);
|
||||
node.parent = idToNode[x.pi.toString()];
|
||||
} else {
|
||||
oldRoot = node;
|
||||
}
|
||||
});
|
||||
logger.debug("Old tree:\n" + treeToString(oldRoot!));
|
||||
|
||||
const newRoot = idToNode[req.query.newRoot as string];
|
||||
recursivelyTurnParentsIntoChildren(newRoot);
|
||||
newRoot.component.pi = undefined;
|
||||
newRoot.component.op = undefined;
|
||||
newRoot.component.pp = undefined;
|
||||
newRoot.parent = undefined;
|
||||
|
||||
// Set/update SortId in top-to-bottom order
|
||||
const stack: INode[] = [newRoot];
|
||||
while (stack.length != 0) {
|
||||
const top = stack.shift()!;
|
||||
top.component.SortId = new Types.ObjectId();
|
||||
top.children.forEach(x => stack.push(x));
|
||||
}
|
||||
|
||||
logger.debug("New tree:\n" + treeToString(newRoot));
|
||||
|
||||
await guild.save();
|
||||
|
||||
res.json(await getDojoClient(guild, 0));
|
||||
};
|
||||
|
||||
interface INode {
|
||||
component: IDojoComponentDatabase;
|
||||
parent: INode | undefined;
|
||||
children: INode[];
|
||||
}
|
||||
|
||||
const treeToString = (root: INode, depth: number = 0): string => {
|
||||
let str = " ".repeat(depth * 4) + root.component.pf + " (" + root.component._id.toString() + ")\n";
|
||||
root.children.forEach(x => {
|
||||
str += treeToString(x, depth + 1);
|
||||
});
|
||||
return str;
|
||||
};
|
||||
|
||||
const recursivelyTurnParentsIntoChildren = (node: INode): void => {
|
||||
if (node.parent!.parent) {
|
||||
recursivelyTurnParentsIntoChildren(node.parent!);
|
||||
}
|
||||
|
||||
node.parent!.component.pi = node.component._id;
|
||||
node.parent!.component.op = node.component.pp;
|
||||
node.parent!.component.pp = node.component.op;
|
||||
|
||||
node.parent!.parent = node;
|
||||
node.parent!.children.splice(node.parent!.children.indexOf(node), 1);
|
||||
node.children.push(node.parent!);
|
||||
};
|
@ -1,38 +0,0 @@
|
||||
import { GuildMember } from "@/src/models/guildModel";
|
||||
import { getGuildForRequest, hasGuildPermissionEx } from "@/src/services/guildService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const changeGuildRankController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const member = (await GuildMember.findOne({
|
||||
accountId: accountId,
|
||||
guildId: req.query.guildId as string
|
||||
}))!;
|
||||
const newRank: number = parseInt(req.query.rankChange as string);
|
||||
|
||||
const guild = await getGuildForRequest(req);
|
||||
if (newRank < member.rank || !hasGuildPermissionEx(guild, member, GuildPermission.Promoter)) {
|
||||
res.status(400).json("Invalid permission");
|
||||
return;
|
||||
}
|
||||
|
||||
const target = (await GuildMember.findOne({
|
||||
guildId: req.query.guildId as string,
|
||||
accountId: req.query.targetId as string
|
||||
}))!;
|
||||
target.rank = parseInt(req.query.rankChange as string);
|
||||
await target.save();
|
||||
|
||||
if (newRank == 0) {
|
||||
// If we just promoted someone else to Founding Warlord, we need to demote ourselves to Warlord.
|
||||
member.rank = 1;
|
||||
await member.save();
|
||||
}
|
||||
|
||||
res.json({
|
||||
_id: req.query.targetId as string,
|
||||
Rank: newRank
|
||||
});
|
||||
};
|
@ -7,143 +7,82 @@ import { getRecipe } from "@/src/services/itemDataService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import {
|
||||
getInventory,
|
||||
updateCurrency,
|
||||
addItem,
|
||||
addRecipes,
|
||||
occupySlot,
|
||||
combineInventoryChanges
|
||||
} from "@/src/services/inventoryService";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { IEquipmentClient } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
import { InventorySlot } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { getInventory, updateCurrency, addItem, addMiscItems, addRecipes } from "@/src/services/inventoryService";
|
||||
|
||||
interface IClaimCompletedRecipeRequest {
|
||||
export interface IClaimCompletedRecipeRequest {
|
||||
RecipeIds: IOid[];
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const claimCompletedRecipeController: RequestHandler = async (req, res) => {
|
||||
const claimCompletedRecipeRequest = getJSONfromString<IClaimCompletedRecipeRequest>(String(req.body));
|
||||
const claimCompletedRecipeRequest = getJSONfromString(String(req.body)) as IClaimCompletedRecipeRequest;
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
if (!accountId) throw new Error("no account id");
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
const pendingRecipe = inventory.PendingRecipes.id(claimCompletedRecipeRequest.RecipeIds[0].$oid);
|
||||
const pendingRecipe = inventory.PendingRecipes.find(
|
||||
recipe => recipe._id?.toString() === claimCompletedRecipeRequest.RecipeIds[0].$id
|
||||
);
|
||||
if (!pendingRecipe) {
|
||||
throw new Error(`no pending recipe found with id ${claimCompletedRecipeRequest.RecipeIds[0].$oid}`);
|
||||
logger.error(`no pending recipe found with id ${claimCompletedRecipeRequest.RecipeIds[0].$id}`);
|
||||
throw new Error(`no pending recipe found with id ${claimCompletedRecipeRequest.RecipeIds[0].$id}`);
|
||||
}
|
||||
|
||||
//check recipe is indeed ready to be completed
|
||||
// if (pendingRecipe.CompletionDate > new Date()) {
|
||||
// logger.error(`recipe ${pendingRecipe._id} is not ready to be completed`);
|
||||
// throw new Error(`recipe ${pendingRecipe._id} is not ready to be completed`);
|
||||
// }
|
||||
|
||||
inventory.PendingRecipes.pull(pendingRecipe._id);
|
||||
await inventory.save();
|
||||
|
||||
const recipe = getRecipe(pendingRecipe.ItemType);
|
||||
if (!recipe) {
|
||||
throw new Error(`no completed item found for recipe ${pendingRecipe._id.toString()}`);
|
||||
logger.error(`no completed item found for recipe ${pendingRecipe._id}`);
|
||||
throw new Error(`no completed item found for recipe ${pendingRecipe._id}`);
|
||||
}
|
||||
|
||||
if (req.query.cancel) {
|
||||
const inventoryChanges: IInventoryChanges = {
|
||||
...updateCurrency(inventory, recipe.buildPrice * -1, false)
|
||||
};
|
||||
|
||||
const equipmentIngredients = new Set();
|
||||
for (const category of ["LongGuns", "Pistols", "Melee"] as const) {
|
||||
if (pendingRecipe[category]) {
|
||||
pendingRecipe[category].forEach(item => {
|
||||
const index = inventory[category].push(item) - 1;
|
||||
inventoryChanges[category] ??= [];
|
||||
inventoryChanges[category].push(inventory[category][index].toJSON<IEquipmentClient>());
|
||||
equipmentIngredients.add(item.ItemType);
|
||||
|
||||
occupySlot(inventory, InventorySlot.WEAPONS, false);
|
||||
inventoryChanges.WeaponBin ??= { Slots: 0 };
|
||||
inventoryChanges.WeaponBin.Slots -= 1;
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const ingredient of recipe.ingredients) {
|
||||
if (!equipmentIngredients.has(ingredient.ItemType)) {
|
||||
combineInventoryChanges(
|
||||
inventoryChanges,
|
||||
await addItem(inventory, ingredient.ItemType, ingredient.ItemCount)
|
||||
);
|
||||
}
|
||||
}
|
||||
const currencyChanges = await updateCurrency(recipe.buildPrice * -1, false, accountId);
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
addMiscItems(inventory, recipe.ingredients);
|
||||
await inventory.save();
|
||||
res.json(inventoryChanges); // Not a bug: In the specific case of cancelling a recipe, InventoryChanges are expected to be the root.
|
||||
|
||||
// Not a bug: In the specific case of cancelling a recipe, InventoryChanges are expected to be the root.
|
||||
res.json({
|
||||
...currencyChanges,
|
||||
MiscItems: recipe.ingredients
|
||||
});
|
||||
} else {
|
||||
logger.debug("Claiming Recipe", { recipe, pendingRecipe });
|
||||
|
||||
let BrandedSuits: undefined | IOid[];
|
||||
if (recipe.secretIngredientAction == "SIA_SPECTRE_LOADOUT_COPY") {
|
||||
inventory.PendingSpectreLoadouts ??= [];
|
||||
inventory.SpectreLoadouts ??= [];
|
||||
|
||||
const pendingLoadoutIndex = inventory.PendingSpectreLoadouts.findIndex(
|
||||
x => x.ItemType == recipe.resultType
|
||||
);
|
||||
if (pendingLoadoutIndex != -1) {
|
||||
const loadoutIndex = inventory.SpectreLoadouts.findIndex(x => x.ItemType == recipe.resultType);
|
||||
if (loadoutIndex != -1) {
|
||||
inventory.SpectreLoadouts.splice(loadoutIndex, 1);
|
||||
}
|
||||
logger.debug(
|
||||
"moving spectre loadout from pending to active",
|
||||
inventory.toJSON().PendingSpectreLoadouts![pendingLoadoutIndex]
|
||||
);
|
||||
inventory.SpectreLoadouts.push(inventory.PendingSpectreLoadouts[pendingLoadoutIndex]);
|
||||
inventory.PendingSpectreLoadouts.splice(pendingLoadoutIndex, 1);
|
||||
}
|
||||
} else if (recipe.secretIngredientAction == "SIA_UNBRAND") {
|
||||
inventory.BrandedSuits!.splice(
|
||||
inventory.BrandedSuits!.findIndex(x => x.equals(pendingRecipe.SuitToUnbrand)),
|
||||
1
|
||||
);
|
||||
BrandedSuits = [toOid(pendingRecipe.SuitToUnbrand!)];
|
||||
}
|
||||
|
||||
let InventoryChanges: IInventoryChanges = {};
|
||||
let InventoryChanges = {};
|
||||
if (recipe.consumeOnUse) {
|
||||
addRecipes(inventory, [
|
||||
const recipeChanges = [
|
||||
{
|
||||
ItemType: pendingRecipe.ItemType,
|
||||
ItemCount: -1
|
||||
}
|
||||
]);
|
||||
];
|
||||
|
||||
InventoryChanges = { ...InventoryChanges, Recipes: recipeChanges };
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
addRecipes(inventory, recipeChanges);
|
||||
await inventory.save();
|
||||
}
|
||||
if (req.query.rush) {
|
||||
const end = Math.trunc(pendingRecipe.CompletionDate.getTime() / 1000);
|
||||
const start = end - recipe.buildTime;
|
||||
const secondsElapsed = Math.trunc(Date.now() / 1000) - start;
|
||||
const progress = secondsElapsed / recipe.buildTime;
|
||||
logger.debug(`rushing recipe at ${Math.trunc(progress * 100)}% completion`);
|
||||
const cost = Math.round(recipe.skipBuildTimePrice * (1 - (progress - 0.5)));
|
||||
InventoryChanges = {
|
||||
...InventoryChanges,
|
||||
...updateCurrency(inventory, cost, true)
|
||||
...(await updateCurrency(recipe.skipBuildTimePrice, true, accountId))
|
||||
};
|
||||
}
|
||||
if (recipe.secretIngredientAction != "SIA_UNBRAND") {
|
||||
InventoryChanges = {
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
...InventoryChanges,
|
||||
...(await addItem(
|
||||
inventory,
|
||||
recipe.resultType,
|
||||
recipe.num,
|
||||
false,
|
||||
undefined,
|
||||
pendingRecipe.TargetFingerprint
|
||||
))
|
||||
};
|
||||
}
|
||||
await inventory.save();
|
||||
res.json({ InventoryChanges, BrandedSuits });
|
||||
...(await addItem(accountId, recipe.resultType, recipe.num)).InventoryChanges
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
@ -1,31 +0,0 @@
|
||||
import { addFusionPoints, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const claimLibraryDailyTaskRewardController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
|
||||
const rewardQuantity = inventory.LibraryActiveDailyTaskInfo!.RewardQuantity;
|
||||
const rewardStanding = inventory.LibraryActiveDailyTaskInfo!.RewardStanding;
|
||||
inventory.LibraryActiveDailyTaskInfo = undefined;
|
||||
inventory.LibraryAvailableDailyTaskInfo = undefined;
|
||||
|
||||
let syndicate = inventory.Affiliations.find(x => x.Tag == "LibrarySyndicate");
|
||||
if (!syndicate) {
|
||||
syndicate = inventory.Affiliations[inventory.Affiliations.push({ Tag: "LibrarySyndicate", Standing: 0 }) - 1];
|
||||
}
|
||||
syndicate.Standing += rewardStanding;
|
||||
|
||||
addFusionPoints(inventory, 80 * rewardQuantity);
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
RewardItem: "/Lotus/StoreItems/Upgrades/Mods/FusionBundles/RareFusionBundle",
|
||||
RewardQuantity: rewardQuantity,
|
||||
StandingAwarded: rewardStanding,
|
||||
InventoryChanges: {
|
||||
FusionPoints: 80 * rewardQuantity
|
||||
}
|
||||
});
|
||||
};
|
@ -1,25 +0,0 @@
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const clearDialogueHistoryController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const request = JSON.parse(String(req.body)) as IClearDialogueRequest;
|
||||
if (inventory.DialogueHistory && inventory.DialogueHistory.Dialogues) {
|
||||
inventory.DialogueHistory.Resets ??= 0;
|
||||
inventory.DialogueHistory.Resets += 1;
|
||||
for (const dialogueName of request.Dialogues) {
|
||||
const index = inventory.DialogueHistory.Dialogues.findIndex(x => x.DialogueName == dialogueName);
|
||||
if (index != -1) {
|
||||
inventory.DialogueHistory.Dialogues.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
await inventory.save();
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface IClearDialogueRequest {
|
||||
Dialogues: string[];
|
||||
}
|
@ -1,6 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
// example req.body: {"NewEpisodeReward":true,"crossPlaySetting":"ENABLED"}
|
||||
export const clearNewEpisodeRewardController: RequestHandler = (_req, res) => {
|
||||
res.status(200).end();
|
||||
};
|
@ -1,41 +0,0 @@
|
||||
import { getCalendarProgress, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { handleStoreItemAcquisition } from "@/src/services/purchaseService";
|
||||
import { getWorldState } from "@/src/services/worldStateService";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
// GET request; query parameters: CompletedEventIdx=0&Iteration=4&Version=19&Season=CST_SUMMER
|
||||
export const completeCalendarEventController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const calendarProgress = getCalendarProgress(inventory);
|
||||
const currentSeason = getWorldState().KnownCalendarSeasons[0];
|
||||
let inventoryChanges: IInventoryChanges = {};
|
||||
let dayIndex = 0;
|
||||
for (const day of currentSeason.Days) {
|
||||
if (day.events.length == 0 || day.events[0].type != "CET_CHALLENGE") {
|
||||
if (dayIndex == calendarProgress.SeasonProgress.LastCompletedDayIdx) {
|
||||
if (day.events.length != 0) {
|
||||
const selection = day.events[parseInt(req.query.CompletedEventIdx as string)];
|
||||
if (selection.type == "CET_REWARD") {
|
||||
inventoryChanges = (await handleStoreItemAcquisition(selection.reward!, inventory))
|
||||
.InventoryChanges;
|
||||
} else if (selection.type == "CET_UPGRADE") {
|
||||
calendarProgress.YearProgress.Upgrades.push(selection.upgrade!);
|
||||
} else if (selection.type != "CET_PLOT") {
|
||||
throw new Error(`unexpected selection type: ${selection.type}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
++dayIndex;
|
||||
}
|
||||
}
|
||||
calendarProgress.SeasonProgress.LastCompletedDayIdx++;
|
||||
await inventory.save();
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges,
|
||||
CalendarProgress: inventory.CalendarProgress
|
||||
});
|
||||
};
|
@ -1,45 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { addMiscItems, getInventory, updateCurrency } from "@/src/services/inventoryService";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { IMiscItem } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { createUnveiledRivenFingerprint } from "@/src/helpers/rivenHelper";
|
||||
import { ExportUpgrades } from "warframe-public-export-plus";
|
||||
|
||||
export const completeRandomModChallengeController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const request = getJSONfromString<ICompleteRandomModChallengeRequest>(String(req.body));
|
||||
let inventoryChanges: IInventoryChanges = {};
|
||||
|
||||
// Remove 20 plat or riven cipher
|
||||
if ((req.query.p as string) == "1") {
|
||||
inventoryChanges = { ...updateCurrency(inventory, 20, true) };
|
||||
} else {
|
||||
const miscItemChanges: IMiscItem[] = [
|
||||
{
|
||||
ItemType: "/Lotus/Types/Items/MiscItems/RivenIdentifier",
|
||||
ItemCount: -1
|
||||
}
|
||||
];
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
inventoryChanges.MiscItems = miscItemChanges;
|
||||
}
|
||||
|
||||
// Update riven fingerprint to a randomised unveiled state
|
||||
const upgrade = inventory.Upgrades.id(request.ItemId)!;
|
||||
const meta = ExportUpgrades[upgrade.ItemType];
|
||||
upgrade.UpgradeFingerprint = JSON.stringify(createUnveiledRivenFingerprint(meta));
|
||||
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges,
|
||||
Fingerprint: upgrade.UpgradeFingerprint
|
||||
});
|
||||
};
|
||||
|
||||
interface ICompleteRandomModChallengeRequest {
|
||||
ItemId: string;
|
||||
}
|
@ -1,37 +0,0 @@
|
||||
import { Alliance, AllianceMember, Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { getAllianceClient } from "@/src/services/guildService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const confirmAllianceInvitationController: RequestHandler = async (req, res) => {
|
||||
// Check requester is a warlord in their guild
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const guildMember = (await GuildMember.findOne({ accountId, status: 0 }))!;
|
||||
if (guildMember.rank > 1) {
|
||||
res.status(400).json({ Error: 104 });
|
||||
return;
|
||||
}
|
||||
|
||||
const allianceMember = await AllianceMember.findOne({
|
||||
allianceId: req.query.allianceId,
|
||||
guildId: guildMember.guildId
|
||||
});
|
||||
if (!allianceMember || !allianceMember.Pending) {
|
||||
res.status(400);
|
||||
return;
|
||||
}
|
||||
allianceMember.Pending = false;
|
||||
|
||||
const guild = (await Guild.findById(guildMember.guildId))!;
|
||||
guild.AllianceId = allianceMember.allianceId;
|
||||
|
||||
await Promise.all([allianceMember.save(), guild.save()]);
|
||||
|
||||
// Give client the new alliance data which uses "AllianceId" instead of "_id" in this response
|
||||
const alliance = (await Alliance.findById(allianceMember.allianceId))!;
|
||||
const { _id, ...rest } = await getAllianceClient(alliance, guild);
|
||||
res.json({
|
||||
AllianceId: _id,
|
||||
...rest
|
||||
});
|
||||
};
|
@ -1,118 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { Account } from "@/src/models/loginModel";
|
||||
import {
|
||||
deleteGuild,
|
||||
getGuildClient,
|
||||
giveClanKey,
|
||||
hasGuildPermission,
|
||||
removeDojoKeyItems
|
||||
} from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountForRequest, getAccountIdForRequest, getSuffixedName } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
// GET request: A player accepting an invite they got in their inbox.
|
||||
export const confirmGuildInvitationGetController: RequestHandler = async (req, res) => {
|
||||
const account = await getAccountForRequest(req);
|
||||
const invitedGuildMember = await GuildMember.findOne({
|
||||
accountId: account._id,
|
||||
guildId: req.query.clanId as string
|
||||
});
|
||||
if (invitedGuildMember && invitedGuildMember.status == 2) {
|
||||
let inventoryChanges: IInventoryChanges = {};
|
||||
|
||||
// If this account is already in a guild, we need to do cleanup first.
|
||||
const guildMember = await GuildMember.findOneAndDelete({ accountId: account._id, status: 0 });
|
||||
if (guildMember) {
|
||||
const inventory = await getInventory(account._id.toString(), "LevelKeys Recipes");
|
||||
inventoryChanges = removeDojoKeyItems(inventory);
|
||||
await inventory.save();
|
||||
|
||||
if (guildMember.rank == 0) {
|
||||
await deleteGuild(guildMember.guildId);
|
||||
}
|
||||
}
|
||||
|
||||
// Now that we're sure this account is not in a guild right now, we can just proceed with the normal updates.
|
||||
invitedGuildMember.status = 0;
|
||||
await invitedGuildMember.save();
|
||||
|
||||
// Remove pending applications for this account
|
||||
await GuildMember.deleteMany({ accountId: account._id, status: 1 });
|
||||
|
||||
// Update inventory of new member
|
||||
const inventory = await getInventory(account._id.toString(), "GuildId LevelKeys Recipes");
|
||||
inventory.GuildId = new Types.ObjectId(req.query.clanId as string);
|
||||
giveClanKey(inventory, inventoryChanges);
|
||||
await inventory.save();
|
||||
|
||||
const guild = (await Guild.findById(req.query.clanId as string))!;
|
||||
|
||||
// Add join to clan log
|
||||
guild.RosterActivity ??= [];
|
||||
guild.RosterActivity.push({
|
||||
dateTime: new Date(),
|
||||
entryType: 6,
|
||||
details: getSuffixedName(account)
|
||||
});
|
||||
await guild.save();
|
||||
|
||||
res.json({
|
||||
...(await getGuildClient(guild, account._id.toString())),
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
} else {
|
||||
res.end();
|
||||
}
|
||||
};
|
||||
|
||||
// POST request: Clan representative accepting invite(s).
|
||||
export const confirmGuildInvitationPostController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const guild = (await Guild.findById(req.query.clanId as string, "Ranks RosterActivity"))!;
|
||||
if (!(await hasGuildPermission(guild, accountId, GuildPermission.Recruiter))) {
|
||||
res.status(400).json("Invalid permission");
|
||||
return;
|
||||
}
|
||||
const payload = getJSONfromString<{ userId: string }>(String(req.body));
|
||||
const filter: { accountId?: string; status: number } = { status: 1 };
|
||||
if (payload.userId != "all") {
|
||||
filter.accountId = payload.userId;
|
||||
}
|
||||
const guildMembers = await GuildMember.find(filter);
|
||||
const newMembers: string[] = [];
|
||||
for (const guildMember of guildMembers) {
|
||||
guildMember.status = 0;
|
||||
guildMember.RequestMsg = undefined;
|
||||
guildMember.RequestExpiry = undefined;
|
||||
await guildMember.save();
|
||||
|
||||
// Remove other pending applications for this account
|
||||
await GuildMember.deleteMany({ accountId: guildMember.accountId, status: 1 });
|
||||
|
||||
// Update inventory of new member
|
||||
const inventory = await getInventory(guildMember.accountId.toString(), "GuildId LevelKeys Recipes");
|
||||
inventory.GuildId = new Types.ObjectId(req.query.clanId as string);
|
||||
giveClanKey(inventory);
|
||||
await inventory.save();
|
||||
|
||||
// Add join to clan log
|
||||
const account = (await Account.findOne({ _id: guildMember.accountId }))!;
|
||||
guild.RosterActivity ??= [];
|
||||
guild.RosterActivity.push({
|
||||
dateTime: new Date(),
|
||||
entryType: 6,
|
||||
details: getSuffixedName(account)
|
||||
});
|
||||
|
||||
newMembers.push(account._id.toString());
|
||||
}
|
||||
await guild.save();
|
||||
res.json({
|
||||
NewMembers: newMembers
|
||||
});
|
||||
};
|
@ -1,67 +0,0 @@
|
||||
import { toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { checkClanAscensionHasRequiredContributors } from "@/src/services/guildService";
|
||||
import { addFusionPoints, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
export const contributeGuildClassController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const payload = getJSONfromString<IContributeGuildClassRequest>(String(req.body));
|
||||
const guild = (await Guild.findById(payload.GuildId))!;
|
||||
|
||||
// First contributor initiates ceremony and locks the pending class.
|
||||
if (!guild.CeremonyContributors) {
|
||||
guild.CeremonyContributors = [];
|
||||
guild.CeremonyClass = guildXpToClass(guild.XP);
|
||||
guild.CeremonyEndo = 0;
|
||||
for (let i = guild.Class; i != guild.CeremonyClass; ++i) {
|
||||
guild.CeremonyEndo += (i + 1) * 1000;
|
||||
}
|
||||
guild.ClassChanges ??= [];
|
||||
guild.ClassChanges.push({
|
||||
dateTime: new Date(),
|
||||
entryType: 13,
|
||||
details: guild.CeremonyClass
|
||||
});
|
||||
}
|
||||
|
||||
guild.CeremonyContributors.push(new Types.ObjectId(accountId));
|
||||
|
||||
await checkClanAscensionHasRequiredContributors(guild);
|
||||
|
||||
await guild.save();
|
||||
|
||||
// Either way, endo is given to the contributor.
|
||||
const inventory = await getInventory(accountId, "FusionPoints");
|
||||
addFusionPoints(inventory, guild.CeremonyEndo!);
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
NumContributors: guild.CeremonyContributors.length,
|
||||
FusionPointReward: guild.CeremonyEndo,
|
||||
Class: guild.Class,
|
||||
CeremonyResetDate: guild.CeremonyResetDate ? toMongoDate(guild.CeremonyResetDate) : undefined
|
||||
});
|
||||
};
|
||||
|
||||
interface IContributeGuildClassRequest {
|
||||
GuildId: string;
|
||||
RequiredContributors: number;
|
||||
}
|
||||
|
||||
const guildXpToClass = (xp: number): number => {
|
||||
const cummXp = [
|
||||
0, 11000, 34000, 69000, 114000, 168000, 231000, 302000, 381000, 68000, 563000, 665000, 774000, 891000
|
||||
];
|
||||
let highest = 0;
|
||||
for (let i = 0; i != cummXp.length; ++i) {
|
||||
if (xp < cummXp[i]) {
|
||||
break;
|
||||
}
|
||||
highest = i;
|
||||
}
|
||||
return highest;
|
||||
};
|
@ -1,168 +0,0 @@
|
||||
import { GuildMember, TGuildDatabaseDocument } from "@/src/models/guildModel";
|
||||
import { TInventoryDatabaseDocument } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import {
|
||||
addGuildMemberMiscItemContribution,
|
||||
getDojoClient,
|
||||
getGuildForRequestEx,
|
||||
hasAccessToDojo,
|
||||
processDojoBuildMaterialsGathered,
|
||||
scaleRequiredCount,
|
||||
setDojoRoomLogFunded
|
||||
} from "@/src/services/guildService";
|
||||
import { addMiscItems, getInventory, updateCurrency } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IDojoContributable, IGuildMemberDatabase } from "@/src/types/guildTypes";
|
||||
import { IMiscItem } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportDojoRecipes, IDojoBuild } from "warframe-public-export-plus";
|
||||
|
||||
interface IContributeToDojoComponentRequest {
|
||||
ComponentId: string;
|
||||
DecoId?: string;
|
||||
DecoType?: string;
|
||||
IngredientContributions: IMiscItem[];
|
||||
RegularCredits: number;
|
||||
VaultIngredientContributions: IMiscItem[];
|
||||
VaultCredits: number;
|
||||
}
|
||||
|
||||
export const contributeToDojoComponentController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
// Any clan member should have permission to contribute although notably permission is denied if they have not crafted the dojo key and were simply invited in.
|
||||
if (!hasAccessToDojo(inventory)) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
const guildMember = (await GuildMember.findOne(
|
||||
{ accountId, guildId: guild._id },
|
||||
"RegularCreditsContributed MiscItemsContributed"
|
||||
))!;
|
||||
const request = JSON.parse(String(req.body)) as IContributeToDojoComponentRequest;
|
||||
const component = guild.DojoComponents.id(request.ComponentId)!;
|
||||
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
if (!component.CompletionTime) {
|
||||
// Room is in "Collecting Materials" state
|
||||
if (request.DecoId) {
|
||||
throw new Error("attempt to contribute to a deco in an unfinished room?!");
|
||||
}
|
||||
const meta = Object.values(ExportDojoRecipes.rooms).find(x => x.resultType == component.pf)!;
|
||||
processContribution(guild, guildMember, request, inventory, inventoryChanges, meta, component);
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (component.CompletionTime) {
|
||||
setDojoRoomLogFunded(guild, component);
|
||||
}
|
||||
} else {
|
||||
// Room is past "Collecting Materials"
|
||||
if (request.DecoId) {
|
||||
const deco = component.Decos!.find(x => x._id.equals(request.DecoId))!;
|
||||
const meta = Object.values(ExportDojoRecipes.decos).find(x => x.resultType == deco.Type)!;
|
||||
processContribution(guild, guildMember, request, inventory, inventoryChanges, meta, deco);
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all([guild.save(), inventory.save(), guildMember.save()]);
|
||||
res.json({
|
||||
...(await getDojoClient(guild, 0, component._id)),
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
};
|
||||
|
||||
const processContribution = (
|
||||
guild: TGuildDatabaseDocument,
|
||||
guildMember: IGuildMemberDatabase,
|
||||
request: IContributeToDojoComponentRequest,
|
||||
inventory: TInventoryDatabaseDocument,
|
||||
inventoryChanges: IInventoryChanges,
|
||||
meta: IDojoBuild,
|
||||
component: IDojoContributable
|
||||
): void => {
|
||||
component.RegularCredits ??= 0;
|
||||
if (request.RegularCredits) {
|
||||
component.RegularCredits += request.RegularCredits;
|
||||
inventoryChanges.RegularCredits = -request.RegularCredits;
|
||||
updateCurrency(inventory, request.RegularCredits, false);
|
||||
|
||||
guildMember.RegularCreditsContributed ??= 0;
|
||||
guildMember.RegularCreditsContributed += request.RegularCredits;
|
||||
}
|
||||
if (request.VaultCredits) {
|
||||
component.RegularCredits += request.VaultCredits;
|
||||
guild.VaultRegularCredits! -= request.VaultCredits;
|
||||
}
|
||||
if (component.RegularCredits > scaleRequiredCount(guild.Tier, meta.price)) {
|
||||
guild.VaultRegularCredits ??= 0;
|
||||
guild.VaultRegularCredits += component.RegularCredits - scaleRequiredCount(guild.Tier, meta.price);
|
||||
component.RegularCredits = scaleRequiredCount(guild.Tier, meta.price);
|
||||
}
|
||||
|
||||
component.MiscItems ??= [];
|
||||
if (request.VaultIngredientContributions.length) {
|
||||
for (const ingredientContribution of request.VaultIngredientContributions) {
|
||||
const componentMiscItem = component.MiscItems.find(x => x.ItemType == ingredientContribution.ItemType);
|
||||
if (componentMiscItem) {
|
||||
const ingredientMeta = meta.ingredients.find(x => x.ItemType == ingredientContribution.ItemType)!;
|
||||
if (
|
||||
componentMiscItem.ItemCount + ingredientContribution.ItemCount >
|
||||
scaleRequiredCount(guild.Tier, ingredientMeta.ItemCount)
|
||||
) {
|
||||
ingredientContribution.ItemCount =
|
||||
scaleRequiredCount(guild.Tier, ingredientMeta.ItemCount) - componentMiscItem.ItemCount;
|
||||
}
|
||||
componentMiscItem.ItemCount += ingredientContribution.ItemCount;
|
||||
} else {
|
||||
component.MiscItems.push(ingredientContribution);
|
||||
}
|
||||
const vaultMiscItem = guild.VaultMiscItems!.find(x => x.ItemType == ingredientContribution.ItemType)!;
|
||||
vaultMiscItem.ItemCount -= ingredientContribution.ItemCount;
|
||||
}
|
||||
}
|
||||
if (request.IngredientContributions.length) {
|
||||
const miscItemChanges: IMiscItem[] = [];
|
||||
for (const ingredientContribution of request.IngredientContributions) {
|
||||
const componentMiscItem = component.MiscItems.find(x => x.ItemType == ingredientContribution.ItemType);
|
||||
if (componentMiscItem) {
|
||||
const ingredientMeta = meta.ingredients.find(x => x.ItemType == ingredientContribution.ItemType)!;
|
||||
if (
|
||||
componentMiscItem.ItemCount + ingredientContribution.ItemCount >
|
||||
scaleRequiredCount(guild.Tier, ingredientMeta.ItemCount)
|
||||
) {
|
||||
ingredientContribution.ItemCount =
|
||||
scaleRequiredCount(guild.Tier, ingredientMeta.ItemCount) - componentMiscItem.ItemCount;
|
||||
}
|
||||
componentMiscItem.ItemCount += ingredientContribution.ItemCount;
|
||||
} else {
|
||||
component.MiscItems.push(ingredientContribution);
|
||||
}
|
||||
miscItemChanges.push({
|
||||
ItemType: ingredientContribution.ItemType,
|
||||
ItemCount: ingredientContribution.ItemCount * -1
|
||||
});
|
||||
|
||||
addGuildMemberMiscItemContribution(guildMember, ingredientContribution);
|
||||
}
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
inventoryChanges.MiscItems = miscItemChanges;
|
||||
}
|
||||
|
||||
if (component.RegularCredits >= scaleRequiredCount(guild.Tier, meta.price)) {
|
||||
let fullyFunded = true;
|
||||
for (const ingredient of meta.ingredients) {
|
||||
const componentMiscItem = component.MiscItems.find(x => x.ItemType == ingredient.ItemType);
|
||||
if (
|
||||
!componentMiscItem ||
|
||||
componentMiscItem.ItemCount < scaleRequiredCount(guild.Tier, ingredient.ItemCount)
|
||||
) {
|
||||
fullyFunded = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (fullyFunded) {
|
||||
component.CompletionTime = new Date(Date.now() + meta.time * 1000);
|
||||
processDojoBuildMaterialsGathered(guild, meta);
|
||||
}
|
||||
}
|
||||
};
|
@ -1,113 +0,0 @@
|
||||
import {
|
||||
Alliance,
|
||||
Guild,
|
||||
GuildMember,
|
||||
TGuildDatabaseDocument,
|
||||
TGuildMemberDatabaseDocument
|
||||
} from "@/src/models/guildModel";
|
||||
import {
|
||||
addGuildMemberMiscItemContribution,
|
||||
addGuildMemberShipDecoContribution,
|
||||
addVaultFusionTreasures,
|
||||
addVaultMiscItems,
|
||||
addVaultShipDecos,
|
||||
getGuildForRequestEx
|
||||
} from "@/src/services/guildService";
|
||||
import {
|
||||
addFusionTreasures,
|
||||
addMiscItems,
|
||||
addShipDecorations,
|
||||
getInventory,
|
||||
updateCurrency
|
||||
} from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IFusionTreasure, IMiscItem, ITypeCount } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const contributeToVaultController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId RegularCredits MiscItems ShipDecorations FusionTreasures");
|
||||
const request = JSON.parse(String(req.body)) as IContributeToVaultRequest;
|
||||
|
||||
if (request.Alliance) {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
const alliance = (await Alliance.findById(guild.AllianceId!))!;
|
||||
alliance.VaultRegularCredits ??= 0;
|
||||
alliance.VaultRegularCredits += request.RegularCredits;
|
||||
if (request.FromVault) {
|
||||
guild.VaultRegularCredits! -= request.RegularCredits;
|
||||
await Promise.all([guild.save(), alliance.save()]);
|
||||
} else {
|
||||
updateCurrency(inventory, request.RegularCredits, false);
|
||||
await Promise.all([inventory.save(), alliance.save()]);
|
||||
}
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
|
||||
let guild: TGuildDatabaseDocument;
|
||||
let guildMember: TGuildMemberDatabaseDocument | undefined;
|
||||
if (request.GuildVault) {
|
||||
guild = (await Guild.findById(request.GuildVault))!;
|
||||
} else {
|
||||
guild = await getGuildForRequestEx(req, inventory);
|
||||
guildMember = (await GuildMember.findOne(
|
||||
{ accountId, guildId: guild._id },
|
||||
"RegularCreditsContributed MiscItemsContributed ShipDecorationsContributed"
|
||||
))!;
|
||||
}
|
||||
|
||||
if (request.RegularCredits) {
|
||||
updateCurrency(inventory, request.RegularCredits, false);
|
||||
|
||||
guild.VaultRegularCredits ??= 0;
|
||||
guild.VaultRegularCredits += request.RegularCredits;
|
||||
|
||||
if (guildMember) {
|
||||
guildMember.RegularCreditsContributed ??= 0;
|
||||
guildMember.RegularCreditsContributed += request.RegularCredits;
|
||||
}
|
||||
}
|
||||
if (request.MiscItems.length) {
|
||||
addVaultMiscItems(guild, request.MiscItems);
|
||||
for (const item of request.MiscItems) {
|
||||
if (guildMember) {
|
||||
addGuildMemberMiscItemContribution(guildMember, item);
|
||||
}
|
||||
addMiscItems(inventory, [{ ...item, ItemCount: item.ItemCount * -1 }]);
|
||||
}
|
||||
}
|
||||
if (request.ShipDecorations.length) {
|
||||
addVaultShipDecos(guild, request.ShipDecorations);
|
||||
for (const item of request.ShipDecorations) {
|
||||
if (guildMember) {
|
||||
addGuildMemberShipDecoContribution(guildMember, item);
|
||||
}
|
||||
addShipDecorations(inventory, [{ ...item, ItemCount: item.ItemCount * -1 }]);
|
||||
}
|
||||
}
|
||||
if (request.FusionTreasures.length) {
|
||||
addVaultFusionTreasures(guild, request.FusionTreasures);
|
||||
for (const item of request.FusionTreasures) {
|
||||
addFusionTreasures(inventory, [{ ...item, ItemCount: item.ItemCount * -1 }]);
|
||||
}
|
||||
}
|
||||
|
||||
const promises: Promise<unknown>[] = [guild.save(), inventory.save()];
|
||||
if (guildMember) {
|
||||
promises.push(guildMember.save());
|
||||
}
|
||||
await Promise.all(promises);
|
||||
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface IContributeToVaultRequest {
|
||||
RegularCredits: number;
|
||||
MiscItems: IMiscItem[];
|
||||
ShipDecorations: ITypeCount[];
|
||||
FusionTreasures: IFusionTreasure[];
|
||||
Alliance?: boolean;
|
||||
FromVault?: boolean;
|
||||
GuildVault?: string;
|
||||
}
|
@ -1,50 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Alliance, AllianceMember, Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { getAllianceClient } from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const createAllianceController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId");
|
||||
const guild = (await Guild.findById(inventory.GuildId!, "Name Tier AllianceId"))!;
|
||||
if (guild.AllianceId) {
|
||||
res.status(400).send("Guild is already in an alliance").end();
|
||||
return;
|
||||
}
|
||||
const guildMember = (await GuildMember.findOne({ guildId: guild._id, accountId }, "rank"))!;
|
||||
if (guildMember.rank > 1) {
|
||||
res.status(400).send("Invalid permission").end();
|
||||
return;
|
||||
}
|
||||
const data = getJSONfromString<ICreateAllianceRequest>(String(req.body));
|
||||
const alliance = new Alliance({ Name: data.allianceName });
|
||||
try {
|
||||
await alliance.save();
|
||||
} catch (e) {
|
||||
res.status(400).send("Alliance name already in use").end();
|
||||
return;
|
||||
}
|
||||
guild.AllianceId = alliance._id;
|
||||
await Promise.all([
|
||||
guild.save(),
|
||||
AllianceMember.insertOne({
|
||||
allianceId: alliance._id,
|
||||
guildId: guild._id,
|
||||
Pending: false,
|
||||
Permissions:
|
||||
GuildPermission.Ruler |
|
||||
GuildPermission.Promoter |
|
||||
GuildPermission.Recruiter |
|
||||
GuildPermission.Treasurer |
|
||||
GuildPermission.ChatModerator
|
||||
})
|
||||
]);
|
||||
res.json(await getAllianceClient(alliance, guild));
|
||||
};
|
||||
|
||||
interface ICreateAllianceRequest {
|
||||
allianceName: string;
|
||||
}
|
@ -1,44 +1,38 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { createUniqueClanName, getGuildClient, giveClanKey } from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { Inventory } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { ICreateGuildRequest } from "@/src/types/guildTypes";
|
||||
|
||||
export const createGuildController: RequestHandler = async (req, res) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const createGuildController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const payload = getJSONfromString<ICreateGuildRequest>(String(req.body));
|
||||
|
||||
// Remove pending applications for this account
|
||||
await GuildMember.deleteMany({ accountId, status: 1 });
|
||||
const payload = getJSONfromString(String(req.body)) as ICreateGuildRequest;
|
||||
|
||||
// Create guild on database
|
||||
const guild = new Guild({
|
||||
Name: await createUniqueClanName(payload.guildName)
|
||||
Name: payload.guildName
|
||||
});
|
||||
await guild.save();
|
||||
|
||||
// Create guild member on database
|
||||
await GuildMember.insertOne({
|
||||
accountId: accountId,
|
||||
guildId: guild._id,
|
||||
status: 0,
|
||||
rank: 0
|
||||
});
|
||||
// Update inventory
|
||||
const inventory = await Inventory.findOne({ accountOwnerId: accountId });
|
||||
if (inventory) {
|
||||
// Set GuildId
|
||||
inventory.GuildId = guild._id;
|
||||
|
||||
const inventory = await getInventory(accountId, "GuildId LevelKeys Recipes");
|
||||
inventory.GuildId = guild._id;
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
giveClanKey(inventory, inventoryChanges);
|
||||
await inventory.save();
|
||||
// Give clan key (TODO: This should only be a blueprint)
|
||||
inventory.LevelKeys ??= [];
|
||||
inventory.LevelKeys.push({
|
||||
ItemType: "/Lotus/Types/Keys/DojoKey",
|
||||
ItemCount: 1
|
||||
});
|
||||
|
||||
res.json({
|
||||
...(await getGuildClient(guild, accountId)),
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
await inventory.save();
|
||||
}
|
||||
|
||||
res.json(guild);
|
||||
};
|
||||
|
||||
interface ICreateGuildRequest {
|
||||
guildName: string;
|
||||
}
|
||||
export { createGuildController };
|
||||
|
@ -1,27 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { config } from "@/src/services/configService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
|
||||
export const creditsController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
|
||||
const inventory = await getInventory(accountId, "RegularCredits TradesRemaining PremiumCreditsFree PremiumCredits");
|
||||
|
||||
const response = {
|
||||
RegularCredits: inventory.RegularCredits,
|
||||
TradesRemaining: inventory.TradesRemaining,
|
||||
PremiumCreditsFree: inventory.PremiumCreditsFree,
|
||||
PremiumCredits: inventory.PremiumCredits
|
||||
};
|
||||
|
||||
if (config.infiniteCredits) {
|
||||
response.RegularCredits = 999999999;
|
||||
}
|
||||
if (config.infinitePlatinum) {
|
||||
response.PremiumCreditsFree = 0;
|
||||
response.PremiumCredits = 999999999;
|
||||
}
|
||||
|
||||
res.json(response);
|
||||
};
|
@ -1,28 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { ICrewMemberClient } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
export const crewMembersController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "CrewMembers");
|
||||
const data = getJSONfromString<ICrewMembersRequest>(String(req.body));
|
||||
const dbCrewMember = inventory.CrewMembers.id(data.crewMember.ItemId.$oid)!;
|
||||
dbCrewMember.AssignedRole = data.crewMember.AssignedRole;
|
||||
dbCrewMember.SkillEfficiency = data.crewMember.SkillEfficiency;
|
||||
dbCrewMember.WeaponConfigIdx = data.crewMember.WeaponConfigIdx;
|
||||
dbCrewMember.WeaponId = new Types.ObjectId(data.crewMember.WeaponId.$oid);
|
||||
dbCrewMember.Configs = data.crewMember.Configs;
|
||||
dbCrewMember.SecondInCommand = data.crewMember.SecondInCommand;
|
||||
await inventory.save();
|
||||
res.json({
|
||||
crewMemberId: data.crewMember.ItemId.$oid,
|
||||
NemesisFingerprint: data.crewMember.NemesisFingerprint
|
||||
});
|
||||
};
|
||||
|
||||
interface ICrewMembersRequest {
|
||||
crewMember: ICrewMemberClient;
|
||||
}
|
@ -1,84 +0,0 @@
|
||||
import {
|
||||
addCrewShipSalvagedWeaponSkin,
|
||||
addCrewShipRawSalvage,
|
||||
getInventory,
|
||||
addEquipment
|
||||
} from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
import { ICrewShipComponentFingerprint, IInnateDamageFingerprint } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { ExportCustoms, ExportRailjackWeapons, ExportUpgrades } from "warframe-public-export-plus";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { getRandomInt } from "@/src/services/rngService";
|
||||
import { IFingerprintStat } from "@/src/helpers/rivenHelper";
|
||||
import { IEquipmentDatabase } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
|
||||
export const crewShipIdentifySalvageController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(
|
||||
accountId,
|
||||
"CrewShipSalvagedWeaponSkins CrewShipSalvagedWeapons CrewShipRawSalvage"
|
||||
);
|
||||
const payload = getJSONfromString<ICrewShipIdentifySalvageRequest>(String(req.body));
|
||||
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
if (payload.ItemType in ExportCustoms) {
|
||||
const meta = ExportCustoms[payload.ItemType];
|
||||
let upgradeFingerprint: ICrewShipComponentFingerprint = { compat: payload.ItemType, buffs: [] };
|
||||
if (meta.subroutines) {
|
||||
upgradeFingerprint = {
|
||||
SubroutineIndex: getRandomInt(0, meta.subroutines.length - 1),
|
||||
...upgradeFingerprint
|
||||
};
|
||||
}
|
||||
for (const upgrade of meta.randomisedUpgrades!) {
|
||||
upgradeFingerprint.buffs.push({ Tag: upgrade.tag, Value: Math.trunc(Math.random() * 0x40000000) });
|
||||
}
|
||||
addCrewShipSalvagedWeaponSkin(
|
||||
inventory,
|
||||
payload.ItemType,
|
||||
JSON.stringify(upgradeFingerprint),
|
||||
inventoryChanges
|
||||
);
|
||||
} else {
|
||||
const meta = ExportRailjackWeapons[payload.ItemType];
|
||||
let defaultOverwrites: Partial<IEquipmentDatabase> | undefined;
|
||||
if (meta.defaultUpgrades?.[0]) {
|
||||
const upgradeType = meta.defaultUpgrades[0].ItemType;
|
||||
const upgradeMeta = ExportUpgrades[upgradeType];
|
||||
const buffs: IFingerprintStat[] = [];
|
||||
for (const buff of upgradeMeta.upgradeEntries!) {
|
||||
buffs.push({
|
||||
Tag: buff.tag,
|
||||
Value: Math.trunc(Math.random() * 0x40000000)
|
||||
});
|
||||
}
|
||||
defaultOverwrites = {
|
||||
UpgradeType: upgradeType,
|
||||
UpgradeFingerprint: JSON.stringify({
|
||||
compat: payload.ItemType,
|
||||
buffs
|
||||
} satisfies IInnateDamageFingerprint)
|
||||
};
|
||||
}
|
||||
addEquipment(inventory, "CrewShipSalvagedWeapons", payload.ItemType, defaultOverwrites, inventoryChanges);
|
||||
}
|
||||
|
||||
inventoryChanges.CrewShipRawSalvage = [
|
||||
{
|
||||
ItemType: payload.ItemType,
|
||||
ItemCount: -1
|
||||
}
|
||||
];
|
||||
addCrewShipRawSalvage(inventory, inventoryChanges.CrewShipRawSalvage);
|
||||
|
||||
await inventory.save();
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
};
|
||||
|
||||
interface ICrewShipIdentifySalvageRequest {
|
||||
ItemType: string;
|
||||
}
|
@ -1,48 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { getAccountForRequest } from "@/src/services/loginService";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const customObstacleCourseLeaderboardController: RequestHandler = async (req, res) => {
|
||||
const data = getJSONfromString<ICustomObstacleCourseLeaderboardRequest>(String(req.body));
|
||||
const guild = (await Guild.findById(data.g, "DojoComponents"))!;
|
||||
const component = guild.DojoComponents.id(data.c)!;
|
||||
if (req.query.act == "f") {
|
||||
res.json({
|
||||
results: component.Leaderboard ?? []
|
||||
});
|
||||
} else if (req.query.act == "p") {
|
||||
const account = await getAccountForRequest(req);
|
||||
component.Leaderboard ??= [];
|
||||
const entry = component.Leaderboard.find(x => x.n == account.DisplayName);
|
||||
if (entry) {
|
||||
entry.s = data.s!;
|
||||
} else {
|
||||
component.Leaderboard.push({
|
||||
s: data.s!,
|
||||
n: account.DisplayName,
|
||||
r: 0
|
||||
});
|
||||
}
|
||||
component.Leaderboard.sort((a, b) => a.s - b.s); // In this case, the score is the time in milliseconds, so smaller is better.
|
||||
if (component.Leaderboard.length > 10) {
|
||||
component.Leaderboard.shift();
|
||||
}
|
||||
let r = 0;
|
||||
for (const entry of component.Leaderboard) {
|
||||
entry.r = ++r;
|
||||
}
|
||||
await guild.save();
|
||||
res.status(200).end();
|
||||
} else {
|
||||
logger.debug(`data provided to ${req.path}: ${String(req.body)}`);
|
||||
throw new Error(`unknown customObstacleCourseLeaderboard act: ${String(req.query.act)}`);
|
||||
}
|
||||
};
|
||||
|
||||
interface ICustomObstacleCourseLeaderboardRequest {
|
||||
g: string;
|
||||
c: string;
|
||||
s?: number; // act=p
|
||||
}
|
@ -1,21 +0,0 @@
|
||||
import { getGuildForRequest, hasGuildPermission } from "@/src/services/guildService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission, IGuildRank } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const customizeGuildRanksController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const guild = await getGuildForRequest(req);
|
||||
const payload = JSON.parse(String(req.body)) as ICustomizeGuildRanksRequest;
|
||||
if (!(await hasGuildPermission(guild, accountId, GuildPermission.Ruler))) {
|
||||
res.status(400).json("Invalid permission");
|
||||
return;
|
||||
}
|
||||
guild.Ranks = payload.GuildRanks;
|
||||
await guild.save();
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface ICustomizeGuildRanksRequest {
|
||||
GuildRanks: IGuildRank[];
|
||||
}
|
@ -1,17 +0,0 @@
|
||||
import { AllianceMember, GuildMember } from "@/src/models/guildModel";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const declineAllianceInviteController: RequestHandler = async (req, res) => {
|
||||
// Check requester is a warlord in their guild
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const guildMember = (await GuildMember.findOne({ accountId, status: 0 }))!;
|
||||
if (guildMember.rank > 1) {
|
||||
res.status(400).json({ Error: 104 });
|
||||
return;
|
||||
}
|
||||
|
||||
await AllianceMember.deleteOne({ allianceId: req.query.allianceId, guildId: guildMember.guildId });
|
||||
|
||||
res.end();
|
||||
};
|
@ -1,14 +0,0 @@
|
||||
import { GuildMember } from "@/src/models/guildModel";
|
||||
import { getAccountForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const declineGuildInviteController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountForRequest(req);
|
||||
|
||||
await GuildMember.deleteOne({
|
||||
accountId: accountId,
|
||||
guildId: req.query.clanId as string
|
||||
});
|
||||
|
||||
res.end();
|
||||
};
|
@ -1,33 +0,0 @@
|
||||
import {
|
||||
getDojoClient,
|
||||
getGuildForRequestEx,
|
||||
hasAccessToDojo,
|
||||
hasGuildPermission,
|
||||
removeDojoDeco
|
||||
} from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const destroyDojoDecoController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId LevelKeys");
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Decorator))) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
const request = JSON.parse(String(req.body)) as IDestroyDojoDecoRequest;
|
||||
|
||||
removeDojoDeco(guild, request.ComponentId, request.DecoId);
|
||||
|
||||
await guild.save();
|
||||
res.json(await getDojoClient(guild, 0, request.ComponentId));
|
||||
};
|
||||
|
||||
interface IDestroyDojoDecoRequest {
|
||||
DecoType: string;
|
||||
ComponentId: string;
|
||||
DecoId: string;
|
||||
}
|
@ -1,67 +0,0 @@
|
||||
import { Alliance, AllianceMember, Guild, GuildMember } from "@/src/models/guildModel";
|
||||
import { getAccountForRequest } from "@/src/services/loginService";
|
||||
import { GuildPermission } from "@/src/types/guildTypes";
|
||||
import { parallelForeach } from "@/src/utils/async-utils";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const divvyAllianceVaultController: RequestHandler = async (req, res) => {
|
||||
// Afaict, there's no way to put anything other than credits in the alliance vault (anymore?), so just no-op if this is not a request to divvy credits.
|
||||
if (req.query.credits == "1") {
|
||||
// Check requester is a warlord in their guild
|
||||
const account = await getAccountForRequest(req);
|
||||
const guildMember = (await GuildMember.findOne({ accountId: account._id, status: 0 }))!;
|
||||
if (guildMember.rank > 1) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Check guild has treasurer permissions in the alliance
|
||||
const allianceMember = (await AllianceMember.findOne({
|
||||
allianceId: req.query.allianceId,
|
||||
guildId: guildMember.guildId
|
||||
}))!;
|
||||
if (!(allianceMember.Permissions & GuildPermission.Treasurer)) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const allianceMembers = await AllianceMember.find({ allianceId: req.query.allianceId });
|
||||
const memberCounts: Record<string, number> = {};
|
||||
let totalMembers = 0;
|
||||
await parallelForeach(allianceMembers, async allianceMember => {
|
||||
const memberCount = await GuildMember.countDocuments({
|
||||
guildId: allianceMember.guildId
|
||||
});
|
||||
memberCounts[allianceMember.guildId.toString()] = memberCount;
|
||||
totalMembers += memberCount;
|
||||
});
|
||||
logger.debug(`alliance has ${totalMembers} members between all its clans`);
|
||||
|
||||
const alliance = (await Alliance.findById(allianceMember.allianceId, "VaultRegularCredits"))!;
|
||||
if (alliance.VaultRegularCredits) {
|
||||
let creditsHandedOutInTotal = 0;
|
||||
await parallelForeach(allianceMembers, async allianceMember => {
|
||||
const memberCount = memberCounts[allianceMember.guildId.toString()];
|
||||
const cutPercentage = memberCount / totalMembers;
|
||||
const creditsToHandOut = Math.trunc(alliance.VaultRegularCredits! * cutPercentage);
|
||||
logger.debug(
|
||||
`${allianceMember.guildId.toString()} has ${memberCount} member(s) = ${Math.trunc(cutPercentage * 100)}% of alliance; giving ${creditsToHandOut} credit(s)`
|
||||
);
|
||||
if (creditsToHandOut != 0) {
|
||||
await Guild.updateOne(
|
||||
{ _id: allianceMember.guildId },
|
||||
{ $inc: { VaultRegularCredits: creditsToHandOut } }
|
||||
);
|
||||
creditsHandedOutInTotal += creditsToHandOut;
|
||||
}
|
||||
});
|
||||
alliance.VaultRegularCredits -= creditsHandedOutInTotal;
|
||||
logger.debug(
|
||||
`handed out ${creditsHandedOutInTotal} credits; alliance vault now has ${alliance.VaultRegularCredits} credit(s)`
|
||||
);
|
||||
}
|
||||
await alliance.save();
|
||||
}
|
||||
res.end();
|
||||
};
|
@ -1,76 +0,0 @@
|
||||
import { GuildMember, TGuildDatabaseDocument } from "@/src/models/guildModel";
|
||||
import { getDojoClient, getGuildForRequestEx, hasAccessToDojo, scaleRequiredCount } from "@/src/services/guildService";
|
||||
import { getInventory, updateCurrency } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IDojoContributable } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportDojoRecipes, IDojoBuild } from "warframe-public-export-plus";
|
||||
|
||||
interface IDojoComponentRushRequest {
|
||||
DecoType?: string;
|
||||
DecoId?: string;
|
||||
ComponentId: string;
|
||||
Amount: number;
|
||||
VaultAmount: number;
|
||||
AllianceVaultAmount: number;
|
||||
}
|
||||
|
||||
export const dojoComponentRushController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
if (!hasAccessToDojo(inventory)) {
|
||||
res.json({ DojoRequestStatus: -1 });
|
||||
return;
|
||||
}
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
const request = JSON.parse(String(req.body)) as IDojoComponentRushRequest;
|
||||
const component = guild.DojoComponents.id(request.ComponentId)!;
|
||||
|
||||
let platinumDonated = request.Amount;
|
||||
const inventoryChanges = updateCurrency(inventory, request.Amount, true);
|
||||
if (request.VaultAmount) {
|
||||
platinumDonated += request.VaultAmount;
|
||||
guild.VaultPremiumCredits! -= request.VaultAmount;
|
||||
}
|
||||
|
||||
if (request.DecoId) {
|
||||
const deco = component.Decos!.find(x => x._id.equals(request.DecoId))!;
|
||||
const meta = Object.values(ExportDojoRecipes.decos).find(x => x.resultType == deco.Type)!;
|
||||
processContribution(guild, deco, meta, platinumDonated);
|
||||
} else {
|
||||
const meta = Object.values(ExportDojoRecipes.rooms).find(x => x.resultType == component.pf)!;
|
||||
processContribution(guild, component, meta, platinumDonated);
|
||||
|
||||
const entry = guild.RoomChanges?.find(x => x.componentId.equals(component._id));
|
||||
if (entry) {
|
||||
entry.dateTime = component.CompletionTime!;
|
||||
}
|
||||
}
|
||||
|
||||
const guildMember = (await GuildMember.findOne({ accountId, guildId: guild._id }, "PremiumCreditsContributed"))!;
|
||||
guildMember.PremiumCreditsContributed ??= 0;
|
||||
guildMember.PremiumCreditsContributed += request.Amount;
|
||||
|
||||
await Promise.all([guild.save(), inventory.save(), guildMember.save()]);
|
||||
|
||||
res.json({
|
||||
...(await getDojoClient(guild, 0, component._id)),
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
};
|
||||
|
||||
const processContribution = (
|
||||
guild: TGuildDatabaseDocument,
|
||||
component: IDojoContributable,
|
||||
meta: IDojoBuild,
|
||||
platinumDonated: number
|
||||
): void => {
|
||||
const fullPlatinumCost = scaleRequiredCount(guild.Tier, meta.skipTimePrice);
|
||||
const fullDurationSeconds = meta.time;
|
||||
const secondsPerPlatinum = fullDurationSeconds / fullPlatinumCost;
|
||||
component.CompletionTime = new Date(
|
||||
component.CompletionTime!.getTime() - secondsPerPlatinum * platinumDonated * 1000
|
||||
);
|
||||
component.RushPlatinum ??= 0;
|
||||
component.RushPlatinum += platinumDonated;
|
||||
};
|
@ -1,11 +1,5 @@
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
// Arbiter Dojo endpoints, not really used by us as we don't provide a ContentURL.
|
||||
|
||||
export const dojoController: RequestHandler = (_req, res) => {
|
||||
res.json("-1"); // Tell client to use authorised request.
|
||||
};
|
||||
|
||||
export const setDojoURLController: RequestHandler = (_req, res) => {
|
||||
res.end();
|
||||
};
|
||||
|
@ -1,143 +1,7 @@
|
||||
import { toMongoDate, toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { config } from "@/src/services/configService";
|
||||
import { addMiscItems, getInventory } from "@/src/services/inventoryService";
|
||||
import { fromStoreItem } from "@/src/services/itemDataService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getRandomInt, getRandomWeightedRewardUc } from "@/src/services/rngService";
|
||||
import { IMongoDate, IOid } from "@/src/types/commonTypes";
|
||||
import { IDroneClient } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportDrones, ExportResources, ExportSystems } from "warframe-public-export-plus";
|
||||
|
||||
export const dronesController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
if ("GetActive" in req.query) {
|
||||
const inventory = await getInventory(accountId, "Drones");
|
||||
const activeDrones: IActiveDrone[] = [];
|
||||
for (const drone of inventory.Drones) {
|
||||
if (drone.DeployTime) {
|
||||
activeDrones.push({
|
||||
DeployTime: toMongoDate(drone.DeployTime),
|
||||
System: drone.System!,
|
||||
ItemId: toOid(drone._id),
|
||||
ItemType: drone.ItemType,
|
||||
CurrentHP: drone.CurrentHP,
|
||||
DamageTime: toMongoDate(drone.DamageTime!),
|
||||
PendingDamage: drone.PendingDamage!,
|
||||
Resources: [
|
||||
{
|
||||
ItemType: drone.ResourceType!,
|
||||
BinTotal: drone.ResourceCount!,
|
||||
StartTime: toMongoDate(drone.DeployTime)
|
||||
}
|
||||
]
|
||||
});
|
||||
}
|
||||
}
|
||||
res.json({
|
||||
ActiveDrones: activeDrones
|
||||
});
|
||||
} else if ("droneId" in req.query && "systemIndex" in req.query) {
|
||||
const inventory = await getInventory(accountId, "Drones");
|
||||
const drone = inventory.Drones.id(req.query.droneId as string)!;
|
||||
const droneMeta = ExportDrones[drone.ItemType];
|
||||
drone.DeployTime = config.instantResourceExtractorDrones ? new Date(0) : new Date();
|
||||
if (drone.RepairStart) {
|
||||
const repairMinutes = (Date.now() - drone.RepairStart.getTime()) / 60_000;
|
||||
const hpPerMinute = droneMeta.repairRate / 60;
|
||||
drone.CurrentHP = Math.min(drone.CurrentHP + Math.round(repairMinutes * hpPerMinute), droneMeta.durability);
|
||||
drone.RepairStart = undefined;
|
||||
}
|
||||
drone.System = parseInt(req.query.systemIndex as string);
|
||||
const system = ExportSystems[drone.System - 1];
|
||||
drone.DamageTime = config.instantResourceExtractorDrones
|
||||
? new Date()
|
||||
: new Date(Date.now() + getRandomInt(3 * 3600 * 1000, 4 * 3600 * 1000));
|
||||
drone.PendingDamage =
|
||||
!config.noResourceExtractorDronesDamage && Math.random() < system.damageChance
|
||||
? getRandomInt(system.droneDamage.minValue, system.droneDamage.maxValue)
|
||||
: 0;
|
||||
const resource = getRandomWeightedRewardUc(system.resources, droneMeta.probabilities)!;
|
||||
//logger.debug(`drone rolled`, resource);
|
||||
drone.ResourceType = fromStoreItem(resource.StoreItem);
|
||||
const resourceMeta = ExportResources[drone.ResourceType];
|
||||
if (resourceMeta.pickupQuantity) {
|
||||
const pickupsToCollect = droneMeta.binCapacity * droneMeta.capacityMultipliers[resource.Rarity];
|
||||
drone.ResourceCount = 0;
|
||||
for (let i = 0; i != pickupsToCollect; ++i) {
|
||||
drone.ResourceCount += getRandomInt(
|
||||
resourceMeta.pickupQuantity.minValue,
|
||||
resourceMeta.pickupQuantity.maxValue
|
||||
);
|
||||
}
|
||||
} else {
|
||||
drone.ResourceCount = 1;
|
||||
}
|
||||
await inventory.save();
|
||||
res.json({});
|
||||
} else if ("collectDroneId" in req.query) {
|
||||
const inventory = await getInventory(accountId);
|
||||
const drone = inventory.Drones.id(req.query.collectDroneId as string)!;
|
||||
|
||||
if (new Date() >= drone.DamageTime!) {
|
||||
drone.CurrentHP -= drone.PendingDamage!;
|
||||
drone.RepairStart = new Date();
|
||||
}
|
||||
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
if (drone.CurrentHP <= 0) {
|
||||
inventory.RegularCredits += 100;
|
||||
inventoryChanges.RegularCredits = 100;
|
||||
inventory.Drones.pull({ _id: req.query.collectDroneId as string });
|
||||
inventoryChanges.RemovedIdItems = [
|
||||
{
|
||||
ItemId: { $oid: req.query.collectDroneId }
|
||||
}
|
||||
];
|
||||
} else {
|
||||
const completionTime = drone.DeployTime!.getTime() + ExportDrones[drone.ItemType].fillRate * 3600_000;
|
||||
if (Date.now() >= completionTime) {
|
||||
const miscItemChanges = [
|
||||
{
|
||||
ItemType: drone.ResourceType!,
|
||||
ItemCount: drone.ResourceCount!
|
||||
}
|
||||
];
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
inventoryChanges.MiscItems = miscItemChanges;
|
||||
}
|
||||
|
||||
drone.DeployTime = undefined;
|
||||
drone.System = undefined;
|
||||
drone.DamageTime = undefined;
|
||||
drone.PendingDamage = undefined;
|
||||
drone.ResourceType = undefined;
|
||||
drone.ResourceCount = undefined;
|
||||
|
||||
inventoryChanges.Drones = [drone.toJSON<IDroneClient>()];
|
||||
}
|
||||
|
||||
await inventory.save();
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges
|
||||
});
|
||||
} else {
|
||||
throw new Error(`drones.php query not handled`);
|
||||
}
|
||||
const dronesController: RequestHandler = (_req, res) => {
|
||||
res.json({});
|
||||
};
|
||||
|
||||
interface IActiveDrone {
|
||||
DeployTime: IMongoDate;
|
||||
System: number;
|
||||
ItemId: IOid;
|
||||
ItemType: string;
|
||||
CurrentHP: number;
|
||||
DamageTime: IMongoDate;
|
||||
PendingDamage: number;
|
||||
Resources: {
|
||||
ItemType: string;
|
||||
BinTotal: number;
|
||||
StartTime: IMongoDate;
|
||||
}[];
|
||||
}
|
||||
export { dronesController };
|
||||
|
@ -1,60 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { TEndlessXpCategory } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
|
||||
export const endlessXpController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const payload = getJSONfromString<IEndlessXpRequest>(String(req.body));
|
||||
|
||||
inventory.EndlessXP ??= [];
|
||||
const entry = inventory.EndlessXP.find(x => x.Category == payload.Category);
|
||||
if (entry) {
|
||||
entry.Choices = payload.Choices;
|
||||
} else {
|
||||
inventory.EndlessXP.push({
|
||||
Category: payload.Category,
|
||||
Choices: payload.Choices
|
||||
});
|
||||
}
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
NewProgress: {
|
||||
Category: payload.Category,
|
||||
Earn: 0,
|
||||
Claim: 0,
|
||||
BonusAvailable: {
|
||||
$date: {
|
||||
$numberLong: "9999999999999"
|
||||
}
|
||||
},
|
||||
Expiry: {
|
||||
$date: {
|
||||
$numberLong: "9999999999999"
|
||||
}
|
||||
},
|
||||
Choices: payload.Choices,
|
||||
PendingRewards: [
|
||||
{
|
||||
RequiredTotalXp: 190,
|
||||
Rewards: [
|
||||
{
|
||||
StoreItem: "/Lotus/StoreItems/Upgrades/Mods/Aura/PlayerHealthAuraMod",
|
||||
ItemCount: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
// ...
|
||||
]
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
interface IEndlessXpRequest {
|
||||
Mode: string; // "r"
|
||||
Category: TEndlessXpCategory;
|
||||
Choices: string[];
|
||||
}
|
@ -1,71 +0,0 @@
|
||||
import { toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const entratiLabConquestModeController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(
|
||||
accountId,
|
||||
"EntratiVaultCountResetDate EntratiVaultCountLastPeriod EntratiLabConquestUnlocked EchoesHexConquestUnlocked EchoesHexConquestActiveFrameVariants EchoesHexConquestActiveStickers EntratiLabConquestActiveFrameVariants EntratiLabConquestCacheScoreMission EchoesHexConquestCacheScoreMission"
|
||||
);
|
||||
const body = getJSONfromString<IEntratiLabConquestModeRequest>(String(req.body));
|
||||
if (!inventory.EntratiVaultCountResetDate || Date.now() >= inventory.EntratiVaultCountResetDate.getTime()) {
|
||||
const EPOCH = 1734307200 * 1000; // Mondays, amirite?
|
||||
const day = Math.trunc((Date.now() - EPOCH) / 86400000);
|
||||
const week = Math.trunc(day / 7);
|
||||
const weekStart = EPOCH + week * 604800000;
|
||||
const weekEnd = weekStart + 604800000;
|
||||
inventory.EntratiVaultCountLastPeriod = 0;
|
||||
inventory.EntratiVaultCountResetDate = new Date(weekEnd);
|
||||
if (inventory.EntratiLabConquestUnlocked) {
|
||||
inventory.EntratiLabConquestUnlocked = 0;
|
||||
inventory.EntratiLabConquestCacheScoreMission = 0;
|
||||
inventory.EntratiLabConquestActiveFrameVariants = [];
|
||||
}
|
||||
if (inventory.EchoesHexConquestUnlocked) {
|
||||
inventory.EchoesHexConquestUnlocked = 0;
|
||||
inventory.EchoesHexConquestCacheScoreMission = 0;
|
||||
inventory.EchoesHexConquestActiveFrameVariants = [];
|
||||
inventory.EchoesHexConquestActiveStickers = [];
|
||||
}
|
||||
}
|
||||
if (body.BuyMode) {
|
||||
inventory.EntratiVaultCountLastPeriod! += 2;
|
||||
if (body.IsEchoesDeepArchemedea) {
|
||||
inventory.EchoesHexConquestUnlocked = 1;
|
||||
} else {
|
||||
inventory.EntratiLabConquestUnlocked = 1;
|
||||
}
|
||||
}
|
||||
if (body.IsEchoesDeepArchemedea) {
|
||||
if (inventory.EchoesHexConquestUnlocked) {
|
||||
inventory.EchoesHexConquestActiveFrameVariants = body.EchoesHexConquestActiveFrameVariants!;
|
||||
inventory.EchoesHexConquestActiveStickers = body.EchoesHexConquestActiveStickers!;
|
||||
}
|
||||
} else {
|
||||
if (inventory.EntratiLabConquestUnlocked) {
|
||||
inventory.EntratiLabConquestActiveFrameVariants = body.EntratiLabConquestActiveFrameVariants!;
|
||||
}
|
||||
}
|
||||
await inventory.save();
|
||||
res.json({
|
||||
EntratiVaultCountResetDate: toMongoDate(inventory.EntratiVaultCountResetDate),
|
||||
EntratiVaultCountLastPeriod: inventory.EntratiVaultCountLastPeriod,
|
||||
EntratiLabConquestUnlocked: inventory.EntratiLabConquestUnlocked,
|
||||
EntratiLabConquestCacheScoreMission: inventory.EntratiLabConquestCacheScoreMission,
|
||||
EchoesHexConquestUnlocked: inventory.EchoesHexConquestUnlocked,
|
||||
EchoesHexConquestCacheScoreMission: inventory.EchoesHexConquestCacheScoreMission
|
||||
});
|
||||
};
|
||||
|
||||
interface IEntratiLabConquestModeRequest {
|
||||
BuyMode?: number;
|
||||
IsEchoesDeepArchemedea?: number;
|
||||
EntratiLabConquestUnlocked?: number;
|
||||
EntratiLabConquestActiveFrameVariants?: string[];
|
||||
EchoesHexConquestUnlocked?: number;
|
||||
EchoesHexConquestActiveFrameVariants?: string[];
|
||||
EchoesHexConquestActiveStickers?: string[];
|
||||
}
|
@ -1,48 +1,32 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { addMiscItems, getInventory } from "@/src/services/inventoryService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getRecipe, WeaponTypeInternal } from "@/src/services/itemDataService";
|
||||
import { WeaponTypeInternal } from "@/src/services/itemDataService";
|
||||
import { EquipmentFeatures } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const evolveWeaponController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const payload = getJSONfromString<IEvolveWeaponRequest>(String(req.body));
|
||||
const payload = getJSONfromString(String(req.body)) as IEvolveWeaponRequest;
|
||||
console.assert(payload.Action == "EWA_INSTALL");
|
||||
|
||||
const recipe = getRecipe(payload.Recipe)!;
|
||||
if (payload.Action == "EWA_INSTALL") {
|
||||
addMiscItems(
|
||||
inventory,
|
||||
recipe.ingredients.map(x => ({ ItemType: x.ItemType, ItemCount: x.ItemCount * -1 }))
|
||||
);
|
||||
// TODO: We should remove the Genesis item & its resources, but currently we don't know these "recipes".
|
||||
|
||||
const item = inventory[payload.Category].id(req.query.ItemId as string)!;
|
||||
item.Features ??= 0;
|
||||
item.Features |= EquipmentFeatures.INCARNON_GENESIS;
|
||||
const item = inventory[payload.Category].find(item => item._id.toString() == (req.query.ItemId as string))!;
|
||||
item.Features ??= 0;
|
||||
item.Features |= EquipmentFeatures.INCARNON_GENESIS;
|
||||
|
||||
item.SkillTree = "0";
|
||||
item.SkillTree = "0";
|
||||
|
||||
inventory.EvolutionProgress ??= [];
|
||||
if (!inventory.EvolutionProgress.find(entry => entry.ItemType == payload.EvoType)) {
|
||||
inventory.EvolutionProgress.push({
|
||||
Progress: 0,
|
||||
Rank: 1,
|
||||
ItemType: payload.EvoType
|
||||
});
|
||||
}
|
||||
} else if (payload.Action == "EWA_UNINSTALL") {
|
||||
addMiscItems(inventory, [
|
||||
{
|
||||
ItemType: recipe.resultType,
|
||||
ItemCount: 1
|
||||
}
|
||||
]);
|
||||
|
||||
const item = inventory[payload.Category].id(req.query.ItemId as string)!;
|
||||
item.Features! &= ~EquipmentFeatures.INCARNON_GENESIS;
|
||||
} else {
|
||||
throw new Error(`unexpected evolve weapon action: ${payload.Action}`);
|
||||
inventory.EvolutionProgress ??= [];
|
||||
if (!inventory.EvolutionProgress.find(entry => entry.ItemType == payload.EvoType)) {
|
||||
inventory.EvolutionProgress.push({
|
||||
Progress: 0,
|
||||
Rank: 1,
|
||||
ItemType: payload.EvoType
|
||||
});
|
||||
}
|
||||
|
||||
await inventory.save();
|
||||
@ -50,7 +34,7 @@ export const evolveWeaponController: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
interface IEvolveWeaponRequest {
|
||||
Action: string;
|
||||
Action: "EWA_INSTALL";
|
||||
Category: WeaponTypeInternal;
|
||||
Recipe: string; // e.g. "/Lotus/Types/Items/MiscItems/IncarnonAdapters/UnlockerBlueprints/DespairIncarnonBlueprint"
|
||||
UninstallRecipe: "";
|
||||
|
@ -1,28 +1,31 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getSession } from "@/src/managers/sessionManager";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { IFindSessionRequest } from "@/src/types/session";
|
||||
|
||||
export const findSessionsController: RequestHandler = (_req, res) => {
|
||||
const req = JSON.parse(String(_req.body)) as IFindSessionRequest;
|
||||
logger.debug("FindSession Request ", req);
|
||||
//TODO: cleanup
|
||||
const findSessionsController: RequestHandler = (_req, res) => {
|
||||
const reqBody = JSON.parse(String(_req.body));
|
||||
logger.debug("FindSession Request ", { reqBody });
|
||||
const req = JSON.parse(String(_req.body));
|
||||
if (req.id != undefined) {
|
||||
logger.debug("Found ID");
|
||||
const session = getSession(req.id);
|
||||
const session = getSession(req.id as string);
|
||||
|
||||
if (session.length) res.json({ queryId: req.queryId, Sessions: session });
|
||||
if (session) res.json({ queryId: req.queryId, Sessions: session });
|
||||
else res.json({});
|
||||
} else if (req.originalSessionId != undefined) {
|
||||
logger.debug("Found OriginalSessionID");
|
||||
|
||||
const session = getSession(req.originalSessionId);
|
||||
if (session.length) res.json({ queryId: req.queryId, Sessions: session });
|
||||
const session = getSession(req.originalSessionId as string);
|
||||
if (session) res.json({ queryId: req.queryId, Sessions: session });
|
||||
else res.json({});
|
||||
} else {
|
||||
logger.debug("Found SessionRequest");
|
||||
|
||||
const session = getSession(req);
|
||||
if (session.length) res.json({ queryId: req.queryId, Sessions: session });
|
||||
const session = getSession(String(_req.body));
|
||||
if (session) res.json({ queryId: req.queryId, Sessions: session });
|
||||
else res.json({});
|
||||
}
|
||||
};
|
||||
|
||||
export { findSessionsController };
|
||||
|
@ -1,47 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addMiscItems, addStanding, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IMiscItem } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportResources } from "warframe-public-export-plus";
|
||||
|
||||
export const fishmongerController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const body = getJSONfromString<IFishmongerRequest>(String(req.body));
|
||||
const miscItemChanges: IMiscItem[] = [];
|
||||
let syndicateTag: string | undefined;
|
||||
let gainedStanding = 0;
|
||||
for (const fish of body.Fish) {
|
||||
const fishData = ExportResources[fish.ItemType];
|
||||
if (req.query.dissect == "1") {
|
||||
for (const part of fishData.dissectionParts!) {
|
||||
const partItem = miscItemChanges.find(x => x.ItemType == part.ItemType);
|
||||
if (partItem) {
|
||||
partItem.ItemCount += part.ItemCount * fish.ItemCount;
|
||||
} else {
|
||||
miscItemChanges.push({ ItemType: part.ItemType, ItemCount: part.ItemCount * fish.ItemCount });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
syndicateTag = fishData.syndicateTag!;
|
||||
gainedStanding += fishData.standingBonus! * fish.ItemCount;
|
||||
}
|
||||
miscItemChanges.push({ ItemType: fish.ItemType, ItemCount: fish.ItemCount * -1 });
|
||||
}
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
let affiliationMod;
|
||||
if (gainedStanding && syndicateTag) affiliationMod = addStanding(inventory, syndicateTag, gainedStanding);
|
||||
await inventory.save();
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
MiscItems: miscItemChanges
|
||||
},
|
||||
SyndicateTag: syndicateTag,
|
||||
StandingChange: affiliationMod?.Standing || 0
|
||||
});
|
||||
};
|
||||
|
||||
interface IFishmongerRequest {
|
||||
Fish: IMiscItem[];
|
||||
}
|
@ -1,40 +1,19 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory, addMiscItems, addEquipment, occupySlot } from "@/src/services/inventoryService";
|
||||
import { IMiscItem, TFocusPolarity, TEquipmentKey, InventorySlot } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { getInventory, addMiscItems, addEquipment } from "@/src/services/inventoryService";
|
||||
import { IMiscItem, TFocusPolarity } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { ExportFocusUpgrades } from "warframe-public-export-plus";
|
||||
import { IEquipmentClient } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
import { Inventory } from "@/src/models/inventoryModels/inventoryModel";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const focusController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
switch (req.query.op) {
|
||||
default:
|
||||
logger.error("Unhandled focus op type: " + String(req.query.op));
|
||||
logger.debug(String(req.body));
|
||||
logger.error("Unhandled focus op type: " + req.query.op);
|
||||
logger.debug(req.body.toString());
|
||||
res.end();
|
||||
break;
|
||||
case FocusOperation.InstallLens: {
|
||||
const request = JSON.parse(String(req.body)) as ILensInstallRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
const item = inventory[request.Category].id(request.WeaponId);
|
||||
if (item) {
|
||||
item.FocusLens = request.LensType;
|
||||
addMiscItems(inventory, [
|
||||
{
|
||||
ItemType: request.LensType,
|
||||
ItemCount: -1
|
||||
} satisfies IMiscItem
|
||||
]);
|
||||
}
|
||||
await inventory.save();
|
||||
res.json({
|
||||
weaponId: request.WeaponId,
|
||||
lensType: request.LensType
|
||||
});
|
||||
break;
|
||||
}
|
||||
case FocusOperation.UnlockWay: {
|
||||
const focusType = (JSON.parse(String(req.body)) as IWayRequest).FocusType;
|
||||
const focusPolarity = focusTypeToPolarity(focusType);
|
||||
@ -54,16 +33,9 @@ export const focusController: RequestHandler = async (req, res) => {
|
||||
}
|
||||
case FocusOperation.ActivateWay: {
|
||||
const focusType = (JSON.parse(String(req.body)) as IWayRequest).FocusType;
|
||||
|
||||
await Inventory.updateOne(
|
||||
{
|
||||
accountOwnerId: accountId
|
||||
},
|
||||
{
|
||||
FocusAbility: focusType
|
||||
}
|
||||
);
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.FocusAbility = focusType;
|
||||
await inventory.save();
|
||||
res.end();
|
||||
break;
|
||||
}
|
||||
@ -76,7 +48,7 @@ export const focusController: RequestHandler = async (req, res) => {
|
||||
cost += ExportFocusUpgrades[focusType].baseFocusPointCost;
|
||||
inventory.FocusUpgrades.push({ ItemType: focusType, Level: 0 });
|
||||
}
|
||||
inventory.FocusXP![focusPolarity] -= cost;
|
||||
inventory.FocusXP[focusPolarity] -= cost;
|
||||
await inventory.save();
|
||||
res.json({
|
||||
FocusTypes: request.FocusTypes,
|
||||
@ -94,7 +66,7 @@ export const focusController: RequestHandler = async (req, res) => {
|
||||
const focusUpgradeDb = inventory.FocusUpgrades.find(entry => entry.ItemType == focusUpgrade.ItemType)!;
|
||||
focusUpgradeDb.Level = focusUpgrade.Level;
|
||||
}
|
||||
inventory.FocusXP![focusPolarity] -= cost;
|
||||
inventory.FocusXP[focusPolarity] -= cost;
|
||||
await inventory.save();
|
||||
res.json({
|
||||
FocusInfos: request.FocusInfos,
|
||||
@ -104,24 +76,20 @@ export const focusController: RequestHandler = async (req, res) => {
|
||||
}
|
||||
case FocusOperation.SentTrainingAmplifier: {
|
||||
const request = JSON.parse(String(req.body)) as ISentTrainingAmplifierRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
const inventoryChanges = addEquipment(inventory, "OperatorAmps", request.StartingWeaponType, {
|
||||
ModularParts: [
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingGrip",
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingChassis",
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingBarrel"
|
||||
]
|
||||
});
|
||||
occupySlot(inventory, InventorySlot.AMPS, false);
|
||||
await inventory.save();
|
||||
res.json((inventoryChanges.OperatorAmps as IEquipmentClient[])[0]);
|
||||
const parts: string[] = [
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingGrip",
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingChassis",
|
||||
"/Lotus/Weapons/Sentients/OperatorAmplifiers/SentTrainingAmplifier/SentAmpTrainingBarrel"
|
||||
];
|
||||
const result = await addEquipment("OperatorAmps", request.StartingWeaponType, accountId, parts);
|
||||
res.json(result);
|
||||
break;
|
||||
}
|
||||
case FocusOperation.UnbindUpgrade: {
|
||||
const request = JSON.parse(String(req.body)) as IUnbindUpgradeRequest;
|
||||
const focusPolarity = focusTypeToPolarity(request.FocusTypes[0]);
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.FocusXP![focusPolarity] -= 750_000 * request.FocusTypes.length;
|
||||
inventory.FocusXP[focusPolarity] -= 750_000 * request.FocusTypes.length;
|
||||
addMiscItems(inventory, [
|
||||
{
|
||||
ItemType: "/Lotus/Types/Gameplay/Eidolon/Resources/SentientShards/SentientShardBrilliantItem",
|
||||
@ -176,7 +144,6 @@ export const focusController: RequestHandler = async (req, res) => {
|
||||
};
|
||||
|
||||
enum FocusOperation {
|
||||
InstallLens = "1",
|
||||
UnlockWay = "2",
|
||||
UnlockUpgrade = "3",
|
||||
LevelUpUpgrade = "4",
|
||||
@ -219,12 +186,6 @@ interface ISentTrainingAmplifierRequest {
|
||||
StartingWeaponType: string;
|
||||
}
|
||||
|
||||
interface ILensInstallRequest {
|
||||
LensType: string;
|
||||
Category: TEquipmentKey;
|
||||
WeaponId: string;
|
||||
}
|
||||
|
||||
// Works for ways & upgrades
|
||||
const focusTypeToPolarity = (type: string): TFocusPolarity => {
|
||||
return ("AP_" + type.substr(1).split("/")[3].toUpperCase()) as TFocusPolarity;
|
||||
|
@ -1,52 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportResources } from "warframe-public-export-plus";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { addFusionTreasures, addMiscItems, getInventory } from "@/src/services/inventoryService";
|
||||
import { IFusionTreasure, IMiscItem } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
|
||||
interface IFusionTreasureRequest {
|
||||
oldTreasureName: string;
|
||||
newTreasureName: string;
|
||||
}
|
||||
|
||||
const parseFusionTreasure = (name: string, count: number): IFusionTreasure => {
|
||||
const arr = name.split("_");
|
||||
return {
|
||||
ItemType: arr[0],
|
||||
Sockets: parseInt(arr[1], 16),
|
||||
ItemCount: count
|
||||
};
|
||||
};
|
||||
|
||||
export const fusionTreasuresController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const request = JSON.parse(String(req.body)) as IFusionTreasureRequest;
|
||||
|
||||
// Swap treasures
|
||||
const oldTreasure = parseFusionTreasure(request.oldTreasureName, -1);
|
||||
const newTreasure = parseFusionTreasure(request.newTreasureName, 1);
|
||||
const fusionTreasureChanges = [oldTreasure, newTreasure];
|
||||
addFusionTreasures(inventory, fusionTreasureChanges);
|
||||
|
||||
// Remove consumed stars
|
||||
const miscItemChanges: IMiscItem[] = [];
|
||||
const filledSockets = newTreasure.Sockets & ~oldTreasure.Sockets;
|
||||
for (let i = 0; filledSockets >> i; ++i) {
|
||||
if ((filledSockets >> i) & 1) {
|
||||
//console.log("Socket", i, "has been filled with", ExportResources[oldTreasure.ItemType].sockets![i]);
|
||||
miscItemChanges.push({
|
||||
ItemType: ExportResources[oldTreasure.ItemType].sockets![i],
|
||||
ItemCount: -1
|
||||
});
|
||||
}
|
||||
}
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
|
||||
await inventory.save();
|
||||
// The response itself is the inventory changes for this endpoint.
|
||||
res.json({
|
||||
MiscItems: miscItemChanges,
|
||||
FusionTreasures: fusionTreasureChanges
|
||||
});
|
||||
};
|
@ -1,84 +0,0 @@
|
||||
import { toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addMiscItem, getInventory } from "@/src/services/inventoryService";
|
||||
import { toStoreItem } from "@/src/services/itemDataService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { createGarden, getPersonalRooms } from "@/src/services/personalRoomsService";
|
||||
import { IMongoDate } from "@/src/types/commonTypes";
|
||||
import { IMissionReward } from "@/src/types/missionTypes";
|
||||
import { IPersonalRoomsClient } from "@/src/types/personalRoomsTypes";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { IGardeningClient } from "@/src/types/shipTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { dict_en, ExportResources } from "warframe-public-export-plus";
|
||||
|
||||
export const gardeningController: RequestHandler = async (req, res) => {
|
||||
const data = getJSONfromString<IGardeningRequest>(String(req.body));
|
||||
if (data.Mode != "HarvestAll") {
|
||||
throw new Error(`unexpected gardening mode: ${data.Mode}`);
|
||||
}
|
||||
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const [inventory, personalRooms] = await Promise.all([
|
||||
getInventory(accountId, "MiscItems"),
|
||||
getPersonalRooms(accountId, "Apartment")
|
||||
]);
|
||||
|
||||
// Harvest plants
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
const rewards: Record<string, IMissionReward[][]> = {};
|
||||
for (const planter of personalRooms.Apartment.Gardening.Planters) {
|
||||
rewards[planter.Name] = [];
|
||||
for (const plant of planter.Plants) {
|
||||
const itemType =
|
||||
"/Lotus/Types/Gameplay/Duviri/Resource/DuviriPlantItem" +
|
||||
plant.PlantType.substring(plant.PlantType.length - 1);
|
||||
const itemCount = Math.random() < 0.775 ? 2 : 4;
|
||||
|
||||
addMiscItem(inventory, itemType, itemCount, inventoryChanges);
|
||||
|
||||
rewards[planter.Name].push([
|
||||
{
|
||||
StoreItem: toStoreItem(itemType),
|
||||
TypeName: itemType,
|
||||
ItemCount: itemCount,
|
||||
DailyCooldown: false,
|
||||
Rarity: itemCount == 2 ? 0.7743589743589744 : 0.22564102564102564,
|
||||
TweetText: `${itemCount}x ${dict_en[ExportResources[itemType].name]} (Resource)`,
|
||||
ProductCategory: "MiscItems"
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
// Refresh garden
|
||||
personalRooms.Apartment.Gardening = createGarden();
|
||||
|
||||
await Promise.all([inventory.save(), personalRooms.save()]);
|
||||
|
||||
const planter = personalRooms.Apartment.Gardening.Planters[personalRooms.Apartment.Gardening.Planters.length - 1];
|
||||
const plant = planter.Plants[planter.Plants.length - 1];
|
||||
res.json({
|
||||
GardenTagName: planter.Name,
|
||||
PlantType: plant.PlantType,
|
||||
PlotIndex: plant.PlotIndex,
|
||||
EndTime: toMongoDate(plant.EndTime),
|
||||
InventoryChanges: inventoryChanges,
|
||||
Gardening: personalRooms.toJSON<IPersonalRoomsClient>().Apartment.Gardening,
|
||||
Rewards: rewards
|
||||
} satisfies IGardeningResponse);
|
||||
};
|
||||
|
||||
interface IGardeningRequest {
|
||||
Mode: string;
|
||||
}
|
||||
|
||||
interface IGardeningResponse {
|
||||
GardenTagName: string;
|
||||
PlantType: string;
|
||||
PlotIndex: number;
|
||||
EndTime: IMongoDate;
|
||||
InventoryChanges: IInventoryChanges;
|
||||
Gardening: IGardeningClient;
|
||||
Rewards: Record<string, IMissionReward[][]>;
|
||||
}
|
@ -7,9 +7,10 @@ import { IGenericUpdate } from "@/src/types/genericUpdate";
|
||||
// This endpoint used to be /api/genericUpdate.php, but sometime around the Jade Shadows update, it was changed to /api/updateNodeIntros.php.
|
||||
// SpaceNinjaServer supports both endpoints right now.
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const genericUpdateController: RequestHandler = async (request, response) => {
|
||||
const accountId = await getAccountIdForRequest(request);
|
||||
const update = getJSONfromString<IGenericUpdate>(String(request.body));
|
||||
const update = getJSONfromString(String(request.body)) as IGenericUpdate;
|
||||
response.json(await updateGeneric(update, accountId));
|
||||
};
|
||||
|
||||
|
@ -1,25 +1,7 @@
|
||||
import { Alliance, Guild } from "@/src/models/guildModel";
|
||||
import { getAllianceClient } from "@/src/services/guildService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getAllianceController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId");
|
||||
if (inventory.GuildId) {
|
||||
const guild = (await Guild.findById(inventory.GuildId, "Name Tier AllianceId"))!;
|
||||
if (guild.AllianceId) {
|
||||
const alliance = (await Alliance.findById(guild.AllianceId))!;
|
||||
res.json(await getAllianceClient(alliance, guild));
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.end();
|
||||
const getAllianceController: RequestHandler = (_req, res) => {
|
||||
res.sendStatus(200);
|
||||
};
|
||||
|
||||
/*interface IGetAllianceRequest {
|
||||
memberCount: number;
|
||||
clanLeaderName: string;
|
||||
clanLeaderId: string;
|
||||
}*/
|
||||
export { getAllianceController };
|
||||
|
29
src/controllers/api/getCreditsController.ts
Normal file
29
src/controllers/api/getCreditsController.ts
Normal file
@ -0,0 +1,29 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { config } from "@/src/services/configService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const getCreditsController: RequestHandler = async (req, res) => {
|
||||
let accountId;
|
||||
try {
|
||||
accountId = await getAccountIdForRequest(req);
|
||||
} catch (e) {
|
||||
res.status(400).send("Log-in expired");
|
||||
return;
|
||||
}
|
||||
|
||||
if (config.infiniteResources) {
|
||||
res.json({
|
||||
RegularCredits: 999999999,
|
||||
PremiumCredits: 999999999
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
res.json({
|
||||
RegularCredits: inventory.RegularCredits,
|
||||
PremiumCredits: inventory.PremiumCredits
|
||||
});
|
||||
};
|
@ -1,7 +1,6 @@
|
||||
import { Request, Response } from "express";
|
||||
|
||||
// POST with {} instead of GET as of 38.5.0
|
||||
const getFriendsController = (_request: Request, response: Response): void => {
|
||||
const getFriendsController = (_request: Request, response: Response) => {
|
||||
response.writeHead(200, {
|
||||
//Connection: "keep-alive",
|
||||
//"Content-Encoding": "gzip",
|
||||
|
@ -1,19 +0,0 @@
|
||||
import { GuildMember } from "@/src/models/guildModel";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IGuildMemberClient } from "@/src/types/guildTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getGuildContributionsController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const guildId = (await getInventory(accountId, "GuildId")).GuildId;
|
||||
const guildMember = (await GuildMember.findOne({ guildId, accountId: req.query.buddyId }))!;
|
||||
res.json({
|
||||
_id: { $oid: req.query.buddyId as string },
|
||||
RegularCreditsContributed: guildMember.RegularCreditsContributed,
|
||||
PremiumCreditsContributed: guildMember.PremiumCreditsContributed,
|
||||
MiscItemsContributed: guildMember.MiscItemsContributed,
|
||||
ConsumablesContributed: [], // ???
|
||||
ShipDecorationsContributed: guildMember.ShipDecorationsContributed
|
||||
} satisfies Partial<IGuildMemberClient>);
|
||||
};
|
@ -1,32 +1,7 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { createUniqueClanName, getGuildClient } from "@/src/services/guildService";
|
||||
|
||||
export const getGuildController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId");
|
||||
if (inventory.GuildId) {
|
||||
const guild = await Guild.findById(inventory.GuildId);
|
||||
if (guild) {
|
||||
// Handle guilds created before we added discriminators
|
||||
if (guild.Name.indexOf("#") == -1) {
|
||||
guild.Name = await createUniqueClanName(guild.Name);
|
||||
await guild.save();
|
||||
}
|
||||
|
||||
if (guild.CeremonyResetDate && Date.now() >= guild.CeremonyResetDate.getTime()) {
|
||||
logger.debug(`ascension ceremony is over`);
|
||||
guild.CeremonyEndo = undefined;
|
||||
guild.CeremonyContributors = undefined;
|
||||
guild.CeremonyResetDate = undefined;
|
||||
await guild.save();
|
||||
}
|
||||
res.json(await getGuildClient(guild, accountId));
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.end();
|
||||
const getGuildController: RequestHandler = (_, res) => {
|
||||
res.json({});
|
||||
};
|
||||
|
||||
export { getGuildController };
|
||||
|
@ -1,33 +1,60 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { Types } from "mongoose";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { getDojoClient } from "@/src/services/guildService";
|
||||
import { IDojoClient, IDojoComponentClient } from "@/src/types/guildTypes";
|
||||
import { toOid, toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const getGuildDojoController: RequestHandler = async (req, res) => {
|
||||
const guildId = req.query.guildId as string;
|
||||
|
||||
const guild = await Guild.findById(guildId);
|
||||
const guild = await Guild.findOne({ _id: guildId });
|
||||
if (!guild) {
|
||||
res.status(404).end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Populate dojo info if not present
|
||||
if (guild.DojoComponents.length == 0) {
|
||||
guild.DojoComponents.push({
|
||||
_id: new Types.ObjectId(),
|
||||
pf: "/Lotus/Levels/ClanDojo/DojoHall.level",
|
||||
ppf: "",
|
||||
CompletionTime: new Date(Date.now()),
|
||||
DecoCapacity: 600
|
||||
});
|
||||
if (!guild.DojoComponents || guild.DojoComponents.length == 0) {
|
||||
guild.DojoComponents = [
|
||||
{
|
||||
_id: new Types.ObjectId(),
|
||||
pf: "/Lotus/Levels/ClanDojo/DojoHall.level",
|
||||
ppf: "",
|
||||
CompletionTime: new Date(Date.now())
|
||||
}
|
||||
];
|
||||
await guild.save();
|
||||
}
|
||||
|
||||
const payload: IGetGuildDojoRequest = req.body ? (JSON.parse(String(req.body)) as IGetGuildDojoRequest) : {};
|
||||
res.json(await getDojoClient(guild, 0, payload.ComponentId));
|
||||
const dojo: IDojoClient = {
|
||||
_id: { $id: guildId },
|
||||
Name: guild.Name,
|
||||
Tier: 1,
|
||||
FixedContributions: true,
|
||||
DojoRevision: 1,
|
||||
RevisionTime: Math.round(Date.now() / 1000),
|
||||
Energy: 5,
|
||||
Capacity: 100,
|
||||
DojoRequestStatus: 0,
|
||||
DojoComponents: []
|
||||
};
|
||||
guild.DojoComponents.forEach(dojoComponent => {
|
||||
const clientComponent: IDojoComponentClient = {
|
||||
id: toOid(dojoComponent._id),
|
||||
pf: dojoComponent.pf,
|
||||
ppf: dojoComponent.ppf,
|
||||
DecoCapacity: 600
|
||||
};
|
||||
if (dojoComponent.pi) {
|
||||
clientComponent.pi = toOid(dojoComponent.pi);
|
||||
clientComponent.op = dojoComponent.op!;
|
||||
clientComponent.pp = dojoComponent.pp!;
|
||||
}
|
||||
if (dojoComponent.CompletionTime) {
|
||||
clientComponent.CompletionTime = toMongoDate(dojoComponent.CompletionTime);
|
||||
}
|
||||
dojo.DojoComponents.push(clientComponent);
|
||||
});
|
||||
res.json(dojo);
|
||||
};
|
||||
|
||||
interface IGetGuildDojoRequest {
|
||||
ComponentId?: string;
|
||||
}
|
||||
|
@ -1,60 +1,11 @@
|
||||
import { toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
import { Guild } from "@/src/models/guildModel";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IMongoDate } from "@/src/types/commonTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getGuildLogController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "GuildId");
|
||||
if (inventory.GuildId) {
|
||||
const guild = await Guild.findById(inventory.GuildId);
|
||||
if (guild) {
|
||||
const log: Record<string, IGuildLogEntryClient[]> = {
|
||||
RoomChanges: [],
|
||||
TechChanges: [],
|
||||
RosterActivity: [],
|
||||
StandingsUpdates: [],
|
||||
ClassChanges: []
|
||||
};
|
||||
guild.RoomChanges?.forEach(entry => {
|
||||
log.RoomChanges.push({
|
||||
dateTime: toMongoDate(entry.dateTime ?? new Date()),
|
||||
entryType: entry.entryType,
|
||||
details: entry.details
|
||||
});
|
||||
});
|
||||
guild.TechChanges?.forEach(entry => {
|
||||
log.TechChanges.push({
|
||||
dateTime: toMongoDate(entry.dateTime ?? new Date()),
|
||||
entryType: entry.entryType,
|
||||
details: entry.details
|
||||
});
|
||||
});
|
||||
guild.RosterActivity?.forEach(entry => {
|
||||
log.RosterActivity.push({
|
||||
dateTime: toMongoDate(entry.dateTime),
|
||||
entryType: entry.entryType,
|
||||
details: entry.details
|
||||
});
|
||||
});
|
||||
guild.ClassChanges?.forEach(entry => {
|
||||
log.ClassChanges.push({
|
||||
dateTime: toMongoDate(entry.dateTime),
|
||||
entryType: entry.entryType,
|
||||
details: entry.details
|
||||
});
|
||||
});
|
||||
res.json(log);
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.sendStatus(200);
|
||||
export const getGuildLogController: RequestHandler = (_req, res) => {
|
||||
res.json({
|
||||
RoomChanges: [],
|
||||
TechChanges: [],
|
||||
RosterActivity: [],
|
||||
StandingsUpdates: [],
|
||||
ClassChanges: []
|
||||
});
|
||||
};
|
||||
|
||||
interface IGuildLogEntryClient {
|
||||
dateTime: IMongoDate;
|
||||
entryType: number;
|
||||
details: number | string;
|
||||
}
|
||||
|
@ -1,20 +1,16 @@
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { Account, Ignore } from "@/src/models/loginModel";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IFriendInfo } from "@/src/types/guildTypes";
|
||||
import { parallelForeach } from "@/src/utils/async-utils";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getIgnoredUsersController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const ignores = await Ignore.find({ ignorer: accountId });
|
||||
const ignoredUsers: IFriendInfo[] = [];
|
||||
await parallelForeach(ignores, async ignore => {
|
||||
const ignoreeAccount = (await Account.findById(ignore.ignoree, "DisplayName"))!;
|
||||
ignoredUsers.push({
|
||||
_id: toOid(ignore.ignoree),
|
||||
DisplayName: ignoreeAccount.DisplayName + ""
|
||||
});
|
||||
const getIgnoredUsersController: RequestHandler = (_req, res) => {
|
||||
res.writeHead(200, {
|
||||
"Content-Type": "text/html",
|
||||
"Content-Length": "3"
|
||||
});
|
||||
res.json({ IgnoredUsers: ignoredUsers });
|
||||
res.end(
|
||||
Buffer.from([
|
||||
0x7b, 0x22, 0x4e, 0x6f, 0x6e, 0x63, 0x65, 0x22, 0x3a, 0x38, 0x33, 0x30, 0x34, 0x30, 0x37, 0x37, 0x32, 0x32,
|
||||
0x34, 0x30, 0x32, 0x32, 0x32, 0x36, 0x31, 0x35, 0x30, 0x31, 0x7d
|
||||
])
|
||||
);
|
||||
};
|
||||
|
||||
export { getIgnoredUsersController };
|
||||
|
@ -1,19 +1,13 @@
|
||||
import { Inventory } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import { generateRewardSeed } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getNewRewardSeedController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
|
||||
const rewardSeed = generateRewardSeed();
|
||||
await Inventory.updateOne(
|
||||
{
|
||||
accountOwnerId: accountId
|
||||
},
|
||||
{
|
||||
RewardSeed: rewardSeed
|
||||
}
|
||||
);
|
||||
res.json({ rewardSeed: rewardSeed });
|
||||
const getNewRewardSeedController: RequestHandler = (_req, res) => {
|
||||
res.json({ rewardSeed: generateRewardSeed() });
|
||||
};
|
||||
|
||||
function generateRewardSeed(): number {
|
||||
const min = -Number.MAX_SAFE_INTEGER;
|
||||
const max = Number.MAX_SAFE_INTEGER;
|
||||
return Math.floor(Math.random() * (max - min + 1)) + min;
|
||||
}
|
||||
|
||||
export { getNewRewardSeedController };
|
||||
|
@ -2,44 +2,33 @@ import { RequestHandler } from "express";
|
||||
import { config } from "@/src/services/configService";
|
||||
import allShipFeatures from "@/static/fixed_responses/allShipFeatures.json";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { createGarden, getPersonalRooms } from "@/src/services/personalRoomsService";
|
||||
import { getPersonalRooms } from "@/src/services/personalRoomsService";
|
||||
import { getShip } from "@/src/services/shipService";
|
||||
import { Loadout } from "@/src/models/inventoryModels/loadoutModel";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { IGetShipResponse } from "@/src/types/shipTypes";
|
||||
import { IPersonalRoomsClient } from "@/src/types/personalRoomsTypes";
|
||||
import { getLoadout } from "@/src/services/loadoutService";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const getShipController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const personalRoomsDb = await getPersonalRooms(accountId);
|
||||
|
||||
// Setup gardening if it's missing. Maybe should be done as part of some quest completion in the future.
|
||||
if (personalRoomsDb.Apartment.Gardening.Planters.length == 0) {
|
||||
personalRoomsDb.Apartment.Gardening = createGarden();
|
||||
await personalRoomsDb.save();
|
||||
}
|
||||
|
||||
const personalRooms = personalRoomsDb.toJSON<IPersonalRoomsClient>();
|
||||
const personalRooms = await getPersonalRooms(accountId);
|
||||
const loadout = await getLoadout(accountId);
|
||||
const ship = await getShip(personalRoomsDb.activeShipId, "ShipAttachments SkinFlavourItem");
|
||||
const ship = await getShip(personalRooms.activeShipId, "ShipInteriorColors ShipAttachments SkinFlavourItem");
|
||||
|
||||
const getShipResponse: IGetShipResponse = {
|
||||
ShipOwnerId: accountId,
|
||||
LoadOutInventory: { LoadOutPresets: loadout.toJSON() },
|
||||
Ship: {
|
||||
...personalRooms.Ship,
|
||||
ShipId: toOid(personalRoomsDb.activeShipId),
|
||||
...personalRooms.toJSON().Ship,
|
||||
ShipId: toOid(personalRooms.activeShipId),
|
||||
ShipInterior: {
|
||||
Colors: personalRooms.ShipInteriorColors,
|
||||
Colors: ship.ShipInteriorColors,
|
||||
ShipAttachments: ship.ShipAttachments,
|
||||
SkinFlavourItem: ship.SkinFlavourItem
|
||||
},
|
||||
FavouriteLoadoutId: personalRooms.Ship.FavouriteLoadoutId
|
||||
? toOid(personalRooms.Ship.FavouriteLoadoutId)
|
||||
: undefined
|
||||
}
|
||||
},
|
||||
Apartment: personalRooms.Apartment,
|
||||
TailorShop: personalRooms.TailorShop
|
||||
Apartment: personalRooms.Apartment
|
||||
};
|
||||
|
||||
if (config.unlockAllShipFeatures) {
|
||||
@ -48,3 +37,14 @@ export const getShipController: RequestHandler = async (req, res) => {
|
||||
|
||||
res.json(getShipResponse);
|
||||
};
|
||||
|
||||
export const getLoadout = async (accountId: string) => {
|
||||
const loadout = await Loadout.findOne({ loadoutOwnerId: accountId });
|
||||
|
||||
if (!loadout) {
|
||||
logger.error(`loadout not found for account ${accountId}`);
|
||||
throw new Error("loadout not found");
|
||||
}
|
||||
|
||||
return loadout;
|
||||
};
|
||||
|
@ -1,14 +1,23 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getVendorManifestByTypeName } from "@/src/services/serversideVendorsService";
|
||||
import ArchimedeanVendorManifest from "@/static/fixed_responses/getVendorInfo/ArchimedeanVendorManifest.json";
|
||||
import MaskSalesmanManifest from "@/static/fixed_responses/getVendorInfo/MaskSalesmanManifest.json";
|
||||
import ZarimanCommisionsManifestArchimedean from "@/static/fixed_responses/getVendorInfo/ZarimanCommisionsManifestArchimedean.json";
|
||||
|
||||
export const getVendorInfoController: RequestHandler = (req, res) => {
|
||||
if (typeof req.query.vendor == "string") {
|
||||
const manifest = getVendorManifestByTypeName(req.query.vendor);
|
||||
if (!manifest) {
|
||||
switch (req.query.vendor as string) {
|
||||
case "/Lotus/Types/Game/VendorManifests/Zariman/ArchimedeanVendorManifest":
|
||||
res.json(ArchimedeanVendorManifest);
|
||||
break;
|
||||
|
||||
case "/Lotus/Types/Game/VendorManifests/Ostron/MaskSalesmanManifest":
|
||||
res.json(MaskSalesmanManifest);
|
||||
break;
|
||||
|
||||
case "/Lotus/Types/Game/VendorManifests/Zariman/ZarimanCommisionsManifestArchimedean":
|
||||
res.json(ZarimanCommisionsManifestArchimedean);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown vendor: ${req.query.vendor}`);
|
||||
}
|
||||
res.json(manifest);
|
||||
} else {
|
||||
res.status(400).end();
|
||||
}
|
||||
};
|
||||
|
@ -1,38 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { crackRelic } from "@/src/helpers/relicHelper";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IVoidTearParticipantInfo } from "@/src/types/requestTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const getVoidProjectionRewardsController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const data = getJSONfromString<IVoidProjectionRewardRequest>(String(req.body));
|
||||
|
||||
if (data.ParticipantInfo.QualifiesForReward && !data.ParticipantInfo.HaveRewardResponse) {
|
||||
const inventory = await getInventory(accountId);
|
||||
await crackRelic(inventory, data.ParticipantInfo);
|
||||
await inventory.save();
|
||||
}
|
||||
|
||||
const response: IVoidProjectionRewardResponse = {
|
||||
CurrentWave: data.CurrentWave,
|
||||
ParticipantInfo: data.ParticipantInfo,
|
||||
DifficultyTier: data.DifficultyTier
|
||||
};
|
||||
res.json(response);
|
||||
};
|
||||
|
||||
interface IVoidProjectionRewardRequest {
|
||||
CurrentWave: number;
|
||||
ParticipantInfo: IVoidTearParticipantInfo;
|
||||
VoidTier: string;
|
||||
DifficultyTier: number;
|
||||
VoidProjectionRemovalHash: string;
|
||||
}
|
||||
|
||||
interface IVoidProjectionRewardResponse {
|
||||
CurrentWave: number;
|
||||
ParticipantInfo: IVoidTearParticipantInfo;
|
||||
DifficultyTier: number;
|
||||
}
|
@ -1,92 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { Account } from "@/src/models/loginModel";
|
||||
import { createMessage } from "@/src/services/inboxService";
|
||||
import { getInventory, updateCurrency } from "@/src/services/inventoryService";
|
||||
import { getAccountForRequest, getSuffixedName } from "@/src/services/loginService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import { IPurchaseParams } from "@/src/types/purchaseTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportFlavour } from "warframe-public-export-plus";
|
||||
|
||||
export const giftingController: RequestHandler = async (req, res) => {
|
||||
const data = getJSONfromString<IGiftingRequest>(String(req.body));
|
||||
if (data.PurchaseParams.Source != 0 || !data.PurchaseParams.UsePremium) {
|
||||
throw new Error(`unexpected purchase params in gifting request: ${String(req.body)}`);
|
||||
}
|
||||
|
||||
const account = await Account.findOne(
|
||||
data.RecipientId ? { _id: data.RecipientId.$oid } : { DisplayName: data.Recipient }
|
||||
);
|
||||
if (!account) {
|
||||
res.status(400).send("9").end();
|
||||
return;
|
||||
}
|
||||
const inventory = await getInventory(account._id.toString(), "Suits Settings");
|
||||
|
||||
// Cannot gift items to players that have not completed the tutorial.
|
||||
if (inventory.Suits.length == 0) {
|
||||
res.status(400).send("14").end();
|
||||
return;
|
||||
}
|
||||
|
||||
// Cannot gift to players who have gifting disabled.
|
||||
// TODO: Also consider GIFT_MODE_FRIENDS once friends are implemented
|
||||
if (inventory.Settings?.GiftMode == "GIFT_MODE_NONE") {
|
||||
res.status(400).send("17").end();
|
||||
return;
|
||||
}
|
||||
|
||||
// TODO: Cannot gift items with mastery requirement to players who are too low level. (Code 2)
|
||||
// TODO: Cannot gift archwing items to players that have not completed the archwing quest. (Code 7)
|
||||
// TODO: Cannot gift necramechs to players that have not completed heart of deimos. (Code 20)
|
||||
|
||||
const senderAccount = await getAccountForRequest(req);
|
||||
const senderInventory = await getInventory(
|
||||
senderAccount._id.toString(),
|
||||
"PremiumCredits PremiumCreditsFree ActiveAvatarImageType GiftsRemaining"
|
||||
);
|
||||
|
||||
if (senderInventory.GiftsRemaining == 0) {
|
||||
res.status(400).send("10").end();
|
||||
return;
|
||||
}
|
||||
senderInventory.GiftsRemaining -= 1;
|
||||
|
||||
updateCurrency(senderInventory, data.PurchaseParams.ExpectedPrice, true);
|
||||
await senderInventory.save();
|
||||
|
||||
const senderName = getSuffixedName(senderAccount);
|
||||
await createMessage(account._id, [
|
||||
{
|
||||
sndr: senderName,
|
||||
msg: data.Message || "/Lotus/Language/Menu/GiftReceivedBody_NoCustomMessage",
|
||||
arg: [
|
||||
{
|
||||
Key: "GIFTER_NAME",
|
||||
Tag: senderName
|
||||
},
|
||||
{
|
||||
Key: "GIFT_QUANTITY",
|
||||
Tag: data.PurchaseParams.Quantity
|
||||
}
|
||||
],
|
||||
sub: "/Lotus/Language/Menu/GiftReceivedSubject",
|
||||
icon: ExportFlavour[senderInventory.ActiveAvatarImageType].icon,
|
||||
gifts: [
|
||||
{
|
||||
GiftType: data.PurchaseParams.StoreItem
|
||||
}
|
||||
]
|
||||
}
|
||||
]);
|
||||
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface IGiftingRequest {
|
||||
PurchaseParams: IPurchaseParams;
|
||||
Message?: string;
|
||||
Recipient?: string;
|
||||
RecipientId?: IOid;
|
||||
buildLabel: string;
|
||||
}
|
@ -1,40 +1,52 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addMiscItems, getInventory } from "@/src/services/inventoryService";
|
||||
import { TEquipmentKey } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { ArtifactPolarity, EquipmentFeatures, IEquipmentClient } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
import { ExportRecipes } from "warframe-public-export-plus";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { WeaponTypeInternal } from "@/src/services/itemDataService";
|
||||
import { ArtifactPolarity, EquipmentFeatures } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
|
||||
const modularWeaponCategory: (WeaponTypeInternal | "Hoverboards")[] = [
|
||||
"LongGuns",
|
||||
"Pistols",
|
||||
"Melee",
|
||||
"OperatorAmps",
|
||||
"Hoverboards" // Not sure about hoverboards just coppied from modual crafting
|
||||
];
|
||||
|
||||
interface IGildWeaponRequest {
|
||||
ItemName: string;
|
||||
Recipe: string; // e.g. /Lotus/Weapons/SolarisUnited/LotusGildKitgunBlueprint
|
||||
Recipe: string; // /Lotus/Weapons/SolarisUnited/LotusGildKitgunBlueprint
|
||||
PolarizeSlot?: number;
|
||||
PolarizeValue?: ArtifactPolarity;
|
||||
ItemId: string;
|
||||
Category: TEquipmentKey;
|
||||
Category: WeaponTypeInternal | "Hoverboards";
|
||||
}
|
||||
|
||||
// In export there no recipes for gild action, so reputation and ressources only consumed visually
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const gildWeaponController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const data = getJSONfromString<IGildWeaponRequest>(String(req.body));
|
||||
const data: IGildWeaponRequest = getJSONfromString(String(req.body));
|
||||
data.ItemId = String(req.query.ItemId);
|
||||
data.Category = req.query.Category as TEquipmentKey;
|
||||
if (!modularWeaponCategory.includes(req.query.Category as WeaponTypeInternal | "Hoverboards")) {
|
||||
throw new Error(`Unknown modular weapon Category: ${req.query.Category}`);
|
||||
}
|
||||
data.Category = req.query.Category as WeaponTypeInternal | "Hoverboards";
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
if (!inventory[data.Category]) {
|
||||
throw new Error(`Category ${req.query.Category} not found in inventory`);
|
||||
}
|
||||
const weaponIndex = inventory[data.Category].findIndex(x => String(x._id) === data.ItemId);
|
||||
if (weaponIndex === -1) {
|
||||
throw new Error(`Weapon with ${data.ItemId} not found in category ${String(req.query.Category)}`);
|
||||
throw new Error(`Weapon with ${data.ItemId} not found in category ${req.query.Category}`);
|
||||
}
|
||||
|
||||
const weapon = inventory[data.Category][weaponIndex];
|
||||
weapon.Features ??= 0;
|
||||
weapon.Features |= EquipmentFeatures.GILDED;
|
||||
if (data.Recipe != "webui") {
|
||||
weapon.ItemName = data.ItemName;
|
||||
weapon.XP = 0;
|
||||
}
|
||||
weapon.Features = EquipmentFeatures.GILDED; // maybe 9 idk if DOUBLE_CAPACITY is also given
|
||||
weapon.ItemName = data.ItemName;
|
||||
weapon.XP = 0;
|
||||
if (data.Category != "OperatorAmps" && data.PolarizeSlot && data.PolarizeValue) {
|
||||
weapon.Polarity = [
|
||||
{
|
||||
@ -44,32 +56,11 @@ export const gildWeaponController: RequestHandler = async (req, res) => {
|
||||
];
|
||||
}
|
||||
inventory[data.Category][weaponIndex] = weapon;
|
||||
const inventoryChanges: IInventoryChanges = {};
|
||||
inventoryChanges[data.Category] = [weapon.toJSON<IEquipmentClient>()];
|
||||
|
||||
const affiliationMods = [];
|
||||
|
||||
if (data.Recipe != "webui") {
|
||||
const recipe = ExportRecipes[data.Recipe];
|
||||
inventoryChanges.MiscItems = recipe.secretIngredients!.map(ingredient => ({
|
||||
ItemType: ingredient.ItemType,
|
||||
ItemCount: ingredient.ItemCount * -1
|
||||
}));
|
||||
addMiscItems(inventory, inventoryChanges.MiscItems);
|
||||
|
||||
if (recipe.syndicateStandingChange) {
|
||||
const affiliation = inventory.Affiliations.find(x => x.Tag == recipe.syndicateStandingChange!.tag)!;
|
||||
affiliation.Standing += recipe.syndicateStandingChange.value;
|
||||
affiliationMods.push({
|
||||
Tag: recipe.syndicateStandingChange.tag,
|
||||
Standing: recipe.syndicateStandingChange.value
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges,
|
||||
AffiliationMods: affiliationMods
|
||||
InventoryChanges: {
|
||||
[data.Category]: [weapon]
|
||||
}
|
||||
});
|
||||
};
|
||||
|
@ -1,17 +0,0 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { parseString } from "@/src/helpers/general";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { giveKeyChainItem } from "@/src/services/questService";
|
||||
import { IKeyChainRequest } from "@/src/types/requestTypes";
|
||||
|
||||
export const giveKeyChainTriggeredItemsController: RequestHandler = async (req, res) => {
|
||||
const accountId = parseString(req.query.accountId);
|
||||
const keyChainInfo = getJSONfromString<IKeyChainRequest>((req.body as string).toString());
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
const inventoryChanges = await giveKeyChainItem(inventory, keyChainInfo);
|
||||
await inventory.save();
|
||||
|
||||
res.send(inventoryChanges);
|
||||
};
|
@ -1,16 +0,0 @@
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { giveKeyChainMessage } from "@/src/services/questService";
|
||||
import { IKeyChainRequest } from "@/src/types/requestTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const giveKeyChainTriggeredMessageController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const keyChainInfo = JSON.parse((req.body as Buffer).toString()) as IKeyChainRequest;
|
||||
|
||||
const inventory = await getInventory(accountId, "QuestKeys");
|
||||
await giveKeyChainMessage(inventory, accountId, keyChainInfo);
|
||||
await inventory.save();
|
||||
|
||||
res.send(1);
|
||||
};
|
@ -1,45 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addItem, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const giveQuestKeyRewardController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const rewardRequest = getJSONfromString<IQuestKeyRewardRequest>((req.body as Buffer).toString());
|
||||
|
||||
if (Array.isArray(rewardRequest.reward)) {
|
||||
throw new Error("Multiple rewards not expected");
|
||||
}
|
||||
|
||||
const reward = rewardRequest.reward;
|
||||
const inventory = await getInventory(accountId);
|
||||
const inventoryChanges = await addItem(inventory, reward.ItemType, reward.Amount);
|
||||
await inventory.save();
|
||||
res.json(inventoryChanges);
|
||||
//TODO: consider whishlist changes
|
||||
};
|
||||
|
||||
interface IQuestKeyRewardRequest {
|
||||
reward: IQuestKeyReward;
|
||||
}
|
||||
|
||||
interface IQuestKeyReward {
|
||||
RewardType: string;
|
||||
CouponType: string;
|
||||
Icon: string;
|
||||
ItemType: string;
|
||||
StoreItemType: string;
|
||||
ProductCategory: string;
|
||||
Amount: number;
|
||||
ScalingMultiplier: number;
|
||||
Durability: string;
|
||||
DisplayName: string;
|
||||
Duration: number;
|
||||
CouponSku: number;
|
||||
Syndicate: string;
|
||||
//Milestones: any[];
|
||||
ChooseSetIndex: number;
|
||||
NewSystemReward: boolean;
|
||||
_id: IOid;
|
||||
}
|
@ -1,20 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addLoreFragmentScans, addShipDecorations, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { ILoreFragmentScan, ITypeCount } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
export const giveShipDecoAndLoreFragmentController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId, "LoreFragmentScans ShipDecorations");
|
||||
const data = getJSONfromString<IGiveShipDecoAndLoreFragmentRequest>(String(req.body));
|
||||
addLoreFragmentScans(inventory, data.LoreFragmentScans);
|
||||
addShipDecorations(inventory, data.ShipDecorations);
|
||||
await inventory.save();
|
||||
res.end();
|
||||
};
|
||||
|
||||
interface IGiveShipDecoAndLoreFragmentRequest {
|
||||
LoreFragmentScans: ILoreFragmentScan[];
|
||||
ShipDecorations: ITypeCount[];
|
||||
}
|
@ -1,16 +1,14 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addStartingGear, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { TPartialStartingGear } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { RequestHandler } from "express";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const giveStartingGearController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const startingGear = getJSONfromString<TPartialStartingGear>(String(req.body));
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
|
||||
const inventoryChanges = await addStartingGear(inventory, startingGear);
|
||||
inventory.ReceivedStartingGear = true;
|
||||
console.log(req.query);
|
||||
await inventory.save();
|
||||
|
||||
res.send(inventoryChanges);
|
||||
res.status(200);
|
||||
};
|
||||
|
@ -1,457 +1,5 @@
|
||||
import { RequestHandler } from "express";
|
||||
import {
|
||||
addGuildMemberMiscItemContribution,
|
||||
getGuildForRequestEx,
|
||||
getGuildVault,
|
||||
hasAccessToDojo,
|
||||
hasGuildPermission,
|
||||
processFundedGuildTechProject,
|
||||
processGuildTechProjectContributionsUpdate,
|
||||
removePigmentsFromGuildMembers,
|
||||
scaleRequiredCount,
|
||||
setGuildTechLogState
|
||||
} from "@/src/services/guildService";
|
||||
import { ExportDojoRecipes } from "warframe-public-export-plus";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import {
|
||||
addCrewShipWeaponSkin,
|
||||
addEquipment,
|
||||
addItem,
|
||||
addMiscItems,
|
||||
addRecipes,
|
||||
combineInventoryChanges,
|
||||
getInventory,
|
||||
occupySlot,
|
||||
updateCurrency
|
||||
} from "@/src/services/inventoryService";
|
||||
import { IMiscItem, InventorySlot } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { IInventoryChanges } from "@/src/types/purchaseTypes";
|
||||
import { config } from "@/src/services/configService";
|
||||
import { GuildPermission, ITechProjectClient } from "@/src/types/guildTypes";
|
||||
import { GuildMember } from "@/src/models/guildModel";
|
||||
import { toMongoDate, toOid } from "@/src/helpers/inventoryHelpers";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { TInventoryDatabaseDocument } from "@/src/models/inventoryModels/inventoryModel";
|
||||
|
||||
export const guildTechController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const inventory = await getInventory(accountId);
|
||||
const data = JSON.parse(String(req.body)) as TGuildTechRequest;
|
||||
if (data.Action == "Sync") {
|
||||
let needSave = false;
|
||||
const techProjects: ITechProjectClient[] = [];
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (guild.TechProjects) {
|
||||
for (const project of guild.TechProjects) {
|
||||
const techProject: ITechProjectClient = {
|
||||
ItemType: project.ItemType,
|
||||
ReqCredits: project.ReqCredits,
|
||||
ReqItems: project.ReqItems,
|
||||
State: project.State
|
||||
};
|
||||
if (project.CompletionDate) {
|
||||
techProject.CompletionDate = toMongoDate(project.CompletionDate);
|
||||
if (Date.now() >= project.CompletionDate.getTime()) {
|
||||
needSave ||= setGuildTechLogState(guild, project.ItemType, 4, project.CompletionDate);
|
||||
}
|
||||
}
|
||||
techProjects.push(techProject);
|
||||
}
|
||||
}
|
||||
if (needSave) {
|
||||
await guild.save();
|
||||
}
|
||||
res.json({ TechProjects: techProjects });
|
||||
} else if (data.Action == "Start") {
|
||||
if (data.Mode == "Guild") {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Tech))) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
const recipe = ExportDojoRecipes.research[data.RecipeType];
|
||||
guild.TechProjects ??= [];
|
||||
if (!guild.TechProjects.find(x => x.ItemType == data.RecipeType)) {
|
||||
const techProject =
|
||||
guild.TechProjects[
|
||||
guild.TechProjects.push({
|
||||
ItemType: data.RecipeType,
|
||||
ReqCredits: config.noDojoResearchCosts ? 0 : scaleRequiredCount(guild.Tier, recipe.price),
|
||||
ReqItems: recipe.ingredients.map(x => ({
|
||||
ItemType: x.ItemType,
|
||||
ItemCount: config.noDojoResearchCosts ? 0 : scaleRequiredCount(guild.Tier, x.ItemCount)
|
||||
})),
|
||||
State: 0
|
||||
}) - 1
|
||||
];
|
||||
setGuildTechLogState(guild, techProject.ItemType, 5);
|
||||
if (config.noDojoResearchCosts) {
|
||||
processFundedGuildTechProject(guild, techProject, recipe);
|
||||
} else {
|
||||
if (data.RecipeType.substring(0, 39) == "/Lotus/Types/Items/Research/DojoColors/") {
|
||||
guild.ActiveDojoColorResearch = data.RecipeType;
|
||||
}
|
||||
}
|
||||
}
|
||||
await guild.save();
|
||||
res.end();
|
||||
} else {
|
||||
const recipe = ExportDojoRecipes.research[data.RecipeType];
|
||||
if (data.TechProductCategory) {
|
||||
if (
|
||||
data.TechProductCategory != "CrewShipWeapons" &&
|
||||
data.TechProductCategory != "CrewShipWeaponSkins"
|
||||
) {
|
||||
throw new Error(`unexpected TechProductCategory: ${data.TechProductCategory}`);
|
||||
}
|
||||
if (!inventory[getSalvageCategory(data.TechProductCategory)].id(data.CategoryItemId)) {
|
||||
throw new Error(
|
||||
`no item with id ${data.CategoryItemId} in ${getSalvageCategory(data.TechProductCategory)} array`
|
||||
);
|
||||
}
|
||||
}
|
||||
const techProject =
|
||||
inventory.PersonalTechProjects[
|
||||
inventory.PersonalTechProjects.push({
|
||||
State: 0,
|
||||
ReqCredits: recipe.price,
|
||||
ItemType: data.RecipeType,
|
||||
ProductCategory: data.TechProductCategory,
|
||||
CategoryItemId: data.CategoryItemId,
|
||||
ReqItems: recipe.ingredients
|
||||
}) - 1
|
||||
];
|
||||
await inventory.save();
|
||||
res.json({
|
||||
isPersonal: true,
|
||||
action: "Start",
|
||||
personalTech: techProject.toJSON()
|
||||
});
|
||||
}
|
||||
} else if (data.Action == "Contribute") {
|
||||
if ((req.query.guildId as string) == "000000000000000000000000") {
|
||||
const techProject = inventory.PersonalTechProjects.id(data.ResearchId)!;
|
||||
|
||||
techProject.ReqCredits -= data.RegularCredits;
|
||||
const inventoryChanges: IInventoryChanges = updateCurrency(inventory, data.RegularCredits, false);
|
||||
|
||||
const miscItemChanges = [];
|
||||
for (const miscItem of data.MiscItems) {
|
||||
const reqItem = techProject.ReqItems.find(x => x.ItemType == miscItem.ItemType);
|
||||
if (reqItem) {
|
||||
if (miscItem.ItemCount > reqItem.ItemCount) {
|
||||
miscItem.ItemCount = reqItem.ItemCount;
|
||||
}
|
||||
reqItem.ItemCount -= miscItem.ItemCount;
|
||||
miscItemChanges.push({
|
||||
ItemType: miscItem.ItemType,
|
||||
ItemCount: miscItem.ItemCount * -1
|
||||
});
|
||||
}
|
||||
}
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
inventoryChanges.MiscItems = miscItemChanges;
|
||||
|
||||
techProject.HasContributions = true;
|
||||
|
||||
if (techProject.ReqCredits == 0 && !techProject.ReqItems.find(x => x.ItemCount > 0)) {
|
||||
techProject.State = 1;
|
||||
const recipe = ExportDojoRecipes.research[techProject.ItemType];
|
||||
techProject.CompletionDate = new Date(Date.now() + recipe.time * 1000);
|
||||
}
|
||||
|
||||
await inventory.save();
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges,
|
||||
PersonalResearch: { $oid: data.ResearchId },
|
||||
PersonalResearchDate: techProject.CompletionDate ? toMongoDate(techProject.CompletionDate) : undefined
|
||||
});
|
||||
} else {
|
||||
if (!hasAccessToDojo(inventory)) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
const guildMember = (await GuildMember.findOne(
|
||||
{ accountId, guildId: guild._id },
|
||||
"RegularCreditsContributed MiscItemsContributed"
|
||||
))!;
|
||||
|
||||
const techProject = guild.TechProjects!.find(x => x.ItemType == data.RecipeType)!;
|
||||
|
||||
if (data.VaultCredits) {
|
||||
if (data.VaultCredits > techProject.ReqCredits) {
|
||||
data.VaultCredits = techProject.ReqCredits;
|
||||
}
|
||||
techProject.ReqCredits -= data.VaultCredits;
|
||||
guild.VaultRegularCredits! -= data.VaultCredits;
|
||||
}
|
||||
|
||||
if (data.RegularCredits > techProject.ReqCredits) {
|
||||
data.RegularCredits = techProject.ReqCredits;
|
||||
}
|
||||
techProject.ReqCredits -= data.RegularCredits;
|
||||
|
||||
guildMember.RegularCreditsContributed ??= 0;
|
||||
guildMember.RegularCreditsContributed += data.RegularCredits;
|
||||
|
||||
if (data.VaultMiscItems.length) {
|
||||
for (const miscItem of data.VaultMiscItems) {
|
||||
const reqItem = techProject.ReqItems.find(x => x.ItemType == miscItem.ItemType);
|
||||
if (reqItem) {
|
||||
if (miscItem.ItemCount > reqItem.ItemCount) {
|
||||
miscItem.ItemCount = reqItem.ItemCount;
|
||||
}
|
||||
reqItem.ItemCount -= miscItem.ItemCount;
|
||||
|
||||
const vaultMiscItem = guild.VaultMiscItems!.find(x => x.ItemType == miscItem.ItemType)!;
|
||||
vaultMiscItem.ItemCount -= miscItem.ItemCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const miscItemChanges = [];
|
||||
for (const miscItem of data.MiscItems) {
|
||||
const reqItem = techProject.ReqItems.find(x => x.ItemType == miscItem.ItemType);
|
||||
if (reqItem) {
|
||||
if (miscItem.ItemCount > reqItem.ItemCount) {
|
||||
miscItem.ItemCount = reqItem.ItemCount;
|
||||
}
|
||||
reqItem.ItemCount -= miscItem.ItemCount;
|
||||
miscItemChanges.push({
|
||||
ItemType: miscItem.ItemType,
|
||||
ItemCount: miscItem.ItemCount * -1
|
||||
});
|
||||
|
||||
addGuildMemberMiscItemContribution(guildMember, miscItem);
|
||||
}
|
||||
}
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
const inventoryChanges: IInventoryChanges = updateCurrency(inventory, data.RegularCredits, false);
|
||||
inventoryChanges.MiscItems = miscItemChanges;
|
||||
|
||||
// Check if research is fully funded now.
|
||||
await processGuildTechProjectContributionsUpdate(guild, techProject);
|
||||
|
||||
await Promise.all([guild.save(), inventory.save(), guildMember.save()]);
|
||||
res.json({
|
||||
InventoryChanges: inventoryChanges,
|
||||
Vault: getGuildVault(guild)
|
||||
});
|
||||
}
|
||||
} else if (data.Action.split(",")[0] == "Buy") {
|
||||
const purchase = data as IGuildTechBuyRequest;
|
||||
if (purchase.Mode == "Guild") {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (
|
||||
!hasAccessToDojo(inventory) ||
|
||||
!(await hasGuildPermission(guild, accountId, GuildPermission.Fabricator))
|
||||
) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
const quantity = parseInt(data.Action.split(",")[1]);
|
||||
const recipeChanges = [
|
||||
{
|
||||
ItemType: purchase.RecipeType,
|
||||
ItemCount: quantity
|
||||
}
|
||||
];
|
||||
addRecipes(inventory, recipeChanges);
|
||||
const currencyChanges = updateCurrency(
|
||||
inventory,
|
||||
ExportDojoRecipes.research[purchase.RecipeType].replicatePrice,
|
||||
false
|
||||
);
|
||||
await inventory.save();
|
||||
// Not a mistake: This response uses `inventoryChanges` instead of `InventoryChanges`.
|
||||
res.json({
|
||||
inventoryChanges: {
|
||||
...currencyChanges,
|
||||
Recipes: recipeChanges
|
||||
}
|
||||
});
|
||||
} else {
|
||||
const inventoryChanges = claimSalvagedComponent(inventory, purchase.CategoryItemId!);
|
||||
await inventory.save();
|
||||
res.json({
|
||||
inventoryChanges: inventoryChanges
|
||||
});
|
||||
}
|
||||
} else if (data.Action == "Fabricate") {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Fabricator))) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
const recipe = ExportDojoRecipes.fabrications[data.RecipeType];
|
||||
const inventoryChanges: IInventoryChanges = updateCurrency(inventory, recipe.price, false);
|
||||
inventoryChanges.MiscItems = recipe.ingredients.map(x => ({
|
||||
ItemType: x.ItemType,
|
||||
ItemCount: x.ItemCount * -1
|
||||
}));
|
||||
addMiscItems(inventory, inventoryChanges.MiscItems);
|
||||
combineInventoryChanges(inventoryChanges, await addItem(inventory, recipe.resultType));
|
||||
await inventory.save();
|
||||
// Not a mistake: This response uses `inventoryChanges` instead of `InventoryChanges`.
|
||||
res.json({ inventoryChanges: inventoryChanges });
|
||||
} else if (data.Action == "Pause") {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Tech))) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
const project = guild.TechProjects!.find(x => x.ItemType == data.RecipeType)!;
|
||||
project.State = -2;
|
||||
guild.ActiveDojoColorResearch = "";
|
||||
await guild.save();
|
||||
await removePigmentsFromGuildMembers(guild._id);
|
||||
res.end();
|
||||
} else if (data.Action == "Unpause") {
|
||||
const guild = await getGuildForRequestEx(req, inventory);
|
||||
if (!hasAccessToDojo(inventory) || !(await hasGuildPermission(guild, accountId, GuildPermission.Tech))) {
|
||||
res.status(400).send("-1").end();
|
||||
return;
|
||||
}
|
||||
const project = guild.TechProjects!.find(x => x.ItemType == data.RecipeType)!;
|
||||
project.State = 0;
|
||||
guild.ActiveDojoColorResearch = data.RecipeType;
|
||||
await guild.save();
|
||||
res.end();
|
||||
} else if (data.Action == "Cancel" && data.CategoryItemId) {
|
||||
const personalTechProjectIndex = inventory.PersonalTechProjects.findIndex(x =>
|
||||
x.CategoryItemId?.equals(data.CategoryItemId)
|
||||
);
|
||||
const personalTechProject = inventory.PersonalTechProjects[personalTechProjectIndex];
|
||||
inventory.PersonalTechProjects.splice(personalTechProjectIndex, 1);
|
||||
|
||||
const meta = ExportDojoRecipes.research[personalTechProject.ItemType];
|
||||
const contributedCredits = meta.price - personalTechProject.ReqCredits;
|
||||
const inventoryChanges = updateCurrency(inventory, contributedCredits * -1, false);
|
||||
inventoryChanges.MiscItems = [];
|
||||
for (const ingredient of meta.ingredients) {
|
||||
const reqItem = personalTechProject.ReqItems.find(x => x.ItemType == ingredient.ItemType);
|
||||
if (reqItem) {
|
||||
const contributedItems = ingredient.ItemCount - reqItem.ItemCount;
|
||||
inventoryChanges.MiscItems.push({
|
||||
ItemType: ingredient.ItemType,
|
||||
ItemCount: contributedItems
|
||||
});
|
||||
}
|
||||
}
|
||||
addMiscItems(inventory, inventoryChanges.MiscItems);
|
||||
|
||||
await inventory.save();
|
||||
res.json({
|
||||
action: "Cancel",
|
||||
isPersonal: true,
|
||||
inventoryChanges: inventoryChanges,
|
||||
personalTech: {
|
||||
ItemId: toOid(personalTechProject._id)
|
||||
}
|
||||
});
|
||||
} else if (data.Action == "Rush" && data.CategoryItemId) {
|
||||
const inventoryChanges: IInventoryChanges = {
|
||||
...updateCurrency(inventory, 20, true),
|
||||
...claimSalvagedComponent(inventory, data.CategoryItemId)
|
||||
};
|
||||
await inventory.save();
|
||||
res.json({
|
||||
inventoryChanges: inventoryChanges
|
||||
});
|
||||
} else if (data.Action == "InstantFinish") {
|
||||
if (data.TechProductCategory != "CrewShipWeapons" && data.TechProductCategory != "CrewShipWeaponSkins") {
|
||||
throw new Error(`unexpected TechProductCategory: ${data.TechProductCategory}`);
|
||||
}
|
||||
const inventoryChanges = finishComponentRepair(inventory, data.TechProductCategory, data.CategoryItemId!);
|
||||
inventoryChanges.MiscItems = [
|
||||
{
|
||||
ItemType: "/Lotus/Types/Items/MiscItems/InstantSalvageRepairItem",
|
||||
ItemCount: -1
|
||||
}
|
||||
];
|
||||
addMiscItems(inventory, inventoryChanges.MiscItems);
|
||||
await inventory.save();
|
||||
res.json({
|
||||
inventoryChanges: inventoryChanges
|
||||
});
|
||||
} else {
|
||||
logger.debug(`data provided to ${req.path}: ${String(req.body)}`);
|
||||
throw new Error(`unhandled guildTech request`);
|
||||
}
|
||||
};
|
||||
|
||||
type TGuildTechRequest =
|
||||
| { Action: "Sync" | "SomethingElseThatWeMightNotKnowAbout" }
|
||||
| IGuildTechBasicRequest
|
||||
| IGuildTechContributeRequest;
|
||||
|
||||
interface IGuildTechBasicRequest {
|
||||
Action: "Start" | "Fabricate" | "Pause" | "Unpause" | "Cancel" | "Rush" | "InstantFinish";
|
||||
Mode: "Guild" | "Personal";
|
||||
RecipeType: string;
|
||||
TechProductCategory?: string;
|
||||
CategoryItemId?: string;
|
||||
}
|
||||
|
||||
interface IGuildTechBuyRequest extends Omit<IGuildTechBasicRequest, "Action"> {
|
||||
Action: string;
|
||||
}
|
||||
|
||||
interface IGuildTechContributeRequest {
|
||||
Action: "Contribute";
|
||||
ResearchId: string;
|
||||
RecipeType: string;
|
||||
RegularCredits: number;
|
||||
MiscItems: IMiscItem[];
|
||||
VaultCredits: number;
|
||||
VaultMiscItems: IMiscItem[];
|
||||
}
|
||||
|
||||
const getSalvageCategory = (
|
||||
category: "CrewShipWeapons" | "CrewShipWeaponSkins"
|
||||
): "CrewShipSalvagedWeapons" | "CrewShipSalvagedWeaponSkins" => {
|
||||
return category == "CrewShipWeapons" ? "CrewShipSalvagedWeapons" : "CrewShipSalvagedWeaponSkins";
|
||||
};
|
||||
|
||||
const claimSalvagedComponent = (inventory: TInventoryDatabaseDocument, itemId: string): IInventoryChanges => {
|
||||
// delete personal tech project
|
||||
const personalTechProjectIndex = inventory.PersonalTechProjects.findIndex(x => x.CategoryItemId?.equals(itemId));
|
||||
const personalTechProject = inventory.PersonalTechProjects[personalTechProjectIndex];
|
||||
inventory.PersonalTechProjects.splice(personalTechProjectIndex, 1);
|
||||
|
||||
const category = personalTechProject.ProductCategory! as "CrewShipWeapons" | "CrewShipWeaponSkins";
|
||||
return finishComponentRepair(inventory, category, itemId);
|
||||
};
|
||||
|
||||
const finishComponentRepair = (
|
||||
inventory: TInventoryDatabaseDocument,
|
||||
category: "CrewShipWeapons" | "CrewShipWeaponSkins",
|
||||
itemId: string
|
||||
): IInventoryChanges => {
|
||||
const salvageCategory = getSalvageCategory(category);
|
||||
|
||||
// find salved part & delete it
|
||||
const salvageIndex = inventory[salvageCategory].findIndex(x => x._id.equals(itemId));
|
||||
const salvageItem = inventory[salvageCategory][salvageIndex];
|
||||
inventory[salvageCategory].splice(salvageIndex, 1);
|
||||
|
||||
// add final item
|
||||
const inventoryChanges = {
|
||||
...(category == "CrewShipWeaponSkins"
|
||||
? addCrewShipWeaponSkin(inventory, salvageItem.ItemType, salvageItem.UpgradeFingerprint)
|
||||
: addEquipment(inventory, category, salvageItem.ItemType, {
|
||||
UpgradeFingerprint: salvageItem.UpgradeFingerprint
|
||||
})),
|
||||
...occupySlot(inventory, InventorySlot.RJ_COMPONENT_AND_ARMAMENTS, false)
|
||||
};
|
||||
|
||||
inventoryChanges.RemovedIdItems = [
|
||||
{
|
||||
ItemId: { $oid: itemId }
|
||||
}
|
||||
];
|
||||
|
||||
return inventoryChanges;
|
||||
export const guildTechController: RequestHandler = (_req, res) => {
|
||||
res.status(500).end(); // This is what I got for a fresh clan.
|
||||
};
|
||||
|
@ -4,6 +4,7 @@ import { createNewSession } from "@/src/managers/sessionManager";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { ISession } from "@/src/types/session";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const hostSessionController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const hostSessionRequest = JSON.parse(req.body as string) as ISession;
|
||||
@ -11,7 +12,7 @@ const hostSessionController: RequestHandler = async (req, res) => {
|
||||
const session = createNewSession(hostSessionRequest, accountId);
|
||||
logger.debug(`New Session Created`, { session });
|
||||
|
||||
res.json({ sessionId: { $oid: session.sessionId }, rewardSeed: 99999999 });
|
||||
res.json({ sessionId: { $id: session.sessionId }, rewardSeed: 99999999 });
|
||||
};
|
||||
|
||||
export { hostSessionController };
|
||||
|
@ -1,45 +0,0 @@
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { addBooster, getInventory } from "@/src/services/inventoryService";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getRandomInt } from "@/src/services/rngService";
|
||||
import { RequestHandler } from "express";
|
||||
import { ExportBoosters } from "warframe-public-export-plus";
|
||||
|
||||
export const hubBlessingController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const data = getJSONfromString<IHubBlessingRequest>(String(req.body));
|
||||
const boosterType = ExportBoosters[data.booster].typeName;
|
||||
if (req.query.mode == "send") {
|
||||
const inventory = await getInventory(accountId, "BlessingCooldown Boosters");
|
||||
inventory.BlessingCooldown = new Date(Date.now() + 86400000);
|
||||
addBooster(boosterType, 3 * 3600, inventory);
|
||||
await inventory.save();
|
||||
|
||||
let token = "";
|
||||
for (let i = 0; i != 32; ++i) {
|
||||
token += getRandomInt(0, 15).toString(16);
|
||||
}
|
||||
|
||||
res.json({
|
||||
BlessingCooldown: inventory.BlessingCooldown,
|
||||
SendTime: Math.trunc(Date.now() / 1000).toString(),
|
||||
Token: token
|
||||
});
|
||||
} else {
|
||||
const inventory = await getInventory(accountId, "Boosters");
|
||||
addBooster(boosterType, 3 * 3600, inventory);
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
BoosterType: data.booster,
|
||||
Sender: data.senderId
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
interface IHubBlessingRequest {
|
||||
booster: string;
|
||||
senderId?: string; // mode=request
|
||||
sendTime?: string; // mode=request
|
||||
token?: string; // mode=request
|
||||
}
|
@ -1,125 +1,8 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { Inbox } from "@/src/models/inboxModel";
|
||||
import {
|
||||
createMessage,
|
||||
createNewEventMessages,
|
||||
deleteAllMessagesRead,
|
||||
deleteMessageRead,
|
||||
getAllMessagesSorted,
|
||||
getMessage
|
||||
} from "@/src/services/inboxService";
|
||||
import { getAccountForRequest, getAccountFromSuffixedName, getSuffixedName } from "@/src/services/loginService";
|
||||
import { addItems, combineInventoryChanges, getInventory } from "@/src/services/inventoryService";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { ExportFlavour, ExportGear } from "warframe-public-export-plus";
|
||||
import { handleStoreItemAcquisition } from "@/src/services/purchaseService";
|
||||
import { fromStoreItem, isStoreItem } from "@/src/services/itemDataService";
|
||||
import inbox from "@/static/fixed_responses/inbox.json";
|
||||
|
||||
export const inboxController: RequestHandler = async (req, res) => {
|
||||
const { deleteId, lastMessage: latestClientMessageId, messageId } = req.query;
|
||||
|
||||
const account = await getAccountForRequest(req);
|
||||
const accountId = account._id.toString();
|
||||
|
||||
if (deleteId) {
|
||||
if (deleteId === "DeleteAllRead") {
|
||||
await deleteAllMessagesRead(accountId);
|
||||
res.status(200).end();
|
||||
return;
|
||||
}
|
||||
|
||||
await deleteMessageRead(deleteId as string);
|
||||
res.status(200).end();
|
||||
} else if (messageId) {
|
||||
const message = await getMessage(messageId as string);
|
||||
message.r = true;
|
||||
await message.save();
|
||||
|
||||
const attachmentItems = message.attVisualOnly ? undefined : message.att;
|
||||
const attachmentCountedItems = message.attVisualOnly ? undefined : message.countedAtt;
|
||||
|
||||
if (!attachmentItems && !attachmentCountedItems && !message.gifts) {
|
||||
res.status(200).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
const inventoryChanges = {};
|
||||
if (attachmentItems) {
|
||||
await addItems(
|
||||
inventory,
|
||||
attachmentItems.map(attItem => ({
|
||||
ItemType: isStoreItem(attItem) ? fromStoreItem(attItem) : attItem,
|
||||
ItemCount: attItem in ExportGear ? (ExportGear[attItem].purchaseQuantity ?? 1) : 1
|
||||
})),
|
||||
inventoryChanges
|
||||
);
|
||||
}
|
||||
if (attachmentCountedItems) {
|
||||
await addItems(inventory, attachmentCountedItems, inventoryChanges);
|
||||
}
|
||||
if (message.gifts) {
|
||||
const sender = await getAccountFromSuffixedName(message.sndr);
|
||||
const recipientName = getSuffixedName(account);
|
||||
const giftQuantity = message.arg!.find(x => x.Key == "GIFT_QUANTITY")!.Tag as number;
|
||||
for (const gift of message.gifts) {
|
||||
combineInventoryChanges(
|
||||
inventoryChanges,
|
||||
(await handleStoreItemAcquisition(gift.GiftType, inventory, giftQuantity)).InventoryChanges
|
||||
);
|
||||
if (sender) {
|
||||
await createMessage(sender._id, [
|
||||
{
|
||||
sndr: recipientName,
|
||||
msg: "/Lotus/Language/Menu/GiftReceivedConfirmationBody",
|
||||
arg: [
|
||||
{
|
||||
Key: "RECIPIENT_NAME",
|
||||
Tag: recipientName
|
||||
},
|
||||
{
|
||||
Key: "GIFT_TYPE",
|
||||
Tag: gift.GiftType
|
||||
},
|
||||
{
|
||||
Key: "GIFT_QUANTITY",
|
||||
Tag: giftQuantity
|
||||
}
|
||||
],
|
||||
sub: "/Lotus/Language/Menu/GiftReceivedConfirmationSubject",
|
||||
icon: ExportFlavour[inventory.ActiveAvatarImageType].icon,
|
||||
highPriority: true
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
await inventory.save();
|
||||
res.json({ InventoryChanges: inventoryChanges });
|
||||
} else if (latestClientMessageId) {
|
||||
await createNewEventMessages(req);
|
||||
const messages = await Inbox.find({ ownerId: accountId }).sort({ date: 1 });
|
||||
|
||||
const latestClientMessage = messages.find(m => m._id.toString() === latestClientMessageId);
|
||||
|
||||
if (!latestClientMessage) {
|
||||
logger.debug(`this should only happen after DeleteAllRead `);
|
||||
res.json({ Inbox: messages });
|
||||
return;
|
||||
}
|
||||
const newMessages = messages.filter(m => m.date > latestClientMessage.date);
|
||||
|
||||
if (newMessages.length === 0) {
|
||||
res.send("no-new");
|
||||
return;
|
||||
}
|
||||
|
||||
res.json({ Inbox: newMessages });
|
||||
} else {
|
||||
//newly created event messages must be newer than account.LatestEventMessageDate
|
||||
await createNewEventMessages(req);
|
||||
const messages = await getAllMessagesSorted(accountId);
|
||||
const inbox = messages.map(m => m.toJSON());
|
||||
res.json({ Inbox: inbox });
|
||||
}
|
||||
const inboxController: RequestHandler = (_req, res) => {
|
||||
res.json(inbox);
|
||||
};
|
||||
|
||||
export { inboxController };
|
||||
|
@ -1,35 +1,18 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getJSONfromString } from "@/src/helpers/stringHelpers";
|
||||
import { getInventory, addMiscItems, updateCurrency, addRecipes, freeUpSlot } from "@/src/services/inventoryService";
|
||||
import { getInventory, addMiscItems } from "@/src/services/inventoryService";
|
||||
import { IOid } from "@/src/types/commonTypes";
|
||||
import {
|
||||
IConsumedSuit,
|
||||
IHelminthFoodRecord,
|
||||
IInventoryClient,
|
||||
IMiscItem,
|
||||
InventorySlot
|
||||
} from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { ExportMisc } from "warframe-public-export-plus";
|
||||
import { getRecipe } from "@/src/services/itemDataService";
|
||||
import { toMongoDate } from "@/src/helpers/inventoryHelpers";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { colorToShard } from "@/src/helpers/shardHelper";
|
||||
import { config } from "@/src/services/configService";
|
||||
import {
|
||||
addInfestedFoundryXP,
|
||||
applyCheatsToInfestedFoundry,
|
||||
handleSubsumeCompletion
|
||||
} from "@/src/services/infestedFoundryService";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const infestedFoundryController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
switch (req.query.mode) {
|
||||
case "s": {
|
||||
// shard installation
|
||||
const request = getJSONfromString<IShardInstallRequest>(String(req.body));
|
||||
const request = getJSONfromString(String(req.body)) as IShardInstallRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
const suit = inventory.Suits.id(request.SuitId.$oid)!;
|
||||
const suit = inventory.Suits.find(suit => suit._id.toString() == request.SuitId.$id)!;
|
||||
if (!suit.ArchonCrystalUpgrades || suit.ArchonCrystalUpgrades.length != 5) {
|
||||
suit.ArchonCrystalUpgrades = [{}, {}, {}, {}, {}];
|
||||
}
|
||||
@ -53,52 +36,9 @@ export const infestedFoundryController: RequestHandler = async (req, res) => {
|
||||
break;
|
||||
}
|
||||
|
||||
case "x": {
|
||||
// shard removal
|
||||
const request = getJSONfromString<IShardUninstallRequest>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
const suit = inventory.Suits.id(request.SuitId.$oid)!;
|
||||
|
||||
const miscItemChanges: IMiscItem[] = [];
|
||||
if (suit.ArchonCrystalUpgrades![request.Slot].Color) {
|
||||
// refund shard
|
||||
const shard = Object.entries(colorToShard).find(
|
||||
([color]) => color == suit.ArchonCrystalUpgrades![request.Slot].Color
|
||||
)![1];
|
||||
miscItemChanges.push({
|
||||
ItemType: shard,
|
||||
ItemCount: 1
|
||||
});
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
}
|
||||
|
||||
// remove from suit
|
||||
suit.ArchonCrystalUpgrades![request.Slot] = {};
|
||||
|
||||
if (!config.infiniteHelminthMaterials) {
|
||||
// remove bile
|
||||
const bile = inventory.InfestedFoundry!.Resources!.find(
|
||||
x => x.ItemType == "/Lotus/Types/Items/InfestedFoundry/HelminthBile"
|
||||
)!;
|
||||
bile.Count -= 300;
|
||||
}
|
||||
|
||||
await inventory.save();
|
||||
|
||||
const infestedFoundry = inventory.toJSON<IInventoryClient>().InfestedFoundry!;
|
||||
applyCheatsToInfestedFoundry(infestedFoundry);
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
MiscItems: miscItemChanges,
|
||||
InfestedFoundry: infestedFoundry
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "n": {
|
||||
// name the beast
|
||||
const request = getJSONfromString<IHelminthNameRequest>(String(req.body));
|
||||
const request = getJSONfromString(String(req.body)) as IHelminthNameRequest;
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.InfestedFoundry ??= {};
|
||||
inventory.InfestedFoundry.Name = request.newName;
|
||||
@ -113,251 +53,13 @@ export const infestedFoundryController: RequestHandler = async (req, res) => {
|
||||
break;
|
||||
}
|
||||
|
||||
case "c": {
|
||||
// consume items
|
||||
|
||||
if (config.infiniteHelminthMaterials) {
|
||||
res.status(400).end();
|
||||
return;
|
||||
}
|
||||
|
||||
const request = getJSONfromString<IHelminthFeedRequest>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.InfestedFoundry ??= {};
|
||||
inventory.InfestedFoundry.Resources ??= [];
|
||||
|
||||
const miscItemChanges: IMiscItem[] = [];
|
||||
let totalPercentagePointsGained = 0;
|
||||
|
||||
const currentUnixSeconds = Math.trunc(Date.now() / 1000);
|
||||
|
||||
for (const contribution of request.ResourceContributions) {
|
||||
const snack = ExportMisc.helminthSnacks[contribution.ItemType];
|
||||
|
||||
// tally items for removal
|
||||
const change = miscItemChanges.find(x => x.ItemType == contribution.ItemType);
|
||||
if (change) {
|
||||
change.ItemCount -= snack.count;
|
||||
} else {
|
||||
miscItemChanges.push({ ItemType: contribution.ItemType, ItemCount: snack.count * -1 });
|
||||
}
|
||||
|
||||
if (snack.type == "/Lotus/Types/Items/InfestedFoundry/HelminthAppetiteCooldownReducer") {
|
||||
// sentinent apetite
|
||||
let mostDislikedSnackRecord: IHelminthFoodRecord = { ItemType: "", Date: 0 };
|
||||
for (const resource of inventory.InfestedFoundry.Resources) {
|
||||
if (resource.RecentlyConvertedResources) {
|
||||
for (const record of resource.RecentlyConvertedResources) {
|
||||
if (record.Date > mostDislikedSnackRecord.Date) {
|
||||
mostDislikedSnackRecord = record;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
logger.debug("helminth eats sentient resource; most disliked snack:", {
|
||||
type: mostDislikedSnackRecord.ItemType,
|
||||
date: mostDislikedSnackRecord.Date
|
||||
});
|
||||
mostDislikedSnackRecord.Date = currentUnixSeconds + 24 * 60 * 60; // Possibly unfaithful
|
||||
continue;
|
||||
}
|
||||
|
||||
let resource = inventory.InfestedFoundry.Resources.find(x => x.ItemType == snack.type);
|
||||
if (!resource) {
|
||||
resource =
|
||||
inventory.InfestedFoundry.Resources[
|
||||
inventory.InfestedFoundry.Resources.push({ ItemType: snack.type, Count: 0 }) - 1
|
||||
];
|
||||
}
|
||||
|
||||
resource.RecentlyConvertedResources ??= [];
|
||||
let record = resource.RecentlyConvertedResources.find(x => x.ItemType == contribution.ItemType);
|
||||
if (!record) {
|
||||
record =
|
||||
resource.RecentlyConvertedResources[
|
||||
resource.RecentlyConvertedResources.push({ ItemType: contribution.ItemType, Date: 0 }) - 1
|
||||
];
|
||||
}
|
||||
|
||||
const hoursRemaining = (record.Date - currentUnixSeconds) / 3600;
|
||||
const apetiteFactor = apetiteModel(hoursRemaining) / 30;
|
||||
logger.debug(`helminth eating ${contribution.ItemType} (+${(snack.gain * 100).toFixed(0)}%)`, {
|
||||
hoursRemaining,
|
||||
apetiteFactor
|
||||
});
|
||||
if (hoursRemaining >= 18) {
|
||||
record.Date = currentUnixSeconds + 72 * 60 * 60; // Possibly unfaithful
|
||||
} else {
|
||||
record.Date = currentUnixSeconds + 24 * 60 * 60;
|
||||
}
|
||||
|
||||
totalPercentagePointsGained += snack.gain * 100 * apetiteFactor; // 30% would be gain=0.3, so percentage points is equal to gain * 100.
|
||||
resource.Count += Math.trunc(snack.gain * 1000 * apetiteFactor); // 30% would be gain=0.3 or Count=300, so Count=gain*1000.
|
||||
if (resource.Count > 1000) resource.Count = 1000;
|
||||
}
|
||||
|
||||
const recipeChanges = addInfestedFoundryXP(inventory.InfestedFoundry, 666 * totalPercentagePointsGained);
|
||||
addRecipes(inventory, recipeChanges);
|
||||
addMiscItems(inventory, miscItemChanges);
|
||||
await inventory.save();
|
||||
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
Recipes: recipeChanges,
|
||||
InfestedFoundry: {
|
||||
XP: inventory.InfestedFoundry.XP,
|
||||
Resources: inventory.InfestedFoundry.Resources,
|
||||
Slots: inventory.InfestedFoundry.Slots
|
||||
},
|
||||
MiscItems: miscItemChanges
|
||||
}
|
||||
});
|
||||
case "o": // offerings update
|
||||
// {"OfferingsIndex":540,"SuitTypes":["/Lotus/Powersuits/PaxDuviricus/PaxDuviricusBaseSuit","/Lotus/Powersuits/Nezha/NezhaBaseSuit","/Lotus/Powersuits/Devourer/DevourerBaseSuit"],"Extra":false}
|
||||
res.status(404).end();
|
||||
break;
|
||||
}
|
||||
|
||||
case "o": {
|
||||
// offerings update
|
||||
const request = getJSONfromString<IHelminthOfferingsUpdate>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.InfestedFoundry ??= {};
|
||||
inventory.InfestedFoundry.InvigorationIndex = request.OfferingsIndex;
|
||||
inventory.InfestedFoundry.InvigorationSuitOfferings = request.SuitTypes;
|
||||
if (request.Extra) {
|
||||
inventory.InfestedFoundry.InvigorationsApplied = 0;
|
||||
}
|
||||
await inventory.save();
|
||||
const infestedFoundry = inventory.toJSON<IInventoryClient>().InfestedFoundry!;
|
||||
applyCheatsToInfestedFoundry(infestedFoundry);
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
InfestedFoundry: infestedFoundry
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "a": {
|
||||
// subsume warframe
|
||||
const request = getJSONfromString<IHelminthSubsumeRequest>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
const recipe = getRecipe(request.Recipe)!;
|
||||
if (!config.infiniteHelminthMaterials) {
|
||||
for (const ingredient of recipe.secretIngredients!) {
|
||||
const resource = inventory.InfestedFoundry!.Resources!.find(x => x.ItemType == ingredient.ItemType);
|
||||
if (resource) {
|
||||
resource.Count -= ingredient.ItemCount;
|
||||
}
|
||||
}
|
||||
}
|
||||
const suit = inventory.Suits.id(request.SuitId.$oid)!;
|
||||
inventory.Suits.pull(suit);
|
||||
const consumedSuit: IConsumedSuit = { s: suit.ItemType };
|
||||
if (suit.Configs[0] && suit.Configs[0].pricol) {
|
||||
consumedSuit.c = suit.Configs[0].pricol;
|
||||
}
|
||||
if ((inventory.InfestedFoundry!.XP ?? 0) < 73125_00) {
|
||||
inventory.InfestedFoundry!.Slots!--;
|
||||
}
|
||||
inventory.InfestedFoundry!.ConsumedSuits ??= [];
|
||||
inventory.InfestedFoundry!.ConsumedSuits.push(consumedSuit);
|
||||
inventory.InfestedFoundry!.LastConsumedSuit = suit;
|
||||
inventory.InfestedFoundry!.AbilityOverrideUnlockCooldown = new Date(Date.now() + 24 * 60 * 60 * 1000);
|
||||
const recipeChanges = addInfestedFoundryXP(inventory.InfestedFoundry!, 1600_00);
|
||||
addRecipes(inventory, recipeChanges);
|
||||
freeUpSlot(inventory, InventorySlot.SUITS);
|
||||
await inventory.save();
|
||||
const infestedFoundry = inventory.toJSON<IInventoryClient>().InfestedFoundry!;
|
||||
applyCheatsToInfestedFoundry(infestedFoundry);
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
Recipes: recipeChanges,
|
||||
RemovedIdItems: [
|
||||
{
|
||||
ItemId: request.SuitId
|
||||
}
|
||||
],
|
||||
SuitBin: {
|
||||
count: -1,
|
||||
platinum: 0,
|
||||
Slots: 1
|
||||
},
|
||||
InfestedFoundry: infestedFoundry
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "r": {
|
||||
// rush subsume
|
||||
const inventory = await getInventory(accountId);
|
||||
const currencyChanges = updateCurrency(inventory, 50, true);
|
||||
const recipeChanges = handleSubsumeCompletion(inventory);
|
||||
await inventory.save();
|
||||
const infestedFoundry = inventory.toJSON<IInventoryClient>().InfestedFoundry!;
|
||||
applyCheatsToInfestedFoundry(infestedFoundry);
|
||||
res.json({
|
||||
InventoryChanges: {
|
||||
...currencyChanges,
|
||||
Recipes: recipeChanges,
|
||||
InfestedFoundry: infestedFoundry
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "u": {
|
||||
const request = getJSONfromString<IHelminthInvigorationRequest>(String(req.body));
|
||||
const inventory = await getInventory(accountId);
|
||||
const suit = inventory.Suits.id(request.SuitId.$oid)!;
|
||||
const upgradesExpiry = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
|
||||
suit.OffensiveUpgrade = request.OffensiveUpgradeType;
|
||||
suit.DefensiveUpgrade = request.DefensiveUpgradeType;
|
||||
suit.UpgradesExpiry = upgradesExpiry;
|
||||
const recipeChanges = addInfestedFoundryXP(inventory.InfestedFoundry!, 4800_00);
|
||||
addRecipes(inventory, recipeChanges);
|
||||
if (!config.infiniteHelminthMaterials) {
|
||||
for (let i = 0; i != request.ResourceTypes.length; ++i) {
|
||||
inventory.InfestedFoundry!.Resources!.find(x => x.ItemType == request.ResourceTypes[i])!.Count -=
|
||||
request.ResourceCosts[i];
|
||||
}
|
||||
}
|
||||
inventory.InfestedFoundry!.InvigorationsApplied ??= 0;
|
||||
inventory.InfestedFoundry!.InvigorationsApplied += 1;
|
||||
await inventory.save();
|
||||
const infestedFoundry = inventory.toJSON<IInventoryClient>().InfestedFoundry!;
|
||||
applyCheatsToInfestedFoundry(infestedFoundry);
|
||||
res.json({
|
||||
SuitId: request.SuitId,
|
||||
OffensiveUpgrade: request.OffensiveUpgradeType,
|
||||
DefensiveUpgrade: request.DefensiveUpgradeType,
|
||||
UpgradesExpiry: toMongoDate(upgradesExpiry),
|
||||
InventoryChanges: {
|
||||
Recipes: recipeChanges,
|
||||
InfestedFoundry: infestedFoundry
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case "custom_unlockall": {
|
||||
const inventory = await getInventory(accountId);
|
||||
inventory.InfestedFoundry ??= {};
|
||||
inventory.InfestedFoundry.XP ??= 0;
|
||||
if (151875_00 > inventory.InfestedFoundry.XP) {
|
||||
const recipeChanges = addInfestedFoundryXP(
|
||||
inventory.InfestedFoundry,
|
||||
151875_00 - inventory.InfestedFoundry.XP
|
||||
);
|
||||
addRecipes(inventory, recipeChanges);
|
||||
await inventory.save();
|
||||
}
|
||||
res.end();
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
logger.debug(`data provided to ${req.path}: ${String(req.body)}`);
|
||||
throw new Error(`unhandled infestedFoundry mode: ${String(req.query.mode)}`);
|
||||
throw new Error(`unhandled infestedFoundry mode: ${req.query.mode}`);
|
||||
}
|
||||
};
|
||||
|
||||
@ -368,74 +70,21 @@ interface IShardInstallRequest {
|
||||
Color: string;
|
||||
}
|
||||
|
||||
interface IShardUninstallRequest {
|
||||
SuitId: IOid;
|
||||
Slot: number;
|
||||
}
|
||||
|
||||
interface IHelminthNameRequest {
|
||||
newName: string;
|
||||
}
|
||||
|
||||
interface IHelminthFeedRequest {
|
||||
ResourceContributions: {
|
||||
ItemType: string;
|
||||
Date: number; // unix timestamp
|
||||
}[];
|
||||
}
|
||||
|
||||
interface IHelminthSubsumeRequest {
|
||||
SuitId: IOid;
|
||||
Recipe: string;
|
||||
}
|
||||
|
||||
interface IHelminthOfferingsUpdate {
|
||||
OfferingsIndex: number;
|
||||
SuitTypes: string[];
|
||||
Extra: boolean;
|
||||
}
|
||||
|
||||
interface IHelminthInvigorationRequest {
|
||||
SuitId: IOid;
|
||||
OffensiveUpgradeType: string;
|
||||
DefensiveUpgradeType: string;
|
||||
ResourceTypes: string[];
|
||||
ResourceCosts: number[];
|
||||
}
|
||||
|
||||
// A fitted model for observed apetite values. Likely slightly inaccurate.
|
||||
//
|
||||
// Hours remaining, percentage points gained (out of 30 total)
|
||||
// 0, 30
|
||||
// 5, 25.8
|
||||
// 10, 21.6
|
||||
// 12, 20
|
||||
// 16, 16.6
|
||||
// 17, 15.8
|
||||
// 18, 15
|
||||
// 20, 15
|
||||
// 24, 15
|
||||
// 36, 15
|
||||
// 40, 13.6
|
||||
// 47, 11.3
|
||||
// 48, 11
|
||||
// 50, 10.3
|
||||
// 60, 7
|
||||
// 70, 3.6
|
||||
// 71, 3.3
|
||||
// 72, 3
|
||||
const apetiteModel = (x: number): number => {
|
||||
if (x <= 0) {
|
||||
return 30;
|
||||
}
|
||||
if (x < 18) {
|
||||
return -0.84 * x + 30;
|
||||
}
|
||||
if (x <= 36) {
|
||||
return 15;
|
||||
}
|
||||
if (x < 71.9) {
|
||||
return -0.3327892 * x + 26.94135;
|
||||
}
|
||||
return 3;
|
||||
const colorToShard: Record<string, string> = {
|
||||
ACC_RED: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalAmar",
|
||||
ACC_RED_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalAmarMythic",
|
||||
ACC_YELLOW: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalNira",
|
||||
ACC_YELLOW_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalNiraMythic",
|
||||
ACC_BLUE: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalBoreal",
|
||||
ACC_BLUE_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalBorealMythic",
|
||||
ACC_GREEN: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalGreen",
|
||||
ACC_GREEN_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalGreenMythic",
|
||||
ACC_ORANGE: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalOrange",
|
||||
ACC_ORANGE_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalOrangeMythic",
|
||||
ACC_PURPLE: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalViolet",
|
||||
ACC_PURPLE_MYTHIC: "/Lotus/Types/Gameplay/NarmerSorties/ArchonCrystalVioletMythic"
|
||||
};
|
||||
|
@ -1,32 +1,20 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { Inventory, TInventoryDatabaseDocument } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import { toInventoryResponse } from "@/src/helpers/inventoryHelpers";
|
||||
import { Inventory } from "@/src/models/inventoryModels/inventoryModel";
|
||||
import { config } from "@/src/services/configService";
|
||||
import allDialogue from "@/static/fixed_responses/allDialogue.json";
|
||||
import { ILoadoutDatabase } from "@/src/types/saveLoadoutTypes";
|
||||
import { IInventoryClient, IShipInventory, equipmentKeys } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { IPolarity, ArtifactPolarity, EquipmentFeatures } from "@/src/types/inventoryTypes/commonInventoryTypes";
|
||||
import {
|
||||
ExportCustoms,
|
||||
ExportFlavour,
|
||||
ExportRegions,
|
||||
ExportResources,
|
||||
ExportVirtuals
|
||||
} from "warframe-public-export-plus";
|
||||
import { applyCheatsToInfestedFoundry, handleSubsumeCompletion } from "@/src/services/infestedFoundryService";
|
||||
import {
|
||||
addMiscItems,
|
||||
allDailyAffiliationKeys,
|
||||
cleanupInventory,
|
||||
createLibraryDailyTask,
|
||||
generateRewardSeed
|
||||
} from "@/src/services/inventoryService";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
import { catBreadHash } from "@/src/helpers/stringHelpers";
|
||||
import { Types } from "mongoose";
|
||||
import { IInventoryDatabase } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
//import new_inventory from "@/static/fixed_responses/postTutorialInventory.json";
|
||||
|
||||
export const inventoryController: RequestHandler = async (request, response) => {
|
||||
const accountId = await getAccountIdForRequest(request);
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const inventoryController: RequestHandler = async (request, response) => {
|
||||
let accountId;
|
||||
try {
|
||||
accountId = await getAccountIdForRequest(request);
|
||||
} catch (e) {
|
||||
response.status(400).send("Log-in expired");
|
||||
return;
|
||||
}
|
||||
|
||||
const inventory = await Inventory.findOne({ accountOwnerId: accountId });
|
||||
|
||||
@ -35,179 +23,49 @@ export const inventoryController: RequestHandler = async (request, response) =>
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle daily reset
|
||||
if (!inventory.NextRefill || Date.now() >= inventory.NextRefill.getTime()) {
|
||||
for (const key of allDailyAffiliationKeys) {
|
||||
inventory[key] = 16000 + inventory.PlayerLevel * 500;
|
||||
}
|
||||
inventory.DailyFocus = 250000 + inventory.PlayerLevel * 5000;
|
||||
inventory.GiftsRemaining = Math.max(8, inventory.PlayerLevel);
|
||||
inventory.TradesRemaining = inventory.PlayerLevel;
|
||||
//TODO: make a function that converts from database representation to client
|
||||
const inventoryJSON: IInventoryDatabase = inventory.toJSON();
|
||||
console.log(inventoryJSON.Ships);
|
||||
|
||||
inventory.LibraryAvailableDailyTaskInfo = createLibraryDailyTask();
|
||||
const inventoryResponse = toInventoryResponse(inventoryJSON);
|
||||
|
||||
if (inventory.NextRefill) {
|
||||
if (config.noArgonCrystalDecay) {
|
||||
inventory.FoundToday = undefined;
|
||||
} else {
|
||||
const lastLoginDay = Math.trunc(inventory.NextRefill.getTime() / 86400000) - 1;
|
||||
const today = Math.trunc(Date.now() / 86400000);
|
||||
const daysPassed = today - lastLoginDay;
|
||||
for (let i = 0; i != daysPassed; ++i) {
|
||||
const numArgonCrystals =
|
||||
inventory.MiscItems.find(x => x.ItemType == "/Lotus/Types/Items/MiscItems/ArgonCrystal")
|
||||
?.ItemCount ?? 0;
|
||||
if (numArgonCrystals == 0) {
|
||||
break;
|
||||
}
|
||||
const numStableArgonCrystals = Math.min(
|
||||
numArgonCrystals,
|
||||
inventory.FoundToday?.find(x => x.ItemType == "/Lotus/Types/Items/MiscItems/ArgonCrystal")
|
||||
?.ItemCount ?? 0
|
||||
);
|
||||
const numDecayingArgonCrystals = numArgonCrystals - numStableArgonCrystals;
|
||||
const numDecayingArgonCrystalsToRemove = Math.ceil(numDecayingArgonCrystals / 2);
|
||||
logger.debug(`ticking argon crystals for day ${i + 1} of ${daysPassed}`, {
|
||||
numArgonCrystals,
|
||||
numStableArgonCrystals,
|
||||
numDecayingArgonCrystals,
|
||||
numDecayingArgonCrystalsToRemove
|
||||
});
|
||||
// Remove half of owned decaying argon crystals
|
||||
addMiscItems(inventory, [
|
||||
{
|
||||
ItemType: "/Lotus/Types/Items/MiscItems/ArgonCrystal",
|
||||
ItemCount: numDecayingArgonCrystalsToRemove * -1
|
||||
}
|
||||
]);
|
||||
// All stable argon crystals are now decaying
|
||||
inventory.FoundToday = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cleanupInventory(inventory);
|
||||
|
||||
inventory.NextRefill = new Date((Math.trunc(Date.now() / 86400000) + 1) * 86400000);
|
||||
//await inventory.save();
|
||||
}
|
||||
|
||||
if (
|
||||
inventory.InfestedFoundry &&
|
||||
inventory.InfestedFoundry.AbilityOverrideUnlockCooldown &&
|
||||
new Date() >= inventory.InfestedFoundry.AbilityOverrideUnlockCooldown
|
||||
) {
|
||||
handleSubsumeCompletion(inventory);
|
||||
//await inventory.save();
|
||||
}
|
||||
|
||||
if (inventory.LastInventorySync) {
|
||||
const lastSyncDuviriMood = Math.trunc(inventory.LastInventorySync.getTimestamp().getTime() / 7200000);
|
||||
const currentDuviriMood = Math.trunc(Date.now() / 7200000);
|
||||
if (lastSyncDuviriMood != currentDuviriMood) {
|
||||
logger.debug(`refreshing duviri seed`);
|
||||
inventory.DuviriInfo.Seed = generateRewardSeed();
|
||||
}
|
||||
}
|
||||
inventory.LastInventorySync = new Types.ObjectId();
|
||||
await inventory.save();
|
||||
|
||||
response.json(await getInventoryResponse(inventory, "xpBasedLevelCapDisabled" in request.query));
|
||||
};
|
||||
|
||||
export const getInventoryResponse = async (
|
||||
inventory: TInventoryDatabaseDocument,
|
||||
xpBasedLevelCapDisabled: boolean
|
||||
): Promise<IInventoryClient> => {
|
||||
const inventoryWithLoadOutPresets = await inventory.populate<{ LoadOutPresets: ILoadoutDatabase }>(
|
||||
"LoadOutPresets"
|
||||
);
|
||||
const inventoryWithLoadOutPresetsAndShips = await inventoryWithLoadOutPresets.populate<{ Ships: IShipInventory }>(
|
||||
"Ships"
|
||||
);
|
||||
const inventoryResponse = inventoryWithLoadOutPresetsAndShips.toJSON<IInventoryClient>();
|
||||
|
||||
if (config.infiniteCredits) {
|
||||
if (config.infiniteResources) {
|
||||
inventoryResponse.RegularCredits = 999999999;
|
||||
}
|
||||
if (config.infinitePlatinum) {
|
||||
inventoryResponse.PremiumCreditsFree = 0;
|
||||
inventoryResponse.PremiumCredits = 999999999;
|
||||
}
|
||||
if (config.infiniteEndo) {
|
||||
inventoryResponse.FusionPoints = 999999999;
|
||||
}
|
||||
if (config.infiniteRegalAya) {
|
||||
inventoryResponse.PrimeTokens = 999999999;
|
||||
}
|
||||
|
||||
if (config.skipAllDialogue) {
|
||||
inventoryResponse.TauntHistory = [
|
||||
{
|
||||
node: "TreasureTutorial",
|
||||
state: "TS_COMPLETED"
|
||||
}
|
||||
];
|
||||
for (const str of allDialogue) {
|
||||
addString(inventoryResponse.NodeIntrosCompleted, str);
|
||||
}
|
||||
}
|
||||
// if (config.unlockAllMissions) {
|
||||
// //inventoryResponse.Missions = allMissions;
|
||||
// //inventoryResponse.NodeIntrosCompleted.push("TeshinHardModeUnlocked");
|
||||
// }
|
||||
|
||||
if (config.unlockAllMissions) {
|
||||
inventoryResponse.Missions = [];
|
||||
for (const tag of Object.keys(ExportRegions)) {
|
||||
inventoryResponse.Missions.push({
|
||||
Completes: 1,
|
||||
Tier: 1,
|
||||
Tag: tag
|
||||
});
|
||||
}
|
||||
addString(inventoryResponse.NodeIntrosCompleted, "TeshinHardModeUnlocked");
|
||||
}
|
||||
// if (config.unlockAllMissions) {
|
||||
// //inventoryResponse.Missions = allMissions;
|
||||
// //addString(inventoryResponse.NodeIntrosCompleted, "TeshinHardModeUnlocked");
|
||||
// }
|
||||
|
||||
if (config.unlockAllShipDecorations) {
|
||||
inventoryResponse.ShipDecorations = [];
|
||||
for (const [uniqueName, item] of Object.entries(ExportResources)) {
|
||||
if (item.productCategory == "ShipDecorations") {
|
||||
inventoryResponse.ShipDecorations.push({ ItemType: uniqueName, ItemCount: 999_999 });
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (config.unlockAllFlavourItems) {
|
||||
// inventoryResponse.FlavourItems = [];
|
||||
// for (const uniqueName in ExportFlavour) {
|
||||
// inventoryResponse.FlavourItems.push({ ItemType: uniqueName });
|
||||
// }
|
||||
// }
|
||||
|
||||
if (config.unlockAllFlavourItems) {
|
||||
inventoryResponse.FlavourItems = [];
|
||||
for (const uniqueName in ExportFlavour) {
|
||||
inventoryResponse.FlavourItems.push({ ItemType: uniqueName });
|
||||
}
|
||||
}
|
||||
|
||||
if (config.unlockAllSkins) {
|
||||
const missingWeaponSkins = new Set(Object.keys(ExportCustoms));
|
||||
inventoryResponse.WeaponSkins.forEach(x => missingWeaponSkins.delete(x.ItemType));
|
||||
for (const uniqueName of missingWeaponSkins) {
|
||||
inventoryResponse.WeaponSkins.push({
|
||||
ItemId: {
|
||||
$oid: "ca70ca70ca70ca70" + catBreadHash(uniqueName).toString(16).padStart(8, "0")
|
||||
},
|
||||
ItemType: uniqueName
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (config.unlockAllCapturaScenes) {
|
||||
for (const uniqueName of Object.keys(ExportResources)) {
|
||||
if (resourceInheritsFrom(uniqueName, "/Lotus/Types/Items/MiscItems/PhotoboothTile")) {
|
||||
inventoryResponse.MiscItems.push({
|
||||
ItemType: uniqueName,
|
||||
ItemCount: 1
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// if (config.unlockAllSkins) {
|
||||
// inventoryResponse.WeaponSkins = [];
|
||||
// for (const uniqueName in ExportCustoms) {
|
||||
// inventoryResponse.WeaponSkins.push({
|
||||
// ItemId: {
|
||||
// $id: "000000000000000000000000"
|
||||
// },
|
||||
// ItemType: uniqueName
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
if (typeof config.spoofMasteryRank === "number" && config.spoofMasteryRank >= 0) {
|
||||
inventoryResponse.PlayerLevel = config.spoofMasteryRank;
|
||||
if (!xpBasedLevelCapDisabled) {
|
||||
if (!("xpBasedLevelCapDisabled" in request.query)) {
|
||||
// This client has not been patched to accept any mastery rank, need to fake the XP.
|
||||
inventoryResponse.XPInfo = [];
|
||||
let numFrames = getExpRequiredForMr(Math.min(config.spoofMasteryRank, 5030)) / 6000;
|
||||
@ -220,86 +78,18 @@ export const getInventoryResponse = async (
|
||||
}
|
||||
}
|
||||
|
||||
if (config.universalPolarityEverywhere) {
|
||||
const Polarity: IPolarity[] = [];
|
||||
// 12 is needed for necramechs. 15 is needed for plexus/crewshipharness.
|
||||
for (let i = 0; i != 15; ++i) {
|
||||
Polarity.push({
|
||||
Slot: i,
|
||||
Value: ArtifactPolarity.Any
|
||||
});
|
||||
}
|
||||
for (const key of equipmentKeys) {
|
||||
if (key in inventoryResponse) {
|
||||
for (const equipment of inventoryResponse[key]) {
|
||||
equipment.Polarity = Polarity;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fix for #380
|
||||
inventoryResponse.NextRefill = { $date: { $numberLong: "9999999999999" } };
|
||||
|
||||
if (config.unlockDoubleCapacityPotatoesEverywhere) {
|
||||
for (const key of equipmentKeys) {
|
||||
if (key in inventoryResponse) {
|
||||
for (const equipment of inventoryResponse[key]) {
|
||||
equipment.Features ??= 0;
|
||||
equipment.Features |= EquipmentFeatures.DOUBLE_CAPACITY;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (config.unlockExilusEverywhere) {
|
||||
for (const key of equipmentKeys) {
|
||||
if (key in inventoryResponse) {
|
||||
for (const equipment of inventoryResponse[key]) {
|
||||
equipment.Features ??= 0;
|
||||
equipment.Features |= EquipmentFeatures.UTILITY_SLOT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (config.unlockArcanesEverywhere) {
|
||||
for (const key of equipmentKeys) {
|
||||
if (key in inventoryResponse) {
|
||||
for (const equipment of inventoryResponse[key]) {
|
||||
equipment.Features ??= 0;
|
||||
equipment.Features |= EquipmentFeatures.ARCANE_SLOT;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (config.noDailyStandingLimits) {
|
||||
const spoofedDailyAffiliation = Math.max(999_999, 16000 + inventoryResponse.PlayerLevel * 500);
|
||||
for (const key of allDailyAffiliationKeys) {
|
||||
inventoryResponse[key] = spoofedDailyAffiliation;
|
||||
}
|
||||
}
|
||||
|
||||
if (config.noDailyFocusLimit) {
|
||||
inventoryResponse.DailyFocus = Math.max(999_999, 250000 + inventoryResponse.PlayerLevel * 5000);
|
||||
}
|
||||
|
||||
if (inventoryResponse.InfestedFoundry) {
|
||||
applyCheatsToInfestedFoundry(inventoryResponse.InfestedFoundry);
|
||||
}
|
||||
|
||||
// Omitting this field so opening the navigation resyncs the inventory which is more desirable for typical usage.
|
||||
inventoryResponse.LastInventorySync = undefined;
|
||||
|
||||
// Set 2FA enabled so trading post can be used
|
||||
inventoryResponse.HWIDProtectEnabled = true;
|
||||
|
||||
return inventoryResponse;
|
||||
response.json(inventoryResponse);
|
||||
};
|
||||
|
||||
/*
|
||||
const addString = (arr: string[], str: string): void => {
|
||||
if (!arr.find(x => x == str)) {
|
||||
arr.push(str);
|
||||
}
|
||||
};
|
||||
};*/
|
||||
|
||||
const getExpRequiredForMr = (rank: number): number => {
|
||||
if (rank <= 30) {
|
||||
@ -308,20 +98,4 @@ const getExpRequiredForMr = (rank: number): number => {
|
||||
return 2_250_000 + 147_500 * (rank - 30);
|
||||
};
|
||||
|
||||
const resourceInheritsFrom = (resourceName: string, targetName: string): boolean => {
|
||||
let parentName = resourceGetParent(resourceName);
|
||||
for (; parentName != undefined; parentName = resourceGetParent(parentName)) {
|
||||
if (parentName == targetName) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
const resourceGetParent = (resourceName: string): string | undefined => {
|
||||
if (resourceName in ExportResources) {
|
||||
return ExportResources[resourceName].parentName;
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
return ExportVirtuals[resourceName]?.parentName;
|
||||
};
|
||||
export { inventoryController };
|
||||
|
@ -1,9 +1,8 @@
|
||||
import { getAccountIdForRequest } from "@/src/services/loginService";
|
||||
import { getInventory, updateCurrency } from "@/src/services/inventoryService";
|
||||
import { updateCurrency } from "@/src/services/inventoryService";
|
||||
import { RequestHandler } from "express";
|
||||
import { updateSlots } from "@/src/services/inventoryService";
|
||||
import { InventorySlot } from "@/src/types/inventoryTypes/inventoryTypes";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
|
||||
/*
|
||||
loadout slots are additionally purchased slots only
|
||||
@ -19,22 +18,19 @@ import { logger } from "@/src/utils/logger";
|
||||
number of frames = extra - slots + 2
|
||||
*/
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
export const inventorySlotsController: RequestHandler = async (req, res) => {
|
||||
const accountId = await getAccountIdForRequest(req);
|
||||
const body = JSON.parse(req.body as string) as IInventorySlotsRequest;
|
||||
//const body = JSON.parse(req.body as string) as IInventorySlotsRequest;
|
||||
|
||||
if (body.Bin != InventorySlot.SUITS && body.Bin != InventorySlot.PVE_LOADOUTS) {
|
||||
logger.warn(`unexpected slot purchase of type ${body.Bin}, account may be overcharged`);
|
||||
}
|
||||
//console.log(body);
|
||||
|
||||
const inventory = await getInventory(accountId);
|
||||
const currencyChanges = updateCurrency(inventory, 20, true);
|
||||
updateSlots(inventory, body.Bin, 1, 1);
|
||||
await inventory.save();
|
||||
//TODO: check which slot was purchased because pvpBonus is also possible
|
||||
|
||||
const currencyChanges = await updateCurrency(20, true, accountId);
|
||||
await updateSlots(accountId, InventorySlot.PVE_LOADOUTS, 1, 1);
|
||||
|
||||
//console.log({ InventoryChanges: currencyChanges }, " added loadout changes:");
|
||||
|
||||
res.json({ InventoryChanges: currencyChanges });
|
||||
};
|
||||
|
||||
interface IInventorySlotsRequest {
|
||||
Bin: InventorySlot;
|
||||
}
|
||||
|
@ -2,13 +2,12 @@ import { RequestHandler } from "express";
|
||||
import { getSessionByID } from "@/src/managers/sessionManager";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
|
||||
export const joinSessionController: RequestHandler = (req, res) => {
|
||||
const reqBody = JSON.parse(String(req.body)) as IJoinSessionRequest;
|
||||
const joinSessionController: RequestHandler = (_req, res) => {
|
||||
const reqBody = JSON.parse(String(_req.body));
|
||||
logger.debug(`JoinSession Request`, { reqBody });
|
||||
const session = getSessionByID(reqBody.sessionIds[0]);
|
||||
res.json({ rewardSeed: session?.rewardSeed, sessionId: { $oid: session?.sessionId } });
|
||||
const req = JSON.parse(String(_req.body));
|
||||
const session = getSessionByID(req.sessionIds[0] as string);
|
||||
res.json({ rewardSeed: session?.rewardSeed, sessionId: { $id: session?.sessionId } });
|
||||
};
|
||||
|
||||
interface IJoinSessionRequest {
|
||||
sessionIds: string[];
|
||||
}
|
||||
export { joinSessionController };
|
||||
|
@ -1,55 +1,43 @@
|
||||
/* eslint-disable @typescript-eslint/no-unused-vars */
|
||||
import { RequestHandler } from "express";
|
||||
|
||||
import { config } from "@/src/services/configService";
|
||||
import { buildConfig } from "@/src/services/buildConfigService";
|
||||
import buildConfig from "@/static/data/buildConfig.json";
|
||||
|
||||
import { toLoginRequest } from "@/src/helpers/loginHelpers";
|
||||
import { Account } from "@/src/models/loginModel";
|
||||
import { createAccount, isCorrectPassword, isNameTaken } from "@/src/services/loginService";
|
||||
import { IDatabaseAccountJson, ILoginRequest, ILoginResponse } from "@/src/types/loginTypes";
|
||||
import { createAccount, isCorrectPassword } from "@/src/services/loginService";
|
||||
import { ILoginResponse } from "@/src/types/loginTypes";
|
||||
import { logger } from "@/src/utils/logger";
|
||||
|
||||
export const loginController: RequestHandler = async (request, response) => {
|
||||
const loginRequest = JSON.parse(String(request.body)) as ILoginRequest; // parse octet stream of json data to json object
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
const loginController: RequestHandler = async (request, response) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-argument
|
||||
const body = JSON.parse(request.body); // parse octet stream of json data to json object
|
||||
const loginRequest = toLoginRequest(body);
|
||||
|
||||
const account = await Account.findOne({ email: loginRequest.email });
|
||||
const nonce = Math.round(Math.random() * Number.MAX_SAFE_INTEGER);
|
||||
|
||||
const buildLabel: string =
|
||||
typeof request.query.buildLabel == "string"
|
||||
? request.query.buildLabel.split(" ").join("+")
|
||||
: buildConfig.buildLabel;
|
||||
|
||||
const myAddress = request.host.indexOf("warframe.com") == -1 ? request.host : config.myAddress;
|
||||
|
||||
if (
|
||||
!account &&
|
||||
((config.autoCreateAccount && loginRequest.ClientType != "webui") ||
|
||||
loginRequest.ClientType == "webui-register")
|
||||
) {
|
||||
if (!account && config.autoCreateAccount && loginRequest.ClientType != "webui") {
|
||||
try {
|
||||
const nameFromEmail = loginRequest.email.substring(0, loginRequest.email.indexOf("@"));
|
||||
let name = nameFromEmail || loginRequest.email.substring(1) || "SpaceNinja";
|
||||
if (await isNameTaken(name)) {
|
||||
let suffix = 0;
|
||||
do {
|
||||
++suffix;
|
||||
name = nameFromEmail + suffix;
|
||||
} while (await isNameTaken(name));
|
||||
}
|
||||
const newAccount = await createAccount({
|
||||
email: loginRequest.email,
|
||||
password: loginRequest.password,
|
||||
DisplayName: name,
|
||||
CountryCode: loginRequest.lang.toUpperCase(),
|
||||
ClientType: loginRequest.ClientType == "webui-register" ? "webui" : loginRequest.ClientType,
|
||||
CrossPlatformAllowed: true,
|
||||
ForceLogoutVersion: 0,
|
||||
ConsentNeeded: false,
|
||||
TrackedSettings: [],
|
||||
DisplayName: loginRequest.email.substring(0, loginRequest.email.indexOf("@")),
|
||||
Nonce: nonce
|
||||
});
|
||||
logger.debug("created new account");
|
||||
response.json(createLoginResponse(myAddress, newAccount, buildLabel));
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { email, password, ...databaseAccount } = newAccount;
|
||||
const newLoginResponse: ILoginResponse = {
|
||||
...databaseAccount,
|
||||
BuildLabel: buildConfig.buildLabel,
|
||||
NatHash: "0",
|
||||
SteamId: "0"
|
||||
};
|
||||
|
||||
response.json(newLoginResponse);
|
||||
return;
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof Error) {
|
||||
@ -58,61 +46,27 @@ export const loginController: RequestHandler = async (request, response) => {
|
||||
}
|
||||
}
|
||||
|
||||
if (!account) {
|
||||
response.status(400).json({ error: "unknown user" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginRequest.ClientType == "webui-register") {
|
||||
response.status(400).json({ error: "account already exists" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isCorrectPassword(loginRequest.password, account.password)) {
|
||||
//email not found or incorrect password
|
||||
if (!account || !isCorrectPassword(loginRequest.password, account.password)) {
|
||||
response.status(400).json({ error: "incorrect login data" });
|
||||
return;
|
||||
}
|
||||
|
||||
if (loginRequest.ClientType == "webui") {
|
||||
if (!account.Nonce) {
|
||||
account.ClientType = "webui";
|
||||
account.Nonce = nonce;
|
||||
}
|
||||
} else {
|
||||
if (account.Nonce && account.ClientType != "webui" && !account.Dropped && !loginRequest.kick) {
|
||||
response.status(400).json({ error: "nonce still set" });
|
||||
return;
|
||||
}
|
||||
|
||||
account.ClientType = loginRequest.ClientType;
|
||||
if (account.Nonce == 0 || loginRequest.ClientType != "webui") {
|
||||
account.Nonce = nonce;
|
||||
account.CountryCode = loginRequest.lang.toUpperCase();
|
||||
}
|
||||
|
||||
await account.save();
|
||||
|
||||
response.json(createLoginResponse(myAddress, account.toJSON(), buildLabel));
|
||||
const { email, password, ...databaseAccount } = account.toJSON();
|
||||
const newLoginResponse: ILoginResponse = {
|
||||
...databaseAccount,
|
||||
BuildLabel: buildConfig.buildLabel,
|
||||
NatHash: "0",
|
||||
SteamId: "0"
|
||||
};
|
||||
|
||||
response.json(newLoginResponse);
|
||||
};
|
||||
|
||||
const createLoginResponse = (myAddress: string, account: IDatabaseAccountJson, buildLabel: string): ILoginResponse => {
|
||||
return {
|
||||
id: account.id,
|
||||
DisplayName: account.DisplayName,
|
||||
CountryCode: account.CountryCode,
|
||||
ClientType: account.ClientType,
|
||||
CrossPlatformAllowed: account.CrossPlatformAllowed,
|
||||
ForceLogoutVersion: account.ForceLogoutVersion,
|
||||
AmazonAuthToken: account.AmazonAuthToken,
|
||||
AmazonRefreshToken: account.AmazonRefreshToken,
|
||||
ConsentNeeded: account.ConsentNeeded,
|
||||
TrackedSettings: account.TrackedSettings,
|
||||
Nonce: account.Nonce,
|
||||
Groups: [],
|
||||
IRC: config.myIrcAddresses ?? [myAddress],
|
||||
platformCDNs: [`https://${myAddress}/`],
|
||||
HUB: `https://${myAddress}/api/`,
|
||||
NRS: config.NRS,
|
||||
DTLS: 99,
|
||||
BuildLabel: buildLabel,
|
||||
MatchmakingBuildId: buildConfig.matchmakingBuildId
|
||||
};
|
||||
};
|
||||
export { loginController };
|
||||
|
@ -1,55 +1,8 @@
|
||||
import { RequestHandler } from "express";
|
||||
import { getAccountForRequest } from "@/src/services/loginService";
|
||||
import {
|
||||
claimLoginReward,
|
||||
getRandomLoginRewards,
|
||||
ILoginRewardsReponse,
|
||||
isLoginRewardAChoice,
|
||||
setAccountGotLoginRewardToday
|
||||
} from "@/src/services/loginRewardService";
|
||||
import { getInventory } from "@/src/services/inventoryService";
|
||||
import loginRewards from "@/static/fixed_responses/loginRewards.json";
|
||||
|
||||
export const loginRewardsController: RequestHandler = async (req, res) => {
|
||||
const account = await getAccountForRequest(req);
|
||||
const today = Math.trunc(Date.now() / 86400000) * 86400;
|
||||
const isMilestoneDay = account.LoginDays == 5 || account.LoginDays % 50 == 0;
|
||||
const nextMilestoneDay = account.LoginDays < 5 ? 5 : (Math.trunc(account.LoginDays / 50) + 1) * 50;
|
||||
|
||||
if (today == account.LastLoginRewardDate) {
|
||||
res.json({
|
||||
DailyTributeInfo: {
|
||||
IsMilestoneDay: isMilestoneDay,
|
||||
IsChooseRewardSet: isLoginRewardAChoice(account),
|
||||
LoginDays: account.LoginDays,
|
||||
NextMilestoneReward: "",
|
||||
NextMilestoneDay: nextMilestoneDay
|
||||
}
|
||||
} satisfies ILoginRewardsReponse);
|
||||
return;
|
||||
}
|
||||
|
||||
const inventory = await getInventory(account._id.toString());
|
||||
const randomRewards = getRandomLoginRewards(account, inventory);
|
||||
const response: ILoginRewardsReponse = {
|
||||
DailyTributeInfo: {
|
||||
Rewards: randomRewards,
|
||||
IsMilestoneDay: isMilestoneDay,
|
||||
IsChooseRewardSet: randomRewards.length != 1,
|
||||
LoginDays: account.LoginDays,
|
||||
NextMilestoneReward: "",
|
||||
NextMilestoneDay: nextMilestoneDay,
|
||||
HasChosenReward: false
|
||||
},
|
||||
LastLoginRewardDate: today
|
||||
};
|
||||
if (!isMilestoneDay && randomRewards.length == 1) {
|
||||
response.DailyTributeInfo.HasChosenReward = true;
|
||||
response.DailyTributeInfo.ChosenReward = randomRewards[0];
|
||||
response.DailyTributeInfo.NewInventory = await claimLoginReward(inventory, randomRewards[0]);
|
||||
await inventory.save();
|
||||
|
||||
setAccountGotLoginRewardToday(account);
|
||||
await account.save();
|
||||
}
|
||||
res.json(response);
|
||||
const loginRewardsController: RequestHandler = (_req, res) => {
|
||||
res.json(loginRewards);
|
||||
};
|
||||
|
||||
export { loginRewardsController };
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user