More code cleanups

This commit is contained in:
LukePulverenti Luke Pulverenti luke pulverenti 2012-09-11 15:37:14 -04:00
parent 670a53258e
commit f1e668bad8
58 changed files with 296 additions and 298 deletions

View File

@ -76,9 +76,9 @@ namespace MediaBrowser.Api
bool includeChildren = true, bool includeChildren = true,
bool includePeople = true) bool includePeople = true)
{ {
DtoBaseItem dto = new DtoBaseItem(); var dto = new DtoBaseItem();
List<Task> tasks = new List<Task>(); var tasks = new List<Task>();
tasks.Add(AttachStudios(dto, item)); tasks.Add(AttachStudios(dto, item));
@ -134,7 +134,7 @@ namespace MediaBrowser.Api
dto.OfficialRating = item.OfficialRating; dto.OfficialRating = item.OfficialRating;
dto.Overview = item.Overview; dto.Overview = item.Overview;
// If there are no backdrops, indicate what parent has them in case the UI wants to allow inheritance // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
if (dto.BackdropCount == 0) if (dto.BackdropCount == 0)
{ {
int backdropCount; int backdropCount;
@ -149,7 +149,7 @@ namespace MediaBrowser.Api
dto.ParentIndexNumber = item.ParentIndexNumber; dto.ParentIndexNumber = item.ParentIndexNumber;
// If there is no logo, indicate what parent has one in case the UI wants to allow inheritance // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
if (!dto.HasLogo) if (!dto.HasLogo)
{ {
dto.ParentLogoItemId = GetParentLogoItemId(item); dto.ParentLogoItemId = GetParentLogoItemId(item);
@ -174,7 +174,7 @@ namespace MediaBrowser.Api
dto.UserData = GetDtoUserItemData(item.GetUserData(user, false)); dto.UserData = GetDtoUserItemData(item.GetUserData(user, false));
Folder folder = item as Folder; var folder = item as Folder;
if (folder != null) if (folder != null)
{ {
@ -185,7 +185,7 @@ namespace MediaBrowser.Api
} }
// Add AudioInfo // Add AudioInfo
Audio audio = item as Audio; var audio = item as Audio;
if (audio != null) if (audio != null)
{ {
@ -200,7 +200,7 @@ namespace MediaBrowser.Api
} }
// Add VideoInfo // Add VideoInfo
Video video = item as Video; var video = item as Video;
if (video != null) if (video != null)
{ {
@ -225,11 +225,11 @@ namespace MediaBrowser.Api
} }
// Add SeriesInfo // Add SeriesInfo
Series series = item as Series; var series = item as Series;
if (series != null) if (series != null)
{ {
DayOfWeek[] airDays = series.AirDays == null ? new DayOfWeek[] { } : series.AirDays.ToArray(); ; DayOfWeek[] airDays = series.AirDays == null ? new DayOfWeek[] { } : series.AirDays.ToArray();
dto.SeriesInfo = new SeriesInfo dto.SeriesInfo = new SeriesInfo
{ {
@ -240,7 +240,7 @@ namespace MediaBrowser.Api
} }
// Add MovieInfo // Add MovieInfo
Movie movie = item as Movie; var movie = item as Movie;
if (movie != null) if (movie != null)
{ {
@ -268,7 +268,7 @@ namespace MediaBrowser.Api
for (int i = 0; i < entities.Length; i++) for (int i = 0; i < entities.Length; i++)
{ {
Studio entity = entities[i]; Studio entity = entities[i];
BaseItemStudio baseItemStudio = new BaseItemStudio(); var baseItemStudio = new BaseItemStudio{};
baseItemStudio.Name = entity.Name; baseItemStudio.Name = entity.Name;
@ -317,7 +317,7 @@ namespace MediaBrowser.Api
dto.People = item.People.Select(p => dto.People = item.People.Select(p =>
{ {
BaseItemPerson baseItemPerson = new BaseItemPerson(); var baseItemPerson = new BaseItemPerson{};
baseItemPerson.Name = p.Key; baseItemPerson.Name = p.Key;
baseItemPerson.Overview = p.Value.Overview; baseItemPerson.Overview = p.Value.Overview;
@ -381,9 +381,9 @@ namespace MediaBrowser.Api
/// <summary> /// <summary>
/// Gets an ImagesByName entity along with the number of items containing it /// Gets an ImagesByName entity along with the number of items containing it
/// </summary> /// </summary>
public static IBNItem GetIBNItem(BaseEntity entity, int itemCount) public static IbnItem GetIbnItem(BaseEntity entity, int itemCount)
{ {
return new IBNItem return new IbnItem
{ {
Id = entity.Id, Id = entity.Id,
BaseItemCount = itemCount, BaseItemCount = itemCount,

View File

@ -147,7 +147,7 @@ namespace MediaBrowser.Api.HttpHandlers
protected async override Task WriteResponseToOutputStream(Stream stream) protected async override Task WriteResponseToOutputStream(Stream stream)
{ {
ProcessStartInfo startInfo = new ProcessStartInfo(); var startInfo = new ProcessStartInfo{};
startInfo.CreateNoWindow = true; startInfo.CreateNoWindow = true;
@ -163,7 +163,7 @@ namespace MediaBrowser.Api.HttpHandlers
Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments); Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
Process process = new Process(); var process = new Process{};
process.StartInfo = startInfo; process.StartInfo = startInfo;
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
@ -208,7 +208,7 @@ namespace MediaBrowser.Api.HttpHandlers
LogFileStream.Dispose(); LogFileStream.Dispose();
} }
Process process = sender as Process; var process = sender as Process;
Logger.LogInfo("FFMpeg exited with code " + process.ExitCode); Logger.LogInfo("FFMpeg exited with code " + process.ExitCode);

View File

@ -15,17 +15,17 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets a single genre /// Gets a single genre
/// </summary> /// </summary>
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class GenreHandler : BaseSerializationHandler<IBNItem> public class GenreHandler : BaseSerializationHandler<IbnItem>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("genre", request); return ApiService.IsApiUrlMatch("genre", request);
} }
protected override Task<IBNItem> GetObjectToSerialize() protected override Task<IbnItem> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); var user = ApiService.GetUserById(QueryString["userid"], true);
string name = QueryString["name"]; string name = QueryString["name"];
@ -35,7 +35,7 @@ namespace MediaBrowser.Api.HttpHandlers
/// <summary> /// <summary>
/// Gets a Genre /// Gets a Genre
/// </summary> /// </summary>
private async Task<IBNItem> GetGenre(Folder parent, User user, string name) private async Task<IbnItem> GetGenre(Folder parent, User user, string name)
{ {
int count = 0; int count = 0;
@ -51,7 +51,7 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the original entity so that we can also supply the PrimaryImagePath // Get the original entity so that we can also supply the PrimaryImagePath
return ApiService.GetIBNItem(await Kernel.Instance.ItemController.GetGenre(name).ConfigureAwait(false), count); return ApiService.GetIbnItem(await Kernel.Instance.ItemController.GetGenre(name).ConfigureAwait(false), count);
} }
} }
} }

View File

@ -11,16 +11,16 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.HttpHandlers namespace MediaBrowser.Api.HttpHandlers
{ {
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class GenresHandler : BaseSerializationHandler<IBNItem[]> public class GenresHandler : BaseSerializationHandler<IbnItem[]>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("genres", request); return ApiService.IsApiUrlMatch("genres", request);
} }
protected override Task<IBNItem[]> GetObjectToSerialize() protected override Task<IbnItem[]> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); User user = ApiService.GetUserById(QueryString["userid"], true);
return GetAllGenres(parent, user); return GetAllGenres(parent, user);
@ -30,9 +30,9 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets all genres from all recursive children of a folder /// Gets all genres from all recursive children of a folder
/// The CategoryInfo class is used to keep track of the number of times each genres appears /// The CategoryInfo class is used to keep track of the number of times each genres appears
/// </summary> /// </summary>
private async Task<IBNItem[]> GetAllGenres(Folder parent, User user) private async Task<IbnItem[]> GetAllGenres(Folder parent, User user)
{ {
Dictionary<string, int> data = new Dictionary<string, int>(); var data = new Dictionary<string, int>();
// Get all the allowed recursive children // Get all the allowed recursive children
IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user); IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user);
@ -60,16 +60,16 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the Genre objects // Get the Genre objects
Genre[] entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetGenre(key); })).ConfigureAwait(false); Genre[] entities = await Task.WhenAll(data.Keys.Select(key => Kernel.Instance.ItemController.GetGenre(key))).ConfigureAwait(false);
// Convert to an array of IBNItem // Convert to an array of IBNItem
IBNItem[] items = new IBNItem[entities.Length]; var items = new IbnItem[entities.Length];
for (int i = 0; i < entities.Length; i++) for (int i = 0; i < entities.Length; i++)
{ {
Genre e = entities[i]; Genre e = entities[i];
items[i] = ApiService.GetIBNItem(e, data[e.Name]); items[i] = ApiService.GetIbnItem(e, data[e.Name]);
} }
return items; return items;

View File

@ -24,10 +24,7 @@ namespace MediaBrowser.Api.HttpHandlers
private string _imagePath; private string _imagePath;
private async Task<string> GetImagePath() private async Task<string> GetImagePath()
{ {
if (_imagePath == null) _imagePath = _imagePath ?? await DiscoverImagePath();
{
_imagePath = await DiscoverImagePath();
}
return _imagePath; return _imagePath;
} }

View File

@ -22,15 +22,12 @@ namespace MediaBrowser.Api.HttpHandlers
{ {
User user = ApiService.GetUserById(QueryString["userid"], true); User user = ApiService.GetUserById(QueryString["userid"], true);
return Task.WhenAll(GetItemsToSerialize(user).Select(i => return Task.WhenAll(GetItemsToSerialize(user).Select(i => ApiService.GetDtoBaseItem(i, user, includeChildren: false, includePeople: false)));
{
return ApiService.GetDtoBaseItem(i, user, includeChildren: false, includePeople: false);
}));
} }
private IEnumerable<BaseItem> GetItemsToSerialize(User user) private IEnumerable<BaseItem> GetItemsToSerialize(User user)
{ {
Folder parent = ApiService.GetItemById(ItemId) as Folder; var parent = ApiService.GetItemById(ItemId) as Folder;
if (ListType.Equals("inprogressitems", StringComparison.OrdinalIgnoreCase)) if (ListType.Equals("inprogressitems", StringComparison.OrdinalIgnoreCase))
{ {

View File

@ -24,7 +24,7 @@ namespace MediaBrowser.Api.HttpHandlers
{ {
User user = ApiService.GetUserById(QueryString["userid"], true); User user = ApiService.GetUserById(QueryString["userid"], true);
Movie movie = ApiService.GetItemById(ItemId) as Movie; var movie = ApiService.GetItemById(ItemId) as Movie;
// If none // If none
if (movie.SpecialFeatures == null) if (movie.SpecialFeatures == null)
@ -32,10 +32,7 @@ namespace MediaBrowser.Api.HttpHandlers
return Task.FromResult(new DtoBaseItem[] { }); return Task.FromResult(new DtoBaseItem[] { });
} }
return Task.WhenAll(movie.SpecialFeatures.Select(i => return Task.WhenAll(movie.SpecialFeatures.Select(i => ApiService.GetDtoBaseItem(i, user, includeChildren: false)));
{
return ApiService.GetDtoBaseItem(i, user, includeChildren: false);
}));
} }
protected string ItemId protected string ItemId

View File

@ -13,17 +13,17 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets a single Person /// Gets a single Person
/// </summary> /// </summary>
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class PersonHandler : BaseSerializationHandler<IBNItem> public class PersonHandler : BaseSerializationHandler<IbnItem>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("person", request); return ApiService.IsApiUrlMatch("person", request);
} }
protected override Task<IBNItem> GetObjectToSerialize() protected override Task<IbnItem> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); var user = ApiService.GetUserById(QueryString["userid"], true);
string name = QueryString["name"]; string name = QueryString["name"];
@ -33,7 +33,7 @@ namespace MediaBrowser.Api.HttpHandlers
/// <summary> /// <summary>
/// Gets a Person /// Gets a Person
/// </summary> /// </summary>
private async Task<IBNItem> GetPerson(Folder parent, User user, string name) private async Task<IbnItem> GetPerson(Folder parent, User user, string name)
{ {
int count = 0; int count = 0;
@ -49,7 +49,7 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the original entity so that we can also supply the PrimaryImagePath // Get the original entity so that we can also supply the PrimaryImagePath
return ApiService.GetIBNItem(await Kernel.Instance.ItemController.GetPerson(name).ConfigureAwait(false), count); return ApiService.GetIbnItem(await Kernel.Instance.ItemController.GetPerson(name).ConfigureAwait(false), count);
} }
} }
} }

View File

@ -19,20 +19,17 @@ namespace MediaBrowser.Api.HttpHandlers
{ {
return ApiService.IsApiUrlMatch("plugins", request); return ApiService.IsApiUrlMatch("plugins", request);
} }
protected override Task<IEnumerable<PluginInfo>> GetObjectToSerialize() protected override Task<IEnumerable<PluginInfo>> GetObjectToSerialize()
{ {
var plugins = Kernel.Instance.Plugins.Select(p => var plugins = Kernel.Instance.Plugins.Select(p => new PluginInfo
{ {
return new PluginInfo Name = p.Name,
{ Enabled = p.Enabled,
Name = p.Name, DownloadToUI = p.DownloadToUi,
Enabled = p.Enabled, Version = p.Version.ToString(),
DownloadToUI = p.DownloadToUI, AssemblyFileName = p.AssemblyFileName,
Version = p.Version.ToString(), ConfigurationDateLastModified = p.ConfigurationDateLastModified
AssemblyFileName = p.AssemblyFileName,
ConfigurationDateLastModified = p.ConfigurationDateLastModified
};
}); });
return Task.FromResult(plugins); return Task.FromResult(plugins);

View File

@ -15,17 +15,17 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets a single studio /// Gets a single studio
/// </summary> /// </summary>
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class StudioHandler : BaseSerializationHandler<IBNItem> public class StudioHandler : BaseSerializationHandler<IbnItem>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("studio", request); return ApiService.IsApiUrlMatch("studio", request);
} }
protected override Task<IBNItem> GetObjectToSerialize() protected override Task<IbnItem> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); var user = ApiService.GetUserById(QueryString["userid"], true);
string name = QueryString["name"]; string name = QueryString["name"];
@ -35,7 +35,7 @@ namespace MediaBrowser.Api.HttpHandlers
/// <summary> /// <summary>
/// Gets a Studio /// Gets a Studio
/// </summary> /// </summary>
private async Task<IBNItem> GetStudio(Folder parent, User user, string name) private async Task<IbnItem> GetStudio(Folder parent, User user, string name)
{ {
int count = 0; int count = 0;
@ -51,7 +51,7 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the original entity so that we can also supply the PrimaryImagePath // Get the original entity so that we can also supply the PrimaryImagePath
return ApiService.GetIBNItem(await Kernel.Instance.ItemController.GetStudio(name).ConfigureAwait(false), count); return ApiService.GetIbnItem(await Kernel.Instance.ItemController.GetStudio(name).ConfigureAwait(false), count);
} }
} }
} }

View File

@ -11,17 +11,17 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.HttpHandlers namespace MediaBrowser.Api.HttpHandlers
{ {
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class StudiosHandler : BaseSerializationHandler<IBNItem[]> public class StudiosHandler : BaseSerializationHandler<IbnItem[]>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("studios", request); return ApiService.IsApiUrlMatch("studios", request);
} }
protected override Task<IBNItem[]> GetObjectToSerialize() protected override Task<IbnItem[]> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); var user = ApiService.GetUserById(QueryString["userid"], true);
return GetAllStudios(parent, user); return GetAllStudios(parent, user);
} }
@ -30,9 +30,9 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets all studios from all recursive children of a folder /// Gets all studios from all recursive children of a folder
/// The CategoryInfo class is used to keep track of the number of times each studio appears /// The CategoryInfo class is used to keep track of the number of times each studio appears
/// </summary> /// </summary>
private async Task<IBNItem[]> GetAllStudios(Folder parent, User user) private async Task<IbnItem[]> GetAllStudios(Folder parent, User user)
{ {
Dictionary<string, int> data = new Dictionary<string, int>(); var data = new Dictionary<string, int>();
// Get all the allowed recursive children // Get all the allowed recursive children
IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user); IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user);
@ -60,16 +60,16 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the Studio objects // Get the Studio objects
Studio[] entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetStudio(key); })).ConfigureAwait(false); Studio[] entities = await Task.WhenAll(data.Keys.Select(key => Kernel.Instance.ItemController.GetStudio(key))).ConfigureAwait(false);
// Convert to an array of IBNItem // Convert to an array of IBNItem
IBNItem[] items = new IBNItem[entities.Length]; var items = new IbnItem[entities.Length];
for (int i = 0; i < entities.Length; i++) for (int i = 0; i < entities.Length; i++)
{ {
Studio e = entities[i]; Studio e = entities[i];
items[i] = ApiService.GetIBNItem(e, data[e.Name]); items[i] = ApiService.GetIbnItem(e, data[e.Name]);
} }
return items; return items;

View File

@ -19,7 +19,7 @@ namespace MediaBrowser.Api.HttpHandlers
{ {
string id = QueryString["id"]; string id = QueryString["id"];
User user = string.IsNullOrEmpty(id) ? ApiService.GetDefaultUser(false) : ApiService.GetUserById(id, false); ; User user = string.IsNullOrEmpty(id) ? ApiService.GetDefaultUser(false) : ApiService.GetUserById(id, false);
DtoUser dto = ApiService.GetDtoUser(user); DtoUser dto = ApiService.GetDtoUser(user);

View File

@ -81,7 +81,7 @@ namespace MediaBrowser.Api.HttpHandlers
/// <summary> /// <summary>
/// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line /// Translates the output file extension to the format param that follows "-f" on the ffmpeg command line
/// </summary> /// </summary>
private string GetFFMpegOutputFormat(VideoOutputFormats outputFormat) private string GetFfMpegOutputFormat(VideoOutputFormats outputFormat)
{ {
if (outputFormat == VideoOutputFormats.Mkv) if (outputFormat == VideoOutputFormats.Mkv)
{ {
@ -110,7 +110,7 @@ namespace MediaBrowser.Api.HttpHandlers
LibraryItem.Path, LibraryItem.Path,
GetVideoArguments(outputFormat), GetVideoArguments(outputFormat),
GetAudioArguments(outputFormat), GetAudioArguments(outputFormat),
GetFFMpegOutputFormat(outputFormat) GetFfMpegOutputFormat(outputFormat)
); );
} }

View File

@ -13,17 +13,17 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets a single year /// Gets a single year
/// </summary> /// </summary>
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class YearHandler : BaseSerializationHandler<IBNItem> public class YearHandler : BaseSerializationHandler<IbnItem>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("year", request); return ApiService.IsApiUrlMatch("year", request);
} }
protected override Task<IBNItem> GetObjectToSerialize() protected override Task<IbnItem> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); var user = ApiService.GetUserById(QueryString["userid"], true);
string year = QueryString["year"]; string year = QueryString["year"];
@ -33,7 +33,7 @@ namespace MediaBrowser.Api.HttpHandlers
/// <summary> /// <summary>
/// Gets a Year /// Gets a Year
/// </summary> /// </summary>
private async Task<IBNItem> GetYear(Folder parent, User user, int year) private async Task<IbnItem> GetYear(Folder parent, User user, int year)
{ {
int count = 0; int count = 0;
@ -49,7 +49,7 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the original entity so that we can also supply the PrimaryImagePath // Get the original entity so that we can also supply the PrimaryImagePath
return ApiService.GetIBNItem(await Kernel.Instance.ItemController.GetYear(year).ConfigureAwait(false), count); return ApiService.GetIbnItem(await Kernel.Instance.ItemController.GetYear(year).ConfigureAwait(false), count);
} }
} }
} }

View File

@ -11,16 +11,16 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.HttpHandlers namespace MediaBrowser.Api.HttpHandlers
{ {
[Export(typeof(BaseHandler))] [Export(typeof(BaseHandler))]
public class YearsHandler : BaseSerializationHandler<IBNItem[]> public class YearsHandler : BaseSerializationHandler<IbnItem[]>
{ {
public override bool HandlesRequest(HttpListenerRequest request) public override bool HandlesRequest(HttpListenerRequest request)
{ {
return ApiService.IsApiUrlMatch("years", request); return ApiService.IsApiUrlMatch("years", request);
} }
protected override Task<IBNItem[]> GetObjectToSerialize() protected override Task<IbnItem[]> GetObjectToSerialize()
{ {
Folder parent = ApiService.GetItemById(QueryString["id"]) as Folder; var parent = ApiService.GetItemById(QueryString["id"]) as Folder;
User user = ApiService.GetUserById(QueryString["userid"], true); User user = ApiService.GetUserById(QueryString["userid"], true);
return GetAllYears(parent, user); return GetAllYears(parent, user);
@ -30,9 +30,9 @@ namespace MediaBrowser.Api.HttpHandlers
/// Gets all years from all recursive children of a folder /// Gets all years from all recursive children of a folder
/// The CategoryInfo class is used to keep track of the number of times each year appears /// The CategoryInfo class is used to keep track of the number of times each year appears
/// </summary> /// </summary>
private async Task<IBNItem[]> GetAllYears(Folder parent, User user) private async Task<IbnItem[]> GetAllYears(Folder parent, User user)
{ {
Dictionary<int, int> data = new Dictionary<int, int>(); var data = new Dictionary<int, int>();
// Get all the allowed recursive children // Get all the allowed recursive children
IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user); IEnumerable<BaseItem> allItems = parent.GetParentalAllowedRecursiveChildren(user);
@ -57,16 +57,16 @@ namespace MediaBrowser.Api.HttpHandlers
} }
// Get the Year objects // Get the Year objects
Year[] entities = await Task.WhenAll(data.Keys.Select(key => { return Kernel.Instance.ItemController.GetYear(key); })).ConfigureAwait(false); Year[] entities = await Task.WhenAll(data.Keys.Select(key => Kernel.Instance.ItemController.GetYear(key))).ConfigureAwait(false);
// Convert to an array of IBNItem // Convert to an array of IBNItem
IBNItem[] items = new IBNItem[entities.Length]; var items = new IbnItem[entities.Length];
for (int i = 0; i < entities.Length; i++) for (int i = 0; i < entities.Length; i++)
{ {
Year e = entities[i]; Year e = entities[i];
items[i] = ApiService.GetIBNItem(e, data[int.Parse(e.Name)]); items[i] = ApiService.GetIbnItem(e, data[int.Parse(e.Name)]);
} }
return items; return items;

View File

@ -79,7 +79,7 @@ namespace MediaBrowser.Api
quality = 90; quality = 90;
} }
using (EncoderParameters encoderParameters = new EncoderParameters(1)) using (var encoderParameters = new EncoderParameters(1))
{ {
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality.Value); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, quality.Value);
newImage.Save(target, GetImageCodeInfo("image/jpeg"), encoderParameters); newImage.Save(target, GetImageCodeInfo("image/jpeg"), encoderParameters);

View File

@ -11,7 +11,7 @@ namespace MediaBrowser.ApiInteraction
} }
public ApiClient() public ApiClient()
: this(new WebRequestHandler() { CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate) }) : this(new WebRequestHandler { CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate) })
{ {
} }
} }

View File

@ -12,7 +12,7 @@ namespace MediaBrowser.ApiInteraction
/// </summary> /// </summary>
public abstract class BaseApiClient : IDisposable public abstract class BaseApiClient : IDisposable
{ {
public BaseApiClient() protected BaseApiClient()
{ {
DataSerializer.Configure(); DataSerializer.Configure();
} }
@ -45,7 +45,7 @@ namespace MediaBrowser.ApiInteraction
{ {
get get
{ {
return ApiInteraction.SerializationFormats.Protobuf; return SerializationFormats.Protobuf;
} }
} }
@ -301,8 +301,8 @@ namespace MediaBrowser.ApiInteraction
/// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param> /// <param name="quality">Quality level, from 0-100. Currently only applies to JPG. The default value should suffice.</param>
public string[] GetBackdropImageUrls(DtoBaseItem item, int? width = null, int? height = null, int? maxWidth = null, int? maxHeight = null, int? quality = null) public string[] GetBackdropImageUrls(DtoBaseItem item, int? width = null, int? height = null, int? maxWidth = null, int? maxHeight = null, int? quality = null)
{ {
Guid? backdropItemId = null; Guid? backdropItemId;
int backdropCount = 0; int backdropCount;
if (item.BackdropCount == 0) if (item.BackdropCount == 0)
{ {
@ -320,7 +320,7 @@ namespace MediaBrowser.ApiInteraction
return new string[] { }; return new string[] { };
} }
string[] files = new string[backdropCount]; var files = new string[backdropCount];
for (int i = 0; i < backdropCount; i++) for (int i = 0; i < backdropCount; i++)
{ {

View File

@ -28,7 +28,7 @@ namespace MediaBrowser.ApiInteraction
private WebClient HttpClient { get; set; } private WebClient HttpClient { get; set; }
#else #else
public BaseHttpApiClient(HttpClientHandler handler) protected BaseHttpApiClient(HttpClientHandler handler)
: base() : base()
{ {
handler.AutomaticDecompression = DecompressionMethods.Deflate; handler.AutomaticDecompression = DecompressionMethods.Deflate;
@ -81,13 +81,13 @@ namespace MediaBrowser.ApiInteraction
/// <summary> /// <summary>
/// Gets all Genres /// Gets all Genres
/// </summary> /// </summary>
public async Task<IBNItem[]> GetAllGenresAsync(Guid userId) public async Task<IbnItem[]> GetAllGenresAsync(Guid userId)
{ {
string url = ApiUrl + "/genres?userId=" + userId.ToString(); string url = ApiUrl + "/genres?userId=" + userId.ToString();
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem[]>(stream); return DeserializeFromStream<IbnItem[]>(stream);
} }
} }
@ -174,13 +174,13 @@ namespace MediaBrowser.ApiInteraction
/// <summary> /// <summary>
/// Gets all Years /// Gets all Years
/// </summary> /// </summary>
public async Task<IBNItem[]> GetAllYearsAsync(Guid userId) public async Task<IbnItem[]> GetAllYearsAsync(Guid userId)
{ {
string url = ApiUrl + "/years?userId=" + userId.ToString(); string url = ApiUrl + "/years?userId=" + userId.ToString();
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem[]>(stream); return DeserializeFromStream<IbnItem[]>(stream);
} }
} }
@ -265,13 +265,13 @@ namespace MediaBrowser.ApiInteraction
/// <summary> /// <summary>
/// Gets all studious /// Gets all studious
/// </summary> /// </summary>
public async Task<IBNItem[]> GetAllStudiosAsync(Guid userId) public async Task<IbnItem[]> GetAllStudiosAsync(Guid userId)
{ {
string url = ApiUrl + "/studios?userId=" + userId.ToString(); string url = ApiUrl + "/studios?userId=" + userId.ToString();
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem[]>(stream); return DeserializeFromStream<IbnItem[]>(stream);
} }
} }
@ -297,52 +297,52 @@ namespace MediaBrowser.ApiInteraction
/// <summary> /// <summary>
/// Gets a studio /// Gets a studio
/// </summary> /// </summary>
public async Task<IBNItem> GetStudioAsync(Guid userId, string name) public async Task<IbnItem> GetStudioAsync(Guid userId, string name)
{ {
string url = ApiUrl + "/studio?userId=" + userId.ToString() + "&name=" + name; string url = ApiUrl + "/studio?userId=" + userId.ToString() + "&name=" + name;
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem>(stream); return DeserializeFromStream<IbnItem>(stream);
} }
} }
/// <summary> /// <summary>
/// Gets a genre /// Gets a genre
/// </summary> /// </summary>
public async Task<IBNItem> GetGenreAsync(Guid userId, string name) public async Task<IbnItem> GetGenreAsync(Guid userId, string name)
{ {
string url = ApiUrl + "/genre?userId=" + userId.ToString() + "&name=" + name; string url = ApiUrl + "/genre?userId=" + userId.ToString() + "&name=" + name;
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem>(stream); return DeserializeFromStream<IbnItem>(stream);
} }
} }
/// <summary> /// <summary>
/// Gets a person /// Gets a person
/// </summary> /// </summary>
public async Task<IBNItem> GetPersonAsync(Guid userId, string name) public async Task<IbnItem> GetPersonAsync(Guid userId, string name)
{ {
string url = ApiUrl + "/person?userId=" + userId.ToString() + "&name=" + name; string url = ApiUrl + "/person?userId=" + userId.ToString() + "&name=" + name;
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem>(stream); return DeserializeFromStream<IbnItem>(stream);
} }
} }
/// <summary> /// <summary>
/// Gets a year /// Gets a year
/// </summary> /// </summary>
public async Task<IBNItem> GetYearAsync(Guid userId, int year) public async Task<IbnItem> GetYearAsync(Guid userId, int year)
{ {
string url = ApiUrl + "/year?userId=" + userId.ToString() + "&year=" + year; string url = ApiUrl + "/year?userId=" + userId.ToString() + "&year=" + year;
using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false)) using (Stream stream = await GetSerializedStreamAsync(url).ConfigureAwait(false))
{ {
return DeserializeFromStream<IBNItem>(stream); return DeserializeFromStream<IbnItem>(stream);
} }
} }

View File

@ -25,11 +25,11 @@ namespace MediaBrowser.ApiInteraction
//return Serializer.Deserialize<T>(stream); //return Serializer.Deserialize<T>(stream);
return ProtobufModelSerializer.Deserialize(stream, null, typeof(T)) as T; return ProtobufModelSerializer.Deserialize(stream, null, typeof(T)) as T;
} }
else if (format == SerializationFormats.Jsv) if (format == SerializationFormats.Jsv)
{ {
return TypeSerializer.DeserializeFromStream<T>(stream); return TypeSerializer.DeserializeFromStream<T>(stream);
} }
else if (format == SerializationFormats.Json) if (format == SerializationFormats.Json)
{ {
return JsonSerializer.DeserializeFromStream<T>(stream); return JsonSerializer.DeserializeFromStream<T>(stream);
} }
@ -42,16 +42,16 @@ namespace MediaBrowser.ApiInteraction
/// </summary> /// </summary>
public static object DeserializeFromStream(Stream stream, SerializationFormats format, Type type) public static object DeserializeFromStream(Stream stream, SerializationFormats format, Type type)
{ {
if (format == ApiInteraction.SerializationFormats.Protobuf) if (format == SerializationFormats.Protobuf)
{ {
//throw new NotImplementedException(); //throw new NotImplementedException();
return ProtobufModelSerializer.Deserialize(stream, null, type); return ProtobufModelSerializer.Deserialize(stream, null, type);
} }
else if (format == ApiInteraction.SerializationFormats.Jsv) if (format == SerializationFormats.Jsv)
{ {
return TypeSerializer.DeserializeFromStream(type, stream); return TypeSerializer.DeserializeFromStream(type, stream);
} }
else if (format == ApiInteraction.SerializationFormats.Json) if (format == SerializationFormats.Json)
{ {
return JsonSerializer.DeserializeFromStream(type, stream); return JsonSerializer.DeserializeFromStream(type, stream);
} }
@ -61,7 +61,7 @@ namespace MediaBrowser.ApiInteraction
public static void Configure() public static void Configure()
{ {
JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.ISO8601; JsConfig.DateHandler = JsonDateHandler.ISO8601;
JsConfig.ExcludeTypeInfo = true; JsConfig.ExcludeTypeInfo = true;
JsConfig.IncludeNullValues = false; JsConfig.IncludeNullValues = false;
} }

View File

@ -5,7 +5,7 @@ using System.Reflection;
namespace MediaBrowser.Common.Kernel namespace MediaBrowser.Common.Kernel
{ {
/// <summary> /// <summary>
/// Provides a base class to hold common application paths used by both the UI and Server. /// Provides a base class to hold common application paths used by both the Ui and Server.
/// This can be subclassed to add application-specific paths. /// This can be subclassed to add application-specific paths.
/// </summary> /// </summary>
public abstract class BaseApplicationPaths public abstract class BaseApplicationPaths
@ -22,6 +22,7 @@ namespace MediaBrowser.Common.Kernel
{ {
_programDataPath = GetProgramDataPath(); _programDataPath = GetProgramDataPath();
} }
return _programDataPath; return _programDataPath;
} }
} }

View File

@ -18,7 +18,7 @@ using System.Threading.Tasks;
namespace MediaBrowser.Common.Kernel namespace MediaBrowser.Common.Kernel
{ {
/// <summary> /// <summary>
/// Represents a shared base kernel for both the UI and server apps /// Represents a shared base kernel for both the Ui and server apps
/// </summary> /// </summary>
public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel public abstract class BaseKernel<TConfigurationType, TApplicationPathsType> : IDisposable, IKernel
where TConfigurationType : BaseApplicationConfiguration, new() where TConfigurationType : BaseApplicationConfiguration, new()
@ -44,8 +44,8 @@ namespace MediaBrowser.Common.Kernel
private IEnumerable<BaseHandler> HttpHandlers { get; set; } private IEnumerable<BaseHandler> HttpHandlers { get; set; }
/// <summary> /// <summary>
/// Both the UI and server will have a built-in HttpServer. /// Both the Ui and server will have a built-in HttpServer.
/// People will inevitably want remote control apps so it's needed in the UI too. /// People will inevitably want remote control apps so it's needed in the Ui too.
/// </summary> /// </summary>
public HttpServer HttpServer { get; private set; } public HttpServer HttpServer { get; private set; }

View File

@ -4,6 +4,6 @@ namespace MediaBrowser.Common.Kernel
public enum KernelContext public enum KernelContext
{ {
Server, Server,
UI Ui
} }
} }

View File

@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Logging
public void LogException(string message, Exception exception, params object[] paramList) public void LogException(string message, Exception exception, params object[] paramList)
{ {
StringBuilder builder = new StringBuilder(); var builder = new StringBuilder();
if (exception != null) if (exception != null)
{ {
@ -67,7 +67,7 @@ namespace MediaBrowser.Common.Logging
Thread currentThread = Thread.CurrentThread; Thread currentThread = Thread.CurrentThread;
LogRow row = new LogRow var row = new LogRow
{ {
Severity = severity, Severity = severity,
Message = message, Message = message,

View File

@ -25,19 +25,19 @@ namespace MediaBrowser.Common.Net.Handlers
} }
} }
private bool _TotalContentLengthDiscovered; private bool _totalContentLengthDiscovered;
private long? _TotalContentLength; private long? _totalContentLength;
public long? TotalContentLength public long? TotalContentLength
{ {
get get
{ {
if (!_TotalContentLengthDiscovered) if (!_totalContentLengthDiscovered)
{ {
_TotalContentLength = GetTotalContentLength(); _totalContentLength = GetTotalContentLength();
_TotalContentLengthDiscovered = true; _totalContentLengthDiscovered = true;
} }
return _TotalContentLength; return _totalContentLength;
} }
} }
@ -65,14 +65,14 @@ namespace MediaBrowser.Common.Net.Handlers
} }
} }
private List<KeyValuePair<long, long?>> _RequestedRanges; private List<KeyValuePair<long, long?>> _requestedRanges;
protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges protected IEnumerable<KeyValuePair<long, long?>> RequestedRanges
{ {
get get
{ {
if (_RequestedRanges == null) if (_requestedRanges == null)
{ {
_RequestedRanges = new List<KeyValuePair<long, long?>>(); _requestedRanges = new List<KeyValuePair<long, long?>>();
if (IsRangeRequest) if (IsRangeRequest)
{ {
@ -95,12 +95,12 @@ namespace MediaBrowser.Common.Net.Handlers
end = long.Parse(vals[1]); end = long.Parse(vals[1]);
} }
_RequestedRanges.Add(new KeyValuePair<long, long?>(start, end)); _requestedRanges.Add(new KeyValuePair<long, long?>(start, end));
} }
} }
} }
return _RequestedRanges; return _requestedRanges;
} }
} }
@ -379,21 +379,21 @@ namespace MediaBrowser.Common.Net.Handlers
} }
} }
private Hashtable _FormValues; private Hashtable _formValues;
/// <summary> /// <summary>
/// Gets a value from form POST data /// Gets a value from form POST data
/// </summary> /// </summary>
protected async Task<string> GetFormValue(string name) protected async Task<string> GetFormValue(string name)
{ {
if (_FormValues == null) if (_formValues == null)
{ {
_FormValues = await GetFormValues(HttpListenerContext.Request).ConfigureAwait(false); _formValues = await GetFormValues(HttpListenerContext.Request).ConfigureAwait(false);
} }
if (_FormValues.ContainsKey(name)) if (_formValues.ContainsKey(name))
{ {
return _FormValues[name].ToString(); return _formValues[name].ToString();
} }
return null; return null;
@ -404,7 +404,7 @@ namespace MediaBrowser.Common.Net.Handlers
/// </summary> /// </summary>
private async Task<Hashtable> GetFormValues(HttpListenerRequest request) private async Task<Hashtable> GetFormValues(HttpListenerRequest request)
{ {
Hashtable formVars = new Hashtable(); var formVars = new Hashtable();
if (request.HasEntityBody) if (request.HasEntityBody)
{ {
@ -412,7 +412,7 @@ namespace MediaBrowser.Common.Net.Handlers
{ {
using (Stream requestBody = request.InputStream) using (Stream requestBody = request.InputStream)
{ {
using (StreamReader reader = new StreamReader(requestBody, request.ContentEncoding)) using (var reader = new StreamReader(requestBody, request.ContentEncoding))
{ {
string s = await reader.ReadToEndAsync().ConfigureAwait(false); string s = await reader.ReadToEndAsync().ConfigureAwait(false);

View File

@ -6,6 +6,7 @@ using MediaBrowser.Common.Serialization;
namespace MediaBrowser.Common.Net.Handlers namespace MediaBrowser.Common.Net.Handlers
{ {
public abstract class BaseSerializationHandler<T> : BaseHandler public abstract class BaseSerializationHandler<T> : BaseHandler
where T : class
{ {
public SerializationFormat SerializationFormat public SerializationFormat SerializationFormat
{ {
@ -35,21 +36,21 @@ namespace MediaBrowser.Common.Net.Handlers
} }
} }
private bool _ObjectToSerializeEnsured; private bool _objectToSerializeEnsured;
private T _ObjectToSerialize; private T _objectToSerialize;
private async Task EnsureObjectToSerialize() private async Task EnsureObjectToSerialize()
{ {
if (!_ObjectToSerializeEnsured) if (!_objectToSerializeEnsured)
{ {
_ObjectToSerialize = await GetObjectToSerialize().ConfigureAwait(false); _objectToSerialize = await GetObjectToSerialize().ConfigureAwait(false);
if (_ObjectToSerialize == null) if (_objectToSerialize == null)
{ {
StatusCode = 404; StatusCode = 404;
} }
_ObjectToSerializeEnsured = true; _objectToSerializeEnsured = true;
} }
} }
@ -67,13 +68,13 @@ namespace MediaBrowser.Common.Net.Handlers
switch (SerializationFormat) switch (SerializationFormat)
{ {
case SerializationFormat.Jsv: case SerializationFormat.Jsv:
JsvSerializer.SerializeToStream(_ObjectToSerialize, stream); JsvSerializer.SerializeToStream(_objectToSerialize, stream);
break; break;
case SerializationFormat.Protobuf: case SerializationFormat.Protobuf:
ProtobufSerializer.SerializeToStream(_ObjectToSerialize, stream); ProtobufSerializer.SerializeToStream(_objectToSerialize, stream);
break; break;
default: default:
JsonSerializer.SerializeToStream(_ObjectToSerialize, stream); JsonSerializer.SerializeToStream(_objectToSerialize, stream);
break; break;
} }
} }

View File

@ -15,42 +15,42 @@ namespace MediaBrowser.Common.Net.Handlers
return false; return false;
} }
private string _Path; private string _path;
public virtual string Path public virtual string Path
{ {
get get
{ {
if (!string.IsNullOrWhiteSpace(_Path)) if (!string.IsNullOrWhiteSpace(_path))
{ {
return _Path; return _path;
} }
return QueryString["path"]; return QueryString["path"];
} }
set set
{ {
_Path = value; _path = value;
} }
} }
private bool _SourceStreamEnsured; private bool _sourceStreamEnsured;
private Stream _SourceStream; private Stream _sourceStream;
private Stream SourceStream private Stream SourceStream
{ {
get get
{ {
EnsureSourceStream(); EnsureSourceStream();
return _SourceStream; return _sourceStream;
} }
} }
private void EnsureSourceStream() private void EnsureSourceStream()
{ {
if (!_SourceStreamEnsured) if (!_sourceStreamEnsured)
{ {
try try
{ {
_SourceStream = File.OpenRead(Path); _sourceStream = File.OpenRead(Path);
} }
catch (FileNotFoundException ex) catch (FileNotFoundException ex)
{ {
@ -69,7 +69,7 @@ namespace MediaBrowser.Common.Net.Handlers
} }
finally finally
{ {
_SourceStreamEnsured = true; _sourceStreamEnsured = true;
} }
} }
} }
@ -245,9 +245,9 @@ namespace MediaBrowser.Common.Net.Handlers
if (count == null) if (count == null)
{ {
byte[] buffer = new byte[16 * 1024]; var buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
int read; int read;
while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0) while ((read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false)) > 0)
@ -259,9 +259,9 @@ namespace MediaBrowser.Common.Net.Handlers
} }
else else
{ {
byte[] buffer = new byte[count.Value]; var buffer = new byte[count.Value];
using (MemoryStream ms = new MemoryStream()) using (var ms = new MemoryStream())
{ {
int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); int read = await input.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);

View File

@ -6,21 +6,21 @@ namespace MediaBrowser.Common.Net
{ {
public class HttpServer : IObservable<HttpListenerContext>, IDisposable public class HttpServer : IObservable<HttpListenerContext>, IDisposable
{ {
private readonly HttpListener listener; private readonly HttpListener _listener;
private readonly IObservable<HttpListenerContext> stream; private readonly IObservable<HttpListenerContext> _stream;
public HttpServer(string url) public HttpServer(string url)
{ {
listener = new HttpListener(); _listener = new HttpListener();
listener.Prefixes.Add(url); _listener.Prefixes.Add(url);
listener.Start(); _listener.Start();
stream = ObservableHttpContext(); _stream = ObservableHttpContext();
} }
private IObservable<HttpListenerContext> ObservableHttpContext() private IObservable<HttpListenerContext> ObservableHttpContext()
{ {
return Observable.Create<HttpListenerContext>(obs => return Observable.Create<HttpListenerContext>(obs =>
Observable.FromAsync(() => listener.GetContextAsync()) Observable.FromAsync(() => _listener.GetContextAsync())
.Subscribe(obs)) .Subscribe(obs))
.Repeat() .Repeat()
.Retry() .Retry()
@ -29,12 +29,12 @@ namespace MediaBrowser.Common.Net
} }
public void Dispose() public void Dispose()
{ {
listener.Stop(); _listener.Stop();
} }
public IDisposable Subscribe(IObserver<HttpListenerContext> observer) public IDisposable Subscribe(IObserver<HttpListenerContext> observer)
{ {
return stream.Subscribe(observer); return _stream.Subscribe(observer);
} }
} }
} }

View File

@ -74,20 +74,20 @@ namespace MediaBrowser.Common.Plugins
} }
} }
private DateTime? _ConfigurationDateLastModified; private DateTime? _configurationDateLastModified;
public DateTime ConfigurationDateLastModified public DateTime ConfigurationDateLastModified
{ {
get get
{ {
if (_ConfigurationDateLastModified == null) if (_configurationDateLastModified == null)
{ {
if (File.Exists(ConfigurationFilePath)) if (File.Exists(ConfigurationFilePath))
{ {
_ConfigurationDateLastModified = File.GetLastWriteTimeUtc(ConfigurationFilePath); _configurationDateLastModified = File.GetLastWriteTimeUtc(ConfigurationFilePath);
} }
} }
return _ConfigurationDateLastModified ?? DateTime.MinValue; return _configurationDateLastModified ?? DateTime.MinValue;
} }
} }
@ -123,7 +123,7 @@ namespace MediaBrowser.Common.Plugins
} }
} }
private string _DataFolderPath; private string _dataFolderPath;
/// <summary> /// <summary>
/// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed /// Gets the full path to the data folder, where the plugin can store any miscellaneous files needed
/// </summary> /// </summary>
@ -131,19 +131,19 @@ namespace MediaBrowser.Common.Plugins
{ {
get get
{ {
if (_DataFolderPath == null) if (_dataFolderPath == null)
{ {
// Give the folder name the same name as the config file name // Give the folder name the same name as the config file name
// We can always make this configurable if/when needed // We can always make this configurable if/when needed
_DataFolderPath = Path.Combine(Kernel.ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(ConfigurationFileName)); _dataFolderPath = Path.Combine(Kernel.ApplicationPaths.PluginsPath, Path.GetFileNameWithoutExtension(ConfigurationFileName));
if (!Directory.Exists(_DataFolderPath)) if (!Directory.Exists(_dataFolderPath))
{ {
Directory.CreateDirectory(_DataFolderPath); Directory.CreateDirectory(_dataFolderPath);
} }
} }
return _DataFolderPath; return _dataFolderPath;
} }
} }
@ -156,9 +156,9 @@ namespace MediaBrowser.Common.Plugins
} }
/// <summary> /// <summary>
/// Returns true or false indicating if the plugin should be downloaded and run within the UI. /// Returns true or false indicating if the plugin should be downloaded and run within the Ui.
/// </summary> /// </summary>
public virtual bool DownloadToUI public virtual bool DownloadToUi
{ {
get get
{ {
@ -188,9 +188,9 @@ namespace MediaBrowser.Common.Plugins
{ {
InitializeOnServer(); InitializeOnServer();
} }
else if (kernel.KernelContext == KernelContext.UI) else if (kernel.KernelContext == KernelContext.Ui)
{ {
InitializeInUI(); InitializeInUi();
} }
} }
} }
@ -204,9 +204,9 @@ namespace MediaBrowser.Common.Plugins
} }
/// <summary> /// <summary>
/// Starts the plugin in the UI /// Starts the plugin in the Ui
/// </summary> /// </summary>
protected virtual void InitializeInUI() protected virtual void InitializeInUi()
{ {
} }
@ -219,9 +219,9 @@ namespace MediaBrowser.Common.Plugins
{ {
DisposeOnServer(); DisposeOnServer();
} }
else if (Context == KernelContext.UI) else if (Context == KernelContext.Ui)
{ {
InitializeInUI(); InitializeInUi();
} }
} }
@ -233,9 +233,9 @@ namespace MediaBrowser.Common.Plugins
} }
/// <summary> /// <summary>
/// Disposes the plugin in the UI /// Disposes the plugin in the Ui
/// </summary> /// </summary>
protected virtual void DisposeInUI() protected virtual void DisposeInUi()
{ {
} }
@ -252,7 +252,7 @@ namespace MediaBrowser.Common.Plugins
} }
// Reset this so it will be loaded again next time it's accessed // Reset this so it will be loaded again next time it's accessed
_ConfigurationDateLastModified = null; _configurationDateLastModified = null;
} }
} }
} }

View File

@ -59,15 +59,15 @@ namespace MediaBrowser.Common.Serialization
return ServiceStack.Text.JsonSerializer.DeserializeFromStream(type, stream); return ServiceStack.Text.JsonSerializer.DeserializeFromStream(type, stream);
} }
private static bool IsConfigured; private static bool _isConfigured;
private static void Configure() private static void Configure()
{ {
if (!IsConfigured) if (!_isConfigured)
{ {
ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.ISO8601; ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.JsonDateHandler.ISO8601;
ServiceStack.Text.JsConfig.ExcludeTypeInfo = true; ServiceStack.Text.JsConfig.ExcludeTypeInfo = true;
ServiceStack.Text.JsConfig.IncludeNullValues = false; ServiceStack.Text.JsConfig.IncludeNullValues = false;
IsConfigured = true; _isConfigured = true;
} }
} }
} }

View File

@ -25,7 +25,7 @@ namespace MediaBrowser.Common.Serialization
public static void SerializeToFile<T>(T obj, string file) public static void SerializeToFile<T>(T obj, string file)
{ {
using (FileStream stream = new FileStream(file, FileMode.Create)) using (var stream = new FileStream(file, FileMode.Create))
{ {
SerializeToStream(obj, stream); SerializeToStream(obj, stream);
} }
@ -41,7 +41,7 @@ namespace MediaBrowser.Common.Serialization
public static void SerializeToFile(object obj, string file) public static void SerializeToFile(object obj, string file)
{ {
using (FileStream stream = new FileStream(file, FileMode.Create)) using (var stream = new FileStream(file, FileMode.Create))
{ {
ServiceStack.Text.XmlSerializer.SerializeToStream(obj, stream); ServiceStack.Text.XmlSerializer.SerializeToStream(obj, stream);
} }

View File

@ -28,8 +28,8 @@ namespace MediaBrowser.Common.UI
{ {
Kernel = InstantiateKernel(); Kernel = InstantiateKernel();
Progress<TaskProgress> progress = new Progress<TaskProgress>(); var progress = new Progress<TaskProgress>();
Splash splash = new Splash(progress); var splash = new Splash(progress);
splash.Show(); splash.Show();

View File

@ -368,7 +368,7 @@ namespace Microsoft.Shell
/// <param name="channelName">Application's IPC channel name.</param> /// <param name="channelName">Application's IPC channel name.</param>
private static void CreateRemoteService(string channelName) private static void CreateRemoteService(string channelName)
{ {
BinaryServerFormatterSinkProvider serverProvider = new BinaryServerFormatterSinkProvider(); var serverProvider = new BinaryServerFormatterSinkProvider { };
serverProvider.TypeFilterLevel = TypeFilterLevel.Full; serverProvider.TypeFilterLevel = TypeFilterLevel.Full;
IDictionary props = new Dictionary<string, string>(); IDictionary props = new Dictionary<string, string>();
@ -383,7 +383,7 @@ namespace Microsoft.Shell
ChannelServices.RegisterChannel(channel, true); ChannelServices.RegisterChannel(channel, true);
// Expose the remote service with the REMOTE_SERVICE_NAME // Expose the remote service with the REMOTE_SERVICE_NAME
IPCRemoteService remoteService = new IPCRemoteService(); var remoteService = new IPCRemoteService();
RemotingServices.Marshal(remoteService, RemoteServiceName); RemotingServices.Marshal(remoteService, RemoteServiceName);
} }
@ -398,13 +398,13 @@ namespace Microsoft.Shell
/// </param> /// </param>
private static void SignalFirstInstance(string channelName, IList<string> args) private static void SignalFirstInstance(string channelName, IList<string> args)
{ {
IpcClientChannel secondInstanceChannel = new IpcClientChannel(); var secondInstanceChannel = new IpcClientChannel();
ChannelServices.RegisterChannel(secondInstanceChannel, true); ChannelServices.RegisterChannel(secondInstanceChannel, true);
string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName; string remotingServiceUrl = IpcProtocol + channelName + "/" + RemoteServiceName;
// Obtain a reference to the remoting service exposed by the server i.e the first instance of the application // Obtain a reference to the remoting service exposed by the server i.e the first instance of the application
IPCRemoteService firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl); var firstInstanceRemoteServiceReference = (IPCRemoteService)RemotingServices.Connect(typeof(IPCRemoteService), remotingServiceUrl);
// Check that the remote service exists, in some cases the first instance may not yet have created one, in which case // Check that the remote service exists, in some cases the first instance may not yet have created one, in which case
// the second instance should just exit // the second instance should just exit
@ -424,7 +424,7 @@ namespace Microsoft.Shell
private static object ActivateFirstInstanceCallback(object arg) private static object ActivateFirstInstanceCallback(object arg)
{ {
// Get command line args to be passed to first instance // Get command line args to be passed to first instance
IList<string> args = arg as IList<string>; var args = arg as IList<string>;
ActivateFirstInstance(args); ActivateFirstInstance(args);
return null; return null;
} }

View File

@ -15,11 +15,11 @@ namespace MediaBrowser.Common.UI
{ {
InitializeComponent(); InitializeComponent();
progress.ProgressChanged += progress_ProgressChanged; progress.ProgressChanged += ProgressChanged;
Loaded+=Splash_Loaded; Loaded+=SplashLoaded;
} }
void progress_ProgressChanged(object sender, TaskProgress e) void ProgressChanged(object sender, TaskProgress e)
{ {
// If logging has loaded, put a message in the log. // If logging has loaded, put a message in the log.
if (Logger.LoggerInstance != null) if (Logger.LoggerInstance != null)
@ -31,7 +31,7 @@ namespace MediaBrowser.Common.UI
pbProgress.Value = (double)e.PercentComplete; pbProgress.Value = (double)e.PercentComplete;
} }
private void Splash_Loaded(object sender, RoutedEventArgs e) private void SplashLoaded(object sender, RoutedEventArgs e)
{ {
// Setting this in markup throws an exception at runtime // Setting this in markup throws an exception at runtime
ShowTitleBar = false; ShowTitleBar = false;

View File

@ -5,7 +5,7 @@ namespace MediaBrowser.Controller.Entities
{ {
public class UserItemData public class UserItemData
{ {
private float? _Rating; private float? _rating;
/// <summary> /// <summary>
/// Gets or sets the users 0-10 rating /// Gets or sets the users 0-10 rating
/// </summary> /// </summary>
@ -13,7 +13,7 @@ namespace MediaBrowser.Controller.Entities
{ {
get get
{ {
return _Rating; return _rating;
} }
set set
{ {
@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.Entities
} }
} }
_Rating = value; _rating = value;
} }
} }

View File

@ -18,7 +18,7 @@ namespace MediaBrowser.Controller.FFMpeg
/// </summary> /// </summary>
public static FFProbeResult Run(BaseItem item, string cacheDirectory) public static FFProbeResult Run(BaseItem item, string cacheDirectory)
{ {
string cachePath = GetFFProbeCachePath(item, cacheDirectory); string cachePath = GetFfProbeCachePath(item, cacheDirectory);
// Use try catch to avoid having to use File.Exists // Use try catch to avoid having to use File.Exists
try try
@ -72,7 +72,7 @@ namespace MediaBrowser.Controller.FFMpeg
private static FFProbeResult Run(string input) private static FFProbeResult Run(string input)
{ {
ProcessStartInfo startInfo = new ProcessStartInfo(); var startInfo = new ProcessStartInfo { };
startInfo.CreateNoWindow = true; startInfo.CreateNoWindow = true;
@ -88,12 +88,12 @@ namespace MediaBrowser.Controller.FFMpeg
//Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments); //Logger.LogInfo(startInfo.FileName + " " + startInfo.Arguments);
Process process = new Process(); var process = new Process { };
process.StartInfo = startInfo; process.StartInfo = startInfo;
process.EnableRaisingEvents = true; process.EnableRaisingEvents = true;
process.Exited += process_Exited; process.Exited += ProcessExited;
try try
{ {
@ -122,12 +122,12 @@ namespace MediaBrowser.Controller.FFMpeg
} }
} }
static void process_Exited(object sender, EventArgs e) static void ProcessExited(object sender, EventArgs e)
{ {
(sender as Process).Dispose(); (sender as Process).Dispose();
} }
private static string GetFFProbeCachePath(BaseItem item, string cacheDirectory) private static string GetFfProbeCachePath(BaseItem item, string cacheDirectory)
{ {
string outputDirectory = Path.Combine(cacheDirectory, item.Id.ToString().Substring(0, 1)); string outputDirectory = Path.Combine(cacheDirectory, item.Id.ToString().Substring(0, 1));

View File

@ -18,7 +18,7 @@ namespace MediaBrowser.Controller.IO
public void Start() public void Start()
{ {
List<string> pathsToWatch = new List<string>(); var pathsToWatch = new List<string>();
var rootFolder = Kernel.Instance.RootFolder; var rootFolder = Kernel.Instance.RootFolder;
@ -42,7 +42,7 @@ namespace MediaBrowser.Controller.IO
foreach (string path in pathsToWatch) foreach (string path in pathsToWatch)
{ {
FileSystemWatcher watcher = new FileSystemWatcher(path, "*"); var watcher = new FileSystemWatcher(path, "*") { };
watcher.IncludeSubdirectories = true; watcher.IncludeSubdirectories = true;
@ -88,7 +88,7 @@ namespace MediaBrowser.Controller.IO
private Task ProcessPathChanges(IEnumerable<string> paths) private Task ProcessPathChanges(IEnumerable<string> paths)
{ {
List<BaseItem> itemsToRefresh = new List<BaseItem>(); var itemsToRefresh = new List<BaseItem>();
foreach (BaseItem item in paths.Select(p => GetAffectedBaseItem(p))) foreach (BaseItem item in paths.Select(p => GetAffectedBaseItem(p)))
{ {

View File

@ -167,12 +167,12 @@ namespace MediaBrowser.Controller.IO
public static string ResolveShortcut(string filename) public static string ResolveShortcut(string filename)
{ {
ShellLink link = new ShellLink(); var link = new ShellLink();
((IPersistFile)link).Load(filename, STGM_READ); ((IPersistFile)link).Load(filename, STGM_READ);
// TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files.
// ((IShellLinkW)link).Resolve(hwnd, 0) // ((IShellLinkW)link).Resolve(hwnd, 0)
StringBuilder sb = new StringBuilder(MAX_PATH); var sb = new StringBuilder(MAX_PATH);
WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); var data = new WIN32_FIND_DATAW();
((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0);
return sb.ToString(); return sb.ToString();
} }

View File

@ -209,7 +209,7 @@ namespace MediaBrowser.Controller
/// </summary> /// </summary>
public AuthenticationResult AuthenticateUser(User user, string password) public AuthenticationResult AuthenticateUser(User user, string password)
{ {
AuthenticationResult result = new AuthenticationResult(); var result = new AuthenticationResult();
// When EnableUserProfiles is false, only the default User can login // When EnableUserProfiles is false, only the default User can login
if (!Configuration.EnableUserProfiles) if (!Configuration.EnableUserProfiles)
@ -237,7 +237,7 @@ namespace MediaBrowser.Controller
public async Task ReloadItem(BaseItem item) public async Task ReloadItem(BaseItem item)
{ {
Folder folder = item as Folder; var folder = item as Folder;
if (folder != null && folder.IsRoot) if (folder != null && folder.IsRoot)
{ {
@ -283,16 +283,16 @@ namespace MediaBrowser.Controller
/// </summary> /// </summary>
private IEnumerable<User> GetAllUsers() private IEnumerable<User> GetAllUsers()
{ {
List<User> list = new List<User>(); var list = new List<User>();
// Return a dummy user for now since all calls to get items requre a userId // Return a dummy user for now since all calls to get items requre a userId
User user = new User(); var user = new User { };
user.Name = "Default User"; user.Name = "Default User";
user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b"); user.Id = Guid.Parse("5d1cf7fce25943b790d140095457a42b");
list.Add(user); list.Add(user);
user = new User(); user = new User { };
user.Name = "Abobader"; user.Name = "Abobader";
user.Id = Guid.NewGuid(); user.Id = Guid.NewGuid();
user.LastLoginDate = DateTime.UtcNow.AddDays(-1); user.LastLoginDate = DateTime.UtcNow.AddDays(-1);
@ -300,12 +300,12 @@ namespace MediaBrowser.Controller
user.Password = GetMD5("1234").ToString(); user.Password = GetMD5("1234").ToString();
list.Add(user); list.Add(user);
user = new User(); user = new User { };
user.Name = "Scottisafool"; user.Name = "Scottisafool";
user.Id = Guid.NewGuid(); user.Id = Guid.NewGuid();
list.Add(user); list.Add(user);
user = new User(); user = new User { };
user.Name = "Redshirt"; user.Name = "Redshirt";
user.Id = Guid.NewGuid(); user.Id = Guid.NewGuid();
list.Add(user); list.Add(user);
@ -381,7 +381,7 @@ namespace MediaBrowser.Controller
// Extract exe // Extract exe
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Controller.FFMpeg." + Path.GetFileName(exe))) using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MediaBrowser.Controller.FFMpeg." + Path.GetFileName(exe)))
{ {
using (FileStream fileStream = new FileStream(exe, FileMode.Create)) using (var fileStream = new FileStream(exe, FileMode.Create))
{ {
stream.CopyTo(fileStream); stream.CopyTo(fileStream);
} }

View File

@ -114,11 +114,7 @@ namespace MediaBrowser.Controller.Library
{ {
// If it's a folder look for child entities // If it's a folder look for child entities
(item as Folder).Children = (await Task.WhenAll(GetChildren(item as Folder, fileSystemChildren, allowInternetProviders)).ConfigureAwait(false)) (item as Folder).Children = (await Task.WhenAll(GetChildren(item as Folder, fileSystemChildren, allowInternetProviders)).ConfigureAwait(false))
.Where(i => i != null).OrderBy(f => .Where(i => i != null).OrderBy(f => (string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName));
{
return string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName;
});
} }
} }
@ -130,7 +126,7 @@ namespace MediaBrowser.Controller.Library
/// </summary> /// </summary>
private Task<BaseItem>[] GetChildren(Folder folder, WIN32_FIND_DATA[] fileSystemChildren, bool allowInternetProviders) private Task<BaseItem>[] GetChildren(Folder folder, WIN32_FIND_DATA[] fileSystemChildren, bool allowInternetProviders)
{ {
Task<BaseItem>[] tasks = new Task<BaseItem>[fileSystemChildren.Length]; var tasks = new Task<BaseItem>[fileSystemChildren.Length];
for (int i = 0; i < fileSystemChildren.Length; i++) for (int i = 0; i < fileSystemChildren.Length; i++)
{ {
@ -147,8 +143,8 @@ namespace MediaBrowser.Controller.Library
/// </summary> /// </summary>
private WIN32_FIND_DATA[] FilterChildFileSystemEntries(WIN32_FIND_DATA[] fileSystemChildren, bool flattenShortcuts) private WIN32_FIND_DATA[] FilterChildFileSystemEntries(WIN32_FIND_DATA[] fileSystemChildren, bool flattenShortcuts)
{ {
WIN32_FIND_DATA[] returnArray = new WIN32_FIND_DATA[fileSystemChildren.Length]; var returnArray = new WIN32_FIND_DATA[fileSystemChildren.Length];
List<WIN32_FIND_DATA> resolvedShortcuts = new List<WIN32_FIND_DATA>(); var resolvedShortcuts = new List<WIN32_FIND_DATA>();
for (int i = 0; i < fileSystemChildren.Length; i++) for (int i = 0; i < fileSystemChildren.Length; i++)
{ {
@ -256,7 +252,7 @@ namespace MediaBrowser.Controller.Library
private async Task<T> CreateImagesByNameItem<T>(string path, string name) private async Task<T> CreateImagesByNameItem<T>(string path, string name)
where T : BaseEntity, new() where T : BaseEntity, new()
{ {
T item = new T(); var item = new T { };
item.Name = name; item.Name = name;
item.Id = Kernel.GetMD5(path); item.Id = Kernel.GetMD5(path);
@ -269,7 +265,7 @@ namespace MediaBrowser.Controller.Library
item.DateCreated = Directory.GetCreationTimeUtc(path); item.DateCreated = Directory.GetCreationTimeUtc(path);
item.DateModified = Directory.GetLastWriteTimeUtc(path); item.DateModified = Directory.GetLastWriteTimeUtc(path);
ItemResolveEventArgs args = new ItemResolveEventArgs(); var args = new ItemResolveEventArgs { };
args.FileInfo = FileData.GetFileData(path); args.FileInfo = FileData.GetFileData(path);
args.FileSystemChildren = FileData.GetFileSystemEntries(path, "*").ToArray(); args.FileSystemChildren = FileData.GetFileSystemEntries(path, "*").ToArray();

View File

@ -249,7 +249,7 @@ namespace MediaBrowser.Controller.Providers
private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict) private Dictionary<string, string> ConvertDictionaryToCaseInSensitive(Dictionary<string, string> dict)
{ {
Dictionary<string, string> newDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); var newDict = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (string key in dict.Keys) foreach (string key in dict.Keys)
{ {

View File

@ -347,7 +347,7 @@ namespace MediaBrowser.Controller.Providers
private AudioStream FetchMediaInfoAudio(XmlReader reader) private AudioStream FetchMediaInfoAudio(XmlReader reader)
{ {
AudioStream stream = new AudioStream(); var stream = new AudioStream();
reader.MoveToContent(); reader.MoveToContent();
@ -466,7 +466,7 @@ namespace MediaBrowser.Controller.Providers
private SubtitleStream FetchMediaInfoSubtitles(XmlReader reader) private SubtitleStream FetchMediaInfoSubtitles(XmlReader reader)
{ {
SubtitleStream stream = new SubtitleStream(); var stream = new SubtitleStream();
reader.MoveToContent(); reader.MoveToContent();
@ -681,7 +681,7 @@ namespace MediaBrowser.Controller.Providers
private PersonInfo GetPersonFromXmlNode(XmlReader reader) private PersonInfo GetPersonFromXmlNode(XmlReader reader)
{ {
PersonInfo person = new PersonInfo(); var person = new PersonInfo();
reader.MoveToContent(); reader.MoveToContent();

View File

@ -26,7 +26,7 @@ namespace MediaBrowser.Controller.Providers
{ {
if (args.ContainsFile("folder.xml")) if (args.ContainsFile("folder.xml"))
{ {
await Task.Run(() => { Fetch(item, args); }).ConfigureAwait(false); await Task.Run(() => Fetch(item, args)).ConfigureAwait(false);
} }
} }

View File

@ -32,10 +32,10 @@ namespace MediaBrowser.Controller.Providers
if (baseItem != null) if (baseItem != null)
{ {
return Task.Run(() => { PopulateBaseItemImages(baseItem, args); }); return Task.Run(() => PopulateBaseItemImages(baseItem, args));
} }
return Task.Run(() => { PopulateImages(item, args); }); return Task.Run(() => PopulateImages(item, args));
} }
return Task.FromResult<object>(null); return Task.FromResult<object>(null);
@ -74,7 +74,7 @@ namespace MediaBrowser.Controller.Providers
/// </summary> /// </summary>
private void PopulateBaseItemImages(BaseItem item, ItemResolveEventArgs args) private void PopulateBaseItemImages(BaseItem item, ItemResolveEventArgs args)
{ {
List<string> backdropFiles = new List<string>(); var backdropFiles = new List<string>();
for (int i = 0; i < args.FileSystemChildren.Length; i++) for (int i = 0; i < args.FileSystemChildren.Length; i++)
{ {

View File

@ -28,11 +28,11 @@ namespace MediaBrowser.Controller.Providers
{ {
if (args.ContainsFolder("trailers")) if (args.ContainsFolder("trailers"))
{ {
List<Video> items = new List<Video>(); var items = new List<Video>();
foreach (WIN32_FIND_DATA file in FileData.GetFileSystemEntries(Path.Combine(args.Path, "trailers"), "*")) foreach (WIN32_FIND_DATA file in FileData.GetFileSystemEntries(Path.Combine(args.Path, "trailers"), "*"))
{ {
Video video = await Kernel.Instance.ItemController.GetItem(file.Path, fileInfo: file).ConfigureAwait(false) as Video; var video = await Kernel.Instance.ItemController.GetItem(file.Path, fileInfo: file).ConfigureAwait(false) as Video;
if (video != null) if (video != null)
{ {

View File

@ -22,7 +22,7 @@ namespace MediaBrowser.Controller.Providers.Movies
public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args)
{ {
await Task.Run(() => { Fetch(item, args); }).ConfigureAwait(false); await Task.Run(() => Fetch(item, args)).ConfigureAwait(false);
} }
private void Fetch(BaseEntity item, ItemResolveEventArgs args) private void Fetch(BaseEntity item, ItemResolveEventArgs args)

View File

@ -26,11 +26,11 @@ namespace MediaBrowser.Controller.Providers.Movies
{ {
if (args.ContainsFolder("specials")) if (args.ContainsFolder("specials"))
{ {
List<Video> items = new List<Video>(); var items = new List<Video>();
foreach (WIN32_FIND_DATA file in FileData.GetFileSystemEntries(Path.Combine(args.Path, "specials"), "*")) foreach (WIN32_FIND_DATA file in FileData.GetFileSystemEntries(Path.Combine(args.Path, "specials"), "*"))
{ {
Video video = await Kernel.Instance.ItemController.GetItem(file.Path, fileInfo: file).ConfigureAwait(false) as Video; var video = await Kernel.Instance.ItemController.GetItem(file.Path, fileInfo: file).ConfigureAwait(false) as Video;
if (video != null) if (video != null)
{ {

View File

@ -25,13 +25,13 @@ namespace MediaBrowser.Controller.Providers.TV
{ {
return Task.Run(() => return Task.Run(() =>
{ {
Episode episode = item as Episode; var episode = item as Episode;
string metadataFolder = Path.Combine(args.Parent.Path, "metadata"); string metadataFolder = Path.Combine(args.Parent.Path, "metadata");
string episodeFileName = Path.GetFileName(episode.Path); string episodeFileName = Path.GetFileName(episode.Path);
Season season = args.Parent as Season; var season = args.Parent as Season;
SetPrimaryImagePath(episode, season, metadataFolder, episodeFileName); SetPrimaryImagePath(episode, season, metadataFolder, episodeFileName);
}); });
@ -40,7 +40,7 @@ namespace MediaBrowser.Controller.Providers.TV
private void SetPrimaryImagePath(Episode item, Season season, string metadataFolder, string episodeFileName) private void SetPrimaryImagePath(Episode item, Season season, string metadataFolder, string episodeFileName)
{ {
// Look for the image file in the metadata folder, and if found, set PrimaryImagePath // Look for the image file in the metadata folder, and if found, set PrimaryImagePath
string[] imageFiles = new string[] { var imageFiles = new string[] {
Path.Combine(metadataFolder, Path.ChangeExtension(episodeFileName, ".jpg")), Path.Combine(metadataFolder, Path.ChangeExtension(episodeFileName, ".jpg")),
Path.Combine(metadataFolder, Path.ChangeExtension(episodeFileName, ".png")) Path.Combine(metadataFolder, Path.ChangeExtension(episodeFileName, ".png"))
}; };

View File

@ -22,7 +22,7 @@ namespace MediaBrowser.Controller.Providers.TV
public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args)
{ {
await Task.Run(() => { Fetch(item, args); }).ConfigureAwait(false); await Task.Run(() => Fetch(item, args)).ConfigureAwait(false);
} }
private void Fetch(BaseEntity item, ItemResolveEventArgs args) private void Fetch(BaseEntity item, ItemResolveEventArgs args)

View File

@ -22,7 +22,7 @@ namespace MediaBrowser.Controller.Providers.TV
public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args) public override async Task FetchAsync(BaseEntity item, ItemResolveEventArgs args)
{ {
await Task.Run(() => { Fetch(item, args); }).ConfigureAwait(false); await Task.Run(() => Fetch(item, args)).ConfigureAwait(false);
} }
private void Fetch(BaseEntity item, ItemResolveEventArgs args) private void Fetch(BaseEntity item, ItemResolveEventArgs args)

View File

@ -87,7 +87,7 @@ namespace MediaBrowser.Controller.Providers
private void FetchFromAudioStream(Video video, MediaStream stream) private void FetchFromAudioStream(Video video, MediaStream stream)
{ {
AudioStream audio = new AudioStream(); var audio = new AudioStream{};
audio.Codec = stream.codec_name; audio.Codec = stream.codec_name;
@ -112,7 +112,7 @@ namespace MediaBrowser.Controller.Providers
private void FetchFromSubtitleStream(Video video, MediaStream stream) private void FetchFromSubtitleStream(Video video, MediaStream stream)
{ {
SubtitleStream subtitle = new SubtitleStream(); var subtitle = new SubtitleStream{};
subtitle.Language = GetDictionaryValue(stream.tags, "language"); subtitle.Language = GetDictionaryValue(stream.tags, "language");
@ -157,7 +157,7 @@ namespace MediaBrowser.Controller.Providers
return false; return false;
} }
if (video.FrameRate == 0 || video.Height == 0 || video.Width == 0 || video.BitRate == 0) if (Convert.ToInt32(video.FrameRate) == 0 || video.Height == 0 || video.Width == 0 || video.BitRate == 0)
{ {
return false; return false;
} }

View File

@ -66,7 +66,7 @@ namespace MediaBrowser.Controller.Resolvers.Movies
{ {
var child = args.FileSystemChildren[i]; var child = args.FileSystemChildren[i];
ItemResolveEventArgs childArgs = new ItemResolveEventArgs() var childArgs = new ItemResolveEventArgs
{ {
FileInfo = child, FileInfo = child,
FileSystemChildren = new WIN32_FIND_DATA[] { }, FileSystemChildren = new WIN32_FIND_DATA[] { },
@ -77,7 +77,7 @@ namespace MediaBrowser.Controller.Resolvers.Movies
if (item != null) if (item != null)
{ {
return new Movie() return new Movie
{ {
Path = item.Path, Path = item.Path,
VideoType = item.VideoType VideoType = item.VideoType

View File

@ -12,19 +12,12 @@ namespace MediaBrowser.Controller.Resolvers.TV
{ {
if (args.Parent is Series && args.IsDirectory) if (args.Parent is Series && args.IsDirectory)
{ {
Season season = new Season(); var season = new Season { };
season.IndexNumber = TVUtils.GetSeasonNumberFromPath(args.Path); season.IndexNumber = TVUtils.GetSeasonNumberFromPath(args.Path);
// Gather these now so that the episode provider classes can utilize them instead of having to make their own file system calls // Gather these now so that the episode provider classes can utilize them instead of having to make their own file system calls
if (args.ContainsFolder("metadata")) season.MetadataFiles = args.ContainsFolder("metadata") ? Directory.GetFiles(Path.Combine(args.Path, "metadata"), "*", SearchOption.TopDirectoryOnly) : new string[] { };
{
season.MetadataFiles = Directory.GetFiles(Path.Combine(args.Path, "metadata"), "*", SearchOption.TopDirectoryOnly);
}
else
{
season.MetadataFiles = new string[] { };
}
return season; return season;
} }

View File

@ -21,7 +21,7 @@ namespace MediaBrowser.Controller.Weather
public WeatherClient() public WeatherClient()
{ {
WebRequestHandler handler = new WebRequestHandler(); var handler = new WebRequestHandler { };
handler.AutomaticDecompression = DecompressionMethods.Deflate; handler.AutomaticDecompression = DecompressionMethods.Deflate;
handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate); handler.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Revalidate);
@ -56,7 +56,7 @@ namespace MediaBrowser.Controller.Weather
/// </summary> /// </summary>
private WeatherInfo GetWeatherInfo(WeatherData data) private WeatherInfo GetWeatherInfo(WeatherData data)
{ {
WeatherInfo info = new WeatherInfo(); var info = new WeatherInfo();
if (data.current_condition != null) if (data.current_condition != null)
{ {

View File

@ -7,7 +7,7 @@ namespace MediaBrowser.Model.DTO
/// This is a stub class used by the api to get IBN types along with their item counts /// This is a stub class used by the api to get IBN types along with their item counts
/// </summary> /// </summary>
[ProtoContract] [ProtoContract]
public class IBNItem public class IbnItem
{ {
/// <summary> /// <summary>
/// The name of the person, genre, etc /// The name of the person, genre, etc

View File

@ -44,7 +44,7 @@
<Compile Include="DTO\DtoUser.cs" /> <Compile Include="DTO\DtoUser.cs" />
<Compile Include="DTO\VideoInfo.cs" /> <Compile Include="DTO\VideoInfo.cs" />
<Compile Include="DTO\VideoOutputFormats.cs" /> <Compile Include="DTO\VideoOutputFormats.cs" />
<Compile Include="DTO\IBNItem.cs" /> <Compile Include="DTO\IbnItem.cs" />
<Compile Include="Entities\AudioStream.cs" /> <Compile Include="Entities\AudioStream.cs" />
<Compile Include="Entities\ImageType.cs" /> <Compile Include="Entities\ImageType.cs" />
<Compile Include="Entities\IHasProviderIds.cs" /> <Compile Include="Entities\IHasProviderIds.cs" />

View File

@ -30,7 +30,7 @@ namespace MediaBrowser.ServerApplication
SingleInstance<App>.Cleanup(); SingleInstance<App>.Cleanup();
} }
} }
#region ISingleInstanceApp Members #region ISingleInstanceApp Members
public bool SignalExternalCommandLineArgs(IList<string> args) public bool SignalExternalCommandLineArgs(IList<string> args)
{ {
@ -42,9 +42,30 @@ namespace MediaBrowser.ServerApplication
public static void OpenDashboard() public static void OpenDashboard()
{ {
using (Process process = Process.Start("http://localhost:" + Kernel.Instance.Configuration.HttpServerPortNumber + "/mediabrowser/dashboard/index.html")) OpenUrl("http://localhost:" + Kernel.Instance.Configuration.HttpServerPortNumber +
"/mediabrowser/dashboard/index.html");
}
public static void OpenUrl(string url)
{
var process = new Process
{ {
} StartInfo = new ProcessStartInfo
{
FileName = url
},
EnableRaisingEvents = true
};
process.Exited += ProcessExited;
process.Start();
}
static void ProcessExited(object sender, EventArgs e)
{
(sender as Process).Dispose();
} }
protected override IKernel InstantiateKernel() protected override IKernel InstantiateKernel()

View File

@ -23,9 +23,7 @@ namespace MediaBrowser.ServerApplication
private void cmVisitCT_click(object sender, RoutedEventArgs e) private void cmVisitCT_click(object sender, RoutedEventArgs e)
{ {
using (Process process = Process.Start("http://community.mediabrowser.tv/")) App.OpenUrl("http://community.mediabrowser.tv/");
{
}
} }
private void cmExit_click(object sender, RoutedEventArgs e) private void cmExit_click(object sender, RoutedEventArgs e)