C#:
// Все права принадлежат дискорд сообществу https://discord.gg/VgNHPpNrz6
using Newtonsoft.Json;
using Oxide.Core.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using Oxide.Core;
using Oxide.Game.Rust.Cui;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
using Object = System.Object;
using System.Text.RegularExpressions;
using ConVar;
using Newtonsoft.Json.Linq;
using Oxide.Core.Libraries;
using Oxide.Core.Database;
namespace Oxide.Plugins {
[Info("IQPermissions", "", "1.7.1")]
[Description("Extended privilege granting system")]
public class IQPermissions : RustPlugin {
/// <summary>
/// Обновление 1.7.0
/// Нововведения :
/// - Добавлено новое API
/// Изменения :
/// - Изменен принцип возврата привилегий при выгрузке плагина
/// </summary>
#region Vars
private Boolean IsFullLoaded = false;
public enum TypeData {
Permission, Group
}
private enum TypeAlert {
Add, Expired, Alert
}
private static IQPermissions _;
private static InterfaceBuilder _interface;
private const Boolean LanguageEn = true;
#endregion
#region Reference
[PluginReference]
Plugin IQChat, ImageLibrary, UAlertSystem;
public void SendChat(String Message, BasePlayer player, ConVar.Chat.ChatChannel channel = ConVar.Chat.ChatChannel.Global) {
if (IQChat) if (config.AlertConfigurations.SettingIQChat.UIAlertUse) IQChat?.Call("API_ALERT_PLAYER_UI", player, Message);
else IQChat?.Call("API_ALERT_PLAYER", player, Message, config.AlertConfigurations.SettingIQChat.CustomPrefix, config.AlertConfigurations.SettingIQChat.CustomAvatar);
else player.SendConsoleCommand("chat.add", channel, 0, Message);
}
private String GetImage(String fileName, UInt64 skin = 0) {
String imageId = (String)plugins.Find("ImageLibrary").CallHook("ImageUi.GetImage", fileName, skin);
return !String.IsNullOrEmpty(imageId) ? imageId : String.Empty;
}
#endregion
#region Configuration
private static Configuration config = new Configuration();
private class Configuration {
[JsonProperty(LanguageEn ? "Basic Settings" : "Основные настройки")]
public GeneralSetting GeneralSettings = new GeneralSetting();
[JsonProperty(LanguageEn ? "Configuring the interface" : "Настройка интерфейса")]
public InterfaceConfiguration InterfaceSetting = new InterfaceConfiguration();
[JsonProperty(LanguageEn ? "Setting up Notifications" : "Настройка уведомлений")]
public AlertConfiguration AlertConfigurations = new AlertConfiguration();
[JsonProperty(LanguageEn ? "PERMISSIONS ON THE SERVER : [Permission] = Customization" : "ПРАВА НА СЕРВЕРЕ : [Permission] = Настройка")]
public Dictionary<String, StructureLanguage> PermissionList = new Dictionary<String, StructureLanguage>();
[JsonProperty(LanguageEn ? "GROUPS WITH RIGHTS ON THE SERVER : [Group] = Customization" : "ГРУППЫ С ПРАВАМИ НА СЕРВЕРЕ : [Group] = Настройка")]
public Dictionary<String, StructureLanguage> GroupList = new Dictionary<String, StructureLanguage>();
internal class GeneralSetting {
[JsonProperty(LanguageEn ? "Webhook from the Discord channel for logging" : "Webhook от канала Discord для логирования")]
public String WebHooksDiscord;
[JsonProperty(LanguageEn ? "Connecting data storage on the MySQL side" : "Подключение хранения данных на стороне MySQL")]
public MySQLInitialize MySQLSetting = new MySQLInitialize();
[JsonProperty(LanguageEn ? "Use the removal of temporary groups from the player when unloading the plugin (when loading, they will be returned)" : "Использовать удаление временных групп у игрока при выгрузке плагина (при загрузке - они будут возвращены)")]
public Boolean UseRemoveGroupsWhenUnload;
[JsonProperty(LanguageEn ? "Use the removal of temporary permission from the player when unloading the plugin (when loading, they will be returned)" : "Использовать удаление временных прав у игрока при выгрузке плагина (при загрузке - они будут возвращены)")]
public Boolean UseRemovePermissionsХWhenUnload;
[JsonProperty(LanguageEn ? "Settings for automatically granting privileges to server novices (They will be considered novices - while the player is not in the database or datafile)" : "Настройки автоматической выдачи привилегии новичкам сервера (Они будут считаться новичками - пока игрока нет в базе или датафайле)")]
public AutoGive AutoGiveSettings = new AutoGive();
internal class AutoGive {
[JsonProperty(LanguageEn ? "Use automatic granting of permissions to a new player" : "Использовать автоматическую выдачу прав новому игроку")]
public Boolean UseAutGivePermissions;
[JsonProperty(LanguageEn ? "Use automatic granting of groups to a new player" : "Использовать автоматическую выдачу групп новому игроку")]
public Boolean UseAutGiveGroups;
[JsonProperty(LanguageEn ? "List of permissions to issue [group] = time in the format (1d/h/m/s)" : "Список прав для выдачи [группа] = время в формате (1d/h/m/s)")]
public Dictionary<String, String> PermissionList = new Dictionary<String, String>();
[JsonProperty(LanguageEn ? "List of groups to issue [group] = time in the format (1d/h/m/s)" : "Список групп для выдачи [группа] = время в формате (1d/h/m/s)")]
public Dictionary<String, String> GroupList = new Dictionary<String, String>();
}
internal class MySQLInitialize {
[JsonProperty(LanguageEn ? "Setting up a MySQL connection" : "Настройка MySQL соединения")]
public MySQLConnect ConnectSetting = new MySQLConnect();
[JsonProperty(LanguageEn ? "The desired table name in MySQL" : "Желаемое название таблицы в MySQL")]
public String TableName;
[JsonProperty(LanguageEn ? "Settings privilege migration between servers connected to the same MySQL (Example: Server #1 and #2 are connected to the same MySQL - a player with privileges on server #1 - going to server #2 - will get it there)" : "Настройка миграцию привилегий между среверами подключенными к одной MySQL (Пример : Сервер #1 и #2 подключены к одной MySQL - игрок с привилегий на сервере #1 - зайдя на сервер #2 - получит ее и там)")]
public MigrationPrivilage MigrationSettings = new MigrationPrivilage();
internal class MigrationPrivilage {
[JsonProperty(LanguageEn ? "Use the list of permissions available for migration (otherwise they will be all that the player has in MySQL)" : "Использовать список прав доступных для миграции (иначе будут все, что есть у игрока в MySQL)")]
public Boolean UseMigrationPermissionsList;
[JsonProperty(LanguageEn ? "List of permissions in available for synchronization on another server in case of player migration" : "Список прав в доступных для синхронизации на другом сервере случае миграции игрока")]
public List<String> MigrationPermissionList = new List<String>();
[JsonProperty(LanguageEn ? "Use the list of groups available for migration (otherwise they will be all that the player has in MySQL)" : "Использовать список групп доступных для миграции (иначе будут все, что есть у игрока в MySQL)")]
public Boolean UseMigrationGroupList;
[JsonProperty(LanguageEn ? "List of groups in available for synchronization on another server in case of player migration" : "Список групп в доступных для синхронизации на другом сервере случае миграции игрока")]
public List<String> MigrationGroupList = new List<String>();
}
internal class MySQLConnect {
public String Host;
public String Port;
public String DatabaseName;
public String UserName;
public String Passowrd;
}
}
}
internal class AlertConfiguration {
[JsonProperty(LanguageEn ? "Use the plugin's UI notification for notifications (otherwise it will be displayed in the chat)" : "Использовать для уведомлений UI-уведомление плагина (иначе будет отображаться в чате)")]
public Boolean UsePoopUp;
[JsonProperty(LanguageEn ? "Remind players that they are running out of group?" : "Напоминать игрокам о том, что у них заканчивается группа?")]
public Boolean UseAlertedGroup;
[JsonProperty(LanguageEn ? "The list of groups for which the reminder will work" : "Список групп на которые сработает напоминание")]
public List<String> GrpupListAlerted = new List<String>();
[JsonProperty(LanguageEn ? "Remind players that they are running out of permission?" : "Напоминать игрокам о том, что у них заканчивается права?")]
public Boolean UseAlertedPermission;
[JsonProperty(LanguageEn ? "The list of permissions for which the reminder will work" : "Список прав на которые сработает напоминание")]
public List<String> PermissionsListAlerted = new List<String>();
[JsonProperty(LanguageEn ? "How many days before the end of the privilege to remind the player about it" : "За сколько дней до окончания привилегии напоминать игроку об этом")]
public Int32 DayAlerted;
[JsonProperty(LanguageEn ? "How many seconds to show notifications to the player" : "Сколько секунд показывать уведомления игроку")]
public Single TimeAlert;
[JsonProperty(LanguageEn ? "Setting up IQChat (If installed)" : "Настройка IQChat (Если установлен)")]
public IQChatSetting SettingIQChat = new IQChatSetting();
internal class IQChatSetting {
[JsonProperty(LanguageEn ? "IQChat : Custom prefix in chat" : "IQChat : Кастомный префикс в чате")]
public String CustomPrefix;
[JsonProperty(LanguageEn ? "IQChat : Custom avatar in the chat (If required)" : "IQChat : Кастомный аватар в чате(Если требуется)")]
public String CustomAvatar;
[JsonProperty(LanguageEn ? "IQChat : Use UI notifications" : "IQChat : Использовать UI уведомления")]
public Boolean UIAlertUse;
}
}
internal class InterfaceConfiguration {
[JsonProperty(LanguageEn ? "PNG : Link to the background of the notification" : "PNG : Ссылка на задний фон уведомления")]
public String PNGBackground;
[JsonProperty(LanguageEn ? "PNG : Link to the image when receiving the privilege" : "PNG : Ссылка на картинку при получении привилегии")]
public String PNGPrivilageAdd;
[JsonProperty(LanguageEn ? "PNG : Link to the picture at the end of the privilege" : "PNG : Ссылка на картинку при окончании привилегии")]
public String PNGPrivilageExpired;
[JsonProperty(LanguageEn ? "PNG : Link to the picture at the notification of the end of the privilege" : "PNG : Ссылка на картинку при уведомлении об окончании привилегии")]
public String PNGPrivilageAlert;
[JsonProperty(LanguageEn ? "RGBA : Header Color" : "RGBA : Цвет заголовка")]
public String RGBAColorTitle;
[JsonProperty(LanguageEn ? "RGBA : Additional text color" : "RGBA : Цвет дополнительного текста")]
public String RGBAColorDescription;
}
internal class StructureLanguage {
[JsonProperty(LanguageEn ? "Name in Russian (Not obligatory.Only for Russian players)" : "Название на русском")]
public String RussianName;
[JsonProperty(LanguageEn ? "Name in English" : "Название на английском")]
public String EnglishName;
public StructureLanguage(String russianName, String englishName) {
RussianName = russianName;
EnglishName = englishName;
}
}
public static Configuration GetNewConfiguration() {
return new Configuration {
PermissionList = new Dictionary<String, StructureLanguage>(), GroupList = new Dictionary<String, StructureLanguage>(), GeneralSettings = new GeneralSetting {
WebHooksDiscord = "", UseRemoveGroupsWhenUnload = true, UseRemovePermissionsХWhenUnload = true, AutoGiveSettings = new GeneralSetting.AutoGive {
UseAutGivePermissions = false, UseAutGiveGroups = false, PermissionList = new Dictionary<String, String>() {
["iqchat.vip"]
= "7d", ["opt.oneperm"] = "1d"
}
, GroupList = new Dictionary<String, String>() {
["vip"]
= "7d", ["oneperm"] = "1d"
}
}
, MySQLSetting = new GeneralSetting.MySQLInitialize {
TableName = "players", MigrationSettings = new GeneralSetting.MySQLInitialize.MigrationPrivilage {
UseMigrationPermissionsList = true, MigrationPermissionList = new List<String> {
"iqchat.vip", "iqchat.premium", "iqbreakingtools.use",
}
, UseMigrationGroupList = true, MigrationGroupList = new List<String> {
"vip", "premium", "king", "deluxe",
}
,
}
, ConnectSetting = new GeneralSetting.MySQLInitialize.MySQLConnect {
Host = "", Port = "", DatabaseName = "", UserName = "", Passowrd = ""
}
}
}
, InterfaceSetting = new InterfaceConfiguration {
PNGBackground = "https://i.imgur.com/4lmBa3O.png", PNGPrivilageAdd = "https://i.imgur.com/WY7QFpX.png", PNGPrivilageExpired = "https://i.imgur.com/ZhVCqoS.png", PNGPrivilageAlert = "https://i.imgur.com/OkjSSB3.png", RGBAColorTitle = "0.73 0.32 0.57 1", RGBAColorDescription = "0.80 0.54 0.68 1",
}
, AlertConfigurations = new AlertConfiguration {
UseAlertedPermission = true, PermissionsListAlerted = new List<String>() {
"iqchat.vip", "iqchat.premium", "iqbreakingtools.use",
}
, UseAlertedGroup = true, GrpupListAlerted = new List<String>() {
"vip", "premium", "king", "deluxe",
}
, DayAlerted = 3, TimeAlert = 5f, UsePoopUp = true, SettingIQChat = new AlertConfiguration.IQChatSetting {
CustomPrefix = "[IQPermission]", CustomAvatar = "", UIAlertUse = false
}
,
}
}
;
}
}
protected override void LoadConfig() {
base.LoadConfig();
try {
config = Config.ReadObject<Configuration>();
if (config == null) LoadDefaultConfig();
}
catch {
PrintWarning(LanguageEn ? $"Error #554548 reading the configuration 'oxide/config/{Name}', creating a new configuration!!" : $"Ошибка #554548 чтения конфигурации 'oxide/config/{Name}', создаём новую конфигурацию!!");
LoadDefaultConfig();
}
if (config.GeneralSettings.MySQLSetting.TableName == null || String.IsNullOrWhiteSpace(config.GeneralSettings.MySQLSetting.TableName)) config.GeneralSettings.MySQLSetting.TableName = "players";
NextTick(SaveConfig);
}
protected override void LoadDefaultConfig() => config = Configuration.GetNewConfiguration();
protected override void SaveConfig() => Config.WriteObject(config, true);
private static String GetIcon(TypeAlert typeAlert) {
Configuration.InterfaceConfiguration Interfaces = config.InterfaceSetting;
String Icon = typeAlert == TypeAlert.Add ? Interfaces.PNGPrivilageAdd : typeAlert == TypeAlert.Expired ? Interfaces.PNGPrivilageExpired : typeAlert == TypeAlert.Alert ? Interfaces.PNGPrivilageAlert : String.Empty;
return ImageUi.GetImage(Icon);
}
private String GetTitle(TypeAlert typeAlert) {
String Lang = typeAlert == TypeAlert.Add ? "TITLE_ALERT_ADD" : typeAlert == TypeAlert.Expired ? "TITLE_ALERT_EXPIRED" : typeAlert == TypeAlert.Alert ? "TITLE_ALERT_INFO" : String.Empty;
return Lang;
}
private String GetDescription(String UserID, TypeAlert typeAlert, String ReplaceKey, String DataExpired) {
String Lang = typeAlert == TypeAlert.Add ? GetLang("DESCRIPTION_ALERT_ADD", UserID, ReplaceKey) : typeAlert == TypeAlert.Expired ? GetLang("DESCRIPTION_ALERT_EXPIRED", UserID, ReplaceKey) : typeAlert == TypeAlert.Alert ? GetLang("DESCRIPTION_ALERT_INFO", UserID, ReplaceKey, DataExpired) : String.Empty;
return Lang;
}
private String GetLanguageNamePrivilage(BasePlayer player, String Key, TypeData type) {
String ReplaceKey = String.Empty;
switch (type) {
case TypeData.Permission : {
if (config.PermissionList.ContainsKey(Key)) {
ReplaceKey = lang.GetLanguage(player.UserIDString) == "ru" ? config.PermissionList[Key].RussianName : config.PermissionList[Key].EnglishName;
return ReplaceKey;
}
break;
}
case TypeData.Group : if (config.GroupList.ContainsKey(Key)) {
ReplaceKey = lang.GetLanguage(player.UserIDString) == "ru" ? config.GroupList[Key].RussianName : config.GroupList[Key].EnglishName;
return ReplaceKey;
}
break;
}
return null;
}
#endregion
#region Data
[JsonProperty(LanguageEn ? "Information about privileges" : "Информация о привилегиях")]
private StructureData InformationPrivilagesUser = new StructureData();
[JsonProperty(LanguageEn ? "Players who are no longer considered beginners" : "Игроки, которые более не считают новичками")]
private List<UInt64> OldPlayers = new List<UInt64>();
private void SetupAutoPrivilages(BasePlayer player) {
if (OldPlayers.Contains(player.userID)) return;
if (config.GeneralSettings.AutoGiveSettings.UseAutGivePermissions) {
foreach (KeyValuePair<String, String> Permission in config.GeneralSettings.AutoGiveSettings.PermissionList) {
TimeSpan duration;
if (!TryParseTimeSpan(Permission.Value, out duration)) {
_.Puts(LanguageEn ? $"Automatic privilege issue error - {Permission.Key} - invalid time format" : $"Ошибка выдачи автоматической привилегии - {Permission.Key} - неверный формат времени");
_.LogToFile("LogPermission", $"=========> AutoGive : Not correct format time - {Permission.Key}", _);
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Permission.Key, player.userID, TypeData.Permission) + duration;
InformationPrivilagesUser.SetParametres(Permission.Key, player.userID, ThisTime, TypeData.Permission);
_.LogToFile("LogPermission", $"=========> AutoGive : Success give - {Permission.Key} : {player.userID}", _);
}
}
if (config.GeneralSettings.AutoGiveSettings.UseAutGiveGroups) {
foreach (KeyValuePair<String, String> Group in config.GeneralSettings.AutoGiveSettings.GroupList) {
TimeSpan duration;
if (!TryParseTimeSpan(Group.Value, out duration)) {
_.Puts(LanguageEn ? $"Automatic privilege issue error - {Group.Key} - invalid time format" : $"Ошибка выдачи автоматической привилегии - {Group.Key} - неверный формат времени");
_.LogToFile("LogPermission", $"=========> AutoGive : Not correct format time - {Group.Key}", _);
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Group.Key, player.userID, TypeData.Group) + duration;
InformationPrivilagesUser.SetParametres(Group.Key, player.userID, ThisTime, TypeData.Group);
_.LogToFile("LogPermission", $"=========> AutoGive : Success give - {Group.Key} : {player.userID}", _);
}
}
OldPlayers.Add(player.userID);
}
internal class StructureData {
[JsonProperty(LanguageEn ? "Information about player permissions" : "Информация о привилегиях игрока")]
public Dictionary<String, Dictionary<UInt64, DateTime>> UserPermissions = new Dictionary<String, Dictionary<UInt64, DateTime>>();
[JsonProperty(LanguageEn ? "Information about player groups" : "Информация о группах игрока")]
public Dictionary<String, Dictionary<UInt64, DateTime>> UserGrpups = new Dictionary<String, Dictionary<UInt64, DateTime>>();
public Dictionary<String, DateTime> GetParametresUser(UInt64 userID, TypeData typeDictonary) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
Dictionary<String, DateTime> ParametresUser = selectStructureData.Where(structure => structure.Value.ContainsKey(userID)).ToDictionary(structure => structure.Key, structure => structure.Value[userID]);
return ParametresUser;
}
public Dictionary<UInt64, DateTime> GePlayerList(String Key, TypeData typeDictonary) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
return selectStructureData.ContainsKey(Key) ? selectStructureData[Key] : null;
}
public DateTime GetExpiredPermissionData(String Key, UInt64 userID, TypeData typeDictonary) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
return selectStructureData.ContainsKey(Key) ? selectStructureData[Key].ContainsKey(userID) ? selectStructureData[Key][userID] : DateTime.Now : DateTime.Now;
}
public void SetParametres(String Key, UInt64 userID, DateTime dateExpired, TypeData typeDictonary, Boolean IsMigration = false) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
if (!selectStructureData.ContainsKey(Key)) selectStructureData.Add(Key, new Dictionary<UInt64, DateTime>() {
}
);
if (selectStructureData[Key].ContainsKey(userID)) selectStructureData[Key][userID] = dateExpired;
else selectStructureData[Key].Add(userID, dateExpired);
if (typeDictonary == TypeData.Permission) _.permission.GrantUserPermission(userID.ToString(), Key, null);
else _.permission.AddUserGroup(userID.ToString(), Key);
String LeftTime = _.GetLeftTime(dateExpired, userID.ToString());
_.InserDatabase(userID.ToString(), typeDictonary, Key, dateExpired);
_.Puts(LanguageEn ? $"Player {userID} successfully obtained {(typeDictonary == TypeData.Permission ? "permission" : "group")} - {Key} (End date in : {LeftTime})" : $"Игрок {userID} успешно получил {(typeDictonary == TypeData.Permission ? "права" : "группу")} - {Key} (Дата окончания через : {LeftTime})");
if (!IsMigration) {
_.AlertPlayer(userID, TypeAlert.Add, Key, typeDictonary, $"{LeftTime}");
_.LogToFile("LogPermission", $"===> Set - Type : {typeDictonary.ToString()} | Key : {Key} | DataExpired in : {LeftTime}", _);
List<Fields> fields = new List<Fields> {
new Fields("Steam64ID", userID.ToString(), true), new Fields(LanguageEn ? $"Received {(typeDictonary == TypeData.Permission ? "permission" : "group")}" : $"Получил {(typeDictonary == TypeData.Permission ? "права" : "группу")}", Key, true), new Fields(LanguageEn ? "Date Expired in" : $"Дата окончания через", $"{LeftTime}", true),
}
;
_.SendDiscord(fields);
}
}
public void RemoveParametres(String Key, UInt64 userID, TypeData typeDictonary, DateTime timeRevoed = default(DateTime)) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
if (!selectStructureData.ContainsKey(Key) ) return;
if (timeRevoed == default(DateTime)) {
selectStructureData[Key].Remove(userID);
_.DeleteDatabase(userID.ToString(), typeDictonary, Key);
}
else {
selectStructureData[Key][userID] = timeRevoed;
if (!IsExpiredPermission(Key, userID, typeDictonary)) {
String LeftTime = _.GetLeftTime(timeRevoed, userID.ToString());
_.Puts(LanguageEn ? $"The player has {userID} reduced action time {(typeDictonary == TypeData.Permission ? "permission" : "group")} - {Key} | End date in : {LeftTime}" : $"У игрока {userID} снижено время действия {(typeDictonary == TypeData.Permission ? "права" : "группы")} - {Key} | Дата окончания через : {LeftTime}");
_.LogToFile("LogPermission", $"=====> Remove time - Type : {typeDictonary.ToString()} | Key : {Key}", _);
List<Fields> fieldsRemoveTime = new List<Fields> {
new Fields("Steam64ID", userID.ToString(), true), new Fields(LanguageEn ? $"Reduced action time {(typeDictonary == TypeData.Permission ? "permission" : "group")}" : $"Снижено время дейтсвия {(typeDictonary == TypeData.Permission ? "прав" : "группы")}", Key, true), new Fields(LanguageEn ? "End Date in" : $"Дата окончания через", $"{LeftTime}", true),
}
;
_.SendDiscord(fieldsRemoveTime);
_.InserDatabase(userID.ToString(), typeDictonary, Key, selectStructureData[Key][userID]);
return;
}
selectStructureData[Key].Remove(userID);
_.DeleteDatabase(userID.ToString(), typeDictonary, Key);
}
if (selectStructureData[Key].Count == 0) selectStructureData.Remove(Key);
if (typeDictonary == TypeData.Permission) _.permission.RevokeUserPermission(userID.ToString(), Key);
else _.permission.RemoveUserGroup(userID.ToString(), Key);
_.AlertPlayer(userID, TypeAlert.Expired, Key, typeDictonary, null);
_.Puts(LanguageEn ? $"The player {userID} has run out of {(typeDictonary == TypeData.Permission ? "permission" : "group")} - {Key}" : $"У игрока {userID} {(typeDictonary == TypeData.Permission ? "закончились права" : "закончилась группа")} - {Key}");
_.LogToFile("LogPermission", $"=====> Remove - Type : {typeDictonary.ToString()} | Key : {Key}", _);
List<Fields> fields = new List<Fields> {
new Fields("Steam64ID", userID.ToString(), true), new Fields(LanguageEn ? $"Expired {(typeDictonary == TypeData.Permission ? "permission" : "group")}" : $"{(typeDictonary == TypeData.Permission ? "Закончились права" : "Закончилась группа")}", Key, true),
}
;
_.SendDiscord(fields);
}
public void SetParametresUnload() {
_.LogToFile("LogPermission", $"=========> Set Permissions in UNLOAD <=========", _);
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userPermission in UserPermissions) foreach (KeyValuePair<UInt64, DateTime> userInformation in userPermission.Value.Where(userInformation => !_.permission.UserHasPermission(userInformation.Key.ToString(), userPermission.Key))) {
_.permission.GrantUserPermission(userInformation.Key.ToString(), userPermission.Key, null);
_.LogToFile("LogPermission", $"=======> Set UserID (Unload) : {userInformation.Key} | Key : {userPermission.Key}", _);
}
_.LogToFile("LogPermission", $"=========> Set Group in UNLOAD <=========", _);
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userGroup in UserGrpups) foreach (KeyValuePair<UInt64, DateTime> userInformation in userGroup.Value.Where(userInformation => !_.permission.UserHasGroup(userInformation.Key.ToString(), userGroup.Key))) {
_.permission.AddUserGroup(userInformation.Key.ToString(), userGroup.Key);
_.LogToFile("LogPermission", $"=======> Set UserID (Unload) : {userInformation.Key} | Key : {userGroup.Key}", _);
}
}
public void RemoveParametresUnload() {
_.Unsubscribe("OnUserGroupRemoved");
_.Unsubscribe("OnUserPermissionRevoked");
if (config.GeneralSettings.UseRemovePermissionsХWhenUnload) {
_.LogToFile("LogPermission", $"=========> Remove Permissions in UNLOAD <=========", _);
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userPermission in UserPermissions) foreach (KeyValuePair<UInt64, DateTime> userInformation in userPermission.Value.Where(userInformation => _.permission.UserHasPermission(userInformation.Key.ToString(), userPermission.Key))) {
_.permission.RevokeUserPermission(userInformation.Key.ToString(), userPermission.Key);
_.LogToFile("LogPermission", $"=======> Remove UserID (Unload) : {userInformation.Key} | Key : {userPermission.Key}", _);
}
}
if (config.GeneralSettings.UseRemoveGroupsWhenUnload) {
_.LogToFile("LogPermission", $"=========> Remove Group in UNLOAD <=========", _);
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userGroup in UserGrpups) {
foreach (KeyValuePair<UInt64, DateTime> userInformation in userGroup.Value.Where(userInformation => _.permission.UserHasGroup(userInformation.Key.ToString(), userGroup.Key))) {
_.permission.RemoveUserGroup(userInformation.Key.ToString(), userGroup.Key);
_.LogToFile("LogPermission", $"=======> Remove UserID (Unload) : {userInformation.Key} | Key : {userGroup.Key}", _);
}
}
}
}
private Boolean IsExpiredPermission(String Key, UInt64 userID, TypeData typeDictonary) {
Dictionary<String, Dictionary<UInt64, DateTime>> selectStructureData = typeDictonary == TypeData.Permission ? UserPermissions : UserGrpups;
if (!selectStructureData.ContainsKey(Key)) return false;
return selectStructureData[Key][userID] < DateTime.Now;
}
public void TrackerExpireds() {
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userPermission in UserPermissions) foreach (KeyValuePair<UInt64, DateTime> PlayersListPermission in userPermission.Value.Where(PlayersListPermission => IsExpiredPermission(userPermission.Key, PlayersListPermission.Key, TypeData.Permission))) _.NextTick(() => RemoveParametres(userPermission.Key, PlayersListPermission.Key, TypeData.Permission));
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userGrpup in UserGrpups) foreach (KeyValuePair<UInt64, DateTime> PlayerListGroup in userGrpup.Value.Where(PlayerListGroup => IsExpiredPermission(userGrpup.Key, PlayerListGroup.Key, TypeData.Group))) _.NextTick(() => RemoveParametres(userGrpup.Key, PlayerListGroup.Key, TypeData.Group));
}
}
private void ReadData() {
OldPlayers = Oxide.Core.Interface.Oxide.DataFileSystem.ReadObject<List<UInt64>>("IQSystem/IQPermissions/OldPlayers");
if (sqlConnection != null) return;
InformationPrivilagesUser = Oxide.Core.Interface.Oxide.DataFileSystem.ReadObject<StructureData>("IQSystem/IQPermissions/Permissions");
}
private void WriteData() {
Oxide.Core.Interface.Oxide.DataFileSystem.WriteObject("IQSystem/IQPermissions/OldPlayers", OldPlayers);
if (sqlConnection != null) return;
Oxide.Core.Interface.Oxide.DataFileSystem.WriteObject("IQSystem/IQPermissions/Permissions", InformationPrivilagesUser);
}
#endregion
#region Hooks
private void Init() {
_ = this;
ReadData();
}
private void OnServerInitialized() {
Subscribe("OnUserGroupRemoved");
Subscribe("OnUserPermissionRevoked");
GrablingPermissions();
GrablingGroups();
PreLoadedPlugin();
StartPluginLoad();
Interface.Call("OnIQPermissionInitialized");
}
private void Unload() {
_.InformationPrivilagesUser.RemoveParametresUnload();
WriteData();
if (coroutineMigration != null) {
ServerMgr.Instance.StopCoroutine(coroutineMigration);
coroutineMigration = null;
}
if (RoutineQueue != null) {
foreach (KeyValuePair<UInt64, Coroutine> keyValuePair in RoutineQueue.Where(r => r.Value != null)) ServerMgr.Instance.StopCoroutine(keyValuePair.Value);
RoutineQueue.Clear();
}
InterfaceBuilder.DestroyAll();
ImageUi.Unload();
sqlLibrary.CloseDb(sqlConnection);
_.IsFullLoaded = false;
_ = null;
}
private void OnPlayerConnected(BasePlayer player) {
MigrationPrivilage(player);
SetupAutoPrivilages(player);
if (!config.AlertConfigurations.UseAlertedGroup && !config.AlertConfigurations.UseAlertedPermission) return;
player.Invoke(() => {
if (!RoutineQueue.ContainsKey(player.userID)) RoutineQueue.Add(player.userID, ServerMgr.Instance.StartCoroutine(JoinedAlertPlayer(player)));
else RoutineQueue[player.userID] = ServerMgr.Instance.StartCoroutine(JoinedAlertPlayer(player));
}
, 10f);
}
private void OnPermissionRegistered(String name, Plugin owner) => NewPermissionRegistered(name);
private void OnGroupCreated(String name) => NewGroupRegistered(name);
private void OnUserGroupRemoved(String id, String groupName) => InformationPrivilagesUser.RemoveParametres(groupName, UInt64.Parse(id), TypeData.Group);
private void OnUserPermissionRevoked(String id, String permName) => InformationPrivilagesUser.RemoveParametres(permName, UInt64.Parse(id), TypeData.Permission);
#endregion
#region Metods
#region MySQL
private readonly Core.MySql.Libraries.MySql sqlLibrary = Interface.Oxide.GetLibrary<Core.MySql.Libraries.MySql>();
private Connection sqlConnection = null;
private String SQL_Query_SelectedDatabase() {
String SelectDB = $"SELECT * FROM {config.GeneralSettings.MySQLSetting.TableName}";
return SelectDB;
}
private String SQL_Query_CreatedDatabase() {
String CreatedDB = $"CREATE TABLE IF NOT EXISTS `{config.GeneralSettings.MySQLSetting.TableName}`(" + "`id` INT(11) NOT NULL AUTO_INCREMENT," + "`steamid` VARCHAR(255) NOT NULL," + "`permission` VARCHAR(255) NOT NULL," + "`group` VARCHAR(255) NOT NULL," + "`data_expired` VARCHAR(255) NOT NULL," + " PRIMARY KEY(`id`))";
return CreatedDB;
}
private String SQL_Query_InsertUser() {
String InserUser = $"INSERT INTO `{config.GeneralSettings.MySQLSetting.TableName}`" + "(`steamid`, `permission`, `group`, `data_expired`) VALUES ('{0}','{1}','{2}','{3}')";
return InserUser;
}
#region Connection
private void SQL_OpenConnection() {
Configuration.GeneralSetting.MySQLInitialize.MySQLConnect SQLInfo = config.GeneralSettings.MySQLSetting.ConnectSetting;
if (String.IsNullOrWhiteSpace(SQLInfo.Host) || String.IsNullOrWhiteSpace(SQLInfo.Passowrd) || String.IsNullOrWhiteSpace(SQLInfo.Port) || String.IsNullOrWhiteSpace(SQLInfo.DatabaseName) || String.IsNullOrWhiteSpace(SQLInfo.UserName)) return;
sqlConnection = sqlLibrary.OpenDb(SQLInfo.Host, Convert.ToInt32(SQLInfo.Port), SQLInfo.DatabaseName, SQLInfo.UserName, SQLInfo.Passowrd, this);
if (sqlConnection == null) return;
Sql sql = Sql.Builder.Append(SQL_Query_CreatedDatabase());
sqlLibrary.Insert(sql, sqlConnection);
sql = Sql.Builder.Append(SQL_Query_SelectedDatabase());
sqlLibrary.Query(sql, sqlConnection, list => {
if (list.Count > 0) foreach (Dictionary<String, Object> entry in list) {
UInt64 SteamID = 0;
if(!UInt64.TryParse((String)entry["steamid"], out SteamID)) {
PrintError(LanguageEn ? "Error parsing SteamID player" : "Ошибка парсинга SteamID игрока");
return;
}
if (!String.IsNullOrWhiteSpace((String)entry["group"])) {
String Group = (String)entry["group"];
if (!_.InformationPrivilagesUser.UserGrpups.ContainsKey(Group)) _.InformationPrivilagesUser.UserGrpups.Add(Group, new Dictionary<UInt64, DateTime>());
if (!_.InformationPrivilagesUser.UserGrpups[Group].ContainsKey(SteamID)) _.InformationPrivilagesUser.UserGrpups[Group].Add(SteamID, DateTime.Parse((String)entry["data_expired"]));
else _.InformationPrivilagesUser.UserGrpups[Group][SteamID] = DateTime.Parse((String)entry["data_expired"]);
}
else if (!String.IsNullOrWhiteSpace((String)entry["permission"])) {
String Permission = (String)entry["permission"];
if(!_.InformationPrivilagesUser.UserPermissions.ContainsKey(Permission)) _.InformationPrivilagesUser.UserPermissions.Add(Permission, new Dictionary<UInt64, DateTime>());
if (!_.InformationPrivilagesUser.UserPermissions[Permission].ContainsKey(SteamID)) {
_.InformationPrivilagesUser.UserPermissions[Permission].Add(SteamID, DateTime.Parse((String)entry["data_expired"]));
}
else {
_.InformationPrivilagesUser.UserPermissions[Permission][SteamID] = DateTime.Parse((String)entry["data_expired"]);
}
}
}
PrintWarning(LanguageEn ? "Updated information about users from the database" : "Обновлена информация о пользователях из БД");
}
);
}
#endregion
#region Inserting
private void InserDatabase(String UserID, TypeData typeData, String Key, DateTime dateExpired) {
if (sqlConnection == null) return;
String Permission = typeData == TypeData.Permission ? Key : String.Empty;
String Group = typeData == TypeData.Group ? Key : String.Empty;
String sqlQuery = typeData == TypeData.Permission ? $"UPDATE {config.GeneralSettings.MySQLSetting.TableName} SET `steamid` = @0, `permission` = @1,`group` = @2,`data_expired` = @3 WHERE `steamid` = @0 AND `permission` = @1" : $"UPDATE {config.GeneralSettings.MySQLSetting.TableName} SET `steamid` = @0, `permission` = @1,`group` = @2,`data_expired` = @3 WHERE `steamid` = @0 AND`group` = @2";
Sql updateCommand = Oxide.Core.Database.Sql.Builder.Append(sqlQuery, UserID, Permission, Group, dateExpired.ToString());
sqlLibrary.Update(updateCommand, sqlConnection, rowsAffected => {
if (rowsAffected <= 0) {
String Query = String.Format(SQL_Query_InsertUser(), UserID, Permission, Group, dateExpired.ToString());
Sql sql = Sql.Builder.Append(Query);
sqlLibrary.Insert(sql, sqlConnection, rowsAffecteds => {
Puts(LanguageEn ? "A new user has been added to the database" : "В БД был внесен новый пользователь");
}
);
}
else Puts(LanguageEn ? "The data for the user has been updated in the database" : "В БД были обновлены данные для пользователя");
}
);
}
#endregion
#region Deleted
private void DeleteDatabase(String UserID, TypeData typeData, String Key) {
if (sqlConnection == null) return;
String Permission = typeData == TypeData.Permission ? Key : String.Empty;
String Group = typeData == TypeData.Group ? Key : String.Empty;
String sqlQuery = typeData == TypeData.Permission ? $"DELETE FROM `{config.GeneralSettings.MySQLSetting.TableName}` WHERE `steamid` = @0 AND `permission` = @1" : $"DELETE FROM `{config.GeneralSettings.MySQLSetting.TableName}` WHERE `steamid` = @0 AND`group` = @1";
Sql deleteCommand = Oxide.Core.Database.Sql.Builder.Append(sqlQuery, UserID, typeData == TypeData.Permission ? Permission : Group);
sqlLibrary.Delete(deleteCommand, sqlConnection, rowsAffected => {
Puts(LanguageEn ? "The user's information was deleted in the database" : "В БД была удалена информация пользователя");
}
);
}
#endregion
#region MigrationPrivilage
private void MigrationPrivilage(BasePlayer player) {
if (player == null || sqlConnection == null) return;
Configuration.GeneralSetting.MySQLInitialize.MigrationPrivilage MigrationInfo = config.GeneralSettings.MySQLSetting.MigrationSettings;
if(MigrationInfo.UseMigrationPermissionsList) foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> Permissions in InformationPrivilagesUser.UserPermissions.Where(x => MigrationInfo.MigrationPermissionList.Contains(x.Key))) foreach (KeyValuePair<UInt64, DateTime> PlayerInformation in Permissions.Value.Where(x => x.Key == player.userID)) if (!permission.UserHasPermission(PlayerInformation.Key.ToString(), Permissions.Key)) permission.GrantUserPermission(PlayerInformation.Key.ToString(), Permissions.Key, null);
if(MigrationInfo.UseMigrationGroupList) foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> Groups in InformationPrivilagesUser.UserGrpups.Where(x => MigrationInfo.MigrationGroupList.Contains(x.Key))) foreach (KeyValuePair<UInt64, DateTime> PlayerInformation in Groups.Value.Where(x => x.Key == player.userID)) if (!permission.UserHasGroup(PlayerInformation.Key.ToString(), Groups.Key)) permission.AddUserGroup(PlayerInformation.Key.ToString(), Groups.Key);
}
#endregion
#endregion
#region DiscordSend
private void SendDiscord(List<Fields> fields) {
if (config.GeneralSettings.WebHooksDiscord == null || String.IsNullOrWhiteSpace(config.GeneralSettings.WebHooksDiscord)) return;
FancyMessage newMessage = new FancyMessage(null, false, new FancyMessage.Embeds[1] {
new FancyMessage.Embeds(null, 10710525, fields, new Authors("IQPermissions", null, "https://i.imgur.com/F5nsCbX.png", null), null)
}
);
Request($"{config.GeneralSettings.WebHooksDiscord}", newMessage.toJSON());
}
#endregion
#region JoinAlerted
private Dictionary<UInt64, Coroutine> RoutineQueue = new Dictionary<UInt64, Coroutine>();
private IEnumerator JoinedAlertPlayer(BasePlayer player) {
if (config.AlertConfigurations.UseAlertedPermission) {
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userPermission in InformationPrivilagesUser.UserPermissions.Where(userPermission => userPermission.Value.ContainsKey(player.userID) && config.AlertConfigurations.PermissionsListAlerted.Contains(userPermission.Key)).Where(userPermission => ((userPermission.Value[player.userID] - DateTime.Now).Days + 1) <= config.AlertConfigurations.DayAlerted)) {
AlertPlayer(player.userID, TypeAlert.Alert, userPermission.Key, TypeData.Permission, $"{GetLeftTime(userPermission.Value[player.userID], player.UserIDString)}");
yield return CoroutineEx.waitForSeconds(config.AlertConfigurations.TimeAlert + 2f);
}
}
if (config.AlertConfigurations.UseAlertedGroup) {
foreach (KeyValuePair<String, Dictionary<UInt64, DateTime>> userGroup in InformationPrivilagesUser.UserGrpups.Where(userGroup => userGroup.Value.ContainsKey(player.userID) && config.AlertConfigurations.GrpupListAlerted.Contains(userGroup.Key)).Where(userGroup => ((userGroup.Value[player.userID] - DateTime.Now).Days + 1) <= config.AlertConfigurations.DayAlerted)) {
AlertPlayer(player.userID, TypeAlert.Alert, userGroup.Key, TypeData.Group, $"{GetLeftTime(userGroup.Value[player.userID], player.UserIDString)}");
yield return CoroutineEx.waitForSeconds(config.AlertConfigurations.TimeAlert + 2f);
}
}
// CuiHelper.DestroyUi(player, InterfaceBuilder.UI_POOPUP_PANEL);
if (RoutineQueue == null) yield break;
if (!RoutineQueue.ContainsKey(player.userID)) yield break;
if (RoutineQueue[player.userID] != null) ServerMgr.Instance.StopCoroutine(RoutineQueu
// ... [Code preview truncated due to length. Full source in attached file] ...