using Newtonsoft.Json;
using RuriLib.Models;
using RuriLib.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Media;
namespace RuriLib
{
///
/// Static Class used to access serialization and deserialization of objects.
///
public static class IOManager
{
private static JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All };
///
/// Saves the RuriLib settings to a file.
///
/// The file you want to save to
/// The RuriLib settings object
public static void SaveSettings(string settingsFile, RLSettingsViewModel settings)
{
File.WriteAllText(settingsFile, JsonConvert.SerializeObject(settings, Formatting.Indented));
}
///
/// Loads the RuriLib settings from a file.
///
/// The file you want to load from
/// An instance of RLSettingsViewModel
public static RLSettingsViewModel LoadSettings(string settingsFile)
{
return JsonConvert.DeserializeObject(File.ReadAllText(settingsFile));
}
///
/// Serializes a block to a JSON string.
///
/// The block to serialize
/// The JSON-encoded BlockBase object with TypeNameHandling on
public static string SerializeBlock(BlockBase block)
{
return JsonConvert.SerializeObject(block, Formatting.None, settings);
}
///
/// Deserializes a Block from a JSON string.
///
/// The JSON-encoded string with TypeNameHandling on
/// An instance of BlockBase
public static BlockBase DeserializeBlock(string block)
{
return JsonConvert.DeserializeObject(block, settings);
}
///
/// Serializes a list of blocks to a JSON string.
///
/// The list of blocks to serialize
/// The JSON-encoded List of BlockBase objects with TypeNameHandling on
public static string SerializeBlocks(List blocks)
{
return JsonConvert.SerializeObject(blocks, Formatting.None, settings);
}
///
/// Deserializes a list of blocks from a JSON string.
///
/// The JSON-encoded string with TypeNameHandling on
/// A list of instances of BlockBase
public static List DeserializeBlocks(string blocks)
{
return JsonConvert.DeserializeObject>(blocks, settings);
}
///
/// Serializes a Config object to the loli-formatted string.
///
/// The Config to serialize
/// The loli-formatted string
public static string SerializeConfig(Config config)
{
StringWriter writer = new StringWriter();
writer.WriteLine("[SETTINGS]");
writer.WriteLine(JsonConvert.SerializeObject(config.Settings, Formatting.Indented));
writer.WriteLine("");
writer.WriteLine("[SCRIPT]");
writer.Write(config.Script);
return writer.ToString();
}
///
/// Deserializes a Config object from a loli-formatted string.
///
/// The loli-formatted string
/// An instance of the Config object
public static Config DeserializeConfig(string config)
{
var split = config.Split(new string[] { "[SETTINGS]", "[SCRIPT]" }, StringSplitOptions.RemoveEmptyEntries);
return new Config(JsonConvert.DeserializeObject(split[0]), split[1].TrimStart('\r', '\n'));
}
///
/// Serializes a list of proxies to a JSON string.
///
/// The list of proxies to serialize
/// The JSON-encoded list of CProxy objects with TypeNameHandling on
public static string SerializeProxies(List proxies)
{
return JsonConvert.SerializeObject(proxies, Formatting.None);
}
///
/// Deserializes a list of proxies from a JSON string.
///
/// The JSON-encoded list of proxies with TypeNameHandling on
/// A list of CProxy objects
public static List DeserializeProxies(string proxies)
{
return JsonConvert.DeserializeObject>(proxies);
}
///
/// Loads a Config object from a .loli file.
///
/// The config file
/// A Config object
public static Config LoadConfig(string fileName)
{
return DeserializeConfig(File.ReadAllText(fileName));
}
///
/// Saves a Config object to a .loli file.
///
/// The viewmodel of the config to save
/// The path of the file where the Config will be saved
/// Whether the file has been saved successfully
public static bool SaveConfig(Config config, string fileName)
{
try
{
File.WriteAllText(fileName, SerializeConfig(config));
return true;
}
catch { return false; }
}
///
/// Clones a Config object by serializing and deserializing it.
///
/// The object to clone
/// The cloned Config object
public static Config CloneConfig(Config config)
{
return DeserializeConfig(SerializeConfig(config));
}
///
/// Clones a BlockBase object by serializing and deserializing it.
///
/// The object to clone
/// The cloned BlockBase object
public static BlockBase CloneBlock(BlockBase block)
{
return DeserializeBlock(SerializeBlock(block));
}
///
/// Clones a list of proxies by serializing and deserializing it.
///
/// The list of proxies to clone
/// The cloned list of proxies
public static List CloneProxies(List proxies)
{
return DeserializeProxies(SerializeProxies(proxies));
}
///
/// Parses the EnvironmentSettings from a file.
///
/// The .ini file of the settings
/// The loaded EnvironmentSettings object
public static EnvironmentSettings ParseEnvironmentSettings(string envFile)
{
var env = new EnvironmentSettings();
var lines = File.ReadAllLines(envFile).Where(l => !string.IsNullOrEmpty(l)).ToArray();
for (int i = 0; i < lines.Count(); i++)
{
var line = lines[i];
if (line.StartsWith("#")) continue;
else if (line.StartsWith("["))
{
Type type;
var header = line;
switch (line.Trim())
{
case "[WLTYPE]": type = typeof(WordlistType); break;
case "[CUSTOMKC]": type = typeof(CustomKeychain); break;
case "[EXPFORMAT]": type = typeof(ExportFormat); break;
default: throw new Exception("Unrecognized ini header");
}
var parameters = new List();
int j = i + 1;
for (; j < lines.Count(); j++)
{
line = lines[j];
if (line.StartsWith("[")) break;
else if (line.Trim() == "" || line.StartsWith("#")) continue;
else parameters.Add(line);
}
switch (header)
{
case "[WLTYPE]": env.WordlistTypes.Add((WordlistType)ParseObjectFromIni(type, parameters)); break;
case "[CUSTOMKC]": env.CustomKeychains.Add((CustomKeychain)ParseObjectFromIni(type, parameters)); break;
case "[EXPFORMAT]": env.ExportFormats.Add((ExportFormat)ParseObjectFromIni(type, parameters)); break;
default: break;
}
i = j - 1;
}
}
return env;
}
private static object ParseObjectFromIni(Type type, List parameters)
{
object obj = Activator.CreateInstance(type);
foreach (var pair in parameters
.Where(p => !string.IsNullOrEmpty(p))
.Select(p => p.Split(new char[] { '=' }, 2)))
{
var prop = type.GetProperty(pair[0]);
var propObj = prop.GetValue(obj);
dynamic value = null;
var ts = new TypeSwitch()
.Case((String x) => value = pair[1])
.Case((Int32 x) => value = Int32.Parse(pair[1]))
.Case((Boolean x) => value = Boolean.Parse(pair[1]))
.Case((List x) => value = pair[1].Split(',').ToList())
.Case((Color x) => value = Color.FromRgb(
System.Drawing.Color.FromName(pair[1]).R,
System.Drawing.Color.FromName(pair[1]).G,
System.Drawing.Color.FromName(pair[1]).B
))
;
ts.Switch(propObj);
prop.SetValue(obj, value);
}
return obj;
}
}
}