Compare commits

..

51 Commits

Author SHA1 Message Date
beu
787964a8ed improve logging 2025-06-22 19:59:01 +02:00
beu
af10e1678a bump version 2025-06-22 19:56:53 +02:00
beu
33cc10b6c1 fix non-blocking errors 2025-06-22 19:38:50 +02:00
beu
5d2c6c4627 bump version 2025-06-22 19:30:51 +02:00
beu
36280769bb add logging 2025-06-22 19:30:16 +02:00
beu
803b58eb08 improving logging 2025-06-22 19:23:33 +02:00
beu
6928fe2ce2 fix php 8.4 compatibility 2025-06-22 18:58:00 +02:00
beu
8d01340d22 fix missing management of loading and unloading plugins 2025-06-22 18:57:33 +02:00
beu
6887384578 fix php 8.4 compatibility + improve logging / chat messages 2025-06-22 18:57:12 +02:00
beu
f8c8ff6269 move chat prefix as constant 2025-06-22 18:15:58 +02:00
beu
0352d96fdf fix match score saving after an error when launching 2025-06-22 17:57:07 +02:00
beu
ebecb7da73 improve logging 2025-06-22 17:54:17 +02:00
beu
9efa66ac5d improve logging 2025-06-22 11:52:48 +02:00
beu
0fe9dc3e14 prevent crash when no settings 2025-06-22 00:13:46 +02:00
beu
8e632d5057 change default message 2025-03-31 15:35:06 +02:00
beu
7a6fdebc67 fix setteampoints command 2025-03-31 15:34:41 +02:00
beu
ea877c9cae add eCM plugin 2025-03-27 15:33:58 +01:00
beu
a8069ad874 add Fast Kick plugin 2025-03-21 11:55:27 +01:00
beu
9fda8274b4 prevent sending data when sheetname is empty 2025-03-20 22:43:56 +01:00
beu
5d92ce5900 fix loading and removing configs 2025-03-20 18:05:50 +01:00
beu
986db202d8 fix description 2025-03-17 23:40:37 +01:00
beu
c2b5f1bfec fix error when getting listener class on php 7 2025-03-17 23:30:38 +01:00
beu
b82dbe771b remove colorize property 2025-03-17 22:45:12 +01:00
beu
971238ed8b bump version 2025-03-16 16:39:55 +01:00
beu
a7e40750f4 use chatprefix function from match manager core 2025-03-16 16:36:13 +01:00
beu
365d2ffbce remove debug log 2025-03-16 10:52:45 +01:00
beu
08faf3157d change z-index 2025-03-15 23:46:42 +01:00
beu
f538c31d8e fix double callback when player join 2025-03-15 23:46:01 +01:00
beu
9b4073f456 improve custom gamemode settings detection 2025-03-15 23:44:25 +01:00
beu
0e47b75e3d fix missing break 2025-03-15 22:00:39 +01:00
beu
66cd4a8430 prevent to trigger pause twice 2025-03-15 14:10:48 +01:00
beu
ab36a5b20e fix permission check 2025-03-15 13:15:19 +01:00
beu
d44aa97759 Add TMWT Duo Integration 2025-03-15 13:14:43 +01:00
beu
44bc21f3d1 separate setpoints command for teams 2025-03-15 13:13:43 +01:00
beu
46c26d70a5 completely rework Admin UI plugin 2025-03-15 13:00:53 +01:00
beu
ac76a326bf remove log 2025-03-15 12:31:52 +01:00
beu
abe85dc9e8 remove log 2025-03-15 12:31:32 +01:00
beu
30474b32e7 fix variable name 2025-03-15 12:31:25 +01:00
beu
b2fbbb1f98 use new chatprefix command 2025-03-15 12:19:24 +01:00
beu
18ea56e1c0 add code in query parameter 2025-03-15 12:18:34 +01:00
beu
3cda510834 improve error logging 2025-03-15 12:18:23 +01:00
beu
fb48d5f661 add canStartMatch function and callables 2025-03-14 22:58:10 +01:00
beu
d604c3f3fc add getChatPrefix function 2025-03-14 22:57:02 +01:00
beu
58dd834c9b remove skipround property 2025-03-13 15:58:57 +01:00
beu
9a9122ed0e change default parameter for the linter 2025-03-13 15:58:24 +01:00
beu
fe1f9b9c8b change default pause timer 2025-03-13 15:57:51 +01:00
beu
3eee022618 add markers comments 2025-03-13 15:57:39 +01:00
beu
d116abc4dc fix variable name 2025-02-22 00:19:21 +01:00
beu
f42e12e7a2 fix missing argument in the callback 2025-02-21 23:17:16 +01:00
beu
3bddeb2308 add support of map points and round points 2025-02-21 22:59:18 +01:00
beu
6a2b384648 add guestlist info commands 2025-02-21 22:43:15 +01:00
17 changed files with 3112 additions and 1200 deletions

3
.gitignore vendored
View File

@ -19,4 +19,5 @@
!Beu/ReloadDevTool.php !Beu/ReloadDevTool.php
!Beu/SimpleChatColorer.php !Beu/SimpleChatColorer.php
!Beu/SimpleSkinsRemover.php !Beu/SimpleSkinsRemover.php
!Beu/SmallTextOverlay.php !Beu/SmallTextOverlay.php
!Beu/FastKick.php

View File

@ -31,7 +31,7 @@ class BeuCustomConfig implements CallbackListener, Plugin {
* Constants * Constants
*/ */
const PLUGIN_ID = 193; const PLUGIN_ID = 193;
const PLUGIN_VERSION = 1.2; const PLUGIN_VERSION = 1.3;
const PLUGIN_NAME = 'BeuCustomConfig'; const PLUGIN_NAME = 'BeuCustomConfig';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -79,7 +79,7 @@ class BeuCustomConfig implements CallbackListener, Plugin {
* @see \ManiaControl\Plugins\Plugin::getDescription() * @see \ManiaControl\Plugins\Plugin::getDescription()
*/ */
public static function getDescription() { public static function getDescription() {
return "A plugin to display a donation button"; return "Default config for event servers";
} }
/** /**
@ -149,7 +149,7 @@ class BeuCustomConfig implements CallbackListener, Plugin {
]); ]);
} }
public function updateSettings(Setting $setting = null) { public function updateSettings(?Setting $setting = null) {
if ($setting !== null && $setting->belongsToClass($this)) { if ($setting !== null && $setting->belongsToClass($this)) {
$this->changeManiacontrolSettings(); $this->changeManiacontrolSettings();
} }

View File

@ -25,7 +25,7 @@ class BeuDonationButton implements ManialinkPageAnswerListener, CallbackListener
* Constants * Constants
*/ */
const PLUGIN_ID = 169; const PLUGIN_ID = 169;
const PLUGIN_VERSION = 1.0; const PLUGIN_VERSION = 1.1;
const PLUGIN_NAME = 'Beu Donation Button'; const PLUGIN_NAME = 'Beu Donation Button';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -103,7 +103,7 @@ class BeuDonationButton implements ManialinkPageAnswerListener, CallbackListener
$this->maniaControl->getManialinkManager()->sendManialink($this->manialink,$player->login); $this->maniaControl->getManialinkManager()->sendManialink($this->manialink,$player->login);
} }
public function updateSettings(Setting $setting = null) { public function updateSettings(?Setting $setting = null) {
$this->generateManialink(); $this->generateManialink();
$this->maniaControl->getManialinkManager()->sendManialink($this->manialink); $this->maniaControl->getManialinkManager()->sendManialink($this->manialink);
} }

239
Beu/FastKick.php Normal file
View File

@ -0,0 +1,239 @@
<?php
namespace Beu;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerActions;
use ManiaControl\Plugins\Plugin;
use ManiaControl\Commands\CommandListener;
use FML\Controls\Frame;
use FML\Controls\Label;
use FML\Controls\Quad;
use FML\Controls\Quads\Quad_Icons64x64_1;
use FML\ManiaLink;
/**
* Beu Donation Button
*
* @author Beu
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class FastKick implements ManialinkPageAnswerListener, CommandListener, Plugin {
/*
* MARK: Constants
*/
const PLUGIN_ID = 212;
const PLUGIN_VERSION = 1.0;
const PLUGIN_NAME = 'Fast Kick';
const PLUGIN_AUTHOR = 'Beu';
const MANIALINK_ID = 'FastKick::MainWindow';
const ACTION_CLOSE = 'FastKick::close';
const ACTION_KICK = 'FastKick::kick';
/*
* MARK: Private properties
*/
private ManiaControl $maniaControl;
/*
* MARK: Functions
*/
/**
* @see \ManiaControl\Plugins\Plugin::prepare()
*/
public static function prepare(ManiaControl $maniaControl) {
}
/**
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::PLUGIN_ID;
}
/**
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return self::PLUGIN_NAME;
}
/**
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::PLUGIN_VERSION;
}
/**
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return self::PLUGIN_AUTHOR;
}
/**
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return "Quick plugin to kick player easily using //fk command by matching the nearest name";
}
/**
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
$this->maniaControl->getCommandManager()->registerCommandListener(['fkick', 'fk', 'fastkick'], $this, 'handleFastKick', true);
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ACTION_CLOSE, $this, 'handleClose');
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerRegexListener('/^'. self::ACTION_KICK .'/', $this, 'handleKick');
}
/**
* handle Fast Kick command
*
* @param array $structure
* @param Player $adminPlayer
* @return void
*/
public function handleFastKick(array $structure, Player $adminPlayer) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($adminPlayer, PlayerActions::SETTING_PERMISSION_KICK_PLAYER)) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($adminPlayer);
return;
}
$params = explode(' ', $structure[1][2], 3);
if (count($params) <= 1 || $params[1] === '') {
$message = $this->maniaControl->getChat()->formatMessage(
'No player name given! Example: %s',
$params[0] .' <player name>'
);
$this->maniaControl->getChat()->sendUsageInfo($message, $adminPlayer);
return;
}
$target = $params[1];
$players = $this->maniaControl->getPlayerManager()->getPlayers();
$indexedList = [];
foreach ($players as $player) {
similar_text($target, $player->nickname, $percent);
$indexedList[intval($percent)][] = $player;
}
krsort($indexedList);
$manialink = new ManiaLink(self::MANIALINK_ID);
$parentFrame = new Frame();
$manialink->addChild($parentFrame);
$parentFrame->setPosition(-150., -35., 100.);
$background = new Quad();
$parentFrame->addChild($background);
$background->setHorizontalAlign(Quad::LEFT);
$background->setVerticalAlign(Quad::TOP);
$background->setBackgroundColor('000000');
$background->setOpacity(0.7);
$background->setSize(60., 25.);
$background->setZ(-1.);
$closeButton = new Quad_Icons64x64_1();
$parentFrame->addChild($closeButton);
$closeButton->setPosition(58., -2.);
$closeButton->setSize(6, 6);
$closeButton->setSubStyle($closeButton::SUBSTYLE_QuitRace);
$closeButton->setAction(self::ACTION_CLOSE);
$headerName = new Label();
$parentFrame->addChild($headerName);
$headerName->setPosition(1., -3);
$headerName->setHorizontalAlign($headerName::LEFT);
$headerName->setTextFont('GameFontExtraBold');
$headerName->setTextColor('ffffff');
$headerName->setTextSize(1.5);
$headerName->setText('Player Name');
$headerMatching = new Label();
$parentFrame->addChild($headerMatching);
$headerMatching->setPosition(40., -3);
$headerMatching->setHorizontalAlign($headerMatching::CENTER);
$headerMatching->setTextFont('GameFontExtraBold');
$headerMatching->setTextColor('ffffff');
$headerMatching->setTextSize(1.5);
$headerMatching->setText('Matching');
$count = 1;
$posY = -7.;
foreach ($indexedList as $percent => $players) {
foreach ($players as $player) {
$frame = new Frame();
$parentFrame->addChild($frame);
$frame->setY($posY);
$name = new Label();
$frame->addChild($name);
$name->setX(1.5);
$name->setSize(30., 3.5);
$name->setHorizontalAlign($name::LEFT);
$name->setTextFont('GameFontSemiBold');
$name->setTextColor('ffffff');
$name->setTextSize(1.2);
$name->setText($player->nickname);
$matching = new Label();
$frame->addChild($matching);
$matching->setX(40.);
$matching->setHorizontalAlign($name::CENTER);
$matching->setTextFont('GameFontSemiBold');
$matching->setTextColor('ffffff');
$matching->setTextSize(1.2);
$matching->setText($percent . '%');
$kickButton = new Quad();
$frame->addChild($kickButton);
$kickButton->setX(57.);
$kickButton->setSize(4, 4);
$kickButton->setStyle('UICommon64_2');
$kickButton->setSubStyle('UserDelete_light');
$kickButton->setAction(self::ACTION_KICK . '.' . $player->login);
$posY += -3.8;
$count++;
if ($count > 5) break 2;
}
}
$this->maniaControl->getManialinkManager()->sendManialink($manialink, $adminPlayer, ToggleUIFeature: false);
}
public function handleClose(array $structure, Player $adminPlayer) {
$this->maniaControl->getManialinkManager()->hideManialink(self::MANIALINK_ID, $adminPlayer);
}
public function handleKick(array $structure, Player $adminPlayer) {
if (!$this->maniaControl->getAuthenticationManager()->checkPermission($adminPlayer, PlayerActions::SETTING_PERMISSION_KICK_PLAYER)) {
$this->maniaControl->getAuthenticationManager()->sendNotAllowed($adminPlayer);
return;
}
$targetLogin = explode('.', $structure[1][2])[1];
$targetPlayer = $this->maniaControl->getPlayerManager()->getPlayer($targetLogin);
Logger::log("========================= Fast kick info: ====");
Logger::log(json_encode($targetPlayer));
Logger::log(json_encode($this->maniaControl->getClient()->getNetworkStats()));
$this->maniaControl->getPlayerManager()->getPlayerActions()->kickPlayer($adminPlayer, $targetLogin);
$this->maniaControl->getManialinkManager()->hideManialink(self::MANIALINK_ID, $adminPlayer);
}
/**
* Unload the plugin and its Resources
*/
public function unload() {}
}

View File

@ -23,7 +23,7 @@ class GuestlistManager implements CommandListener, CallbackListener, TimerListen
* Constants * Constants
*/ */
const PLUGIN_ID = 154; const PLUGIN_ID = 154;
const PLUGIN_VERSION = 2.0; const PLUGIN_VERSION = 2.3;
const PLUGIN_NAME = 'Guestlist Manager'; const PLUGIN_NAME = 'Guestlist Manager';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -100,6 +100,9 @@ class GuestlistManager implements CommandListener, CallbackListener, TimerListen
$this->maniaControl->getCommandManager()->registerCommandListener(['glload', 'loadgl'], $this, 'handleLoad', true, 'Load the guestlist file'); $this->maniaControl->getCommandManager()->registerCommandListener(['glload', 'loadgl'], $this, 'handleLoad', true, 'Load the guestlist file');
$this->maniaControl->getCommandManager()->registerCommandListener(['glclear', 'glclean', 'cleangl'], $this, 'handleClear', true, 'Clear the guestlist'); $this->maniaControl->getCommandManager()->registerCommandListener(['glclear', 'glclean', 'cleangl'], $this, 'handleClear', true, 'Clear the guestlist');
$this->maniaControl->getCommandManager()->registerCommandListener(['glkickall'], $this, 'handleKickAll', true, 'Kick non-guestlisted players'); $this->maniaControl->getCommandManager()->registerCommandListener(['glkickall'], $this, 'handleKickAll', true, 'Kick non-guestlisted players');
$this->maniaControl->getCommandManager()->registerCommandListener(['glinfo'], $this, 'handleInfo', true, 'Get guestlist info');
$this->maniaControl->getCommandManager()->registerCommandListener(['gllist'], $this, 'handleList', true, 'List all guestlisted players');
$this->maniaControl->getCallbackManager()->registerCallbackListener(AuthenticationManager::CB_AUTH_LEVEL_CHANGED, $this, 'handleAuthLevelChanged'); $this->maniaControl->getCallbackManager()->registerCallbackListener(AuthenticationManager::CB_AUTH_LEVEL_CHANGED, $this, 'handleAuthLevelChanged');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect'); $this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
@ -409,6 +412,119 @@ class GuestlistManager implements CommandListener, CallbackListener, TimerListen
$this->maniaControl->getChat()->sendSuccess($kicked . ' players kicked', $player); $this->maniaControl->getChat()->sendSuccess($kicked . ' players kicked', $player);
} }
/**
* handle Info command
*
* @param array $chat
* @param \ManiaControl\Players\Player $adminplayer
*/
public function handleInfo(Array $chat, Player $adminplayer) {
$guests = array_column($this->maniaControl->getClient()->getGuestList(), 'login');
$players = $this->maniaControl->getPlayerManager()->getPlayers(true);
$spectators = $this->maniaControl->getPlayerManager()->getSpectators();
$nbPlayersConnected = 0;
$nbSpectatorsConnected = 0;
$nbSpectatorsConnected = 0;
$nbPerRole[0] = 0;
$nbPerRoleConnected[0] = 0;
foreach ($guests as $login) {
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if ($player === null) {
$nbPerRole[0]++;
} else {
$players = array_filter($players, function($obj) use ($player) {
return $obj !== $player;
});
$spectators = array_filter($spectators, function($obj) use ($player) {
return $obj !== $player;
});
if (!array_key_exists($player->authLevel, $nbPerRole)) {
$nbPerRole[$player->authLevel] = 0;
$nbPerRoleConnected[$player->authLevel] = 0;
}
$nbPerRole[$player->authLevel]++;
if ($player->isConnected) {
$nbPerRoleConnected[$player->authLevel]++;
if ($player->isSpectator) $nbSpectatorsConnected++;
else $nbPlayersConnected++;
}
}
}
$message = '================ Guestlist info ================';
$message .= PHP_EOL . '$<$ee0' . count($guests) . '$> guests in the guestlist. Type //gllist to get the list';
$message .= PHP_EOL . '====== Connected on the server:';
$message .= PHP_EOL . 'Guestlisted: $<$ee0'. $nbPlayersConnected . '$> players - $<$ee0'. $nbSpectatorsConnected .'$> spectators';
$message .= PHP_EOL . 'Not guestlisted: $<$ee0'. count($players) . '$> players - $<$ee0'. count($spectators) .'$> spectators';
$message .= PHP_EOL . '====== Per role:';
ksort($nbPerRole);
ksort($nbPerRoleConnected);
$part1 = PHP_EOL . 'Connected: ';
$part2 = PHP_EOL . 'Disconnected: ';
foreach ($nbPerRole as $authLevel => $count) {
$part1 .= '$<$ee0'. $nbPerRoleConnected[$authLevel] .'$> '. $this->maniaControl->getAuthenticationManager()->getAuthLevelName($authLevel) .'s - ';
$part2 .= '$<$ee0'. $count - $nbPerRoleConnected[$authLevel] .'$> '. $this->maniaControl->getAuthenticationManager()->getAuthLevelName($authLevel) .'s - ';
}
$message .= substr($part1, 0, -3) . substr($part2, 0, -3);
$this->maniaControl->getChat()->sendSuccess($message, $adminplayer);
}
/**
* handle List command
*
* @param array $chat
* @param \ManiaControl\Players\Player $adminplayer
*/
public function handleList(Array $chat, Player $adminplayer) {
$guests = array_column($this->maniaControl->getClient()->getGuestList(), 'login');
$logins = [];
$names = [];
$connectedNames = [];
foreach ($guests as $login) {
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if ($player === null || $player->nickname === '') {
$logins[] = $login;
} else {
$names[] = $player->nickname;
if ($player->isConnected) {
$connectedNames[] = $player->nickname;
}
}
}
natcasesort($logins);
natcasesort($names);
$message = '================ Guestlist list ================'. PHP_EOL;
$message .= '====== Known players:'. PHP_EOL;
foreach ($names as $name) {
if (in_array($name, $connectedNames)) {
$message .= '$<$1c0' . $name . '$> ';
} else {
$message .= '$<$c00' . $name . '$> ';
}
}
$message .= PHP_EOL .'====== Unknown players:'. PHP_EOL;
foreach ($logins as $login) {
$message .= '$<$c00' . $login . '$> ';
}
$this->maniaControl->getChat()->sendSuccess($message, $adminplayer);
}
/** /**
* Kick non-guestlist players from the server * Kick non-guestlist players from the server
* *
@ -440,9 +556,10 @@ class GuestlistManager implements CommandListener, CallbackListener, TimerListen
if (!$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADD_ADMINS)) return; if (!$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADD_ADMINS)) return;
$guestlist = $this->maniaControl->getClient()->getGuestList(); $guestlist = $this->maniaControl->getClient()->getGuestList();
$authLevel = $this->maniaControl->getAuthenticationManager()->getAuthLevelInt($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL));
$admins = $this->maniaControl->getAuthenticationManager()->getAdmins($authLevel);
foreach ($this->maniaControl->getAuthenticationManager()->getAdmins() as $admin) { foreach ($admins as $admin) {
if ($this->maniaControl->getAuthenticationManager()->checkRight($admin, $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL))) continue;
$this->addLoginToGL($admin->login, $guestlist); $this->addLoginToGL($admin->login, $guestlist);
} }
} }
@ -458,7 +575,8 @@ class GuestlistManager implements CommandListener, CallbackListener, TimerListen
$guestlist = $this->maniaControl->getClient()->getGuestList(); $guestlist = $this->maniaControl->getClient()->getGuestList();
$isGuestlisted = in_array($player->login, array_column($guestlist, 'login')); $isGuestlisted = in_array($player->login, array_column($guestlist, 'login'));
$isAdmin = $this->maniaControl->getAuthenticationManager()->checkRight($player,$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL)); $authLevel = $this->maniaControl->getAuthenticationManager()->getAuthLevelInt($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL));
$isAdmin = $this->maniaControl->getAuthenticationManager()->checkRight($player, $authLevel);
if (!$isGuestlisted && $isAdmin) { if (!$isGuestlisted && $isAdmin) {
$this->addLoginToGL($player->login, $guestlist); $this->addLoginToGL($player->login, $guestlist);

View File

@ -20,7 +20,7 @@ class MoreModesTools implements CommandListener, Plugin {
* Constants * Constants
*/ */
const PLUGIN_ID = 164; const PLUGIN_ID = 164;
const PLUGIN_VERSION = 1.1; const PLUGIN_VERSION = 1.3;
const PLUGIN_NAME = 'MoreModesTools'; const PLUGIN_NAME = 'MoreModesTools';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -82,7 +82,8 @@ class MoreModesTools implements CommandListener, Plugin {
$this->maniaControl->getCommandManager()->registerCommandListener('endround', $this, 'onCommandEndRound', true, 'End the round'); $this->maniaControl->getCommandManager()->registerCommandListener('endround', $this, 'onCommandEndRound', true, 'End the round');
$this->maniaControl->getCommandManager()->registerCommandListener(['endwu', 'endwarmup'], $this, 'onCommandEndWarmUp', true, 'End the WarmUp'); $this->maniaControl->getCommandManager()->registerCommandListener(['endwu', 'endwarmup'], $this, 'onCommandEndWarmUp', true, 'End the WarmUp');
$this->maniaControl->getCommandManager()->registerCommandListener(['extendwu', 'extendwarmup'], $this, 'onCommandExtendWarmUp', true, 'If the warm up has a time limit, increase it'); $this->maniaControl->getCommandManager()->registerCommandListener(['extendwu', 'extendwarmup'], $this, 'onCommandExtendWarmUp', true, 'If the warm up has a time limit, increase it');
$this->maniaControl->getCommandManager()->registerCommandListener('setpoints', $this, 'onCommandSetPoints', true, 'Set Points for a player or a team'); $this->maniaControl->getCommandManager()->registerCommandListener('setpoints', $this, 'onCommandSetPoints', true, 'Set Points for a player');
$this->maniaControl->getCommandManager()->registerCommandListener('setteampoints', $this, 'onCommandSetTeamPoints', true, 'Set Points for a team');
return true; return true;
} }
@ -147,7 +148,6 @@ class MoreModesTools implements CommandListener, Plugin {
$text = $chat[1][2]; $text = $chat[1][2];
$text = explode(" ", $text); $text = explode(" ", $text);
if (is_numeric($text[1])) { if (is_numeric($text[1])) {
var_dump($text[1]);
$this->maniaControl->getModeScriptEventManager()->triggerModeScriptEvent("Trackmania.WarmUp.Extend", [ strval(intval($text[1]) * 1000)]); $this->maniaControl->getModeScriptEventManager()->triggerModeScriptEvent("Trackmania.WarmUp.Extend", [ strval(intval($text[1]) * 1000)]);
$this->maniaControl->getChat()->sendSuccessToAdmins('Extend Warmup Sent'); $this->maniaControl->getChat()->sendSuccessToAdmins('Extend Warmup Sent');
} else { } else {
@ -156,60 +156,131 @@ class MoreModesTools implements CommandListener, Plugin {
} }
/** /**
* Send SetPoints * Command //setpoints for admin
* *
* @param array $chat * @param array $chatCallback
* @param \ManiaControl\Players\Player $player * @param \ManiaControl\Players\Player $player
*/ */
public function onCommandSetPoints(Array $chat, Player $player) { public function onCommandSetPoints(array $chatCallback, Player $adminplayer) {
$text = $chat[1][2]; $text = $chatCallback[1][2];
$text = explode(" ", $text); $text = explode(" ", $text);
if (isset($text[1]) && isset($text[2]) && is_numeric($text[2]) && $text[2] >= 0 ) { if (count($text) < 3) {
if (strcasecmp($text[1], "Blue") == 0 || $text[1] == "0") { $this->maniaControl->getChat()->sendError('Missing parameters. Eg: //setpoints <Player Name or Login> <Match points> <Map Points (optional)> <Round Points (optional)>', $adminplayer);
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints("0", "", $text[2], $text[2]); return;
$this->maniaControl->getChat()->sendSuccess('$<$00fBlue$> Team now has $<$ff0' . $text[2] . '$> points!'); }
} elseif (strcasecmp($text[1], "Red") == 0 || $text[1] == "1") {
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints("1", "", $text[2] , $text[2]); $target = $text[1];
$this->maniaControl->getChat()->sendSuccess('$<$f00Red$> Team now has $<$ff0' . $text[2] . '$> points!'); $matchpoints = $text[2];
} elseif (is_numeric($text[1])) {//TODO: add support of name of teams (need update from NADEO) $mappoints = '';
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints($text[1], "", $text[2] , $text[2]); $roundpoints = '';
$this->maniaControl->getChat()->sendSuccess('Team ' . $text[1] . ' now has $<$ff0' . $text[2] . '$> points!');
if (!is_numeric($matchpoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Match points', $adminplayer);
return;
}
if (isset($text[3])) {
$mappoints = $text[3];
if (!is_numeric($mappoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Map points', $adminplayer);
return;
}
}
if (isset($text[4])) {
$roundpoints = $text[4];
if (!is_numeric($roundpoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Round points', $adminplayer);
return;
}
}
$mysqli = $this->maniaControl->getDatabase()->getMysqli();
$stmt = $mysqli->prepare('SELECT login FROM `' . PlayerManager::TABLE_PLAYERS . '` WHERE nickname LIKE ?');
$stmt->bind_param('s', $target);
if (!$stmt->execute()) {
Logger::logError('Error executing MySQL query: '. $stmt->error);
}
$result = $stmt->get_result();
$array = mysqli_fetch_array($result);
if (isset($array[0])) {
$login = $array[0];
} elseif (strlen($target) == 22) {
$login = $target;
}
if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR);
}
if (isset($login)) {
$player = $this->maniaControl->getPlayerManager()->getPlayer($login,true);
if ($player) {
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaPlayerPoints($player, $roundpoints, $mappoints, $matchpoints);
$this->maniaControl->getChat()->sendSuccess('Player $<$ff0' . $player->nickname . '$> now has $<$ff0' . $matchpoints . '$> points!');
} else { } else {
$mysqli = $this->maniaControl->getDatabase()->getMysqli(); $this->maniaControl->getChat()->sendError('Player ' . $target . " isn't connected", $adminplayer);
$query = $mysqli->prepare('SELECT login FROM `' . PlayerManager::TABLE_PLAYERS . '` WHERE nickname LIKE ?');
$query->bind_param('s', $text[1]);
if (!$query->execute()) {
trigger_error('Error executing MySQL query: ' . $query->error);
return;
}
$result = $query->get_result();
$array = mysqli_fetch_array($result);
if (isset($array[0])) {
$login = $array[0];
} elseif (strlen($text[1]) == 22) {
$login = $text[1];
}
if ($mysqli->error) {
trigger_error($mysqli->error, E_USER_ERROR);
}
if (isset($login)) {
$playerpoints = $this->maniaControl->getPlayerManager()->getPlayer($login, true);
if ($player) {
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaPlayerPoints($playerpoints, "", "", $text[2]);
$this->maniaControl->getChat()->sendSuccess('Player $<$ff0' . $playerpoints->nickname . '$> now has $<$ff0' . $text[2] . '$> points!');
} else {
$this->maniaControl->getChat()->sendError('Player ' . $text[1] . " isn't connected", $player);
}
} else {
$this->maniaControl->getChat()->sendError('Player ' . $text[1] . " doesn't exist", $player);
}
} }
} else { } else {
$this->maniaControl->getChat()->sendError($this->chatprefix . 'Missing or invalid parameters', $player); $this->maniaControl->getChat()->sendError('Player ' . $target . " doesn't exist", $adminplayer);
}
}
/**
* Command //setteampoints for admin
*
* @param array $chatCallback
* @param Player $adminplayer
*/
public function onCommandSetTeamPoints(array $chatCallback, Player $adminplayer) {
$text = $chatCallback[1][2];
$text = explode(" ", $text);
if (count($text) < 3) {
$this->maniaControl->getChat()->sendError('Missing parameters. Eg: //setteampoints <Team Name or Id> <Match points> <Map Points (optional)> <Round Points (optional)>', $adminplayer);
return;
}
$target = $text[1];
$matchpoints = $text[2];
$mappoints = '';
$roundpoints = '';
if (!is_numeric($matchpoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Match points', $adminplayer);
return;
}
if (isset($text[3])) {
$mappoints = $text[3];
if (!is_numeric($mappoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Map points', $adminplayer);
return;
}
}
if (isset($text[4])) {
$roundpoints = $text[4];
if (!is_numeric($roundpoints)) {
$this->maniaControl->getChat()->sendError('Invalid argument: Round points', $adminplayer);
return;
}
}
if (strcasecmp($target, "Blue") == 0 || $target == "0") {
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints("0", $roundpoints, $mappoints, $matchpoints);
$this->maniaControl->getChat()->sendSuccess('$<$00fBlue$> Team now has $<$ff0' . $matchpoints . '$> points!');
} elseif (strcasecmp($target, "Red") == 0 || $target == "1") {
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints("1", $roundpoints, $mappoints, $matchpoints);
$this->maniaControl->getChat()->sendSuccess('$<$f00Red$> Team now has $<$ff0' . $matchpoints . '$> points!');
} elseif (is_numeric($target)) { //TODO: add support of name of teams (need update from NADEO)
$this->maniaControl->getModeScriptEventManager()->setTrackmaniaTeamPoints($target, $roundpoints, $mappoints, $matchpoints);
$this->maniaControl->getChat()->sendSuccess('Team ' . $target . ' now has $<$ff0' . $matchpoints . '$> points!');
} else {
$this->maniaControl->getChat()->sendError('Can\'t find team: ' . $target, $adminplayer);
} }
} }
} }

View File

@ -26,7 +26,7 @@ class SmallTextOverlay implements TimerListener, CallbackListener, Plugin {
* Constants * Constants
*/ */
const PLUGIN_ID = 195; const PLUGIN_ID = 195;
const PLUGIN_VERSION = 1.0; const PLUGIN_VERSION = 1.4;
const PLUGIN_NAME = 'SmallTextOverlay'; const PLUGIN_NAME = 'SmallTextOverlay';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -115,7 +115,7 @@ class SmallTextOverlay implements TimerListener, CallbackListener, Plugin {
* @param Setting $setting * @param Setting $setting
* @return void * @return void
*/ */
public function updateSettings(Setting $setting = null) { public function updateSettings(?Setting $setting = null) {
if ($setting !== null && !$setting->belongsToClass($this)) { if ($setting !== null && !$setting->belongsToClass($this)) {
return; return;
} }

View File

@ -6,31 +6,21 @@ use FML\Controls\Frame;
use FML\Controls\Label; use FML\Controls\Label;
use FML\Controls\Quad; use FML\Controls\Quad;
use FML\ManiaLink; use FML\ManiaLink;
use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Manialinks\ManialinkManager; use ManiaControl\Manialinks\ManialinkManager;
use ManiaControl\Manialinks\ManialinkPageAnswerListener; use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Logger;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Plugins\Plugin; use ManiaControl\Plugins\Plugin;
use ManiaControl\Plugins\PluginManager;
use ManiaControl\Plugins\PluginMenu;
use ManiaControl\Settings\Setting; use ManiaControl\Settings\Setting;
use ManiaControl\Settings\SettingManager; use ManiaControl\Settings\SettingManager;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Callbacks\Callbacks; use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Logger;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Players\PlayerManager; use ManiaControl\Players\PlayerManager;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol');
return false;
}
/** /**
* MatchManager Admin UI * MatchManager Admin UI
* *
@ -42,38 +32,31 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
* Constants * Constants
*/ */
const PLUGIN_ID = 174; const PLUGIN_ID = 174;
const PLUGIN_VERSION = 1.2; const PLUGIN_VERSION = 2.3;
const PLUGIN_NAME = 'MatchManager Admin UI'; const PLUGIN_NAME = 'MatchManager Admin UI';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerAdminUI] ';
const MLID_ADMINUI_SIDEMENU = 'Matchmanager.AdminUI'; const MLID_ADMINUI_SIDEMENU = 'Matchmanager.AdminUI';
const ML_ACTION_CORE_MANAGESETTINGS = 'MatchManager.AdminUI.ManageSettings';
const ML_ACTION_CORE_STOPMATCH = 'MatchManager.AdminUI.StopMatch';
const ML_ACTION_CORE_PAUSEMATCH = 'MatchManager.AdminUI.PauseMatch';
const ML_ACTION_CORE_SKIPROUND = 'MatchManager.AdminUI.SkipRound';
const ML_ACTION_CORE_STARTMATCH = 'MatchManager.AdminUI.StartMatch';
const ML_ACTION_MULTIPLECONFIGMANAGER_OPENCONFIGMANAGER = 'MatchManager.AdminUI.OpenConfigManager';
const ML_ACTION_GSHEET_MANAGESETTINGS = 'MatchManager.AdminUI.ManageGSheet';
const SETTING_POSX = 'Position X of the plugin'; const SETTING_POSX = 'Position X of the plugin';
const SETTING_POSY = 'Position Y of the plugin'; const SETTING_POSY = 'Position Y of the plugin';
const SETTING_ADMIN_LEVEL = 'Minimum Admin level to see the Admin UI';
// MatchManagerWidget Properties const ML_ITEM_SIZE = 6.;
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
const MATCHMANAGERGSHEET_PLUGIN = 'MatchManagerSuite\MatchManagerGSheet';
const MATCHMANAGERMULTIPLECONFIGMANAGER_PLUGIN = 'MatchManagerSuite\MatchManagerMultipleConfigManager';
/* /*
* Private properties * Private properties
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var \MatchManagerSuite\MatchManagerCore */
private $MatchManagerCore = null;
private $manialink = null; private $manialink = null;
private $updateManialink = true;
/** @var MatchManagerAdminUI_MenuItem[] */
private $menuItems = [];
/** /**
* @param \ManiaControl\ManiaControl $maniaControl * @param \ManiaControl\ManiaControl $maniaControl
@ -125,15 +108,14 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
public function load(ManiaControl $maniaControl) { public function load(ManiaControl $maniaControl) {
// Init plugin // Init plugin
$this->maniaControl = $maniaControl; $this->maniaControl = $maniaControl;
if (!$this->maniaControl->getPluginManager()->getSavedPluginStatus(self::MATCHMANAGERCORE_PLUGIN)) {
throw new \Exception('MatchManager Core is needed to use ' . self::PLUGIN_NAME); $this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERLOOP, $this, 'handleAfterLoop');
} $this->maniaControl->getCallbackManager()->registerCallbackListener(SettingManager::CB_SETTING_CHANGED, $this, 'updateSettings');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
// All callbacks are loaded in handleAfterInit
$this->maniaControl->getTimerManager()->registerOneTimeListening($this, 'afterPluginInit', 1);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_POSX, 156., ""); $this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_POSX, 156., "");
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_POSY, 24., ""); $this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_POSY, 24., "");
$this->maniaControl->getAuthenticationManager()->definePluginPermissionLevel($this, self::SETTING_ADMIN_LEVEL, AuthenticationManager::AUTH_LEVEL_ADMIN);
return true; return true;
} }
@ -144,36 +126,34 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
public function unload() { public function unload() {
$this->maniaControl->getManialinkManager()->hideManialink(self::MLID_ADMINUI_SIDEMENU); $this->maniaControl->getManialinkManager()->hideManialink(self::MLID_ADMINUI_SIDEMENU);
} }
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/** /**
* afterPluginInit * afterPluginInit
* Plugins are loaded alphabetically, so we have to we wait they are all loaded before check. *
* We can't use AFTER_INIT Callback to make it visible when enabled manually
*
* @return void * @return void
*/ */
public function afterPluginInit() { public function handleAfterLoop() {
$this->MatchManagerCore = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERCORE_PLUGIN); if ($this->updateManialink) {
if ($this->MatchManagerCore === null) { $this->updateManialink = false;
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is needed to use ' . self::PLUGIN_NAME . ' plugin.'); $this->generateManialink();
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class()));
return;
} }
$this->generateManialink();
$this->displayManialink();
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_LOADED, $this, 'handlePluginLoaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(SettingManager::CB_SETTING_CHANGED, $this, 'updateSettings');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::MP_STARTMATCHSTART, $this, 'generateManialink');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MatchManagerCore::CB_MATCHMANAGER_STARTMATCH, $this, 'generateManialink');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MatchManagerCore::CB_MATCHMANAGER_ENDMATCH, $this, 'generateManialink');
$this->maniaControl->getCallbackManager()->registerCallbackListener(MatchManagerCore::CB_MATCHMANAGER_STOPMATCH, $this, 'generateManialink');
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer');
} }
/** /**
@ -183,7 +163,7 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
*/ */
public function updateSettings(Setting $setting) { public function updateSettings(Setting $setting) {
if ($setting->belongsToClass($this)) { if ($setting->belongsToClass($this)) {
$this->generateManialink(); $this->updateManialink = true;
} }
} }
@ -193,8 +173,9 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
* @param Player $player * @param Player $player
*/ */
public function handlePlayerConnect(Player $player) { public function handlePlayerConnect(Player $player) {
if ($player->authLevel > 0) { $authLevel = $this->maniaControl->getAuthenticationManager()->getAuthLevelInt($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL));
$this->maniaControl->getManialinkManager()->sendManialink($this->manialink,$player->login); if ($this->maniaControl->getAuthenticationManager()->checkRight($player, $authLevel)) {
$this->maniaControl->getManialinkManager()->sendManialink($this->manialink, $player->login);
} }
} }
@ -204,73 +185,12 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
* @return void * @return void
*/ */
private function displayManialink() { private function displayManialink() {
$admins = $this->maniaControl->getAuthenticationManager()->getAdmins(); $authLevel = $this->maniaControl->getAuthenticationManager()->getAuthLevelInt($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_ADMIN_LEVEL));
if (!empty($admins)) { $admins = $this->maniaControl->getAuthenticationManager()->getAdmins($authLevel);
if (count($admins) > 0) {
$this->maniaControl->getManialinkManager()->sendManialink($this->manialink, $admins); $this->maniaControl->getManialinkManager()->sendManialink($this->manialink, $admins);
} }
} }
/**
* handleManialinkPageAnswer
*
* @param array $callback
* @return void
*/
public function handleManialinkPageAnswer(array $callback) {
$actionId = $callback[1][2];
$actionArray = explode('.', $actionId);
if ($actionArray[0] != "MatchManager" || $actionArray[1] != "AdminUI") {
return;
}
$login = $callback[1][1];
$player = $this->maniaControl->getPlayerManager()->getPlayer($login);
if ($player->authLevel <= 0) {
return;
}
switch ($actionId) {
case self::ML_ACTION_CORE_MANAGESETTINGS:
$pluginMenu = $this->maniaControl->getPluginManager()->getPluginMenu();
if (defined("\ManiaControl\ManiaControl::ISTRACKMANIACONTROL")) {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, "PluginMenu.Settings." . self::MATCHMANAGERCORE_PLUGIN);
} else {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, self::MATCHMANAGERCORE_PLUGIN);
}
$this->maniaControl->getConfigurator()->showMenu($player, $pluginMenu);
break;
case self::ML_ACTION_CORE_STOPMATCH:
$this->MatchManagerCore->MatchStop();
break;
case self::ML_ACTION_CORE_PAUSEMATCH:
$this->MatchManagerCore->setNadeoPause();
break;
case self::ML_ACTION_CORE_SKIPROUND:
$this->MatchManagerCore->onCommandMatchEndWU(array(), $player);
$this->MatchManagerCore->onCommandUnsetPause(array(), $player);
$this->MatchManagerCore->onCommandMatchEndRound(array(), $player);
break;
case self::ML_ACTION_CORE_STARTMATCH:
$this->MatchManagerCore->MatchStart();
break;
case self::ML_ACTION_MULTIPLECONFIGMANAGER_OPENCONFIGMANAGER:
/** @var \MatchManagerSuite\MatchManagerMultipleConfigManager */
$MatchManagerMultipleConfigManager = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERMULTIPLECONFIGMANAGER_PLUGIN);
if ($MatchManagerMultipleConfigManager !== null) {
$MatchManagerMultipleConfigManager->showConfigListUI(array(), $player);
}
break;
case self::ML_ACTION_GSHEET_MANAGESETTINGS:
$pluginMenu = $this->maniaControl->getPluginManager()->getPluginMenu();
if (defined("\ManiaControl\ManiaControl::ISTRACKMANIACONTROL")) {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, "PluginMenu.Settings." . self::MATCHMANAGERGSHEET_PLUGIN);
} else {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, self::MATCHMANAGERGSHEET_PLUGIN);
}
$this->maniaControl->getConfigurator()->showMenu($player, $pluginMenu);
break;
}
}
/** /**
* generate, store and automatically send it to the admin * generate, store and automatically send it to the admin
@ -278,8 +198,8 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
* @return void * @return void
*/ */
public function generateManialink() { public function generateManialink() {
if ($this->MatchManagerCore === null) return; $this->log("Generating interface with ". count($this->menuItems) . " items");
$itemSize = 6.;
$quadStyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultQuadStyle(); $quadStyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultQuadStyle();
$quadSubstyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultQuadSubstyle(); $quadSubstyle = $this->maniaControl->getManialinkManager()->getStyleManager()->getDefaultQuadSubstyle();
$itemMarginFactorX = 1.3; $itemMarginFactorX = 1.3;
@ -293,172 +213,174 @@ class MatchManagerAdminUI implements CallbackListener, ManialinkPageAnswerListen
$posX = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_POSX); $posX = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_POSX);
$posY = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_POSY); $posY = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_POSY);
// Admin Menu Icon Frame if (count($this->menuItems) > 0) {
$iconFrame = new Frame(); // Admin Menu Icon Frame
$frame->addChild($iconFrame); $iconFrame = new Frame();
$iconFrame->setPosition($posX, $posY); $frame->addChild($iconFrame);
$iconFrame->setPosition($posX, $posY);
$backgroundQuad = new Quad(); $backgroundQuad = new Quad();
$iconFrame->addChild($backgroundQuad); $iconFrame->addChild($backgroundQuad);
$backgroundQuad->setSize($itemSize * $itemMarginFactorX, $itemSize * $itemMarginFactorY); $backgroundQuad->setSize(self::ML_ITEM_SIZE * $itemMarginFactorX, self::ML_ITEM_SIZE * $itemMarginFactorY);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle); $backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$backgroundQuad->setZ(-1.); $backgroundQuad->setZ(-1.);
$itemQuad = new Label(); $itemQuad = new Label();
$iconFrame->addChild($itemQuad); $iconFrame->addChild($itemQuad);
$itemQuad->setText('$fc3$w🏆$m'); $itemQuad->setText('$fc3$w🏆$m');
$itemQuad->setSize($itemSize, $itemSize); $itemQuad->setSize(self::ML_ITEM_SIZE, self::ML_ITEM_SIZE);
$itemQuad->setAreaFocusColor("00000000"); $itemQuad->setAreaFocusColor("00000000");
$itemQuad->setAreaColor("00000000"); $itemQuad->setAreaColor("00000000");
// Admin Menu Description // Admin Menu Description
$descriptionLabel = new Label(); $descriptionLabel = new Label();
$frame->addChild($descriptionLabel); $frame->addChild($descriptionLabel);
$descriptionLabel->setAlign($descriptionLabel::RIGHT, $descriptionLabel::TOP); $descriptionLabel->setAlign(Label::RIGHT, Label::TOP);
$descriptionLabel->setSize(40, 4); $descriptionLabel->setSize(40, 4);
$descriptionLabel->setTextSize(1); $descriptionLabel->setTextSize(1);
$descriptionLabel->setTextColor('fff'); $descriptionLabel->setTextColor('fff');
$descriptionLabel->setTextPrefix('$s'); $descriptionLabel->setTextPrefix('$s');
// Admin Menu // Admin Menu
$popoutFrame = new Frame(); $popoutFrame = new Frame();
$frame->addChild($popoutFrame); $frame->addChild($popoutFrame);
$popoutFrame->setPosition($posX - $itemSize * 0.5, $posY); $popoutFrame->setPosition($posX - self::ML_ITEM_SIZE * 0.5, $posY);
$popoutFrame->setHorizontalAlign($popoutFrame::RIGHT); $popoutFrame->setHorizontalAlign($popoutFrame::RIGHT);
$popoutFrame->setVisible(false); $popoutFrame->setVisible(false);
$backgroundQuad = new Quad(); $backgroundQuad = new Quad();
$popoutFrame->addChild($backgroundQuad); $popoutFrame->addChild($backgroundQuad);
$backgroundQuad->setHorizontalAlign($backgroundQuad::RIGHT); $backgroundQuad->setHorizontalAlign($backgroundQuad::RIGHT);
$backgroundQuad->setStyles($quadStyle, $quadSubstyle); $backgroundQuad->setStyles($quadStyle, $quadSubstyle);
$backgroundQuad->setZ(-1.);
$backgroundQuad->setZ(-1.); $itemQuad->addToggleFeature($popoutFrame);
$itemQuad->addToggleFeature($popoutFrame); // Add items
$itemPosX = -4.;
// Add items // sort by Order desc
$itemPosX = -1; usort($this->menuItems, function($a, $b) {
return $b->getOrder() <=> $a->getOrder();
});
// Settings: foreach ($this->menuItems as $menuItem) {
$menuQuad = new Quad(); $menuItem->buildControl($popoutFrame, $descriptionLabel, $itemPosX);
$popoutFrame->addChild($menuQuad); $itemPosX -= self::ML_ITEM_SIZE * 1.05;
$menuQuad->setStyle("UICommon64_1"); }
$menuQuad->setSubStyle("Settings_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Manage Core Settings");
$menuQuad->setAction(self::ML_ACTION_CORE_MANAGESETTINGS);
$MatchManagerMultipleConfigManager = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERMULTIPLECONFIGMANAGER_PLUGIN); $descriptionLabel->setPosition($posX - (count($popoutFrame->getChildren()) - 1) * self::ML_ITEM_SIZE * 1.05 - 5, $posY);
if ($MatchManagerMultipleConfigManager !== null) { $backgroundQuad->setSize((count($popoutFrame->getChildren()) - 1) * self::ML_ITEM_SIZE * 1.05 + 2, self::ML_ITEM_SIZE * $itemMarginFactorY);
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_2");
$menuQuad->setSubStyle("Plugin_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Manage Multiple Configs");
$menuQuad->setAction(self::ML_ACTION_MULTIPLECONFIGMANAGER_OPENCONFIGMANAGER);
} }
$MatchManagerGsheet = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERGSHEET_PLUGIN);
if ($MatchManagerGsheet !== null) {
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_2");
$menuQuad->setSubStyle("DisplayIcons_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Manage Google Sheet config");
$menuQuad->setAction(self::ML_ACTION_GSHEET_MANAGESETTINGS);
}
if ($this->MatchManagerCore->getMatchStatus()) {
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_1");
$menuQuad->setSubStyle("Stop_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Stop the match");
$menuQuad->setAction(self::ML_ACTION_CORE_STOPMATCH);
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_1");
$menuQuad->setSubStyle("Pause_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Pause the match");
$menuQuad->setAction(self::ML_ACTION_CORE_PAUSEMATCH);
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_1");
$menuQuad->setSubStyle("Cross_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Skip the round / Warmup / Pause");
$menuQuad->setAction(self::ML_ACTION_CORE_SKIPROUND);
} else {
$menuQuad = new Quad();
$popoutFrame->addChild($menuQuad);
$menuQuad->setStyle("UICommon64_1");
$menuQuad->setSubStyle("Play_light");
$menuQuad->setSize($itemSize, $itemSize);
$menuQuad->setX($itemPosX);
$menuQuad->setHorizontalAlign($menuQuad::RIGHT);
$itemPosX -= $itemSize * 1.05;
$menuQuad->addTooltipLabelFeature($descriptionLabel, "Start the match");
$menuQuad->setAction(self::ML_ACTION_CORE_STARTMATCH);
}
$descriptionLabel->setPosition($posX - (count($popoutFrame->getChildren()) - 1) * $itemSize * 1.05 - 5, $posY);
$backgroundQuad->setSize((count($popoutFrame->getChildren()) - 1) * $itemSize * 1.05 + 2, $itemSize * $itemMarginFactorY);
$this->manialink = $maniaLink; $this->manialink = $maniaLink;
$this->displayManialink(); $this->displayManialink();
} }
/** public function addMenuItem(MatchManagerAdminUI_MenuItem $menuItem) {
* handlePluginUnloaded $this->removeMenuItem($menuItem->getActionId());
* $this->menuItems[] = $menuItem;
* @param string $pluginClass
* @param Plugin $plugin $this->updateManialink = true;
* @return void
*/
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class()));
}
if (strstr($pluginClass, "MatchManagerSuite")) {
$this->generateManialink();
}
} }
/** public function removeMenuItem(string $actionId) {
* handlePluginLoaded $this->menuItems = array_filter($this->menuItems, function($menuItem) use ($actionId) {
* return $menuItem->getActionId() !== $actionId;
* @param string $pluginClass });
* @param Plugin $plugin
* @return void $this->updateManialink = true;
*/ }
public function handlePluginLoaded(string $pluginClass, Plugin $plugin) { }
if (strstr($pluginClass, "MatchManagerSuite")) {
$this->generateManialink(); class MatchManagerAdminUI_MenuItem {
private string $actionId;
private int $order = 100;
private string $description = '';
private string $text = '';
private string $imageUrl = '';
private string $style = '';
private string $subStyle = '';
private float $size = MatchManagerAdminUI::ML_ITEM_SIZE;
public function getActionId() {
return $this->actionId;
}
public function setActionId(string $actionId) {
$this->actionId = $actionId;
return $this;
}
public function getOrder() {
return $this->order;
}
public function setOrder(int $order) {
$this->order = $order;
return $this;
}
public function getDescription() {
return $this->description;
}
public function setDescription(string $description) {
$this->description = $description;
return $this;
}
public function getImageUrl() {
return $this->imageUrl;
}
public function setImageUrl(string $imageUrl) {
$this->imageUrl = $imageUrl;
return $this;
}
public function getSize() {
return $this->size;
}
public function setSize(float $size) {
$this->size = $size;
return $this;
}
public function getStyle() {
return $this->imageUrl;
}
public function setStyle(string $style) {
$this->style = $style;
return $this;
}
public function getSubStyle() {
return $this->imageUrl;
}
public function setSubStyle(string $subStyle) {
$this->subStyle = $subStyle;
return $this;
}
public function buildControl(Frame $parent, Label $descriptionLabel, float $posX) {
$control = null;
if ($this->text !== '') {
$control = new Label();
$control->setText($this->text);
} else {
$control = new Quad();
if ($this->imageUrl !== '') {
$control->setImageUrl($this->imageUrl);
$control->setKeepRatio('fit');
} else if ($this->style !== '') {
$control->setStyles($this->style, $this->subStyle);
} else {
$control->setBackgroundColor('cccccc');
}
} }
$parent->addChild($control);
$control->setSize($this->size, $this->size);
$control->setX($posX);
$control->setHorizontalAlign(Quad::CENTER);
$control->addTooltipLabelFeature($descriptionLabel, $this->description);
$control->setAction($this->actionId);
} }
} }

View File

@ -12,8 +12,8 @@ use ManiaControl\Settings\SettingManager;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerAutomaticLauncher plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); Logger::logError('MatchManager Core is required to use MatchManagerAutomaticLauncher plugin. Install it and restart Maniacontrol');
return false; return false;
} }
@ -28,7 +28,7 @@ class MatchManagerAutomaticLauncher implements CallbackListener, TimerListener,
* Constants * Constants
*/ */
const PLUGIN_ID = 172; const PLUGIN_ID = 172;
const PLUGIN_VERSION = 1.1; const PLUGIN_VERSION = 1.2;
const PLUGIN_NAME = 'MatchManager Automatic Launcher'; const PLUGIN_NAME = 'MatchManager Automatic Launcher';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
@ -42,6 +42,7 @@ class MatchManagerAutomaticLauncher implements CallbackListener, TimerListener,
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
@ -101,7 +102,7 @@ class MatchManagerAutomaticLauncher implements CallbackListener, TimerListener,
$this->MatchManagerCore = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERCORE_PLUGIN); $this->MatchManagerCore = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERCORE_PLUGIN);
if ($this->MatchManagerCore == null) { if ($this->MatchManagerCore == null) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is needed to use ' . self::PLUGIN_NAME . ' plugin.'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is needed to use ' . self::PLUGIN_NAME . ' plugin.');
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} else { } else {
$this->createTimers(); $this->createTimers();
} }
@ -146,7 +147,7 @@ class MatchManagerAutomaticLauncher implements CallbackListener, TimerListener,
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -170,6 +171,6 @@ class MatchManagerAutomaticLauncher implements CallbackListener, TimerListener,
$newtimers++; $newtimers++;
} }
} }
$this->maniaControl->getChat()->sendSuccessToAdmins($newtimers . " matches are planned"); $this->maniaControl->getChat()->sendSuccessToAdmins($this->MatchManagerCore->getChatPrefix() . $newtimers . " matches are planned");
} }
} }

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,382 @@
<?php
namespace MatchManagerSuite;
use ManiaControl\ManiaControl;
use ManiaControl\Plugins\Plugin;
use ManiaControl\Logger;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\Structures\ManiaPlanet\StartEndStructure;
use ManiaControl\Callbacks\Structures\TrackMania\OnScoresStructure;
use ManiaControl\Files\AsyncHttpRequest;
use ManiaControl\Callbacks\Structures\TrackMania\OnWayPointEventStructure;
use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Plugins\PluginManager;
use ManiaControl\Plugins\PluginMenu;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerECircuitMania plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use MatchManagerECircuitMania plugin. Install it and restart Maniacontrol');
return false;
}
/**
* MatchManagerECircuitMania
*
* @author Beu
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MatchManagerECircuitMania implements CallbackListener, ManialinkPageAnswerListener, TimerListener, Plugin {
/*
* Constants
*/
const PLUGIN_ID = 213;
const PLUGIN_VERSION = 1.1;
const PLUGIN_NAME = 'MatchManager eCircuitMania';
const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerECircuitMania] ';
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
const MATCHMANAGERADMINUI_PLUGIN = 'MatchManagerSuite\MatchManagerAdminUI';
const ML_ACTION_OPENSETTINGS = 'MatchManagerSuite\MatchManagerECircuitMania.OpenSettings';
const SETTING_URL = 'API URL';
const SETTING_MATCH_API_KEY = 'Match API Key';
const SETTING_WITHMATCHMANAGER = 'Only send data when a Match Manager match is running';
const CB_STARTMAP = 'Maniaplanet.StartMap_Start';
/*
* Private properties
*/
private ManiaControl $maniaControl;
private \MatchManagerSuite\MatchManagerCore $MatchManagerCore;
private int $trackNum = 0;
private int $roundNum = 0;
/**
* @see \ManiaControl\Plugins\Plugin::prepare()
*/
public static function prepare(ManiaControl $maniaControl) {
}
/**
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::PLUGIN_ID;
}
/**
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return self::PLUGIN_NAME;
}
/**
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::PLUGIN_VERSION;
}
/**
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return self::PLUGIN_AUTHOR;
}
/**
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return "Plugin to send match data to eCM";
}
/**
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
if ($this->maniaControl->getPluginManager()->getSavedPluginStatus(self::MATCHMANAGERCORE_PLUGIN)) {
$this->maniaControl->getTimerManager()->registerOneTimeListening($this, function () {
$this->MatchManagerCore = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERCORE_PLUGIN);
if ($this->MatchManagerCore === null) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is needed to use ' . self::PLUGIN_NAME . ' plugin.');
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
return;
}
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_LOADED, $this, 'handlePluginLoaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded');
$this->maniaControl->getCallbackManager()->registerScriptCallbackListener(self::CB_STARTMAP, $this, 'handleStartMap');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::MP_STARTROUNDSTART, $this, 'handleStartRound');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::TM_ONWAYPOINT, $this, 'handleOnWaypoint');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::TM_SCORES, $this, 'handleTrackmaniaScores');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::MP_ENDROUNDEND, $this, 'handleEndRound');
$this->updateAdminUIMenuItems();
}, 1);
} else {
throw new \Exception('MatchManager Core is needed to use ' . self::PLUGIN_NAME);
}
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_MATCH_API_KEY, "", "", 5);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_URL, "https://us-central1-fantasy-trackmania.cloudfunctions.net", "", 10);
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ML_ACTION_OPENSETTINGS, $this, 'handleActionOpenSettings');
}
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handlePluginLoaded(string $pluginClass) {
if ($pluginClass === self::MATCHMANAGERADMINUI_PLUGIN) {
$this->updateAdminUIMenuItems();
}
}
/**
* handlePluginUnloaded
*
* @param string $pluginClass
* @param Plugin $plugin
* @return void
*/
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->log(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
}
}
/**
* Add items in AdminUI plugin
*/
public function updateAdminUIMenuItems() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin === null) return;
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
$menuItem = new \MatchManagerSuite\MatchManagerAdminUI_MenuItem();
$menuItem->setActionId(self::ML_ACTION_OPENSETTINGS)
->setOrder(60)
->setImageUrl('https://ecircuitmania.com/favicon.png')
->setSize(4.)
->setDescription('Open eCM Settings');
$adminUIPlugin->addMenuItem($menuItem);
}
/**
* handle Open settings manialink action
*
* @param array $callback
* @param Player $player
*/
public function handleActionOpenSettings(array $callback, Player $player) {
if ($player->authLevel <= 0) return;
$pluginMenu = $this->maniaControl->getPluginManager()->getPluginMenu();
if (defined("\ManiaControl\ManiaControl::ISTRACKMANIACONTROL")) {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, "PluginMenu.Settings." . self::class);
} else {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, self::class);
}
$this->maniaControl->getConfigurator()->showMenu($player, $pluginMenu);
}
public function handleStartMap(array $structure) {
if (!$this->MatchManagerCore->getMatchIsRunning()) return;
$data = json_decode($structure[1][0]);
$this->trackNum = $data->valid;
$this->roundNum = 0;
}
public function handleStartRound(StartEndStructure $structure) {
if (!$this->MatchManagerCore->getMatchIsRunning()) return;
$this->roundNum = $structure->getValidRoundCount();
}
public function handleOnWaypoint(OnWayPointEventStructure $structure) {
if (!$this->MatchManagerCore->getMatchIsRunning()) return;
if (!$structure->getIsEndRace()) return;
if ($this->roundNum <= 0) return; // probably during the WU
$mapuid = "";
$map = $this->maniaControl->getMapManager()->getCurrentMap();
if ($map !== null) {
$mapuid = $map->uid;
}
$payload = json_encode([
"ubisoftUid" => $structure->getPlayer()->getAccountId(),
"finishTime" => $structure->getRaceTime(),
"mapId" => $mapuid,
"trackNum" => $this->trackNum,
"roundNum" => $this->roundNum
]);
$request = $this->getAPIRequest("/match-addRoundTime");
if ($request !== null) {
$request->setContent($payload)->setCallable(function ($content, $error, $headers) use ($payload) {
if ($content !== "Created" || $error !== null) {
$this->logError("Error on the 'addRoundTime' request. answer: " . $content . " / error: " . $error . " / payload: " . $payload);
}
})->postData();
}
}
public function handleTrackmaniaScores(OnScoresStructure $structure) {
if (!$this->MatchManagerCore->getMatchIsRunning()) return;
if ($structure->getSection() !== "PreEndRound") return;
$scores = [];
foreach ($structure->getPlayerScores() as $playerscore) {
$scores[] = $playerscore;
}
/** @var \ManiaControl\Callbacks\Structures\TrackMania\Models\PlayerScore[] $scores */
usort($scores, function ($a, $b) {
if ($a->getPrevRaceTime() === -1 && $b->getPrevRaceTime() === -1) {
return $b->getRoundPoints() - $a->getRoundPoints();
}
if ($a->getPrevRaceTime() === -1) return 1;
if ($b->getPrevRaceTime() === -1) return -1;
if ($a->getPrevRaceTime() === $b->getPrevRaceTime()) {
$acheckpoints = $a->getPrevRaceCheckpoints();
$bcheckpoints = $b->getPrevRaceCheckpoints();
while (end($acheckpoints) === end($bcheckpoints)) {
if (count($acheckpoints) === 0 || count($bcheckpoints) === 0) return 0;
array_pop($acheckpoints);
array_pop($bcheckpoints);
}
return end($acheckpoints) - end($bcheckpoints);
}
return $a->getPrevRaceTime() - $b->getPrevRaceTime();
});
$players = [];
$rank = 1;
foreach ($scores as $playerscore) {
/** @var \ManiaControl\Callbacks\Structures\TrackMania\Models\PlayerScore $playerscore */
if ($playerscore->getPlayer()->isSpectator) continue;
$players[] = [
"ubisoftUid" => $playerscore->getPlayer()->getAccountId(),
"finishTime" => $playerscore->getPrevRaceTime(),
"position" => $rank
];
$rank++;
}
$mapuid = "";
$map = $this->maniaControl->getMapManager()->getCurrentMap();
if ($map !== null) {
$mapuid = $map->uid;
}
$payload = json_encode([
"players" => $players,
"mapId" => $mapuid,
"trackNum" => $this->trackNum,
"roundNum" => $this->roundNum
]);
$request = $this->getAPIRequest("/match-addRound");
if ($request !== null) {
$request->setContent($payload)->setCallable(function ($content, $error, $headers) use ($payload) {
if ($content !== "Created" || $error !== null) {
$this->logError("Error on the 'addRound' request. answer: " . $content . " / error: " . $error . " / payload: " . $payload);
}
})->postData();
}
}
public function handleEndRound(StartEndStructure $structure) {
if (!$this->MatchManagerCore->getMatchIsRunning()) return;
$json = $structure->getPlainJsonObject();
if (!property_exists($json, 'isvalid') || $json->isvalid) return;
$payload = json_encode([
"trackNum" => $this->trackNum,
"roundNum" => $this->roundNum
]);
$request = $this->getAPIRequest("/match-removeRound");
if ($request !== null) {
$request->setContent($payload)->setCallable(function ($content, $error, $headers) use ($payload) {
if ($content !== "Created" || $error !== null) {
$this->logError("Error on the 'removeRound' request. answer: " . $content . " / error: " . $error . " / payload: " . $payload);
}
})->postData();
}
}
private function getAPIRequest(string $url) : ?AsyncHttpRequest {
$baseurl = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_URL);
$matchapikey = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_API_KEY);
$array = explode("_", $matchapikey);
if (count($array) !== 2) return null;
$matchid = $array[0];
$token = $array[1];
if ($baseurl === "") return null;
if ($token === "") return null;
if ($matchid === "") return null;
$asyncHttpRequest = new AsyncHttpRequest($this->maniaControl, $baseurl . $url . "?matchId=" . $matchid);
$asyncHttpRequest->setContentType("application/json");
$asyncHttpRequest->setHeaders(["Authorization: " . $token]);
return $asyncHttpRequest;
}
/**
* Unload the plugin and its Resources
*/
public function unload() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin !== null) {
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
}
}
}

View File

@ -13,13 +13,16 @@ use ManiaControl\Settings\SettingManager;
use ManiaControl\Files\AsyncHttpRequest; use ManiaControl\Files\AsyncHttpRequest;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;
use ManiaControl\Admin\AuthenticationManager; use ManiaControl\Admin\AuthenticationManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\TimerListener; use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\PlayerManager; use ManiaControl\Players\PlayerManager;
use ManiaControl\Plugins\PluginMenu;
use ManiaControl\Utils\WebReader; use ManiaControl\Utils\WebReader;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerGSheet plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); Logger::logError('MatchManager Core is required to use MatchManagerGSheet plugin. Install it and restart Maniacontrol');
return false; return false;
} }
use MatchManagerSuite\MatchManagerCore; use MatchManagerSuite\MatchManagerCore;
@ -31,15 +34,23 @@ use MatchManagerSuite\MatchManagerCore;
* @author Beu * @author Beu
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3 * @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/ */
class MatchManagerGSheet implements CallbackListener, TimerListener, CommandListener, Plugin { class MatchManagerGSheet implements CallbackListener, TimerListener, CommandListener, ManialinkPageAnswerListener, Plugin {
/* /*
* Constants * Constants
*/ */
const PLUGIN_ID = 156; const PLUGIN_ID = 156;
const PLUGIN_VERSION = 2.1; const PLUGIN_VERSION = 2.4;
const PLUGIN_NAME = 'MatchManager GSheet'; const PLUGIN_NAME = 'MatchManager GSheet';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerGSheet] ';
// Other MatchManager plugin
const MATCHMANAGERADMINUI_PLUGIN = 'MatchManagerSuite\MatchManagerAdminUI';
// Actions
const ML_ACTION_OPENSETTINGS = 'MatchManagerSuite\MatchManagerGSheet.OpenSettings';
// MatchManagerGSheet Properties // MatchManagerGSheet Properties
const DB_GSHEETSECRETSETTINGS = 'MatchManagerGSheet_SecretSettings'; const DB_GSHEETSECRETSETTINGS = 'MatchManagerGSheet_SecretSettings';
@ -94,9 +105,9 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
private $matchstatus = ""; private $matchstatus = "";
private $chatprefix = '$<$fc3$w🏆$m$> '; // Would like to create a setting but MC database doesn't support utf8mb4
private $device_code = ""; private $device_code = "";
private $access_token = ""; private $access_token = "";
private $matchid = ""; private $matchid = "";
@ -161,6 +172,9 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
} }
// Callbacks // Callbacks
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ML_ACTION_OPENSETTINGS, $this, 'handleActionOpenSettings');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERINIT, $this, 'handleAfterInit');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_LOADED, $this, 'handlePluginLoaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect'); $this->maniaControl->getCallbackManager()->registerCallbackListener(PlayerManager::CB_PLAYERCONNECT, $this, 'handlePlayerConnect');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded'); $this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(SettingManager::CB_SETTING_CHANGED, $this, 'updateSettings'); $this->maniaControl->getCallbackManager()->registerCallbackListener(SettingManager::CB_SETTING_CHANGED, $this, 'updateSettings');
@ -181,9 +195,11 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$this->access_token = $this->getSecretSetting("access_token"); $this->access_token = $this->getSecretSetting("access_token");
$this->maniaControl->getChat()->sendErrorToAdmins('To use the MatchManagerGSheet plugin, $<$l[https://github.com/AmazingBeu/ManiacontrolPlugins/wiki/MatchManager-GSheet]check the doc$>'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'To use the MatchManagerGSheet plugin, $<$l[https://github.com/AmazingBeu/ManiacontrolPlugins/wiki/MatchManager-GSheet]check the doc$>');
$this->maniaControl->getChat()->sendErrorToAdmins('Since MatchManagerGSheet 2.0, Player names are in the results and no more in a separated list'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Since MatchManagerGSheet 2.0, Player names are in the results and no more in a separated list');
$this->updateAdminUIMenuItems();
return true; return true;
} }
@ -192,6 +208,49 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
* @see \ManiaControl\Plugins\Plugin::unload() * @see \ManiaControl\Plugins\Plugin::unload()
*/ */
public function unload() { public function unload() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin !== null) {
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
}
}
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handleAfterInit() {
$this->updateAdminUIMenuItems();
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handlePluginLoaded(string $pluginClass) {
if ($pluginClass === self::MATCHMANAGERADMINUI_PLUGIN) {
$this->updateAdminUIMenuItems();
}
} }
/** /**
@ -204,7 +263,8 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->log(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -233,7 +293,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
if ($setting->belongsToClass($this)) { if ($setting->belongsToClass($this)) {
if (($setting->setting == self::SETTING_MATCHMANAGERGSHEET_CLIENT_SECRET && $setting->value == "hidden") || $setting->setting == self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID) { if (($setting->setting == self::SETTING_MATCHMANAGERGSHEET_CLIENT_SECRET && $setting->value == "hidden") || $setting->setting == self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID) {
// (Check when hidden = true to avoid double message) // (Check when hidden = true to avoid double message)
$this->maniaControl->getChat()->sendErrorToAdmins('Google API Session cleared. You must revalidate a session with //matchgsheet step1'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Google API Session cleared. You must revalidate a session with //matchgsheet step1');
$this->saveSecretSetting("access_token"); $this->saveSecretSetting("access_token");
$this->saveSecretSetting("expire"); $this->saveSecretSetting("expire");
@ -246,17 +306,50 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
if (($this->matchstatus == "running" || $this->matchstatus == "starting") && $setting->setting == self::SETTING_MATCHMANAGERGSHEET_DATA_MODE && $setting->value != $this->currentdatamode) { if (($this->matchstatus == "running" || $this->matchstatus == "starting") && $setting->setting == self::SETTING_MATCHMANAGERGSHEET_DATA_MODE && $setting->value != $this->currentdatamode) {
$setting->value = $this->currentdatamode; $setting->value = $this->currentdatamode;
$this->maniaControl->getSettingManager()->saveSetting($setting); $this->maniaControl->getSettingManager()->saveSetting($setting);
$this->maniaControl->getChat()->sendErrorToAdmins($this->chatprefix . 'You can\'t change data mode during a Match'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() . 'You can\'t change data mode during a Match');
} }
} }
} }
public function handlePlayerConnect(Player $player) { public function handlePlayerConnect(Player $player) {
if ($this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::AUTH_LEVEL_ADMIN)) { if ($this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::AUTH_LEVEL_ADMIN)) {
$this->maniaControl->getChat()->sendError('Since MatchManagerGSheet 2.0, Player names are in the results and no more in a separated list', $player->login); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Since MatchManagerGSheet 2.0, Player names are in the results and no more in a separated list', $player->login);
} }
} }
/**
* handle Open settings manialink action
*
* @param array $callback
* @param Player $player
*/
public function handleActionOpenSettings(array $callback, Player $player) {
if ($player->authLevel <= 0) return;
$pluginMenu = $this->maniaControl->getPluginManager()->getPluginMenu();
if (defined("\ManiaControl\ManiaControl::ISTRACKMANIACONTROL")) {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, "PluginMenu.Settings." . self::class);
} else {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, self::class);
}
$this->maniaControl->getConfigurator()->showMenu($player, $pluginMenu);
}
/**
* Add items in AdminUI plugin
*/
public function updateAdminUIMenuItems() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin === null) return;
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
$menuItem = new \MatchManagerSuite\MatchManagerAdminUI_MenuItem();
$menuItem->setActionId(self::ML_ACTION_OPENSETTINGS)->setOrder(100)->setStyle('UICommon64_2')->setSubStyle('DisplayIcons_light')->setDescription('Open Gsheet Settings');
$adminUIPlugin->addMenuItem($menuItem);
}
public function onCommandMatchGSheet(array $chatCallback, Player $player) { public function onCommandMatchGSheet(array $chatCallback, Player $player) {
$authLevel = $this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, MatchManagerCore::SETTING_MATCH_AUTHLEVEL); $authLevel = $this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, MatchManagerCore::SETTING_MATCH_AUTHLEVEL);
if (!$this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::getAuthLevel($authLevel))) { if (!$this->maniaControl->getAuthenticationManager()->checkRight($player, AuthenticationManager::getAuthLevel($authLevel))) {
@ -274,15 +367,15 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
} elseif (isset($text[1]) && $text[1] == 'check') { } elseif (isset($text[1]) && $text[1] == 'check') {
$this->CheckSpeadsheetAccess($player); $this->CheckSpeadsheetAccess($player);
} else { } else {
$this->maniaControl->getChat()->sendError('use argument "step1", "step2" or "check"', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'use argument "step1", "step2" or "check"', $player);
} }
} }
private function OAuth2Step1(Player $player) { private function OAuth2Step1(Player $player) {
$clientid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID); $clientid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID);
if (empty($clientid)) { if (empty($clientid)) {
Logger::logError('Client ID empty'); $this->logError('Client ID empty');
$this->maniaControl->getChat()->sendError('Client ID empty', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Client ID empty', $player);
return; return;
} }
@ -290,24 +383,29 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContentType("application/x-www-form-urlencoded"); $asyncHttpRequest->setContentType("application/x-www-form-urlencoded");
$asyncHttpRequest->setCallable(function ($json, $error) use ($player) { $asyncHttpRequest->setCallable(function ($json, $error) use ($player) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendError('Error from Google API: ' . $error, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error, $player);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendError('Json parse error: ' . $json, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json, $player);
return;
}
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return; return;
} }
if (isset($data->device_code)) { if (isset($data->device_code)) {
$this->device_code = $data->device_code; $this->device_code = $data->device_code;
$this->maniaControl->getChat()->sendSuccess('Open $<$l['. $data->verification_url . ']this link$> and type this code: "' . $data->user_code .'"' , $player); $this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() .'Open $<$l['. $data->verification_url .'?user_code=' . $data->user_code . ']this link$> and type this code: "' . $data->user_code .'"' , $player);
$this->maniaControl->getChat()->sendSuccess('After have validate the App, type the commande "//matchgsheet step2"' , $player); $this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() .'After have validate the App, type the commande "//matchgsheet step2"' , $player);
} elseif (isset($data->error_code)) { } elseif (isset($data->error_code)) {
$this->maniaControl->getChat()->sendError('Google refused the request: ' . $data->error_code, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Google refused the request: ' . $data->error_code, $player);
} else { } else {
$this->maniaControl->getChat()->sendError('Unkown error' , $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Unkown error' , $player);
} }
}); });
@ -317,21 +415,21 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
private function OAuth2Step2(Player $player) { private function OAuth2Step2(Player $player) {
$clientid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID); $clientid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_CLIENT_ID);
if (empty($clientid)) { if (empty($clientid)) {
Logger::logError('Client ID empty'); $this->logError('Client ID empty');
$this->maniaControl->getChat()->sendError('Client ID empty', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Client ID empty', $player);
return; return;
} }
$clientsecret = $this->getSecretSetting("client_secret"); $clientsecret = $this->getSecretSetting("client_secret");
if (empty($clientsecret)) { if (empty($clientsecret)) {
Logger::logError('Client Secret empty'); $this->logError('Client Secret empty');
$this->maniaControl->getChat()->sendError('Client Secret empty', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Client Secret empty', $player);
return; return;
} }
if (empty($this->device_code)) { if (empty($this->device_code)) {
Logger::logError('No device_code. Have you run the step 1?'); $this->logError('No device_code. Have you run the step 1?');
$this->maniaControl->getChat()->sendError('No device_code. Have you run the step 1?', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'No device_code. Have you run the step 1?', $player);
return; return;
} }
@ -340,28 +438,34 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setHeaders(array("Content-Length: 0")); $asyncHttpRequest->setHeaders(array("Content-Length: 0"));
$asyncHttpRequest->setCallable(function ($json, $error) use ($player) { $asyncHttpRequest->setCallable(function ($json, $error) use ($player) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendError('Error from Google API: ' . $error, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error, $player);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendError('Json parse error: ' . $json, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json, $player);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
if (isset($data->access_token)) { if (isset($data->access_token)) {
$this->access_token = $data->access_token; $this->access_token = $data->access_token;
$this->saveSecretSetting("access_token", $data->access_token); $this->saveSecretSetting("access_token", $data->access_token);
$this->saveSecretSetting("expire", time() + $data->expires_in); $this->saveSecretSetting("expire", time() + $data->expires_in);
$this->saveSecretSetting("refresh_token", $data->refresh_token); $this->saveSecretSetting("refresh_token", $data->refresh_token);
$this->maniaControl->getChat()->sendSuccess('Maniacontrol is registered' , $player); $this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() .'Maniacontrol is registered' , $player);
} elseif (isset($data->error_description)) { } elseif (isset($data->error_description)) {
Logger::logError('Google refused the request: ' . $data->error_description); $this->logError('Google refused the request: ' . $data->error_description);
$this->maniaControl->getChat()->sendError('Google refused the request: ' . $data->error_description , $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Google refused the request: ' . $data->error_description , $player);
} else { } else {
Logger::logError('Unkown error' . $data->error_description); $this->logError('Unkown error' . $data->error_description);
$this->maniaControl->getChat()->sendError('Unkown error' , $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Unkown error' , $player);
} }
}); });
@ -369,7 +473,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
} }
private function refreshTokenIfNeeded() { private function refreshTokenIfNeeded() {
Logger::Log('refreshTokenIfNeeded'); $this->log('Refresh Google API token if needed');
$this->access_token = $this->getSecretSetting("access_token"); $this->access_token = $this->getSecretSetting("access_token");
$expire = $this->getSecretSetting("expire"); $expire = $this->getSecretSetting("expire");
$refreshtoken = $this->getSecretSetting("refresh_token"); $refreshtoken = $this->getSecretSetting("refresh_token");
@ -382,23 +486,31 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$json = $response->getContent(); $json = $response->getContent();
$error = $response->getError(); $error = $response->getError();
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error during token refresh: ' . $error); $this->logError('Error during token refresh: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error during token refresh: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error during token refresh: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
if (isset($data->access_token)) { if (isset($data->access_token)) {
$this->access_token = $data->access_token; $this->access_token = $data->access_token;
$this->saveSecretSetting("access_token", $data->access_token); $this->saveSecretSetting("access_token", $data->access_token);
$this->saveSecretSetting("expire", time() + $data->expires_in); $this->saveSecretSetting("expire", time() + $data->expires_in);
$this->log('Successfully updated Google API token');
} elseif (isset($data->error_description)) { } elseif (isset($data->error_description)) {
$this->maniaControl->getChat()->sendErrorToAdmins('Google refused the request: ' . $data->error_description); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Google refused the request: ' . $data->error_description);
} else { } else {
$this->maniaControl->getChat()->sendErrorToAdmins('Unkown error'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Unkown error');
} }
} }
return true; return true;
@ -441,7 +553,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
private function CheckSpeadsheetAccess(Player $player) { private function CheckSpeadsheetAccess(Player $player) {
$spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET); $spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET);
if ($spreadsheetid === "") { if ($spreadsheetid === "") {
$this->maniaControl->getChat()->sendError('Empty Spreadsheet Id', $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Empty Spreadsheet Id', $player);
return; return;
} }
@ -451,26 +563,32 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token)); $asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token));
$asyncHttpRequest->setCallable(function ($json, $error) use ($player) { $asyncHttpRequest->setCallable(function ($json, $error) use ($player) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error: ' . $error); $this->logError('Error: ' . $error);
$this->maniaControl->getChat()->sendError('Error: ' . $error, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Error: ' . $error, $player);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendError('Json parse error: ' . $json, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json, $player);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
if (isset($data->properties->title)) { if (isset($data->properties->title)) {
$this->maniaControl->getChat()->sendSuccess('Speadsheet name: ' . $data->properties->title, $player); $this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() .'Speadsheet name: ' . $data->properties->title, $player);
} else { } else {
$this->maniaControl->getChat()->sendError("Can't access to the Spreadsheet: " . $data->error->message, $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() ."Can't access to the Spreadsheet: " . $data->error->message, $player);
} }
}); });
$asyncHttpRequest->getData(1000); $asyncHttpRequest->getData(1000);
} else { } else {
$this->maniaControl->getChat()->sendError("Can't have access to Google API service", $player); $this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() ."Can't have access to Google API service", $player);
} }
} }
@ -493,6 +611,9 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET); $spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET);
if ($spreadsheetid === "") return; if ($spreadsheetid === "") return;
$sheetname = $this->getSheetName();
if ($sheetname === "") return;
foreach ($currentscore as $key => $score) { foreach ($currentscore as $key => $score) {
$name = "~"; $name = "~";
$player = $this->maniaControl->getPlayerManager()->getPlayer($score[1]); $player = $this->maniaControl->getPlayerManager()->getPlayer($score[1]);
@ -504,8 +625,6 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$matchstatus = $this->matchstatus; $matchstatus = $this->matchstatus;
if ($this->refreshTokenIfNeeded()) { if ($this->refreshTokenIfNeeded()) {
$sheetname = $this->getSheetName();
$data = new \stdClass; $data = new \stdClass;
$data->valueInputOption = "RAW"; $data->valueInputOption = "RAW";
@ -536,18 +655,24 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContent(json_encode($data)); $asyncHttpRequest->setContent(json_encode($data));
$asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid, $currentscore, $currentteamsscore, $matchstatus, $nbmaps, $nbrounds) { $asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid, $currentscore, $currentteamsscore, $matchstatus, $nbmaps, $nbrounds) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return;
}
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return; return;
} }
if ($this->currentdatamode == "All Rounds Data" && $matchstatus == "running") { if ($this->currentdatamode == "All Rounds Data" && $matchstatus == "running") {
$this->log('Successfully sent Info data');
$newcurrentscore = []; $newcurrentscore = [];
foreach ($currentscore as $score) { foreach ($currentscore as $score) {
array_push($newcurrentscore, array_merge([$nbmaps, $nbrounds], $score)); array_push($newcurrentscore, array_merge([$nbmaps, $nbrounds], $score));
@ -564,21 +689,28 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContent(json_encode($data)); $asyncHttpRequest->setContent(json_encode($data));
$asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid, $currentteamsscore, $nbmaps, $nbrounds) { $asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid, $currentteamsscore, $nbmaps, $nbrounds) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
$this->log('Successfully appending Player Scores data');
if (!empty($currentteamsscore)) { if (!empty($currentteamsscore)) {
$newcurrentteamsscore = []; $newcurrentteamsscore = [];
foreach ($currentteamsscore as $score) { foreach ($currentteamsscore as $score) {
array_push($newcurrentteamsscore,array_merge([$nbmaps, $nbrounds], $score)); array_push($newcurrentteamsscore, array_merge([$nbmaps, $nbrounds], $score));
} }
$data = new \stdClass; $data = new \stdClass;
@ -592,36 +724,45 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContent(json_encode($data)); $asyncHttpRequest->setContent(json_encode($data));
$asyncHttpRequest->setCallable(function ($json, $error) { $asyncHttpRequest->setCallable(function ($json, $error) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
$this->log('Successfully appending Team Scores data');
}); });
$asyncHttpRequest->postData(1000); $asyncHttpRequest->postData(1000);
} }
}); });
$asyncHttpRequest->postData(1000); $asyncHttpRequest->postData(1000);
} else {
$this->log('Successfully sent Info and Scores data');
} }
}); });
$asyncHttpRequest->postData(1000); $asyncHttpRequest->postData(1000);
} else { } else {
$this->maniaControl->getChat()->sendErrorToAdmins('Impossible to update the Google Sheet'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Impossible to update the Google Sheet');
} }
} }
function onCallbackEndRound(String $matchid, Array $currentscore, Array $currentteamsscore) { function onCallbackEndRound(String $matchid, Array $currentscore, Array $currentteamsscore) {
Logger::Log('onCallbackEndRound'); $this->log('onCallbackEndRound');
$this->matchstatus = "running"; $this->matchstatus = "running";
$this->UpdateGSheetData($matchid, $currentscore, $currentteamsscore); $this->UpdateGSheetData($matchid, $currentscore, $currentteamsscore);
} }
function onCallbackEndMatch(String $matchid, Array $currentscore, Array $currentteamsscore) { function onCallbackEndMatch(String $matchid, Array $currentscore, Array $currentteamsscore) {
Logger::Log('onCallbackEndMatch'); $this->log('onCallbackEndMatch');
$this->matchstatus = "ended"; $this->matchstatus = "ended";
$this->maniaControl->getTimerManager()->registerOneTimeListening($this, function () use ($matchid, $currentscore, $currentteamsscore) { $this->maniaControl->getTimerManager()->registerOneTimeListening($this, function () use ($matchid, $currentscore, $currentteamsscore) {
@ -629,7 +770,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
}, 1000); // Wait a sec before sending last data to avoid collision }, 1000); // Wait a sec before sending last data to avoid collision
} }
function onCallbackStopMatch(String $matchid, Array $currentscore, Array $currentteamsscore) { function onCallbackStopMatch(String $matchid, Array $currentscore, Array $currentteamsscore) {
Logger::Log('onCallbackStopMatch'); $this->log('onCallbackStopMatch');
$this->matchstatus = "stopped"; $this->matchstatus = "stopped";
$this->UpdateGSheetData($matchid, $currentscore, $currentteamsscore); $this->UpdateGSheetData($matchid, $currentscore, $currentteamsscore);
} }
@ -638,27 +779,34 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET); $spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET);
if ($spreadsheetid === "") return; if ($spreadsheetid === "") return;
$sheetname = $this->getSheetName();
if ($sheetname === "") return;
if ($this->refreshTokenIfNeeded()) { if ($this->refreshTokenIfNeeded()) {
$this->matchid = $matchid; $this->matchid = $matchid;
$asyncHttpRequest = new AsyncHttpRequest($this->maniaControl, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetid); $asyncHttpRequest = new AsyncHttpRequest($this->maniaControl, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetid);
$asyncHttpRequest->setContentType(AsyncHttpRequest::CONTENT_TYPE_JSON); $asyncHttpRequest->setContentType(AsyncHttpRequest::CONTENT_TYPE_JSON);
$asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token)); $asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token));
$asyncHttpRequest->setCallable(function ($json, $error) { $asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return;
}
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return; return;
} }
if ($data->properties->title) { if ($data->properties->title) {
$sheetsid = array(); $sheetsid = array();
$sheetname = $this->getSheetName();
$sheetexists = false; $sheetexists = false;
foreach($data->sheets as $value) { foreach($data->sheets as $value) {
if ($value->properties->title == $sheetname) { if ($value->properties->title == $sheetname) {
@ -683,6 +831,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
} }
private function PrepareSheet(String $sheetname, bool $sheetexists, Array $sheetsid) { private function PrepareSheet(String $sheetname, bool $sheetexists, Array $sheetsid) {
if ($sheetname === "") return;
$spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET); $spreadsheetid = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERGSHEET_SPREADSHEET);
if ($spreadsheetid === "") return; if ($spreadsheetid === "") return;
@ -693,7 +842,7 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$i = 0; $i = 0;
if (!$sheetexists) { if (!$sheetexists) {
Logger::Log("Creating new Sheet: " . $sheetname); $this->log("Creating new Sheet: " . $sheetname);
$sheetid = rand(1000,2147483646); $sheetid = rand(1000,2147483646);
while (in_array($sheetid, $sheetsid)) { while (in_array($sheetid, $sheetsid)) {
$sheetid = rand(1000,2147483646); $sheetid = rand(1000,2147483646);
@ -788,31 +937,47 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContent(json_encode($data)); $asyncHttpRequest->setContent(json_encode($data));
$asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid) { $asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
$this->log('Successfully created sheet with formatting');
// Clear Scoreboards data // Clear Scoreboards data
$asyncHttpRequest = new AsyncHttpRequest($this->maniaControl, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetid . '/values/' . urlencode("'". $sheetname . "'") . '!A1:Z300:clear'); $asyncHttpRequest = new AsyncHttpRequest($this->maniaControl, 'https://sheets.googleapis.com/v4/spreadsheets/' . $spreadsheetid . '/values/' . urlencode("'". $sheetname . "'") . '!A1:Z300:clear');
$asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token)); $asyncHttpRequest->setHeaders(array("Authorization: Bearer " . $this->access_token));
$asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid) { $asyncHttpRequest->setCallable(function ($json, $error) use ($sheetname, $spreadsheetid) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
$this->log('Successfully cleared all the data');
// Add headers data // Add headers data
$data = new \stdClass; $data = new \stdClass;
$data->valueInputOption = "RAW"; $data->valueInputOption = "RAW";
@ -835,16 +1000,23 @@ class MatchManagerGSheet implements CallbackListener, TimerListener, CommandLis
$asyncHttpRequest->setContent(json_encode($data)); $asyncHttpRequest->setContent(json_encode($data));
$asyncHttpRequest->setCallable(function ($json, $error) { $asyncHttpRequest->setCallable(function ($json, $error) {
if (!$json || $error) { if (!$json || $error) {
Logger::logError('Error from Google API: ' . $error); $this->logError('Error from Google API: ' . $error);
$this->maniaControl->getChat()->sendErrorToAdmins('Error from Google API: ' . $error); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Error from Google API: ' . $error);
return; return;
} }
$data = json_decode($json); $data = json_decode($json);
if (!$data) { if (!$data) {
Logger::logError('Json parse error: ' . $json); $this->logError('Json parse error: ' . $json);
$this->maniaControl->getChat()->sendErrorToAdmins('Json parse error: ' . $json); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Json parse error: ' . $json);
return; return;
} }
if (property_exists($data, "error")) {
$this->logError('Request error: ' . $data->error->code . " ". $data->error->message);
$this->maniaControl->getChat()->sendErrorToAdmins('$this->MatchManagerCore->getChatPrefix() .Request error: ' . $data->error->code . " ". $data->error->message);
return;
}
$this->log('Successfully added headers data');
}); });
$asyncHttpRequest->postData(1000); $asyncHttpRequest->postData(1000);
}); });

View File

@ -17,16 +17,18 @@ use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Callbacks\CallbackListener; use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\CallbackManager; use ManiaControl\Callbacks\CallbackManager;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Logger; use ManiaControl\Logger;
use ManiaControl\ManiaControl; use ManiaControl\ManiaControl;
use ManiaControl\Players\Player; use ManiaControl\Players\Player;
use ManiaControl\Plugins\Plugin; use ManiaControl\Plugins\Plugin;
use ManiaControl\Plugins\PluginManager; use ManiaControl\Plugins\PluginManager;
use ManiaControl\Commands\CommandListener; use ManiaControl\Commands\CommandListener;
use ManiaControl\Plugins\PluginMenu;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerMultipleConfigManager plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); Logger::logError('MatchManager Core is required to use MatchManagerMultipleConfigManager plugin. Install it and restart Maniacontrol');
return false; return false;
} }
use MatchManagerSuite\MatchManagerCore; use MatchManagerSuite\MatchManagerCore;
@ -42,21 +44,26 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* Constants * Constants
*/ */
const PLUGIN_ID = 171; const PLUGIN_ID = 171;
const PLUGIN_VERSION = 1.4; const PLUGIN_VERSION = 1.7;
const PLUGIN_NAME = 'MatchManager Multiple Config Manager'; const PLUGIN_NAME = 'MatchManager Multiple Config Manager';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerMultipleConfigManager] ';
// MatchManagerWidget Properties // MatchManagerWidget Properties
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore'; const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
const MATCHMANAGERADMINUI_PLUGIN = 'MatchManagerSuite\MatchManagerAdminUI';
const DB_MATCHCONFIG = 'MatchManager_MatchConfigs'; const DB_MATCHCONFIG = 'MatchManager_MatchConfigs';
const ML_ID = 'MatchManager.MultiConfigManager.UI'; const ML_ID = 'MatchManager.MultiConfigManager.UI';
const ML_ACTION_REMOVE_CONFIG = 'MatchManager.MultiConfigManager.RemoveConfig'; const ML_ACTION_OPENSETTINGS = 'MatchManagerSuite\MatchManagerMultipleConfigManager.OpenSettings';
const ML_ACTION_LOAD_CONFIG = 'MatchManager.MultiConfigManager.LoadConfig'; const ML_ACTION_REMOVE_CONFIG = 'MatchManagerSuite\MatchManagerMultipleConfigManager.RemoveConfig';
const ML_ACTION_LOAD_CONFIG_PAGE = 'MatchManager.MultiConfigManager.LoadConfigPage'; const ML_ACTION_LOAD_CONFIG = 'MatchManagerSuite\MatchManagerMultipleConfigManager.LoadConfig';
const ML_ACTION_SAVE_CONFIG = 'MatchManager.MultiConfigManager.SaveConfig'; const ML_ACTION_LOAD_CONFIG_PAGE = 'MatchManagerSuite\MatchManagerMultipleConfigManager.LoadConfigPage';
const ML_ACTION_SAVE_CONFIG_PAGE = 'MatchManager.MultiConfigManager.SaveConfigPage'; const ML_ACTION_SAVE_CONFIG = 'MatchManagerSuite\MatchManagerMultipleConfigManager.SaveConfig';
const ML_ACTION_SAVE_CONFIG_PAGE = 'MatchManagerSuite\MatchManagerMultipleConfigManager.SaveConfigPage';
const ML_NAME_CONFIGNAME = 'MatchManager.MultiConfigManager.ConfigName'; const ML_NAME_CONFIGNAME = 'MatchManager.MultiConfigManager.ConfigName';
const CB_LOADCONFIG = 'MatchManager.MultiConfigManager.LoadConfig'; const CB_LOADCONFIG = 'MatchManager.MultiConfigManager.LoadConfig';
@ -67,6 +74,7 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
/** /**
@ -125,13 +133,15 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
throw new \Exception('MatchManager Core is needed to use MatchManager Players Pause plugin'); throw new \Exception('MatchManager Core is needed to use MatchManager Players Pause plugin');
} }
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERINIT, $this, 'handleAfterInit');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_LOADED, $this, 'handlePluginLoaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded'); $this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_UNLOADED, $this, 'handlePluginUnloaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer'); $this->maniaControl->getCallbackManager()->registerCallbackListener(CallbackManager::CB_MP_PLAYERMANIALINKPAGEANSWER, $this, 'handleManialinkPageAnswer');
$this->maniaControl->getCommandManager()->registerCommandListener('matchconfig', $this, 'showConfigListUI', true, 'Start a match'); $this->maniaControl->getCommandManager()->registerCommandListener('matchconfig', $this, 'showConfigListUI', true, 'Start a match');
$this->initTables(); $this->initTables();
$this->updateAdminUIMenuItems();
return true; return true;
} }
@ -139,6 +149,49 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* @see \ManiaControl\Plugins\Plugin::unload() * @see \ManiaControl\Plugins\Plugin::unload()
*/ */
public function unload() { public function unload() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin !== null) {
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
}
}
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handleAfterInit() {
$this->updateAdminUIMenuItems();
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handlePluginLoaded(string $pluginClass) {
if ($pluginClass === self::MATCHMANAGERADMINUI_PLUGIN) {
$this->updateAdminUIMenuItems();
}
} }
/** /**
@ -151,7 +204,8 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->log(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -174,6 +228,21 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
} }
} }
/**
* Add items in AdminUI plugin
*/
public function updateAdminUIMenuItems() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin === null) return;
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
$menuItem = new \MatchManagerSuite\MatchManagerAdminUI_MenuItem();
$menuItem->setActionId(self::ML_ACTION_OPENSETTINGS)->setOrder(200)->setStyle('UICommon64_2')->setSubStyle('Plugin_light')->setDescription('Manage Multiple Configs');
$adminUIPlugin->addMenuItem($menuItem);
}
/** /**
* handleManialinkPageAnswer * handleManialinkPageAnswer
* *
@ -181,10 +250,10 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* @return void * @return void
*/ */
public function handleManialinkPageAnswer(array $callback) { public function handleManialinkPageAnswer(array $callback) {
Logger::log("handleManialinkPageAnswer");
$actionId = $callback[1][2]; $actionId = $callback[1][2];
$actionArray = explode('.', $actionId); $actionArray = explode('.', $actionId);
if ($actionArray[0] != "MatchManager" || $actionArray[1] != "MultiConfigManager") {
if ($actionArray[0] !== self::class) {
return; return;
} }
@ -194,12 +263,15 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
return; return;
} }
$action = $actionArray[0] . '.' . $actionArray[1] . '.' . $actionArray[2]; $action = $actionArray[0] . "." . $actionArray[1];
switch ($action) { switch ($action) {
case self::ML_ACTION_OPENSETTINGS:
$this->showConfigListUI(array(), $player);
break;
case self::ML_ACTION_REMOVE_CONFIG: case self::ML_ACTION_REMOVE_CONFIG:
$id = intval($actionArray[3]); $id = intval($actionArray[2]);
Logger::log("[MatchManagerMultipleConfigManager] Removing config: " . $id); $this->log("Removing config: " . $id);
$mysqli = $this->maniaControl->getDatabase()->getMysqli(); $mysqli = $this->maniaControl->getDatabase()->getMysqli();
$query = $mysqli->prepare('DELETE FROM `'. self::DB_MATCHCONFIG .'` WHERE id = ?;'); $query = $mysqli->prepare('DELETE FROM `'. self::DB_MATCHCONFIG .'` WHERE id = ?;');
@ -213,7 +285,7 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
$this->showConfigListUI(array(), $player); $this->showConfigListUI(array(), $player);
break; break;
case self::ML_ACTION_LOAD_CONFIG: case self::ML_ACTION_LOAD_CONFIG:
$id = intval($actionArray[3]); $id = intval($actionArray[2]);
// Hide loading before because it can take few seconds // Hide loading before because it can take few seconds
$this->maniaControl->getManialinkManager()->hideManialink(ManialinkManager::MAIN_MLID, $login); $this->maniaControl->getManialinkManager()->hideManialink(ManialinkManager::MAIN_MLID, $login);
$this->loadConfig($id); $this->loadConfig($id);
@ -239,8 +311,8 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
*/ */
public function loadConfig(int $id) { public function loadConfig(int $id) {
if ($this->MatchManagerCore->getMatchStatus()) { if ($this->MatchManagerCore->getMatchStatus()) {
Logger::logError("Impossible to load config during a match"); $this->logError("Impossible to load config during a match");
$this->maniaControl->getChat()->sendErrorToAdmins('Impossible to load config during a match'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Impossible to load config during a match');
return; return;
} }
$mysqli = $this->maniaControl->getDatabase()->getMysqli(); $mysqli = $this->maniaControl->getDatabase()->getMysqli();
@ -261,7 +333,7 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
if ($result[0] && $result[0]["config"]) { if ($result[0] && $result[0]["config"]) {
$allconfigs = json_decode($result[0]["config"],true); $allconfigs = json_decode($result[0]["config"],true);
if ($allconfigs != null) { if ($allconfigs != null) {
Logger::log("[MatchManagerMultipleConfigManager] Loading config: " . $id); $this->log("Loading config: " . $id);
$someconfignotloaded = false; $someconfignotloaded = false;
foreach ($allconfigs as $plugin => $configs) { foreach ($allconfigs as $plugin => $configs) {
$pluginclass = $this->maniaControl->getPluginManager()->getPlugin($plugin); $pluginclass = $this->maniaControl->getPluginManager()->getPlugin($plugin);
@ -272,22 +344,22 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
$setting = $this->maniaControl->getSettingManager()->getSettingObject($pluginclass, $name); $setting = $this->maniaControl->getSettingManager()->getSettingObject($pluginclass, $name);
if ($setting != null) { if ($setting != null) {
if ($setting->value != $value) { if ($setting->value != $value) {
Logger::log("Saving new setting " . $name); $this->log("Saving new setting " . $name);
$setting->value = $value; $setting->value = $value;
$this->maniaControl->getSettingManager()->saveSetting($setting); $this->maniaControl->getSettingManager()->saveSetting($setting);
} }
} else { } else {
$someconfignotloaded = true; $someconfignotloaded = true;
Logger::log("Unable to load setting: " . $name); $this->log("Unable to load setting: " . $name);
} }
} }
} }
} }
if ($someconfignotloaded) { if ($someconfignotloaded) {
$this->maniaControl->getChat()->sendErrorToAdmins('One or more settings could not be imported'); $this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'One or more settings could not be imported');
} }
$this->maniaControl->getSettingManager()->clearStorage(); $this->maniaControl->getSettingManager()->clearStorage();
$this->maniaControl->getChat()->sendSuccessToAdmins('MatchManager Config "' . $result[0]["name"] . '" loaded'); $this->maniaControl->getChat()->sendSuccessToAdmins($this->MatchManagerCore->getChatPrefix() .'MatchManager Config "' . $result[0]["name"] . '" loaded');
} }
} }
@ -301,7 +373,7 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* @return void * @return void
*/ */
public function saveCurrentConfig(array $fields) { public function saveCurrentConfig(array $fields) {
Logger::log("[MatchManagerMultipleConfigManager] Saving current config"); $this->log("Saving current config");
$result = array(); $result = array();
$configname = ""; $configname = "";
$gamemodebase = ""; $gamemodebase = "";
@ -389,7 +461,6 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* @param Player $player * @param Player $player
*/ */
public function showConfigListUI(array $chat, Player $player) { public function showConfigListUI(array $chat, Player $player) {
Logger::log("showConfigListUI");
$width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth(); $width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth();
$height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight(); $height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight();
@ -491,15 +562,15 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
$index++; $index++;
} }
//Search for Map-Name // Save config button
$mapNameButton = $this->maniaControl->getManialinkManager()->getElementBuilder()->buildRoundTextButton( $saveConfigButton = $this->maniaControl->getManialinkManager()->getElementBuilder()->buildRoundTextButton(
'Save current config', 'Save current config',
35, 35,
5, 5,
self::ML_ACTION_SAVE_CONFIG_PAGE self::ML_ACTION_SAVE_CONFIG_PAGE
); );
$frame->addChild($mapNameButton); $frame->addChild($saveConfigButton);
$mapNameButton->setPosition(-$width / 2 + 110, -$height / 2 + 6); $saveConfigButton->setPosition(-$width / 2 + 110, -$height / 2 + 6);
// Render and display xml // Render and display xml
$this->maniaControl->getManialinkManager()->displayWidget($maniaLink, $player, self::ML_ID); $this->maniaControl->getManialinkManager()->displayWidget($maniaLink, $player, self::ML_ID);
@ -513,7 +584,6 @@ class MatchManagerMultipleConfigManager implements ManialinkPageAnswerListener,
* @param Player $player * @param Player $player
*/ */
public function showSaveConfigUI(Player $player) { public function showSaveConfigUI(Player $player) {
Logger::log("showConfigListUI");
$width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth(); $width = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsWidth();
$height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight(); $height = $this->maniaControl->getManialinkManager()->getStyleManager()->getListWidgetsHeight();

View File

@ -21,8 +21,8 @@ use ManiaControl\Commands\CommandListener;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerPlayersPause plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); Logger::logError('MatchManager Core is required to use MatchManagerPlayersPause plugin. Install it and restart Maniacontrol');
return false; return false;
} }
@ -38,10 +38,12 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
* Constants * Constants
*/ */
const PLUGIN_ID = 159; const PLUGIN_ID = 159;
const PLUGIN_VERSION = 1.4; const PLUGIN_VERSION = 1.6;
const PLUGIN_NAME = 'MatchManager Players Pause'; const PLUGIN_NAME = 'MatchManager Players Pause';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerPlayersPause] ';
// MatchManagerWidget Properties // MatchManagerWidget Properties
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore'; const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
@ -58,8 +60,8 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
private $chatprefix = '$<$fc3$w🏆$m$> '; // Would like to create a setting but MC database doesn't support utf8mb4
private $playerspausestate = array(); private $playerspausestate = array();
@ -161,6 +163,24 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
$this->closePauseWidget(); $this->closePauseWidget();
} }
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/** /**
* handlePluginUnloaded * handlePluginUnloaded
* *
@ -171,7 +191,8 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->log(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -212,14 +233,14 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
if ($nbpause >= $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_PAUSE_NBPLAYERS)) { if ($nbpause >= $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_PAUSE_NBPLAYERS)) {
$this->playerspausestate = array(); $this->playerspausestate = array();
$this->closePauseWidget(); $this->closePauseWidget();
Logger::log('Pause requested by players'); $this->log('Pause requested by players');
if (!$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_PAUSE_WAIT_END_ROUND)) { if (!$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_PAUSE_WAIT_END_ROUND)) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this->maniaControl, MatchManagerCore::SETTING_MATCH_PAUSE_DURATION) <= 0) { if ($this->maniaControl->getSettingManager()->getSettingValue($this->maniaControl, MatchManagerCore::SETTING_MATCH_PAUSE_DURATION) <= 0) {
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Ask the admins to resume the match'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Ask the admins to resume the match');
} }
$this->MatchManagerCore->setNadeoPause(); $this->MatchManagerCore->setNadeoPause();
} else { } else {
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Pause will start at the end of this round'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Pause will start at the end of this round');
$this->LaunchPauseAtTheEnd = true; $this->LaunchPauseAtTheEnd = true;
} }
return; return;
@ -296,10 +317,10 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
if (isset($this->playerspausestate[$player->login])) { if (isset($this->playerspausestate[$player->login])) {
if ($this->playerspausestate[$player->login] == 0) { if ($this->playerspausestate[$player->login] == 0) {
$this->playerspausestate[$player->login] = 1; $this->playerspausestate[$player->login] = 1;
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Player $<$ff0' . $player->nickname . '$> asks a pause'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Player $<$ff0' . $player->nickname . '$> asks a pause');
} elseif ($this->playerspausestate[$player->login] == 1) { } elseif ($this->playerspausestate[$player->login] == 1) {
$this->playerspausestate[$player->login] = 0; $this->playerspausestate[$player->login] = 0;
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Player $<$ff0' . $player->nickname . '$> no longer asks for a pause'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Player $<$ff0' . $player->nickname . '$> no longer asks for a pause');
} }
$this->PauseMatchIfNeeded($player); $this->PauseMatchIfNeeded($player);
} }
@ -322,7 +343,7 @@ class MatchManagerPlayersPause implements ManialinkPageAnswerListener, CommandLi
public function handleBeginRoundCallback() { public function handleBeginRoundCallback() {
if ($this->LaunchPauseAtTheEnd) { if ($this->LaunchPauseAtTheEnd) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this->maniaControl, MatchManagerCore::SETTING_MATCH_PAUSE_DURATION) <= 0) { if ($this->maniaControl->getSettingManager()->getSettingValue($this->maniaControl, MatchManagerCore::SETTING_MATCH_PAUSE_DURATION) <= 0) {
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Ask the admins to resume the match'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Ask the admins to resume the match');
} }
$this->LaunchPauseAtTheEnd = false; $this->LaunchPauseAtTheEnd = false;

View File

@ -20,8 +20,8 @@ use ManiaControl\Commands\CommandListener;
use Maniaplanet\DedicatedServer\InvalidArgumentException; use Maniaplanet\DedicatedServer\InvalidArgumentException;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerReadyButton plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); Logger::logError('MatchManager Core is required to use MatchManagerReadyButton plugin. Install it and restart Maniacontrol');
return false; return false;
} }
@ -37,10 +37,12 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
* Constants * Constants
*/ */
const PLUGIN_ID = 158; const PLUGIN_ID = 158;
const PLUGIN_VERSION = 1.4; const PLUGIN_VERSION = 1.6;
const PLUGIN_NAME = 'MatchManager Ready Button'; const PLUGIN_NAME = 'MatchManager Ready Button';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerReadyButton] ';
// MatchManagerWidget Properties // MatchManagerWidget Properties
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore'; const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
@ -57,8 +59,8 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
private $chatprefix = '$<$fc3$w🏆$m$> '; // Would like to create a setting but MC database doesn't support utf8mb4
private $playersreadystate = array(); private $playersreadystate = array();
@ -155,6 +157,24 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
$this->closeReadyWidget(); $this->closeReadyWidget();
} }
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/** /**
* handlePluginUnloaded * handlePluginUnloaded
* *
@ -165,7 +185,7 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -206,7 +226,7 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
if ($nbready >= $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_READY_NBPLAYERS)) { if ($nbready >= $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCH_READY_NBPLAYERS)) {
$this->playersreadystate = array(); $this->playersreadystate = array();
$this->closeReadyWidget(); $this->closeReadyWidget();
Logger::log('Start Match via Ready Button'); $this->log('Start Match via Ready Button');
$this->MatchManagerCore->MatchStart(); $this->MatchManagerCore->MatchStart();
return; return;
} }
@ -235,7 +255,7 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
} else if (!$player->isSpectator && !isset($this->playersreadystate[$player->login])) { } else if (!$player->isSpectator && !isset($this->playersreadystate[$player->login])) {
$this->playersreadystate[$player->login] = 0; $this->playersreadystate[$player->login] = 0;
$this->maniaControl->getManialinkManager()->sendManialink($this->MLisNotReady, $player->login, ToggleUIFeature: false); $this->maniaControl->getManialinkManager()->sendManialink($this->MLisNotReady, $player->login, ToggleUIFeature: false);
$this->maniaControl->getChat()->sendSuccess($this->chatprefix . 'You can now set you $<$f00Ready$> by clicking on the button', $player); $this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() . 'You can now set you $<$f00Ready$> by clicking on the button', $player);
} else if (!$player->isSpectator && isset($this->playersreadystate[$player->login])) { } else if (!$player->isSpectator && isset($this->playersreadystate[$player->login])) {
if ($this->playersreadystate[$player->login] == 1) { if ($this->playersreadystate[$player->login] == 1) {
$this->maniaControl->getManialinkManager()->sendManialink($this->MLisReady, $player->login, ToggleUIFeature: false); $this->maniaControl->getManialinkManager()->sendManialink($this->MLisReady, $player->login, ToggleUIFeature: false);
@ -283,10 +303,10 @@ class MatchManagerReadyButton implements ManialinkPageAnswerListener, CommandLis
if (isset($this->playersreadystate[$player->login])) { if (isset($this->playersreadystate[$player->login])) {
if ($this->playersreadystate[$player->login] == 0) { if ($this->playersreadystate[$player->login] == 0) {
$this->playersreadystate[$player->login] = 1; $this->playersreadystate[$player->login] = 1;
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Player $<$ff0' . $player->nickname . '$> now is $<$z$0f0ready$>'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Player $<$ff0' . $player->nickname . '$> now is $<$z$0f0ready$>');
} elseif ($this->playersreadystate[$player->login] == 1) { } elseif ($this->playersreadystate[$player->login] == 1) {
$this->playersreadystate[$player->login] = 0; $this->playersreadystate[$player->login] = 0;
$this->maniaControl->getChat()->sendInformation($this->chatprefix . 'Player $<$ff0' . $player->nickname . '$> now is $<$z$f00not ready$>'); $this->maniaControl->getChat()->sendInformation($this->MatchManagerCore->getChatPrefix() . 'Player $<$ff0' . $player->nickname . '$> now is $<$z$f00not ready$>');
} }
$this->StartMatchIfNeeded($player); $this->StartMatchIfNeeded($player);
} }

View File

@ -0,0 +1,506 @@
<?php
namespace MatchManagerSuite;
use ManiaControl\Callbacks\CallbackListener;
use ManiaControl\Callbacks\Callbacks;
use ManiaControl\Callbacks\TimerListener;
use ManiaControl\Commands\CommandListener;
use ManiaControl\Logger;
use ManiaControl\ManiaControl;
use ManiaControl\Manialinks\ManialinkPageAnswerListener;
use ManiaControl\Players\Player;
use ManiaControl\Plugins\Plugin;
use ManiaControl\Plugins\PluginManager;
use ManiaControl\Plugins\PluginMenu;
use ManiaControl\Settings\Setting;
use ManiaControl\Settings\SettingManager;
use ManiaControl\Utils\WebReader;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerTMWTDuoIntegration plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use MatchManagerTMWTDuoIntegration plugin. Install it and restart Maniacontrol');
return false;
}
use MatchManagerSuite\MatchManagerCore;
/**
* MatchManager TMWT Duo Integration
*
* @author Beu (based on MatchManagerWidget by jonthekiller)
* @license http://www.gnu.org/licenses/ GNU General Public License, Version 3
*/
class MatchManagerTMWTDuoIntegration implements CallbackListener, ManialinkPageAnswerListener, CommandListener, TimerListener, Plugin {
/*
* Constants
*/
const PLUGIN_ID = 211;
const PLUGIN_VERSION = 1.2;
const PLUGIN_NAME = 'MatchManager TMWT Duo Integration';
const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerTMWTDuoIntegration] ';
// Other MatchManager plugin
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
const MATCHMANAGERADMINUI_PLUGIN = 'MatchManagerSuite\MatchManagerAdminUI';
// Actions
const ML_ACTION_OPENSETTINGS = 'MatchManagerSuite\MatchManagerTMWTDuoIntegration.OpenSettings';
const XMLRPC_CALLBACK_PICKANDBANCOMPLETE = 'PickBan.Complete';
const XMLRPC_CALLBACK_STARTMAP = 'Maniaplanet.StartMap_Start';
const XMLRPC_METHOD_STARTPICKANDBAN = 'PickBan.Start';
const XMLRPC_METHOD_ADDPLAYER = 'Club.Match.AddPlayer';
const XMLRPC_METHOD_REMOVEPLAYER = 'Club.Match.RemovePlayer';
const XMLRPC_METHOD_MATCHSTARTED = 'Club.Match.Start';
const XMLRPC_METHOD_MATCHCOMPLETED = 'Club.Match.Completed';
const SETTING_TEAM1 = 'Team 1 Id';
const SETTING_TEAM2 = 'Team 2 Id';
const SETTING_PICKANDBAN_ENABLE = 'Enable Pick & Ban';
const SETTING_PICKANDBAN_STEPCONFIG = 'Pick & Ban: Step config';
const SETTING_PICKANDBAN_STEPDURATION = 'Pick & Ban: Step duration';
const SETTING_PICKANDBAN_OVERRIDEMAPORDER = 'Pick & Ban: Override Map Order';
const SETTING_PICKANDBAN_RESULTDURATION = 'Pick & Ban: Result duration';
const STATE_NOTHING = 0;
const STATE_PRESETTING = 1;
const STATE_PREMATCH = 2;
const STATE_MATCH = 3;
/*
* Private properties
*/
/** @var ManiaControl $maniaControl */
private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null;
private $state = 0;
/**
* @param \ManiaControl\ManiaControl $maniaControl
* @see \ManiaControl\Plugins\Plugin::prepare()
*/
public static function prepare(ManiaControl $maniaControl) {
}
/**
* @see \ManiaControl\Plugins\Plugin::getId()
*/
public static function getId() {
return self::PLUGIN_ID;
}
/**
* @see \ManiaControl\Plugins\Plugin::getName()
*/
public static function getName() {
return self::PLUGIN_NAME;
}
/**
* @see \ManiaControl\Plugins\Plugin::getVersion()
*/
public static function getVersion() {
return self::PLUGIN_VERSION;
}
/**
* @see \ManiaControl\Plugins\Plugin::getAuthor()
*/
public static function getAuthor() {
return self::PLUGIN_AUTHOR;
}
/**
* @see \ManiaControl\Plugins\Plugin::getDescription()
*/
public static function getDescription() {
return 'Integration of TMWT duo teams & pick and ban for MatchManager';
}
/**
* @param \ManiaControl\ManiaControl $maniaControl
* @return bool
* @see \ManiaControl\Plugins\Plugin::load()
*/
public function load(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
/** @var MatchManagerCore */
$this->MatchManagerCore = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERCORE_PLUGIN);
if ($this->MatchManagerCore == Null) {
throw new \Exception('MatchManager Core is needed to use ' . self::PLUGIN_NAME);
}
// Settings
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_TEAM1, '', '', 10);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_TEAM2, '', '', 10);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_PICKANDBAN_ENABLE, false, '', 20);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_PICKANDBAN_STEPCONFIG, '', 'Similar syntax as the ofiicial Competition Tool. e.g: b:1,b:0,p:0,p:1,p:1,p:0,b:0,b:1,p:r');
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_PICKANDBAN_STEPDURATION, 60000, 'Each step duration in ms', 110);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_PICKANDBAN_OVERRIDEMAPORDER, '', 'Override map order received by the server. e.g: 1,2,4,3,5', 120);
$this->maniaControl->getSettingManager()->initSetting($this, self::SETTING_PICKANDBAN_RESULTDURATION, 10000, 'result duration in ms', 130);
// Callbacks
$this->maniaControl->getManialinkManager()->registerManialinkPageAnswerListener(self::ML_ACTION_OPENSETTINGS, $this, 'handleActionOpenSettings');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::AFTERINIT, $this, 'handleAfterInit');
$this->maniaControl->getCallbackManager()->registerCallbackListener(PluginManager::CB_PLUGIN_LOADED, $this, 'handlePluginLoaded');
$this->maniaControl->getCallbackManager()->registerCallbackListener($this->MatchManagerCore::CB_MATCHMANAGER_STARTMATCH, $this, 'handleMatchManagerStartMatch');
$this->maniaControl->getCallbackManager()->registerCallbackListener(Callbacks::MP_STARTMATCHSTART, $this, 'handleStartMatchStartCallback');
$this->maniaControl->getCallbackManager()->registerScriptCallbackListener(self::XMLRPC_CALLBACK_STARTMAP, $this, 'handleStartMapStartCallback');
$this->maniaControl->getCallbackManager()->registerCallbackListener($this->MatchManagerCore::CB_MATCHMANAGER_STOPMATCH, $this, 'handleMatchManagerEndMatch');
$this->maniaControl->getCallbackManager()->registerCallbackListener($this->MatchManagerCore::CB_MATCHMANAGER_ENDMATCH, $this, 'handleMatchManagerEndMatch');
$this->maniaControl->getCallbackManager()->registerScriptCallbackListener(self::XMLRPC_CALLBACK_PICKANDBANCOMPLETE, $this, 'handlePickAndBanComplete');
$this->maniaControl->getCallbackManager()->registerCallbackListener(SettingManager::CB_SETTING_CHANGED, $this, 'handleSettingChanged');
$this->MatchManagerCore->addCanStartFunction($this, 'canStartMatch');
$this->updateAdminUIMenuItems();
}
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handleAfterInit() {
$this->updateAdminUIMenuItems();
}
/**
* handle Plugin Loaded
*
* @param string $pluginClass
*/
public function handlePluginLoaded(string $pluginClass) {
if ($pluginClass === self::MATCHMANAGERADMINUI_PLUGIN) {
$this->updateAdminUIMenuItems();
}
}
/**
* Add items in AdminUI plugin
*/
public function updateAdminUIMenuItems() {
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin === null) return;
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
$menuItem = new \MatchManagerSuite\MatchManagerAdminUI_MenuItem();
$menuItem->setActionId(self::ML_ACTION_OPENSETTINGS)
->setOrder(50)
->setImageUrl('https://files.virtit.fr/TrackMania/Images/Others/TMWT_Logo.dds')
->setSize(4.5)
->setDescription('Open TMWT Integration Settings');
$adminUIPlugin->addMenuItem($menuItem);
}
/**
* handle Open settings manialink action
*
* @param array $callback
* @param Player $player
*/
public function handleActionOpenSettings(array $callback, Player $player) {
if ($player->authLevel <= 0) return;
$pluginMenu = $this->maniaControl->getPluginManager()->getPluginMenu();
if (defined("\ManiaControl\ManiaControl::ISTRACKMANIACONTROL")) {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, "PluginMenu.Settings." . self::class);
} else {
$player->setCache($pluginMenu, PluginMenu::CACHE_SETTING_CLASS, self::class);
}
$this->maniaControl->getConfigurator()->showMenu($player, $pluginMenu);
}
/**
* Callback function to check if everything is ok before starting the match
*
* @return bool
*/
public function canStartMatch() {
if ($this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, 'S_TeamsUrl') === '') {
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() . "S_TeamsUrl must be defined");
return false;
}
if (
$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_TEAM1) === '' ||
$this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_TEAM2) === ''
) {
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() . "Team Id must be defined");
return false;
}
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_ENABLE)) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, $this->MatchManagerCore::SETTING_MATCH_SETTINGS_MODE) !== "All from the plugin") {
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'TMWT Pick and bans are only supported in MatchManagerCore "All from the plugin" mode');
return false;
}
}
return true;
}
/**
* handle MatchManagerCore StartMatch callback
*
* @return void
*/
public function handleMatchManagerStartMatch() {
$this->state = self::STATE_PRESETTING;
$setting = $this->maniaControl->getSettingManager()->getSettingObject($this->MatchManagerCore, 'S_IsMatchmaking');
if ($setting !== null && !$setting->value) {
$setting->value = true;
$this->maniaControl->getSettingManager()->saveSetting($setting);
$this->logError('Remplacing S_IsMatchmaking setting value in MatchManagerCore for TMWT integration');
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Remplacing S_IsMatchmaking setting value in MatchManagerCore for TMWT integration');
}
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_ENABLE)) {
$setting = $this->maniaControl->getSettingManager()->getSettingObject($this->MatchManagerCore, 'S_PickAndBan_Enable');
if ($setting !== null && !$setting->value) {
$setting->value = true;
$this->maniaControl->getSettingManager()->saveSetting($setting);
$this->logError('Remplacing S_PickAndBan_Enable setting value in MatchManagerCore for TMWT integration');
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'Remplacing S_PickAndBan_Enable setting value in MatchManagerCore for TMWT integration');
}
}
}
/**
* handle MatchManagerCore StopMatch & EndMatch callback
*
* @return void
*/
public function handleMatchManagerEndMatch() {
$this->state = self::STATE_NOTHING;
}
/**
* handle StartMatch_Start script callback
*
* @return void
*/
public function handleStartMatchStartCallback() {
if ($this->MatchManagerCore->getMatchStatus() && $this->state === self::STATE_PREMATCH) {
// reset match state in just in case
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_MATCHCOMPLETED, []);
}
}
/**
* handle StartMap_Start script callback
*
* @return void
*/
public function handleStartMapStartCallback() {
if (!$this->MatchManagerCore->getMatchStatus()) return;
if ($this->state === self::STATE_PRESETTING) {
$this->state = self::STATE_PREMATCH;
$this->maniaControl->getClient()->setModeScriptSettings(['S_IsMatchmaking' => true], false);
$this->maniaControl->getClient()->restartMap();
} else if ($this->state === self::STATE_PREMATCH) {
$teamsUrl = $this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, 'S_TeamsUrl');
if ($teamsUrl !== '') {
$response = WebReader::getUrl($teamsUrl);
$content = $response->getContent();
$json = json_decode($content);
if ($json !== null) {
$team1 = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_TEAM1);
$team2 = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_TEAM2);
foreach ($json as $team) {
if ($team->Id === $team1) {
$team1 = null;
foreach ($team->Players as $player) {
$this->log($player->AccountId ." added to team 1");
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_ADDPLAYER, [$player->AccountId, "1"], true);
}
}
if ($team->Id === $team2) {
$team2 = null;
foreach ($team->Players as $player) {
$this->log($player->AccountId ." added to team 2");
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_ADDPLAYER, [$player->AccountId, "2"], true);
}
}
if ($team1 === null && $team2 === null) break;
}
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_ENABLE)) {
$this->log('Starting Pick & ban in 10 seconds');
$this->maniaControl->getChat()->sendSuccess($this->MatchManagerCore->getChatPrefix() .'Starting pick & ban in 10 seconds');
$this->maniaControl->getTimerManager()->registerOneTimeListening($this, function () {
$payload = [
'stepDuration' => $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_STEPDURATION),
'resultDuration' => $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_RESULTDURATION),
'steps' => []
];
$stepConfig = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_STEPCONFIG);
foreach (explode(',', $stepConfig) as $stepRaw) {
$stepPayload = [];
$step = explode(':', $stepRaw);
if ($step[1] === 'r') {
$stepPayload['action'] = 'randompick';
} else {
if ($step[0] === 'p') {
$stepPayload['action'] = 'pick';
} else if ($step[0] === 'b') {
$stepPayload['action'] = 'ban';
}
$stepPayload['team'] = $step[1] + 1;
}
$payload['steps'][] = $stepPayload;
}
$json = json_encode($payload);
$this->log('Starting Pick & ban: '. $json);
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_STARTPICKANDBAN, [$json], true);
}, 5000);
} else {
$this->state = self::STATE_MATCH;
$this->log('Sending match start callback');
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_MATCHSTARTED, [], true);
}
}
}
}
}
/**
* handle Pick & Ban completed script callback
*
* @param array $structure
* @return void
*/
public function handlePickAndBanComplete(array $structure) {
if (!$this->MatchManagerCore->getMatchStatus()) return;
$this->log('Received picks: '. $structure[1][0]);
$this->maniaControl->getTimerManager()->registerOneTimeListening($this, function () use ($structure) {
try {
$json = json_decode($structure[1][0]);
$mapUids = array_column($json->playlist, 'uid');
$order = explode(',', $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_OVERRIDEMAPORDER));
if (count($order) === count($mapUids)) {
$this->log("Re-ordering maps");
try {
$orderedMapUid = [];
foreach ($order as $number) {
$orderedMapUid[] = $mapUids[$number - 1];
}
$mapUids = $orderedMapUid;
} catch (\Throwable $th) {
$this->logError("Invalid Map order setting");
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() ."Invalid Map order setting");
}
}
$mapList = [];
foreach ($this->maniaControl->getMapManager()->getMaps() as $map) {
$index = array_search($map->uid, $mapUids);
if ($index === false) {
$this->maniaControl->getClient()->removeMap($map->fileName);
} else {
$mapList[$index] = $map->fileName;
}
}
if (count($mapUids) !== count($mapList)) {
$this->logError("Missing maps: ". implode(' ', array_diff($mapUids, $mapList)));
}
ksort($mapList);
$this->maniaControl->getClient()->chooseNextMapList(array_values($mapList));
} catch (\Throwable $th) {
$this->logError("Can't apply map list: ". $th->getMessage());
$this->maniaControl->getChat()->sendError($this->MatchManagerCore->getChatPrefix() ."Can't apply map list: ". $th->getMessage());
}
$this->state = self::STATE_MATCH;
$this->log('Sending match start callback');
$this->maniaControl->getClient()->triggerModeScriptEvent(self::XMLRPC_METHOD_MATCHSTARTED, [], true);
$this->maniaControl->getMapManager()->getMapActions()->skipMap();
}, $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_RESULTDURATION));
}
/**
* handlePluginUnloaded
*
* @param string $pluginClass
* @param Plugin $plugin
* @return void
*/
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
}
}
/**
* handle Setting Changed callback
*
* @param Setting $setting
* @return void
*/
public function handleSettingChanged(Setting $setting) {
if ($setting->setting === self::SETTING_PICKANDBAN_ENABLE || $setting->setting === $this->MatchManagerCore::SETTING_MATCH_SETTINGS_MODE) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_PICKANDBAN_ENABLE)) {
if ($this->maniaControl->getSettingManager()->getSettingValue($this->MatchManagerCore, $this->MatchManagerCore::SETTING_MATCH_SETTINGS_MODE) !== "All from the plugin") {
$this->maniaControl->getChat()->sendErrorToAdmins($this->MatchManagerCore->getChatPrefix() .'TMWT Pick and bans are only supported in Match Manager Core "All from the plugin" mode');
}
}
}
}
/**
* @see \ManiaControl\Plugins\Plugin::unload()
*/
public function unload() {
if ($this->MatchManagerCore !== null) $this->MatchManagerCore->removeCanStartFunction($this, 'canStartMatch');
/** @var \MatchManagerSuite\MatchManagerAdminUI|null */
$adminUIPlugin = $this->maniaControl->getPluginManager()->getPlugin(self::MATCHMANAGERADMINUI_PLUGIN);
if ($adminUIPlugin !== null) {
$adminUIPlugin->removeMenuItem(self::ML_ACTION_OPENSETTINGS);
}
}
}

View File

@ -20,8 +20,8 @@ use ManiaControl\Settings\Setting;
use ManiaControl\Settings\SettingManager; use ManiaControl\Settings\SettingManager;
if (!class_exists('MatchManagerSuite\MatchManagerCore')) { if (!class_exists('MatchManagerSuite\MatchManagerCore')) {
$this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->maniaControl->getChat()->sendErrorToAdmins('MatchManager Core is required to use MatchManagerWidget plugin. Install it and restart Maniacontrol');
Logger::logError('MatchManager Core is required to use one of MatchManager plugin. Install it and restart Maniacontrol'); $this->logError('MatchManager Core is required to use MatchManagerWidget plugin. Install it and restart Maniacontrol');
return false; return false;
} }
use MatchManagerSuite\MatchManagerCore; use MatchManagerSuite\MatchManagerCore;
@ -38,10 +38,12 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* Constants * Constants
*/ */
const PLUGIN_ID = 153; const PLUGIN_ID = 153;
const PLUGIN_VERSION = 1.7; const PLUGIN_VERSION = 1.9;
const PLUGIN_NAME = 'MatchManager Widget'; const PLUGIN_NAME = 'MatchManager Widget';
const PLUGIN_AUTHOR = 'Beu'; const PLUGIN_AUTHOR = 'Beu';
const LOG_PREFIX = '[MatchManagerWidget] ';
// MatchManagerWidget Properties // MatchManagerWidget Properties
const MATCHMANAGERWIDGET_COMPATIBLE_GM = ["Cup", "Teams", "Rounds"]; const MATCHMANAGERWIDGET_COMPATIBLE_GM = ["Cup", "Teams", "Rounds"];
const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore'; const MATCHMANAGERCORE_PLUGIN = 'MatchManagerSuite\MatchManagerCore';
@ -64,10 +66,11 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
*/ */
/** @var ManiaControl $maniaControl */ /** @var ManiaControl $maniaControl */
private $maniaControl = null; private $maniaControl = null;
/** @var MatchManagerCore $MatchManagerCore */
private $MatchManagerCore = null; private $MatchManagerCore = null;
private $gmbase = ""; private $gmbase = "";
private $manialinkData = ""; private $manialinkData = null;
private $manialinkBackground = ""; private $manialinkBackground = null;
private $playerswithML = []; private $playerswithML = [];
private $specswithML = []; private $specswithML = [];
@ -171,6 +174,24 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
$this->closeWidgets(); $this->closeWidgets();
} }
/**
* Custom log function to add prefix
*
* @param mixed $message
*/
private function log(mixed $message) {
Logger::log(self::LOG_PREFIX . $message);
}
/**
* Custom logError function to add prefix
*
* @param mixed $message
*/
private function logError(mixed $message) {
Logger::logError(self::LOG_PREFIX . $message);
}
/** /**
* handlePluginUnloaded * handlePluginUnloaded
* *
@ -181,7 +202,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) { public function handlePluginUnloaded(string $pluginClass, Plugin $plugin) {
if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) { if ($pluginClass == self::MATCHMANAGERCORE_PLUGIN) {
$this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled"); $this->maniaControl->getChat()->sendErrorToAdmins(self::PLUGIN_NAME . " disabled because MatchManager Core is now disabled");
$this->maniaControl->getPluginManager()->deactivatePlugin((get_class())); $this->maniaControl->getPluginManager()->deactivatePlugin((get_class($this)));
} }
} }
@ -215,7 +236,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* @param array $settings * @param array $settings
*/ */
public function InitMatch(string $matchid, array $settings) { public function InitMatch(string $matchid, array $settings) {
Logger::Log("InitMatch"); $this->log("InitMatch");
$this->gmbase = $settings['currentgmbase']; $this->gmbase = $settings['currentgmbase'];
$this->displayManialinks(false); $this->displayManialinks(false);
} }
@ -224,7 +245,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* Clear variables and hide widget * Clear variables and hide widget
*/ */
public function ClearMatch() { public function ClearMatch() {
Logger::Log("ClearMatch"); $this->log("ClearMatch");
$this->gmbase = ""; $this->gmbase = "";
$this->manialinkData = ""; $this->manialinkData = "";
$this->closeWidgets(); $this->closeWidgets();
@ -295,7 +316,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* @param Player $player * @param Player $player
*/ */
public function handlePlayerConnect(Player $player) { public function handlePlayerConnect(Player $player) {
Logger::Log("handlePlayerConnect"); $this->log("handlePlayerConnect");
if (strlen($this->gmbase) > 0) { if (strlen($this->gmbase) > 0) {
$this->displayManialinks($player->login); $this->displayManialinks($player->login);
@ -405,7 +426,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* Generate the manilink of the background of the widget * Generate the manilink of the background of the widget
*/ */
public function generateMatchLiveWidgetBackground() { public function generateMatchLiveWidgetBackground() {
Logger::Log("generateMatchLiveWidgetBackground"); $this->log("generateMatchLiveWidgetBackground");
$posX = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERWIDGET_LIVE_POSX); $posX = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERWIDGET_LIVE_POSX);
$posY = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERWIDGET_LIVE_POSY); $posY = $this->maniaControl->getSettingManager()->getSettingValue($this, self::SETTING_MATCHMANAGERWIDGET_LIVE_POSY);
@ -448,7 +469,7 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
* @param array $currentscore * @param array $currentscore
*/ */
public function generateMatchLiveWidgetData(array $currentscore) { public function generateMatchLiveWidgetData(array $currentscore) {
Logger::Log("generateMatchLiveWidgetData"); $this->log("generateMatchLiveWidgetData");
if ($this->gmbase == "Cup") { if ($this->gmbase == "Cup") {
$pointlimit = $this->MatchManagerCore->getMatchPointsLimit(); $pointlimit = $this->MatchManagerCore->getMatchPointsLimit();
@ -519,7 +540,6 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
$rankLabel->setTextPrefix('$o'); $rankLabel->setTextPrefix('$o');
$rankLabel->setText($rank); $rankLabel->setText($rank);
$rankLabel->setTextEmboss(true); $rankLabel->setTextEmboss(true);
$rankLabel->setZ(1);
//Name //Name
$nameLabel = new Label(); $nameLabel = new Label();
@ -529,7 +549,6 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
$nameLabel->setSize($width * 0.6, 4); $nameLabel->setSize($width * 0.6, 4);
$nameLabel->setTextSize(1); $nameLabel->setTextSize(1);
$nameLabel->setTextEmboss(true); $nameLabel->setTextEmboss(true);
$nameLabel->setZ(1);
//Points //Points
$pointsLabel = new Label(); $pointsLabel = new Label();
@ -540,14 +559,13 @@ class MatchManagerWidget implements ManialinkPageAnswerListener, CallbackListene
$pointsLabel->setTextSize(1); $pointsLabel->setTextSize(1);
$pointsLabel->setText('$z' . $points); $pointsLabel->setText('$z' . $points);
$pointsLabel->setTextEmboss(true); $pointsLabel->setTextEmboss(true);
$pointsLabel->setZ(1);
//Background with Spec action //Background with Spec action
$quad = new Quad(); $quad = new Quad();
$recordFrame->addChild($quad); $recordFrame->addChild($quad);
$quad->setStyles(Quad_Bgs1InRace::STYLE, Quad_Bgs1InRace::SUBSTYLE_BgCardList); $quad->setStyles(Quad_Bgs1InRace::STYLE, Quad_Bgs1InRace::SUBSTYLE_BgCardList);
$quad->setSize($width-2, 4); $quad->setSize($width-2, 4);
$quad->setZ(1); $quad->setZ(-1);
if ($this->gmbase == "Teams") { if ($this->gmbase == "Teams") {
$team = $this->maniaControl->getClient()->getTeamInfo($score[1] + 1); $team = $this->maniaControl->getClient()->getTeamInfo($score[1] + 1);