C#:
using Oxide.Core.Database;
using System.Collections;
using System.Text;
using Oxide.Core;
using UnityEngine;
using Newtonsoft.Json.Linq;
using Oxide.Core.Plugins;
using System.Text.RegularExpressions;
using UnityEngine.Networking;
using System;
using System.Linq;
using Object = System.Object;
using Oxide.Core.Libraries;
using Newtonsoft.Json;
using Oxide.Game.Rust.Cui;
using ConVar;
using System.Collections.Generic;
namespace Oxide.Plugins {
[Info("IQPermissions", "Sempai#3239", "1.0.6")]
[Description("Extended privilege granting system")]
public class IQPermissions : RustPlugin {
public void SetGroup(UInt64 userID, String Group, String DataExpired) {
TimeSpan duration;
if (!TryParseTimeSpan(DataExpired, out duration)) {
PrintError(LanguageEn ? "API : You specified an incorrect time, use 1d/1m/1s!" : "API : Вы указали неккоректное время, используйте 1d/1m/1s!");
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Group, userID, TypeData.Group) + duration;
InformationPrivilagesUser.SetParametres(Group, userID, ThisTime, TypeData.Group);
}
private Connection sqlConnection = null;
private String SQL_Query_SelectedDatabase() {
String SelectDB = $"SELECT * FROM {config.GeneralSettings.MySQLSetting.TableName}";
return SelectDB;
}
[ConsoleCommand("migration.timedpermissions")]
private void TimedPermissionsMigration(ConsoleSystem.Arg arg) {
if (arg.Player() != null) return;
coroutineMigration = ServerMgr.Instance.StartCoroutine(MigrationTimedPermissions());
}
private void Request(String url, String payload, Action<Int32> callback = null) {
Dictionary<String, String> header = new Dictionary<String, String>();
header.Add("Content-Type", "application/json");
webrequest.Enqueue(url, payload, (code, response) => {
if (code != 200 && code != 204) {
if (response != null) {
try {
JObject json = JObject.Parse(response);
if (code == 429) {
Single seconds = Single.Parse(Math.Ceiling((Double)(Int32)json["retry_after"] / 1000).ToString());
}
else {
PrintWarning($" Discord rejected that payload! Responded with \"{json["message"].ToString()}\" Code: {code}");
}
}
catch {
PrintWarning($"Failed to get a valid response from discord! Error: \"{response}\" Code: {code}");
}
}
else {
PrintWarning($"Discord didn't respond (down?) Code: {code}");
}
}
try {
callback?.Invoke(code);
}
catch (Exception ex) {
}
}
, this, RequestMethod.POST, header);
}
[ConsoleCommand("perm.users")]
private void GetInfoPerm_ConsoleCommand(ConsoleSystem.Arg arg) {
if (arg == null) return;
if(arg.Player() != null) return;
if (arg.Args == null || arg.Args.Length < 1) {
PrintError(LanguageEn ? "Syntax error, use: perm.users Permission" : "Ошибка синтаксиса, используйте : perm.users Permission");
return;
}
String Permission = arg.Args[0];
if (!config.PermissionList.ContainsKey(Permission)) {
PrintError(LanguageEn ? "The permission you specified do not exist!" : "Права которые вы указали - не существуют!");
return;
}
Dictionary<UInt64, DateTime> GetPlayers = InformationPrivilagesUser.GePlayerList(Permission, TypeData.Permission);
String PlayerList = GetPlayers == null ? String.Empty : GetPlayers.Aggregate(String.Empty, (current, Players) => current + $"- ID : {Players.Key} | Expired : {Players.Value:MM/dd/yyyy HH:mm}\n");
String Information = LanguageEn ? $"Total with active privileges ({Permission}) found {GetPlayers.Count} players\n{PlayerList}" : $"Всего с активной привилегий ({Permission}) найдено {GetPlayers.Count} игроков\n{PlayerList}";
Puts(Information);
}
public Dictionary<String, DateTime> GetGroups(UInt64 userID) => InformationPrivilagesUser.GetParametresUser(userID, TypeData.Group);
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());
}
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);
}
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();
_ = null;
sqlLibrary.CloseDb(sqlConnection);
}
private new void LoadDefaultMessages() {
lang.RegisterMessages(new Dictionary<String, String> {
["TITLE_ALERT_ADD"]
= "Privilege received!", ["TITLE_ALERT_INFO"] = "Privilege expires!", ["TITLE_ALERT_EXPIRED"] = "Privilege expired!", ["DESCRIPTION_ALERT_EXPIRED"] = "Privilege {0} expired", ["DESCRIPTION_ALERT_ADD"] = "You have successfully received {0}", ["DESCRIPTION_ALERT_INFO"] = "{0} ends : {1}", ["PINFO_ALERT"] = "YourPrivilages :\n{0}", ["PINFO_ALERT_NOT"] = "You don't have privileges",
}
, this);
lang.RegisterMessages(new Dictionary<String, String> {
["TITLE_ALERT_ADD"]
= "Привилегия получена!", ["TITLE_ALERT_INFO"] = "Привилегия истекает!", ["TITLE_ALERT_EXPIRED"] = "Привилегия истекла!", ["DESCRIPTION_ALERT_EXPIRED"] = "Привилегия {0} истекла", ["DESCRIPTION_ALERT_ADD"] = "Вы успешно получили {0}", ["DESCRIPTION_ALERT_INFO"] = "{0} кончается : {1}", ["PINFO_ALERT"] = "Ваши привилегии :\n{0}", ["PINFO_ALERT_NOT"] = "У вас нет привилегий",
}
, this, "ru");
}
/// <summary>
/// Обновление 1.0.6
/// - Корректировка в команде /pinfo
/// </summary>
public enum TypeData {
Permission, Group
}
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, $"{userPermission.Value[player.userID]:MM/dd/yyyy HH:mm}");
yield return CoroutineEx.waitForSeconds(5f);
}
}
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, $"{userGroup.Value[player.userID]:MM/dd/yyyy HH:mm}");
yield return CoroutineEx.waitForSeconds(5f);
}
}
// CuiHelper.DestroyUi(player, InterfaceBuilder.UI_POOPUP_PANEL);
if(RoutineQueue != null) if (RoutineQueue.ContainsKey(player.userID)) {
ServerMgr.Instance.StopCoroutine(RoutineQueue[player.userID]);
RoutineQueue.Remove(player.userID);
}
}
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;
}
private static Configuration config = new Configuration();
private class Configuration {
[JsonProperty(LanguageEn ? "PERMISSIONS ON THE SERVER : [Permission] = Customization" : "ПРАВА НА СЕРВЕРЕ : [Permission] = Настройка")]
public Dictionary<String, StructureLanguage> PermissionList = new Dictionary<String, StructureLanguage>();
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 ? "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;
}
}
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.735849 0.3297437 0.5744483 1", RGBAColorDescription = "0.8018868 0.5408953 0.6827385 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, UsePoopUp = true, SettingIQChat = new AlertConfiguration.IQChatSetting {
CustomPrefix = "[IQPermission]", CustomAvatar = "", UIAlertUse = false
}
,
}
}
;
}
[JsonProperty(LanguageEn ? "Basic Settings" : "Основные настройки")]
public GeneralSetting GeneralSettings = new GeneralSetting();
[JsonProperty(LanguageEn ? "GROUPS WITH RIGHTS ON THE SERVER : [Group] = Customization" : "ГРУППЫ С ПРАВАМИ НА СЕРВЕРЕ : [Group] = Настройка")]
public Dictionary<String, StructureLanguage> GroupList = new Dictionary<String, StructureLanguage>();
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 GeneralSetting {
[JsonProperty(LanguageEn ? "Use the removal of temporary groups from the player when unloading the plugin (when loading, they will be returned)" : "Использовать удаление временных групп у игрока при выгрузке плагина (при загрузке - они будут возвращены)")]
public Boolean UseRemoveGroupsWhenUnload;
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;
}
}
[JsonProperty(LanguageEn ? "Webhook from the Discord channel for logging" : "Webhook от канала Discord для логирования")]
public String WebHooksDiscord;
[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();
[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 ? "Connecting data storage on the MySQL side" : "Подключение хранения данных на стороне MySQL")]
public MySQLInitialize MySQLSetting = new MySQLInitialize();
internal class AutoGive {
[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 ? "Use automatic granting of groups to a new player" : "Использовать автоматическую выдачу групп новому игроку")]
public Boolean UseAutGiveGroups;
[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>();
[JsonProperty(LanguageEn ? "Use automatic granting of permissions to a new player" : "Использовать автоматическую выдачу прав новому игроку")]
public Boolean UseAutGivePermissions;
}
}
[JsonProperty(LanguageEn ? "Setting up Notifications" : "Настройка уведомлений")]
public AlertConfiguration AlertConfigurations = new AlertConfiguration();
[JsonProperty(LanguageEn ? "Configuring the interface" : "Настройка интерфейса")]
public InterfaceConfiguration InterfaceSetting = new InterfaceConfiguration();
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;
}
}
}
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);
}
public void RevokePermission(UInt64 userID, String Permission, String DataExpired = null) {
if (DataExpired != null) {
TimeSpan duration;
if (!TryParseTimeSpan(DataExpired, out duration)) {
PrintError(LanguageEn ? "API : You specified an incorrect time, use 1d/1m/1s!" : "API : Вы указали неккоректное время, используйте 1d/1m/1s!");
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Permission, userID, TypeData.Permission) - duration;
InformationPrivilagesUser.RemoveParametres(Permission, userID, TypeData.Permission, ThisTime);
return;
}
InformationPrivilagesUser.RemoveParametres(Permission, userID, TypeData.Permission);
}
private class ImageUi {
private static Coroutine coroutineImg = null;
private static Dictionary<String, String> Images = new Dictionary<String, String>();
private static List<String> KeyImages = new List<String>();
public static void DownloadImages() {
coroutineImg = ServerMgr.Instance.StartCoroutine(AddImage());
}
private static IEnumerator AddImage() {
_.PrintWarning(LanguageEn ? "Generating the interface, wait ~10-15 seconds!" : "Генерируем интерфейс, ожидайте ~10-15 секунд!");
if (_ == null) yield break;
_.PrintWarning(LanguageEn ? "Generating the interface, wait ~10-15 seconds!" : "Генерируем интерфейс, ожидайте ~10-15 секунд!");
foreach (String URL in KeyImages) {
String KeyName = URL;
if (KeyName == null) throw new ArgumentNullException(nameof(KeyName));
UnityWebRequest www = UnityWebRequestTexture.GetTexture(URL);
yield return www.SendWebRequest();
if (www.isNetworkError || www.isHttpError) {
_.PrintWarning($"Image download error! Error: {www.error}, Image name: {KeyName}");
www.Dispose();
coroutineImg = null;
yield break;
}
Texture2D texture = DownloadHandlerTexture.GetContent(www);
if (texture != null) {
Byte[] bytes = texture.EncodeToPNG();
String image = FileStorage.server.Store(bytes, FileStorage.Type.png, CommunityEntity.ServerInstance.net.ID).ToString();
if (!Images.ContainsKey(KeyName)) Images.Add(KeyName, image);
else Images[KeyName] = image;
UnityEngine.Object.DestroyImmediate(texture);
}
www.Dispose();
yield return CoroutineEx.waitForSeconds(0.02f);
}
yield return CoroutineEx.waitForSeconds(0.02f);
coroutineImg = null;
_interface = new InterfaceBuilder();
_.PrintWarning(LanguageEn ? "The interface has loaded successfully!" : "Интерфейс успешно загружен!");
_.InformationPrivilagesUser.SetParametresUnload();
_.timer.Every(1f, () => _.InformationPrivilagesUser.TrackerExpireds());
}
public static String GetImage(String ImgKey) => Images.ContainsKey(ImgKey) ? Images[ImgKey] : _.GetImage("LOADING");
public static void Initialize() {
KeyImages = new List<String>();
Images = new Dictionary<String, String>();
Configuration.InterfaceConfiguration Interface = config.InterfaceSetting;
if (!KeyImages.Contains(Interface.PNGBackground)) KeyImages.Add(Interface.PNGBackground);
if (!KeyImages.Contains(Interface.PNGPrivilageAdd)) KeyImages.Add(Interface.PNGPrivilageAdd);
if (!KeyImages.Contains(Interface.PNGPrivilageAlert)) KeyImages.Add(Interface.PNGPrivilageAlert);
if (!KeyImages.Contains(Interface.PNGPrivilageExpired)) KeyImages.Add(Interface.PNGPrivilageExpired);
}
public static void Unload() {
coroutineImg = null;
foreach (KeyValuePair<String, String> item in Images) FileStorage.server.RemoveExact(UInt32.Parse(item.Value), FileStorage.Type.png, CommunityEntity.ServerInstance.net.ID, 0U);
KeyImages.Clear();
KeyImages = null;
Images.Clear();
Images = null;
}
}
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 void OnUserPermissionRevoked(String id, String permName) => InformationPrivilagesUser.RemoveParametres(permName, UInt64.Parse(id), TypeData.Permission);
private class InterfaceBuilder {
public static InterfaceBuilder Instance;
public const String UI_POOPUP_PANEL = "UI_POOPUP_PANEL";
public Dictionary<String, String> Interfaces;
public InterfaceBuilder() {
Instance = this;
Interfaces = new Dictionary<String, String>();
BuildingPlayer_PopUp();
}
public static void AddInterface(String name, String json) {
if (Instance.Interfaces.ContainsKey(name)) {
_.PrintError($"Error #3915! Tried to add existing cui elements! -> {name}");
return;
}
Instance.Interfaces.Add(name, json);
}
public static String GetInterface(String name) {
String json = String.Empty;
if (Instance.Interfaces.TryGetValue(name, out json) == false) {
_.PrintWarning($"Warning! UI elements not found by name! -> {name}");
}
return json;
}
public static void DestroyAll() {
foreach (BasePlayer player in BasePlayer.activePlayerList) CuiHelper.DestroyUi(player, UI_POOPUP_PANEL);
}
private void BuildingPlayer_PopUp() {
CuiElementContainer container = new CuiElementContainer();
container.Add(new CuiElement {
Name = UI_POOPUP_PANEL, Parent = "Overlay", Components = {
new CuiRawImageComponent {
Color = "1 1 1 1", Png = "%PNGBackground%"
}
, new CuiRectTransformComponent {
AnchorMin = "1 0.5", AnchorMax = "1 0.5", OffsetMin = "-252.6 -135.1", OffsetMax = "7.4 -75.1"
}
}
}
);
container.Add(new CuiElement {
Name = "Icon", Parent = UI_POOPUP_PANEL, Components = {
new CuiRawImageComponent {
Color = "1 1 1 1", Png = "%ICON%"
}
, new CuiRectTransformComponent {
AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-116.9 -16", OffsetMax = "-84.9 16"
}
}
}
);
container.Add(new CuiElement {
Name = "Title", Parent = UI_POOPUP_PANEL, Components = {
new CuiTextComponent {
Text = "%TITLE%", Font = "robotocondensed-regular.ttf", FontSize = 16, Align = TextAnchor.MiddleCenter, Color = "%COLOR_TITLE%"
}
, new CuiRectTransformComponent {
AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-84.9 -2.06391", OffsetMax = "125.33 19.46391"
}
}
}
);
container.Add(new CuiElement {
Name = "Description", Parent = UI_POOPUP_PANEL, Components = {
new CuiTextComponent {
Text = "%DESCRIPTION%", Font = "robotocondensed-regular.ttf", FontSize = 10, Align = TextAnchor.UpperCenter, Color = "%COLOR_DESCRIPTION%"
}
, new CuiRectTransformComponent {
AnchorMin = "0.5 0.5", AnchorMax = "0.5 0.5", OffsetMin = "-84.9 -17.671", OffsetMax = "125.33 0"
}
}
}
);
AddInterface("UI_POOPUP_TEMPLATE", container.ToJson());
}
}
[ChatCommand("pinfo")]
private void ChatCommand_Pinfo(BasePlayer player) {
String ResultInfo = String.Empty;
Dictionary<String, DateTime> Group = InformationPrivilagesUser.GetParametresUser(player.userID, TypeData.Group);
Dictionary<String, DateTime> Permission = InformationPrivilagesUser.GetParametresUser(player.userID, TypeData.Permission);
if (Group.Count == 0 && Permission.Count == 0) {
SendChat(GetLang("PINFO_ALERT_NOT", player.UserIDString), player);
return;
}
ResultInfo = Group.Aggregate(ResultInfo, (current, group) => current + $"- {GetLanguageNamePrivilage(player, group.Key, TypeData.Group)} : {group.Value:MM/dd/yyyy HH:mm}\n");
if (!String.IsNullOrWhiteSpace(ResultInfo)) ResultInfo += "\n\n";
ResultInfo = Permission.Aggregate(ResultInfo, (current, permissions) => current + $"- {GetLanguageNamePrivilage(player, permissions.Key, TypeData.Permission)} : {permissions.Value:MM/dd/yyyy HH:mm}\n");
if (IQChat) IQChat?.Call("API_ALERT_PLAYER", player, GetLang("PINFO_ALERT", player.UserIDString, ResultInfo), config.AlertConfigurations.SettingIQChat.CustomPrefix, config.AlertConfigurations.SettingIQChat.CustomAvatar);
else player.SendConsoleCommand("chat.add", Chat.ChatChannel.Global, 0, GetLang("PINFO_ALERT", player.UserIDString, ResultInfo), player);
}
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" : "В БД были обновлены данные для пользователя");
}
);
}
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);
}
public class Fields {
public String name {
get;
set;
}
public String value {
get;
set;
}
public bool inline {
get;
set;
}
public Fields(String name, String value, bool inline) {
this.name = name;
this.value = value;
this.inline = inline;
}
}
private static InterfaceBuilder _interface;
private void PreLoadedPlugin() {
if(!ImageLibrary) {
NextTick(() => {
PrintError($"ImageLibrary not found! Please, check your plugins list.");
Interface.Oxide.UnloadPlugin(Name);
}
);
return;
}
SQL_OpenConnection();
}
[ConsoleCommand("revoke.group")]
private void RevomeGroup_TwoConsoleCommand(ConsoleSystem.Arg arg) => RemoveGroup_ConsoleCommand(arg);
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;
}
[ConsoleCommand("grantperm")]
private void GrantPerm_ConsoleCommand(ConsoleSystem.Arg arg) {
if (arg == null) return;
if(arg.Player() != null) return;
if (arg.Args == null || arg.Args.Length < 3 ) {
PrintError(LanguageEn ? "Syntax error, use: grantperm Steam64ID Permission Time(1d/1m/1s)" : "Ошибка синтаксиса, используйте : grantperm Steam64ID Permission Time(1d/1m/1s)");
return;
}
UInt64 userID;
if (!UInt64.TryParse(arg.Args[0], out userID)) {
PrintError(LanguageEn ? "You have specified an incorrect Steam64ID player!" : "Вы указали неккоректный Steam64ID игрока!");
return;
}
String Permission = arg.Args[1];
if (!config.PermissionList.ContainsKey(Permission)) {
PrintError(LanguageEn ? "The permission you specified do not exist!" : "Права которые вы указали - не существуют!");
return;
}
TimeSpan duration;
if (!TryParseTimeSpan(arg.Args[2], out duration)) {
PrintError(LanguageEn ? "You specified an incorrect time, use 1d/1m/1s!" : "Вы указали неккоректное время, используйте 1d/1m/1s!");
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Permission, userID, TypeData.Permission) + duration;
InformationPrivilagesUser.SetParametres(Permission, userID, ThisTime, TypeData.Permission);
}
private static Int64 ToEpochTime(DateTime dateTime) {
DateTime date = dateTime.ToLocalTime();
Int64 ticks = date.Ticks - new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks;
Int64 ts = ticks / TimeSpan.TicksPerSecond;
return ts;
}
[ConsoleCommand("grant.group")]
private void AddGroup_TwoConsoleCommand(ConsoleSystem.Arg arg) => AddGroup_ConsoleCommand(arg);
class StructureTimePrivilage {
public Dictionary<String, String> groups = new Dictionary<String, String>();
public Dictionary<String, String> permissions = new Dictionary<String, String>();
}
[ConsoleCommand("user.perms")]
private void GetUserPerms_ConsoleCommand(ConsoleSystem.Arg arg) {
if (arg == null) return;
if(arg.Player() != null) return;
if (arg.Args == null || arg.Args.Length < 1) {
PrintError(LanguageEn ? "Syntax error, use: user.perms Steam64ID" : "Ошибка синтаксиса, используйте : user.perms Steam64ID");
return;
}
UInt64 userID;
if (!UInt64.TryParse(arg.Args[0], out userID)) {
PrintError(LanguageEn ? "You have specified an incorrect Steam64ID player!" : "Вы указали неккоректный Steam64ID игрока!");
return;
}
Dictionary<String, DateTime> GetParametres = InformationPrivilagesUser.GetParametresUser(userID, TypeData.Permission);
String PermsList = GetParametres == null ? String.Empty : GetParametres.Aggregate(String.Empty, (current, keyValuePair) => current + $"- {keyValuePair.Key} | Expired : {keyValuePair.Value}\n");
String Information = LanguageEn ? $"Active Player Privileges {userID} ({GetParametres.Count} pieces(/s))\n{PermsList}" : $"Активные привилегии игрока {userID} ({GetParametres.Count} штук(/и))\n{PermsList}";
Puts(Information);
}
[ConsoleCommand("revokegroup")]
private void RemoveGroup_ConsoleCommand(ConsoleSystem.Arg arg) {
if (arg == null) return;
if(arg.Player() != null) return;
if (arg.Args == null || arg.Args.Length < 2) {
PrintError(LanguageEn ? "Syntax error, use: revokegroup Steam64ID Group" : "Ошибка синтаксиса, используйте : revokegroup Steam64ID Group");
return;
}
UInt64 userID;
if (!UInt64.TryParse(arg.Args[0], out userID)) {
PrintError(LanguageEn ? "You have specified an incorrect Steam64ID player!" : "Вы указали неккоректный Steam64ID игрока!");
return;
}
String Group = arg.Args[1];
if (!config.PermissionList.ContainsKey(Group)) {
PrintError(LanguageEn ? "The group you specified do not exist!" : "Группа которую вы указали - не существуют!");
return;
}
if (!permission.UserHasGroup(userID.ToString(), Group)) {
PrintError(LanguageEn ? "The player does not have this group!" : "У игрока отсутствуют данная группа!");
return;
}
if (arg.Args.Length == 3) {
TimeSpan duration;
if (!TryParseTimeSpan(arg.Args[2], out duration)) {
PrintError(LanguageEn ? "You specified an incorrect time, use 1d/1m/1s!" : "Вы указали неккоректное время, используйте 1d/1m/1s!");
return;
}
DateTime ThisTime = InformationPrivilagesUser.GetExpiredPermissionData(Group, userID, TypeData.Group) - duration;
InformationPrivilagesUser.RemoveParametres(Group, userID, TypeData.Group, ThisTime);
return;
}
InformationPrivilagesUser.RemoveParametres(Group, userID, TypeData.Group);
}
private void StartPluginLoad() {
_ = this;
//Load your images here
ImageUi.Initialize();
ImageUi.DownloadImages();
}
private IEnumerator MigrationTimedPermissions() {
if (!Interface.Oxide.DataFileSystem.ExistsDatafile("TimedPermissions")) {
Puts(LanguageEn ? "TimedPermissions file - does not exist, migration is not possible" : "Файла TimedPermissions - не существует, миграция невозможна");
yield break;
}
Puts(LanguageEn ? "Starting the migration from the plugin TimedPermissions -> IQPermissions (This may take some time, depending on the number of entries)" : "Запускаем миграцию из плагина TimedPermissions -> IQPermissions (Это может занять некоторое время, в зависимости от количество записей)");
List<PlayerInformation> dataFile = Interface.Oxide.DataFileSystem.ReadObject<List<PlayerInformation>>("TimedPermissions");
foreach (PlayerInformation playerInformation in dataFile) {
UInt64 userID;
if(!UInt64.TryParse(playerInformation.Id, out userID)) continue;
foreach (ExpiringAccessValue informationPermission in playerInformation._permissions.Where(x => !x.IsExpired)) {
InformationPrivilagesUser.SetParametres(informationPermission.Value, userID, informationPermission.ExpireDate, TypeData.Permission);
yield return CoroutineEx.waitForSeconds(0.15f);
}
foreach (ExpiringAccessValue playerInformationGroup in playerInformation._groups.Where(x => !x.IsExpired)) {
InformationPrivilagesUser.SetParametres(playerInformationGroup.Value, userID, playerInformationGroup.ExpireDate, TypeData.Group);
yield return CoroutineEx.waitForSeconds(0.15f);
}
yield return CoroutineEx.waitForSeconds(0.25f);
}
Interface.Oxide.UnloadPlugin("TimedPermissions");
Puts(LanguageEn ? "Migration is complete, TimedPermissions has been unloaded! (Don't forget to remove the TimedPermissions for stable operation)" : "Миграция завершена, TimedPermissions был выгружен! (Не забудьте удалить TimedPermissions для стабильной работы)");
if (coroutineMigration != null) {
ServerMgr.Instance.StopCoroutine(coroutineMigration);
coroutineMigration = null;
}
}
public void RevokeGroup(UInt64 userID, String Group, DateTime DataExpired = default(DateTime)) => InformationPrivilagesUser.RemoveParametres(Group, userID, TypeData.Group, DataExpired);
private void AlertPlayer(UInt64 userID, TypeAlert typeAlert, String Key, TypeData typeData, String DataExpired) {
BasePlayer player = BasePlayer.FindByID(userID);
if (player == null) return;
if (UAlertSystem) {
String ReplaceKey = GetLanguageNamePrivilage(player, Key, typeData);
if (ReplaceKey == null) return;
UAlertSystem.CallHook("API_SEND_ALERT", GetLang(GetTitle(typeAlert), userID.ToString()), GetDescription(userID.ToString(), typeAlert, ReplaceKey, DataExpired), "0.8490566 0.260324 0.260324 1", "1 1 1 1", 5f);
// ... [Code preview truncated due to length. Full source in attached file] ...