Merge pull request #148 from Artem89233/patch-1

Seems ok!
This commit is contained in:
Lucca Faria Ferri 2024-03-16 10:35:05 +00:00 committed by GitHub
commit 72ee5542a7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
984 changed files with 44550 additions and 48136 deletions

45
.github/workflows/github-ci.yml vendored Normal file
View File

@ -0,0 +1,45 @@
name: Build
on:
# Triggers the workflow on push or pull request events but only for the selected branches
push:
branches: [ test-stable, community ]
pull_request:
branches: [ test-stable, community ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
build:
runs-on: ${{ matrix.os }}
continue-on-error: ${{ matrix.allow_failures }}
name: ${{ matrix.name }} / ${{ matrix.config }}
strategy:
matrix:
config: [Debug, Release]
include:
# for the matrix leg matching the os and version
- os: ubuntu-22.04
name: Ubuntu 22.04 (.Net 7.0)
toolchain: dotnet-sdk-7.0
allow_failures: true
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
- name: Install dependencies (apt)
if: runner.os == 'Linux'
run: |
wget https://packages.microsoft.com/config/ubuntu/22.04/packages-microsoft-prod.deb -O packages-microsoft-prod.deb
sudo dpkg -i packages-microsoft-prod.deb
rm packages-microsoft-prod.deb
sudo apt-get update && sudo apt-get install -y ${{ matrix.toolchain }}
- name: Build (dotnet)
run: |
dotnet restore src/Blizzless-D3.sln
dotnet msbuild src/Blizzless-D3.sln /t:Build /p:Configuration=${{ matrix.config }}

4
.gitignore vendored
View File

@ -35,6 +35,10 @@ bld/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Rider cache
.idea/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/

View File

@ -27,7 +27,6 @@ DiIiS is a fully-functional open-source local server for [Diablo III: Reaper of
## Restrictions
- Donate Store implementation is removed.
- NAT support is hidden, but possible ;)
# Installation
@ -38,16 +37,37 @@ Each version of the client includes changes to structures, opcodes and attribute
The currently supported version of the client: **2.7.4.84161**
## Server Deploying
### Prepare Database
#### Manual
1. Install [PostgreSQL 9.5.25](https://www.enterprisedb.com/downloads/postgres-postgresql-downloads).
2. Create databases in PostgreSQL: `diiis` and `worlds`.
3. Change you account and password in `database.Account.config` and `database.Worlds.conifg`.
4. Restore `worlds.backup` to `worlds` database.
5. Compile by [VS 2019/2022](https://visualstudio.microsoft.com/).
6. [Skip this stage for local game] Copy the [config.ini](configs/config.ini) file to the server folder (It overwrites the default settings):
#### Or using docker
1. [Install docker](https://docs.docker.com/get-docker/)
2. Run `docker-compose up` inside [db](db) folder.
### Compile and run
1. Install [.NET 7 SDK and runtime](https://dotnet.microsoft.com/en-us/download/dotnet/7.0) (just runtime, not asp.net or desktop)
2. Go to the repo directory and compile the project using this command:
```shell
dotnet publish ./src/DiIiS-NA/Blizzless.csproj --configuration Release --output ./publish
```
3. [Skip this stage for local game] Copy the [config.ini](configs/config.ini) file to the publish folder (It overwrites the default settings):
- Update the parameter entries with your IP record on the network: `BindIP` and `PublicIP`.
7. Launch wait until server start, it creates a hierarchy.
8. Create user account(s) using console: `!account add Login Password Tag`
4. Go to the publish folder, launch Blizzless executable, wait until server start - it creates a hierarchy.
5. Create user account(s) using console: `!account add Login Password Tag`
#### Example:
> !account add username@ YourPassword YourBattleTag
Creates an account with Login `username@`, password `YourPassword` and BattleTag `YourBattleTag`
> !account add username@ YourPassword YourBattleTag owner
Creates an account with Login `username@`, password `YourPassword` and BattleTag `YourBattleTag` with rank `owner`
### Example:
@ -71,7 +91,7 @@ Do this for each client connecting to the server.
**Method #1 - Hosts**
Add redirects to the `hosts` file (`%WinDir%\System32\drivers\etc\hosts`):
Add redirects to the `hosts` file (Windows - `%WinDir%\System32\drivers\etc\hosts`, Linux - `/etc/hosts`):
`127.0.0.1 us.actual.battle.net`
`127.0.0.1 eu.actual.battle.net`
@ -95,10 +115,6 @@ Do this for each client connecting to the server.
7. You're in the game world!
## Using Docker
Run `docker-compose up` inside [db](db) folder and continue from the 5th step in section [server](#server-deploying).
# Server Configuration
## Global configuration

View File

@ -1,36 +1,19 @@
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.GameServer.GSSystem.ActorSystem;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.ActorSystem.Implementations.Hirelings;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.GameSystem;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.PlayerSystem;
//Blizzless Project 2022
using DiIiS_NA.GameServer.MessageSystem;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents;
//Blizzless Project 2022
using DiIiS_NA.GameServer.Core.Types.Math;
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Math;
//Blizzless Project 2022
using DiIiS_NA.GameServer.Core.Types.TagMap;
//Blizzless Project 2022
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Animation;
//Blizzless Project 2022
using System.Threading.Tasks;
//Blizzless Project 2022
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Base;
using DiIiS_NA.D3_GameServer.Core.Types.SNO;
@ -65,7 +48,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
StartConversation(world, 17923);
SkeletonKing_Bridge.PlayAnimation(5, SkeletonKing_Bridge.AnimationSet.TagMapAnimDefault[AnimationSetKeys.Opening], 1f);
SkeletonKing_Bridge.PlayAnimation(5, (AnimationSno)SkeletonKing_Bridge.AnimationSet.TagMapAnimDefault[AnimationSetKeys.Opening], 1f);
world.BroadcastIfRevealed(plr => new SetIdleAnimationMessage
{
@ -89,7 +72,7 @@ namespace DiIiS_NA.GameServer.GSSystem.QuestSystem.QuestEvents.Implementations
var spawner = world.GetActorBySNO(ActorSno._trdun_rescuecainskelspawner);
while (spawner != null)
{
var monster = FastRandom.Instance.Next(10) % 2 == 0 ? ActorSno._skeletonking_shield_skeleton : ActorSno._skeletonking_skeleton;
var monster = ActorSno._skeletonking_shield_skeleton;
world.SpawnMonster(monster, spawner.Position);
spawner.Destroy();
spawner = world.GetActorBySNO(ActorSno._trdun_rescuecainskelspawner);

View File

@ -1,39 +1,114 @@
;
; # This is a template configuration file which can be modified as desired.
;
; # Community branch (recommended): https://github.com/blizzless/blizzless-diiis/tree/community
; # test-stable branch: https://github.com/blizzless/blizzless-diiis/
; # Master branch: https://github.com/blizzless/blizzless-diiis/tree/master
;
; Settings for Bnet
[Battle-Server]
Enabled = true
BindIP = 127.0.0.1
WebPort = 9800
Port = 1119
BindIPv6 = ::1
MOTD = Welcome to Diablo 3!
MotdEnabled = true
Motd = Welcome to Blizzless D3!
[IWServer]
IWServer = false
; ------------------------
; [IWServer]
; IWServer = false
; Settings for REST
; ------------------------
; REST services for login (and others)
[REST]
IP = 127.0.0.1
Public = true
PublicIP = 127.0.0.1
PORT = 80
; Settings for game
; ------------------------
; Game server options and game-mods.
;
[Game-Server]
Enabled = true
CoreActive = true
BindIP = 127.0.0.1
WebPort = 9100
Port = 2001
WebPort = 9001
Port = 1345
BindIPv6 = ::1
DRLGemu = true
;Modding of game
; Modding of game (please check https://github.com/blizzless/blizzless-diiis/blob/community/docs/game-world-settings.md)
;
; rates
RateExp = 1
RateMoney = 1
RateDrop = 1
RateChangeDrop = 1
RateMonsterHP = 1
RateMonsterDMG = 1
; items
ChanceHighQualityUnidentified = 30
ChanceNormalUnidentified = 5
; bosses
BossHealthMultiplier = 6
BossDamageMultiplier = 3
; nephalem
NephalemRiftProgressMultiplier = 1
; health
HealthPotionRestorePercentage = 60
HealthPotionCooldown = 30
ResurrectionCharges = 3
; waypoints
UnlockAllWaypoints = false
; player attribute modifier
StrengthMultiplier = 1
StrengthParagonMultiplier = 1
DexterityMultiplier = 1
DexterityParagonMultiplier = 1
IntelligenceMultiplier = 1
IntelligenceParagonMultiplier = 1
VitalityMultiplier = 1
VitalityParagonMultiplier = 1
; quests
AutoSaveQuests = false
; minimap
ForceMinimapVisibility = false
; ------------------------
; Network address translation
;
[NAT]
Enabled = False
Enabled = True
; use your public IP
PublicIP = 127.0.0.1
; ------------------------
; Where the outputs should be.
; Best for visualization (default): AnsiLog (target: Ansi)
; Best for debugging: ConsoleLog (target: console)
; Best for packet analysis: PacketLog (target: file)
;
[AnsiLog]
Enabled = true
Target = Ansi
IncludeTimeStamps = true
MinimumLevel = Debug
MaximumLevel = Fatal
[ConsoleLog]
Enabled = false
Target = Console
IncludeTimeStamps = true
MinimumLevel = Debug
MaximumLevel = PacketDump
[PacketLog]
Enabled = true
Target = file
FileName = packet.log
IncludeTimeStamps = true
MinimumLevel = Debug
MaximumLevel = PacketDump

View File

@ -3,7 +3,7 @@ version: "3.9"
services:
postgres:
container_name: postgres_container
image: postgres:14.5
image: postgres:14
environment:
POSTGRES_USER: "postgres"
POSTGRES_PASSWORD: "postgres"

View File

@ -302,37 +302,75 @@ ALTER TABLE public.craft_data_seq OWNER TO postgres;
CREATE TABLE public.game_accounts (
id bigint NOT NULL,
dbaccount_id bigint,
lastonline bigint,
flags integer,
banner bytea,
uiprefs bytea,
uisettings bytea,
seentutorials bytea,
bossprogress bytea,
stashicons bytea,
lastonline bigint,
flags integer,
paragonlevel integer,
paragonlevelhardcore integer,
experience integer,
experiencehardcore integer,
lastplayedhero_id bigint,
gold bigint,
platinum integer,
hardcoregold bigint,
platinum integer,
hardplatinum integer,
rmtcurrency bigint,
hardrmtcurrency bigint,
bloodshards integer,
hardcorebloodshards integer,
stashsize integer,
hardcorestashsize integer,
seasonstashsize integer,
hardseasonstashsize integer,
eliteskilled bigint,
totalkilled bigint,
totalgold bigint,
hardtotalgold bigint,
totalbloodshards integer,
hardtotalbloodshards integer,
totalbounties integer DEFAULT 0 NOT NULL,
totalbountieshardcore integer DEFAULT 0 NOT NULL,
pvptotalkilled bigint,
hardpvptotalkilled bigint,
pvptotalwins bigint,
pvptotalgold bigint
hardpvptotalwins bigint,
pvptotalgold bigint,
hardpvptotalgold bigint,
craftitem1 integer,
hardcraftitem1 integer,
craftitem2 integer,
hardcraftitem2 integer,
craftitem3 integer,
hardcraftitem3 integer,
craftitem4 integer,
hardcraftitem4 integer,
craftitem5 integer,
hardcraftitem5 integer,
vialofputridness integer,
hardvialofputridness integer,
idolofterror integer,
hardidolofterror integer,
heartoffright integer,
hardheartoffright integer,
leorikkey integer,
hardleorikkey integer,
bigportalkey integer,
hardbigportalkey integer,
horadrica1 integer,
hardhoradrica1 integer,
horadrica2 integer,
hardhoradrica2 integer,
horadrica3 integer,
hardhoradrica3 integer,
horadrica4 integer,
hardhoradrica4 integer,
horadrica5 integer,
hardhoradrica5 integer
);
@ -749,19 +787,7 @@ CREATE TABLE public.toons (
cosmetic1 integer,
cosmetic2 integer,
cosmetic3 integer,
cosmetic4 integer,
craftitem1 integer,
craftitem2 integer,
craftitem3 integer,
craftitem4 integer,
craftitem5 integer,
bigportalkey integer,
leorikkey integer,
horadrica1 integer,
horadrica2 integer,
horadrica3 integer,
horadrica4 integer,
horadrica5 integer
cosmetic4 integer
);

View File

@ -28,6 +28,118 @@
| | | `!lookup actor zombie` | |
| | | `!lookup power Punch` | |
# All Commands
Available commands from `!commands`:
### !account
Provides account management commands.
### !mute
Disables chat messages for the account for some defined time span.
### !tag
Switch private Tag for connect
### !powerful
Makes your character with absurd amount of damage. Useful for testing.
### !resourceful
Makes your character with full resource. Useful for testing.
### !info
Get current game information.
### !followers
Manage your followers.
### !difficulty
Changes difficulty of the game
### !heal
Heals yourself
### !invulnerable
Makes you invulnerable
### !spawn
Spawns a mob.
Usage: spawn [actorSNO] [amount]
### !levelup
Levels your character.
Optionally specify the number of levels: !levelup [count]
### !unlockart
Unlock all artisans: !unlockart
### !platinum
Platinum for your character.
Optionally specify the number of levels: !platinum [count]
### !stashup
Upgrade Stash.
### !gold
Gold for your character.
Optionally specify the number of gold: !gold [count]
### !achiplatinum
Platinum for your character.
Optionally specify the number of levels: !platinum [count]
### !eff
Platinum for your character.
Optionally specify the number of levels: !eff [count]
### !item
Spawns an item (with a name or type).
Usage: item [type <type>|<name>] [amount]
### !drop
Drops an epic item for your class.
Optionally specify the number of items: !drop [1-20]
### !tp
Transfers your character to another world.
### !conversation
Starts a conversation.
Usage: conversation snoConversation
### !speed
Modify speed walk of you character.
Usage: !speed <value>
Reset: !speed
### !commands
Lists available commands for your user-level.
### !help
usage: help <command>
Type 'commands' to get a list of available commands.
### !quest
Retrieves information about quest states and manipulates quest progress.
Usage: quest [triggers | trigger eventType eventValue | advance snoQuest]
### !lookup
Searches in sno databases.
Usage: lookup [actor|conv|power|scene|la|sp|weather] <pattern>
# Item List
You can use the official website to search items: https://eu.diablo3.blizzard.com/en-us/item/

View File

@ -1,19 +1,50 @@
# Global settings for game
# Game World Settings
Using the configuration file you can easily change the parameters of the world.
The parameters of the world can be easily altered using the configuration file located within `config.ini`.
## Configuration
Apply parameters in `config.ini` file to the server folder (It overwrites the default settings)
The parameters specified in the `config.ini` file will be saved to the server folder, overwriting the default settings. For example, all values below use their default settings.
```ini
[Game-Server]
; rates
RateExp = 1
RateMoney = 1
RateDrop = 1
RateChangeDrop = 1
RateMonsterHP = 1
RateMonsterDMG = 1
; items
ChanceHighQualityUnidentified = 30
ChanceNormalUnidentified = 5
; bosses
BossHealthMultiplier = 6
BossDamageMultiplier = 3
; nephalem
NephalemRiftProgressMultiplier = 1
NephalemRiftAutoFinish = false
NephalemRiftAutoFinishThreshold = 2
NephalemRiftOrbsChance = 0
; health
HealthPotionRestorePercentage = 60
HealthPotionCooldown = 30
ResurrectionCharges = 3
; waypoints
UnlockAllWaypoints = false
; player attribute modifier
StrengthMultiplier = 1
StrengthParagonMultiplier = 1
DexterityMultiplier = 1
DexterityParagonMultiplier = 1
IntelligenceMultiplier = 1
IntelligenceParagonMultiplier = 1
VitalityMultiplier = 1
VitalityParagonMultiplier = 1
; quests
AutoSaveQuests = false
; minimap
ForceMinimapVisibility = false
```
## Description
@ -26,4 +57,25 @@ RateMonsterDMG = 1
| `RateChangeDrop` | Drop quality multiplier |
| `RateMonsterHP` | Monsters HP multiplier |
| `RateMonsterDMG` | Monster damage multiplier |
| `ChanceHighQualityUnidentified` | Percentage that a unique, legendary, set or special item created is unidentified |
| `ChanceNormalUnidentified` | Percentage that normal item created is unidentified |
| `ResurrectionCharges` | Amount of times user can resurrect at corpse |
| `BossHealthMultiplier` | Boss Health Multiplier |
| `BossDamageMultiplier` | Boss Damage Multiplier |
| `HealthPotionRestorePercentage` | How much (from 1-100) a health potion will heal. |
| `HealthPotionCooldown` | How much (in seconds) to use a health potion again. |
| `UnlockAllWaypoints` | Unlocks all waypoints in campaign |
| `StrengthMultiplier` | Player's strength multiplier |
| `StrengthParagonMultiplier` | Player's strength multiplier **for paragons** |
| `DexterityMultiplier` | Player's dexterity multiplier |
| `DexterityParagonMultiplier` | Player's dexterity multiplier **for paragons** |
| `IntelligenceMultiplier` | Player's intelligence multiplier |
| `IntelligenceParagonMultiplier` | Player's intelligence multiplier **for paragons** |
| `VitalityMultiplier` | Player's vitality multiplier |
| `VitalityParagonMultiplier` | Player's vitality multiplier **for paragons** |
| `AutoSaveQuests` *in tests* | Force Save Quests/Step, even if Act's quest setup marked as Saveable = FALSE. Doesn't apply to OpenWorld games. |
| `NephalemRiftProgressMultiplier` | Nephalem Rift Progress Modifier |
| `NephalemRiftAutoFinish` | Nephalem Auto-Finish when there's still `NephalemRiftAutoFinishThreshold` monsters or less are alive on the rift |
| `NephalemRiftAutoFinishThreshold` | Nephalem Rift Progress Modifier |
| `NephalemRiftOrbsChance` | Nephalem Rifts chance of spawning a orb. |
| `ForceMinimapVisibility` | Forces the minimap visibility |

View File

@ -1,23 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using bgs.protocol.presence.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Crypthography;
namespace DiIiS_NA.LoginServer.AccountsSystem
@ -27,14 +16,8 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
private DBAccount _dbAccount = null; //may be cached forever, as only MooNetServer changes it
public DBAccount DBAccount
{
get
{
return _dbAccount;
}
set
{
_dbAccount = value;
}
get => _dbAccount;
set => _dbAccount = value;
}
//public D3.PartyMessage.ScreenStatus ScreenStatus { get; set; }
@ -64,13 +47,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
}
}
public StringPresenceField RealIDTagField
{
get
{
return new StringPresenceField(FieldKeyHelper.Program.BNet, FieldKeyHelper.OriginatingClass.Account, 1, 0, string.Format(""));
}
}
public StringPresenceField RealIDTagField => new(FieldKeyHelper.Program.BNet, FieldKeyHelper.OriginatingClass.Account, 1, 0, string.Format(""));
public BoolPresenceField AccountOnlineField
@ -133,34 +110,21 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public bool IsOnline
{
get
{
get =>
//check if gameAccount is online
return GameAccount.IsOnline;
}
set
{
GameAccount.IsOnline = value;
}
GameAccount.IsOnline;
set => GameAccount.IsOnline = value;
}
public List<ulong> FriendsIds = new List<ulong>();
public List<ulong> FriendsIds = new();
public List<ulong> IgnoreIds = new List<ulong>();
public List<ulong> IgnoreIds = new();
public string Email => DBAccount.Email;
public string Email
{
get
{
return DBAccount.Email;
}
private set
{
}
}
public string SaltedTicket
{
get { return DBAccount.SaltedTicket; }
get => DBAccount.SaltedTicket;
internal set
{
DBAccount.SaltedTicket = value;
@ -169,54 +133,63 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
}
public byte[] Salt
{
get { return DBAccount.Salt.ToArray(); }
get => DBAccount.Salt.ToArray();
internal set
{
DBAccount.Salt = value;
DBSessions.SessionUpdate(DBAccount);
}
} // s- User's salt.
public byte[] FullSalt
{
get { return DBAccount.Salt.ToArray(); }
} // s- User's salt.
public byte[] FullSalt => DBAccount.Salt.ToArray(); // s- User's salt.
public byte[] PasswordVerifier
{
get { return DBAccount.PasswordVerifier; }
get => DBAccount.PasswordVerifier;
internal set
{
lock (DBAccount)
{
DBAccount.PasswordVerifier = value;
DBSessions.SessionUpdate(DBAccount);
}
} // v - password verifier.
}
}
public int HashCode
{
get
{
return DBAccount.HashCode;
}
get => DBAccount.HashCode;
private set
{
lock (DBAccount)
{
DBAccount.HashCode = value;
DBSessions.SessionUpdate(DBAccount);
}
}
}
public string BattleTagName
{
get
{
bool staff = (DBAccount.UserLevel > UserLevels.Tester);
//(controller as HandlerController).Client.Account.GameAccount.ProgramField.Value
var bTag = DBAccount.BattleTagName;
//((HandlerController) controller).Client.Account.GameAccount.ProgramField.Value
if(GameAccount.ProgramField.Value == "APP")
return string.Format("{0}", DBAccount.BattleTagName);
else if (GameAccount.ProgramField.Value == "D3")
return string.Format("{0}", DBAccount.BattleTagName);
//return string.Format(staff ? " {{icon:bnet}} {{c_legendary}}{0}{{/c}}" : ("{0}"), this.DBAccount.BattleTagName);
else
return string.Format("{0}", DBAccount.BattleTagName);
return bTag;
if (GameAccount.ProgramField.Value == "D3")
{
return DBAccount.UserLevel switch
{
>= UserLevels.Owner => " {icon:bnet} {c_epic}" + bTag + "{/c}",
>= UserLevels.GM => " {icon:bnet} {c_legendary}" + bTag + "{/c}",
>= UserLevels.Tester => " {icon:bnet} {c_rare}" + bTag + "{/c}",
_ => " {icon:bnet} " + bTag
};
}
return bTag;
//return (staff ? " {icon:bnet} " : (premium ? " {icon:gold} " : "")) + dbAcc.BattleTagName;
} //{c_blue}{/c}
private set
@ -228,10 +201,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public string BattleTag
{
get
{
return BattleTagName + "#" + HashCode.ToString("D4");
}
get => BattleTagName + "#" + HashCode.ToString("D4");
set
{
if (!value.Contains('#'))
@ -246,7 +216,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public UserLevels UserLevel
{
get { return DBAccount.UserLevel; }
get => DBAccount.UserLevel;
internal set
{
DBAccount.UserLevel = value;
@ -279,13 +249,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public static readonly D3.OnlineService.EntityId AccountHasNoToons =
D3.OnlineService.EntityId.CreateBuilder().SetIdHigh(0).SetIdLow(0).Build();
public D3.OnlineService.EntityId LastSelectedGameAccount
{
get
{
return GameAccount.D3GameAccountId;
}
}
public D3.OnlineService.EntityId LastSelectedGameAccount => GameAccount.D3GameAccountId;
public string BroadcastMessage = "";
@ -326,7 +290,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
DoClear(operation.Field);
break;
default:
Logger.Warn("No operation type.");
Logger.Warn($"No operation type in $[olive]${nameof(Account)}.{nameof(Update)}(IList<FieldOperation>)$[/].");
break;
}
}
@ -411,7 +375,8 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
}
else
{
Logger.Warn("Account Unknown query-key: {0}, {1}, {2}", queryKey.Program, queryKey.Group, queryKey.Field);
Logger.Warn(
$"Account Unknown query-key: $[underline yellow]${queryKey.Program}$[/]$, $[underline yellow]${queryKey.Group}$[/]$, $[underline yellow]${queryKey.Field}$[/]$");
}
break;
case FieldKeyHelper.Program.BNet:
@ -425,7 +390,8 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
}
else
{
Logger.Warn("Account Unknown query-key: {0}, {1}, {2}", queryKey.Program, queryKey.Group, queryKey.Field);
Logger.Warn(
$"Account Unknown query-key: $[underline yellow]${queryKey.Program}$[/]$, $[underline yellow]${queryKey.Group}$[/]$, $[underline yellow]${queryKey.Field}$[/]$");
}
break;
}
@ -463,7 +429,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
var operationList = new List<FieldOperation>();
//if (this.LastSelectedHero != AccountHasNoToons)
//operationList.Add(this.LastPlayedHeroIdField.GetFieldOperation());
if (LastSelectedGameAccount != AccountHasNoToons)
if (!Equals(LastSelectedGameAccount, AccountHasNoToons))
{
operationList.Add(LastPlayedToonIdField.GetFieldOperation());
operationList.Add(LastPlayedGameAccountIdField.GetFieldOperation());
@ -481,21 +447,10 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
#endregion
public bool VerifyPassword(string password)
{
if (string.IsNullOrEmpty(password))
return false;
if (password.Length < 8 || password.Length > 16)
return false;
var calculatedVerifier = SRP6a.CalculatePasswordVerifierForAccount(Email, password, FullSalt);
return calculatedVerifier.SequenceEqual(PasswordVerifier);
}
public override string ToString()
{
return String.Format("{{ Account: {0} [lowId: {1}] }}", Email, BnetEntityId.Low);
return $"{{ Account: {Email} [lowId: {BnetEntityId.Low}] }}";
}
/// <summary>
@ -509,5 +464,29 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
Admin,
Owner
}
public static class UserLevelsExtensions
{
public static UserLevels? FromString(string str)
{
if (string.IsNullOrWhiteSpace(str))
return null;
switch (str.ToLower())
{
case "user":
return UserLevels.User;
case "tester":
return UserLevels.Tester;
case "gm":
return UserLevels.GM;
case "admin":
return UserLevels.Admin;
case "owner":
return UserLevels.Owner;
default:
return null;
}
}
}
}
}

View File

@ -1,28 +1,18 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Crypthography;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Toons;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
using Spectre.Console;
using System.Text.RegularExpressions;
namespace DiIiS_NA.LoginServer.AccountsSystem
{
@ -30,12 +20,9 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
{
private static readonly Logger Logger = LogManager.CreateLogger("DataBaseSystem");
public static int TotalAccounts
{
get { return DBSessions.SessionQuery<DBAccount>().Count(); }
}
public static int TotalAccounts => DBSessions.SessionQuery<DBAccount>().Count();
public static readonly ConcurrentDictionary<ulong, Account> LoadedAccounts = new ConcurrentDictionary<ulong, Account>();
public static readonly ConcurrentDictionary<ulong, Account> LoadedAccounts = new();
public static void PreLoadAccounts()
{
@ -79,7 +66,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
{
try
{
if (DBSessions.SessionQueryWhere<DBAccount>(dba => dba.DiscordId == discordId).Count() > 0)
if (DBSessions.SessionQueryWhere<DBAccount>(dba => dba.DiscordId == discordId).Any())
return false;
var account = GetAccountByEmail(email);
@ -97,12 +84,12 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public static Account GetAccountByDiscordId(ulong discordId)
{
List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.DiscordId == discordId).ToList();
if (dbAcc.Count() == 0)
if (!dbAcc.Any())
{
Logger.Warn("GetAccountByDiscordId {0}: DBAccount is null!", discordId);
return null;
}
return GetAccountByDBAccount(dbAcc.First());
return GetDatabaseAccountByPersistentID(dbAcc.First());
}
public static bool GenerateReferralCode(string email)
@ -143,19 +130,19 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
else
{
List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.Email == email);
if (dbAcc.Count() == 0)
if (dbAcc.Count == 0)
{
Logger.Warn("GetAccountByEmail {0}: DBAccount is null!", email);
Logger.Warn($"DBAccount is null from email {email}!");
return null;
}
if (dbAcc.First() == null)
{
Logger.Warn("GetAccountByEmail {0}: DBAccount id is null!", email);
Logger.Warn($"DBAccount is null from email {email}!");
return null;
}
else
Logger.Debug("GetAccountByEmail id - \"{0}\"", dbAcc.First().Id);
return GetAccountByDBAccount(dbAcc.First());
Logger.MethodTrace($"id - {dbAcc.First().Id}");
return GetDatabaseAccountByPersistentID(dbAcc.First());
}
}
@ -164,34 +151,38 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
string[] tagparts = battletag.Split(new[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
int taghash = Convert.ToInt32(tagparts[1], 10);
if (tagparts[0].StartsWith(" {icon"))
tagparts[0] = tagparts[0].Substring(13);
//Logger.Debug("trying GetAccountByBattletag {0}", battletag);
if (tagparts[0].StartsWith("{c_legendary"))
{
tagparts[0] = tagparts[0].Substring(13);
tagparts[0] = tagparts[0].Split('{')[0];
}
// remove everything inside the brackets and empty spaces in tagparts[0] using regex
tagparts[0] = Regex.Replace(tagparts[0], @"\s*?{[^}]+}\s*?", string.Empty).Trim();
tagparts[0] = Regex.Replace(tagparts[0], @"\s*?", string.Empty).Trim();
// if (tagparts[0].StartsWith(" {icon"))
// tagparts[0] = tagparts[0].Substring(13);
// //Logger.Debug("trying GetAccountByBattletag {0}", battletag);
// if (tagparts[0].StartsWith("{c_legendary"))
// {
// tagparts[0] = tagparts[0].Substring(13);
// tagparts[0] = tagparts[0].Split('{')[0];
// }
List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.BattleTagName == tagparts[0] && dba.HashCode == taghash);
if (dbAcc.Count() == 0)
if (dbAcc.Count == 0)
{
Logger.Warn("GetAccountByBattletag {0}: DBAccount is null!", battletag);
Logger.Warn($"$[olive]$GetAccountByBattleTag(\"{battletag})$[/]$ DBAccount is null!");
return null;
}
//else
//Logger.Debug("GetAccountByBattletag \"{0}\"", battletag);
return GetAccountByDBAccount(dbAcc.First());
return GetDatabaseAccountByPersistentID(dbAcc.First());
}
public static Account GetAccountByName(string btname) //pretty bad to use it
{
List<DBAccount> dbAcc = DBSessions.SessionQueryWhere<DBAccount>(dba => dba.BattleTagName == btname);
if (dbAcc.Count() == 0)
if (dbAcc.Count == 0)
{
Logger.Warn("GetAccountByName {0}: DBAccount is null!", btname);
Logger.Warn("$[olive]$GetAccountByName(\"{0}\")$[/]$: DBAccount is null!", btname);
return null;
}
return GetAccountByDBAccount(dbAcc.First());
return GetDatabaseAccountByPersistentID(dbAcc.First());
}
public static Account GetAccountByPersistentID(ulong persistentId)
@ -200,11 +191,11 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
return LoadedAccounts[persistentId];
else
{
return GetAccountByDBAccount(DBSessions.SessionGet<DBAccount>(persistentId));
return GetDatabaseAccountByPersistentID(DBSessions.SessionGet<DBAccount>(persistentId));
}
}
public static Account GetAccountByDBAccount(DBAccount dbAccount)
public static Account GetDatabaseAccountByPersistentID(DBAccount dbAccount)
{
if (dbAccount == null)
return null;
@ -279,7 +270,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
public static Account GetAccountBySaltTicket(string ticket)
{
if (DBSessions.SessionQueryWhere<DBAccount>(dba => dba.SaltedTicket == ticket).Count() > 0)
if (DBSessions.SessionQueryWhere<DBAccount>(dba => dba.SaltedTicket == ticket).Any())
return LoadedAccounts[LoadedAccounts.Single(a => a.Value.SaltedTicket == ticket).Key];
return null;
}

File diff suppressed because it is too large Load Diff

View File

@ -1,15 +1,9 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer.AccountsSystem
@ -18,12 +12,9 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
{
private static readonly Logger Logger = LogManager.CreateLogger("DataBaseSystem");
public static readonly ConcurrentDictionary<ulong, GameAccount> LoadedGameAccounts = new ConcurrentDictionary<ulong, GameAccount>();
public static readonly ConcurrentDictionary<ulong, GameAccount> LoadedGameAccounts = new();
public static int TotalAccounts
{
get { return DBSessions.SessionQuery<DBGameAccount>().Count(); }
}
public static int TotalAccounts => DBSessions.SessionQuery<DBGameAccount>().Count;
public static void PreLoadGameAccounts()
{
@ -44,7 +35,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
return null;
if (LoadedGameAccounts.ContainsKey(dbGameAccount.Id))
{
LoadedGameAccounts[dbGameAccount.Id].DBGameAccount = dbGameAccount;
// LoadedGameAccounts[dbGameAccount.Id].DBGameAccount = dbGameAccount;
return LoadedGameAccounts[dbGameAccount.Id];
}
else
@ -81,24 +72,65 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
ParagonLevelHardcore = 0,
Experience = 7200000,
ExperienceHardcore = 7200000,
StashSize = 700, // Default stash sizes should be 70 with purchasable upgrades
HardcoreStashSize = 700,
StashSize = 700, // Default stash sizes should be 70 with purchasable upgrades.
HardcoreStashSize = 700, // Default stash sizes should be 70 with purchasable upgrades.
SeasonStashSize = 700,
HardSeasonStashSize = 700,
BloodShards = 0,
HardcoreBloodShards = 0,
BossProgress = new byte[] { 0xff, 0xff, 0xff, 0xff, 0xff },
SeenTutorials = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
StashIcons = new byte[] { 0x00, 0x00, 0x00, 0x00 },
RmtCurrency = 0,
HardRmtCurrency = 0,
Platinum = 0,
HardPlatinum = 0,
Gold = 0,
HardcoreGold = 0,
ElitesKilled = 0,
HardElitesKilled = 0,
TotalKilled = 0,
HardTotalKilled = 0,
TotalGold = 0,
HardTotalGold = 0,
TotalBloodShards = 0,
HardTotalBloodShards = 0,
PvPTotalKilled = 0,
HardPvPTotalKilled = 0,
PvPTotalWins = 0,
PvPTotalGold = 0
HardPvPTotalWins = 0,
PvPTotalGold = 0,
HardPvPTotalGold = 0,
CraftItem1 = 0,
HardCraftItem1 = 0,
CraftItem2 = 0,
HardCraftItem2 = 0,
CraftItem3 = 0,
HardCraftItem3 = 0,
CraftItem4 = 0,
HardCraftItem4 = 0,
CraftItem5 = 0,
HardCraftItem5 = 0,
BigPortalKey = 0,
HardBigPortalKey = 0,
LeorikKey = 0,
HardLeorikKey = 0,
VialofPutridness = 0,
HardVialofPutridness = 0,
IdolofTerror = 0,
HardIdolofTerror = 0,
HeartofFright = 0,
HardHeartofFright = 0,
HoradricA1 = 0,
HardHoradricA1 = 0,
HoradricA2 = 0,
HardHoradricA2 = 0,
HoradricA3 = 0,
HardHoradricA3 = 0,
HoradricA4 = 0,
HardHoradricA4 = 0,
HoradricA5 = 0,
HardHoradricA5 = 0
};
DBSessions.SessionSave(newDBGameAccount);
@ -135,7 +167,7 @@ namespace DiIiS_NA.LoginServer.AccountsSystem
crafting.DBGameAccount = dbGAcc;
crafting.isHardcore = hardcore;
crafting.isSeasoned = seasoned;
crafting.LearnedRecipes = new byte[0];
crafting.LearnedRecipes = Array.Empty<byte>();
crafting.Level = 1;
DBSessions.SessionSave(crafting);
}

View File

@ -1,17 +1,9 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using DotNetty.Codecs;
//Blizzless Project 2022
using DotNetty.Buffers;
//Blizzless Project 2022
using DotNetty.Codecs.Http.WebSockets;
//Blizzless Project 2022
using DotNetty.Transport.Channels;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using Google.ProtocolBuffers;
namespace DiIiS_NA.LoginServer.Base

View File

@ -1,7 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using System;
namespace DiIiS_NA.LoginServer.Base

View File

@ -1,35 +1,19 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DotNetty.Codecs;
//Blizzless Project 2022
using DotNetty.Codecs.Http;
//Blizzless Project 2022
using DotNetty.Handlers.Tls;
//Blizzless Project 2022
using DotNetty.Transport.Channels;
//Blizzless Project 2022
using DotNetty.Transport.Channels.Sockets;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Security.Cryptography.X509Certificates;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using DotNetty.Buffers;
//Blizzless Project 2022
using DotNetty.Common.Utilities;
//Blizzless Project 2022
using System.Threading.Tasks;
//Blizzless Project 2022
using DotNetty.Codecs.Http.WebSockets;
namespace DiIiS_NA.LoginServer.Base

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
namespace DiIiS_NA.LoginServer.Base

View File

@ -1,7 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
using System;
namespace DiIiS_NA.LoginServer.Base

View File

@ -1,217 +1,207 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.GameServer.AchievementSystem;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.ItemsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.GamesSystem;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using WatsonTcp;
namespace DiIiS_NA.LoginServer.Battle
{
public class BattleBackend
{
private static readonly Logger Logger = LogManager.CreateLogger("BattleNetEmu");
private static readonly Logger Logger = LogManager.CreateLogger("BattleBackend");
public WatsonTcpServer GameServerSocket;
public readonly WatsonTcpServer GameServerSocket;
public struct ServerDescriptor
{
public string GameIP;
public string GameIp;
public int GamePort;
};
public Dictionary<string, ServerDescriptor> GameServers = new Dictionary<string, ServerDescriptor>();
public readonly Dictionary<string, ServerDescriptor> GameServers = new();
public Dictionary<string, ServerDescriptor> PvPGameServers = new Dictionary<string, ServerDescriptor>();
private readonly Dictionary<string, ServerDescriptor> _pvPGameServers = new();
public BattleBackend(string BattletHost, int BackPort)
public BattleBackend(string battleHost, int port)
{
this.GameServerSocket = new WatsonTcpServer(BattletHost, BackPort, this._receiverClientConnected, this._receiverClientDisconnected, this._receiverMessageReceived, false);
GameServerSocket = new WatsonTcpServer(battleHost, port, ReceiverClientConnected, ReceiverClientDisconnected, ReceiverMessageReceived, false);
System.Threading.Thread.Sleep(3000);
}
private bool _receiverClientConnected(string ipPort)
private bool ReceiverClientConnected(string ipPort)
{
Logger.Info("Game server loaded {0} connecting to BlizzLess.Net...", ipPort);
Logger.Info($"Blizzless client connected {ipPort}...");
return true;
}
private bool _receiverClientDisconnected(string ipPort)
private bool ReceiverClientDisconnected(string ipPort)
{
Logger.Warn("GameServer at {0} was disconnected!", ipPort);
if (this.GameServers.ContainsKey(ipPort)) this.GameServers.Remove(ipPort);
if (this.PvPGameServers.ContainsKey(ipPort)) this.PvPGameServers.Remove(ipPort);
Logger.Warn("Blizzless client disconnected $[white]${0}$[/]$!", ipPort);
if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort);
if (_pvPGameServers.ContainsKey(ipPort)) _pvPGameServers.Remove(ipPort);
if (this.GameServers.Count == 0)
if (GameServers.Count == 0)
Logger.Warn("GameServers list is empty! Unable to use PvE game activities atm.");
if (this.PvPGameServers.Count == 0)
if (_pvPGameServers.Count == 0)
Logger.Warn("PvPGameServers list is empty! Unable to use PvP game activities atm.");
return true;
}
public void CreateGame(string ipPort, int GameId, int level, int act, int difficulty, int questId, int questStepId, bool isHardcore, int gamemode, bool iSseasoned, int perftest_id = 0)
public void CreateGame(string ipPort, int gameId, int level, int act, int difficulty, int questId, int questStepId, bool isHardcore, int gameMode, bool isSeasoned, int perftestId = 0)
{
GameServerSocket.Send(ipPort, Encoding.UTF8.GetBytes(string.Format("diiiscg|{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}/{8}", GameId, level, act, difficulty, questId, questStepId, isHardcore, gamemode, iSseasoned, perftest_id)));
Send(ipPort, $"diiiscg|{gameId}/{level}/{act}/{difficulty}/{questId}/{questStepId}/{isHardcore}/{gameMode}/{isSeasoned}");
}
private bool _receiverMessageReceived(string ipPort, byte[] data)
private void Send(string ipPort, string data)
=> GameServerSocket.Send(ipPort, Encoding.UTF8.GetBytes(data));
private bool ReceiverMessageReceived(string ipPort, byte[] data)
{
string msg = "";
if (data != null && data.Length > 0) msg = Encoding.UTF8.GetString(data);
Logger.Trace("Message received from {0}: {1}", ipPort, msg);
Logger.Trace("Message received from $[grey69]${0}$[/]$: $[white]${1}$[/]$", ipPort, msg);
var message = msg.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
var args = message[1].Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
switch (message[0])
{
case "rngsr":
if (this.GameServers.ContainsKey(ipPort)) this.GameServers.Remove(ipPort);
string rgs_ip = args[0];
int rgs_port = int.Parse(args[1].Trim());
this.GameServers.Add(ipPort, new ServerDescriptor { GameIP = rgs_ip, GamePort = rgs_port });
Logger.Info("Game server was registred for BlizzLess.Net {0}:{1}.", rgs_ip, rgs_port);
if (GameServers.ContainsKey(ipPort)) GameServers.Remove(ipPort);
string rgsIp = args[0];
int rgsPort = int.Parse(args[1].Trim());
GameServers.Add(ipPort, new ServerDescriptor { GameIp = rgsIp, GamePort = rgsPort });
Logger.Info("Game server was registered for Blizzless {0}:{1}.", rgsIp, rgsPort);
break;
case "rnpvpgsr":
if (this.PvPGameServers.ContainsKey(ipPort)) this.PvPGameServers.Remove(ipPort);
string rpgs_ip = args[0];
int rpgs_port = int.Parse(args[1].Trim());
this.PvPGameServers.Add(ipPort, new ServerDescriptor { GameIP = rpgs_ip, GamePort = rpgs_port });
Logger.Info("PvP GameServer at {0}:{1} successfully signed and ready to work.", rpgs_ip, rpgs_port);
if (_pvPGameServers.ContainsKey(ipPort)) _pvPGameServers.Remove(ipPort);
string rpgsIp = args[0];
int rpgsPort = int.Parse(args[1].Trim());
_pvPGameServers.Add(ipPort, new ServerDescriptor { GameIp = rpgsIp, GamePort = rpgsPort });
Logger.Info("PvP GameServer at {0}:{1} successfully signed and ready to work.", rpgsIp, rpgsPort);
break;
case "grachi":
ulong gachi_accId = ulong.Parse(args[0].Trim());
ulong gachi_achId = ulong.Parse(args[1].Trim());
ulong gachiAccId = ulong.Parse(args[0].Trim());
ulong gachiAchId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var gachi_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gachi_accId))
AchievementManager.GrantAchievement(gachi_invokerClient, gachi_achId);
foreach (var gachiInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gachiAccId))
AchievementManager.GrantAchievement(gachiInvokerClient, gachiAchId);
});
break;
case "gcrit":
ulong gc_accId = ulong.Parse(args[0].Trim());
ulong gc_criId = ulong.Parse(args[1].Trim());
ulong gcAccId = ulong.Parse(args[0].Trim());
ulong gcCriId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var gc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gc_accId))
AchievementManager.GrantCriteria(gc_invokerClient, gc_criId);
foreach (var gcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == gcAccId))
AchievementManager.GrantCriteria(gcInvokerClient, gcCriId);
});
break;
case "upequt":
ulong uq_accId = ulong.Parse(args[0].Trim());
ulong uq_achId = ulong.Parse(args[1].Trim());
uint uq_addCounter = uint.Parse(args[2].Trim());
ulong uqAccId = ulong.Parse(args[0].Trim());
ulong uqAchId = ulong.Parse(args[1].Trim());
uint uqAddCounter = uint.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var uq_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uq_accId))
AchievementManager.UpdateQuantity(uq_invokerClient, uq_achId, uq_addCounter);
foreach (var uqInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uqAccId))
AchievementManager.UpdateQuantity(uqInvokerClient, uqAchId, uqAddCounter);
});
break;
case "uoacce":
ulong uac_accId = ulong.Parse(args[0].Trim());
int uac_typeId = int.Parse(args[1].Trim());
uint uac_addCounter = uint.Parse(args[2].Trim());
int uac_comparand = int.Parse(args[3].Trim());
ulong uac_achi = ulong.Parse(args[4].Trim());
ulong uacAccId = ulong.Parse(args[0].Trim());
int uacTypeId = int.Parse(args[1].Trim());
uint uacAddCounter = uint.Parse(args[2].Trim());
int uacComparand = int.Parse(args[3].Trim());
ulong uacAchi = ulong.Parse(args[4].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
if (uac_achi == 0)
foreach (var uac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uac_accId))
AchievementManager.UpdateAllCounters(uac_invokerClient, uac_typeId, uac_addCounter, uac_comparand);
if (uacAchi == 0)
foreach (var uacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uacAccId))
AchievementManager.UpdateAllCounters(uacInvokerClient, uacTypeId, uacAddCounter, uacComparand);
else
foreach (var uac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uac_accId))
AchievementManager.UpdateAllCounters(uac_invokerClient, uac_typeId, uac_addCounter, uac_comparand);
foreach (var uacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uacAccId))
AchievementManager.UpdateAllCounters(uacInvokerClient, uacTypeId, uacAddCounter, uacComparand);
});
break;
case "upsnaccr": //UpdateSingleAchievementCounter
ulong usac_accId = ulong.Parse(args[0].Trim());
ulong usac_achId = ulong.Parse(args[1].Trim());
uint usac_addCounter = uint.Parse(args[2].Trim());
ulong usacAccId = ulong.Parse(args[0].Trim());
ulong usacAchId = ulong.Parse(args[1].Trim());
uint usacAddCounter = uint.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var usac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == usac_accId))
AchievementManager.UpdateQuantity(usac_invokerClient, usac_achId, usac_addCounter);
foreach (var usacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == usacAccId))
AchievementManager.UpdateQuantity(usacInvokerClient, usacAchId, usacAddCounter);
});
break;
case "cqc": //CheckQuestCriteria
ulong cqc_accId = ulong.Parse(args[0].Trim());
int cqc_qId = int.Parse(args[1].Trim());
bool cqc_isCoop = (args[2].Trim() == "True" ? true : false);
ulong cqcAccId = ulong.Parse(args[0].Trim());
int cqcQId = int.Parse(args[1].Trim());
bool cqcIsCoop = (args[2].Trim() == "True" ? true : false);
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var cqc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cqc_accId))
AchievementManager.CheckQuestCriteria(cqc_invokerClient, cqc_qId, cqc_isCoop);
foreach (var cqcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cqcAccId))
AchievementManager.CheckQuestCriteria(cqcInvokerClient, cqcQId, cqcIsCoop);
});
break;
case "ckmc": //CheckKillMonsterCriteria
ulong ckmc_accId = ulong.Parse(args[0].Trim());
int ckmc_actorId = int.Parse(args[1].Trim());
int ckmc_type = int.Parse(args[2].Trim());
bool ckmc_isHardcore = (args[3].Trim() == "True" ? true : false);
ulong ckmcAccId = ulong.Parse(args[0].Trim());
int ckmcActorId = int.Parse(args[1].Trim());
int ckmcType = int.Parse(args[2].Trim());
bool ckmcIsHardcore = (args[3].Trim() == "True" ? true : false);
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var ckmc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ckmc_accId))
AchievementManager.CheckKillMonsterCriteria(ckmc_invokerClient, ckmc_actorId, ckmc_type, ckmc_isHardcore);
foreach (var ckmcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ckmcAccId))
AchievementManager.CheckKillMonsterCriteria(ckmcInvokerClient, ckmcActorId, ckmcType, ckmcIsHardcore);
});
break;
case "clc": //CheckLevelCap
ulong clc_accId = ulong.Parse(args[0].Trim());
ulong clcAccId = ulong.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var clc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clc_accId))
AchievementManager.CheckLevelCap(clc_invokerClient);
foreach (var clcInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clcAccId))
AchievementManager.CheckLevelCap(clcInvokerClient);
});
break;
case "csic": //CheckSalvageItemCriteria
ulong csic_accId = ulong.Parse(args[0].Trim());
int csic_itemId = int.Parse(args[1].Trim());
ulong csicAccId = ulong.Parse(args[0].Trim());
int csicItemId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var csic_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == csic_accId))
AchievementManager.CheckSalvageItemCriteria(csic_invokerClient, csic_itemId);
foreach (var csicInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == csicAccId))
AchievementManager.CheckSalvageItemCriteria(csicInvokerClient, csicItemId);
});
break;
case "clac": //CheckLevelAreaCriteria
ulong clac_accId = ulong.Parse(args[0].Trim());
int clac_laId = int.Parse(args[1].Trim());
ulong clacAccId = ulong.Parse(args[0].Trim());
int clacLaId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var clac_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clac_accId))
AchievementManager.CheckLevelAreaCriteria(clac_invokerClient, clac_laId);
foreach (var clacInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == clacAccId))
AchievementManager.CheckLevelAreaCriteria(clacInvokerClient, clacLaId);
});
break;
case "ccc": //CheckConversationCriteria
ulong ccc_accId = ulong.Parse(args[0].Trim());
int ccc_cId = int.Parse(args[1].Trim());
ulong cccAccId = ulong.Parse(args[0].Trim());
int cccCId = int.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
foreach (var ccc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ccc_accId))
AchievementManager.CheckConversationCriteria(ccc_invokerClient, ccc_cId);
foreach (var cccInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == cccAccId))
AchievementManager.CheckConversationCriteria(cccInvokerClient, cccCId);
});
break;
case "plu": //ParagonLevelUp
ulong plu_accId = ulong.Parse(args[0].Trim());
ulong pluAccId = ulong.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var plr_client = PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == plu_accId).FirstOrDefault();
if (plr_client != null && plr_client.Account.GameAccount. Clan != null)
plr_client.Account.GameAccount.Clan.ParagonRatings[plr_client.Account.GameAccount] = plr_client.Account.GameAccount.DBGameAccount.ParagonLevel;
var plrClient = PlayerManager.OnlinePlayers.FirstOrDefault(c => c.Account.GameAccount.PersistentID == pluAccId);
if (plrClient != null && plrClient.Account.GameAccount. Clan != null)
plrClient.Account.GameAccount.Clan.ParagonRatings[plrClient.Account.GameAccount] = plrClient.Account.GameAccount.DBGameAccount.ParagonLevel;
});
break;
case "uii": //UniqueItemIdentified
ulong uii_accId = ulong.Parse(args[0].Trim());
ulong uii_itemId = ulong.Parse(args[1].Trim());
ulong uiiAccId = ulong.Parse(args[0].Trim());
ulong uiiItemId = ulong.Parse(args[1].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var plr_client = PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uii_accId).FirstOrDefault();
if (plr_client != null && plr_client.Account.GameAccount.Clan != null)
var plrClient = PlayerManager.OnlinePlayers.FirstOrDefault(c => c.Account.GameAccount.PersistentID == uiiAccId);
if (plrClient != null && plrClient.Account.GameAccount.Clan != null)
{
var dbItem = DBSessions.SessionGet<DBInventory>(uii_itemId);
var dbItem = DBSessions.SessionGet<DBInventory>(uiiItemId);
if (dbItem != null)
{
var generator = D3.Items.Generator.CreateBuilder()
@ -231,92 +221,92 @@ namespace DiIiS_NA.LoginServer.Battle
generator.AddBaseAffixes(result);
}
plr_client.Account.GameAccount.Clan.AddNews(plr_client.Account.GameAccount, 0, generator.Build().ToByteArray());
plrClient.Account.GameAccount.Clan.AddNews(plrClient.Account.GameAccount, 0, generator.Build().ToByteArray());
}
}
});
break;
case "uc": //UpdateClient
ulong uc_accId = ulong.Parse(args[0].Trim());
int uc_level = int.Parse(args[1].Trim());
int uc_screen = int.Parse(args[2].Trim());
ulong ucAccId = ulong.Parse(args[0].Trim());
int ucLevel = int.Parse(args[1].Trim());
int ucScreen = int.Parse(args[2].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try
{
foreach (var uc_invokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == uc_accId))
foreach (var ucInvokerClient in PlayerManager.OnlinePlayers.Where(c => c.Account.GameAccount.PersistentID == ucAccId))
{
if (!uc_invokerClient.Account.IsOnline) continue;
uc_invokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(uc_invokerClient.Account.GameAccount.CurrentToon.HeroLevelField);
uc_invokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(uc_invokerClient.Account.GameAccount.CurrentToon.HeroParagonLevelField);
if (uc_screen != -1) uc_invokerClient.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(uc_screen).SetStatus(0).Build();
uc_invokerClient.Account.GameAccount.NotifyUpdate();
if (!ucInvokerClient.Account.IsOnline) continue;
ucInvokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(ucInvokerClient.Account.GameAccount.CurrentToon.HeroLevelField);
ucInvokerClient.Account.GameAccount.ChangedFields.SetPresenceFieldValue(ucInvokerClient.Account.GameAccount.CurrentToon.HeroParagonLevelField);
if (ucScreen != -1) ucInvokerClient.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(ucScreen).SetStatus(0).Build();
ucInvokerClient.Account.GameAccount.NotifyUpdate();
}
}
catch { }
});
break;
case "gpj": //PlayerJoined
int gpj_gameId = int.Parse(args[0].Trim());
int gpjGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try
{
GameFactoryManager.FindGameByDynamicId((ulong)gpj_gameId).PlayersCount++;
GameFactoryManager.FindGameByDynamicId((ulong)gpjGameId).PlayersCount++;
}
catch { }
});
break;
case "gpl": //PlayerLeft
int gpl_gameId = int.Parse(args[0].Trim());
int gplGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try
{
if (GameFactoryManager.FindGameByDynamicId((ulong)gpl_gameId) != null)
GameFactoryManager.FindGameByDynamicId((ulong)gpl_gameId).PlayersCount--;
if (GameFactoryManager.FindGameByDynamicId((ulong)gplGameId) != null)
GameFactoryManager.FindGameByDynamicId((ulong)gplGameId).PlayersCount--;
}
catch { }
});
break;
case "gsp": //SetGamePublic
int gsp_gameId = int.Parse(args[0].Trim());
int gspGameId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try
{
GameFactoryManager.FindGameByDynamicId((ulong)gsp_gameId).Public = true;
GameFactoryManager.FindGameByDynamicId((ulong)gspGameId).Public = true;
}
catch { }
});
break;
case "tsc": //ToonStateChanged
int tsc_toonId = int.Parse(args[0].Trim());
int tscToonId = int.Parse(args[0].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
try
{
LoginServer.Toons.ToonManager.GetToonByLowID((ulong)tsc_toonId).StateChanged();
Toons.ToonManager.GetToonByLowId((ulong)tscToonId).StateChanged();
}
catch { }
});
break;
case "pvpsp": //PvPSaveProgress
ulong pvpsp_gAccId = ulong.Parse(args[0].Trim());
int pvpsp_kills = int.Parse(args[1].Trim());
int pvpsp_wins = int.Parse(args[2].Trim());
int pvpsp_gold = int.Parse(args[3].Trim());
ulong pvpspGAccId = ulong.Parse(args[0].Trim());
int pvpspKills = int.Parse(args[1].Trim());
int pvpspWins = int.Parse(args[2].Trim());
int pvpspGold = int.Parse(args[3].Trim());
System.Threading.Tasks.Task.Delay(1).ContinueWith((a) => {
var gAcc = GameAccountManager.GetAccountByPersistentID(pvpsp_gAccId);
var gAcc = GameAccountManager.GetAccountByPersistentID(pvpspGAccId);
lock (gAcc.DBGameAccount)
{
var dbGAcc = gAcc.DBGameAccount;
dbGAcc.PvPTotalKilled += (ulong)pvpsp_kills;
dbGAcc.PvPTotalWins += (ulong)pvpsp_wins;
dbGAcc.PvPTotalGold += (ulong)pvpsp_gold;
dbGAcc.PvPTotalKilled += (ulong)pvpspKills;
dbGAcc.PvPTotalWins += (ulong)pvpspWins;
dbGAcc.PvPTotalGold += (ulong)pvpspGold;
DBSessions.SessionUpdate(dbGAcc);
}
});
break;
default:
Logger.Warn("Unknown message type: {0}|{1}", message[0], message[1]);
Logger.Warn("Unknown message type: $[white]${0}|{1}$[/]$", message[0], message[1]);
break;
}
return true;

View File

@ -1,87 +1,61 @@
#define LOG_KEEP_ALIVE
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using DiIiS_NA.Core.Helpers.Hash;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.GameServer.ClientSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ServicesSystem;
//Blizzless Project 2022
using DotNetty.Transport.Channels;
//Blizzless Project 2022
using DotNetty.Transport.Channels.Sockets;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using Google.ProtocolBuffers.DescriptorProtos;
//Blizzless Project 2022
using Google.ProtocolBuffers.Descriptors;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Net.Security;
//Blizzless Project 2022
using System.Threading.Tasks;
using DiIiS_NA.GameServer.MessageSystem.Message.Definitions.Text;
namespace DiIiS_NA.LoginServer.Battle
{
public class BattleClient : SimpleChannelInboundHandler<BNetPacket>, IRpcChannel
{
private static readonly Logger Logger = LogManager.CreateLogger("F-Client");
private static readonly Logger Logger = LogManager.CreateLogger(nameof(BattleClient));
public Dictionary<uint, uint> Services { get; private set; }
public ISocketChannel SocketConnection { get; private set; }
public IChannelHandlerContext Connect { get; private set; }
public bool AuthenticationStatus = false;
public ClientLocale ClientLanguage = ClientLocale.enUS;
public ClientLocale ClientLanguage = ClientLocale.EN_US;
public IRpcController ListenerController;
private uint _tokenCounter = 0;
public static bgs.protocol.NO_RESPONSE NO_RESPONSE = bgs.protocol.NO_RESPONSE.CreateBuilder().Build();
private readonly Dictionary<int, RPCCallBack> _pendingResponses = new Dictionary<int, RPCCallBack>();
public static NO_RESPONSE NoResponse = NO_RESPONSE.CreateBuilder().Build();
private readonly Dictionary<int, RPCCallBack> _pendingResponses = new(); // TODO: Check usage and remove if not needed
public bgs.protocol.v2.Attribute AttributeOfServer { get; set; }
public Account Account { get; set; }
public const byte ServiceReply = 0xFE;
public SslStream ssl = null;
private static int REQUEST_SERVICE_ID = 0;
private static int RESPONSE_SERVICE_ID = 254;
public const byte SERVICE_REPLY = 0xFE;
public SslStream Ssl = null;
private static int _requestServiceId = 0;
private static int _responseServiceId = 254;
//public object clientLock = new object();
public object _serviceLock = new object();
public object messageLock = new object();
public readonly object ServiceLock = new();
public object MessageLock = new();
private ulong _listenerId; // last targeted rpc object.
public bool MOTDSent { get; private set; }
private ConcurrentDictionary<ulong, ulong> MappedObjects { get; set; }
public bool GuildChannelsRevealed = false;
public string GameTeamTag = "";
#region Overwatch
public byte[] k0, k1, k2, k3 = new byte[64];
public ulong CID = 0;
#endregion
public readonly ulong Cid = 0;
#region current channel
public Dictionary<ulong, Channel> Channels = new Dictionary<ulong, Channel>();
public readonly Dictionary<ulong, Channel> Channels = new();
public List<Channel> ChatChannels = new List<Channel>();
public readonly List<Channel> ChatChannels = new();
public Channel PartyChannel; //Used for all non game related messages
public Channel GameChannel; //Used for all game related messages
@ -90,28 +64,23 @@ namespace DiIiS_NA.LoginServer.Battle
private Channel _currentChannel;
public Channel CurrentChannel
{
get
{
if (_currentChannel == null)
_currentChannel = this.Channels.Values.Where(c => !c.IsChatChannel).FirstOrDefault();
return _currentChannel;
}
get => _currentChannel ??= Channels.Values.FirstOrDefault(c => !c.IsChatChannel);
set
{
if (value == null)
{
if (_currentChannel != null)
this.Channels.Remove(this._currentChannel.DynamicId);
Channels.Remove(_currentChannel.DynamicId);
//Logger.Trace("Client removed from CurrentChannel: {0}, setting new CurrentChannel to {1}", this._currentChannel, this.Channels.FirstOrDefault().Value);
this._currentChannel = Channels.FirstOrDefault().Value;
_currentChannel = Channels.FirstOrDefault().Value;
}
else if (!Channels.ContainsKey(value.DynamicId))
{
this.Channels.Add(value.DynamicId, value);
this._currentChannel = value;
Channels.Add(value.DynamicId, value);
_currentChannel = value;
}
else
this._currentChannel = value;
_currentChannel = value;
}
}
@ -121,24 +90,32 @@ namespace DiIiS_NA.LoginServer.Battle
if (text.Trim() == string.Empty) return;
var notification = bgs.protocol.notification.v1.Notification.CreateBuilder()
.SetTargetId(this.Account.GameAccount.BnetEntityId)
.SetTargetId(Account.GameAccount.BnetEntityId)
.SetType("WHISPER")
.SetSenderId(this.Account.GameAccount.BnetEntityId)
.SetSenderAccountId(this.Account.BnetEntityId)
.SetSenderId(Account.GameAccount.BnetEntityId)
.SetSenderAccountId(Account.BnetEntityId)
.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("whisper")
.SetValue(Variant.CreateBuilder().SetStringValue(text).Build()).Build()).Build();
this.MakeRPC((lid) => bgs.protocol.notification.v1.NotificationListener.CreateStub(this).
MakeRpc((lid) => bgs.protocol.notification.v1.NotificationListener.CreateStub(this).
OnNotificationReceived(new HandlerController()
{
ListenerId = lid
}, notification, callback => { }));
}
public void SendServerMessage(string text)
{
InGameClient.SendMessage(new BroadcastTextMessage()
{
Field0 = text
});
}
public void LeaveAllChannels()
{
List<Channel> _channels = this.Channels.Values.ToList();
foreach (var channel in _channels)
List<Channel> channels = Channels.Values.ToList();
foreach (var channel in channels)
{
try
{
@ -146,19 +123,18 @@ namespace DiIiS_NA.LoginServer.Battle
}
catch { }
}
this.Channels.Clear();
Channels.Clear();
}
#endregion
public BattleClient(ISocketChannel socketChannel, DotNetty.Handlers.Tls.TlsHandler TLS)
public BattleClient(ISocketChannel socketChannel, DotNetty.Handlers.Tls.TlsHandler tls)
{
SocketConnection = socketChannel;
Services = new Dictionary<uint, uint>();
MappedObjects = new ConcurrentDictionary<ulong, ulong>();
this.MOTDSent = false;
if (SocketConnection.Active)
Logger.Trace("Client - {0} - successfully encrypted the connection", socketChannel.RemoteAddress);
Logger.Trace("Client - $[green]$ {0} $[/]$ - successfully encrypted the connection", socketChannel.RemoteAddress);
}
protected override void ChannelRead0(IChannelHandlerContext ctx, BNetPacket msg)
@ -167,7 +143,7 @@ namespace DiIiS_NA.LoginServer.Battle
Header header = msg.GetHeader();
byte[] payload = (byte[])msg.GetPayload();
if (msg.GetHeader().ServiceId == RESPONSE_SERVICE_ID)
if (msg.GetHeader().ServiceId == _responseServiceId)
{
if (_pendingResponses.Count == 0) return;
RPCCallBack done = _pendingResponses[(int)header.Token];
@ -280,22 +256,18 @@ namespace DiIiS_NA.LoginServer.Battle
ListenerId = 0
};
#if DEBUG
#if !LOG_KEEP_ALIVE
if (method.Name != "KeepAlive")
#endif
{
Logger.Warn("Call: {0}, Service hash: {1}, Method: {2}, ID: {3}",
service.GetType().Name, header.ServiceHash, method.Name, header.MethodId);
}
Logger.Debug(
$"Call: $[underline white]${service.GetType().Name}$[/]$, Service hash: $[underline white]${header.ServiceHash}$[/]$, Method: $[underline white]${method.Name}$[/]$, ID: $[olive]${header.MethodId}$[/]$");
#endif
service.CallMethod(method, controller, message,
(IMessage m) => { sendResponse(ctx, (int)header.Token, m, controller.Status); });
(IMessage m) => { SendResponse(ctx, (int)header.Token, m, controller.Status); });
}
}
catch (NotImplementedException)
{
Logger.Warn("Unimplemented service method: {0}.{1}", service.GetType().Name, method.Name);
Logger.Warn("Unimplemented service method:$[red]$ {0}.{1} $[/]$", service.GetType().Name, method.Name);
}
}
else
@ -333,69 +305,69 @@ namespace DiIiS_NA.LoginServer.Battle
/// <summary>
/// Deutsch.
/// </summary>
deDE,
DE_DE,
/// <summary>
/// English (EU)
/// </summary>
enGB,
EN_GB,
/// <summary>
/// English (Singapore)
/// </summary>
enSG,
EN_SG,
/// <summary>
/// English (US)
/// </summary>
enUS,
EN_US,
/// <summary>
/// Espanol
/// </summary>
esES,
ES_ES,
/// <summary>
/// Espanol (Mexico)
/// </summary>
esMX,
ES_MX,
/// <summary>
/// French
/// </summary>
frFR,
FR_FR,
/// <summary>
/// Italian
/// </summary>
itIT,
IT_IT,
/// <summary>
/// Korean
/// </summary>
koKR,
KO_KR,
/// <summary>
/// Polish
/// </summary>
plPL,
PL_PL,
/// <summary>
/// Portuguese
/// </summary>
ptPT,
PT_PT,
/// <summary>
/// Portuguese (Brazil)
/// </summary>
ptBR,
PT_BR,
/// <summary>
/// Russian
/// </summary>
ruRU,
RU_RU,
/// <summary>
/// Turkish
/// </summary>
trTR,
TR_TR,
/// <summary>
/// Chinese
/// </summary>
zhCN,
ZH_CN,
/// <summary>
/// Chinese (Taiwan)
/// </summary>
zhTW
ZH_TW
}
public virtual void MakeTargetedRPC(RPCObject targetObject, Action<ulong> rpc)
public virtual void MakeTargetedRpc(RPCObject targetObject, Action<ulong> rpc)
{
Task.Run(() =>
{
@ -403,12 +375,11 @@ namespace DiIiS_NA.LoginServer.Battle
//{
try
{
if (this.SocketConnection == null || !this.SocketConnection.Active) return;
var listenerId = this.GetRemoteObjectId(targetObject.DynamicId);
#if DEBUG
Logger.Trace("[RPC: {0}] Method: {1} Target: {2} [localId: {3}, remoteId: {4}].", this, rpc.Method,
if (SocketConnection == null || !SocketConnection.Active) return;
var listenerId = GetRemoteObjectId(targetObject.DynamicId);
Logger.Debug("[$[underline yellow]$RPC: {0}$[/]$] Method: $[underline white]${1}$[/]$ Target: $[underline white]${2}$[/]$ " +
"[localId: $[underline white]${3}$[/]$, remoteId: $[underline white]${4}$[/]$].", GetType().Name, rpc.Method.Name,
targetObject.ToString(), targetObject.DynamicId, listenerId);
#endif
rpc(listenerId);
}
@ -416,7 +387,7 @@ namespace DiIiS_NA.LoginServer.Battle
//}
});
}
public virtual void MakeRPC(Action<ulong> rpc)
public virtual void MakeRpc(Action<ulong> rpc)
{
Task.Run(() =>
{
@ -424,10 +395,8 @@ namespace DiIiS_NA.LoginServer.Battle
//{
try
{
if (this.SocketConnection == null || !this.SocketConnection.Active) return;
#if DEBUG
Logger.Trace("[RPC: {0}] Method: {1} Target: N/A", this, rpc.Method);
#endif
if (SocketConnection == null || !SocketConnection.Active) return;
Logger.Debug("[$[underline yellow]$RPC: {0}$[/]$] Method: $[underline yellow]${1}$[/]$ Target: $[underline red]$N/A$[/]$", GetType().Name, rpc.Method.Name);
rpc(0);
}
catch { }
@ -445,29 +414,29 @@ namespace DiIiS_NA.LoginServer.Battle
str = method.Service.Options.UnknownFields[90000].LengthDelimitedList[0].ToStringUtf8().Remove(0, 2);
var serviceHash = StringHashHelper.HashIdentity(str);
if (!this.Services.ContainsKey(serviceHash))
if (!Services.ContainsKey(serviceHash))
{
Logger.Warn("Service not found for client {0} [0x{1}].", serviceName, serviceHash.ToString("X8"));
Logger.Warn("Service not found for client {0} [$[underline blue]$0x{1}$[/]$].", serviceName, serviceHash.ToString("X8"));
// in english: "Service not found for client {0} [0x{1}]."
return;
}
uint status = 0;
if (controller is HandlerController)
if (controller is HandlerController handlerController)
{
status = (controller as HandlerController).Status;
_listenerId = (controller as HandlerController).ListenerId;
status = handlerController.Status;
_listenerId = handlerController.ListenerId;
}
var serviceId = this.Services[serviceHash];
var token = this._tokenCounter++;
sendRequest(Connect, serviceHash, GetMethodId(method), token, request, (uint)_listenerId, status);
var serviceId = Services[serviceHash];
var token = _tokenCounter++;
SendRequest(Connect, serviceHash, GetMethodId(method), token, request, (uint)_listenerId, status);
}
public static void sendRequest(IChannelHandlerContext ctx, uint serviceHash, uint methodId, uint token, IMessage request, uint listenerId, uint status)
public static void SendRequest(IChannelHandlerContext ctx, uint serviceHash, uint methodId, uint token, IMessage request, uint listenerId, uint status)
{
Header.Builder builder = Header.CreateBuilder();
builder.SetServiceId((uint)REQUEST_SERVICE_ID);
builder.SetServiceId((uint)_requestServiceId);
builder.SetServiceHash(serviceHash);
builder.SetMethodId(methodId);
if (listenerId != 0)
@ -480,11 +449,11 @@ namespace DiIiS_NA.LoginServer.Battle
}
/// <param name="localObjectId">The local objectId.</param>
/// <param name="remoteObjectId">The remote objectId over client.</param>
public void MapLocalObjectID(ulong localObjectId, ulong remoteObjectId)
public void MapLocalObjectId(ulong localObjectId, ulong remoteObjectId)
{
try
{
this.MappedObjects[localObjectId] = remoteObjectId;
MappedObjects[localObjectId] = remoteObjectId;
}
catch (Exception e)
{
@ -497,7 +466,7 @@ namespace DiIiS_NA.LoginServer.Battle
{
try
{
this.MappedObjects.TryRemove(localObjectId, out _);
MappedObjects.TryRemove(localObjectId, out _);
}
catch (Exception e)
{
@ -506,7 +475,7 @@ namespace DiIiS_NA.LoginServer.Battle
}
public ulong GetRemoteObjectId(ulong localObjectId)
{
return localObjectId != 0 ? this.MappedObjects[localObjectId] : 0;
return localObjectId != 0 ? MappedObjects[localObjectId] : 0;
}
public static uint GetMethodId(MethodDescriptor method)
{
@ -519,10 +488,10 @@ namespace DiIiS_NA.LoginServer.Battle
return (uint)(method.Index) + 1;
}
}
public static void sendResponse(IChannelHandlerContext ctx, int token, IMessage response, uint status)
public static void SendResponse(IChannelHandlerContext ctx, int token, IMessage response, uint status)
{
Header.Builder builder = Header.CreateBuilder();
builder.SetServiceId((uint)RESPONSE_SERVICE_ID);
builder.SetServiceId((uint)_responseServiceId);
builder.SetToken((uint)token);
builder.SetStatus(status);
if (response != null)
@ -530,15 +499,12 @@ namespace DiIiS_NA.LoginServer.Battle
ctx.Channel.WriteAndFlushAsync(new BNetPacket(builder.Build(), response));
}
public void SendMOTD()
public void SendMotd()
{
if (this.MOTDSent)
if (string.IsNullOrWhiteSpace(LoginServerConfig.Instance.Motd) || !LoginServerConfig.Instance.MotdEnabled)
return;
var motd = "Welcome to BlizzLess.Net Alpha-Build Server!";
this.SendServerWhisper(motd);
this.MOTDSent = true;
Logger.Debug($"Motd sent to {Account.BattleTag}.");
SendServerWhisper(LoginServerConfig.Instance.Motd);
}
public override void ChannelInactive(IChannelHandlerContext context)
@ -549,7 +515,7 @@ namespace DiIiS_NA.LoginServer.Battle
private void DisconnectClient()
{
if (this.Account != null && this.Account.GameAccount != null) this.Account.GameAccount.LoggedInClient = null;
if (Account != null && Account.GameAccount != null) Account.GameAccount.LoggedInClient = null;
PlayerManager.PlayerDisconnected(this);
}
}

View File

@ -1,25 +1,19 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.Battle
{
public static class PlayerManager
{
public static readonly List<BattleClient> OnlinePlayers = new List<BattleClient>();
public static readonly List<BattleClient> OnlinePlayers = new();
public static void PlayerConnected(BattleClient client)
{
var already_logged = OnlinePlayers.Where(cli => cli.Account.Email == client.Account.Email);
foreach (var logged in already_logged)
var alreadyLoggedIn = OnlinePlayers.Where(cli => cli.Account.Email == client.Account.Email).ToArray();
foreach (var logged in alreadyLoggedIn)
{
OnlinePlayers.Remove(client);
logged.SocketConnection.DisconnectAsync();
@ -28,12 +22,32 @@ namespace DiIiS_NA.LoginServer.Battle
OnlinePlayers.Add(client);
}
public static BattleClient GetClientbyCID(ulong cid)
public static BattleClient GetClientByEmail(string email) => OnlinePlayers.FirstOrDefault(cli => cli.Account.Email == email);
public static BattleClient GetClientByBattleTag(string battleTag) => OnlinePlayers.FirstOrDefault(cli => cli.Account.BattleTag == battleTag);
public static BattleClient GetClientByCid(ulong cid)
{
foreach (var bc in OnlinePlayers)
if (bc.CID == cid)
return bc;
return null;
return OnlinePlayers.FirstOrDefault(bc => bc.Cid == cid);
}
public static void SendWhisper(string message)
{
Broadcast(client =>
{
client.SendServerWhisper(message);
});
}
public static void Broadcast(Action<BattleClient> action, Func<BattleClient, bool> predicate)
{
foreach (var client in OnlinePlayers.Where(predicate))
action(client);
}
public static void Broadcast(Action<BattleClient> action)
{
foreach (var client in OnlinePlayers)
action(client);
}
public static void PlayerDisconnected(BattleClient client)

View File

@ -1,25 +1,13 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.GuildSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
namespace DiIiS_NA.LoginServer.ChannelSystem
@ -104,7 +92,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
this.IsGuildChatChannel = false;
if ((client != null) && (remoteObjectId != 0))
client.MapLocalObjectID(this.DynamicId, remoteObjectId);
client.MapLocalObjectId(this.DynamicId, remoteObjectId);
if (this.IsChatChannel)
Program.Watchdog.AddTask(10, new Action(() =>
@ -186,7 +174,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.AddStateChange(channelMember)
.Build();
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateMemberState(new HandlerController() { ListenerId = lid } , notification, callback => { }));
}
@ -212,7 +200,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
//Notify all Channel members
foreach (var n_member in this.Members.Keys)
{
n_member.MakeTargetedRPC(this, (lid) =>
n_member.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(n_member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
}
}
@ -224,7 +212,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
public void Join(BattleClient client, ulong remoteObjectId)
{
client.MapLocalObjectID(this.DynamicId, remoteObjectId);
client.MapLocalObjectId(this.DynamicId, remoteObjectId);
this.AddMember(client);
}
@ -260,7 +248,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.AddRangeMember(members)
.Build();
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, joinNotification, callback => { }));
@ -287,7 +275,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members.Where(pair => pair.Value != addedMember)) // only send this to previous members of the channel.
{
pair.Key.MakeTargetedRPC(this, (lid) =>
pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberAdded(new HandlerController() { ListenerId = lid }, addNotification, callback => { }));
}
@ -359,10 +347,10 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members)
{
if (pair.Key != client)
pair.Key.MakeTargetedRPC(this, (lid) =>
pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnMemberRemoved(new HandlerController() { ListenerId = lid }, removeMessage, callback => { }));
}
client.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnLeave(new HandlerController() { ListenerId = lid }, leaveMessage, callback =>
client.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnLeave(new HandlerController() { ListenerId = lid }, leaveMessage, callback =>
{
client.UnmapLocalObjectId(this.DynamicId); }));
@ -442,7 +430,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var pair in this.Members) // send to all members of channel even to the actual one that sent the message else he'll not see his own message.
{
if (pair.Key.Account.IgnoreIds.Contains(client.Account.PersistentID)) continue;
pair.Key.MakeTargetedRPC(this, (lid) =>
pair.Key.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(pair.Key).OnSendMessage(new HandlerController() { ListenerId = lid }, notification, callback => { }));
}
}

View File

@ -1,19 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer.ChannelSystem
@ -62,7 +53,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
var notification = bgs.protocol.channel.v1.InvitationAddedNotification.CreateBuilder().SetInvitation(invitation);
invitee.MakeTargetedRPC(this, (lid) =>
invitee.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(invitee).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}
@ -88,7 +79,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(invitation.Id);
GoingInvitations.Remove(request.InvitationId);
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
channel.Join(client, request.ObjectId);
@ -100,7 +91,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys)
{
member.MakeTargetedRPC(channel, (lid) =>
member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
}
@ -122,9 +113,9 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
#region
string GAME_SERVER_IP = Program.GAMESERVERIP;
string gameServerIp = Program.GameServerIp;
if (GameServer.NATConfig.Instance.Enabled)
GAME_SERVER_IP = Program.PUBLICGAMESERVERIP;
gameServerIp = Program.PublicGameServerIp;
uint GAME_SERVER_PORT = 2001;
var member = bgs.protocol.account.v1.GameAccountHandle.CreateBuilder();
@ -132,7 +123,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
var notification = bgs.protocol.matchmaking.v1.MatchmakingResultNotification.CreateBuilder();
var connectInfo = bgs.protocol.matchmaking.v1.ConnectInfo.CreateBuilder();
connectInfo.SetAddress(Address.CreateBuilder().SetAddress_(GAME_SERVER_IP).SetPort(GAME_SERVER_PORT));
connectInfo.SetAddress(Address.CreateBuilder().SetAddress_(gameServerIp).SetPort(GAME_SERVER_PORT));
connectInfo.AddAttribute(bgs.protocol.v2.Attribute.CreateBuilder().SetName("GameAccount").SetValue(bgs.protocol.v2.Variant.CreateBuilder().SetBlobValue(member.Build().ToByteString())));
connectInfo.AddAttribute(bgs.protocol.v2.Attribute.CreateBuilder().SetName("Token").SetValue(bgs.protocol.v2.Variant.CreateBuilder().SetUintValue(0xEEF4364684EE186E))); // FIXME
//connectInfo.AddAttribute(AttributeOfServer); // Game settings
@ -165,7 +156,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.SetStateChange(channelStatePermission)
.Build();
JoinClient.MakeTargetedRPC(JoinClient.CurrentChannel, (lid) =>
JoinClient.MakeTargetedRpc(JoinClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(JoinClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { }));
}
gameFound.StartGame(clients, gameFound.DynamicId);
@ -179,7 +170,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
.SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build());
notificationFound.AddAttribute(attrF);
JoinClient.MakeRPC((lid) =>
JoinClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(JoinClient).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { }));
@ -194,7 +185,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
notification.SetGameHandle(gh);
System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate {
JoinClient.MakeRPC((lid) => bgs.protocol.matchmaking.v1.GameRequestListener.CreateStub(JoinClient).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
JoinClient.MakeRpc((lid) => bgs.protocol.matchmaking.v1.GameRequestListener.CreateStub(JoinClient).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
});
#endregion
@ -244,9 +235,9 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys)
{
member.MakeTargetedRPC(channel, (lid) =>
member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
member.MakeTargetedRPC(channel, (lid) =>
member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, joinstateNotification, callback => { }));
}
@ -272,7 +263,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
client.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
client.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
channel.Join(mem, request.ObjectId); // add invitee to channel -- so inviter and other members will also be notified too.
@ -289,7 +280,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
foreach (var member in channel.Members.Keys)
{
member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
member.MakeTargetedRpc(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, stateNotification, callback => { }));
//member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnJoin(new HandlerController() { ListenerId = lid }, build, callback => { }));
}
@ -313,7 +304,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(invitation.Id);
GoingInvitations.Remove(request.InvitationId);
inviter.LoggedInClient.MakeTargetedRPC(inviter.LoggedInClient.CurrentChannel, (lid) =>
inviter.LoggedInClient.MakeTargetedRpc(inviter.LoggedInClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(inviter.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}
@ -336,7 +327,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
_onGoingInvitations.Remove(request.InvitationId);
GoingInvitations.Remove(request.InvitationId);
inviter.LoggedInClient.MakeTargetedRPC(inviter.LoggedInClient.CurrentChannel, (lid) =>
inviter.LoggedInClient.MakeTargetedRpc(inviter.LoggedInClient.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, updateChannelNotification.Build(), callback => { }));
//notify invitee about revoke
@ -347,7 +338,7 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
if (Subscribers.All(subscriber => subscriber.Key.Account.GameAccount.BnetEntityId.Low != invitation.InviteeIdentity.AccountId.Low)) return;
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelInvitationListener.CreateStub(client).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, invitationRemoved.Build(), callback => { }));
}

View File

@ -1,17 +1,9 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.GamesSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.GuildSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
namespace DiIiS_NA.LoginServer.ChannelSystem

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using bgs.protocol.channel.v1;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
namespace DiIiS_NA.LoginServer.ChannelSystem
@ -59,29 +54,30 @@ namespace DiIiS_NA.LoginServer.ChannelSystem
{
var rank = this.Channel.Guild.GetRank(this.Identity.GameAccountId.Low);
var note = this.Channel.Guild.GetMemberNote(this.Identity.GameAccountId.Low);
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("D3.GuildMember.Rank").SetValue(bgs.protocol.Variant.CreateBuilder().SetIntValue(rank)));
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("D3.GuildMember.Note").SetValue(bgs.protocol.Variant.CreateBuilder().SetStringValue(note)));
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("D3.GuildMember.AchievementPoints").SetValue(bgs.protocol.Variant.CreateBuilder().SetUintValue(this.GameAccount.AchievementPoints)));
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("D3.GuildMember.Rank")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetIntValue(rank)));
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("D3.GuildMember.Note")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetStringValue(note)));
builder.AddAttribute(bgs.protocol.Attribute.CreateBuilder()
.SetName("D3.GuildMember.AchievementPoints").SetValue(bgs.protocol.Variant.CreateBuilder()
.SetUintValue(this.GameAccount.AchievementPoints)));
}
else
{
if (this.Privileges != Privilege.None)
builder.SetPrivileges((ulong)this.Privileges); // We don't have to set this if it is the default (0)
builder.SetPrivileges(
(ulong)this.Privileges); // We don't have to set this if it is the default (0)
}
return builder.Build();
}
}
public bgs.protocol.channel.v1.Member BnetMember
{
get
{
return bgs.protocol.channel.v1.Member.CreateBuilder()
public bgs.protocol.channel.v1.Member BnetMember =>
bgs.protocol.channel.v1.Member.CreateBuilder()
.SetIdentity(this.Identity)
.SetState(this.BnetMemberState)
.Build();
}
}
public Member(Channel channel, GameAccount account, Privilege privs, params Role[] roles)
{

View File

@ -1,27 +0,0 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer
{
public sealed class Config : Core.Config.Config
{
public bool Enabled { get { return this.GetBoolean("Enabled", true); } set { this.Set("Enabled", value); } }
public string BindIP { get { return this.GetString("BindIP", "127.0.0.1"); } set { this.Set("BindIP", value); } }
public int WebPort { get { return this.GetInt("WebPort", 9000); } set { this.Set("WebPort", value); } }
public int Port { get { return this.GetInt("Port", 1119); } set { this.Set("Port", value); } }
public string BindIPv6 { get { return this.GetString("BindIPv6", "::1"); } set { this.Set("BindIPv6", value); } }
private static readonly Config _instance = new Config();
public static Config Instance { get { return _instance; } }
private Config() : base("Battle-Server") { }
}
}

View File

@ -1,5 +1,4 @@
//Blizzless Project 2022
namespace DiIiS_NA.LoginServer.Crypthography
namespace DiIiS_NA.LoginServer.Crypthography
{
public class ARC4
{

View File

@ -1,17 +1,9 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Numerics;
//Blizzless Project 2022
using System.Security.Cryptography;
//Blizzless Project 2022
using System.Text;
namespace DiIiS_NA.LoginServer.Crypthography
@ -89,11 +81,11 @@ namespace DiIiS_NA.LoginServer.Crypthography
// calculate server's public ephemeral value.
this.b = GetRandomBytes(128).ToBigInteger(); // server's secret ephemeral value.
var gModb = BigInteger.ModPow(g, b, N); // pow(g, b, N)
var k = H.ComputeHash(new byte[0].Concat(N.ToArray()).Concat(g.ToArray()).ToArray()).ToBigInteger(); // Multiplier parameter (k = H(N, g) in SRP-6a
this.B = BigInteger.Remainder((this.Account.PasswordVerifier.ToBigInteger() * k) + gModb, N); // B = (k * v + pow(g, b, N)) % N
var k = H.ComputeHash(Array.Empty<byte>().Concat(N.ToArray()).Concat(g.ToArray()).ToArray()).ToBigInteger(); // Multiplier parameter (k = H(N, g) in SRP-6a
this.B = BigInteger.Remainder((BigInteger.Add(BigInteger.Multiply(this.Account.PasswordVerifier.ToBigInteger(), k), gModb)), N); // B = (k * v + pow(g, b, N)) % N
// cook the logon challenge message
this.LogonChallenge = new byte[0]
this.LogonChallenge = Array.Empty<byte>()
.Concat(new byte[] { 0 }) // command = 0
.Concat(this.IdentitySalt.ToByteArray()) // identity-salt - generated by hashing account email.
.Concat(this.Account.Salt) // account-salt - generated on account creation.
@ -119,7 +111,7 @@ namespace DiIiS_NA.LoginServer.Crypthography
var identitySalt = H.ComputeHash(Encoding.ASCII.GetBytes(email)).ToHexString();
var pBytes = H.ComputeHash(Encoding.ASCII.GetBytes(identitySalt.ToUpper() + ":" + password.ToUpper())); // p (identitySalt + password)
var x = H.ComputeHash(new byte[0].Concat(salt).Concat(pBytes).ToArray()).ToBigInteger(); // x = H(s, p)
var x = H.ComputeHash(Array.Empty<byte>().Concat(salt).Concat(pBytes).ToArray()).ToBigInteger(); // x = H(s, p)
return BigInteger.ModPow(g, x, N).ToArray(128);
}
@ -128,16 +120,16 @@ namespace DiIiS_NA.LoginServer.Crypthography
public bool Verify(byte[] A_bytes, byte[] M_client, byte[] seed)
{
var A = A_bytes.ToBigInteger(); // client's public ephemeral
var u = H.ComputeHash(new byte[0].Concat(A_bytes).Concat(B.ToArray(128)).ToArray()).ToBigInteger(); // Random scrambling parameter - u = H(A, B)
var u = H.ComputeHash(Array.Empty<byte>().Concat(A_bytes).Concat(B.ToArray(128)).ToArray()).ToBigInteger(); // Random scrambling parameter - u = H(A, B)
var S_s = BigInteger.ModPow(A * BigInteger.ModPow(this.Account.PasswordVerifier.ToBigInteger(), u, N), b, N); // calculate server session key - S = (Av^u) ^ b
var S_s = BigInteger.ModPow(BigInteger.Multiply(A, BigInteger.ModPow(this.Account.PasswordVerifier.ToBigInteger(), u, N)), b, N); // calculate server session key - S = (Av^u) ^ b
this.SessionKey = Calc_K(S_s.ToArray(128)); // K = H(S) - Shared, strong session key.
byte[] K_s = this.SessionKey;
var hashgxorhashN = Hash_g_and_N_and_xor_them().ToBigInteger(); // H(N) ^ H(g)
var hashedIdentitySalt = H.ComputeHash(Encoding.ASCII.GetBytes(this.IdentitySalt)); // H(I)
var M = H.ComputeHash(new byte[0] // verify client M_client - H(H(N) ^ H(g), H(I), s, A, B, K_c)
var M = H.ComputeHash(Array.Empty<byte>() // verify client M_client - H(H(N) ^ H(g), H(I), s, A, B, K_c)
.Concat(hashgxorhashN.ToArray(32))
.Concat(hashedIdentitySalt)
.Concat(this.Account.Salt.ToArray())
@ -150,14 +142,14 @@ namespace DiIiS_NA.LoginServer.Crypthography
// which allows authentication without the correct password, they should be also calculated for wrong-passsword auths. /raist.
// calculate server proof of session key
var M_server = H.ComputeHash(new byte[0] // M_server = H(A, M_client, K)
var M_server = H.ComputeHash(Array.Empty<byte>() // M_server = H(A, M_client, K)
.Concat(A_bytes)
.Concat(M_client)
.Concat(K_s)
.ToArray());
// cook logon proof message.
LogonProof = new byte[0]
LogonProof = Array.Empty<byte>()
.Concat(new byte[] { 3 }) // command = 3 - server sends proof of session key to client
.Concat(M_server) // server's proof of session key
.Concat(B.ToArray(128)) // second proof

View File

@ -1,23 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer.FriendsSystem
@ -77,7 +66,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
.SetInvitation(invitation)
.SetAccountId(invitee.BnetEntityId);
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback =>
{
}));
@ -99,13 +88,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline)
{
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
}
if (invitee.GameAccount.IsOnline)
{
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
}
@ -154,19 +143,19 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline)
{
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInviter, callback => { }));
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInviter, callback => { }));
}
if (invitee.GameAccount.IsOnline)
{
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnFriendAdded(new HandlerController() { ListenerId = lid }, friendAddedNotificationToInvitee, callback => { }));
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, notificationToInvitee, callback => { }));
}
@ -187,13 +176,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
if (inviter.GameAccount.IsOnline)
{
inviter.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
inviter.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(inviter.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
}
if (invitee.GameAccount.IsOnline)
{
invitee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) =>
invitee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(invitee.GameAccount.LoggedInClient).OnReceivedInvitationRemoved(new HandlerController() { ListenerId = lid }, declinedNotification, callback => { }));
}
@ -225,13 +214,13 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
.SetAccountId(remover.BnetEntityId)
.Build();
client.MakeTargetedRPC(FriendManager.Instance, (lid) =>
client.MakeTargetedRpc(FriendManager.Instance, (lid) =>
bgs.protocol.friends.v1.FriendsListener.CreateStub(client).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemover, callback => { }));
if (removee.GameAccount.IsOnline)
{
var notifyRemovee = bgs.protocol.friends.v1.FriendNotification.CreateBuilder().SetTarget(removerAsFriend).SetAccountId(removee.BnetEntityId).Build();
removee.GameAccount.LoggedInClient.MakeTargetedRPC(FriendManager.Instance, (lid) => bgs.protocol.friends.v1.FriendsListener.CreateStub(removee.GameAccount.LoggedInClient).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemovee, callback => { }));
removee.GameAccount.LoggedInClient.MakeTargetedRpc(FriendManager.Instance, (lid) => bgs.protocol.friends.v1.FriendsListener.CreateStub(removee.GameAccount.LoggedInClient).OnFriendRemoved(new HandlerController() { ListenerId = lid }, notifyRemovee, callback => { }));
}
}

View File

@ -1,27 +1,15 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.FriendsSystem
@ -50,7 +38,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
notifyBlock.SetPlayer(blockedPlayer);
notifyBlock.SetGameAccountId(blocked.BnetEntityId);
client.MakeTargetedRPC(UserManager.Instance, (lid) =>
client.MakeTargetedRpc(UserManager.Instance, (lid) =>
bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerAdded(new HandlerController() { ListenerId = lid }, notifyBlock.Build(), callback => { }));
}
@ -72,16 +60,16 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
var notifyUnblock = bgs.protocol.user_manager.v1.BlockedPlayerRemovedNotification.CreateBuilder();
notifyUnblock.SetPlayer(blockedPlayer);
client.MakeTargetedRPC(UserManager.Instance, (lid) =>
client.MakeTargetedRpc(UserManager.Instance, (lid) =>
bgs.protocol.user_manager.v1.UserManagerListener.CreateStub(client).OnBlockedPlayerRemoved(new HandlerController() { ListenerId = lid }, notifyUnblock.Build(), callback => { }));
}
private static void AddIgnoreToDB(Account owner, Account target)
{
Logger.Trace("AddIgnoreToDB(): owner {0}, target {1}", owner.PersistentID, target.PersistentID);
Logger.MethodTrace($": owner {owner.PersistentID}, target {target.PersistentID}");
try
{
if (DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE").Count() > 0) return;
if (DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE").Any()) return;
var blockRecord = new DBAccountLists
{
@ -99,7 +87,7 @@ namespace DiIiS_NA.LoginServer.FriendsSystem
private static void RemoveIgnoreFromDB(Account owner, Account target)
{
Logger.Trace("RemoveIgnoreFromDB(): owner {0}, target {1}", owner.PersistentID, target.PersistentID);
Logger.MethodTrace($": owner {owner.PersistentID}, target {target.PersistentID}");
try
{
var blockRecords = DBSessions.SessionQueryWhere<DBAccountLists>(dbl => dbl.ListOwner.Id == owner.PersistentID && dbl.ListTarget.Id == target.PersistentID && dbl.Type == "IGNORE");

View File

@ -1,25 +1,14 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol.matchmaking.v1;
//Blizzless Project 2022
using bgs.protocol.matchmaking.v1;
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.GamesSystem
@ -85,7 +74,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
public void StartGame(List<BattleClient> clients, ulong objectId)
{
Logger.Trace("StartGame(): objectId: {0}", objectId);
Logger.MethodTrace($"objectId: {objectId}");
var owner = this.Owner.Account.GameAccount.CurrentToon.DBToon;
if (Program.BattleBackend.GameServers.Count == 0) return;
@ -105,7 +94,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
foreach (var client in clients)
{
client.MapLocalObjectID(this.DynamicId, objectId);
client.MapLocalObjectId(this.DynamicId, objectId);
this.SendConnectionInfo(client);
client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(0).SetStatus(0).Build();
client.Account.GameAccount.NotifyUpdate();
@ -119,7 +108,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
{
foreach (var client in clients)
{
client.MapLocalObjectID(this.DynamicId, objectId);
client.MapLocalObjectId(this.DynamicId, objectId);
this.SendConnectionInfo(client);
client.Account.GameAccount.ScreenStatus = D3.PartyMessage.ScreenStatus.CreateBuilder().SetScreen(1).SetStatus(1).Build();
client.Account.GameAccount.NotifyUpdate();
@ -129,7 +118,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
public bgs.protocol.games.v2.ConnectInfo GetConnectionInfoForClient(BattleClient client)
{
return bgs.protocol.games.v2.ConnectInfo.CreateBuilder()
.SetAddress(bgs.protocol.Address.CreateBuilder().SetAddress_(this.GServer.Value.GameIP).SetPort((uint)this.GServer.Value.GamePort))
.SetAddress(bgs.protocol.Address.CreateBuilder().SetAddress_(this.GServer.Value.GameIp).SetPort((uint)this.GServer.Value.GamePort))
.SetToken(Google.ProtocolBuffers.ByteString.CopyFrom(new byte[] { 0x31, 0x33, 0x38, 0x38, 0x35, 0x34, 0x33, 0x33, 0x32, 0x30, 0x38, 0x34, 0x30, 0x30, 0x38, 0x38, 0x35, 0x37, 0x39, 0x36 }))
.AddAttribute(bgs.protocol.Attribute.CreateBuilder().SetName("Token").SetValue(bgs.protocol.Variant.CreateBuilder().SetUintValue(0xee34d06ffe821c43L)))
@ -156,7 +145,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
.SetChannelState(channelStatePrivacyLevel)
.Build();
client.MakeTargetedRPC(client.CurrentChannel, (lid) =>
client.MakeTargetedRpc(client.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPrivacyLevel, callback => { }));
@ -176,7 +165,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
.SetChannelState(channelStatePartyLock)
.Build();
client.MakeTargetedRPC(client.CurrentChannel, (lid) =>
client.MakeTargetedRpc(client.CurrentChannel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPartyLock, callback => { }));
}
}

View File

@ -1,20 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol.matchmaking.v1;
//Blizzless Project 2022
using bgs.protocol.matchmaking.v1;
using D3.OnlineService;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
using DiIiS_NA.Core.Extensions;
namespace DiIiS_NA.LoginServer.GamesSystem
{
@ -27,7 +19,7 @@ namespace DiIiS_NA.LoginServer.GamesSystem
{
get
{
return GameCreators.Values.Where(game => game.PlayersCount > 0).Count();
return GameCreators.Values.Count(game => game.PlayersCount > 0);
}
set { }
}
@ -103,13 +95,12 @@ namespace DiIiS_NA.LoginServer.GamesSystem
GameDescriptor TagGame = null;
if (client.GameTeamTag != "") TagGame = FindTagGame(client.GameTeamTag);
var rand = new Random();
GameDescriptor gameDescriptor = null;
if(TagGame != null)
gameDescriptor = TagGame;
else if (request_type == "find" && matchingGames.Count > 0)
gameDescriptor = matchingGames[rand.Next(matchingGames.Count)];
gameDescriptor = matchingGames.PickRandom();
else
gameDescriptor = CreateGame(client, request.Options, requestId);

View File

@ -1,27 +1,14 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using DateTime = System.DateTime;
namespace DiIiS_NA.LoginServer.GuildSystem
@ -498,7 +485,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.SetTargetAccountId(account.Owner.BnetEntityId)
.Build();
account.LoggedInClient.MakeRPC((lid) =>
account.LoggedInClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid
}, notificationBuilder, callback => { }));
@ -519,7 +506,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.SetTargetAccountId(account.Owner.BnetEntityId)
.Build();
account.LoggedInClient.MakeRPC((lid) =>
account.LoggedInClient.MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(account.LoggedInClient).OnNotificationReceived(new HandlerController() { ListenerId = lid
}, chatNotificationBuilder, callback => { }));
}
@ -552,7 +539,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
foreach (var member in this.Channel.Members)
//member.Key.MakeTargetedRPC(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
member.Key.MakeTargetedRPC(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnJoin(new HandlerController() { ListenerId = lid }, altnotification, callback => { }));
member.Key.MakeTargetedRpc(this.Channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member.Key).OnJoin(new HandlerController() { ListenerId = lid }, altnotification, callback => { }));
}
public void UpdateMemberAttributes(GameAccount member)
@ -577,7 +564,7 @@ namespace DiIiS_NA.LoginServer.GuildSystem
.Build();
foreach (var mbr in this.Channel.Members)
mbr.Key.MakeTargetedRPC(this.Channel, (lid) =>
mbr.Key.MakeTargetedRpc(this.Channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(mbr.Key).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
}

View File

@ -1,15 +1,8 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer.GuildSystem

View File

@ -1,5 +1,4 @@
//Blizzless Project 2022
namespace DiIiS_NA.LoginServer.Helpers
namespace DiIiS_NA.LoginServer.Helpers
{
public static class EntityIdHelper
{

View File

@ -1,9 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol.presence.v1;
//Blizzless Project 2022
using bgs.protocol.presence.v1;
using DiIiS_NA.LoginServer.Objects;
//Blizzless Project 2022
using System.Collections.Generic;
namespace DiIiS_NA.LoginServer.Helpers

View File

@ -1,9 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Text;
namespace DiIiS_NA.LoginServer.Helpers

View File

@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer
{
public sealed class LoginServerConfig : Core.Config.Config
{
public bool Enabled
{
get => GetBoolean(nameof(Enabled), true);
set => Set(nameof(Enabled), value);
}
public string BindIP
{
get => GetString(nameof(BindIP), "127.0.0.1");
set => Set(nameof(BindIP), value);
}
public int WebPort
{
get => GetInt(nameof(WebPort), 9000);
set => Set(nameof(WebPort), value);
}
public int Port
{
get => GetInt(nameof(Port), 1119);
set => Set(nameof(Port), value);
}
[Obsolete]
public string BindIPv6
{
get => GetString(nameof(BindIPv6), "::1");
set => Set(nameof(BindIPv6), value);
}
/// <summary>
/// Whether Motd should be displayed on login.
/// </summary>
public bool MotdEnabled
{
get => GetBoolean(nameof(MotdEnabled), true);
set => Set(nameof(MotdEnabled), value);
}
/// <summary>
/// Motd text
/// </summary>
public string Motd
{
get => GetString(nameof(Motd),
$"Welcome to Blizzless Server Build {Program.Build} - Stage: {Program.Stage} [{Program.TypeBuild}]!");
set => Set(nameof(Motd), value);
}
public static readonly LoginServerConfig Instance = new();
private LoginServerConfig() : base("Battle-Server")
{
}
}
}

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System.Runtime.Serialization;
using System.Runtime.Serialization;
namespace DiIiS_NA.LoginServer.Objects
{

View File

@ -1,20 +1,14 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Text;
namespace DiIiS_NA.LoginServer.Objects
{
public class EntityIdPresenceFieldList
{
public List<bgs.protocol.EntityId> Value = new List<bgs.protocol.EntityId>();
public List<bgs.protocol.EntityId> Value = new();
protected FieldKeyHelper.Program _program;
protected FieldKeyHelper.OriginatingClass _originatingClass;

View File

@ -1,19 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
namespace DiIiS_NA.LoginServer.Objects
@ -41,7 +32,7 @@ namespace DiIiS_NA.LoginServer.Objects
if (this.Subscribers.ContainsKey(client)) return;
this.Subscribers.TryAdd(client, 0);
client.MapLocalObjectID(this.DynamicId, remoteObjectId);
client.MapLocalObjectId(this.DynamicId, remoteObjectId);
if (client.SocketConnection.Active)
{
@ -64,7 +55,7 @@ namespace DiIiS_NA.LoginServer.Objects
return new List<bgs.protocol.presence.v1.FieldOperation>();
}
public Helpers.FieldKeyHelper ChangedFields = new Helpers.FieldKeyHelper();
public readonly Helpers.FieldKeyHelper ChangedFields = new();
protected void NotifySubscriptionAdded(BattleClient client)
{
@ -104,8 +95,8 @@ namespace DiIiS_NA.LoginServer.Objects
var altnotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState);
if (gameAccount.LoggedInClient != null)
{
gameAccount.LoggedInClient.MakeTargetedRPC(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
gameAccount.LoggedInClient.MakeTargetedRPC(this, (lid) =>
gameAccount.LoggedInClient.MakeTargetedRpc(this, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
gameAccount.LoggedInClient.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(gameAccount.LoggedInClient).OnJoin(new HandlerController() { ListenerId = lid }, altnotification.Build(), callback => { }));
}
}
@ -118,10 +109,10 @@ namespace DiIiS_NA.LoginServer.Objects
var channelState = bgs.protocol.channel.v1.ChannelState.CreateBuilder().SetExtension(bgs.protocol.presence.v1.ChannelState.Presence, state);
var builder = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelState);
var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder().SetStateChange(channelState);
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { }));
client.MakeTargetedRPC(this, (lid) =>
client.MakeTargetedRpc(this, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(client).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}

View File

@ -1,9 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
namespace DiIiS_NA.LoginServer.Objects
@ -13,7 +9,7 @@ namespace DiIiS_NA.LoginServer.Objects
private static readonly Logger Logger = LogManager.CreateLogger();
private static ulong _nextId = 10000;
public static readonly Dictionary<ulong, RPCObject> Objects = new Dictionary<ulong, RPCObject>();
public static readonly Dictionary<ulong, RPCObject> Objects = new();
static RPCObjectManager()
{ }

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
namespace DiIiS_NA.LoginServer.ServicesSystem
namespace DiIiS_NA.LoginServer.ServicesSystem
{
public interface IServerService
{

View File

@ -1,15 +1,8 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Hash;
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Hash;
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem
@ -35,14 +28,14 @@ namespace DiIiS_NA.LoginServer.ServicesSystem
public static class Service
{
private static uint _notImplementedServiceCounter = 99;
public readonly static Dictionary<Type, ServiceAttribute> ProvidedServices = new Dictionary<Type, ServiceAttribute>();
public readonly static Dictionary<Type, IService> Services = new Dictionary<Type, IService>();
private readonly static Dictionary<Type, ServiceAttribute> ProvidedServices = new();
private readonly static Dictionary<Type, IService> Services = new();
static Service()
{
foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(type => type.GetInterface("IServerService") != null))
foreach (var type in Assembly.GetExecutingAssembly().GetTypes().Where(type => type.GetInterface(nameof(IServerService)) != null))
{
object[] attributes = type.GetCustomAttributes(typeof(ServiceAttribute), true);
var attributes = type.GetCustomAttributes(typeof(ServiceAttribute), true);
if (attributes.Length == 0) return;
ProvidedServices.Add(type, (ServiceAttribute)attributes[0]);

View File

@ -1,13 +1,7 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using Google.ProtocolBuffers;
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.account.v1;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
@ -25,7 +19,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
GetAccountStateResponse.Builder builder = GetAccountStateResponse.CreateBuilder();
var AccState = AccountState.CreateBuilder();
if (request.EntityId.Low == (controller as HandlerController).Client.Account.BnetEntityId.Low)
if (request.EntityId.Low == ((HandlerController) controller).Client.Account.BnetEntityId.Low)
{
if (request.Options.FieldPrivacyInfo)
{
@ -54,9 +48,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
level.SetCountry("RUS");
level.SetPreferredRegion(1);
level.SetFullName("Name LastName");
level.SetBattleTag((controller as HandlerController).Client.Account.BattleTag);
level.SetBattleTag(((HandlerController) controller).Client.Account.BattleTag);
level.SetAccountPaidAny(true);
level.SetEmail((controller as HandlerController).Client.Account.Email).SetHeadlessAccount(false);
level.SetEmail(((HandlerController) controller).Client.Account.Email).SetHeadlessAccount(false);
AccState.SetAccountLevelInfo(level);

View File

@ -1,23 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.authentication.v1;
//Blizzless Project 2022
using bgs.protocol.challenge.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Battle;
//Blizzless Project 2022
using Google.ProtocolBuffers;
@ -53,7 +42,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//Error 35 - Battle.net service - Disabled
//Error 36 - Failed to load authentication module
//Error 37 - Authentication service is receiving too many requests.
//Error 38 - To play you need to get BattleTag
//Error 38 - To play you need to get a BattleTag
//Error 42 - You are connecting to the wrong server (Wrong sequence of actions)
//Error 43 - You blocked your account from your mobile phone.
//Error 44 - Unable to perform this action. The account is deprived of the function of voice communication.
@ -98,28 +87,28 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
}
switch (request.Locale)
{
case "deDE": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.deDE; break;
case "enGB": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.enGB; break;
case "enSG": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.enSG; break;
case "enUS": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.enUS; break;
case "esES": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.esES; break;
case "esMX": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.esMX; break;
case "frFR": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.frFR; break;
case "itIT": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.itIT; break;
case "koKR": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.koKR; break;
case "plPL": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.plPL; break;
case "ptBR": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.ptBR; break;
case "ptPT": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.ptPT; break;
case "ruRU": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.ruRU; break;
case "trTR": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.trTR; break;
case "zhCN": ((HandlerController)controller).Client.ClientLanguage = Battle.BattleClient.ClientLocale.zhCN; break;
case "deDE": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.DE_DE; break;
case "enGB": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_GB; break;
case "enSG": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_SG; break;
case "enUS": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.EN_US; break;
case "esES": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ES_ES; break;
case "esMX": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ES_MX; break;
case "frFR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.FR_FR; break;
case "itIT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.IT_IT; break;
case "koKR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.KO_KR; break;
case "plPL": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PL_PL; break;
case "ptBR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PT_BR; break;
case "ptPT": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.PT_PT; break;
case "ruRU": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.RU_RU; break;
case "trTR": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.TR_TR; break;
case "zhCN": ((HandlerController)controller).Client.ClientLanguage = BattleClient.ClientLocale.ZH_CN; break;
}
done(NoData.CreateBuilder().Build());
Logger.Info("----------------------------------------------------------------");
var builder = ChallengeExternalRequest.CreateBuilder();
var complete = LogonResult.CreateBuilder();
switch (request.Program.ToLower())
{
//case "app":
case "d3":
//if (!request.HasCachedWebCredentials)
{
@ -127,20 +116,19 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.HasCachedWebCredentials)
VerifyWebCredentials(controller, VerifyWebCredentialsRequest.CreateBuilder().SetWebCredentials(request.CachedWebCredentials).Build(), callback => { });
builder.SetPayloadType("web_auth_url");
if (REST.Config.Instance.Public)
if (REST.RestConfig.Instance.Public)
builder.SetPayload(ByteString.CopyFromUtf8(
$"http://{REST.Config.Instance.PublicIP}:{REST.Config.Instance.PORT}/battlenet/login"));
$"http://{REST.RestConfig.Instance.PublicIP}:{REST.RestConfig.Instance.Port}/battlenet/login"));
else
builder.SetPayload(ByteString.CopyFromUtf8(
$"http://{Program.RESTSERVERIP}:{REST.Config.Instance.PORT}/battlenet/login"));
$"http://{Program.RestServerIp}:{REST.RestConfig.Instance.Port}/battlenet/login"));
((HandlerController)controller).Client.MakeRPC((lid) => ChallengeListener.CreateStub(((HandlerController)controller).Client).OnExternalChallenge(controller, builder.Build(), callback => { }));
((HandlerController)controller).Client.MakeRpc((lid) => ChallengeListener.CreateStub(((HandlerController)controller).Client).OnExternalChallenge(controller, builder.Build(), callback => { }));
#endregion
}
break;
default:
Logger.Error("Authorization not implemented for Game: {0}", game);
Logger.Info("----------------------------------------------------------------");
Logger.Error("Authorization not implemented for Game: $[red]${0}$[/]$ ({1})", game, request.Program.ToLower());
break;
}
@ -170,47 +158,46 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
done(NoData.CreateBuilder().Build());
#region Authentication complete
if (request.WebCredentials.ToStringUtf8().ToLower().Contains("eu-"))
{
((HandlerController)controller).Client.Account = AccountManager.GetAccountByPersistentID(1);
// if (request.WebCredentials.ToStringUtf8().ToLower().Contains("eu-"))
// {
// ((HandlerController)controller).Client.Account = AccountManager.GetAccountByPersistentID(1);
//
// var comple = LogonResult.CreateBuilder()
// .SetAccountId(((HandlerController)controller).Client.Account.BnetEntityId)
// .SetEmail("TEST@MAIL.DU")
// .SetBattleTag("Test#0000")
// .SetSessionKey(ByteString.CopyFrom("7CB18EDA470F96A4DD70C70B9307CBBA2A4131043075648D8B2F55EE0E383132025D3CC3BA43406DC0740D776B1E5C366BD1123D16E6D6759075B475C28C4022".ToByteArray()))
// .AddAvailableRegion(1)
// .AddAvailableRegion(2)
// .AddAvailableRegion(3)
// .SetConnectedRegion(1)
// .SetGeoipCountry("RU")
// .SetRestrictedMode(false)
// .SetErrorCode(0);
// comple.AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
// ((HandlerController)controller).Client.Account.GameAccount.LoggedInClient = ((HandlerController)controller).Client;
// ((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, comple.Build(), callback => { }));
// ((HandlerController)controller).Client.Account.GameAccount.ProgramField.Value = "FEN";
// PlayerManager.PlayerConnected(((HandlerController)controller).Client);
// var ga1selected = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
// ((HandlerController)controller).Client.MakeRPC((lid) =>
// AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, ga1selected.Build(), callback => { }));
// return;
// }
var comple = LogonResult.CreateBuilder()
.SetAccountId(((HandlerController)controller).Client.Account.BnetEntityId)
.SetEmail("TEST@MAIL.DU")
.SetBattleTag("Test#0000")
.SetSessionKey(ByteString.CopyFrom("7CB18EDA470F96A4DD70C70B9307CBBA2A4131043075648D8B2F55EE0E383132025D3CC3BA43406DC0740D776B1E5C366BD1123D16E6D6759075B475C28C4022".ToByteArray()))
.AddAvailableRegion(1)
.AddAvailableRegion(2)
.AddAvailableRegion(3)
.SetConnectedRegion(1)
.SetGeoipCountry("RU")
.SetRestrictedMode(false)
.SetErrorCode(0);
comple.AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
((HandlerController)controller).Client.Account.GameAccount.LoggedInClient = ((HandlerController)controller).Client;
((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, comple.Build(), callback => { }));
((HandlerController)controller).Client.Account.GameAccount.ProgramField.Value = "FEN";
PlayerManager.PlayerConnected(((HandlerController)controller).Client);
var ga1selected = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
((HandlerController)controller).Client.MakeRPC((lid) =>
AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, ga1selected.Build(), callback => { }));
}
else
{
((HandlerController)controller).Client.Account = AccountManager.GetAccountBySaltTicket(request.WebCredentials.ToStringUtf8());
if (((HandlerController)controller).Client.Account == null)
{
var complete = LogonResult.CreateBuilder().SetErrorCode(2);
((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
((HandlerController)controller).Client.MakeRpc((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
((HandlerController)controller).Client.SocketConnection.CloseAsync();
((HandlerController)controller).Client.Connect.CloseAsync();
}
else
{
Logger.Info("Client connected - {0}#{1}", ((HandlerController)controller).Client.Account.DBAccount.BattleTagName, ((HandlerController)controller).Client.Account.HashCode);
Logger.Info("----------------------------------------------------------------");
Logger.Info(
$"Client connected - {((HandlerController)controller).Client.Account.DBAccount.BattleTagName}#{((HandlerController)controller).Client.Account.HashCode}");
var complete = LogonResult.CreateBuilder()
.SetAccountId(((HandlerController)controller).Client.Account.BnetEntityId)
.SetEmail(((HandlerController)controller).Client.Account.Email)
@ -219,17 +206,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetConnectedRegion(1)
.SetGeoipCountry("RU")
.SetRestrictedMode(false)
.SetErrorCode(0);
complete.AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId); //D3
.SetErrorCode(0)
.AddGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId); //D3
((HandlerController)controller).Client.Account.GameAccount.LoggedInClient = ((HandlerController)controller).Client;
((HandlerController)controller).Client.MakeRPC((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
((HandlerController)controller).Client.MakeRpc((lid) => AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnLogonComplete(controller, complete.Build(), callback => { }));
PlayerManager.PlayerConnected(((HandlerController)controller).Client);
var gaselected = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
((HandlerController)controller).Client.MakeRPC((lid) =>
AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, gaselected.Build(), callback => { }));
}
var selectedGameAccount = GameAccountSelectedRequest.CreateBuilder().SetResult(0).SetGameAccountId(((HandlerController)controller).Client.Account.GameAccount.BnetEntityId);
((HandlerController)controller).Client.MakeRpc((lid) =>
AuthenticationListener.CreateStub(((HandlerController)controller).Client).OnGameAccountSelected(new HandlerController() { ListenerId = lid }, selectedGameAccount.Build(), callback => { }));
}
#endregion
}

View File

@ -1,19 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.challenge.v1;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services

View File

@ -1,19 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.channel.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using System;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -25,11 +16,11 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public readonly ChannelInvitationManager _invitationManager = new ChannelInvitationManager();
public override void Subscribe(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SubscribeRequest request, Action<NoData> done)
public override void Subscribe(Google.ProtocolBuffers.IRpcController controller, SubscribeRequest request, Action<NoData> done)
{
Logger.Trace("Subscribe() {0}", ((controller as HandlerController).Client));
Logger.Trace("Subscribe() {0}", (((HandlerController) controller).Client));
this._invitationManager.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
_invitationManager.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
done(NoData.DefaultInstance);
}
@ -40,7 +31,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var response = AcceptInvitationResponse.CreateBuilder().SetObjectId(channel.DynamicId).Build();
done(response);
this._invitationManager.HandleAccept(((controller as HandlerController).Client), request);
_invitationManager.HandleAccept((((HandlerController) controller).Client), request);
}
public override void DeclineInvitation(Google.ProtocolBuffers.IRpcController controller, DeclineInvitationRequest request, Action<NoData> done)
@ -48,7 +39,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var respone = NoData.CreateBuilder();
done(respone.Build());
this._invitationManager.HandleDecline(((controller as HandlerController).Client), request);
_invitationManager.HandleDecline((((HandlerController) controller).Client), request);
}
public override void RevokeInvitation(Google.ProtocolBuffers.IRpcController controller, RevokeInvitationRequest request, Action<NoData> done)
@ -56,16 +47,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var builder = NoData.CreateBuilder();
done(builder.Build());
this._invitationManager.Revoke(((controller as HandlerController).Client), request);
_invitationManager.Revoke((((HandlerController) controller).Client), request);
}
public override void SendInvitation(Google.ProtocolBuffers.IRpcController controller, SendInvitationRequest request, Action<NoData> done)
{
var invitee = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low);
if (invitee.Owner.IgnoreIds.Contains((controller as HandlerController).Client.Account.PersistentID))
if (invitee.Owner.IgnoreIds.Contains(((HandlerController) controller).Client.Account.PersistentID))
{
((controller as HandlerController).Status) = 403;
(((HandlerController) controller).Status) = 403;
done(NoData.CreateBuilder().Build());
return;
}
@ -90,8 +81,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var invitation = Invitation.CreateBuilder();
invitation.SetId(ChannelInvitationManager.InvitationIdCounter++)
.SetInviterIdentity(Identity.CreateBuilder().SetGameAccountId((controller as HandlerController).Client.Account.GameAccount.BnetEntityId).Build())
.SetInviterName((controller as HandlerController).Client.Account.GameAccount.Owner.BattleTag)
.SetInviterIdentity(Identity.CreateBuilder().SetGameAccountId(((HandlerController) controller).Client.Account.GameAccount.BnetEntityId).Build())
.SetInviterName(((HandlerController) controller).Client.Account.GameAccount.Owner.BattleTag)
.SetInviteeIdentity(Identity.CreateBuilder().SetGameAccountId(request.TargetId).Build())
.SetInviteeName(invitee.Owner.BattleTag)
.SetInvitationMessage(request.Params.InvitationMessage)
@ -109,16 +100,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var builder = JoinNotification.CreateBuilder().SetChannelState(ChannelState.CreateBuilder().AddInvitation(invitation.Clone()));
(controller as HandlerController).Client.MakeTargetedRPC(channel, (lid) => ChannelListener.CreateStub((controller as HandlerController).Client)
((HandlerController) controller).Client.MakeTargetedRpc(channel, (lid) => ChannelListener.CreateStub(((HandlerController) controller).Client)
.OnUpdateChannelState(controller, notification.Build(), callback => { }));
(controller as HandlerController).Client.MakeTargetedRPC(channel, (lid) =>
ChannelListener.CreateStub((controller as HandlerController).Client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { }));
((HandlerController) controller).Client.MakeTargetedRpc(channel, (lid) =>
ChannelListener.CreateStub(((HandlerController) controller).Client).OnJoin(new HandlerController() { ListenerId = lid }, builder.Build(), callback => { }));
this._invitationManager.HandleInvitation((controller as HandlerController).Client, invitation.Build());
_invitationManager.HandleInvitation(((HandlerController) controller).Client, invitation.Build());
}
public override void SuggestInvitation(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SuggestInvitationRequest request, Action<NoData> done)
public override void SuggestInvitation(Google.ProtocolBuffers.IRpcController controller, SuggestInvitationRequest request, Action<NoData> done)
{
var suggester = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low);
var suggestee = GameAccountManager.GetAccountByPersistentID(request.ApprovalId.Low);
@ -126,7 +117,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (suggestee.Owner.IgnoreIds.Contains(suggester.Owner.PersistentID))
{
((controller as HandlerController).Status) = 403;
(((HandlerController) controller).Status) = 403;
done(NoData.CreateBuilder().Build());
return;
}
@ -145,7 +136,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var notification = SuggestionAddedNotification.CreateBuilder().SetSuggestion(suggestion);
suggestee.LoggedInClient.MakeTargetedRPC(this._invitationManager, (lid) =>
suggestee.LoggedInClient.MakeTargetedRpc(_invitationManager, (lid) =>
ChannelInvitationListener.CreateStub(suggestee.LoggedInClient).OnReceivedSuggestionAdded(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
}

View File

@ -1,17 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.channel.v2.membership;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
[Service(serviceID: 0x26, serviceHash: 2119327385)]
public class ChannelMembershipService_ : bgs.protocol.channel.v2.membership.ChannelMembershipService, IServerService
public class ChannelMembershipService_ : ChannelMembershipService, IServerService
{
public override void GetState(IRpcController controller, GetStateRequest request, Action<GetStateResponse> done)
{

View File

@ -1,17 +1,9 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol.channel.v1;
//Blizzless Project 2022
using bgs.protocol.channel.v1;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -21,17 +13,17 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
private static readonly Logger Logger = LogManager.CreateLogger();
public override void CreateChannel(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.CreateChannelRequest request, System.Action<bgs.protocol.channel.v1.CreateChannelResponse> done)
public override void CreateChannel(IRpcController controller, CreateChannelRequest request, Action<CreateChannelResponse> done)
{
var channel = ChannelManager.CreateNewChannel(((controller as HandlerController).Client), request.ObjectId);
var builder = bgs.protocol.channel.v1.CreateChannelResponse.CreateBuilder()
var channel = ChannelManager.CreateNewChannel((((HandlerController) controller).Client), request.ObjectId);
var builder = CreateChannelResponse.CreateBuilder()
.SetObjectId(channel.DynamicId)
.SetChannelId(channel.BnetEntityId)
;
done(builder.Build());
channel.SetOwner(((controller as HandlerController).Client));
channel.AddMember(((controller as HandlerController).Client));
channel.SetOwner((((HandlerController) controller).Client));
channel.AddMember((((HandlerController) controller).Client));
}
public override void ListChannels(IRpcController controller, ListChannelsRequest request, Action<ListChannelsResponse> done)
@ -41,17 +33,17 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
foreach (Channel channel in chatChannels)
{
if (!channel.HasUser(((controller as HandlerController).Client)) && (request.Options.HasName ? request.Options.Name == channel.Name : true) && channel.MaxMembers > channel.Members.Count)
builder.AddChannel(bgs.protocol.channel.v1.ChannelDescription.CreateBuilder().SetCurrentMembers((uint)channel.Members.Count)
if (!channel.HasUser((((HandlerController) controller).Client)) && (request.Options.HasName ? request.Options.Name == channel.Name : true) && channel.MaxMembers > channel.Members.Count)
builder.AddChannel(ChannelDescription.CreateBuilder().SetCurrentMembers((uint)channel.Members.Count)
.SetChannelId(bgs.protocol.EntityId.CreateBuilder().SetHigh(channel.BnetEntityId.High).SetLow(channel.BnetEntityId.Low))
.SetState(channel.State));
}
done(builder.Build());
}
public override void GetChannelInfo(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.GetChannelInfoRequest request, System.Action<bgs.protocol.channel.v1.GetChannelInfoResponse> done)
public override void GetChannelInfo(IRpcController controller, GetChannelInfoRequest request, Action<GetChannelInfoResponse> done)
{
var builder = bgs.protocol.channel.v1.GetChannelInfoResponse.CreateBuilder();
var builder = GetChannelInfoResponse.CreateBuilder();
var channel = ChannelManager.GetChannelByEntityId(request.ChannelId);
if (channel != null)
@ -62,30 +54,30 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
done(builder.Build());
}
public override void JoinChannel(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.JoinChannelRequest request, System.Action<bgs.protocol.channel.v1.JoinChannelResponse> done)
public override void JoinChannel(IRpcController controller, JoinChannelRequest request, Action<JoinChannelResponse> done)
{
var channel = ChannelManager.GetChannelByEntityId(request.ChannelId);
channel.Join(((controller as HandlerController).Client), request.ObjectId);
var builder = bgs.protocol.channel.v1.JoinChannelResponse.CreateBuilder().SetObjectId(channel.DynamicId).SetMemberId((controller as HandlerController).Client.Account.BnetEntityId);
channel.Join((((HandlerController) controller).Client), request.ObjectId);
var builder = JoinChannelResponse.CreateBuilder().SetObjectId(channel.DynamicId).SetMemberId(((HandlerController) controller).Client.Account.BnetEntityId);
((controller as HandlerController).Client).ChatChannels.Add(channel);
(((HandlerController) controller).Client).ChatChannels.Add(channel);
done(builder.Build());
}
public override void SubscribeChannel(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SubscribeChannelRequest request, Action<bgs.protocol.channel.v1.SubscribeChannelResponse> done)
public override void SubscribeChannel(IRpcController controller, SubscribeChannelRequest request, Action<SubscribeChannelResponse> done)
{
var channel = ChannelManager.GetChannelByEntityId(request.ChannelId);
var builder = bgs.protocol.channel.v1.SubscribeChannelResponse.CreateBuilder();
var builder = SubscribeChannelResponse.CreateBuilder();
builder.SetObjectId(channel.DynamicId);
done(builder.Build());
((controller as HandlerController).Client).ChatChannels.Add(channel);
channel.Join(((controller as HandlerController).Client), request.ObjectId);
(((HandlerController) controller).Client).ChatChannels.Add(channel);
channel.Join((((HandlerController) controller).Client), request.ObjectId);
}
}

View File

@ -1,29 +1,16 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.GameServer.CommandManager;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ChannelSystem;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -34,15 +21,15 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private static readonly Logger Logger = LogManager.CreateLogger();
public override void Dissolve(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.DissolveRequest request, System.Action<bgs.protocol.NoData> done)
public override void Dissolve(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.DissolveRequest request, Action<bgs.protocol.NoData> done)
{
throw new NotImplementedException();
}
public override void RemoveMember(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.RemoveMemberRequest request, System.Action<bgs.protocol.NoData> done)
public override void RemoveMember(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.RemoveMemberRequest request, Action<bgs.protocol.NoData> done)
{
Logger.Trace("RemoveMember()");
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId);
Logger.MethodTrace("");
var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.MemberId.Low);
var builder = bgs.protocol.NoData.CreateBuilder();
@ -51,17 +38,17 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
channel.RemoveMember(gameAccount.LoggedInClient, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)request.Reason));
if (request.Reason == 0)
{
ulong invId = ChannelInvitationManager.FindInvAsForClient((controller as HandlerController).Client);
if (invId != System.UInt64.MaxValue)
ChannelInvitationManager.AltConnectToJoin((controller as HandlerController).Client, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build());
//ServicesSystem.Services.ChannelInvitationService.CreateStub((controller as HandlerController).Client).AcceptInvitation(controller, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build(), callback => { });
ulong invId = ChannelInvitationManager.FindInvAsForClient(((HandlerController) controller).Client);
if (invId != UInt64.MaxValue)
ChannelInvitationManager.AltConnectToJoin(((HandlerController) controller).Client, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build());
//ServicesSystem.Services.ChannelInvitationService.CreateStub(((HandlerController) controller).Client).AcceptInvitation(controller, bgs.protocol.channel.v1.AcceptInvitationRequest.CreateBuilder().SetInvitationId(invId).SetObjectId(0).Build(), callback => { });
}
}
public override void SendMessage(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SendMessageRequest request, System.Action<bgs.protocol.NoData> done)
public override void SendMessage(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.SendMessageRequest request, Action<bgs.protocol.NoData> done)
{
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId);
//Logger.Trace("{0} sent a message to channel {1}.", ((controller as HandlerController).Client).Account.GameAccount.CurrentToon, channel);
var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
//Logger.Trace("{0} sent a message to channel {1}.", (((HandlerController) controller).Client).Account.GameAccount.CurrentToon, channel);
var builder = bgs.protocol.NoData.CreateBuilder();
done(builder.Build());
@ -72,13 +59,13 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.Message.AttributeCount == 0 || !request.Message.AttributeList.First().HasValue)
return; // check if it has attributes.
var parsedAsCommand = CommandManager.TryParse(request.Message.AttributeList[0].Value.StringValue, ((controller as HandlerController).Client)); // try parsing the message as a command
var parsedAsCommand = CommandManager.TryParse(request.Message.AttributeList[0].Value.StringValue, (((HandlerController) controller).Client)); // try parsing the message as a command
if (!parsedAsCommand)
channel.SendMessage(((controller as HandlerController).Client), request.Message); // if it's not parsed as an command - let channel itself to broadcast message to it's members.
channel.SendMessage((((HandlerController) controller).Client), request.Message); // if it's not parsed as an command - let channel itself to broadcast message to it's members.
}
public override void UpdateChannelState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateChannelStateRequest request, System.Action<bgs.protocol.NoData> done)
public override void UpdateChannelState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateChannelStateRequest request, Action<bgs.protocol.NoData> done)
{
/*
if (this._loggedInClient.CurrentChannel != channel)
@ -88,9 +75,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
ServicesSystem.Services.ChannelInvitationService.CreateStub(this.LoggedInClient).AcceptInvitation(null, request.Build(), callback => { });
}
//*/
Channel channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId);
Channel channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
Logger.Trace("UpdateChannelState(): {0}", request.ToString());
Logger.Debug($"Agent ID: {(request.HasAgentId ? request.AgentId.ToString() : "N/A")}, gas state change: {(request.HasStateChange ? request.StateChange.ToString() : "N/A")}");
foreach (bgs.protocol.Attribute attribute in request.StateChange.AttributeList)
{
@ -99,9 +86,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (attribute.HasValue && !attribute.Value.MessageValue.IsEmpty) //Sometimes not present -Egris
{
var gameCreateParams = D3.OnlineService.GameCreateParams.ParseFrom(attribute.Value.MessageValue);
Logger.Trace("D3.Party.GameCreateParams: {0}", gameCreateParams.ToString());
Logger.Debug("$[underline]$D3.Party.GameCreateParams:$[/]$ {0}", gameCreateParams.ToString());
//D3.OnlineService.EntityId hero = gameCreateParams.Coop.ResumeFromSaveHeroId;
bool clear_quests = ((controller as HandlerController).Client.GameChannel != null && gameCreateParams.CampaignOrAdventureMode.QuestStepId == -1 &&
bool clear_quests = (((HandlerController) controller).Client.GameChannel != null && gameCreateParams.CampaignOrAdventureMode.QuestStepId == -1 &&
(gameCreateParams.CampaignOrAdventureMode.SnoQuest == 87700 ||
gameCreateParams.CampaignOrAdventureMode.SnoQuest == 80322 ||
gameCreateParams.CampaignOrAdventureMode.SnoQuest == 93595 ||
@ -110,9 +97,9 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var paramsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder(gameCreateParams);
var Mode = D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder(gameCreateParams.CampaignOrAdventureMode);
lock ((controller as HandlerController).Client.Account.GameAccount.CurrentToon.DBToon)
lock (((HandlerController) controller).Client.Account.GameAccount.CurrentToon.DBToon)
{
DBToon toonByClient = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon;
DBToon toonByClient = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
if(toonByClient.CurrentAct == 400)
toonByClient.CurrentAct = gameCreateParams.CampaignOrAdventureMode.Act;
if (!clear_quests)
@ -141,7 +128,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//paramsBuilder.ClearCoop();
//paramsBuilder.SetPvp(D3.OnlineService.PvPCreateParams.CreateBuilder().SetSnoWorld(79100));
/*var toon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon;
/*var toon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
paramsBuilder.SetCoop(D3.OnlineService.CoopCreateParams.CreateBuilder()
.SetDifficultyLevel(toon.CurrentDifficulty)
.SetAct(toon.CurrentAct)
@ -164,8 +151,8 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
else
{
var gameCreateParamsBuilder = D3.OnlineService.GameCreateParams.CreateBuilder();
var toon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon;
var dbToon = ((controller as HandlerController).Client).Account.GameAccount.CurrentToon.DBToon;
var toon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon;
var dbToon = (((HandlerController) controller).Client).Account.GameAccount.CurrentToon.DBToon;
gameCreateParamsBuilder.SetGameType(1);
gameCreateParamsBuilder.SetCreationFlags(0);
gameCreateParamsBuilder.SetCampaignOrAdventureMode(D3.OnlineService.CampaignOrAdventureModeCreateParams.CreateBuilder()
@ -189,7 +176,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
// TODO: Find a game that fits the clients params and join /raist.
var publicGameParams = D3.PartyMessage.SearchForPublicGameParams.ParseFrom(attribute.Value.MessageValue);
Logger.Trace("SearchForPublicGameParams: {0}", publicGameParams.ToString());
Logger.Debug("$[underline]$SearchForPublicGameParams:$[/]$ {0}", publicGameParams.ToString());
var attr = bgs.protocol.Attribute.CreateBuilder()
.SetName("D3.Party.SearchForPublicGame.Params")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(publicGameParams.ToByteString()).Build());
@ -205,12 +192,12 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder());
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.ScreenStatus = null");
Logger.Debug("$[underline]$D3.Party.ScreenStatus$[/]$ is null");
}
else
{
var oldScreen = D3.PartyMessage.ScreenStatus.ParseFrom(attribute.Value.MessageValue);
((controller as HandlerController).Client).Account.GameAccount.ScreenStatus = oldScreen;
(((HandlerController) controller).Client).Account.GameAccount.ScreenStatus = oldScreen;
// TODO: save screen status for use with friends -Egris
var attr = bgs.protocol.Attribute.CreateBuilder()
@ -218,7 +205,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(oldScreen.ToByteString()));
channel.AddAttribute(attr.Build());
Logger.Trace("Client moving to Screen: {0}, with Status: {1}", oldScreen.Screen, oldScreen.Status);
Logger.Debug("Client moving to Screen: {0}, with Status: {1}", oldScreen.Screen, oldScreen.Status);
}
}
else if (attribute.Name == "D3.Party.JoinPermissionPreviousToLock")
@ -232,7 +219,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(joinPermission);
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.JoinPermissionPreviousToLock = {0}", joinPermission.IntValue);
Logger.Debug("$[underline]$D3.Party.JoinPermissionPreviousToLock$[/]$ = {0}", joinPermission.IntValue);
}
else if (attribute.Name == "D3.Party.JoinPermissionPreviousToClose")
{
@ -245,7 +232,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(joinPermission);
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.JoinPermissionPreviousToClose = {0}", joinPermission.IntValue);
Logger.Debug("$[underline]$D3.Party.JoinPermissionPreviousToClose$[/]$ = {0}", joinPermission.IntValue);
}
else if (attribute.Name == "D3.Party.LockReasons")
{
@ -258,7 +245,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(lockReason);
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.LockReasons = {0}", lockReason.IntValue);
Logger.Debug("$[underline]$D3.Party.LockReasons$[/]$ = {0}", lockReason.IntValue);
}
else if (attribute.Name == "D3.Party.GameId")
{
@ -270,10 +257,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(gameId.ToByteString()).Build());
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.GameId = {0}", gameId.GameInstanceId);
Logger.Debug("$[underline]$D3.Party.GameId$[/]$ = {0}", gameId.GameInstanceId);
}
else
Logger.Trace("D3.Party.GameId = null");
Logger.Debug("$[underline]$D3.Party.GameId$[/]$ is null");
}
else if (attribute.Name == "D3.Party.EnterGame.Members")
@ -286,10 +273,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(members.ToByteString()).Build());
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.EnterGame.Members = {0}", members.ToString());
Logger.Debug("$[underline]$D3.Party.EnterGame.Members$[/]$ = {0}", members.ToString());
}
else
Logger.Trace("D3.Party.EnterGame.Members = null");
Logger.Debug("$[underline]$D3.Party.EnterGame.Members$[/]$ is null");
}
else if (attribute.Name == "D3.Party.JoinPermission")
@ -302,10 +289,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(permission.ToByteString()).Build());
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.JoinPermission = {0}", permission.ToString());
Logger.Debug("$[underline]$D3.Party.JoinPermission$[/]$ = {0}", permission.ToString());
}
else
Logger.Trace("D3.Party.JoinPermission = null");
Logger.Debug("$[underline]$D3.Party.JoinPermission$[/]$ is null");
}
else if (attribute.Name == "D3.Party.EnterGame.Leader.AtQueueStart")
@ -318,15 +305,15 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(queueStart.ToByteString()).Build());
channel.AddAttribute(attr.Build());
Logger.Trace("D3.Party.EnterGame.Leader.AtQueueStart = {0}", queueStart.ToString());
Logger.Debug("$[underline]$D3.Party.EnterGame.Leader.AtQueueStart$[/]$ = {0}", queueStart.ToString());
}
else
Logger.Trace("D3.Party.EnterGame.Leader.AtQueueStart = null");
Logger.Debug("$[underline]$D3.Party.EnterGame.Leader.AtQueueStart$[/]$ = null");
}
else
{
Logger.Warn("UpdateChannelState(): Unknown attribute: {0}", attribute.Name);
Logger.MethodTrace($"Unknown attribute: {attribute.Name}");
}
}
@ -337,13 +324,13 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
done(builder.Build());
var notification = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder()
.SetAgentId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId)
.SetAgentId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
/*
.SetChannelId(bgs.protocol.channel.v1.ChannelId.CreateBuilder().SetId((uint)channel.BnetEntityId.Low))
.SetSubscriber(bgs.protocol.account.v1.Identity.CreateBuilder()
.SetAccount(bgs.protocol.account.v1.AccountId.CreateBuilder().SetId((uint)((controller as HandlerController).Client).Account.BnetEntityId.Low))
.SetAccount(bgs.protocol.account.v1.AccountId.CreateBuilder().SetId((uint)(((HandlerController) controller).Client).Account.BnetEntityId.Low))
.SetGameAccount(bgs.protocol.account.v1.GameAccountHandle.CreateBuilder()
.SetId((uint)((controller as HandlerController).Client).Account.GameAccount.BnetEntityId.Low)
.SetId((uint)(((HandlerController) controller).Client).Account.GameAccount.BnetEntityId.Low)
.SetProgram(17459)
.SetRegion(1))
.SetProcess(bgs.protocol.ProcessId.CreateBuilder().SetLabel(0).SetEpoch(DateTime.Today.ToUnixTime())))
@ -353,18 +340,18 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var altnotif = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channel.State).Build();
var client = (controller as HandlerController).Client;
var client = ((HandlerController) controller).Client;
//Notify all Channel members
foreach (var member in channel.Members.Keys)
{
member.MakeTargetedRPC(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
member.MakeTargetedRpc(channel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
}
}
public override void UpdateMemberState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateMemberStateRequest request, System.Action<bgs.protocol.NoData> done)
public override void UpdateMemberState(Google.ProtocolBuffers.IRpcController controller, bgs.protocol.channel.v1.UpdateMemberStateRequest request, Action<bgs.protocol.NoData> done)
{
var channel = ChannelManager.GetChannelByDynamicId(((controller as HandlerController).LastCallHeader).ObjectId);
var channel = ChannelManager.GetChannelByDynamicId((((HandlerController) controller).LastCallHeader).ObjectId);
var builder = bgs.protocol.NoData.CreateBuilder();
done(builder.Build());
@ -380,12 +367,12 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetName("D3.PartyMember.GameId")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetMessageValue(gameId.ToByteString()).Build());
state.AddAttribute(attr);
Logger.Trace("D3.PartyMember.GameId = {0}", gameId.GameInstanceId);
Logger.Debug("$[underline]$D3.PartyMember.GameId$[/]$ = {0}", gameId.GameInstanceId);
}
else
{
Logger.Trace("D3.PartyMember.GameId = null");
channel.RemoveMember((controller as HandlerController).Client, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)2));
Logger.Debug("$[underline]$D3.PartyMember.GameId$[/]$ is null");
channel.RemoveMember(((HandlerController) controller).Client, Channel.GetRemoveReasonForRequest((Channel.RemoveRequestReason)2));
}
}
@ -397,7 +384,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
channelMember.SetState(state);
var notification = bgs.protocol.channel.v1.UpdateMemberStateNotification.CreateBuilder()
.SetAgentId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId)
.SetAgentId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
.AddStateChange(channelMember)
.Build();
@ -413,7 +400,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
//Notify all Channel members
foreach (var member in channel.Members.Keys)
{
member.MakeTargetedRPC(channel, (lid) =>
member.MakeTargetedRpc(channel, (lid) =>
bgs.protocol.channel.v1.ChannelListener.CreateStub(member).OnUpdateMemberState(new HandlerController() { ListenerId = lid }, notification, callback => { }));
}
//*/

View File

@ -1,25 +1,16 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
using System;
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.authentication.v1;
//Blizzless Project 2022
using bgs.protocol.connection.v1;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
[Service(serviceID: 0x0, serviceHash: 1698982289)]
public class ConnectionSerivce : ConnectionService, IServerService
public class ConnectionSvc : ConnectionService, IServerService
{
private static readonly Logger Logger = LogManager.CreateLogger();
public override void Bind(IRpcController controller, BindRequest request, Action<BindResponse> done)
@ -36,31 +27,29 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (request.HasUseBindlessRpc)
builder.SetUseBindlessRpc(true);
(controller as HandlerController).Client.Services.Add(0x54DFDA17, 0x01);
(controller as HandlerController).Client.Services.Add(0xD4DCD093, 0x02);
(controller as HandlerController).Client.Services.Add(0x71240E35, 0x03);
(controller as HandlerController).Client.Services.Add(0xBBDA171F, 0x04);
(controller as HandlerController).Client.Services.Add(0xF084FC20, 0x05);
(controller as HandlerController).Client.Services.Add(0xBF8C8094, 0x06);
(controller as HandlerController).Client.Services.Add(0x166FE4A1, 0x07);
(controller as HandlerController).Client.Services.Add(0xB96F5297, 0x08);
(controller as HandlerController).Client.Services.Add(0x6F259A13, 0x09);
(controller as HandlerController).Client.Services.Add(0xE1CB2EA8, 0x0A);
(controller as HandlerController).Client.Services.Add(0xBC872C22, 0x0B);
(controller as HandlerController).Client.Services.Add(0x7FE36B32, 0x0C);
(controller as HandlerController).Client.Services.Add(233634817, 0x0D);
(controller as HandlerController).Client.Services.Add(0x62DA0891, 0x0E); //AccountService
(controller as HandlerController).Client.Services.Add(510168069, 0x0F);
(controller as HandlerController).Client.Services.Add(0x45E59C4D, 0x10);
(controller as HandlerController).Client.Services.Add(0x135185EF, 0x11);
(controller as HandlerController).Client.Services.Add(1910276758, 0x51);
//(controller as HandlerController).Client.Services.Add(2495170438, 0x25);
(controller as HandlerController).Client.Services.Add(2119327385, 0x26);
((HandlerController) controller).Client.Services.Add(0x54DFDA17, 0x01);
((HandlerController) controller).Client.Services.Add(0xD4DCD093, 0x02);
((HandlerController) controller).Client.Services.Add(0x71240E35, 0x03);
((HandlerController) controller).Client.Services.Add(0xBBDA171F, 0x04);
((HandlerController) controller).Client.Services.Add(0xF084FC20, 0x05);
((HandlerController) controller).Client.Services.Add(0xBF8C8094, 0x06);
((HandlerController) controller).Client.Services.Add(0x166FE4A1, 0x07);
((HandlerController) controller).Client.Services.Add(0xB96F5297, 0x08);
((HandlerController) controller).Client.Services.Add(0x6F259A13, 0x09);
((HandlerController) controller).Client.Services.Add(0xE1CB2EA8, 0x0A);
((HandlerController) controller).Client.Services.Add(0xBC872C22, 0x0B);
((HandlerController) controller).Client.Services.Add(0x7FE36B32, 0x0C);
((HandlerController) controller).Client.Services.Add(233634817, 0x0D);
((HandlerController) controller).Client.Services.Add(0x62DA0891, 0x0E); //AccountService
((HandlerController) controller).Client.Services.Add(510168069, 0x0F);
((HandlerController) controller).Client.Services.Add(0x45E59C4D, 0x10);
((HandlerController) controller).Client.Services.Add(0x135185EF, 0x11);
((HandlerController) controller).Client.Services.Add(1910276758, 0x51);
//((HandlerController) controller).Client.Services.Add(2495170438, 0x25);
((HandlerController) controller).Client.Services.Add(2119327385, 0x26);
done(builder.Build());
Logger.Info("Connect with BlizzLess.Net established. Client - {0}", (controller as HandlerController).Client.SocketConnection.RemoteAddress);
Logger.Info("Connect with Blizzless established. Client - {0}", ((HandlerController) controller).Client.SocketConnection.RemoteAddress);
}
public override void Echo(IRpcController controller, EchoRequest request, Action<EchoResponse> done)
@ -84,22 +73,22 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void RequestDisconnect(IRpcController controller, DisconnectRequest request, Action<NO_RESPONSE> done)
{
Console.WriteLine("Клиент - {0} , отключен", (controller as HandlerController).Client.SocketConnection.RemoteAddress);
this.DisconnectClient(controller as HandlerController);
if ((controller as HandlerController).Client.Account != null)
(controller as HandlerController).Client.Account.GameAccount.Logined = false;
((controller as HandlerController).Client).Connect.CloseAsync();
(controller as HandlerController).Client.SocketConnection.CloseAsync();
Logger.Info("Client - {0} , disconnected", ((HandlerController) controller).Client.SocketConnection.RemoteAddress);
DisconnectClient((HandlerController) controller);
if (((HandlerController) controller).Client.Account != null)
((HandlerController) controller).Client.Account.GameAccount.IsLoggedIn = false;
(((HandlerController) controller).Client).Connect.CloseAsync();
((HandlerController) controller).Client.SocketConnection.CloseAsync();
/*
if ((controller as HandlerController).Client.Account != null)
if (((HandlerController) controller).Client.Account != null)
{
(controller as HandlerController).Client.Account.CurrentGameAccount.Logined = false;
AccountManager.SaveToDB((controller as HandlerController).Client.Account);
if ((controller as HandlerController).Client.Account.CurrentGameAccount != null)
((HandlerController) controller).Client.Account.CurrentGameAccount.Logined = false;
AccountManager.SaveToDB(((HandlerController) controller).Client.Account);
if (((HandlerController) controller).Client.Account.CurrentGameAccount != null)
{
GameAccountManager.SaveToDB((controller as HandlerController).Client.Account.CurrentGameAccount);
(controller as HandlerController).Client.SocketConnection.CloseAsync();
(controller as HandlerController).Client.Connect.CloseAsync();
GameAccountManager.SaveToDB(((HandlerController) controller).Client.Account.CurrentGameAccount);
((HandlerController) controller).Client.SocketConnection.CloseAsync();
((HandlerController) controller).Client.Connect.CloseAsync();
}
}
//*/
@ -108,7 +97,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
private void DisconnectClient(HandlerController controller)
{
if (controller.Client.Account != null && controller.Client.Account.GameAccount != null) controller.Client.Account.GameAccount.LoggedInClient = null;
LoginServer.Battle.PlayerManager.PlayerDisconnected(controller.Client);
Battle.PlayerManager.PlayerDisconnected(controller.Client);
}
}
}

View File

@ -1,25 +1,15 @@
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.friends.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.FriendsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
@ -30,10 +20,10 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done)
{
Logger.Trace("Subscribe() {0}", ((controller as HandlerController).Client));
Logger.Trace("Subscribe() {0}", (((HandlerController) controller).Client));
FriendManager.Instance.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
FriendManager.Instance.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
var builder = SubscribeResponse.CreateBuilder()
.SetMaxFriends(127)
@ -42,7 +32,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.AddRole(Role.CreateBuilder().SetId(1).SetName("battle_tag_friend").Build())
.AddRole(Role.CreateBuilder().SetId(2).SetName("real_id_friend").Build());
var friendsIDs = ((controller as HandlerController).Client).Account.FriendsIds;
var friendsIDs = (((HandlerController) controller).Client).Account.FriendsIds;
foreach (var dbidFriend in friendsIDs) // send friends list.
{
var resp = Friend.CreateBuilder()
@ -57,7 +47,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
foreach (var invitation in FriendManager.OnGoingInvitations.Values)
{
if (invitation.InviteeIdentity.AccountId == ((controller as HandlerController).Client).Account.BnetEntityId && !friendsIDs.Contains(invitation.InviterIdentity.AccountId.Low))
if (invitation.InviteeIdentity.AccountId == (((HandlerController) controller).Client).Account.BnetEntityId && !friendsIDs.Contains(invitation.InviterIdentity.AccountId.Low))
{
invitations.Add(invitation);
}
@ -75,16 +65,16 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
var response = NoData.CreateBuilder();
if (friendRequest.TargetEmail.ToLower() == ((controller as HandlerController).Client).Account.Email.ToLower())
if (friendRequest.TargetEmail.ToLower() == (((HandlerController) controller).Client).Account.Email.ToLower())
{
((controller as HandlerController).Status) = 317202;
(((HandlerController) controller).Status) = 317202;
done(response.Build());
return;
}
if (friendRequest.TargetBattleTag == ((controller as HandlerController).Client).Account.BattleTag)
if (friendRequest.TargetBattleTag == (((HandlerController) controller).Client).Account.BattleTag)
{
((controller as HandlerController).Status) = 317202;
(((HandlerController) controller).Status) = 317202;
done(response.Build());
return;
}
@ -101,44 +91,44 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
if (invitee == null)
{
if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 4;
(((HandlerController) controller).Status) = 4;
else
((controller as HandlerController).Status) = 317203;
(((HandlerController) controller).Status) = 317203;
done(response.Build());
return;
}
else if (FriendManager.AreFriends(((controller as HandlerController).Client).Account, invitee))
else if (FriendManager.AreFriends((((HandlerController) controller).Client).Account, invitee))
{
if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 317201;
(((HandlerController) controller).Status) = 317201;
else
((controller as HandlerController).Status) = 5003;
(((HandlerController) controller).Status) = 5003;
done(response.Build());
return;
}
else if (FriendManager.InvitationExists(((controller as HandlerController).Client).Account, invitee))
else if (FriendManager.InvitationExists((((HandlerController) controller).Client).Account, invitee))
{
if (friendRequest.HasTargetEmail)
((controller as HandlerController).Status) = 317200;
(((HandlerController) controller).Status) = 317200;
else
((controller as HandlerController).Status) = 5005;
(((HandlerController) controller).Status) = 5005;
done(response.Build());
return;
}
else if (invitee.IgnoreIds.Contains((controller as HandlerController).Client.Account.PersistentID))
else if (invitee.IgnoreIds.Contains(((HandlerController) controller).Client.Account.PersistentID))
{
((controller as HandlerController).Status) = 5006;
(((HandlerController) controller).Status) = 5006;
done(response.Build());
return;
}
Logger.Trace("{0} sent {1} friend invitation.", ((controller as HandlerController).Client).Account, invitee);
Logger.Trace("{0} sent {1} friend invitation.", (((HandlerController) controller).Client).Account, invitee);
var invitation = ReceivedInvitation.CreateBuilder()
.SetId(FriendManager.InvitationIdCounter++) // we may actually need to store invitation ids in database with the actual invitation there. /raist.
.SetInviterIdentity(Identity.CreateBuilder().SetAccountId(((controller as HandlerController).Client).Account.BnetEntityId))
.SetInviterIdentity(Identity.CreateBuilder().SetAccountId((((HandlerController) controller).Client).Account.BnetEntityId))
.SetInviteeIdentity(Identity.CreateBuilder().SetAccountId(invitee.BnetEntityId))
.SetInviterName(((controller as HandlerController).Client).Account.BattleTagName)
.SetInviterName((((HandlerController) controller).Client).Account.BattleTagName)
.SetInviteeName(invitee.BattleTagName)
.SetCreationTime(DateTime.Now.ToUnixTime())
.SetUnknownFields(UnknownFieldSet.CreateBuilder()
@ -149,59 +139,59 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
done(response.Build());
// notify the invitee on invitation.
FriendManager.HandleInvitation(((controller as HandlerController).Client), invitation.Build());
FriendManager.HandleInvitation((((HandlerController) controller).Client), invitation.Build());
FriendManager.Instance.NotifyUpdate();
(controller as HandlerController).Client.Account.NotifyUpdate();
(controller as HandlerController).Client.Account.GameAccount.NotifyUpdate();
((HandlerController) controller).Client.Account.NotifyUpdate();
((HandlerController) controller).Client.Account.GameAccount.NotifyUpdate();
}
public override void AcceptInvitation(IRpcController controller, AcceptInvitationRequest request, Action<bgs.protocol.NoData> done)
public override void AcceptInvitation(IRpcController controller, AcceptInvitationRequest request, Action<NoData> done)
{
Logger.Trace("{0} accepted friend invitation.", ((controller as HandlerController).Client).Account);
Logger.Trace("{0} accepted friend invitation.", (((HandlerController) controller).Client).Account);
var response = bgs.protocol.NoData.CreateBuilder();
var response = NoData.CreateBuilder();
done(response.Build());
FriendManager.HandleAccept(((controller as HandlerController).Client), request);
FriendManager.HandleAccept((((HandlerController) controller).Client), request);
}
public override void RevokeInvitation(IRpcController controller, RevokeInvitationRequest request, Action<bgs.protocol.NoData> done)
public override void RevokeInvitation(IRpcController controller, RevokeInvitationRequest request, Action<NoData> done)
{
throw new NotImplementedException();
}
public override void DeclineInvitation(IRpcController controller, DeclineInvitationRequest request, Action<bgs.protocol.NoData> done)
public override void DeclineInvitation(IRpcController controller, DeclineInvitationRequest request, Action<NoData> done)
{
Logger.Trace("{0} declined friend invitation.", ((controller as HandlerController).Client).Account);
Logger.Trace("{0} declined friend invitation.", (((HandlerController) controller).Client).Account);
var response = bgs.protocol.NoData.CreateBuilder();
var response = NoData.CreateBuilder();
done(response.Build());
FriendManager.HandleDecline(((controller as HandlerController).Client), request);
FriendManager.HandleDecline((((HandlerController) controller).Client), request);
}
public override void IgnoreInvitation(IRpcController controller, IgnoreInvitationRequest request, Action<bgs.protocol.NoData> done)
public override void IgnoreInvitation(IRpcController controller, IgnoreInvitationRequest request, Action<NoData> done)
{
//throw new NotImplementedException();
var response = bgs.protocol.NoData.CreateBuilder();
var response = NoData.CreateBuilder();
done(response.Build());
FriendManager.HandleIgnore(((controller as HandlerController).Client), request);
FriendManager.HandleIgnore((((HandlerController) controller).Client), request);
}
public override void RemoveFriend(IRpcController controller, RemoveFriendRequest request, Action<NoData> done)
{
Logger.Trace("{0} removed friend with id {1}.", ((controller as HandlerController).Client).Account, request.TargetId);
Logger.Trace("{0} removed friend with id {1}.", (((HandlerController) controller).Client).Account, request.TargetId);
done(NoData.DefaultInstance);
FriendManager.HandleRemove(((controller as HandlerController).Client), request);
FriendManager.HandleRemove((((HandlerController) controller).Client), request);
FriendManager.Instance.NotifyUpdate();
(controller as HandlerController).Client.Account.NotifyUpdate();
(controller as HandlerController).Client.Account.GameAccount.NotifyUpdate();
((HandlerController) controller).Client.Account.NotifyUpdate();
((HandlerController) controller).Client.Account.GameAccount.NotifyUpdate();
}
public override void ViewFriends(IRpcController controller, ViewFriendsRequest request, Action<ViewFriendsResponse> done)
{
Logger.Trace("ViewFriends(): {0}.", request.ToString());
Logger.MethodTrace(request.ToString());
var builder = ViewFriendsResponse.CreateBuilder();
var friendsIDs = AccountManager.GetAccountByPersistentID(request.TargetId.Low).FriendsIds;
@ -220,7 +210,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
}
public override void UpdateFriendState(IRpcController controller, UpdateFriendStateRequest request, Action<NoData> done)
{
Logger.Trace("UpdateFriendState(): {0}.", request.ToString());
Logger.MethodTrace(request.ToString());
done(NoData.CreateBuilder().Build());
}

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.games.v1;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services

View File

@ -1,23 +1,12 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.matchmaking.v1;
//Blizzless Project 2022
using D3.OnlineService;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.GamesSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -36,79 +25,79 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
}
public override void QueueMatchmaking(IRpcController controller, QueueMatchmakingRequest request, Action<QueueMatchmakingResponse> done)
{
#region Инициализация игры
#region Game initialization
var id = RequestId.CreateBuilder().SetId(Counter); Counter++;
done(QueueMatchmakingResponse.CreateBuilder().SetRequestId(id).Build());
#endregion
string request_type = "";
string ServerPool = "";
bgs.protocol.v2.Attribute AttributeOfServer = null;
string requestType = "";
string serverPool = "";
bgs.protocol.v2.Attribute attributeOfServer = null;
GameCreateParams gameCreateParams = null;
int Difficulty = 0;
int CurrentAct = 0;
int CurrentQuest = 0;
int CurrentStep = 0;
int difficulty = 0;
int currentAct = 0;
int currentQuest = 0;
int currentStep = 0;
foreach (var attr in request.Options.CreationProperties.AttributeList)
{
switch (attr.Name)
{
case "GameCreateParams":
gameCreateParams = GameCreateParams.ParseFrom(attr.Value.BlobValue);
AttributeOfServer = attr;
attributeOfServer = attr;
break;
case "ServerPool":
ServerPool = attr.Value.StringValue;
serverPool = attr.Value.StringValue;
break;
case "request_type":
request_type = attr.Value.StringValue;
requestType = attr.Value.StringValue;
break;
}
}
Difficulty = gameCreateParams.CampaignOrAdventureMode.HandicapLevel;
CurrentAct = gameCreateParams.CampaignOrAdventureMode.Act;
CurrentQuest = gameCreateParams.CampaignOrAdventureMode.SnoQuest;
CurrentStep = gameCreateParams.CampaignOrAdventureMode.QuestStepId;
difficulty = gameCreateParams.CampaignOrAdventureMode.HandicapLevel;
currentAct = gameCreateParams.CampaignOrAdventureMode.Act;
currentQuest = gameCreateParams.CampaignOrAdventureMode.SnoQuest;
currentStep = gameCreateParams.CampaignOrAdventureMode.QuestStepId;
#region Ставим в очередь
#region Put in queue
QueueWaitTimes.Builder timers = QueueWaitTimes.CreateBuilder();
timers.SetMinWait(0).SetMaxWait(120).SetAvgWait(60).SetStdDevWait(0);
var member = bgs.protocol.account.v1.GameAccountHandle.CreateBuilder();
member.SetId((uint)(controller as HandlerController).Client.Account.GameAccount.BnetEntityId.Low).SetProgram(0x00004433).SetRegion(1);
member.SetId((uint)((HandlerController) controller).Client.Account.GameAccount.BnetEntityId.Low).SetProgram(0x00004433).SetRegion(1);
QueueEntryNotification.Builder qen = QueueEntryNotification.CreateBuilder();
qen.SetRequestId(id).SetWaitTimes(timers).AddMember(member).SetRequestInitiator(member);
(controller as HandlerController).Client.MakeRPC((lid) => GameRequestListener.CreateStub((controller as HandlerController).Client).OnQueueEntry(new HandlerController() { ListenerId = lid }, qen.Build(), callback => { }));
((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueEntry(new HandlerController() { ListenerId = lid }, qen.Build(), callback => { }));
#endregion
#region Обновление очереди
#region Update Queue
QueueUpdateNotification.Builder qun = QueueUpdateNotification.CreateBuilder();
qun.SetRequestId(id)
.SetWaitTimes(timers)
.SetIsMatchmaking(true);
(controller as HandlerController).Client.MakeRPC((lid) => GameRequestListener.CreateStub((controller as HandlerController).Client).OnQueueUpdate(new HandlerController() { ListenerId = lid }, qun.Build(), callback => { }));
((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnQueueUpdate(new HandlerController() { ListenerId = lid }, qun.Build(), callback => { }));
#endregion
string GAME_SERVER_IP = Program.GAMESERVERIP;
string gameServerIp = Program.GameServerIp;
if (GameServer.NATConfig.Instance.Enabled)
GAME_SERVER_IP = Program.PUBLICGAMESERVERIP;
uint GAME_SERVER_PORT = 2001;
gameServerIp = Program.PublicGameServerIp;
uint gameServerPort = 2001;
MatchmakingResultNotification.Builder notification = MatchmakingResultNotification.CreateBuilder();
ConnectInfo.Builder connectInfo = ConnectInfo.CreateBuilder();
connectInfo.SetAddress(Address.CreateBuilder().SetAddress_(GAME_SERVER_IP).SetPort(GAME_SERVER_PORT));
connectInfo.SetAddress(Address.CreateBuilder().SetAddress_(gameServerIp).SetPort(gameServerPort));
connectInfo.AddAttribute(bgs.protocol.v2.Attribute.CreateBuilder().SetName("GameAccount").SetValue(bgs.protocol.v2.Variant.CreateBuilder().SetBlobValue(member.Build().ToByteString())));
connectInfo.AddAttribute(bgs.protocol.v2.Attribute.CreateBuilder().SetName("Token").SetValue(bgs.protocol.v2.Variant.CreateBuilder().SetUintValue(0xEEF4364684EE186E))); // FIXME
connectInfo.AddAttribute(AttributeOfServer); // Настройки игры
connectInfo.AddAttribute(attributeOfServer); // GameCreateParams
GameHandle.Builder gh = GameHandle.CreateBuilder();
gh.SetMatchmaker(MatchmakerHandle.CreateBuilder()
.SetId((uint)(controller as HandlerController).Client.Account.GameAccount.BnetEntityId.Low)
.SetId((uint)((HandlerController) controller).Client.Account.GameAccount.BnetEntityId.Low)
.SetAddr(HostProxyPair.CreateBuilder()
.SetHost(ProcessId.CreateBuilder().SetLabel(1250).SetEpoch(1499729350))
.SetProxy(ProcessId.CreateBuilder().SetLabel(0xaa82dfd9).SetEpoch(1497363883))));
@ -116,39 +105,39 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
.SetHost(ProcessId.CreateBuilder().SetLabel(1277).SetEpoch(1499729371))
.SetProxy(ProcessId.CreateBuilder().SetLabel(0xf511871c).SetEpoch(1497363865)));
var gameFound = GameFactoryManager.FindGame((controller as HandlerController).Client, request, ++GameFactoryManager.RequestIdCounter);
var gameFound = GameFactoryManager.FindGame(((HandlerController) controller).Client, request, ++GameFactoryManager.RequestIdCounter);
var clients = (from player in request.Options.PlayerList select GameAccountManager.GetAccountByPersistentID(player.GameAccount.Id) into gameAccount where gameFound != null select gameAccount.LoggedInClient).ToList();
if (((controller as HandlerController).Client).CurrentChannel != null)
if ((((HandlerController)controller).Client).CurrentChannel != null)
{
var channelStatePermission = bgs.protocol.channel.v1.ChannelState.CreateBuilder()
.AddAttribute(bgs.protocol.Attribute.CreateBuilder()
.SetName("D3.Party.JoinPermissionPreviousToLock")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetIntValue(1).Build())
.SetValue(Variant.CreateBuilder().SetIntValue(1).Build())
.Build()).Build();
var notificationPermission = bgs.protocol.channel.v1.UpdateChannelStateNotification.CreateBuilder()
.SetAgentId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId)
.SetAgentId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
.SetStateChange(channelStatePermission)
.Build();
var JoinPerm = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelStatePermission).Build();
var joinNotification = bgs.protocol.channel.v1.JoinNotification.CreateBuilder().SetChannelState(channelStatePermission).Build();
((controller as HandlerController).Client).MakeTargetedRPC(((controller as HandlerController).Client).CurrentChannel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub(((controller as HandlerController).Client)).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { }));
(((HandlerController) controller).Client).MakeTargetedRpc((((HandlerController) controller).Client).CurrentChannel, (lid) => bgs.protocol.channel.v1.ChannelListener.CreateStub((((HandlerController) controller).Client)).OnUpdateChannelState(new HandlerController() { ListenerId = lid }, notificationPermission, callback => { }));
}
gameFound.StartGame(clients, gameFound.DynamicId);
var notificationFound = bgs.protocol.notification.v1.Notification.CreateBuilder()
.SetSenderId(bgs.protocol.EntityId.CreateBuilder().SetHigh((ulong)EntityIdHelper.HighIdType.GameAccountId).SetLow(0).Build())
.SetTargetId(((controller as HandlerController).Client).Account.GameAccount.BnetEntityId)
.SetTargetId((((HandlerController) controller).Client).Account.GameAccount.BnetEntityId)
.SetType("GQ_ENTRY");
var attrF = bgs.protocol.Attribute.CreateBuilder()
.SetName("game_request_id")
.SetValue(bgs.protocol.Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build());
.SetValue(Variant.CreateBuilder().SetUintValue(gameFound.RequestId).Build());
notificationFound.AddAttribute(attrF);
((controller as HandlerController).Client).MakeRPC((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub(((controller as HandlerController).Client)).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { }));
(((HandlerController) controller).Client).MakeRpc((lid) =>
bgs.protocol.notification.v1.NotificationListener.CreateStub((((HandlerController) controller).Client)).OnNotificationReceived(new HandlerController() { ListenerId = lid }, notificationFound.Build(), callback => { }));
gh.SetGameInstanceId((uint)gameFound.BnetEntityId.Low);
@ -162,7 +151,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
notification.SetGameHandle(gh);
System.Threading.Tasks.Task.Delay(2000).ContinueWith(delegate {
(controller as HandlerController).Client.MakeRPC((lid) => GameRequestListener.CreateStub((controller as HandlerController).Client).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
((HandlerController) controller).Client.MakeRpc((lid) => GameRequestListener.CreateStub(((HandlerController) controller).Client).OnMatchmakingResult(new HandlerController() { ListenerId = lid }, notification.Build(), callback => { }));
});
}
}

View File

@ -1,21 +1,11 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.notification.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.GameServer.CommandManager;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -38,20 +28,20 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
case NotificationTypeHelper.NotificationType.Whisper:
var targetAccount = GameAccountManager.GetAccountByPersistentID(request.TargetId.Low);
Logger.Trace(string.Format("NotificationRequest.Whisper by {0} to {1}", (controller as HandlerController).Client.Account.GameAccount, targetAccount));
Logger.Trace(string.Format("NotificationRequest.Whisper by {0} to {1}", ((HandlerController) controller).Client.Account.GameAccount, targetAccount));
if (targetAccount.LoggedInClient == null) return;
if (targetAccount == (controller as HandlerController).Client.Account.GameAccount)
CommandManager.TryParse(request.AttributeList[0].Value.StringValue, (controller as HandlerController).Client); // try parsing it as a command and respond it if so.
if (targetAccount == ((HandlerController) controller).Client.Account.GameAccount)
CommandManager.TryParse(request.AttributeList[0].Value.StringValue, ((HandlerController) controller).Client); // try parsing it as a command and respond it if so.
else
{
var notification = bgs.protocol.notification.v1.Notification.CreateBuilder(request)
.SetSenderId((controller as HandlerController).Client.Account.GameAccount.BnetEntityId)
.SetSenderAccountId((controller as HandlerController).Client.Account.BnetEntityId)
var notification = Notification.CreateBuilder(request)
.SetSenderId(((HandlerController) controller).Client.Account.GameAccount.BnetEntityId)
.SetSenderAccountId(((HandlerController) controller).Client.Account.BnetEntityId)
.Build();
targetAccount.LoggedInClient.MakeRPC((lid) =>
targetAccount.LoggedInClient.MakeRpc((lid) =>
NotificationListener.CreateStub(targetAccount.LoggedInClient).OnNotificationReceived(controller, notification, callback => { }));
}
break;
@ -60,20 +50,20 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
break;
}
//*/
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
}
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<NoData> done)
{
//throw new NotImplementedException();
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
}
public override void Unsubscribe(IRpcController controller, UnsubscribeRequest request, Action<NoData> done)
{
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
//throw new NotImplementedException();
}

View File

@ -1,26 +1,17 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Reflection;
using Google.ProtocolBuffers;
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.presence.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
[Service(serviceID: 0xb, serviceName: "bnet.protocol.presence.PresenceService")]//: )]
[Service(serviceID: 0xb, serviceName: "bnet.protocol.presence.PresenceService")]
public class PresenceService : bgs.protocol.presence.v1.PresenceService, IServerService
{
private static readonly Logger Logger = LogManager.CreateLogger();
@ -39,26 +30,31 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
switch (req.GetHighIdType())
{
case EntityIdHelper.HighIdType.AccountId:
{
var account = AccountManager.GetAccountByPersistentID(req.Low);
if (account != null)
{
Logger.Trace("Subscribe() {0} {1}", ((controller as HandlerController).Client), account);
account.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req).SetResult(0));
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {account}");
account.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req)
.SetResult(0));
}
}
break;
case EntityIdHelper.HighIdType.GameAccountId:
var gameaccount = GameAccountManager.GetAccountByPersistentID(req.Low);
if (gameaccount != null)
{
Logger.Trace("Subscribe() {0} {1}", ((controller as HandlerController).Client), gameaccount);
gameaccount.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req).SetResult(0));
var gameAccount = GameAccountManager.GetAccountByPersistentID(req.Low);
if (gameAccount != null)
{
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
response.AddSubscribeFailed(SubscribeResult.CreateBuilder().SetEntityId(req)
.SetResult(0));
}
}
break;
default:
Logger.Warn("Recieved an unhandled Presence.Subscribe request with type {0} (0x{1})", req.GetHighIdType(), req.High.ToString("X16"));
Logger.Warn("Received an unhandled Presence.Subscribe request with type {0} (0x{1})", req.GetHighIdType(), req.High.ToString("X16"));
break;
}
}
@ -72,102 +68,117 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void BatchUnsubscribe(IRpcController controller, BatchUnsubscribeRequest request, Action<NoData> done)
{
throw new NotImplementedException();
Logger.Fatal("Batch Unsubscribe not implemented");
}
public override void Query(IRpcController controller, QueryRequest request, Action<QueryResponse> done)
{
var builder = bgs.protocol.presence.v1.QueryResponse.CreateBuilder();
var builder = QueryResponse.CreateBuilder();
switch (request.EntityId.GetHighIdType())
{
case EntityIdHelper.HighIdType.AccountId:
var account = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
{
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
foreach (var key in request.KeyList)
{
Logger.Trace("Query() {0} {1} - {2}, {3}, {4}", ((controller as HandlerController).Client), account, (FieldKeyHelper.Program)key.Program, (FieldKeyHelper.OriginatingClass)key.Group, key.Field);
var field = account.QueryField(key);
Logger.MethodTrace(
$"{(((HandlerController)controller).Client)} {gameAccount} - {(FieldKeyHelper.Program)key.Program}, {(FieldKeyHelper.OriginatingClass)key.Group}, {key.Field}");
var field = gameAccount.QueryField(key);
if (field != null) builder.AddField(field);
}
}
break;
case EntityIdHelper.HighIdType.GameAccountId:
var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
{
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
foreach (var key in request.KeyList)
{
Logger.Trace("Query() {0} {1} - {2}, {3}, {4}", ((controller as HandlerController).Client), gameaccount, (FieldKeyHelper.Program)key.Program, (FieldKeyHelper.OriginatingClass)key.Group, key.Field);
var field = gameaccount.QueryField(key);
Logger.MethodTrace(
$"{(((HandlerController)controller).Client)} {gameAccount} - {(FieldKeyHelper.Program)key.Program}, {(FieldKeyHelper.OriginatingClass)key.Group}, {key.Field}");
var field = gameAccount.QueryField(key);
if (field != null) builder.AddField(field);
}
}
break;
default:
Logger.Warn("Recieved an unhandled Presence.Query request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
Logger.Warn("Received an unhandled Presence.Query request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
break;
}
done(builder.Build());
}
public override void Subscribe(IRpcController controller, bgs.protocol.presence.v1.SubscribeRequest request, Action<NoData> done)
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<NoData> done)
{
Task.Run(() =>
{
switch (request.EntityId.GetHighIdType())
{
case EntityIdHelper.HighIdType.AccountId:
var account = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (account != null)
{
Logger.Trace("Subscribe() {0} {1}", ((controller as HandlerController).Client), account);
account.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount != null)
{
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
gameAccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
}
}
break;
case EntityIdHelper.HighIdType.GameAccountId:
{
var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameaccount != null)
{
Logger.Trace("Subscribe() {0} {1}", ((controller as HandlerController).Client), gameaccount);
gameaccount.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameaccount}");
gameaccount.AddSubscriber((((HandlerController)controller).Client), request.ObjectId);
}
}
break;
default:
Logger.Warn("Recieved an unhandled Presence.Subscribe request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
Logger.Warn("Received an unhandled Presence.Subscribe request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
break;
}
});
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
}
public override void Unsubscribe(IRpcController controller, bgs.protocol.presence.v1.UnsubscribeRequest request, Action<NoData> done)
public override void Unsubscribe(IRpcController controller, UnsubscribeRequest request, Action<NoData> done)
{
switch (request.EntityId.GetHighIdType())
{
case EntityIdHelper.HighIdType.AccountId:
var account = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
// The client will probably make sure it doesn't unsubscribe to a null ID, but just to make sure..
if (account != null)
{
account.RemoveSubscriber(((controller as HandlerController).Client));
Logger.Trace("Unsubscribe() {0} {1}", ((controller as HandlerController).Client), account);
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
// The client will probably make sure it doesn't unsubscribe to a null ID, but just to make sure..
if (gameAccount != null)
{
gameAccount.RemoveSubscriber((((HandlerController) controller).Client));
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
}
}
break;
case EntityIdHelper.HighIdType.GameAccountId:
var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameaccount != null)
{
gameaccount.RemoveSubscriber(((controller as HandlerController).Client));
Logger.Trace("Unsubscribe() {0} {1}", ((controller as HandlerController).Client), gameaccount);
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount != null)
{
gameAccount.RemoveSubscriber((((HandlerController)controller).Client));
Logger.MethodTrace($"{(((HandlerController)controller).Client)} {gameAccount}");
}
}
break;
default:
Logger.Warn("Recieved an unhandled Presence.Unsubscribe request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
Logger.Warn("Received an unhandled Presence.Unsubscribe request with type {0} (0x{1})",
request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
break;
}
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
}
@ -175,38 +186,47 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
//4,1
//4,2
switch(request.EntityId.GetHighIdType())
switch (request.EntityId.GetHighIdType())
{
case EntityIdHelper.HighIdType.AccountId:
{
if (request.EntityId.Low <= 0) break;
var account = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (account == null) break;
var a_trace = string.Format("Update() {0} {1} - {2} Operations", ((controller as HandlerController).Client), account, request.FieldOperationCount);
var gameAccount = AccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount == null) break;
var traceData = $"{(((HandlerController)controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations";
foreach (var fieldOp in request.FieldOperationList)
{
a_trace += string.Format("\t{0}, {1}, {2}", (FieldKeyHelper.Program)fieldOp.Field.Key.Program, (FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group, fieldOp.Field.Key.Field);
traceData += $"\t{(FieldKeyHelper.Program)fieldOp.Field.Key.Program}, {(FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group}, {fieldOp.Field.Key.Field}";
}
gameAccount.Update(request.FieldOperationList);
Logger.MethodTrace(traceData);
}
account.Update(request.FieldOperationList);
Logger.Trace(a_trace);
break;
case EntityIdHelper.HighIdType.GameAccountId:
{
if (request.EntityId.Low <= 0) break;
var gameaccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameaccount == null) break;
var ga_trace = string.Format("Update() {0} {1} - {2} Operations", ((controller as HandlerController).Client), gameaccount, request.FieldOperationCount);
var gameAccount = GameAccountManager.GetAccountByPersistentID(request.EntityId.Low);
if (gameAccount == null) break;
var traceData =
$"{(((HandlerController) controller).Client)} {gameAccount} - {request.FieldOperationCount} Operations";
foreach (var fieldOp in request.FieldOperationList)
{
ga_trace += string.Format("\t{0}, {1}, {2}", (FieldKeyHelper.Program)fieldOp.Field.Key.Program, (FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group, fieldOp.Field.Key.Field);
traceData +=
$"\t{(FieldKeyHelper.Program)fieldOp.Field.Key.Program}, {(FieldKeyHelper.OriginatingClass)fieldOp.Field.Key.Group}, {fieldOp.Field.Key.Field}";
}
gameaccount.Update(request.FieldOperationList);
Logger.Trace(ga_trace);
gameAccount.Update(request.FieldOperationList);
Logger.MethodTrace(traceData);
break;
}
default:
Logger.Warn("Recieved an unhandled Presence.Update request with type {0} (0x{1})", request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
Logger.Warn("Received an unhandled Presence.Update request with type {0} (0x{1})",
request.EntityId.GetHighIdType(), request.EntityId.High.ToString("X16"));
break;
}
var builder = bgs.protocol.NoData.CreateBuilder();
var builder = NoData.CreateBuilder();
done(builder.Build());
}

View File

@ -1,25 +1,17 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Reflection;
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.resources.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
[Service(serviceID: 0x3d, serviceName: "bnet.protocol.resources.Resources")]
public class ResourceService : bgs.protocol.resources.v1.ResourcesService, IServerService
public class ResourceService : ResourcesService, IServerService
{
private static readonly Logger Logger = LogManager.CreateLogger();
private static byte[] PFTY_HASH = new byte[] { (byte)0xCF, (byte)0x61, (byte)0xE0, (byte)0x81, (byte)0x09, (byte)0x19, (byte)0xC6, (byte)0xA6, (byte)0xF9, (byte)0xC1, (byte)0xCB, (byte)0x24, (byte)0xB3, (byte)0xC6, (byte)0x9D, (byte)0x03, (byte)0xB0, (byte)0x37, (byte)0x08, (byte)0xEC, (byte)0x16, (byte)0xD9, (byte)0x44, (byte)0x51, (byte)0xC5, (byte)0x1F, (byte)0x90, (byte)0x38, (byte)0xE9, (byte)0x09, (byte)0xA7, (byte)0x5A };
@ -27,7 +19,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void GetContentHandle(IRpcController controller, ContentHandleRequest request, Action<ContentHandle> done)
{
Logger.Trace("GetContentHandle(): ProgramId: 0x{0:X8} StreamId: 0x{1:X8}", request.Program, request.Stream);
Logger.MethodTrace($"ProgramId: 0x{request.Program:X8} StreamId: 0x{request.Stream:X8}");
if (request.Program == (uint)FieldKeyHelper.Program.BNet)
{
var builder = ContentHandle.CreateBuilder()
@ -62,7 +54,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
default:
Logger.Warn("Unknown StreamId: 0x{0:X8}", request.Stream);
builder.SetHash(ByteString.Empty);
(controller as HandlerController).Status = 4;
((HandlerController) controller).Status = 4;
break;
}
done(builder.Build());

View File

@ -1,15 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Reflection;
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol.session.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Math;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using Google.ProtocolBuffers;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
@ -17,12 +12,13 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
[Service(serviceID: 0x13, serviceName: "bnet.protocol.session.SessionService")]
public class SessionService : bgs.protocol.session.v1.SessionService, IServerService
{
private static readonly Logger Logger = LogManager.CreateLogger(nameof(SessionService));
public override void CreateSession(IRpcController controller, CreateSessionRequest request, Action<CreateSessionResponse> done)
{
string Start = "A7B5C8B0593FFEC10000000";
string End = "BCABD";
string session = Start + RandomHelper.Next(0, 9).ToString() + RandomHelper.Next(0, 9).ToString() + RandomHelper.Next(0, 9).ToString() + RandomHelper.Next(0, 9).ToString() + End;
string session = Start + RandomHelper.Next(0, 9) + RandomHelper.Next(0, 9) + RandomHelper.Next(0, 9) + RandomHelper.Next(0, 9) + End;
CreateSessionResponse.Builder builder = CreateSessionResponse.CreateBuilder();
builder.SetSessionId(session);
done(builder.Build());
@ -31,23 +27,26 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
n.SetIdentity(request.Identity)
.SetReason(0)
.SetSessionId(session);
(controller as HandlerController).Client.MakeRPC((lid) => SessionListener.CreateStub((controller as HandlerController).Client).OnSessionCreated(controller, n.Build(), callback => { }));
((HandlerController) controller).Client.MakeRpc((lid) => SessionListener.CreateStub(((HandlerController) controller).Client).OnSessionCreated(controller, n.Build(), callback => { }));
}
private void DisconnectClient(HandlerController controller)
{
if (controller.Client.Account != null && controller.Client.Account.GameAccount != null) controller.Client.Account.GameAccount.LoggedInClient = null;
LoginServer.Battle.PlayerManager.PlayerDisconnected(controller.Client);
if (controller.Client.Account is { GameAccount: { } }) controller.Client.Account.GameAccount.LoggedInClient = null;
Battle.PlayerManager.PlayerDisconnected(controller.Client);
}
public override void DestroySession(IRpcController controller, DestroySessionRequest request, Action<NoData> done)
{
Console.WriteLine("Клиент - {0} , отключен", (controller as HandlerController).Client.SocketConnection.RemoteAddress);
this.DisconnectClient(controller as HandlerController);
if ((controller as HandlerController).Client.Account != null)
(controller as HandlerController).Client.Account.GameAccount.Logined = false;
((controller as HandlerController).Client).Connect.CloseAsync();
(controller as HandlerController).Client.SocketConnection.CloseAsync();
Logger.MethodTrace($"Destroying game session for client {((HandlerController) controller).Client}");
if (controller is HandlerController handlerController)
{
DisconnectClient(handlerController);
if (handlerController.Client.Account != null)
handlerController.Client.Account.GameAccount.IsLoggedIn = false;
(handlerController.Client).Connect.CloseAsync();
handlerController.Client.SocketConnection.CloseAsync();
}
done(NoData.CreateBuilder().Build());
}
@ -64,9 +63,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
}
public override void GetSignedSessionState(IRpcController controller, GetSignedSessionStateRequest request, Action<GetSignedSessionStateResponse> done)
{
done(GetSignedSessionStateResponse.CreateBuilder().SetToken("eyJ0eXAiOiJKV1QiLCJlbnYiOiJwcm9kLmV1IiwiYWxnIjoiUlMyNTYiLCJraWQiOiJmMDE5NzgzMi0zMWMwLTQzN2MtOTc2NC1iMzliOTM5MDJlNWMiLCJrdHkiOiJSU0EifQ").Build());
}
=> done(GetSignedSessionStateResponse.CreateBuilder().SetToken("eyJ0eXAiOiJKV1QiLCJlbnYiOiJwcm9kLmV1IiwiYWxnIjoiUlMyNTYiLCJraWQiOiJmMDE5NzgzMi0zMWMwLTQzN2MtOTc2NC1iMzliOTM5MDJlNWMiLCJrdHkiOiJSU0EifQ").Build());
public override void MarkSessionsAlive(IRpcController controller, MarkSessionsAliveRequest request, Action<MarkSessionsAliveResponse> done)
{

View File

@ -1,19 +1,10 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.sns.v1;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services

View File

@ -1,22 +1,13 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.user_manager.v1;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Base;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.FriendsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
using System.Reflection;
namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
@ -25,15 +16,15 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
{
private static readonly Logger Logger = LogManager.CreateLogger();
public override void Subscribe(Google.ProtocolBuffers.IRpcController controller, SubscribeRequest request, System.Action<SubscribeResponse> done)
public override void Subscribe(IRpcController controller, SubscribeRequest request, Action<SubscribeResponse> done)
{
Logger.Trace("Subscribe() {0}", ((controller as HandlerController).Client));
Logger.MethodTrace((((HandlerController) controller).Client).ToString());
UserManager.Instance.AddSubscriber(((controller as HandlerController).Client), request.ObjectId);
UserManager.Instance.AddSubscriber((((HandlerController) controller).Client), request.ObjectId);
var builder = SubscribeResponse.CreateBuilder();
var blockedIds = (controller as HandlerController).Client.Account.IgnoreIds;
var blockedIds = ((HandlerController) controller).Client.Account.IgnoreIds;
foreach (var blocked in blockedIds)
{
@ -50,7 +41,7 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void AddRecentPlayers(IRpcController controller, AddRecentPlayersRequest request, Action<NoData> done)
{
Logger.Trace("AddRecentPlayers()");
Logger.MethodTrace("");
done(NoData.DefaultInstance);
}
@ -61,18 +52,18 @@ namespace DiIiS_NA.LoginServer.ServicesSystem.Services
public override void BlockPlayer(IRpcController controller, BlockPlayerRequest request, Action<NoData> done)
{
Logger.Trace("BlockEntity()");
Logger.MethodTrace("");
done(NoData.CreateBuilder().Build());
UserManager.BlockAccount(((controller as HandlerController).Client), request);
UserManager.BlockAccount((((HandlerController) controller).Client), request);
}
public override void UnblockPlayer(IRpcController controller, UnblockPlayerRequest request, Action<NoData> done)
{
Logger.Trace("UnblockPlayer()");
Logger.MethodTrace("");
done(NoData.CreateBuilder().Build());
UserManager.UnblockAccount(((controller as HandlerController).Client), request);
UserManager.UnblockAccount((((HandlerController) controller).Client), request);
}
public override void BlockPlayerForSession(IRpcController controller, BlockPlayerRequest request, Action<NoData> done)

View File

@ -1,21 +1,11 @@
//Blizzless Project 2022
//Blizzless Project 2022
using bgs.protocol;
//Blizzless Project 2022
using bgs.protocol;
using bgs.protocol.whisper.v1;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.ServicesSystem;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.BGS_Server.ServicesSystem.Services

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,7 @@
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.Helpers;
using Google.ProtocolBuffers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Text;
namespace DiIiS_NA.LoginServer.Toons

View File

@ -1,33 +1,21 @@
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Math;
//Blizzless Project 2022
using DiIiS_NA.Core.Helpers.Math;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
//Blizzless Project 2022
using DiIiS_NA.GameServer.GSSystem.SkillsSystem;
//Blizzless Project 2022
using DiIiS_NA.LoginServer.AccountsSystem;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using static DiIiS_NA.LoginServer.Toons.Toon;
namespace DiIiS_NA.LoginServer.Toons
{
public static class ToonManager
{
private static readonly ConcurrentDictionary<ulong, Toon> LoadedToons = new ConcurrentDictionary<ulong, Toon>();
private static readonly ConcurrentDictionary<ulong, Toon> LoadedToons = new();
private static readonly Logger Logger = LogManager.CreateLogger("DataBaseSystem");
private static readonly DBInventory NewbiePants = new DBInventory
@ -158,7 +146,7 @@ namespace DiIiS_NA.LoginServer.Toons
Attributes = "383,:1|1E-45;103,:0|0;406,:0|0;409,:1|1E-45;401,:1|1E-45;405,:1941814752|3.0065772E+31;194,:1067030938|1.2;196,:1067030938|1.2;198,:1067030938|1.2;538,:1067030938|1.2;540,:1067030938|1.2;546,:1067030938|1.2;201,:1067030938|1.2;446,:0|0;447,:0|0;448,:0|0;449,:0|0;539,:0|0;541,:0|0;195,:0|0;197,:0|0;231,0:1073741824|2;224,0:1077936128|3;232,0:1073741824|2;225,0:1077936128|3;226,:1077936128|3;233,:1073741824|2;236,:1075838976|2.5;235,0:1075838976|2.5;542,0:1073741824|2;547,0:1073741824|2;220,0:1073741824|2;216,0:1073741824|2;543,0:0|0;234,0:1075838976|2.5;222,0:1065353216|1;223,0:1065353216|1;227,0:1065353216|1;228,:1065353216|1;544,0:1065353216|1;548,0:1065353216|1;213,0:1065353216|1;545,0:0|0;381,:1000|1.401E-42;380,:1000|1.401E-42;100,30592:1|1E-45;102,30592:1|1E-45;388,57:0|0"
};
private static readonly DBInventory NewbieNecr = new DBInventory
private static readonly DBInventory NewbieNecromancer = new DBInventory
{
EquipmentSlot = 4,
LocationX = 0,
@ -193,12 +181,9 @@ namespace DiIiS_NA.LoginServer.Toons
public static void PreLoadToons()
{
Logger.Info("Loading Diablo III - Toons...");
List<DBToon> all_toons = DBSessions.SessionQuery<DBToon>();
foreach (var toon in all_toons)
{
foreach (var toon in DBSessions.SessionQuery<DBToon>())
LoadedToons.TryAdd(toon.Id, new Toon(toon, null));
}
}
public static Toon GetToonByDBToon(DBToon dbToon, GameDBSession session = null)
{
@ -215,15 +200,15 @@ namespace DiIiS_NA.LoginServer.Toons
public static Account GetOwnerAccountByToonLowId(ulong id)
{
return GetToonByLowID(id).GameAccount.Owner;
return GetToonByLowId(id).GameAccount.Owner;
}
public static GameAccount GetOwnerGameAccountByToonLowId(ulong id)
{
return GetToonByLowID(id).GameAccount;
return GetToonByLowId(id).GameAccount;
}
public static Toon GetToonByLowID(ulong id, GameDBSession session = null)
public static Toon GetToonByLowId(ulong id, GameDBSession session = null)
{
if (LoadedToons.ContainsKey(id))
return LoadedToons[id];
@ -237,20 +222,14 @@ namespace DiIiS_NA.LoginServer.Toons
public static Toon GetDeletedToon(GameAccount account)
{
var query = DBSessions.SessionQueryWhere<DBToon>(dbt => dbt.DBGameAccount.Id == account.PersistentID && dbt.Deleted);
return query.Any() ? GetToonByLowID(query.Last().Id) : null;
return query.Any() ? GetToonByLowId(query.Last().Id) : null;
}
public static List<Toon> GetToonsForGameAccount(GameAccount account)
{
var toons = DBSessions.SessionQueryWhere<DBToon>(t => t.DBGameAccount.Id == account.PersistentID).Select(dbt => GetToonByLowID(dbt.Id));
return toons.ToList();
}
public static List<Toon> GetToonsForGameAccount(GameAccount account) =>
DBSessions.SessionQueryWhere<DBToon>(t => t.DBGameAccount.Id == account.PersistentID)
.Select(dbt => GetToonByLowId(dbt.Id)).ToList();
public static int TotalToons
{
get { return DBSessions.SessionQuery<DBToon>().Count; }
}
public static int TotalToons => DBSessions.SessionQuery<DBToon>().Count;
public static Toon CreateNewToon(string name, int classId, ToonFlags flags, byte level, bool IsHardcore, GameAccount gameAccount, int Season)
@ -275,7 +254,7 @@ namespace DiIiS_NA.LoginServer.Toons
CurrentQuestId = 87700,
CurrentQuestStepId = -1,
CurrentDifficulty = 0,
Lore = new byte[0],
Lore = Array.Empty<byte>(),
Stats = "0;0;0;0;0;0",
DBGameAccount = dbGameAccount,
Cosmetic1 = -1,
@ -286,7 +265,7 @@ namespace DiIiS_NA.LoginServer.Toons
DBSessions.SessionSave(newDBToon);
Toon createdToon = GetToonByLowID(newDBToon.Id);
Toon createdToon = GetToonByLowId(newDBToon.Id);
CreateSkillSet(newDBToon);
@ -341,7 +320,7 @@ namespace DiIiS_NA.LoginServer.Toons
armor.isHardcore = isHardcore;
DBSessions.SessionSave(armor);
DBInventory weapon = new DBInventory();
DBInventory weapon;
switch (toon.DBToon.Class)
{
case ToonClass.Barbarian:
@ -363,7 +342,7 @@ namespace DiIiS_NA.LoginServer.Toons
weapon = NewbieWand;
break;
case ToonClass.Necromancer:
weapon = NewbieNecr;
weapon = NewbieNecromancer;
break;
default:
weapon = NewbieKnife;
@ -375,7 +354,6 @@ namespace DiIiS_NA.LoginServer.Toons
DBSessions.SessionSave(weapon);
if (toon.DBToon.Class == ToonClass.Crusader) //add shield
{
DBInventory shield = new DBInventory();
weapon = NewbieShield;
weapon.DBToon = toon.DBToon;
weapon.DBGameAccount = toon.GameAccount.DBGameAccount;
@ -386,14 +364,15 @@ namespace DiIiS_NA.LoginServer.Toons
public static void CreateHirelingProfile(Toon toon, int type)
{
var hireling = new DBHireling();
hireling.Class = type;
hireling.DBToon = toon.DBToon;
hireling.Skill1SNOId = -1;
hireling.Skill2SNOId = -1;
hireling.Skill3SNOId = -1;
hireling.Skill4SNOId = -1;
DBSessions.SessionSave(hireling);
DBSessions.SessionSave(new DBHireling
{
Class = type,
DBToon = toon.DBToon,
Skill1SNOId = -1,
Skill2SNOId = -1,
Skill3SNOId = -1,
Skill4SNOId = -1
});
}
public static void DeleteToon(Toon toon)
@ -436,7 +415,7 @@ namespace DiIiS_NA.LoginServer.Toons
DBGameAccount = gaccount,
TimePlayed = 0,
Stats = "",
Lore = new byte[0],
Lore = Array.Empty<byte>(),
Deleted = false,
Archieved = false,
Cosmetic1 = -1,

View File

@ -1,13 +1,7 @@
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.Schedulers;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.LoginServer

View File

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<RootNamespace>DiIiS_NA</RootNamespace>
<Company>DiIiS Team</Company>
<Copyright>iEvE</Copyright>
@ -68,30 +68,17 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Castle.Core" Version="4.4.1" />
<PackageReference Include="Discord.Net" Version="3.8.0" />
<PackageReference Include="DotNetty.Buffers" Version="0.6.0" />
<PackageReference Include="DotNetty.Codecs" Version="0.6.0" />
<PackageReference Include="DotNetty.Codecs.Http" Version="0.6.0" />
<PackageReference Include="DotNetty.Common" Version="0.6.0" />
<PackageReference Include="DotNetty.Handlers" Version="0.6.0" />
<PackageReference Include="DotNetty.Transport" Version="0.6.0" />
<PackageReference Include="Discord.Net" Version="3.9.0" />
<PackageReference Include="DotNetty.Buffers" Version="0.7.5" />
<PackageReference Include="DotNetty.Codecs" Version="0.7.5" />
<PackageReference Include="DotNetty.Codecs.Http" Version="0.7.5" />
<PackageReference Include="DotNetty.Common" Version="0.7.5" />
<PackageReference Include="DotNetty.Handlers" Version="0.7.5" />
<PackageReference Include="DotNetty.Transport" Version="0.7.5" />
<PackageReference Include="FluentNHibernate" Version="3.1.0" />
<PackageReference Include="ILCompile" Version="1.0.5" />
<PackageReference Include="log4net" Version="2.0.12" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.2.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="5.0.1" />
<PackageReference Include="Npgsql" Version="4.0.4" />
<PackageReference Include="Skater.exe" Version="7.5.0" />
<PackageReference Include="SoapCore" Version="0.9.9.1" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
<PackageReference Include="System.ServiceModel.Web" Version="1.0.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.4.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.2" />
<PackageReference Include="Npgsql" Version="7.0.1" />
</ItemGroup>
<ItemGroup>
@ -133,4 +120,13 @@
</None>
</ItemGroup>
<ItemGroup>
<Compile Update="D3-GameServer\MessageSystem\GameAttribute.List.cs">
<DependentUpon>GameAttribute.cs</DependentUpon>
</Compile>
<Compile Update="D3-GameServer\CommandManager\InvalidParametersException.cs">
<DependentUpon>CommandException.cs</DependentUpon>
</Compile>
</ItemGroup>
</Project>

View File

@ -1,16 +1,20 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using DiIiS_NA.Core.Logging;
using Nini.Config;
namespace DiIiS_NA.Core.Config
{
public class Config
{
private readonly Logger _logger;
private readonly string _sectionName;
private readonly IConfig _section;
public Config(string sectionName)
protected Config(string sectionName)
{
this._section = ConfigurationManager.Section(sectionName) ?? ConfigurationManager.AddSection(sectionName);
_sectionName = sectionName;
_logger = LogManager.CreateLogger($"{GetType().Name}:{sectionName}");
_section = ConfigurationManager.Section(sectionName) ?? ConfigurationManager.AddSection(sectionName);
}
public void Save()
@ -18,14 +22,14 @@ namespace DiIiS_NA.Core.Config
ConfigurationManager.Save();
}
protected bool GetBoolean(string key, bool defaultValue) { return this._section.GetBoolean(key, defaultValue); }
protected double GetDouble(string key, double defaultValue) { return this._section.GetDouble(key, defaultValue); }
protected float GetFloat(string key, float defaultValue) { return this._section.GetFloat(key, defaultValue); }
protected int GetInt(string key, int defaultValue) { return this._section.GetInt(key, defaultValue); }
protected int GetInt(string key, int defaultValue, bool fromAlias) { return this._section.GetInt(key, defaultValue, fromAlias); }
protected long GetLong(string key, long defaultValue) { return this._section.GetLong(key, defaultValue); }
protected string GetString(string key, string defaultValue) { return this._section.Get(key, defaultValue); }
protected string[] GetEntryKeys() { return this._section.GetKeys(); }
protected void Set(string key, object value) { this._section.Set(key, value); }
protected bool GetBoolean(string key, bool defaultValue) => _section.GetBoolean(key, defaultValue);
protected double GetDouble(string key, double defaultValue) => _section.GetDouble(key, defaultValue);
protected float GetFloat(string key, float defaultValue) => _section.GetFloat(key, defaultValue);
protected int GetInt(string key, int defaultValue) => _section.GetInt(key, defaultValue);
protected int GetInt(string key, int defaultValue, bool fromAlias) => _section.GetInt(key, defaultValue, fromAlias);
protected long GetLong(string key, long defaultValue) => _section.GetLong(key, defaultValue);
protected string GetString(string key, string defaultValue) { return _section.Get(key, defaultValue); }
protected string[] GetEntryKeys() { return _section.GetKeys(); }
protected void Set(string key, object value) { _section.Set(key, value); }
}
}

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using DiIiS_NA.Core.Helpers.IO;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using Nini.Config;
namespace DiIiS_NA.Core.Config
@ -21,7 +16,7 @@ namespace DiIiS_NA.Core.Config
{
try
{
ConfigFile = string.Format("{0}/{1}", FileHelpers.AssemblyRoot, "config.ini"); // the config file's location.
ConfigFile = $"{FileHelpers.AssemblyRoot}/{"config.ini"}"; // the config file's location.
Parser = new IniConfigSource(ConfigFile); // see if the file exists by trying to parse it.
_fileExists = true;
}
@ -34,28 +29,28 @@ namespace DiIiS_NA.Core.Config
finally
{
// adds aliases so we can use On and Off directives in ini files.
Parser.Alias.AddAlias("On", true);
Parser.Alias.AddAlias("Off", false);
Parser!.Alias.AddAlias("On", true);
Parser!.Alias.AddAlias("Off", false);
// logger level aliases.
Parser.Alias.AddAlias("MinimumLevel", Logger.Level.Trace);
Parser.Alias.AddAlias("MaximumLevel", Logger.Level.Trace);
Parser!.Alias.AddAlias("MinimumLevel", Logger.Level.Trace);
Parser!.Alias.AddAlias("MaximumLevel", Logger.Level.Trace);
}
Parser.ExpandKeyValues();
}
static internal IConfig Section(string section) // Returns the asked config section.
internal static IConfig Section(string section) // Returns the asked config section.
{
return Parser.Configs[section];
}
static internal IConfig AddSection(string section) // Adds a config section.
internal static IConfig AddSection(string section) // Adds a config section.
{
return Parser.AddConfig(section);
}
static internal void Save() // Saves the settings.
internal static void Save() // Saves the settings.
{
if (_fileExists) Parser.Save();
else

View File

@ -9,6 +9,7 @@ using Discord;
using Discord.Commands;
using Discord.WebSocket;
using DiIiS_NA.Core.Discord.Services;
using DiIiS_NA.Core.Extensions;
using DiIiS_NA.LoginServer.AccountsSystem;
using DiIiS_NA.Core.Logging;
using DiIiS_NA.Core.Storage;
@ -224,10 +225,10 @@ namespace DiIiS_NA.Core.Discord
{
var message = await guild.GetTextChannel(channelId).GetMessageAsync(param.First().Value);
var reactedUsers = await (message as IUserMessage).GetReactionUsersAsync(Emote.Parse("<:wolfRNG:607868292979490816>"), 100).FlattenAsync();
var contestants = reactedUsers.Where(u => !u.IsBot).ToList();
if (contestants.Count() > 0)
var contestants = reactedUsers.Where(u => !u.IsBot).ToArray();
if (contestants.TryPickRandom(out var winner))
{
var winner = reactedUsers.Where(u => !u.IsBot).ToList()[DiIiS_NA.Core.Helpers.Math.FastRandom.Instance.Next(0, reactedUsers.Count() - 1)];
winnerName = guild.GetUser(winner.Id).Nickname;
await winner.SendMessageAsync("Congratulations! You have won **7 days of D3 Reflection Premium**!.\nYour account has already had its Premium prolonged. Have a nice game!");
var acc = AccountManager.GetAccountByDiscordId(winner.Id);

View File

@ -33,11 +33,11 @@ namespace DiIiS_NA.Core.Discord.Modules
}
if (registerInfo.Count() == 3)
if (registerInfo.Length == 3)
{
if (!email.Contains('@'))
{
await ReplyAsync($"<@{Context.User.Id}> " + string.Format("'{0}' is not a valid email address.", email));
await ReplyAsync($"<@{Context.User.Id}> " + $"'{email}' is not a valid email address.");
return;
}
if (!IsValid(email))

View File

@ -8,8 +8,6 @@ using Discord.Commands;
using DiIiS_NA.Core.Extensions;
using DiIiS_NA.Core.Storage;
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
using DiIiS_NA.Core.Storage;
using DiIiS_NA.Core.Storage.AccountDataBase.Entities;
using DiIiS_NA.LoginServer.Battle;
using DiIiS_NA.LoginServer.GamesSystem;

View File

@ -1,9 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
namespace DiIiS_NA.Core.Extensions
@ -80,6 +76,11 @@ namespace DiIiS_NA.Core.Extensions
do action(array, walker.Position);
while (walker.Step());
}
public static int FindIndex<T>(this T[] source, Predicate<T> match)
{
return Array.FindIndex(source, match);
}
}
internal class ArrayTraverse

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Numerics;
namespace DiIiS_NA.Core.Extensions

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using System;
namespace DiIiS_NA.Core.Extensions
{

View File

@ -1,6 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using System;
using System.Collections.Generic;
namespace DiIiS_NA.Core.Extensions
{
@ -21,5 +20,89 @@ namespace DiIiS_NA.Core.Extensions
TimeSpan diff = time.ToUniversalTime() - DateTime.UnixEpoch;
return (ulong)((diff.TotalSeconds - 946695547L) * 1000000000L);
}
/// <summary>
/// Transforms a timespan to a readable text.
/// E.g.:
/// 1 day, 2 hours, 3 minutes and 4 seconds
/// 5 hours, 6 minutes and 7 seconds
///
/// If over certain threshold (millennium or more) it will only return the number of days.
/// </summary>
/// <param name="span">The timespan to be converted</param>
/// <returns>The readable text</returns>
public static string ToText(this TimeSpan span)
{
List<string> parts = new();
// if days are divided by 365, we have years, otherwise we have months or days
if (span.Days / 365 > 0)
{
// if days are divided by 365, we have years
parts.Add($"{((double)span.Days / 365):F} year{(span.Days / 365 > 1 ? "s" : "")}");
// get months from the remaining days
int months = span.Days % 365 / 30;
if (months > 0)
parts.Add($"{months} month{(months > 1 ? "s" : "")}");
// get remaining days
int days = span.Days % 365 % 30;
if (days > 0)
parts.Add($"{days} day{(days > 1 ? "s" : "")}");
}
else if (span.Days / 30 > 0)
{
// if days are divided by 30, we have months
parts.Add($"{((double)span.Days / 30):F} month{(span.Days / 30 > 1 ? "s" : "")}");
// get remaining days
int days = span.Days % 30;
if (days > 0)
parts.Add($"{days} day{(days > 1 ? "s" : "")}");
}
else if (span.Days > 0)
// if days are not divided by 365 or 30, we have days
parts.Add( $"{span.Days} day{(span.Days > 1 ? "s" : "")}");
if (span.Hours > 0)
parts.Add($"{span.Hours} hour{(span.Hours > 1 ? "s" : "")}");
if (span.Minutes > 0)
parts.Add($"{span.Minutes} minute{(span.Minutes > 1 ? "s" : "")}");
if (span.Seconds > 0)
parts.Add($"{span.Seconds} second{(span.Seconds > 1 ? "s" : "")}");
var result = parts.ToArray();
return string.Join(", ", result[..^1]) + (result.Length > 1 ? " and " : "") + parts[^1];
}
public static string ToSmallText(this TimeSpan span)
{
List<string> parts = new();
if (span.Days / 365 > 0)
{
parts.Add($"{((double)span.Days / 365):F}y");
int months = span.Days % 365 / 30;
if (months > 0)
parts.Add($"{months}m");
int days = span.Days % 365 % 30;
if (days > 0)
parts.Add($"{days}d");
}
else if (span.Days / 30 > 0)
{
parts.Add($"{((double)span.Days / 30):F}m");
int days = span.Days % 30;
if (days > 0)
parts.Add($"{days}d");
}
else if (span.Days > 0)
parts.Add($"{span.Days}d");
if (span.Hours > 0)
parts.Add($"{span.Hours}h");
if (span.Minutes > 0)
parts.Add($"{span.Minutes}m");
if (span.Seconds > 0)
parts.Add($"{span.Seconds}s");
return string.Join(" ", parts);
}
}
}

View File

@ -1,32 +1,36 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Linq;
using DiIiS_NA.Core.Helpers.Math;
namespace DiIiS_NA.Core.Extensions
namespace DiIiS_NA.Core.Extensions;
public static class EnumerableExtensions
{
public static class EnumerableExtensions
{
public static string HexDump(this IEnumerable<byte> collection)
public static string ToHex(this byte b) => b.ToString("X2");
public static string HexDump(this byte[] collection, bool skipSpace = false)
{
var sb = new StringBuilder();
foreach (byte value in collection)
{
sb.Append(value.ToString("X2"));
sb.Append(value.ToHex());
if (!skipSpace)
sb.Append(' ');
}
if (sb.Length > 0)
if (!skipSpace && sb.Length > 0)
sb.Remove(sb.Length - 1, 1);
return sb.ToString();
}
public static string ToEncodedString(this IEnumerable<byte> collection, Encoding encoding)
public static string HexDump(this IEnumerable<byte> collection, bool skipSpace = false)
{
return collection.ToArray().HexDump(skipSpace);
}
public static string ToEncodedString(this IEnumerable<byte> collection, Encoding encoding = null)
{
encoding ??= Encoding.UTF8;
return encoding.GetString(collection.ToArray());
}
@ -38,7 +42,7 @@ namespace DiIiS_NA.Core.Extensions
int i = 0;
foreach (byte value in collection)
{
if (i > 0 && ((i % 16) == 0))
if (i > 0 && i % 16 == 0)
{
output.Append(hex);
output.Append(' ');
@ -48,18 +52,21 @@ namespace DiIiS_NA.Core.Extensions
}
hex.Append(value.ToString("X2"));
hex.Append(' ');
text.Append(string.Format("{0}", (char.IsWhiteSpace((char)value) && (char)value != ' ') ? '.' : (char)value)); // prettify text
text.Append($"{(char.IsWhiteSpace((char)value) && (char)value != ' ' ? '.' : (char)value)}"); // prettify text
++i;
}
var hexstring = hex.ToString();
var hexRepresentation = hex.ToString();
if (text.Length < 16)
{
hexstring = hexstring.PadRight(48); // pad the hex representation in-case it's smaller than a regular 16 value line.
hexRepresentation = hexRepresentation.PadRight(48); // pad the hex representation in-case it's smaller than a regular 16 value line.
}
output.Append(hexstring);
output.Append(hexRepresentation);
output.Append(' ');
output.Append(text);
return output.ToString();
}
}
public static TItem PickRandom<TItem>(this IEnumerable<TItem> source) => RandomHelper.RandomItem(source);
public static bool TryPickRandom<TItem>(this IEnumerable<TItem> source, out TItem randomItem) => RandomHelper.TryGetRandomItem(source, out randomItem);
}

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Text;
//Blizzless Project 2022
using Google.ProtocolBuffers;
//Blizzless Project 2022
using Google.ProtocolBuffers.Descriptors;
namespace DiIiS_NA.Core.Extensions

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System.Collections.Generic;
using System.Collections.Generic;
namespace DiIiS_NA.Core.Extensions
{

View File

@ -1,23 +0,0 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System.Runtime.Serialization.Formatters.Binary;
//Blizzless Project 2022
using System.IO;
namespace DiIiS_NA.Core.Extensions
{
public static class DeepCopy
{
public static T DeepClone<T>(T obj)
{
using (var ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, obj);
ms.Position = 0;
return (T)formatter.Deserialize(ms);
}
}
}
}

View File

@ -1,4 +1,7 @@
//Blizzless Project 2022
using System;
using System.Collections.Generic;
using System.Text;
namespace DiIiS_NA.Core.Extensions
{
public static class StringExtensions
@ -25,6 +28,7 @@ namespace DiIiS_NA.Core.Extensions
{
sB.Append((char)item);
}
ms.Close();
sw.Dispose();
ms.Dispose();
@ -53,11 +57,14 @@ namespace DiIiS_NA.Core.Extensions
{
sB.Append((char)byteArray[i]);
}
sr.Close();
ms.Close();
sr.Dispose();
ms.Dispose();
return sB.ToString();
}
public static byte[] ToBytes(this string bytes, Encoding encoding) => encoding.GetBytes(bytes);
public static byte[] ToBytes(this string bytes) => bytes.ToBytes(Encoding.UTF8);
}
}

View File

@ -1,23 +1,14 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.Core.Extensions
{
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Globalization;
//Blizzless Project 2022
using System.Text;
using System;
using System.Globalization;
using System.Text;
public static class Utilities
{

View File

@ -1,7 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Linq;
using System.Text;
namespace DiIiS_NA.Core.Helpers.Hash

View File

@ -1,11 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.Collections.Generic;
using System.IO;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
namespace DiIiS_NA.Core.Helpers.IO

View File

@ -1,10 +1,7 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Text;
using DiIiS_NA.Core.Logging;
namespace DiIiS_NA.Core.Helpers.Math
{
@ -12,7 +9,9 @@ namespace DiIiS_NA.Core.Helpers.Math
{
#region Static Fields
private static readonly FastRandom __seedRng = new FastRandom((int)Environment.TickCount);
private static readonly Logger Logger = LogManager.CreateLogger(nameof(FastRandom));
private static readonly FastRandom _seedRng = new(Environment.TickCount);
public static readonly FastRandom Instance = new FastRandom();
@ -32,7 +31,7 @@ namespace DiIiS_NA.Core.Helpers.Math
public FastRandom()
{
Reinitialise(__seedRng.NextInt());
Reinitialise(_seedRng.NextInt());
}
public FastRandom(int seed)
@ -212,5 +211,12 @@ namespace DiIiS_NA.Core.Helpers.Math
}
#endregion
/// <summary>
/// Chance returns true if a random number between 0 and 100 is lesser than the specified value.
/// </summary>
/// <param name="successPercentage"></param>
/// <returns></returns>
public bool Chance(float successPercentage) => Next(100) < successPercentage;
}
}

View File

@ -1,116 +1,122 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Linq;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
namespace DiIiS_NA.Core.Helpers.Math
namespace DiIiS_NA.Core.Helpers.Math;
public static class RandomHelper
{
public class RandomHelper
{
private readonly static Random _random;
static RandomHelper()
{
_random = new Random();
}
private static readonly Random Random = new();
public static int Next()
{
return _random.Next();
return Random.Next();
}
public static int Next(Int32 maxValue)
public static int Next(int maxValue)
{
return _random.Next(maxValue);
return Random.Next(maxValue);
}
public static int Next(Int32 minValue, Int32 maxValue)
public static int Next(int minValue, int maxValue)
{
return _random.Next(minValue, maxValue);
return Random.Next(minValue, maxValue);
}
public static void NextBytes(byte[] buffer)
{
_random.NextBytes(buffer);
Random.NextBytes(buffer);
}
public static double NextDouble()
{
return _random.NextDouble();
return Random.NextDouble();
}
/*IEnumerable<TValue>*/
public static TValue RandomValue<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
public static T RandomItem<T>(IEnumerable<T> source)
{
List<TValue> values = Enumerable.ToList(dictionary.Values);
int size = dictionary.Count;
/*while (true)
var collection = source as IReadOnlyCollection<T> ?? source?.ToArray();
if (collection == null || collection.Count == 0)
{
yield return values[_random.Next(size)];
}*/
return values[_random.Next(size)];
throw new ArgumentException("Cannot be null or empty", nameof(source));
}
var randomIndex = Next(collection.Count);
return collection.ElementAt(randomIndex);
}
public static bool TryGetRandomItem<T>(IEnumerable<T> source, out T randomItem)
{
var collection = source as IReadOnlyCollection<T> ?? source?.ToArray();
if (collection == null)
{
throw new ArgumentException("Cannot be null", nameof(source));
}
if (collection.Count == 0)
{
randomItem = default;
return false;
}
var randomIndex = Next(collection.Count);
randomItem = collection.ElementAt(randomIndex);
return true;
}
/// <summary>
/// Picks a random item from a list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <param name="source"></param>
/// <param name="probability">A function that assigns each item a probability. If the probabilities dont sum up to 1, they are normalized</param>
/// <returns></returns>
public static T RandomItem<T>(IEnumerable<T> list, Func<T, float> probability)
public static T RandomItem<T>(IEnumerable<T> source, Func<T, float> probability)
{
int cumulative = (int)list.Select(x => probability(x)).Sum();
var collection = source as IReadOnlyCollection<T> ?? source.ToArray();
int cumulative = (int)collection.Select(probability).Sum();
int randomRoll = RandomHelper.Next(cumulative);
int randomRoll = Next(cumulative);
float cumulativePercentages = 0;
foreach (T element in list)
foreach (T element in collection)
{
cumulativePercentages += probability(element);
if (cumulativePercentages > randomRoll)
return element;
}
return list.First();
return collection.First();
}
}
}
public class ItemRandomHelper
{
private static readonly Logger Logger = LogManager.CreateLogger("RH");
uint a;
uint b;
public class ItemRandomHelper
{
uint _a;
uint _b;
public ItemRandomHelper(int seed)
{
a = (uint)seed;
b = 666;
_a = (uint)seed;
_b = 666;
}
public void ReinitSeed()
{
b = 666;
_b = 666;
}
public uint Next()
{
ulong temp = 1791398085UL * (ulong)a + (ulong)b;
a = (uint)temp;
b = (uint)(temp >> 32);
ulong temp = 1791398085UL * _a + _b;
_a = (uint)temp;
_b = (uint)(temp >> 32);
//Logger.Debug("Next(): a {0}, b {1}", a, b);
return (uint)a;
return _a;
}
public float Next(float min, float max)
{
return min + (Next() % (uint)(max - min + 1));
}
}
}

View File

@ -0,0 +1,242 @@
using System;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Spectre.Console;
namespace DiIiS_NA.Core.Logging;
public class AnsiTarget : LogTarget
{
private readonly Table _table;
private static CancellationTokenSource CancellationTokenSource { get; } = new CancellationTokenSource();
private static bool _shutdown = true;
public AnsiTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat)
{
_shutdown = false;
MinimumLevel = minLevel;
MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_table = new Table().Expand().ShowFooters().ShowHeaders().Border(TableBorder.Rounded);
if (IncludeTimeStamps)
_table.AddColumn("Time");
_table
.AddColumn("Level")
.AddColumn("Logger")
.AddColumn("Message")
.AddColumn("Error");
AnsiConsole.Live(_table).StartAsync(async ctx =>
{
int lastCount = 0;
int consoleSize = 0;
while (!CancellationTokenSource.Token.IsCancellationRequested)
{
int currentConsoleSize = 0;
try
{
currentConsoleSize = Console.WindowHeight * Console.WindowWidth;
}
catch {}
if (lastCount != _table.Rows.Count || consoleSize != currentConsoleSize)
{
lastCount = _table.Rows.Count;
consoleSize = currentConsoleSize;
ctx.UpdateTarget(_table);
}
await Task.Delay(100);
}
_shutdown = true;
});
}
public static void StopIfRunning()
{
CancellationTokenSource.Cancel();
while(!_shutdown)
Thread.Sleep(100);
Thread.Sleep(1000);
AnsiConsole.Clear();
AnsiConsole.Cursor.SetPosition(0,0);
}
/// <summary>
/// Logging keywords to beautify the output.
/// It's ugly, I know.
/// Changes are welcome - @iamdroppy
/// </summary>
/// <param name="text">Text to "beautify"</param>
/// <returns>Replaced with color changes</returns>
public static string Beautify(string text)
{
const string blizz = "dodgerblue1";
const string less = "deepskyblue2";
const string diablo = "red3_1";
const string d3 = "red";
const string sql = "underline dodgerblue1";
const string discord = "underline blue";
const string notNull = "green";
const string @null = "underline red";
const string unkNull = "underline yellow";
return text
.Replace("Blizzless", $"[{blizz}]Blizz[/][{less}]less[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("Diablo III", $"[{diablo}]Diablo[/] [{d3}]III[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace(@"D3\.", $"[{diablo}]D[/][{d3}]3[/]", StringComparison.CurrentCultureIgnoreCase) //D3.*
.Replace("SQL", $"[{sql}]SQL[/]")
.Replace("Discord", $"[{discord}]Discord[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace("null", $"[{unkNull}]null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace($"not [{unkNull}]null[/]", $"[{notNull}]is not null[/]", StringComparison.CurrentCultureIgnoreCase)
.Replace($"is [{unkNull}]null[/]", $"[{@null}]is null[/]", StringComparison.CurrentCultureIgnoreCase);
}
/// <summary>
/// Performs a cleanup on the target.
/// All [ becomes [[, and ] becomes ]] (for ignoring ANSI codes)
/// To use a style, use $[..]$abc$[/]$.
/// Example:
/// Logger.Warn("This is a $[red]$red$[/]$ message");
/// instead of
/// Logger.Warn("This is a [red]red[/] message");
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
string Cleanup(string x) => Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
public override void LogMessage(Logger.Level level, string logger, string message)
{
if (CancellationTokenSource.IsCancellationRequested)
return;
try
{
if (IncludeTimeStamps)
_table.AddRow(
new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup("", new Style(foreground: Color.Green3_1)).Centered());
else
_table.AddRow(
new Markup(level.ToString()).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup("", new Style(foreground: Color.Green3_1)).Centered());
}
catch (Exception ex)
{
var regex = new Regex(@"\$\[.*?\]\$");
var matches = regex.Matches(message);
foreach (Match match in matches)
{
message = message.Replace(match.Value, "");
}
if (IncludeTimeStamps)
{
_table.AddRow(
new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup(ex.Message, new Style(foreground: Color.Red3_1)).Centered());
}
else
{
_table.AddRow(
new Markup(level.ToString()).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup(ex.Message, new Style(foreground: Color.Red3_1)).Centered());
}
}
}
public override void LogException(Logger.Level level, string logger, string message, Exception exception)
{
if (CancellationTokenSource.IsCancellationRequested)
return;
try
{
if (IncludeTimeStamps)
_table.AddRow(
new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup(
$"[underline red3_1 on white]{exception.GetType().Name}[/]\n" + Cleanup(exception.Message),
new Style(foreground: Color.Red3_1)).Centered());
else
_table.AddRow(
new Markup(level.ToString()).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(message, GetStyleByLevel(level)).LeftJustified(),
new Markup(
$"[underline red3_1 on white]{exception.GetType().Name}[/]\n" + Cleanup(exception.Message),
new Style(foreground: Color.Red3_1)).Centered());
}
catch (Exception ex)
{
var regex = new Regex(@"\$\[.*?\]\$");
var matches = regex.Matches(message);
foreach (Match match in matches)
{
message = message.Replace(match.Value, "");
}
if (IncludeTimeStamps)
{
_table.AddRow(
new Markup(DateTime.Now.ToString(TimeStampFormat), GetStyleByLevel(level)),
new Markup(level.ToString(), GetStyleByLevel(level)).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup(ex.Message, new Style(foreground: Color.Red3_1)).Centered());
}
else
{
_table.AddRow(
new Markup(level.ToString()).RightJustified(),
new Markup(logger, GetStyleByLevel(level)).LeftJustified(),
new Markup(Cleanup(message), GetStyleByLevel(level)).LeftJustified(),
new Markup(ex.Message, new Style(foreground: Color.Red3_1)).Centered());
}
}
}
private static Style GetStyleByLevel(Logger.Level level)
{
return level switch
{
Logger.Level.RenameAccountLog => new Style(Color.DarkSlateGray3),//
Logger.Level.ChatMessage => new Style(Color.DarkSlateGray2),//
Logger.Level.Debug => new Style(Color.Olive),//
Logger.Level.MethodTrace => new Style(Color.DarkOliveGreen1_1),//
Logger.Level.Trace => new Style(Color.BlueViolet),//
Logger.Level.Info => new Style(Color.White),
Logger.Level.Success => new Style(Color.Green3_1),
Logger.Level.Warn => new Style(Color.Yellow),//
Logger.Level.Error => new Style(Color.IndianRed1),//
Logger.Level.Fatal => new Style(Color.Red3_1),//
Logger.Level.PacketDump => new Style(Color.Maroon),//
_ => new Style(Color.White)
};
}
}
public static class AnsiTargetExtensions
{
public static string SafeAnsi(this string text)
{
return text.Replace("$[", "").Replace("]$", "").Replace("[", "[[").Replace("]", "]]");
}
}

View File

@ -1,6 +1,8 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Spectre.Console;
namespace DiIiS_NA.Core.Logging
{
@ -9,21 +11,22 @@ namespace DiIiS_NA.Core.Logging
/// <param name="minLevel">Minimum level of messages to emit</param>
/// <param name="maxLevel">Maximum level of messages to emit</param>
/// <param name="includeTimeStamps">Include timestamps in log?</param>
public ConsoleTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps)
public ConsoleTarget(Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat)
{
MinimumLevel = minLevel;
MaximumLevel = maxLevel;
this.IncludeTimeStamps = includeTimeStamps;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
}
/// <param name="level">Log level.</param>
/// <param name="logger">Source of the log message.</param>
/// <param name="message">Log message.</param>
public override void LogMessage(Logger.Level level, string logger, string message)
{
var timeStamp = this.IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
SetConsoleForegroundColor(level);
Console.WriteLine(string.Format("{0}[{1}] [{2}]: {3}", timeStamp, level.ToString().PadLeft(5), logger, message));
var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString(TimeStampFormat) + "]] " : "";
AnsiConsole.MarkupLine($"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/]");
}
/// <param name="level">Log level.</param>
@ -32,37 +35,52 @@ namespace DiIiS_NA.Core.Logging
/// <param name="exception">Exception to be included with log message.</param>
public override void LogException(Logger.Level level, string logger, string message, Exception exception)
{
var timeStamp = this.IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
SetConsoleForegroundColor(level);
Console.WriteLine(string.Format("{0}[{1}] [{2}]: {3} - [Exception] {4}", timeStamp, level.ToString().PadLeft(5), logger, message, exception));
var timeStamp = IncludeTimeStamps ? "[[" + DateTime.Now.ToString(TimeStampFormat) + "]] " : "";
AnsiConsole.MarkupLine(
$"{timeStamp}{SetColor(level, true)}[[{level.ToString(),8}]][/] {SetColor(level)}[[{Cleanup(logger),20}]]: {Cleanup(message)}[/] - [underline red on white][[{exception.GetType().Name}]][/][red] {Cleanup(exception.Message)}[/]");
AnsiConsole.WriteException(exception);
}
/// <summary>
/// Performs a cleanup on the target.
/// All [ becomes [[, and ] becomes ]] (for ignoring ANSI codes)
/// To use a style, use $[..]$abc$[/]$.
/// Example:
/// Logger.Warn("This is a $[red]$red$[/]$ message");
/// instead of
/// Logger.Warn("This is a [red]red[/] message");
/// </summary>
/// <param name="x"></param>
/// <returns></returns>
string Cleanup(string x) => AnsiTarget.Beautify(x.Replace("[", "[[").Replace("]", "]]").Replace("$[[/]]$", "[/]").Replace("$[[", "[").Replace("]]$", "]"));
/// <param name="level"></param>
private static void SetConsoleForegroundColor(Logger.Level level)
private static string SetColor(Logger.Level level, bool withBackground = false)
{
string postfix = withBackground ? " on grey19" : "";
switch (level)
{
case Logger.Level.Trace:
case Logger.Level.PacketDump:
Console.ForegroundColor = ConsoleColor.DarkGray;
break;
return $"[grey30{postfix}]";
case Logger.Level.Debug:
Console.ForegroundColor = ConsoleColor.Cyan;
break;
return $"[grey39{postfix}]";
case Logger.Level.Trace:
return $"[purple{postfix}]";
case Logger.Level.Info:
Console.ForegroundColor = ConsoleColor.White;
break;
return $"[white{postfix}]";
case Logger.Level.Success:
return $"[green3_1{postfix}]";
case Logger.Level.Warn:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
return $"[darkorange3_1{postfix}]";
case Logger.Level.Error:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
return $"[indianred1{postfix}]";
case Logger.Level.Fatal:
Console.ForegroundColor = ConsoleColor.Red;
break;
return $"[red3{postfix}]";
default:
break;
return $"[navajowhite3{postfix}]";
}
}
}

View File

@ -1,11 +1,7 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.IO;
//Blizzless Project 2022
using System.Text.RegularExpressions;
using System.Threading;
namespace DiIiS_NA.Core.Logging
@ -26,50 +22,58 @@ namespace DiIiS_NA.Core.Logging
/// <param name="maxLevel">Maximum level of messages to emit</param>
/// <param name="includeTimeStamps">Include timestamps in log?</param>
/// <param name="reset">Reset log file on application startup?</param>
public FileTarget(string fileName, Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, bool reset = false)
public FileTarget(string fileName, Logger.Level minLevel, Logger.Level maxLevel, bool includeTimeStamps, string timeStampFormat, bool reset = false)
{
this.MinimumLevel = minLevel;
this.MaximumLevel = maxLevel;
this.IncludeTimeStamps = includeTimeStamps;
this._fileName = fileName;
this._fileTimestamp = DateTime.Now.ToString("yyyyMMdd_HHmm");
this._filePath = string.Format("{0}/{1}/{2}", LogConfig.Instance.LoggingRoot, this._fileTimestamp, _fileName);
this._fileIndex = 0;
MinimumLevel = minLevel;
MaximumLevel = maxLevel;
IncludeTimeStamps = includeTimeStamps;
TimeStampFormat = timeStampFormat;
_fileName = fileName;
_fileTimestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm");
_filePath = $"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}/{_fileName}";
_fileIndex = 0;
if (!Directory.Exists(LogConfig.Instance.LoggingRoot)) // create logging directory if it does not exist yet.
Directory.CreateDirectory(LogConfig.Instance.LoggingRoot);
if (!Directory.Exists(string.Format("{0}/{1}", LogConfig.Instance.LoggingRoot, this._fileTimestamp))) // create logging directory if it does not exist yet.
Directory.CreateDirectory(string.Format("{0}/{1}", LogConfig.Instance.LoggingRoot, this._fileTimestamp));
if (!Directory.Exists($"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}")) // create logging directory if it does not exist yet.
Directory.CreateDirectory($"{LogConfig.Instance.LoggingRoot}/{_fileTimestamp}");
this._fileStream = new FileStream(_filePath, reset ? FileMode.Create : FileMode.Append, FileAccess.Write, FileShare.Read); // init the file stream.
this._logStream = new StreamWriter(this._fileStream) { AutoFlush = true }; // init the stream writer.
this.TaskQueue = new ConcurrentQueue<Action>();
this.LoggerThread = new Thread(this.CheckQueue) { Name = "Logger", IsBackground = true };
this.LoggerThread.Start();
_fileStream = new FileStream(_filePath, reset ? FileMode.Create : FileMode.Append, FileAccess.Write, FileShare.Read); // init the file stream.
_logStream = new StreamWriter(_fileStream) { AutoFlush = true }; // init the stream writer.
TaskQueue = new ConcurrentQueue<Action>();
LoggerThread = new Thread(CheckQueue) { Name = "Logger", IsBackground = true };
LoggerThread.Start();
}
public void CheckQueue()
{
while (true)
{
Action action = null;
if (this.TaskQueue.TryDequeue(out action))
if (TaskQueue.TryDequeue(out var action))
action.Invoke();
Thread.Sleep(1);
}
}
/// <summary>
/// Replace the colors from AnsiColor so they do not appear in the log file.
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
private string NoColors(string message) => Regex.Replace(message, @"\$\[\[?([\w\W\d\s_\-\/]+)\]\]?\$", "$1");
/// <param name="level">Log level.</param>
/// <param name="logger">Source of the log message.</param>
/// <param name="message">Log message.</param>
public override void LogMessage(Logger.Level level, string logger, string message)
{
this.TaskQueue.Enqueue(() =>
TaskQueue.Enqueue(() =>
{
var timeStamp = this.IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
if (!this._disposed) // make sure we're not disposed.
message = NoColors(message);
var timeStamp = IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
if (!_disposed) // make sure we're not disposed.
{
/*
if (this._fileStream.Length >= 20971520) //20 MB limit
@ -80,10 +84,9 @@ namespace DiIiS_NA.Core.Logging
this._logStream = new StreamWriter(this._fileStream) { AutoFlush = true }; // init the stream writer.
}
//*/
if (level > Logger.Level.ChatMessage)
this._logStream.WriteLine(string.Format("{0}[{1}] [{2}]: {3}", timeStamp, level.ToString().PadLeft(5), logger, message));
else
this._logStream.WriteLine(string.Format("{0}{1}", timeStamp, message));
_logStream.WriteLine(level > Logger.Level.ChatMessage
? $"{timeStamp}[{level.ToString(),5}] [{logger}]: {message}"
: $"{timeStamp}{message}");
}
});
}
@ -94,19 +97,14 @@ namespace DiIiS_NA.Core.Logging
/// <param name="exception">Exception to be included with log message.</param>
public override void LogException(Logger.Level level, string logger, string message, Exception exception)
{
this.TaskQueue.Enqueue(() =>
TaskQueue.Enqueue(() =>
{
var timeStamp = this.IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
if (!this._disposed) // make sure we're not disposed.
message = NoColors(message);
var timeStamp = IncludeTimeStamps ? "[" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff") + "] " : "";
if (!_disposed) // make sure we're not disposed.
{
if (this._fileStream.Length >= 20971520) //20 MB limit
{
System.IO.File.Move(this._filePath, string.Format("{0}.{1}", this._filePath, this._fileIndex));
this._fileIndex++;
this._fileStream = new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.Read); // init the file stream.
this._logStream = new StreamWriter(this._fileStream) { AutoFlush = true }; // init the stream writer.
}
this._logStream.WriteLine(string.Format("{0}[{1}] [{2}]: {3} - [Exception] {4}", timeStamp, level.ToString().PadLeft(5), logger, message, exception));
_logStream.WriteLine(
$"{timeStamp}[{level.ToString(),5}] [{logger}]: {message} - [Exception] {exception}");
}
});
}
@ -119,23 +117,23 @@ namespace DiIiS_NA.Core.Logging
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this); // Take object out the finalization queue to prevent finalization code for it from executing a second time.
GC.SuppressFinalize(this); // Take object out the finalization queue to prevent finalization code for it from executing (~FileTarget).
}
private void Dispose(bool disposing)
{
if (this._disposed) return; // if already disposed, just return
if (_disposed) return; // if already disposed, just return
if (disposing) // only dispose managed resources if we're called from directly or in-directly from user code.
{
this._logStream.Close();
this._logStream.Dispose();
this._fileStream.Close();
this._fileStream.Dispose();
_logStream.Close();
_logStream.Dispose();
_fileStream.Close();
_fileStream.Dispose();
}
this._logStream = null;
this._fileStream = null;
_logStream = null;
_fileStream = null;
_disposed = true;
}

View File

@ -1,75 +1,79 @@
//Blizzless Project 2022
namespace DiIiS_NA.Core.Logging
namespace DiIiS_NA.Core.Logging
{
public sealed class LogConfig : Config.Config
{
public string LoggingRoot
{
get { return this.GetString("Root", @"logs"); }
set { this.Set("Root", value); }
get => GetString("Root", @"logs");
set => Set("Root", value);
}
public LogTargetConfig[] Targets = new[]
public LogTargetConfig[] Targets { get; } = new[]
{
new LogTargetConfig("ConsoleLog"),
new LogTargetConfig("AnsiLog"),
//new LogTargetConfig("ServerLog"),
//new LogTargetConfig("ChatLog"),
//new LogTargetConfig("RenameAccountLog"),
//new LogTargetConfig("PacketLog")
new LogTargetConfig("PacketLog")
};
private LogConfig() :
base("Logging")
base(nameof(Logging))
{ }
public static LogConfig Instance { get { return _instance; } }
private static readonly LogConfig _instance = new LogConfig();
public static readonly LogConfig Instance = new();
}
public class LogTargetConfig : Config.Config
{
public bool Enabled
{
get { return this.GetBoolean("Enabled", true); }
set { this.Set("Enabled", value); }
get => GetBoolean(nameof(Enabled), true);
set => Set(nameof(Enabled), value);
}
public string Target
{
get { return this.GetString("Target", "Console"); }
set { this.GetString("Target", value); }
get => GetString(nameof(Target), "Console");
set => GetString(nameof(Target), value);
}
public bool IncludeTimeStamps
{
get { return this.GetBoolean("IncludeTimeStamps", false); }
set { this.Set("IncludeTimeStamps", value); }
get => GetBoolean(nameof(IncludeTimeStamps), false);
set => Set(nameof(IncludeTimeStamps), value);
}
public string FileName
{
get { return this.GetString("FileName", ""); }
set { this.GetString("FileName", value); }
get => GetString(nameof(FileName), "");
set => GetString(nameof(FileName), value);
}
public Logger.Level MinimumLevel
{
get { return (Logger.Level)(this.GetInt("MinimumLevel", (int)Logger.Level.Info, true)); }
set { this.Set("MinimumLevel", (int)value); }
get => (Logger.Level)(GetInt(nameof(MinimumLevel), (int)Logger.Level.Info, true));
set => Set(nameof(MinimumLevel), (int)value);
}
public Logger.Level MaximumLevel
{
get { return (Logger.Level)(this.GetInt("MaximumLevel", (int)Logger.Level.Fatal, true)); }
set { this.Set("MaximumLevel", (int)value); }
get => (Logger.Level)(GetInt(nameof(MaximumLevel), (int)Logger.Level.Fatal, true));
set => Set(nameof(MaximumLevel), (int)value);
}
public bool ResetOnStartup
{
get { return this.GetBoolean("ResetOnStartup", false); }
set { this.Set("ResetOnStartup", value); }
get => GetBoolean(nameof(ResetOnStartup), false);
set => Set(nameof(ResetOnStartup), value);
}
public LogTargetConfig(string loggerName)
: base(loggerName) { }
public string TimeStampFormat
{
get => GetString(nameof(TimeStampFormat), "dd/MM/yyyy HH:mm:ss");
set => Set(nameof(TimeStampFormat), value);
}
public LogTargetConfig(string loggerName) : base(loggerName) { }
}
}

View File

@ -1,9 +1,5 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Diagnostics;
namespace DiIiS_NA.Core.Logging
@ -18,12 +14,12 @@ namespace DiIiS_NA.Core.Logging
/// <summary>
/// Available & configured log targets.
/// </summary>
internal readonly static List<LogTarget> Targets = new List<LogTarget>();
internal static readonly List<LogTarget> Targets = new();
/// <summary>
/// Available loggers.
/// </summary>
internal static readonly Dictionary<string, Logger> Loggers = new Dictionary<string, Logger>();
internal readonly static Dictionary<string, Logger> Loggers = new();
/// <summary>
/// Creates and returns a logger named with declaring type.
@ -37,10 +33,7 @@ namespace DiIiS_NA.Core.Logging
if (name == null) // see if we got a name.
throw new Exception("Error getting full name for declaring type.");
if (!Loggers.ContainsKey(name)) // see if we already have instance for the given name.
Loggers.Add(name, new Logger(name)); // add it to dictionary of loggers.
return Loggers[name]; // return the newly created logger.
return CreateLogger(name); // return the newly created logger.
}
/// <summary>

View File

@ -1,7 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Linq;
namespace DiIiS_NA.Core.Logging
@ -19,7 +16,7 @@ namespace DiIiS_NA.Core.Logging
if (LogManager.Targets.Count == 0) // if we don't have any active log-targets,
{
var t = new FileTarget(@"log.txt", Logger.Level.PacketDump,
Logger.Level.PacketDump, false, true);
Logger.Level.PacketDump, false, "dd/MM/yyyy HH:mm:ss", true);
LogManager.Targets.Add(t);
}// return; // just skip

View File

@ -1,6 +1,4 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
using System;
namespace DiIiS_NA.Core.Logging
{
@ -9,6 +7,7 @@ namespace DiIiS_NA.Core.Logging
public Logger.Level MinimumLevel { get; protected set; }
public Logger.Level MaximumLevel { get; protected set; }
public bool IncludeTimeStamps { get; protected set; }
public string TimeStampFormat { get; protected set; }
public virtual void LogMessage(Logger.Level level, string logger, string message)
{

View File

@ -1,13 +1,11 @@
//Blizzless Project 2022
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Globalization;
//Blizzless Project 2022
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
//Blizzless Project 2022
using DiIiS_NA.Core.Extensions;
//Blizzless Project 2022
using DiIiS_NA.GameServer.MessageSystem;
namespace DiIiS_NA.Core.Logging
@ -16,7 +14,11 @@ namespace DiIiS_NA.Core.Logging
{
public string Name { get; protected set; }
/// <param name="name">Name of the logger.</param>
/// <summary>
/// A logger base type is used to create a logger instance.
/// E.g. ConsoleTarget, FileTarget, etc.
/// </summary>
/// <param name="name">Logger name</param>
public Logger(string name)
{
Name = name;
@ -25,80 +27,133 @@ namespace DiIiS_NA.Core.Logging
public enum Level
{
RenameAccountLog,
/// <summary>
/// Chat messages.
/// </summary>
ChatMessage,
BotCommand,
Trace,
/// <summary>
/// The messages meant for debugging purposes.
/// Shouldn't be shown in production as they are not meant for the end user.
/// </summary>
Debug,
/// <summary>
/// The messages meant for method call tracing.
/// </summary>
MethodTrace,
/// <summary>
/// The messages meant for tracing purposes.
/// Trace messages are rarer than debug messages and should be used for more precise tracing.
/// </summary>
Trace,
/// <summary>
/// Informational messages.
/// </summary>
Info,
/// <summary>
/// Success messages.
/// </summary>
Success,
/// <summary>
/// Warning messages.
/// </summary>
Warn,
/// <summary>
/// Error messages.
/// </summary>
Error,
/// <summary>
/// Fatal messages (usually unrecoverable errors that leads to client or server crashes).
/// </summary>
Fatal,
/// <summary>
/// Packet messages.
/// </summary>
PacketDump,
}
#region message loggers
/// <param name="message">The log message.</param>
public void ChatMessage(string message) { Log(Level.ChatMessage, message, null); }
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void ChatMessage(string message, params object[] args) { Log(Level.ChatMessage, message, args); }
public void ChatMessage(string message) => Log(Level.ChatMessage, message, null);
/// <param name="message">The log message.</param>
public void BotCommand(string message) { Log(Level.BotCommand, message, null); }
/// <param name="args">Additional arguments.</param>
public void ChatMessage(string message, params object[] args) => Log(Level.ChatMessage, message, args);
/// <param name="message">The log message.</param>
public void BotCommand(string message) => Log(Level.BotCommand, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void BotCommand(string message, params object[] args) { Log(Level.BotCommand, message, args); }
/// <param name="message">The log message.</param>
public void RenameAccount(string message) { Log(Level.RenameAccountLog, message, null); }
public void RenameAccount(string message) => Log(Level.RenameAccountLog, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void RenameAccount(string message, params object[] args) { Log(Level.RenameAccountLog, message, args); }
public void RenameAccount(string message, params object[] args) => Log(Level.RenameAccountLog, message, args);
/// <param name="message">The log message.</param>
public void Trace(string message) { Log(Level.Trace, message, null); }
public void Trace(string message) => Log(Level.Trace, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Trace(string message, params object[] args) { Log(Level.Trace, message, args); }
public void Trace(string message, params object[] args) => Log(Level.Trace, message, args);
/// <param name="message">The log message.</param>
public void Debug(string message) { Log(Level.Debug, message, null); }
public void MethodTrace(string message, [CallerMemberName] string methodName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
#if DEBUG
var fileName = Path.GetFileName(filePath);
Log(Level.MethodTrace, $"$[underline white]${fileName}:{lineNumber}$[/]$ $[darkolivegreen3_2]${methodName}()$[/]$: " + message, null);
#else
Log(Level.MethodTrace, $"$[darkolivegreen3_2]${methodName}()$[/]$: " + message, null);
#endif
}
/// <param name="message">The log message.</param>
public void Debug(string message) => Log(Level.Debug, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Debug(string message, params object[] args) { Log(Level.Debug, message, args); }
public void Debug(string message, params object[] args) => Log(Level.Debug, message, args);
/// <param name="message">The log message.</param>
public void Info(string message) { Log(Level.Info, message, null); }
public void Info(string message) => Log(Level.Info, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Info(string message, params object[] args) { Log(Level.Info, message, args); }
public void Info(string message, params object[] args) => Log(Level.Info, message, args);
/// <param name="message">The log message.</param>
public void Warn(string message) { Log(Level.Warn, message, null); }
public void Success(string message) => Log(Level.Success, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Warn(string message, params object[] args) { Log(Level.Warn, message, args); }
public void Success(string message, params object[] args) => Log(Level.Success, message, args);
/// <param name="message">The log message.</param>
public void Error(string message) { Log(Level.Error, message, null); }
public void Warn(string message) => Log(Level.Warn, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Error(string message, params object[] args) { Log(Level.Error, message, args); }
public void Warn(string message, params object[] args) => Log(Level.Warn, message, args);
/// <param name="message">The log message.</param>
public void Fatal(string message) { Log(Level.Fatal, message, null); }
public void Error(string message) => Log(Level.Error, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Fatal(string message, params object[] args) { Log(Level.Fatal, message, args); }
public void Error(string message, params object[] args) => Log(Level.Error, message, args);
/// <param name="message">The log message.</param>
public void Fatal(string message) => Log(Level.Fatal, message, null);
/// <param name="message">The log message.</param>
/// <param name="args">Additional arguments.</param>
public void Fatal(string message, params object[] args) => Log(Level.Fatal, message, args);
#endregion

View File

@ -1,13 +1,6 @@
//Blizzless Project 2022
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
//Blizzless Project 2022
using DiIiS_NA.GameServer.Core.Types.SNO;
//Blizzless Project 2022
//Blizzless Project 2022
using System;
 using DiIiS_NA.Core.Logging;
using DiIiS_NA.GameServer.Core.Types.SNO;
using System;
namespace DiIiS_NA.Core.MPQ
{

View File

@ -1,12 +1,7 @@
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
//Blizzless Project 2022
using DiIiS_NA.Core.Storage;
using DiIiS_NA.GameServer.Core.Types.SNO;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Globalization;
//Blizzless Project 2022
using System.Threading;
namespace DiIiS_NA.Core.MPQ

View File

@ -1,32 +1,31 @@
//Blizzless Project 2022
using CrystalMpq;
//Blizzless Project 2022
using CrystalMpq;
using DiIiS_NA.Core.Logging;
//Blizzless Project 2022
using DiIiS_NA.GameServer.Core.Types.SNO;
//Blizzless Project 2022
using Gibbed.IO;
//Blizzless Project 2022
using Microsoft.Data.Sqlite;
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System.Collections.Concurrent;
//Blizzless Project 2022
using System.Collections.Generic;
//Blizzless Project 2022
using System.IO;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Reflection;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
using DiIiS_NA.D3_GameServer.Core.Types.SNO;
using Spectre.Console;
namespace DiIiS_NA.Core.MPQ
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class SnoFileNameAttribute : Attribute
{
public string FileName { get; }
public SnoFileNameAttribute(string fileName)
{
FileName = fileName;
}
}
public class Data : MPQPatchChain
{
public Dictionary<SNOGroup, ConcurrentDictionary<int, Asset>> Assets = new Dictionary<SNOGroup, ConcurrentDictionary<int, Asset>>();
@ -68,12 +67,15 @@ namespace DiIiS_NA.Core.MPQ
#endregion
private static new readonly Logger Logger = LogManager.CreateLogger("DataBaseWorker");
private new static readonly Logger Logger = LogManager.CreateLogger("MPQWorker");
public Data()
//: base(0, new List<string> { "CoreData.mpq", "ClientData.mpq" }, "/base/d3-update-base-(?<version>.*?).mpq")
: base(0, new List<string> { "Core.mpq", "Core1.mpq", "Core2.mpq", "Core3.mpq", "Core4.mpq" }, "/base/d3-update-base-(?<version>.*?).mpq")
{ }
: base(0, new List<string> { "Core.mpq", "Core1.mpq", "Core2.mpq", "Core3.mpq", "Core4.mpq" },
"/base/d3-update-base-(?<version>.*?).mpq")
{
}
public void Init()
{
@ -137,8 +139,7 @@ namespace DiIiS_NA.Core.MPQ
string[] MyFiles = Directory.GetFiles(@"E:\\Unpacked\\2.7.1\\Rope\\", @"*", SearchOption.AllDirectories);
string writePath = @"E:\Unpacked\Rope.txt";
int i = 0;
//Blizzless Project 2022
using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding.Default))
using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding.Default))
{
foreach (var file in MyFiles)
@ -197,10 +198,57 @@ using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding
this.LoadSNODict(DictSNOTutorial, SNOGroup.Tutorial);
this.LoadSNODict(DictSNOWeathers, SNOGroup.Weather);
this.LoadSNODict(DictSNOWorlds, SNOGroup.Worlds);
this.LoadDBCatalog();
#if DEBUG
SnoBreakdown();
#endif
}
public void SnoBreakdown(bool fullBreakdown = false)
{
Console.WriteLine();
if (Program.IsTargetEnabled("ansi"))
Console.Clear();
var breakdownChart = new BreakdownChart()
.FullSize()
.AddItem("Actor", DictSNOActor.Count, Color.Blue)
.AddItem("Effect Group", DictSNOEffectGroup.Count, Color.Yellow)
.AddItem("Game Balance", DictSNOGameBalance.Count, Color.Cyan3)
.AddItem("Monster", DictSNOMonster.Count, Color.Red)
.AddItem("Power", DictSNOPower.Count, Color.LightPink1)
.AddItem("Quest", DictSNOQuest.Count, Color.Fuchsia)
.AddItem("Quest Range", DictSNOQuestRange.Count, Color.Magenta2_1)
.AddItem("Recipe", DictSNORecipe.Count, Color.Lime)
.AddItem("Scene", DictSNOScene.Count, Color.DarkOrange3);
if (fullBreakdown)
{
breakdownChart.AddItem("Accolade", DictSNOAccolade.Count, Color.Gold1)
.AddItem("Boss Encounter", DictSNOBossEncounter.Count, Color.Cornsilk1)
.AddItem("Act", DictSNOAct.Count, Color.IndianRed)
.AddItem("Adventure", DictSNOAdventure.Count, Color.Orange4_1)
.AddItem("Ambient Sound", DictSNOAmbientSound.Count, Color.OrangeRed1)
.AddItem("Animations", DictSNOAnim.Count, Color.Orchid)
.AddItem("Animation 2D", DictSNOAnimation2D.Count, Color.BlueViolet)
.AddItem("Animation Set", DictSNOAnimSet.Count, Color.LightGoldenrod1)
.AddItem("Conversation", DictSNOConversation.Count, Color.Aquamarine1_1)
.AddItem("Encounter", DictSNOEncounter.Count, Color.Green3_1)
.AddItem("Level Area", DictSNOLevelArea.Count, Color.Grey62)
.AddItem("Lore", DictSNOLore.Count, Color.Plum4)
.AddItem("Marker Set", DictSNOMarkerSet.Count, Color.Salmon1)
.AddItem("Music", DictSNOMusic.Count, Color.Olive)
.AddItem("Observer", DictSNOObserver.Count, Color.Violet)
.AddItem("Phys Mesh", DictSNOPhysMesh.Count, Color.CornflowerBlue)
.AddItem("Ropes", DictSNORopes.Count, Color.Yellow2)
.AddItem("Skill Kit", DictSNOSkillKit.Count, Color.DeepPink4_1)
.AddItem("Tutorial", DictSNOTutorial.Count, Color.NavajoWhite3)
.AddItem("Weather", DictSNOWeathers.Count, Color.Navy)
.AddItem("Worlds", DictSNOWorlds.Count, Color.SlateBlue3_1);
}
AnsiConsole.Write(breakdownChart);
Console.WriteLine();
}
private void LoadSNODict(Dictionary<string, int> DictSNO, SNOGroup group)
{
foreach (var point in DictSNO)
@ -279,8 +327,7 @@ using (StreamWriter sw = new StreamWriter(writePath, false, System.Text.Encoding
int assetCount = 0;
var timerStart = DateTime.Now;
//Blizzless Project 2022
using (var cmd = new SqliteCommand("SELECT * FROM TOC", Storage.DBManager.MPQMirror))
using (var cmd = new SqliteCommand("SELECT * FROM TOC", Storage.DBManager.MPQMirror))
{
var itemReader = cmd.ExecuteReader();

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +1,7 @@
//Blizzless Project 2022
using System;
//Blizzless Project 2022
using System;
using System.Collections.Generic;
//Blizzless Project 2022
using System.Linq;
//Blizzless Project 2022
using System.Text;
//Blizzless Project 2022
using System.Threading.Tasks;
namespace DiIiS_NA.Core.MPQ

Some files were not shown because too many files have changed in this diff Show More