C#:
using Oxide.Game.Rust.Cui;
using Oxide.Core.Database;
using Object = System.Object;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System;
using Newtonsoft.Json.Linq;
using System.Collections;
using Newtonsoft.Json;
using Oxide.Core.Libraries;
using Oxide.Core.Plugins;
using ConVar;
using System.Text;
using Oxide.Core;
using UnityEngine.Networking;
using System.Linq;
using UnityEngine;
///Скачано с дискорд сервера Rust Edit [PRO+]
///discord.gg/9vyTXsJyKR
namespace Oxide.Plugins {
[Info("IQPermissions", "discord.gg/9vyTXsJyKR", "1.3.2")]
[Description("Krytoy plugin")]
public class IQPermissions : RustPlugin {
private static Configuration config = new Configuration();
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");
}
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 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 Connection sqlConnection = null;
private String Format(Int32 units, String form1, String form2, String form3) {
var tmp = units % 10;
if (units >= 5 && units <= 20 || tmp >= 5 && tmp <= 9) return $"{units}{form1}";
if (tmp >= 2 && tmp <= 4) return $"{units}{form2}";
return $"{units}{form3}";
}
[JsonProperty(LanguageEn ? "Information about privileges" : "Информация о привилегиях")]
private StructureData InformationPrivilagesUser = new StructureData();
private void OnGroupCreated(String name) => NewGroupRegistered(name);
public void RevokePermission(UInt64 userID, String Permission, DateTime DataExpired = default(DateTime)) => InformationPrivilagesUser.RemoveParametres(Permission, userID, TypeData.Permission, DataExpired);
[ConsoleCommand("revoke.group")]
private void RevomeGroup_TwoConsoleCommand(ConsoleSystem.Arg arg) => RemoveGroup_ConsoleCommand(arg);
class StructureTimePrivilage {
public Dictionary<String, String> groups = new Dictionary<String, String>();
public Dictionary<String, String> permissions = new Dictionary<String, String>();
}
public void SetGroup(UInt64 userID, String Group, DateTime DataExpired) => InformationPrivilagesUser.SetParametres(Group, userID, DataExpired, TypeData.Group);
private void OnServerInitialized() {
GrablingPermissions();
GrablingGroups();
PreLoadedPlugin();
StartPluginLoad();
}
[ConsoleCommand("revoke.permission")]
private void RevokePerm_TwoConsoleCommand(ConsoleSystem.Arg arg) => RevokePerm_ConsoleCommand(arg);
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() {
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 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 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);
}
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);
}
[ConsoleCommand("group.users")]
private void GetInfoGroup_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: group.users Group" : "Ошибка синтаксиса, используйте : group.users Group");
return;
}
String Group = arg.Args[0];
if (!config.GroupList.ContainsKey(Group)) {
PrintError(LanguageEn ? "The group you specified do not exist!" : "Группу которую вы указали - не существуют!");
return;
}
Dictionary<UInt64, DateTime> GetPlayers = InformationPrivilagesUser.GePlayerList(Group, TypeData.Group);
String PlayerList = GetPlayers == null ? String.Empty : GetPlayers.Aggregate(String.Empty, (current, Players) => current + $"- ID : {Players.Key} | Expired : {GetLeftTime(Players.Value, Players.Key.ToString())}\n");
String Information = LanguageEn ? $"Total with active privileges ({Group}) found {GetPlayers.Count} players\n{PlayerList}" : $"Всего с активной привилегий ({Group}) найдено {GetPlayers.Count} игроков\n{PlayerList}";
Puts(Information);
}
public class FancyMessage {
public String content {
get;
set;
}
public Boolean tts {
get;
set;
}
public Embeds[] embeds {
get;
set;
}
public class Embeds {
public String title {
get;
set;
}
public Int32 color {
get;
set;
}
public List<Fields> fields {
get;
set;
}
public Footer footer {
get;
set;
}
public Authors author {
get;
set;
}
public Embeds(String title, Int32 color, List<Fields> fields, Authors author, Footer footer) {
this.title = title;
this.color = color;
this.fields = fields;
this.author = author;
this.footer = footer;
}
}
public FancyMessage(String content, bool tts, Embeds[] embeds) {
this.content = content;
this.tts = tts;
this.embeds = embeds;
}
public String toJSON() => JsonConvert.SerializeObject(this);
}
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;
}
private void DrawUI_PoopUp(BasePlayer player, TypeAlert typeAlert, String Key, TypeData typeData, String DataExpired) {
String Interface = InterfaceBuilder.GetInterface("UI_POOPUP_TEMPLATE");
if (Interface == null) return;
String ReplaceKey = GetLanguageNamePrivilage(player, Key, typeData);
if (ReplaceKey == null) return;
Configuration.InterfaceConfiguration Interfaces = config.InterfaceSetting;
Interface = Interface.Replace("%PNGBackground%", ImageUi.GetImage(Interfaces.PNGBackground));
Interface = Interface.Replace("%ICON%", GetIcon(typeAlert));
Interface = Interface.Replace("%TITLE%", GetLang(GetTitle(typeAlert), player.UserIDString));
Interface = Interface.Replace("%DESCRIPTION%", GetDescription(player.UserIDString, typeAlert, ReplaceKey, DataExpired));
Interface = Interface.Replace("%COLOR_TITLE%", Interfaces.RGBAColorTitle);
Interface = Interface.Replace("%COLOR_DESCRIPTION%", Interfaces.RGBAColorDescription);
CuiHelper.DestroyUi(player, InterfaceBuilder.UI_POOPUP_PANEL);
CuiHelper.AddUi(player, Interface);
player.Invoke(() => CuiHelper.DestroyUi(player, InterfaceBuilder.UI_POOPUP_PANEL), config.AlertConfigurations.TimeAlert);
}
public Dictionary<String, DateTime> GetPermissions(UInt64 userID) => InformationPrivilagesUser.GetParametresUser(userID, TypeData.Permission);
private class PlayerInformation {
[JsonProperty("Id")]
public string Id {
get;
set;
}
[JsonProperty("Name")]
public string Name {
get;
set;
}
[JsonProperty("Permissions")]
public List<ExpiringAccessValue> _permissions = new List<ExpiringAccessValue>();
[JsonProperty("Groups")]
public List<ExpiringAccessValue> _groups = new List<ExpiringAccessValue>();
}
private class ExpiringAccessValue {
[JsonProperty]
public string Value {
get;
private set;
}
[JsonProperty]
public DateTime ExpireDate {
get;
set;
}
[JsonIgnore]
public bool IsExpired => DateTime.Compare(DateTime.UtcNow, ExpireDate) > 0;
}
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" : "В БД была удалена информация пользователя");
}
);
}
private void NewPermissionRegistered(String Permission) {
if(config.PermissionList.ContainsKey(Permission)) return;
String ExampleName = Permission.Substring(Permission.IndexOf('.') + 1).ToUpper();
config.PermissionList.Add(Permission, new Configuration.StructureLanguage(ExampleName, ExampleName));
Puts(LanguageEn ?$"A new permission {Permission} has been added to the configuration file" : $"В конфигурационный файл была добавлена новое право {Permission}");
SaveConfig();
}
private IEnumerator MigrationTimePrivilage() {
if (!Interface.Oxide.DataFileSystem.ExistsDatafile("Timeprivileges")) {
Puts(LanguageEn ? "Timeprivileges file - does not exist, migration is not possible" : "Файла Timeprivileges - не существует, миграция невозможна");
yield break;
}
Puts(LanguageEn ? "Starting the migration from the plugin TimePrivilage -> IQPermissions (This may take some time, depending on the number of entries)" : "Запускаем миграцию из плагина TimePrivilage -> IQPermissions (Это может занять некоторое время, в зависимости от количество записей)");
Dictionary<String, StructureTimePrivilage> dataFile = Interface.Oxide.DataFileSystem.ReadObject<Dictionary<String, StructureTimePrivilage>>("Timeprivileges");
foreach (KeyValuePair<String, StructureTimePrivilage> timePrivilage in dataFile) {
UInt64 userID;
if (!UInt64.TryParse(timePrivilage.Key, out userID)) continue;
foreach (KeyValuePair<String, String> Permissions in timePrivilage.Value.permissions) {
DateTime Time = Convert.ToDateTime(Permissions.Value);
InformationPrivilagesUser.SetParametres(Permissions.Key, userID, Time, TypeData.Permission);
yield return CoroutineEx.waitForSeconds(0.15f);
}
foreach (KeyValuePair<String, String> Groups in timePrivilage.Value.groups) {
DateTime Time = Convert.ToDateTime(Groups.Value);
InformationPrivilagesUser.SetParametres(Groups.Key, userID, Time, TypeData.Group);
yield return CoroutineEx.waitForSeconds(0.15f);
}
yield return CoroutineEx.waitForSeconds(0.25f);
}
Interface.Oxide.UnloadPlugin("TimePrivilage");
Puts(LanguageEn ? "Migration is complete, TimePrivilege has been unloaded! (Don't forget to remove the TimePrivilage for stable operation)" : "Миграция завершена, TimePrivilage был выгружен! (Не забудьте удалить TimePrivilage для стабильной работы)");
if (coroutineMigration != null) {
ServerMgr.Instance.StopCoroutine(coroutineMigration);
coroutineMigration = null;
}
}
public void RevokeGroup(UInt64 userID, String Group, 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(Group, userID, TypeData.Group) - duration;
InformationPrivilagesUser.RemoveParametres(Group, userID, TypeData.Group, ThisTime);
return;
}
InformationPrivilagesUser.RemoveParametres(Group, userID, TypeData.Group);
}
private Boolean TryParseTimeSpan(String source, out TimeSpan timeSpan) {
Int32 seconds = 0, minutes = 0, hours = 0, days = 0;
Match s = new Regex(@"(\d+?)s", RegexOptions.IgnoreCase).Match(source);
Match m = new Regex(@"(\d+?)m", RegexOptions.IgnoreCase).Match(source);
Match h = new Regex(@"(\d+?)h", RegexOptions.IgnoreCase).Match(source);
Match d = new Regex(@"(\d+?)d", RegexOptions.IgnoreCase).Match(source);
if (s.Success) seconds = Convert.ToInt32(s.Groups[1].ToString());
if (m.Success) minutes = Convert.ToInt32(m.Groups[1].ToString());
if (h.Success) hours = Convert.ToInt32(h.Groups[1].ToString());
if (d.Success) days = Convert.ToInt32(d.Groups[1].ToString());
source = source.Replace(seconds + "s", string.Empty);
source = source.Replace(minutes + "m", string.Empty);
source = source.Replace(hours + "h", string.Empty);
source = source.Replace(days + "d", string.Empty);
if (!String.IsNullOrEmpty(source) || (!s.Success && !m.Success && !h.Success && !d.Success)) {
timeSpan = default(TimeSpan);
return false;
}
timeSpan = new TimeSpan(days, hours, minutes, seconds);
return true;
}
private static StringBuilder sb = new StringBuilder();
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;
}
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() {
if (config.GeneralSettings.UseRemovePermissionsХWhenUnload) {
_.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}", _);
}
}
if (config.GeneralSettings.UseRemoveGroupsWhenUnload) {
_.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() {
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 StartPluginLoad() {
_ = this;
//Load your images here
ImageUi.Initialize();
ImageUi.DownloadImages();
}
private readonly Core.MySql.Libraries.MySql sqlLibrary = Interface.Oxide.GetLibrary<Core.MySql.Libraries.MySql>();
private static Coroutine coroutineMigration = null;
private void OnPermissionRegistered(String name, Plugin owner) => NewPermissionRegistered(name);
public String FormatTime(TimeSpan time, String UserID) {
String Result = String.Empty;
String Days = GetLang("TITLE_FORMAT_DAYS", UserID);
String Hourse = GetLang("TITLE_FORMAT_HOURSE", UserID);
String Minutes = GetLang("TITLE_FORMAT_MINUTES", UserID);
String Seconds = GetLang("TITLE_FORMAT_SECONDS", UserID);
if (time.Days != 0) Result += $"{Format(time.Days, Days, Days, Days)} ";
if (time.Hours != 0) Result += $"{Format(time.Hours, Hourse, Hourse, Hourse)} ";
if (time.Minutes != 0) Result += $"{Format(time.Minutes, Minutes, Minutes, Minutes)} ";
if (time.Days == 0 && time.Hours == 0 && time.Minutes == 0 && time.Seconds != 0) Result = $"{Format(time.Seconds, Seconds, Seconds, Seconds)} ";
return Result;
}
private void OnPlayerConnected(BasePlayer player) {
MigrationPrivilage(player);
SetupAutoPrivilages(player);
if (config.AlertConfigurations.UseAlertedGroup || config.AlertConfigurations.UseAlertedPermission) {
if (!RoutineQueue.ContainsKey(player.userID)) RoutineQueue.Add(player.userID, ServerMgr.Instance.StartCoroutine(JoinedAlertPlayer(player)));
else RoutineQueue[player.userID] = ServerMgr.Instance.StartCoroutine(JoinedAlertPlayer(player));
}
}
protected override void LoadDefaultConfig() => config = Configuration.GetNewConfiguration();
[ConsoleCommand("grant.group")]
private void AddGroup_TwoConsoleCommand(ConsoleSystem.Arg arg) => AddGroup_ConsoleCommand(arg);
private void OnUserGroupRemoved(String id, String groupName) => InformationPrivilagesUser.RemoveParametres(groupName, UInt64.Parse(id), TypeData.Group);
public void SetPermission(UInt64 userID, String Permission, DateTime DataExpired) => InformationPrivilagesUser.SetParametres(Permission, userID, DataExpired, TypeData.Permission);
private const Boolean LanguageEn = false;
private void Init() => ReadData();
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 static InterfaceBuilder _interface;
private String GetLeftTime(DateTime dateExpired, String userID) {
System.TimeSpan DiffTime = dateExpired.Subtract(DateTime.Now);
String LeftTime = _.FormatTime(TimeSpan.FromSeconds(DiffTime.TotalSeconds), userID);
return LeftTime;
}
[ConsoleCommand("migration.grant")]
private void GrantMigration(ConsoleSystem.Arg arg) {
if (arg.Player() != null) return;
coroutineMigration = ServerMgr.Instance.StartCoroutine(MigrationGrant());
}
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);
}
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;
}
}
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;
}
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 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 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);
}
public class Footer {
public String text {
get;
set;
}
public String icon_url {
get;
set;
}
public String proxy_icon_url {
get;
set;
}
public Footer(String text, String icon_url, String proxy_icon_url) {
this.text = text;
this.icon_url = icon_url;
this.proxy_icon_url = proxy_icon_url;
}
}
public class Authors {
public String name {
get;
set;
}
public String url {
get;
set;
}
public String icon_url {
get;
set;
}
public String proxy_icon_url {
get;
set;
}
public Authors(String name, String url, String icon_url, String proxy_icon_url) {
this.name = name;
this.url = url;
this.icon_url = icon_url;
this.proxy_icon_url = proxy_icon_url;
}
}
[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) {
P
// ... [Code preview truncated due to length. Full source in attached file] ...