Removed module projects because it can't work like that atm. Commented out package commands.

This commit is contained in:
Master Kwoth
2017-10-15 09:39:46 +02:00
parent 90e71a3a30
commit 696a0eb2a7
180 changed files with 21625 additions and 1058 deletions

View File

@ -1,195 +0,0 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace NadekoBot.Modules.Administration.Common.Migration
{
public class CommandPrefixes0_9
{
public string Administration { get; set; }
public string Searches { get; set; }
public string NSFW { get; set; }
public string Conversations { get; set; }
public string ClashOfClans { get; set; }
public string Help { get; set; }
public string Music { get; set; }
public string Trello { get; set; }
public string Games { get; set; }
public string Gambling { get; set; }
public string Permissions { get; set; }
public string Programming { get; set; }
public string Pokemon { get; set; }
public string Utility { get; set; }
}
public class Config0_9
{
public bool DontJoinServers { get; set; }
public bool ForwardMessages { get; set; }
public bool ForwardToAllOwners { get; set; }
public bool IsRotatingStatus { get; set; }
public int BufferSize { get; set; }
public List<string> RaceAnimals { get; set; }
public string RemindMessageFormat { get; set; }
public Dictionary<string, List<string>> CustomReactions { get; set; }
public List<string> RotatingStatuses { get; set; }
public CommandPrefixes0_9 CommandPrefixes { get; set; }
public List<ulong> ServerBlacklist { get; set; }
public List<ulong> ChannelBlacklist { get; set; }
public List<ulong> UserBlacklist { get; set; }
public List<string> _8BallResponses { get; set; }
public string CurrencySign { get; set; }
public string CurrencyName { get; set; }
public string DMHelpString { get; set; }
public string HelpString { get; set; }
}
/// <summary>
/// Holds a permission list
/// </summary>
public class Permissions
{
/// <summary>
/// Name of the parent object whose permissions these are
/// </summary>
public string Name { get; set; }
/// <summary>
/// Module name with allowed/disallowed
/// </summary>
public ConcurrentDictionary<string, bool> Modules { get; set; }
/// <summary>
/// Command name with allowed/disallowed
/// </summary>
public ConcurrentDictionary<string, bool> Commands { get; set; }
/// <summary>
/// Should the bot filter invites to other discord servers (and ref links in the future)
/// </summary>
public bool FilterInvites { get; set; }
/// <summary>
/// Should the bot filter words which are specified in the Words hashset
/// </summary>
public bool FilterWords { get; set; }
public Permissions(string name)
{
Name = name;
Modules = new ConcurrentDictionary<string, bool>();
Commands = new ConcurrentDictionary<string, bool>();
FilterInvites = false;
FilterWords = false;
}
public void CopyFrom(Permissions other)
{
Modules.Clear();
foreach (var mp in other.Modules)
Modules.AddOrUpdate(mp.Key, mp.Value, (s, b) => mp.Value);
Commands.Clear();
foreach (var cp in other.Commands)
Commands.AddOrUpdate(cp.Key, cp.Value, (s, b) => cp.Value);
FilterInvites = other.FilterInvites;
FilterWords = other.FilterWords;
}
public override string ToString()
{
var toReturn = "";
var bannedModules = Modules.Where(kvp => kvp.Value == false);
var bannedModulesArray = bannedModules as KeyValuePair<string, bool>[] ?? bannedModules.ToArray();
if (bannedModulesArray.Any())
{
toReturn += "`Banned Modules:`\n";
toReturn = bannedModulesArray.Aggregate(toReturn, (current, m) => current + $"\t`[x] {m.Key}`\n");
}
var bannedCommands = Commands.Where(kvp => kvp.Value == false);
var bannedCommandsArr = bannedCommands as KeyValuePair<string, bool>[] ?? bannedCommands.ToArray();
if (bannedCommandsArr.Any())
{
toReturn += "`Banned Commands:`\n";
toReturn = bannedCommandsArr.Aggregate(toReturn, (current, c) => current + $"\t`[x] {c.Key}`\n");
}
return toReturn;
}
}
public class ServerPermissions0_9
{
/// <summary>
/// The guy who can edit the permissions
/// </summary>
public string PermissionsControllerRole { get; set; }
/// <summary>
/// Does it print the error when a restriction occurs
/// </summary>
public bool Verbose { get; set; }
/// <summary>
/// The id of the thing (user/server/channel)
/// </summary>
public ulong Id { get; set; } //a string because of the role name.
/// <summary>
/// Permission object bound to the id of something/role name
/// </summary>
public Permissions Permissions { get; set; }
/// <summary>
/// Banned words, usually profanities, like word "java"
/// </summary>
public HashSet<string> Words { get; set; }
public Dictionary<ulong, Permissions> UserPermissions { get; set; }
public Dictionary<ulong, Permissions> ChannelPermissions { get; set; }
public Dictionary<ulong, Permissions> RolePermissions { get; set; }
/// <summary>
/// Dictionary of command names with their respective cooldowns
/// </summary>
public ConcurrentDictionary<string, int> CommandCooldowns { get; set; }
public ServerPermissions0_9(ulong id, string name)
{
Id = id;
PermissionsControllerRole = "Nadeko";
Verbose = true;
Permissions = new Permissions(name);
Permissions.Modules.TryAdd("NSFW", false);
UserPermissions = new Dictionary<ulong, Permissions>();
ChannelPermissions = new Dictionary<ulong, Permissions>();
RolePermissions = new Dictionary<ulong, Permissions>();
CommandCooldowns = new ConcurrentDictionary<string, int>();
Words = new HashSet<string>();
}
}
public class ServerSpecificConfig
{
public bool VoicePlusTextEnabled { get; set; }
public bool SendPrivateMessageOnMention { get; set; }
public ulong? LogChannel { get; set; } = null;
public ulong? LogPresenceChannel { get; set; } = null;
public HashSet<ulong> LogserverIgnoreChannels { get; set; }
public ConcurrentDictionary<ulong, ulong> VoiceChannelLog { get; set; }
public HashSet<ulong> ListOfSelfAssignableRoles { get; set; }
public ulong AutoAssignedRole { get; set; }
public ConcurrentDictionary<ulong, int> GenerateCurrencyChannels { get; set; }
public bool AutoDeleteMessagesOnCommand { get; set; }
public bool ExclusiveSelfAssignedRoles { get; set; }
public float DefaultMusicVolume { get; set; }
public HashSet<StreamNotificationConfig0_9> ObservingStreams { get; set; }
}
public class StreamNotificationConfig0_9
{
public string Username { get; set; }
public StreamType Type { get; set; }
public ulong ServerId { get; set; }
public ulong ChannelId { get; set; }
public bool LastStatus { get; set; }
public enum StreamType
{
Twitch,
Beam,
Hitbox,
YoutubeGaming
}
}
}

View File

@ -1,9 +0,0 @@
using System;
namespace NadekoBot.Modules.Administration.Common.Migration
{
public class MigrationException : Exception
{
}
}

View File

@ -1,381 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Discord.Commands;
using NadekoBot.Core.Services;
using NadekoBot.Core.Services.Database.Models;
using Newtonsoft.Json;
using System.Collections.Concurrent;
using NadekoBot.Extensions;
using NadekoBot.Core.Services.Database;
using Microsoft.Data.Sqlite;
using NadekoBot.Common.Attributes;
using NadekoBot.Common.Collections;
using NadekoBot.Modules.Administration.Common.Migration;
namespace NadekoBot.Modules.Administration
{
public partial class Administration
{
[Group]
public class MigrationCommands : NadekoSubmodule
{
private const int CURRENT_VERSION = 1;
private readonly DbService _db;
public MigrationCommands(DbService db)
{
_db = db;
}
[NadekoCommand, Usage, Description, Aliases]
[OwnerOnly]
public async Task MigrateData()
{
var version = 0;
using (var uow = _db.UnitOfWork)
{
version = uow.BotConfig.GetOrCreate().MigrationVersion;
}
try
{
for (var i = version; i < CURRENT_VERSION; i++)
{
switch (i)
{
case 0:
Migrate0_9To1_0();
break;
}
}
await ReplyConfirmLocalized("migration_done").ConfigureAwait(false);
}
catch (Exception ex)
{
_log.Error(ex);
await ReplyErrorLocalized("migration_error").ConfigureAwait(false);
}
}
private void Migrate0_9To1_0()
{
using (var uow = _db.UnitOfWork)
{
var botConfig = uow.BotConfig.GetOrCreate();
MigrateConfig0_9(uow, botConfig);
MigratePermissions0_9(uow);
MigrateServerSpecificConfigs0_9(uow);
MigrateDb0_9(uow);
//NOW save it
_log.Warn("Writing to disc");
uow.Complete();
botConfig.MigrationVersion = 1;
}
}
private void MigrateDb0_9(IUnitOfWork uow)
{
var db = new SqliteConnection("Data Source=data/nadekobot.sqlite");
if (!File.Exists("data/nadekobot.sqlite"))
{
_log.Warn("No data from the old database will be migrated.");
return;
}
db.Open();
var com = db.CreateCommand();
var i = 0;
try
{
com.CommandText = "SELECT * FROM Announcement";
var reader = com.ExecuteReader();
while (reader.Read())
{
var gid = (ulong)(long)reader["ServerId"];
var greet = (long)reader["Greet"] == 1;
var greetDM = (long)reader["GreetPM"] == 1;
var greetChannel = (ulong)(long)reader["GreetChannelId"];
var greetMsg = (string)reader["GreetText"];
var bye = (long)reader["Bye"] == 1;
var byeChannel = (ulong)(long)reader["ByeChannelId"];
var byeMsg = (string)reader["ByeText"];
var gc = uow.GuildConfigs.For(gid, set => set);
if (greetDM)
gc.SendDmGreetMessage = greet;
else
gc.SendChannelGreetMessage = greet;
gc.GreetMessageChannelId = greetChannel;
gc.ChannelGreetMessageText = greetMsg;
gc.SendChannelByeMessage = bye;
gc.ByeMessageChannelId = byeChannel;
gc.ChannelByeMessageText = byeMsg;
_log.Info(++i);
}
}
catch {
_log.Warn("Greet/bye messages won't be migrated");
}
var com2 = db.CreateCommand();
com2.CommandText = "SELECT * FROM CurrencyState GROUP BY UserId";
i = 0;
try
{
var reader2 = com2.ExecuteReader();
while (reader2.Read())
{
_log.Info(++i);
var curr = new Currency()
{
Amount = (long)reader2["Value"],
UserId = (ulong)(long)reader2["UserId"]
};
uow.Currency.Add(curr);
}
}
catch
{
_log.Warn("Currency won't be migrated");
}
db.Close();
try { File.Move("data/nadekobot.sqlite", "data/DELETE_ME_nadekobot.sqlite"); } catch { }
}
private void MigrateServerSpecificConfigs0_9(IUnitOfWork uow)
{
const string specificConfigsPath = "data/ServerSpecificConfigs.json";
if (!File.Exists(specificConfigsPath))
{
_log.Warn($"No data from {specificConfigsPath} will be migrated.");
return;
}
var configs = new ConcurrentDictionary<ulong, ServerSpecificConfig>();
try
{
configs = JsonConvert
.DeserializeObject<ConcurrentDictionary<ulong, ServerSpecificConfig>>(
File.ReadAllText(specificConfigsPath), new JsonSerializerSettings()
{
Error = (s, e) =>
{
if (e.ErrorContext.Member.ToString() == "GenerateCurrencyChannels")
{
e.ErrorContext.Handled = true;
}
}
});
}
catch (Exception ex)
{
_log.Warn(ex, "ServerSpecificConfig deserialization failed");
return;
}
var i = 0;
var selfAssRoles = new ConcurrentHashSet<SelfAssignedRole>();
configs
.Select(p => new { data = p.Value, gconfig = uow.GuildConfigs.For(p.Key) })
.AsParallel()
.ForAll(config =>
{
try
{
var guildConfig = config.gconfig;
var data = config.data;
guildConfig.AutoAssignRoleId = data.AutoAssignedRole;
guildConfig.DeleteMessageOnCommand = data.AutoDeleteMessagesOnCommand;
guildConfig.DefaultMusicVolume = data.DefaultMusicVolume;
guildConfig.ExclusiveSelfAssignedRoles = data.ExclusiveSelfAssignedRoles;
guildConfig.GenerateCurrencyChannelIds = new HashSet<GCChannelId>(data.GenerateCurrencyChannels.Select(gc => new GCChannelId() { ChannelId = gc.Key }));
selfAssRoles.AddRange(data.ListOfSelfAssignableRoles.Select(r => new SelfAssignedRole() { GuildId = guildConfig.GuildId, RoleId = r }).ToArray());
guildConfig.LogSetting.IgnoredChannels = new HashSet<IgnoredLogChannel>(data.LogserverIgnoreChannels.Select(id => new IgnoredLogChannel() { ChannelId = id }));
guildConfig.LogSetting.LogUserPresenceId = data.LogPresenceChannel;
guildConfig.FollowedStreams = new HashSet<FollowedStream>(data.ObservingStreams.Select(x =>
{
FollowedStream.FollowedStreamType type = FollowedStream.FollowedStreamType.Twitch;
switch (x.Type)
{
case StreamNotificationConfig0_9.StreamType.Twitch:
type = FollowedStream.FollowedStreamType.Twitch;
break;
case StreamNotificationConfig0_9.StreamType.Beam:
type = FollowedStream.FollowedStreamType.Mixer;
break;
case StreamNotificationConfig0_9.StreamType.Hitbox:
type = FollowedStream.FollowedStreamType.Smashcast;
break;
default:
break;
}
return new FollowedStream()
{
ChannelId = x.ChannelId,
GuildId = guildConfig.GuildId,
Username = x.Username.ToLowerInvariant(),
Type = type
};
}));
guildConfig.VoicePlusTextEnabled = data.VoicePlusTextEnabled;
_log.Info("Migrating SpecificConfig for {0} done ({1})", guildConfig.GuildId, ++i);
}
catch (Exception ex)
{
_log.Error(ex);
}
});
uow.SelfAssignedRoles.AddRange(selfAssRoles.ToArray());
try { File.Move("data/ServerSpecificConfigs.json", "data/DELETE_ME_ServerSpecificCOnfigs.json"); } catch { }
}
private void MigratePermissions0_9(IUnitOfWork uow)
{
var permissionsDict = new ConcurrentDictionary<ulong, ServerPermissions0_9>();
if (!Directory.Exists("data/permissions/"))
{
_log.Warn("No data from permissions will be migrated.");
return;
}
foreach (var file in Directory.EnumerateFiles("data/permissions/"))
{
try
{
var strippedFileName = Path.GetFileNameWithoutExtension(file);
if (string.IsNullOrWhiteSpace(strippedFileName)) continue;
var id = ulong.Parse(strippedFileName);
var data = JsonConvert.DeserializeObject<ServerPermissions0_9>(File.ReadAllText(file));
permissionsDict.TryAdd(id, data);
}
catch
{
// ignored
}
}
var i = 0;
permissionsDict
.Select(p => new { data = p.Value, gconfig = uow.GuildConfigs.For(p.Key) })
.AsParallel()
.ForAll(perms =>
{
try
{
var data = perms.data;
var gconfig = perms.gconfig;
gconfig.PermissionRole = data.PermissionsControllerRole;
gconfig.VerbosePermissions = data.Verbose;
gconfig.FilteredWords = new HashSet<FilteredWord>(data.Words.Select(w => w.ToLowerInvariant())
.Distinct()
.Select(w => new FilteredWord() { Word = w }));
gconfig.FilterWords = data.Permissions.FilterWords;
gconfig.FilterInvites = data.Permissions.FilterInvites;
gconfig.FilterInvitesChannelIds = new HashSet<FilterChannelId>();
gconfig.FilterInvitesChannelIds.AddRange(data.ChannelPermissions.Where(kvp => kvp.Value.FilterInvites)
.Select(cp => new FilterChannelId()
{
ChannelId = cp.Key
}));
gconfig.FilterWordsChannelIds = new HashSet<FilterChannelId>();
gconfig.FilterWordsChannelIds.AddRange(data.ChannelPermissions.Where(kvp => kvp.Value.FilterWords)
.Select(cp => new FilterChannelId()
{
ChannelId = cp.Key
}));
gconfig.CommandCooldowns = new HashSet<CommandCooldown>(data.CommandCooldowns
.Where(cc => !string.IsNullOrWhiteSpace(cc.Key) && cc.Value > 0)
.Select(cc => new CommandCooldown()
{
CommandName = cc.Key,
Seconds = cc.Value
}));
_log.Info("Migrating data from permissions folder for {0} done ({1})", gconfig.GuildId, ++i);
}
catch (Exception ex)
{
_log.Error(ex);
}
});
try { Directory.Move("data/permissions", "data/DELETE_ME_permissions"); } catch { }
}
private void MigrateConfig0_9(IUnitOfWork uow, BotConfig botConfig)
{
Config0_9 oldConfig;
const string configPath = "data/config.json";
try
{
oldConfig = JsonConvert.DeserializeObject<Config0_9>(File.ReadAllText(configPath));
}
catch (FileNotFoundException)
{
_log.Warn("config.json not found");
return;
}
catch (Exception)
{
_log.Error("Unknown error while deserializing file config.json, pls check its integrity, aborting migration");
throw new MigrationException();
}
//Basic
botConfig.ForwardMessages = oldConfig.ForwardMessages;
botConfig.ForwardToAllOwners = oldConfig.ForwardToAllOwners;
botConfig.BufferSize = (ulong)oldConfig.BufferSize;
botConfig.RemindMessageFormat = oldConfig.RemindMessageFormat;
botConfig.CurrencySign = oldConfig.CurrencySign;
botConfig.CurrencyName = oldConfig.CurrencyName;
botConfig.DMHelpString = oldConfig.DMHelpString;
botConfig.HelpString = oldConfig.HelpString;
//messages
botConfig.RotatingStatuses = oldConfig.IsRotatingStatus;
var messages = new List<PlayingStatus>();
oldConfig.RotatingStatuses.ForEach(i => messages.Add(new PlayingStatus { Status = i }));
botConfig.RotatingStatusMessages = messages;
//Blacklist
var blacklist = new HashSet<BlacklistItem>(oldConfig.ServerBlacklist.Select(server => new BlacklistItem() { ItemId = server, Type = BlacklistType.Server }));
blacklist.AddRange(oldConfig.ChannelBlacklist.Select(channel => new BlacklistItem() { ItemId = channel, Type = BlacklistType.Channel }));
blacklist.AddRange(oldConfig.UserBlacklist.Select(user => new BlacklistItem() { ItemId = user, Type = BlacklistType.User }));
botConfig.Blacklist = blacklist;
//Eightball
botConfig.EightBallResponses = new HashSet<EightBallResponse>(oldConfig._8BallResponses.Select(response => new EightBallResponse() { Text = response }));
//customreactions
uow.CustomReactions.AddRange(oldConfig.CustomReactions.SelectMany(cr =>
{
return cr.Value.Select(res => new CustomReaction()
{
GuildId = null,
IsRegex = false,
OwnerOnly = false,
Response = res,
Trigger = cr.Key.ToLowerInvariant(),
});
}).ToArray());
try { File.Move(configPath, "./data/DELETE_ME_config.json"); } catch { }
}
}
}
}

View File

@ -1,91 +1,91 @@
using Discord.Commands;
using NadekoBot.Common.Attributes;
using NadekoBot.Modules.Administration.Services;
using NadekoBot.Extensions;
using System;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Linq;
//using Discord.Commands;
//using NadekoBot.Common.Attributes;
//using NadekoBot.Modules.Administration.Services;
//using NadekoBot.Extensions;
//using System;
//using System.IO;
//using System.Reflection;
//using System.Text.RegularExpressions;
//using System.Threading.Tasks;
//using System.Linq;
namespace NadekoBot.Modules.Administration
{
public partial class Administration
{
[Group]
public class PackagesCommands : NadekoSubmodule<PackagesService>
{
private readonly NadekoBot _bot;
//namespace NadekoBot.Modules.Administration
//{
// public partial class Administration
// {
// [Group]
// public class PackagesCommands : NadekoSubmodule<PackagesService>
// {
// private readonly NadekoBot _bot;
public PackagesCommands(NadekoBot bot)
{
_bot = bot;
}
// public PackagesCommands(NadekoBot bot)
// {
// _bot = bot;
// }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task PackageList()
{
_service.ReloadAvailablePackages();
await Context.Channel.SendConfirmAsync(
string.Join(
"\n",
_service.Packages
.Select(x => _bot.LoadedPackages.Contains(x)
? "✅ " + x
: x)));
}
// [NadekoCommand, Usage, Description, Aliases]
// [RequireContext(ContextType.Guild)]
// public async Task PackageList()
// {
// _service.ReloadAvailablePackages();
// await Context.Channel.SendConfirmAsync(
// string.Join(
// "\n",
// _service.Packages
// .Select(x => _bot.LoadedPackages.Contains(x)
// ? "【✘】" + x
// : "【 】" + x)));
// }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task PackageUnload(string name)
{
if (name.Contains(":") || name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
return;
name = name.ToTitleCase();
var package = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory,
"modules",
$"NadekoBot.Modules.{name}",
$"NadekoBot.Modules.{name}.dll"));
// [NadekoCommand, Usage, Description, Aliases]
// [RequireContext(ContextType.Guild)]
// [OwnerOnly]
// public async Task PackageUnload(string name)
// {
// if (name.Contains(":") || name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
// return;
// name = name.ToTitleCase();
// var package = Assembly.LoadFrom(Path.Combine(AppContext.BaseDirectory,
// "modules",
// $"NadekoBot.Modules.{name}",
// $"NadekoBot.Modules.{name}.dll"));
await _bot.UnloadPackage(name).ConfigureAwait(false);
await ReplyAsync(":ok:");
}
// await _bot.UnloadPackage(name).ConfigureAwait(false);
// await ReplyAsync(":ok:");
// }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task PackageLoad(string name)
{
if (name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
return;
name = name.ToTitleCase();
// [NadekoCommand, Usage, Description, Aliases]
// [RequireContext(ContextType.Guild)]
// [OwnerOnly]
// public async Task PackageLoad(string name)
// {
// if (name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
// return;
// name = name.ToTitleCase();
if (await _bot.LoadPackage(name))
await ReplyAsync(":ok:");
else
await ReplyAsync(":x:");
}
// if (await _bot.LoadPackage(name))
// await ReplyAsync(":ok:");
// else
// await ReplyAsync(":x:");
// }
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
[OwnerOnly]
public async Task PackageReload(string name)
{
if (name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
return;
name = name.ToTitleCase();
// [NadekoCommand, Usage, Description, Aliases]
// [RequireContext(ContextType.Guild)]
// [OwnerOnly]
// public async Task PackageReload(string name)
// {
// if (name.Contains(".") || name.Contains("\\") || name.Contains("/") || name.Contains("~"))
// return;
// name = name.ToTitleCase();
if (await _bot.UnloadPackage(name))
{
await _bot.LoadPackage(name);
await ReplyAsync(":ok:");
}
else
await ReplyAsync(":x:");
}
}
}
}
// if (await _bot.UnloadPackage(name))
// {
// await _bot.LoadPackage(name);
// await ReplyAsync(":ok:");
// }
// else
// await ReplyAsync(":x:");
// }
// }
// }
//}