Initial check-in

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti
2012-07-12 02:55:27 -04:00
commit b50f78e5da
93 changed files with 5325 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
using System;
namespace MediaBrowser.Common.Events
{
public class GenericItemEventArgs<TItemType> : EventArgs
{
public TItemType Item { get; set; }
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MediaBrowser.Common.Json
{
public class JsonSerializer
{
public static void Serialize<T>(T o, Stream stream)
{
using (StreamWriter streamWriter = new StreamWriter(stream))
{
using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
var settings = new Newtonsoft.Json.JsonSerializerSettings()
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
};
Newtonsoft.Json.JsonSerializer.Create(settings).Serialize(writer, o);
}
}
}
public static void Serialize<T>(T o, string file)
{
using (StreamWriter streamWriter = new StreamWriter(file))
{
using (Newtonsoft.Json.JsonTextWriter writer = new Newtonsoft.Json.JsonTextWriter(streamWriter))
{
var settings = new Newtonsoft.Json.JsonSerializerSettings()
{
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore
};
Newtonsoft.Json.JsonSerializer.Create(settings).Serialize(writer, o);
}
}
}
public static T Deserialize<T>(string file)
{
using (StreamReader streamReader = new StreamReader(file))
{
using (Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(streamReader))
{
return Newtonsoft.Json.JsonSerializer.Create(new Newtonsoft.Json.JsonSerializerSettings() { }).Deserialize<T>(reader);
}
}
}
}
}

View File

@@ -0,0 +1,80 @@
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace MediaBrowser.Common.Logging
{
public abstract class BaseLogger
{
public LogSeverity LogSeverity { get; set; }
public void LogInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Info, paramList);
}
public void LogDebugInfo(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Debug, paramList);
}
public void LogError(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Error, paramList);
}
public void LogException(string message, Exception exception, params object[] paramList)
{
StringBuilder builder = new StringBuilder();
if (exception != null)
{
var trace = new StackTrace(exception, true);
builder.AppendFormat("Exception. Type={0} Msg={1} Src={2} Method={5} Line={6} Col={7}{4}StackTrace={4}{3}",
exception.GetType().FullName,
exception.Message,
exception.Source,
exception.StackTrace,
Environment.NewLine,
trace.GetFrame(0).GetMethod().Name,
trace.GetFrame(0).GetFileLineNumber(),
trace.GetFrame(0).GetFileColumnNumber());
}
StackFrame frame = new StackFrame(1);
message = string.Format(message, paramList);
LogError(string.Format("{0} ( {1} )", message, builder));
}
public void LogWarning(string message, params object[] paramList)
{
LogEntry(message, LogSeverity.Warning, paramList);
}
private void LogEntry(string message, LogSeverity severity, params object[] paramList)
{
if (severity < LogSeverity) return;
message = string.Format(message, paramList);
Thread currentThread = Thread.CurrentThread;
LogRow row = new LogRow()
{
Severity = severity,
Message = message,
Category = string.Empty,
ThreadId = currentThread.ManagedThreadId,
ThreadName = currentThread.Name,
Time = DateTime.Now
};
LogEntry(row);
}
protected abstract void LogEntry(LogRow row);
}
}

View File

@@ -0,0 +1,55 @@
using System;
using System.IO;
using System.Text;
namespace MediaBrowser.Common.Logging
{
public class FileLogger : BaseLogger, IDisposable
{
private string LogDirectory { get; set; }
private string CurrentLogFile { get; set; }
private FileStream FileStream { get; set; }
public FileLogger(string logDirectory)
{
LogDirectory = logDirectory;
}
private void EnsureStream()
{
if (FileStream == null)
{
if (!Directory.Exists(LogDirectory))
{
Directory.CreateDirectory(LogDirectory);
}
DateTime now = DateTime.Now;
CurrentLogFile = Path.Combine(LogDirectory, now.ToString("dMyyyy") + "-" + now.Ticks + ".log");
FileStream = new FileStream(CurrentLogFile, FileMode.Append, FileAccess.Write, FileShare.Read);
}
}
protected override void LogEntry(LogRow row)
{
EnsureStream();
byte[] bytes = new UTF8Encoding().GetBytes(row.ToString() + Environment.NewLine);
FileStream.Write(bytes, 0, bytes.Length);
FileStream.Flush();
}
public void Dispose()
{
if (FileStream != null)
{
FileStream.Dispose();
}
}
}
}

View File

@@ -0,0 +1,118 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MediaBrowser.Common.Logging
{
public struct LogRow
{
const string TimePattern = "h:mm:ss.fff tt d/M/yyyy";
public LogSeverity Severity { get; set; }
public string Message { get; set; }
public string Category { get; set; }
public int ThreadId { get; set; }
public string ThreadName { get; set; }
public DateTime Time { get; set; }
public string ShortMessage
{
get
{
var message = Message;
if (message.Length > 120)
{
message = Message.Substring(0, 120).Replace(Environment.NewLine, " ") + " ... ";
}
return message;
}
}
public string FullDescription
{
get
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Time: {0}", Time);
sb.AppendLine();
sb.AppendFormat("Thread Id: {0} {1}", ThreadId, ThreadName);
sb.AppendLine();
sb.AppendLine(Message);
return sb.ToString();
}
}
public override string ToString()
{
StringBuilder builder = new StringBuilder();
builder.Append(Time.ToString(TimePattern))
.Append(" , ")
.Append(Enum.GetName(typeof(LogSeverity), Severity))
.Append(" , ")
.Append(Encode(Message))
.Append(" , ")
.Append(Encode(Category))
.Append(" , ")
.Append(ThreadId)
.Append(" , ")
.Append(Encode(ThreadName));
return builder.ToString();
}
private string Encode(string str)
{
return (str ?? "").Replace(",", ",,").Replace(Environment.NewLine, " [n] ");
}
public static LogRow FromString(string message)
{
var split = splitString(message);
return new LogRow()
{
Time = DateTime.ParseExact(split[0], TimePattern, null),
Severity = (LogSeverity)Enum.Parse(typeof(LogSeverity), split[1]),
Message = split[2],
Category = split[3],
ThreadId = int.Parse(split[4]),
ThreadName = split[5]
};
}
static string[] splitString(string message)
{
List<string> items = new List<string>();
bool gotComma = false;
StringBuilder currentItem = new StringBuilder();
foreach (var chr in message)
{
if (chr == ',' && gotComma)
{
gotComma = false;
currentItem.Append(',');
}
else if (chr == ',')
{
gotComma = true;
}
else if (gotComma)
{
items.Add(currentItem.ToString().Replace(" [n] ", Environment.NewLine).Trim());
currentItem = new StringBuilder();
gotComma = false;
}
else
{
currentItem.Append(chr);
}
}
items.Add(currentItem.ToString().Replace("[n]", Environment.NewLine).Trim());
return items.ToArray();
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Logging
{
[Flags]
public enum LogSeverity
{
None = 0,
Debug = 1,
Info = 2,
Warning = 4,
Error = 8
}
}

View File

@@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Logging
{
public static class Logger
{
public static BaseLogger LoggerInstance { get; set; }
public static void LogInfo(string message, params object[] paramList)
{
LoggerInstance.LogInfo(message, paramList);
}
public static void LogDebugInfo(string message, params object[] paramList)
{
LoggerInstance.LogDebugInfo(message, paramList);
}
public static void LogError(string message, params object[] paramList)
{
LoggerInstance.LogError(message, paramList);
}
public static void LogException(string message, Exception ex, params object[] paramList)
{
LoggerInstance.LogException(message, ex, paramList);
}
public static void LogWarning(string message, params object[] paramList)
{
LoggerInstance.LogWarning(message, paramList);
}
}
}

View File

@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{9142EEFA-7570-41E1-BFCC-468BB571AF2F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MediaBrowser.Common</RootNamespace>
<AssemblyName>MediaBrowser.Common</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json">
<HintPath>..\packages\Newtonsoft.Json.4.5.7\lib\net40\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Events\GenericItemEventArgs.cs" />
<Compile Include="Json\JsonSerializer.cs" />
<Compile Include="Plugins\BasePluginConfiguration.cs" />
<Compile Include="Logging\BaseLogger.cs" />
<Compile Include="Logging\FileLogger.cs" />
<Compile Include="Logging\Logger.cs" />
<Compile Include="Logging\LogRow.cs" />
<Compile Include="Logging\LogSeverity.cs" />
<Compile Include="Plugins\BasePlugin.cs" />
<Compile Include="Plugins\PluginController.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using MediaBrowser.Common.Json;
namespace MediaBrowser.Common.Plugins
{
public abstract class BasePlugin<TConfigurationType> : IDisposable, IPlugin
where TConfigurationType : BasePluginConfiguration, new()
{
public string Path { get; set; }
public TConfigurationType Configuration { get; private set; }
private string ConfigurationPath
{
get
{
return System.IO.Path.Combine(Path, "config.js");
}
}
public void Init()
{
Configuration = GetConfiguration();
if (Configuration.Enabled)
{
InitInternal();
}
}
protected abstract void InitInternal();
public virtual void Dispose()
{
}
private TConfigurationType GetConfiguration()
{
if (!File.Exists(ConfigurationPath))
{
return new TConfigurationType();
}
return JsonSerializer.Deserialize<TConfigurationType>(ConfigurationPath);
}
}
public interface IPlugin
{
string Path { get; set; }
void Init();
void Dispose();
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MediaBrowser.Common.Plugins
{
public class BasePluginConfiguration
{
public bool Enabled { get; set; }
public BasePluginConfiguration()
{
Enabled = true;
}
}
}

View File

@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace MediaBrowser.Common.Plugins
{
public class PluginController
{
public string PluginsPath { get; set; }
public PluginController(string pluginFolderPath)
{
PluginsPath = pluginFolderPath;
}
public IEnumerable<IPlugin> GetAllPlugins()
{
AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(CurrentDomain_AssemblyResolve);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
if (!Directory.Exists(PluginsPath))
{
Directory.CreateDirectory(PluginsPath);
}
List<IPlugin> plugins = new List<IPlugin>();
foreach (string folder in Directory.GetDirectories(PluginsPath, "*", SearchOption.TopDirectoryOnly))
{
IPlugin plugin = GetPluginFromDirectory(folder);
plugin.Path = folder;
if (plugin != null)
{
plugins.Add(plugin);
}
}
return plugins;
}
private IPlugin GetPluginFromDirectory(string path)
{
string dll = Directory.GetFiles(path, "*.dll", SearchOption.TopDirectoryOnly).FirstOrDefault();
if (!string.IsNullOrEmpty(dll))
{
return GetPluginFromDll(dll);
}
return null;
}
private IPlugin GetPluginFromDll(string path)
{
return FindPlugin(Assembly.Load(File.ReadAllBytes(path)));
}
private IPlugin FindPlugin(Assembly assembly)
{
var plugin = assembly.GetTypes().Where(type => typeof(IPlugin).IsAssignableFrom(type)).FirstOrDefault();
if (plugin != null)
{
return plugin.GetConstructor(Type.EmptyTypes).Invoke(null) as IPlugin;
}
return null;
}
Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
AssemblyName assemblyName = new AssemblyName(args.Name);
IEnumerable<string> dllPaths = Directory.GetFiles(PluginsPath, "*.dll", SearchOption.AllDirectories);
string dll = dllPaths.FirstOrDefault(f => Path.GetFileNameWithoutExtension(f) == assemblyName.Name);
if (!string.IsNullOrEmpty(dll))
{
return Assembly.Load(File.ReadAllBytes(dll));
}
return null;
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MediaBrowser.Common")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MediaBrowser.Common")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cdec1bb7-6ffd-409f-b41f-0524a73df9be")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Newtonsoft.Json" version="4.5.7" targetFramework="net45" />
</packages>