Reports - Add Users activities

pull/702/head
Tavares André 10 years ago
parent ff26b09583
commit 1e07dbec63

@ -84,6 +84,8 @@
<Compile Include="Playback\MediaInfoService.cs" />
<Compile Include="Playback\TranscodingThrottler.cs" />
<Compile Include="PlaylistService.cs" />
<Compile Include="Reports\Activities\ReportActivitiesBuilder.cs" />
<Compile Include="Reports\Common\HeaderActivitiesMetadata.cs" />
<Compile Include="Reports\Common\HeaderMetadata.cs" />
<Compile Include="Reports\Common\ItemViewType.cs" />
<Compile Include="Reports\Common\ReportBuilderBase.cs" />
@ -91,15 +93,16 @@
<Compile Include="Reports\Common\ReportFieldType.cs" />
<Compile Include="Reports\Common\ReportHeaderIdType.cs" />
<Compile Include="Reports\Common\ReportHelper.cs" />
<Compile Include="Reports\Common\ReportIncludeItemTypes.cs" />
<Compile Include="Reports\Common\ReportViewType.cs" />
<Compile Include="Reports\Data\ReportBuilder.cs" />
<Compile Include="Reports\Data\ReportExport.cs" />
<Compile Include="Reports\Data\ReportGroup.cs" />
<Compile Include="Reports\Data\ReportHeader.cs" />
<Compile Include="Reports\Data\ReportItem.cs" />
<Compile Include="Reports\Data\ReportOptions.cs" />
<Compile Include="Reports\Data\ReportResult.cs" />
<Compile Include="Reports\Data\ReportRow.cs" />
<Compile Include="Reports\Model\ReportGroup.cs" />
<Compile Include="Reports\Model\ReportHeader.cs" />
<Compile Include="Reports\Model\ReportItem.cs" />
<Compile Include="Reports\Model\ReportResult.cs" />
<Compile Include="Reports\Model\ReportRow.cs" />
<Compile Include="Reports\ReportRequests.cs" />
<Compile Include="Reports\ReportsService.cs" />
<Compile Include="Reports\Stat\ReportStatBuilder.cs" />
@ -204,6 +207,13 @@
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<!-- 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">

@ -0,0 +1,240 @@
using MediaBrowser.Model.Activity;
using MediaBrowser.Model.Querying;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
namespace MediaBrowser.Api.Reports
{
/// <summary> A report activities builder. </summary>
/// <seealso cref="T:MediaBrowser.Api.Reports.ReportBuilderBase"/>
public class ReportActivitiesBuilder : ReportBuilderBase
{
#region [Constructors]
/// <summary>
/// Initializes a new instance of the MediaBrowser.Api.Reports.ReportActivitiesBuilder class. </summary>
/// <param name="libraryManager"> Manager for library. </param>
/// <param name="userManager"> Manager for user. </param>
public ReportActivitiesBuilder(ILibraryManager libraryManager, IUserManager userManager)
: base(libraryManager)
{
_userManager = userManager;
}
#endregion
#region [Private Fields]
private readonly IUserManager _userManager; ///< Manager for user
#endregion
#region [Public Methods]
/// <summary> Gets a result. </summary>
/// <param name="queryResult"> The query result. </param>
/// <param name="request"> The request. </param>
/// <returns> The result. </returns>
public ReportResult GetResult(QueryResult<ActivityLogEntry> queryResult, IReportsQuery request)
{
List<ReportOptions<ActivityLogEntry>> options = this.GetReportOptions<ActivityLogEntry>(request,
() => this.GetDefaultHeaderMetadata(),
(hm) => this.GetOption(hm)).Where(x => x.Header.Visible == true).ToList();
var headers = GetHeaders<ActivityLogEntry>(options);
var rows = GetReportRows(queryResult.Items, options);
ReportResult result = new ReportResult { Headers = headers };
HeaderMetadata groupBy = ReportHelper.GetHeaderMetadataType(request.GroupBy);
int i = headers.FindIndex(x => x.FieldName == groupBy);
if (groupBy != HeaderMetadata.None && i >= 0)
{
var rowsGroup = rows.SelectMany(x => x.Columns[i].Name.Split(';'), (x, g) => new { Group = g.Trim(), Rows = x })
.GroupBy(x => x.Group)
.OrderBy(x => x.Key)
.Select(x => new ReportGroup { Name = x.Key, Rows = x.Select(r => r.Rows).ToList() });
result.Groups = rowsGroup.ToList();
result.IsGrouped = true;
}
else
{
result.Rows = rows;
result.IsGrouped = false;
}
return result;
}
#endregion
#region [Protected Internal Methods]
/// <summary> Gets the headers. </summary>
/// <typeparam name="H"> Type of the header. </typeparam>
/// <param name="request"> The request. </param>
/// <returns> The headers. </returns>
/// <seealso cref="M:MediaBrowser.Api.Reports.ReportBuilderBase.GetHeaders{H}(H)"/>
protected internal override List<ReportHeader> GetHeaders<H>(H request)
{
return this.GetHeaders<ActivityLogEntry>(request, () => this.GetDefaultHeaderMetadata(), (hm) => this.GetOption(hm));
}
#endregion
#region [Private Methods]
/// <summary> Gets default header metadata. </summary>
/// <returns> The default header metadata. </returns>
private List<HeaderMetadata> GetDefaultHeaderMetadata()
{
return new List<HeaderMetadata>
{
HeaderMetadata.Date,
HeaderMetadata.User,
HeaderMetadata.Type,
HeaderMetadata.Severity,
HeaderMetadata.Name,
HeaderMetadata.ShortOverview,
HeaderMetadata.Overview,
//HeaderMetadata.UserPrimaryImageTag,
//HeaderMetadata.Item,
};
}
/// <summary> Gets an option. </summary>
/// <param name="header"> The header. </param>
/// <param name="sortField"> The sort field. </param>
/// <returns> The option. </returns>
private ReportOptions<ActivityLogEntry> GetOption(HeaderMetadata header, string sortField = "")
{
HeaderMetadata internalHeader = header;
ReportOptions<ActivityLogEntry> option = new ReportOptions<ActivityLogEntry>()
{
Header = new ReportHeader
{
HeaderFieldType = ReportFieldType.String,
SortField = sortField,
Type = "",
ItemViewType = ItemViewType.None
}
};
switch (header)
{
case HeaderMetadata.StatusImage:
option.Header.ItemViewType = ItemViewType.StatusImage;
internalHeader = HeaderMetadata.Status;
option.Header.CanGroup = false;
break;
case HeaderMetadata.Name:
option.Column = (i, r) => i.Name;
break;
case HeaderMetadata.Overview:
option.Column = (i, r) => i.Overview;
option.Header.SortField = "";
option.Header.CanGroup = false;
break;
case HeaderMetadata.ShortOverview:
option.Column = (i, r) => i.ShortOverview;
option.Header.SortField = "";
option.Header.CanGroup = false;
break;
case HeaderMetadata.Type:
option.Column = (i, r) => i.Type;
option.Header.SortField = "";
break;
case HeaderMetadata.Date:
option.Column = (i, r) => i.Date;
option.Header.SortField = "";
option.Header.HeaderFieldType = ReportFieldType.DateTime;
option.Header.Type = "";
break;
case HeaderMetadata.UserPrimaryImageTag:
option.Column = (i, r) => i.UserPrimaryImageTag;
option.Header.SortField = "";
break;
case HeaderMetadata.Severity:
option.Column = (i, r) => i.Severity;
option.Header.SortField = "";
break;
case HeaderMetadata.Item:
option.Column = (i, r) => i.ItemId;
option.Header.SortField = "";
break;
case HeaderMetadata.User:
option.Column = (i, r) =>
{
if (!string.IsNullOrEmpty(i.UserId))
{
MediaBrowser.Controller.Entities.User user = _userManager.GetUserById(i.UserId);
if (user != null)
return user.Name;
}
return string.Empty;
};
option.Header.SortField = "";
break;
}
option.Header.Name = GetLocalizedHeader(internalHeader);
option.Header.FieldName = header;
return option;
}
/// <summary> Gets report rows. </summary>
/// <param name="items"> The items. </param>
/// <param name="options"> Options for controlling the operation. </param>
/// <returns> The report rows. </returns>
private List<ReportRow> GetReportRows(IEnumerable<ActivityLogEntry> items, List<ReportOptions<ActivityLogEntry>> options)
{
var rows = new List<ReportRow>();
foreach (ActivityLogEntry item in items)
{
ReportRow rRow = GetRow(item);
foreach (ReportOptions<ActivityLogEntry> option in options)
{
object itemColumn = option.Column != null ? option.Column(item, rRow) : "";
object itemId = option.ItemID != null ? option.ItemID(item) : "";
ReportItem rItem = new ReportItem
{
Name = ReportHelper.ConvertToString(itemColumn, option.Header.HeaderFieldType),
Id = ReportHelper.ConvertToString(itemId, ReportFieldType.Object)
};
rRow.Columns.Add(rItem);
}
rows.Add(rRow);
}
return rows;
}
/// <summary> Gets a row. </summary>
/// <param name="item"> The item. </param>
/// <returns> The row. </returns>
private ReportRow GetRow(ActivityLogEntry item)
{
ReportRow rRow = new ReportRow
{
Id = item.Id,
};
return rRow;
}
#endregion
}
}

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MediaBrowser.Api.Reports
{
public enum HeaderActivitiesMetadata
{
None,
Name,
Overview,
ShortOverview,
Type,
Date,
UserPrimaryImageTag,
Severity,
Item,
User
}
}

@ -42,6 +42,15 @@ namespace MediaBrowser.Api.Reports
AudioAlbumArtist,
MusicArtist,
AudioAlbum,
Status
Status,
//Activity logs
Overview,
ShortOverview,
Type,
Date,
UserPrimaryImageTag,
Severity,
Item,
User
}
}

@ -14,8 +14,11 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.Reports
{
/// <summary> A report builder base. </summary>
public class ReportBuilderBase
public abstract class ReportBuilderBase
{
#region [Constructors]
/// <summary>
/// Initializes a new instance of the MediaBrowser.Api.Reports.ReportBuilderBase class. </summary>
/// <param name="libraryManager"> Manager for library. </param>
@ -24,8 +27,43 @@ namespace MediaBrowser.Api.Reports
_libraryManager = libraryManager;
}
#endregion
#region [Protected Fields]
/// <summary> Manager for library. </summary>
protected readonly ILibraryManager _libraryManager;
protected readonly ILibraryManager _libraryManager; ///< Manager for library
protected Func<bool, string> GetBoolString = s => s == true ? "x" : ""; ///< .
#endregion
#region [Protected Internal Methods]
/// <summary> Gets the headers. </summary>
/// <typeparam name="H"> Type of the header. </typeparam>
/// <param name="request"> The request. </param>
/// <returns> The headers. </returns>
protected internal abstract List<ReportHeader> GetHeaders<H>(H request) where H : IReportsHeader;
#endregion
#region [Protected Methods]
/// <summary> Gets active headers. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="options"> Options for controlling the operation. </param>
/// <returns> The active headers. </returns>
protected List<ReportHeader> GetActiveHeaders<T>(List<ReportOptions<T>> options)
{
List<ReportHeader> headers = new List<ReportHeader>();
foreach (ReportOptions<T> option in options.Where(x => x.Header.Visible == true))
{
headers.Add(option.Header);
}
return headers;
}
/// <summary> Gets audio stream. </summary>
/// <param name="item"> The item. </param>
@ -73,6 +111,33 @@ namespace MediaBrowser.Api.Reports
GetGenre(name).Id);
}
/// <summary> Gets the headers. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="options"> Options for controlling the operation. </param>
/// <returns> The headers. </returns>
protected List<ReportHeader> GetHeaders<T>(List<ReportOptions<T>> options)
{
List<ReportHeader> headers = new List<ReportHeader>();
foreach (ReportOptions<T> option in options)
{
headers.Add(option.Header);
}
return headers;
}
/// <summary> Gets the headers. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="request"> The request. </param>
/// <param name="getHeadersMetadata"> The get headers metadata. </param>
/// <param name="getOptions"> Options for controlling the get. </param>
/// <returns> The headers. </returns>
protected List<ReportHeader> GetHeaders<T>(IReportsHeader request, Func<List<HeaderMetadata>> getHeadersMetadata, Func<HeaderMetadata, ReportOptions<T>> getOptions)
{
List<ReportOptions<T>> options = this.GetReportOptions(request, getHeadersMetadata, getOptions);
return this.GetHeaders(options);
}
/// <summary> Gets list as string. </summary>
/// <param name="items"> The items. </param>
/// <returns> The list as string. </returns>
@ -81,6 +146,22 @@ namespace MediaBrowser.Api.Reports
return String.Join("; ", items);
}
/// <summary> Gets localized header. </summary>
/// <param name="internalHeader"> The internal header. </param>
/// <returns> The localized header. </returns>
protected static string GetLocalizedHeader(HeaderMetadata internalHeader)
{
string headerName = "";
if (internalHeader != HeaderMetadata.None)
{
string localHeader = "Header" + internalHeader.ToString();
headerName = internalHeader != HeaderMetadata.None ? ReportHelper.GetJavaScriptLocalizedString(localHeader) : "";
if (string.Compare(localHeader, headerName, StringComparison.CurrentCultureIgnoreCase) == 0)
headerName = ReportHelper.GetServerLocalizedString(localHeader);
}
return headerName;
}
/// <summary> Gets media source information. </summary>
/// <param name="item"> The item. </param>
/// <returns> The media source information. </returns>
@ -130,6 +211,36 @@ namespace MediaBrowser.Api.Reports
GetPerson(name).Id);
}
/// <summary> Gets report options. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="request"> The request. </param>
/// <param name="getHeadersMetadata"> The get headers metadata. </param>
/// <param name="getOptions"> Options for controlling the get. </param>
/// <returns> The report options. </returns>
protected List<ReportOptions<T>> GetReportOptions<T>(IReportsHeader request, Func<List<HeaderMetadata>> getHeadersMetadata, Func<HeaderMetadata, ReportOptions<T>> getOptions)
{
List<HeaderMetadata> headersMetadata = getHeadersMetadata();
List<ReportOptions<T>> options = new List<ReportOptions<T>>();
foreach (HeaderMetadata header in headersMetadata)
{
options.Add(getOptions(header));
}
if (request != null && !string.IsNullOrEmpty(request.ReportColumns))
{
List<HeaderMetadata> headersMetadataFiltered = ReportHelper.GetFilteredReportHeaderMetadata(request.ReportColumns, () => headersMetadata);
foreach (ReportHeader header in options.Select(x => x.Header))
{
if (!headersMetadataFiltered.Contains(header.FieldName))
{
header.Visible = false;
}
}
}
return options;
}
/// <summary> Gets runtime date time. </summary>
/// <param name="runtime"> The runtime. </param>
/// <returns> The runtime date time. </returns>
@ -225,5 +336,7 @@ namespace MediaBrowser.Api.Reports
return string.Empty;
}
#endregion
}
}

@ -7,8 +7,77 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.Reports
{
/// <summary> A report helper. </summary>
public class ReportHelper
{
#region [Public Methods]
/// <summary> Convert field to string. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="value"> The value. </param>
/// <param name="fieldType"> Type of the field. </param>
/// <returns> The field converted to string. </returns>
public static string ConvertToString<T>(T value, ReportFieldType fieldType)
{
if (value == null)
return "";
switch (fieldType)
{
case ReportFieldType.String:
return value.ToString();
case ReportFieldType.Boolean:
return value.ToString();
case ReportFieldType.Date:
return string.Format("{0:d}", value);
case ReportFieldType.Time:
return string.Format("{0:t}", value);
case ReportFieldType.DateTime:
return string.Format("{0:d}", value);
case ReportFieldType.Minutes:
return string.Format("{0}mn", value);
case ReportFieldType.Int:
return string.Format("", value);
default:
if (value is Guid)
return string.Format("{0:N}", value);
return value.ToString();
}
}
/// <summary> Gets filtered report header metadata. </summary>
/// <param name="reportColumns"> The report columns. </param>
/// <param name="defaultReturnValue"> The default return value. </param>
/// <returns> The filtered report header metadata. </returns>
public static List<HeaderMetadata> GetFilteredReportHeaderMetadata(string reportColumns, Func<List<HeaderMetadata>> defaultReturnValue = null)
{
if (!string.IsNullOrEmpty(reportColumns))
{
var s = reportColumns.Split('|').Select(x => ReportHelper.GetHeaderMetadataType(x)).Where(x => x != HeaderMetadata.None);
return s.ToList();
}
else
if (defaultReturnValue != null)
return defaultReturnValue();
else
return new List<HeaderMetadata>();
}
/// <summary> Gets header metadata type. </summary>
/// <param name="header"> The header. </param>
/// <returns> The header metadata type. </returns>
public static HeaderMetadata GetHeaderMetadataType(string header)
{
if (string.IsNullOrEmpty(header))
return HeaderMetadata.None;
HeaderMetadata rType;
if (!Enum.TryParse<HeaderMetadata>(header, out rType))
return HeaderMetadata.None;
return rType;
}
/// <summary> Gets java script localized string. </summary>
/// <param name="phrase"> The phrase. </param>
/// <returns> The java script localized string. </returns>
@ -26,76 +95,47 @@ namespace MediaBrowser.Api.Reports
return phrase;
}
/// <summary> Gets server localized string. </summary>
/// <param name="phrase"> The phrase. </param>
/// <returns> The server localized string. </returns>
public static string GetServerLocalizedString(string phrase)
{
return BaseItem.LocalizationManager.GetLocalizedString(phrase, BaseItem.ConfigurationManager.Configuration.UICulture);
}
/// <summary> Gets row type. </summary>
/// <summary> Gets report view type. </summary>
/// <param name="rowType"> The type. </param>
/// <returns> The row type. </returns>
public static ReportViewType GetRowType(string rowType)
/// <returns> The report view type. </returns>
public static ReportViewType GetReportViewType(string rowType)
{
if (string.IsNullOrEmpty(rowType))
return ReportViewType.BaseItem;
return ReportViewType.ReportData;
ReportViewType rType;
if (!Enum.TryParse<ReportViewType>(rowType, out rType))
return ReportViewType.BaseItem;
return ReportViewType.ReportData;
return rType;
}
/// <summary> Gets header metadata type. </summary>
/// <param name="header"> The header. </param>
/// <returns> The header metadata type. </returns>
public static HeaderMetadata GetHeaderMetadataType(string header)
/// <summary> Gets row type. </summary>
/// <param name="rowType"> The type. </param>
/// <returns> The row type. </returns>
public static ReportIncludeItemTypes GetRowType(string rowType)
{
if (string.IsNullOrEmpty(header))
return HeaderMetadata.None;
if (string.IsNullOrEmpty(rowType))
return ReportIncludeItemTypes.BaseItem;
HeaderMetadata rType;
ReportIncludeItemTypes rType;
if (!Enum.TryParse<HeaderMetadata>(header, out rType))
return HeaderMetadata.None;
if (!Enum.TryParse<ReportIncludeItemTypes>(rowType, out rType))
return ReportIncludeItemTypes.BaseItem;
return rType;
}
/// <summary> Convert field to string. </summary>
/// <typeparam name="T"> Generic type parameter. </typeparam>
/// <param name="value"> The value. </param>
/// <param name="fieldType"> Type of the field. </param>
/// <returns> The field converted to string. </returns>
public static string ConvertToString<T>(T value, ReportFieldType fieldType)
{
if (value == null)
return "";
switch (fieldType)
/// <summary> Gets server localized string. </summary>
/// <param name="phrase"> The phrase. </param>
/// <returns> The server localized string. </returns>
public static string GetServerLocalizedString(string phrase)
{
case ReportFieldType.String:
return value.ToString();
case ReportFieldType.Boolean:
return value.ToString();
case ReportFieldType.Date:
return string.Format("{0:d}", value);
case ReportFieldType.Time:
return string.Format("{0:t}", value);
case ReportFieldType.DateTime:
return string.Format("{0:d}", value);
case ReportFieldType.Minutes:
return string.Format("{0}mn", value);
case ReportFieldType.Int:
return string.Format("", value);
default:
if (value is Guid)
return string.Format("{0:N}", value);
return value.ToString();
}
return BaseItem.LocalizationManager.GetLocalizedString(phrase, BaseItem.ConfigurationManager.Configuration.UICulture);
}
#endregion
}
}

@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace MediaBrowser.Api.Reports
{
public enum ReportIncludeItemTypes
{
MusicArtist,
MusicAlbum,
Book,
BoxSet,
Episode,
Game,
Video,
Movie,
MusicVideo,
Trailer,
Season,
Series,
Audio,
BaseItem,
Artist
}
}

@ -6,20 +6,9 @@ namespace MediaBrowser.Api.Reports
{
public enum ReportViewType
{
MusicArtist,
MusicAlbum,
Book,
BoxSet,
Episode,
Game,
Video,
Movie,
MusicVideo,
Trailer,
Season,
Series,
Audio,
BaseItem,
Artist
ReportData,
ReportStatistics,
ReportActivities
}
}

@ -22,6 +22,8 @@ namespace MediaBrowser.Api.Reports
public class ReportBuilder : ReportBuilderBase
{
#region [Constructors]
/// <summary>
/// Initializes a new instance of the MediaBrowser.Api.Reports.ReportBuilder class. </summary>
/// <param name="libraryManager"> Manager for library. </param>
@ -30,22 +32,31 @@ namespace MediaBrowser.Api.Reports
{
}
private Func<bool, string> GetBoolString = s => s == true ? "x" : "";
#endregion
#region [Public Methods]
public ReportResult GetReportResult(BaseItem[] items, ReportViewType reportRowType, BaseReportRequest request)
/// <summary> Gets report result. </summary>
/// <param name="items"> The items. </param>
/// <param name="request"> The request. </param>
/// <returns> The report result. </returns>
public ReportResult GetResult(BaseItem[] items, IReportsQuery request)
{
List<HeaderMetadata> headersMetadata = this.GetFilteredReportHeaderMetadata(reportRowType, request);
ReportIncludeItemTypes reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
List<ReportOptions<BaseItem>> options = this.GetReportOptions<BaseItem>(request,
() => this.GetDefaultHeaderMetadata(reportRowType),
(hm) => this.GetOption(hm)).Where(x => x.Header.Visible == true).ToList();
var headers = GetReportHeaders(reportRowType, headersMetadata);
var rows = GetReportRows(items, headersMetadata);
var headers = GetHeaders<BaseItem>(options);
var rows = GetReportRows(items, options);
ReportResult result = new ReportResult { Headers = headers };
HeaderMetadata groupBy = ReportHelper.GetHeaderMetadataType(request.GroupBy);
int i = headers.FindIndex(x => x.FieldName == groupBy);
if (groupBy != HeaderMetadata.None && i > 0)
if (groupBy != HeaderMetadata.None && i >= 0)
{
var rowsGroup = rows.SelectMany(x => x.Columns[i].Name.Split(';'), (x, g) => new { Genre = g.Trim(), Rows = x })
.GroupBy(x => x.Genre)
var rowsGroup = rows.SelectMany(x => x.Columns[i].Name.Split(';'), (x, g) => new { Group = g.Trim(), Rows = x })
.GroupBy(x => x.Group)
.OrderBy(x => x.Key)
.Select(x => new ReportGroup { Name = x.Key, Rows = x.Select(r => r.Rows).ToList() });
@ -61,117 +72,33 @@ namespace MediaBrowser.Api.Reports
return result;
}
public List<ReportHeader> GetReportHeaders(ReportViewType reportRowType, BaseReportRequest request)
{
List<ReportHeader> headersMetadata = this.GetReportHeaders(reportRowType);
if (request != null && !string.IsNullOrEmpty(request.ReportColumns))
{
List<HeaderMetadata> headersMetadataFiltered = this.GetFilteredReportHeaderMetadata(reportRowType, request);
foreach (ReportHeader reportHeader in headersMetadata)
{
if (!headersMetadataFiltered.Contains(reportHeader.FieldName))
{
reportHeader.Visible = false;
}
}
#endregion
}
return headersMetadata;
}
public List<ReportHeader> GetReportHeaders(ReportViewType reportRowType, List<HeaderMetadata> headersMetadata = null)
{
if (headersMetadata == null)
headersMetadata = this.GetDefaultReportHeaderMetadata(reportRowType);
List<ReportOptions<BaseItem>> options = new List<ReportOptions<BaseItem>>();
foreach (HeaderMetadata header in headersMetadata)
{
options.Add(GetReportOption(header));
}
#region [Protected Internal Methods]
List<ReportHeader> headers = new List<ReportHeader>();
foreach (ReportOptions<BaseItem> option in options)
{
headers.Add(option.Header);
}
return headers;
}
private List<ReportRow> GetReportRows(IEnumerable<BaseItem> items, List<HeaderMetadata> headersMetadata)
{
List<ReportOptions<BaseItem>> options = new List<ReportOptions<BaseItem>>();
foreach (HeaderMetadata header in headersMetadata)
{
options.Add(GetReportOption(header));
}
var rows = new List<ReportRow>();
foreach (BaseItem item in items)
{
ReportRow rRow = GetRow(item);
foreach (ReportOptions<BaseItem> option in options)
/// <summary> Gets the headers. </summary>
/// <typeparam name="H"> Type of the header. </typeparam>
/// <param name="request"> The request. </param>
/// <returns> The headers. </returns>
/// <seealso cref="M:MediaBrowser.Api.Reports.ReportBuilderBase.GetHeaders{H}(H)"/>
protected internal override List<ReportHeader> GetHeaders<H>(H request)
{
object itemColumn = option.Column != null ? option.Column(item, rRow) : "";
object itemId = option.ItemID != null ? option.ItemID(item) : "";
ReportItem rItem = new ReportItem
{
Name = ReportHelper.ConvertToString(itemColumn, option.Header.HeaderFieldType),
Id = ReportHelper.ConvertToString(itemId, ReportFieldType.Object)
};
rRow.Columns.Add(rItem);
ReportIncludeItemTypes reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
return this.GetHeaders<BaseItem>(request, () => this.GetDefaultHeaderMetadata(reportRowType), (hm) => this.GetOption(hm));
}
rows.Add(rRow);
}
#endregion
return rows;
}
#region [Private Methods]
/// <summary> Gets a row. </summary>
/// <param name="item"> The item. </param>
/// <returns> The row. </returns>
private ReportRow GetRow(BaseItem item)
/// <summary> Gets default report header metadata. </summary>
/// <param name="reportIncludeItemTypes"> Type of the report row. </param>
/// <returns> The default report header metadata. </returns>
private List<HeaderMetadata> GetDefaultHeaderMetadata(ReportIncludeItemTypes reportIncludeItemTypes)
{
var hasTrailers = item as IHasTrailers;
var hasSpecialFeatures = item as IHasSpecialFeatures;
var video = item as Video;
ReportRow rRow = new ReportRow
switch (reportIncludeItemTypes)
{
Id = item.Id.ToString("N"),
HasLockData = item.IsLocked,
IsUnidentified = item.IsUnidentified,
HasLocalTrailer = hasTrailers != null ? hasTrailers.GetTrailerIds().Count() > 0 : false,
HasImageTagsPrimary = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Primary) > 0),
HasImageTagsBackdrop = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Backdrop) > 0),
HasImageTagsLogo = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Logo) > 0),
HasSpecials = hasSpecialFeatures != null ? hasSpecialFeatures.SpecialFeatureIds.Count > 0 : false,
HasSubtitles = video != null ? video.HasSubtitles : false,
RowType = ReportHelper.GetRowType(item.GetClientTypeName())
};
return rRow;
}
public List<HeaderMetadata> GetFilteredReportHeaderMetadata(ReportViewType reportRowType, BaseReportRequest request)
{
if (request != null && !string.IsNullOrEmpty(request.ReportColumns))
{
var s = request.ReportColumns.Split('|').Select(x => ReportHelper.GetHeaderMetadataType(x)).Where(x => x != HeaderMetadata.None);
return s.ToList();
}
else
return this.GetDefaultReportHeaderMetadata(reportRowType);
}
public List<HeaderMetadata> GetDefaultReportHeaderMetadata(ReportViewType reportRowType)
{
switch (reportRowType)
{
case ReportViewType.Season:
case ReportIncludeItemTypes.Season:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -183,7 +110,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Genres
};
case ReportViewType.Series:
case ReportIncludeItemTypes.Series:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -199,7 +126,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Specials
};
case ReportViewType.MusicAlbum:
case ReportIncludeItemTypes.MusicAlbum:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -212,7 +139,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Genres
};
case ReportViewType.MusicArtist:
case ReportIncludeItemTypes.MusicArtist:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -223,7 +150,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Genres
};
case ReportViewType.Game:
case ReportIncludeItemTypes.Game:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -239,7 +166,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Trailers
};
case ReportViewType.Movie:
case ReportIncludeItemTypes.Movie:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -259,7 +186,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Specials
};
case ReportViewType.Book:
case ReportIncludeItemTypes.Book:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -272,7 +199,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.CommunityRating
};
case ReportViewType.BoxSet:
case ReportIncludeItemTypes.BoxSet:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -286,7 +213,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Trailers
};
case ReportViewType.Audio:
case ReportIncludeItemTypes.Audio:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -305,7 +232,7 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Audio
};
case ReportViewType.Episode:
case ReportIncludeItemTypes.Episode:
return new List<HeaderMetadata>
{
HeaderMetadata.StatusImage,
@ -327,10 +254,10 @@ namespace MediaBrowser.Api.Reports
HeaderMetadata.Specials
};
case ReportViewType.Video:
case ReportViewType.MusicVideo:
case ReportViewType.Trailer:
case ReportViewType.BaseItem:
case ReportIncludeItemTypes.Video:
case ReportIncludeItemTypes.MusicVideo:
case ReportIncludeItemTypes.Trailer:
case ReportIncludeItemTypes.BaseItem:
default:
return new List<HeaderMetadata>
{
@ -359,231 +286,274 @@ namespace MediaBrowser.Api.Reports
/// <param name="header"> The header. </param>
/// <param name="sortField"> The sort field. </param>
/// <returns> The report option. </returns>
private ReportOptions<BaseItem> GetReportOption(HeaderMetadata header, string sortField = "")
private ReportOptions<BaseItem> GetOption(HeaderMetadata header, string sortField = "")
{
ReportHeader reportHeader = new ReportHeader
HeaderMetadata internalHeader = header;
ReportOptions<BaseItem> option = new ReportOptions<BaseItem>()
{
Header = new ReportHeader
{
HeaderFieldType = ReportFieldType.String,
SortField = sortField,
Type = "",
ItemViewType = ItemViewType.None
}
};
Func<BaseItem, ReportRow, object> column = null;
Func<BaseItem, object> itemId = null;
HeaderMetadata internalHeader = header;
switch (header)
{
case HeaderMetadata.StatusImage:
reportHeader.ItemViewType = ItemViewType.StatusImage;
option.Header.ItemViewType = ItemViewType.StatusImage;
internalHeader = HeaderMetadata.Status;
reportHeader.CanGroup = false;
option.Header.CanGroup = false;
break;
case HeaderMetadata.Name:
column = (i, r) => i.Name;
reportHeader.ItemViewType = ItemViewType.Detail;
reportHeader.SortField = "SortName";
option.Column = (i, r) => i.Name;
option.Header.ItemViewType = ItemViewType.Detail;
option.Header.SortField = "SortName";
break;
case HeaderMetadata.DateAdded:
column = (i, r) => i.DateCreated;
reportHeader.SortField = "DateCreated,SortName";
reportHeader.HeaderFieldType = ReportFieldType.DateTime;
reportHeader.Type = "";
option.Column = (i, r) => i.DateCreated;
option.Header.SortField = "DateCreated,SortName";
option.Header.HeaderFieldType = ReportFieldType.DateTime;
option.Header.Type = "";
break;
case HeaderMetadata.PremiereDate:
case HeaderMetadata.ReleaseDate:
column = (i, r) => i.PremiereDate;
reportHeader.HeaderFieldType = ReportFieldType.DateTime;
reportHeader.SortField = "ProductionYear,PremiereDate,SortName";
option.Column = (i, r) => i.PremiereDate;
option.Header.HeaderFieldType = ReportFieldType.DateTime;
option.Header.SortField = "ProductionYear,PremiereDate,SortName";
break;
case HeaderMetadata.Runtime:
column = (i, r) => this.GetRuntimeDateTime(i.RunTimeTicks);
reportHeader.HeaderFieldType = ReportFieldType.Minutes;
reportHeader.SortField = "Runtime,SortName";
option.Column = (i, r) => this.GetRuntimeDateTime(i.RunTimeTicks);
option.Header.HeaderFieldType = ReportFieldType.Minutes;
option.Header.SortField = "Runtime,SortName";
break;
case HeaderMetadata.PlayCount:
reportHeader.HeaderFieldType = ReportFieldType.Int;
option.Header.HeaderFieldType = ReportFieldType.Int;
break;
case HeaderMetadata.Season:
column = (i, r) => this.GetEpisode(i);
reportHeader.ItemViewType = ItemViewType.Detail;
reportHeader.SortField = "SortName";
option.Column = (i, r) => this.GetEpisode(i);
option.Header.ItemViewType = ItemViewType.Detail;
option.Header.SortField = "SortName";
break;
case HeaderMetadata.SeasonNumber:
column = (i, r) => this.GetObject<Season, string>(i, (x) => x.IndexNumber == null ? "" : x.IndexNumber.ToString());
reportHeader.SortField = "IndexNumber";
reportHeader.HeaderFieldType = ReportFieldType.Int;
option.Column = (i, r) => this.GetObject<Season, string>(i, (x) => x.IndexNumber == null ? "" : x.IndexNumber.ToString());
option.Header.SortField = "IndexNumber";
option.Header.HeaderFieldType = ReportFieldType.Int;
break;
case HeaderMetadata.Series:
column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
reportHeader.ItemViewType = ItemViewType.Detail;
reportHeader.SortField = "SeriesSortName,SortName";
option.Column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
option.Header.ItemViewType = ItemViewType.Detail;
option.Header.SortField = "SeriesSortName,SortName";
break;
case HeaderMetadata.EpisodeSeries:
column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
reportHeader.ItemViewType = ItemViewType.Detail;
itemId = (i) =>
option.Column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
option.Header.ItemViewType = ItemViewType.Detail;
option.ItemID = (i) =>
{
Series series = this.GetObject<Episode, Series>(i, (x) => x.Series);
if (series == null)
return string.Empty;
return series.Id;
};
reportHeader.SortField = "SeriesSortName,SortName";
option.Header.SortField = "SeriesSortName,SortName";
internalHeader = HeaderMetadata.Series;
break;
case HeaderMetadata.EpisodeSeason:
column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
reportHeader.ItemViewType = ItemViewType.Detail;
itemId = (i) =>
option.Column = (i, r) => this.GetObject<IHasSeries, string>(i, (x) => x.SeriesName);
option.Header.ItemViewType = ItemViewType.Detail;
option.ItemID = (i) =>
{
Season season = this.GetObject<Episode, Season>(i, (x) => x.Season);
if (season == null)
return string.Empty;
return season.Id;
};
reportHeader.SortField = "SortName";
option.Header.SortField = "SortName";
internalHeader = HeaderMetadata.Season;
break;
case HeaderMetadata.Network:
column = (i, r) => this.GetListAsString(i.Studios);
itemId = (i) => this.GetStudioID(i.Studios.FirstOrDefault());
reportHeader.ItemViewType = ItemViewType.ItemByNameDetails;
reportHeader.SortField = "Studio,SortName";
option.Column = (i, r) => this.GetListAsString(i.Studios);
option.ItemID = (i) => this.GetStudioID(i.Studios.FirstOrDefault());
option.Header.ItemViewType = ItemViewType.ItemByNameDetails;
option.Header.SortField = "Studio,SortName";
break;
case HeaderMetadata.Year:
column = (i, r) => this.GetSeriesProductionYear(i);
reportHeader.SortField = "ProductionYear,PremiereDate,SortName";
option.Column = (i, r) => this.GetSeriesProductionYear(i);
option.Header.SortField = "ProductionYear,PremiereDate,SortName";
break;
case HeaderMetadata.ParentalRating:
column = (i, r) => i.OfficialRating;
reportHeader.SortField = "OfficialRating,SortName";
option.Column = (i, r) => i.OfficialRating;
option.Header.SortField = "OfficialRating,SortName";
break;
case HeaderMetadata.CommunityRating:
column = (i, r) => i.CommunityRating;
reportHeader.SortField = "CommunityRating,SortName";
option.Column = (i, r) => i.CommunityRating;
option.Header.SortField = "CommunityRating,SortName";
break;
case HeaderMetadata.Trailers:
column = (i, r) => this.GetBoolString(r.HasLocalTrailer);
reportHeader.ItemViewType = ItemViewType.TrailersImage;
option.Column = (i, r) => this.GetBoolString(r.HasLocalTrailer);
option.Header.ItemViewType = ItemViewType.TrailersImage;
break;
case HeaderMetadata.Specials:
column = (i, r) => this.GetBoolString(r.HasSpecials);
reportHeader.ItemViewType = ItemViewType.SpecialsImage;
option.Column = (i, r) => this.GetBoolString(r.HasSpecials);
option.Header.ItemViewType = ItemViewType.SpecialsImage;
break;
case HeaderMetadata.GameSystem:
column = (i, r) => this.GetObject<Game, string>(i, (x) => x.GameSystem);
reportHeader.SortField = "GameSystem,SortName";
option.Column = (i, r) => this.GetObject<Game, string>(i, (x) => x.GameSystem);
option.Header.SortField = "GameSystem,SortName";
break;
case HeaderMetadata.Players:
column = (i, r) => this.GetObject<Game, int?>(i, (x) => x.PlayersSupported);
reportHeader.SortField = "Players,GameSystem,SortName";
option.Column = (i, r) => this.GetObject<Game, int?>(i, (x) => x.PlayersSupported);
option.Header.SortField = "Players,GameSystem,SortName";
break;
case HeaderMetadata.AlbumArtist:
column = (i, r) => this.GetObject<MusicAlbum, string>(i, (x) => x.AlbumArtist);
itemId = (i) => this.GetPersonID(this.GetObject<MusicAlbum, string>(i, (x) => x.AlbumArtist));
reportHeader.ItemViewType = ItemViewType.Detail;
reportHeader.SortField = "AlbumArtist,Album,SortName";
option.Column = (i, r) => this.GetObject<MusicAlbum, string>(i, (x) => x.AlbumArtist);
option.ItemID = (i) => this.GetPersonID(this.GetObject<MusicAlbum, string>(i, (x) => x.AlbumArtist));
option.Header.ItemViewType = ItemViewType.Detail;
option.Header.SortField = "AlbumArtist,Album,SortName";
break;
case HeaderMetadata.MusicArtist:
column = (i, r) => this.GetObject<MusicArtist, string>(i, (x) => x.GetLookupInfo().Name);
reportHeader.ItemViewType = ItemViewType.Detail;
reportHeader.SortField = "AlbumArtist,Album,SortName";
option.Column = (i, r) => this.GetObject<MusicArtist, string>(i, (x) => x.GetLookupInfo().Name);
option.Header.ItemViewType = ItemViewType.Detail;
option.Header.SortField = "AlbumArtist,Album,SortName";
internalHeader = HeaderMetadata.AlbumArtist;
break;
case HeaderMetadata.AudioAlbumArtist:
column = (i, r) => this.GetListAsString(this.GetObject<Audio, List<string>>(i, (x) => x.AlbumArtists));
reportHeader.SortField = "AlbumArtist,Album,SortName";
option.Column = (i, r) => this.GetListAsString(this.GetObject<Audio, List<string>>(i, (x) => x.AlbumArtists));
option.Header.SortField = "AlbumArtist,Album,SortName";
internalHeader = HeaderMetadata.AlbumArtist;
break;
case HeaderMetadata.AudioAlbum:
column = (i, r) => this.GetObject<Audio, string>(i, (x) => x.Album);
reportHeader.SortField = "Album,SortName";
option.Column = (i, r) => this.GetObject<Audio, string>(i, (x) => x.Album);
option.Header.SortField = "Album,SortName";
internalHeader = HeaderMetadata.Album;
break;
case HeaderMetadata.Countries:
column = (i, r) => this.GetListAsString(this.GetObject<IHasProductionLocations, List<string>>(i, (x) => x.ProductionLocations));
option.Column = (i, r) => this.GetListAsString(this.GetObject<IHasProductionLocations, List<string>>(i, (x) => x.ProductionLocations));
break;
case HeaderMetadata.Disc:
column = (i, r) => i.ParentIndexNumber;
option.Column = (i, r) => i.ParentIndexNumber;
break;
case HeaderMetadata.Track:
column = (i, r) => i.IndexNumber;
option.Column = (i, r) => i.IndexNumber;
break;
case HeaderMetadata.Tracks:
column = (i, r) => this.GetObject<MusicAlbum, List<Audio>>(i, (x) => x.Tracks.ToList(), new List<Audio>()).Count();
option.Column = (i, r) => this.GetObject<MusicAlbum, List<Audio>>(i, (x) => x.Tracks.ToList(), new List<Audio>()).Count();
break;
case HeaderMetadata.Audio:
column = (i, r) => this.GetAudioStream(i);
option.Column = (i, r) => this.GetAudioStream(i);
break;
case HeaderMetadata.EmbeddedImage:
break;
case HeaderMetadata.Video:
column = (i, r) => this.GetVideoStream(i);
option.Column = (i, r) => this.GetVideoStream(i);
break;
case HeaderMetadata.Resolution:
column = (i, r) => this.GetVideoResolution(i);
option.Column = (i, r) => this.GetVideoResolution(i);
break;
case HeaderMetadata.Subtitles:
column = (i, r) => this.GetBoolString(r.HasSubtitles);
reportHeader.ItemViewType = ItemViewType.SubtitleImage;
option.Column = (i, r) => this.GetBoolString(r.HasSubtitles);
option.Header.ItemViewType = ItemViewType.SubtitleImage;
break;
case HeaderMetadata.Genres:
column = (i, r) => this.GetListAsString(i.Genres);
option.Column = (i, r) => this.GetListAsString(i.Genres);
break;
}
string headerName = "";
if (internalHeader != HeaderMetadata.None)
option.Header.Name = GetLocalizedHeader(internalHeader);
option.Header.FieldName = header;
return option;
}
/// <summary> Gets report rows. </summary>
/// <param name="items"> The items. </param>
/// <param name="options"> Options for controlling the operation. </param>
/// <returns> The report rows. </returns>
private List<ReportRow> GetReportRows(IEnumerable<BaseItem> items, List<ReportOptions<BaseItem>> options)
{
var rows = new List<ReportRow>();
foreach (BaseItem item in items)
{
ReportRow rRow = GetRow(item);
foreach (ReportOptions<BaseItem> option in options)
{
object itemColumn = option.Column != null ? option.Column(item, rRow) : "";
object itemId = option.ItemID != null ? option.ItemID(item) : "";
ReportItem rItem = new ReportItem
{
string localHeader = "Header" + internalHeader.ToString();
headerName = internalHeader != HeaderMetadata.None ? ReportHelper.GetJavaScriptLocalizedString(localHeader) : "";
if (string.Compare(localHeader, headerName, StringComparison.CurrentCultureIgnoreCase) == 0)
headerName = ReportHelper.GetServerLocalizedString(localHeader);
Name = ReportHelper.ConvertToString(itemColumn, option.Header.HeaderFieldType),
Id = ReportHelper.ConvertToString(itemId, ReportFieldType.Object)
};
rRow.Columns.Add(rItem);
}
reportHeader.Name = headerName;
reportHeader.FieldName = header;
ReportOptions<BaseItem> option = new ReportOptions<BaseItem>()
rows.Add(rRow);
}
return rows;
}
/// <summary> Gets a row. </summary>
/// <param name="item"> The item. </param>
/// <returns> The row. </returns>
private ReportRow GetRow(BaseItem item)
{
var hasTrailers = item as IHasTrailers;
var hasSpecialFeatures = item as IHasSpecialFeatures;
var video = item as Video;
ReportRow rRow = new ReportRow
{
Header = reportHeader,
Column = column,
ItemID = itemId
Id = item.Id.ToString("N"),
HasLockData = item.IsLocked,
IsUnidentified = item.IsUnidentified,
HasLocalTrailer = hasTrailers != null ? hasTrailers.GetTrailerIds().Count() > 0 : false,
HasImageTagsPrimary = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Primary) > 0),
HasImageTagsBackdrop = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Backdrop) > 0),
HasImageTagsLogo = (item.ImageInfos != null && item.ImageInfos.Count(n => n.Type == ImageType.Logo) > 0),
HasSpecials = hasSpecialFeatures != null ? hasSpecialFeatures.SpecialFeatureIds.Count > 0 : false,
HasSubtitles = video != null ? video.HasSubtitles : false,
RowType = ReportHelper.GetRowType(item.GetClientTypeName())
};
return option;
return rRow;
}
#endregion
}
}

@ -7,8 +7,9 @@ using System.Threading.Tasks;
namespace MediaBrowser.Api.Reports
{
/// <summary> A report options. </summary>
internal class ReportOptions<I>
public class ReportOptions<I>
{
/// <summary> Initializes a new instance of the ReportOptions class. </summary>
public ReportOptions()

@ -66,6 +66,6 @@ namespace MediaBrowser.Api.Reports
/// <summary> Gets or sets the type. </summary>
/// <value> The type. </value>
public ReportViewType RowType { get; set; }
public ReportIncludeItemTypes RowType { get; set; }
}
}

@ -7,8 +7,80 @@ using System.Linq;
namespace MediaBrowser.Api.Reports
{
public class BaseReportRequest : BaseItemsRequest
public interface IReportsDownload : IReportsQuery
{
/// <summary> Gets or sets the minimum date. </summary>
/// <value> The minimum date. </value>
string MinDate { get; set; }
}
/// <summary> Interface for reports query. </summary>
public interface IReportsQuery : IReportsHeader
{
/// <summary>
/// Gets or sets a value indicating whether this MediaBrowser.Api.Reports.GetActivityLogs has
/// query limit. </summary>
/// <value>
/// true if this MediaBrowser.Api.Reports.GetActivityLogs has query limit, false if not. </value>
bool HasQueryLimit { get; set; }
/// <summary> Gets or sets who group this MediaBrowser.Api.Reports.GetActivityLogs. </summary>
/// <value> Describes who group this MediaBrowser.Api.Reports.GetActivityLogs. </value>
string GroupBy { get; set; }
/// <summary>
/// Skips over a given number of items within the results. Use for paging.
/// </summary>
/// <value>The start index.</value>
int? StartIndex { get; set; }
/// <summary>
/// The maximum number of items to return
/// </summary>
/// <value>The limit.</value>
int? Limit { get; set; }
}
public interface IReportsHeader
{
/// <summary> Gets or sets the report view. </summary>
/// <value> The report view. </value>
string ReportView { get; set; }
/// <summary> Gets or sets the report columns. </summary>
/// <value> The report columns. </value>
string ReportColumns { get; set; }
/// <summary> Gets or sets a list of types of the include items. </summary>
/// <value> A list of types of the include items. </value>
string IncludeItemTypes { get; set; }
}
public class BaseReportRequest : BaseItemsRequest, IReportsQuery
{
/// <summary> Gets or sets the report view. </summary>
/// <value> The report view. </value>
[ApiMember(Name = "ReportView", Description = "The report view. Values (ReportData, ReportStatistics, ReportActivities)", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportView { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this MediaBrowser.Api.Reports.BaseReportRequest has
/// query limit. </summary>
/// <value>
/// true if this MediaBrowser.Api.Reports.BaseReportRequest has query limit, false if not. </value>
[ApiMember(Name = "HasQueryLimit", Description = "Optional. If specified, results will include all records.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool HasQueryLimit { get; set; }
/// <summary>
/// Gets or sets who group this MediaBrowser.Api.Reports.BaseReportRequest. </summary>
/// <value> Describes who group this MediaBrowser.Api.Reports.BaseReportRequest. </value>
[ApiMember(Name = "GroupBy", Description = "Optional. If specified, results will include grouped records.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string GroupBy { get; set; }
/// <summary> Gets or sets the report columns. </summary>
/// <value> The report columns. </value>
[ApiMember(Name = "ReportColumns", Description = "Optional. The columns to show.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportColumns { get; set; }
/// <summary>
/// Gets or sets the user id.
/// </summary>
@ -63,11 +135,6 @@ namespace MediaBrowser.Api.Reports
[ApiMember(Name = "Ids", Description = "Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string Ids { get; set; }
public bool HasQueryLimit { get; set; }
public string GroupBy { get; set; }
public string ReportColumns { get; set; }
/// <summary>
/// Gets or sets the video types.
/// </summary>
@ -261,8 +328,22 @@ namespace MediaBrowser.Api.Reports
}
[Route("/Reports/Headers", "GET", Summary = "Gets reports headers based on library items")]
public class GetReportHeaders : BaseReportRequest, IReturn<List<ReportHeader>>
public class GetReportHeaders : IReturn<List<ReportHeader>>, IReportsHeader
{
/// <summary> Gets or sets the report view. </summary>
/// <value> The report view. </value>
[ApiMember(Name = "ReportView", Description = "The report view. Values (ReportData, ReportStatistics, ReportActivities)", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportView { get; set; }
/// <summary> Gets or sets a list of types of the include items. </summary>
/// <value> A list of types of the include items. </value>
[ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string IncludeItemTypes { get; set; }
/// <summary> Gets or sets the report columns. </summary>
/// <value> The report columns. </value>
[ApiMember(Name = "ReportColumns", Description = "Optional. The columns to show.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportColumns { get; set; }
}
[Route("/Reports/Statistics", "GET", Summary = "Gets reports statistics based on library items")]
@ -273,7 +354,7 @@ namespace MediaBrowser.Api.Reports
}
[Route("/Reports/Items/Download", "GET", Summary = "Downloads report")]
public class GetReportDownload : BaseReportRequest
public class GetReportDownload : BaseReportRequest, IReportsDownload
{
public GetReportDownload()
{
@ -281,6 +362,61 @@ namespace MediaBrowser.Api.Reports
}
public ReportExportType ExportType { get; set; }
/// <summary> Gets or sets the minimum date. </summary>
/// <value> The minimum date. </value>
[ApiMember(Name = "MinDate", Description = "Optional. The minimum date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string MinDate { get; set; }
}
[Route("/Reports/Activities", "GET", Summary = "Gets activities entries")]
public class GetActivityLogs : IReturn<ReportResult>, IReportsQuery, IReportsDownload
{
/// <summary> Gets or sets the report view. </summary>
/// <value> The report view. </value>
[ApiMember(Name = "ReportView", Description = "The report view. Values (ReportData, ReportStatistics, ReportActivities)", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportView { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this MediaBrowser.Api.Reports.GetActivityLogs has
/// query limit. </summary>
/// <value>
/// true if this MediaBrowser.Api.Reports.GetActivityLogs has query limit, false if not. </value>
[ApiMember(Name = "HasQueryLimit", Description = "Optional. If specified, results will include all records.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
public bool HasQueryLimit { get; set; }
/// <summary> Gets or sets who group this MediaBrowser.Api.Reports.GetActivityLogs. </summary>
/// <value> Describes who group this MediaBrowser.Api.Reports.GetActivityLogs. </value>
[ApiMember(Name = "GroupBy", Description = "Optional. If specified, results will include grouped records.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string GroupBy { get; set; }
/// <summary> Gets or sets the report columns. </summary>
/// <value> The report columns. </value>
[ApiMember(Name = "ReportColumns", Description = "Optional. The columns to show.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public string ReportColumns { get; set; }
/// <summary>
/// Skips over a given number of items within the results. Use for paging.
/// </summary>
/// <value>The start index.</value>
[ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? StartIndex { get; set; }
/// <summary>
/// The maximum number of items to return
/// </summary>
/// <value>The limit.</value>
[ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? Limit { get; set; }
/// <summary> Gets or sets the minimum date. </summary>
/// <value> The minimum date. </value>
[ApiMember(Name = "MinDate", Description = "Optional. The minimum date. Format = ISO", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "POST")]
public string MinDate { get; set; }
[ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
public string IncludeItemTypes { get; set; }
}
}

@ -28,26 +28,51 @@ namespace MediaBrowser.Api.Reports
/// <seealso cref="T:MediaBrowser.Api.BaseApiService"/>
public class ReportsService : BaseApiService
{
/// <summary> Manager for user. </summary>
private readonly IUserManager _userManager;
/// <summary> Manager for library. </summary>
private readonly ILibraryManager _libraryManager;
/// <summary> The localization. </summary>
private readonly ILocalizationManager _localization;
#region [Constructors]
/// <summary>
/// Initializes a new instance of the MediaBrowser.Api.Reports.ReportsService class. </summary>
/// <param name="userManager"> Manager for user. </param>
/// <param name="libraryManager"> Manager for library. </param>
/// <param name="localization"> The localization. </param>
public ReportsService(IUserManager userManager, ILibraryManager libraryManager, ILocalizationManager localization)
/// <param name="activityManager"> Manager for activity. </param>
public ReportsService(IUserManager userManager, ILibraryManager libraryManager, ILocalizationManager localization, IActivityManager activityManager, IActivityRepository repo)
{
_userManager = userManager;
_libraryManager = libraryManager;
_localization = localization;
_activityManager = activityManager;
_repo = repo;
}
#endregion
#region [Private Fields]
private readonly IActivityManager _activityManager; ///< Manager for activity
/// <summary> Manager for library. </summary>
private readonly ILibraryManager _libraryManager; ///< Manager for library
/// <summary> The localization. </summary>
private readonly ILocalizationManager _localization; ///< The localization
private readonly IActivityRepository _repo;
/// <summary> Manager for user. </summary>
private readonly IUserManager _userManager; ///< Manager for user
#endregion
#region [Public Methods]
/// <summary> Gets the given request. </summary>
/// <param name="request"> The request. </param>
/// <returns> A Task&lt;object&gt; </returns>
public async Task<object> Get(GetActivityLogs request)
{
ReportResult result = await GetReportActivities(request).ConfigureAwait(false);
return ToOptimizedResult(result);
}
/// <summary> Gets the given request. </summary>
@ -58,11 +83,25 @@ namespace MediaBrowser.Api.Reports
if (string.IsNullOrEmpty(request.IncludeItemTypes))
return null;
ReportViewType reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
ReportBuilder reportBuilder = new ReportBuilder(_libraryManager);
var reportResult = reportBuilder.GetReportHeaders(reportRowType, request);
ReportViewType reportViewType = ReportHelper.GetReportViewType(request.ReportView);
ReportIncludeItemTypes reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
return ToOptimizedResult(reportResult);
List<ReportHeader> result = new List<ReportHeader>();
switch (reportViewType)
{
case ReportViewType.ReportData:
ReportBuilder dataBuilder = new ReportBuilder(_libraryManager);
result = dataBuilder.GetHeaders(request);
break;
case ReportViewType.ReportStatistics:
break;
case ReportViewType.ReportActivities:
ReportActivitiesBuilder activityBuilder = new ReportActivitiesBuilder(_libraryManager, _userManager);
result = activityBuilder.GetHeaders(request);
break;
}
return ToOptimizedResult(result);
}
@ -79,6 +118,18 @@ namespace MediaBrowser.Api.Reports
return ToOptimizedResult(reportResult);
}
/// <summary> Gets the given request. </summary>
/// <param name="request"> The request. </param>
/// <returns> A Task&lt;object&gt; </returns>
public async Task<object> Get(GetReportStatistics request)
{
if (string.IsNullOrEmpty(request.IncludeItemTypes))
return null;
var reportResult = await GetReportStatistic(request);
return ToOptimizedResult(reportResult);
}
/// <summary> Gets the given request. </summary>
/// <param name="request"> The request. </param>
/// <returns> A Task&lt;object&gt; </returns>
@ -87,6 +138,7 @@ namespace MediaBrowser.Api.Reports
if (string.IsNullOrEmpty(request.IncludeItemTypes))
return null;
ReportViewType reportViewType = ReportHelper.GetReportViewType(request.ReportView);
var headers = new Dictionary<string, string>();
string fileExtension = "csv";
string contentType = "text/plain;charset='utf-8'";
@ -105,221 +157,40 @@ namespace MediaBrowser.Api.Reports
headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", filename);
headers["Content-Encoding"] = "UTF-8";
ReportViewType reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
ReportBuilder reportBuilder = new ReportBuilder(_libraryManager);
ReportResult result = null;
switch (reportViewType)
{
case ReportViewType.ReportStatistics:
case ReportViewType.ReportData:
ReportIncludeItemTypes reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
ReportBuilder dataBuilder = new ReportBuilder(_libraryManager);
QueryResult<BaseItem> queryResult = await GetQueryResult(request).ConfigureAwait(false);
ReportResult reportResult = reportBuilder.GetReportResult(queryResult.Items, reportRowType, request);
reportResult.TotalRecordCount = queryResult.TotalRecordCount;
result = dataBuilder.GetResult(queryResult.Items, request);
result.TotalRecordCount = queryResult.TotalRecordCount;
break;
case ReportViewType.ReportActivities:
result = await GetReportActivities(request).ConfigureAwait(false);
break;
}
string result = string.Empty;
string returnResult = string.Empty;
switch (request.ExportType)
{
case ReportExportType.CSV:
result = new ReportExport().ExportToCsv(reportResult);
returnResult = new ReportExport().ExportToCsv(result);
break;
case ReportExportType.Excel:
result = new ReportExport().ExportToExcel(reportResult);
returnResult = new ReportExport().ExportToExcel(result);
break;
}
object ro = ResultFactory.GetResult(result, contentType, headers);
object ro = ResultFactory.GetResult(returnResult, contentType, headers);
return ro;
}
/// <summary> Gets the given request. </summary>
/// <param name="request"> The request. </param>
/// <returns> A Task&lt;object&gt; </returns>
public async Task<object> Get(GetReportStatistics request)
{
if (string.IsNullOrEmpty(request.IncludeItemTypes))
return null;
var reportResult = await GetReportStatistic(request);
return ToOptimizedResult(reportResult);
}
/// <summary> Gets report statistic. </summary>
/// <param name="request"> The request. </param>
/// <returns> The report statistic. </returns>
private async Task<ReportStatResult> GetReportStatistic(GetReportStatistics request)
{
ReportViewType reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
QueryResult<BaseItem> queryResult = await GetQueryResult(request).ConfigureAwait(false);
ReportStatBuilder reportBuilder = new ReportStatBuilder(_libraryManager);
ReportStatResult reportResult = reportBuilder.GetReportStatResult(queryResult.Items, ReportHelper.GetRowType(request.IncludeItemTypes), request.TopItems ?? 5);
reportResult.TotalRecordCount = reportResult.Groups.Count();
return reportResult;
}
/// <summary> Gets report result. </summary>
/// <param name="request"> The request. </param>
/// <returns> The report result. </returns>
private async Task<ReportResult> GetReportResult(GetItemReport request)
{
ReportViewType reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
ReportBuilder reportBuilder = new ReportBuilder(_libraryManager);
QueryResult<BaseItem> queryResult = await GetQueryResult(request).ConfigureAwait(false);
ReportResult reportResult = reportBuilder.GetReportResult(queryResult.Items, reportRowType, request);
reportResult.TotalRecordCount = queryResult.TotalRecordCount;
return reportResult;
}
/// <summary> Gets query result. </summary>
/// <param name="request"> The request. </param>
/// <returns> The query result. </returns>
private async Task<QueryResult<BaseItem>> GetQueryResult(BaseReportRequest request)
{
// Placeholder in case needed later
request.Recursive = true;
var user = !string.IsNullOrWhiteSpace(request.UserId) ? _userManager.GetUserById(request.UserId) : null;
request.Fields = "MediaSources,DateCreated,Settings,Studios,SyncInfo,ItemCounts";
#endregion
var parentItem = string.IsNullOrEmpty(request.ParentId) ?
(user == null ? _libraryManager.RootFolder : user.RootFolder) :
_libraryManager.GetItemById(request.ParentId);
var item = string.IsNullOrEmpty(request.ParentId) ?
user == null ? _libraryManager.RootFolder : user.RootFolder :
parentItem;
IEnumerable<BaseItem> items;
if (request.Recursive)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false);
return result;
}
else
{
if (user == null)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, null)).ConfigureAwait(false);
return result;
}
var userRoot = item as UserRootFolder;
if (userRoot == null)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false);
return result;
}
items = ((Folder)item).GetChildren(user, true);
}
return new QueryResult<BaseItem> { Items = items.ToArray() };
}
/// <summary> Gets items query. </summary>
/// <param name="request"> The request. </param>
/// <param name="user"> The user. </param>
/// <returns> The items query. </returns>
private InternalItemsQuery GetItemsQuery(BaseReportRequest request, User user)
{
var query = new InternalItemsQuery
{
User = user,
IsPlayed = request.IsPlayed,
MediaTypes = request.GetMediaTypes(),
IncludeItemTypes = request.GetIncludeItemTypes(),
ExcludeItemTypes = request.GetExcludeItemTypes(),
Recursive = true,
SortBy = request.GetOrderBy(),
SortOrder = request.SortOrder ?? SortOrder.Ascending,
Filter = i => ApplyAdditionalFilters(request, i, user, true, _libraryManager),
StartIndex = request.StartIndex,
IsMissing = request.IsMissing,
IsVirtualUnaired = request.IsVirtualUnaired,
IsUnaired = request.IsUnaired,
CollapseBoxSetItems = request.CollapseBoxSetItems,
NameLessThan = request.NameLessThan,
NameStartsWith = request.NameStartsWith,
NameStartsWithOrGreater = request.NameStartsWithOrGreater,
HasImdbId = request.HasImdbId,
IsYearMismatched = request.IsYearMismatched,
IsUnidentified = request.IsUnidentified,
IsPlaceHolder = request.IsPlaceHolder,
IsLocked = request.IsLocked,
IsInBoxSet = request.IsInBoxSet,
IsHD = request.IsHD,
Is3D = request.Is3D,
HasTvdbId = request.HasTvdbId,
HasTmdbId = request.HasTmdbId,
HasOverview = request.HasOverview,
HasOfficialRating = request.HasOfficialRating,
HasParentalRating = request.HasParentalRating,
HasSpecialFeature = request.HasSpecialFeature,
HasSubtitles = request.HasSubtitles,
HasThemeSong = request.HasThemeSong,
HasThemeVideo = request.HasThemeVideo,
HasTrailer = request.HasTrailer,
Tags = request.GetTags(),
OfficialRatings = request.GetOfficialRatings(),
Genres = request.GetGenres(),
Studios = request.GetStudios(),
StudioIds = request.GetStudioIds(),
Person = request.Person,
PersonIds = request.GetPersonIds(),
PersonTypes = request.GetPersonTypes(),
Years = request.GetYears(),
ImageTypes = request.GetImageTypes().ToArray(),
VideoTypes = request.GetVideoTypes().ToArray(),
AdjacentTo = request.AdjacentTo
};
if (!string.IsNullOrWhiteSpace(request.Ids))
{
query.CollapseBoxSetItems = false;
}
foreach (var filter in request.GetFilters())
{
switch (filter)
{
case ItemFilter.Dislikes:
query.IsLiked = false;
break;
case ItemFilter.IsFavorite:
query.IsFavorite = true;
break;
case ItemFilter.IsFavoriteOrLikes:
query.IsFavoriteOrLiked = true;
break;
case ItemFilter.IsFolder:
query.IsFolder = true;
break;
case ItemFilter.IsNotFolder:
query.IsFolder = false;
break;
case ItemFilter.IsPlayed:
query.IsPlayed = true;
break;
case ItemFilter.IsRecentlyAdded:
break;
case ItemFilter.IsResumable:
query.IsResumable = true;
break;
case ItemFilter.IsUnplayed:
query.IsPlayed = false;
break;
case ItemFilter.Likes:
query.IsLiked = true;
break;
}
}
if (request.HasQueryLimit)
query.Limit = request.Limit;
return query;
}
#region [Internal Methods]
/// <summary> Applies filtering. </summary>
/// <param name="items"> The items. </param>
@ -401,6 +272,10 @@ namespace MediaBrowser.Api.Reports
return items;
}
#endregion
#region [Private Methods]
/// <summary> Applies the additional filters. </summary>
/// <param name="request"> The request. </param>
/// <param name="i"> Zero-based index of the. </param>
@ -1159,5 +1034,209 @@ namespace MediaBrowser.Api.Reports
return items;
}
/// <summary> Gets items query. </summary>
/// <param name="request"> The request. </param>
/// <param name="user"> The user. </param>
/// <returns> The items query. </returns>
private InternalItemsQuery GetItemsQuery(BaseReportRequest request, User user)
{
var query = new InternalItemsQuery
{
User = user,
IsPlayed = request.IsPlayed,
MediaTypes = request.GetMediaTypes(),
IncludeItemTypes = request.GetIncludeItemTypes(),
ExcludeItemTypes = request.GetExcludeItemTypes(),
Recursive = true,
SortBy = request.GetOrderBy(),
SortOrder = request.SortOrder ?? SortOrder.Ascending,
Filter = i => ApplyAdditionalFilters(request, i, user, true, _libraryManager),
StartIndex = request.StartIndex,
IsMissing = request.IsMissing,
IsVirtualUnaired = request.IsVirtualUnaired,
IsUnaired = request.IsUnaired,
CollapseBoxSetItems = request.CollapseBoxSetItems,
NameLessThan = request.NameLessThan,
NameStartsWith = request.NameStartsWith,
NameStartsWithOrGreater = request.NameStartsWithOrGreater,
HasImdbId = request.HasImdbId,
IsYearMismatched = request.IsYearMismatched,
IsUnidentified = request.IsUnidentified,
IsPlaceHolder = request.IsPlaceHolder,
IsLocked = request.IsLocked,
IsInBoxSet = request.IsInBoxSet,
IsHD = request.IsHD,
Is3D = request.Is3D,
HasTvdbId = request.HasTvdbId,
HasTmdbId = request.HasTmdbId,
HasOverview = request.HasOverview,
HasOfficialRating = request.HasOfficialRating,
HasParentalRating = request.HasParentalRating,
HasSpecialFeature = request.HasSpecialFeature,
HasSubtitles = request.HasSubtitles,
HasThemeSong = request.HasThemeSong,
HasThemeVideo = request.HasThemeVideo,
HasTrailer = request.HasTrailer,
Tags = request.GetTags(),
OfficialRatings = request.GetOfficialRatings(),
Genres = request.GetGenres(),
Studios = request.GetStudios(),
StudioIds = request.GetStudioIds(),
Person = request.Person,
PersonIds = request.GetPersonIds(),
PersonTypes = request.GetPersonTypes(),
Years = request.GetYears(),
ImageTypes = request.GetImageTypes().ToArray(),
VideoTypes = request.GetVideoTypes().ToArray(),
AdjacentTo = request.AdjacentTo
};
if (!string.IsNullOrWhiteSpace(request.Ids))
{
query.CollapseBoxSetItems = false;
}
foreach (var filter in request.GetFilters())
{
switch (filter)
{
case ItemFilter.Dislikes:
query.IsLiked = false;
break;
case ItemFilter.IsFavorite:
query.IsFavorite = true;
break;
case ItemFilter.IsFavoriteOrLikes:
query.IsFavoriteOrLiked = true;
break;
case ItemFilter.IsFolder:
query.IsFolder = true;
break;
case ItemFilter.IsNotFolder:
query.IsFolder = false;
break;
case ItemFilter.IsPlayed:
query.IsPlayed = true;
break;
case ItemFilter.IsRecentlyAdded:
break;
case ItemFilter.IsResumable:
query.IsResumable = true;
break;
case ItemFilter.IsUnplayed:
query.IsPlayed = false;
break;
case ItemFilter.Likes:
query.IsLiked = true;
break;
}
}
if (request.HasQueryLimit)
query.Limit = request.Limit;
return query;
}
/// <summary> Gets query result. </summary>
/// <param name="request"> The request. </param>
/// <returns> The query result. </returns>
private async Task<QueryResult<BaseItem>> GetQueryResult(BaseReportRequest request)
{
// Placeholder in case needed later
request.Recursive = true;
var user = !string.IsNullOrWhiteSpace(request.UserId) ? _userManager.GetUserById(request.UserId) : null;
request.Fields = "MediaSources,DateCreated,Settings,Studios,SyncInfo,ItemCounts";
var parentItem = string.IsNullOrEmpty(request.ParentId) ?
(user == null ? _libraryManager.RootFolder : user.RootFolder) :
_libraryManager.GetItemById(request.ParentId);
var item = string.IsNullOrEmpty(request.ParentId) ?
user == null ? _libraryManager.RootFolder : user.RootFolder :
parentItem;
IEnumerable<BaseItem> items;
if (request.Recursive)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false);
return result;
}
else
{
if (user == null)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, null)).ConfigureAwait(false);
return result;
}
var userRoot = item as UserRootFolder;
if (userRoot == null)
{
var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false);
return result;
}
items = ((Folder)item).GetChildren(user, true);
}
return new QueryResult<BaseItem> { Items = items.ToArray() };
}
/// <summary> Gets report activities. </summary>
/// <param name="request"> The request. </param>
/// <returns> The report activities. </returns>
private Task<ReportResult> GetReportActivities(IReportsDownload request)
{
return Task<ReportResult>.Run(() =>
{
DateTime? minDate = string.IsNullOrWhiteSpace(request.MinDate) ?
(DateTime?)null :
DateTime.Parse(request.MinDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
var queryResult = _repo.GetActivityLogEntries(minDate, request.StartIndex, request.Limit);
//var queryResult = _activityManager.GetActivityLogEntries(minDate, request.StartIndex, request.Limit);
ReportActivitiesBuilder builder = new ReportActivitiesBuilder(_libraryManager, _userManager);
var result = builder.GetResult(queryResult, request);
result.TotalRecordCount = queryResult.TotalRecordCount;
return result;
});
}
/// <summary> Gets report result. </summary>
/// <param name="request"> The request. </param>
/// <returns> The report result. </returns>
private async Task<ReportResult> GetReportResult(GetItemReport request)
{
ReportBuilder reportBuilder = new ReportBuilder(_libraryManager);
QueryResult<BaseItem> queryResult = await GetQueryResult(request).ConfigureAwait(false);
ReportResult reportResult = reportBuilder.GetResult(queryResult.Items, request);
reportResult.TotalRecordCount = queryResult.TotalRecordCount;
return reportResult;
}
/// <summary> Gets report statistic. </summary>
/// <param name="request"> The request. </param>
/// <returns> The report statistic. </returns>
private async Task<ReportStatResult> GetReportStatistic(GetReportStatistics request)
{
ReportIncludeItemTypes reportRowType = ReportHelper.GetRowType(request.IncludeItemTypes);
QueryResult<BaseItem> queryResult = await GetQueryResult(request).ConfigureAwait(false);
ReportStatBuilder reportBuilder = new ReportStatBuilder(_libraryManager);
ReportStatResult reportResult = reportBuilder.GetResult(queryResult.Items, ReportHelper.GetRowType(request.IncludeItemTypes), request.TopItems ?? 5);
reportResult.TotalRecordCount = reportResult.Groups.Count();
return reportResult;
}
#endregion
}
}

@ -13,6 +13,8 @@ namespace MediaBrowser.Api.Reports
/// <seealso cref="T:MediaBrowser.Api.Reports.ReportBuilderBase"/>
public class ReportStatBuilder : ReportBuilderBase
{
#region [Constructors]
/// <summary>
/// Initializes a new instance of the MediaBrowser.Api.Reports.ReportStatBuilder class. </summary>
/// <param name="libraryManager"> Manager for library. </param>
@ -21,12 +23,16 @@ namespace MediaBrowser.Api.Reports
{
}
#endregion
#region [Public Methods]
/// <summary> Gets report stat result. </summary>
/// <param name="items"> The items. </param>
/// <param name="reportRowType"> Type of the report row. </param>
/// <param name="reportIncludeItemTypes"> List of types of the report include items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The report stat result. </returns>
public ReportStatResult GetReportStatResult(BaseItem[] items, ReportViewType reportRowType, int topItem = 5)
public ReportStatResult GetResult(BaseItem[] items, ReportIncludeItemTypes reportIncludeItemTypes, int topItem = 5)
{
ReportStatResult result = new ReportStatResult();
result = this.GetResultGenres(result, items, topItem);
@ -37,25 +43,25 @@ namespace MediaBrowser.Api.Reports
result = this.GetResultCommunityRatings(result, items, topItem);
result = this.GetResultParentalRatings(result, items, topItem);
switch (reportRowType)
switch (reportIncludeItemTypes)
{
case ReportViewType.Season:
case ReportViewType.Series:
case ReportViewType.MusicAlbum:
case ReportViewType.MusicArtist:
case ReportViewType.Game:
case ReportIncludeItemTypes.Season:
case ReportIncludeItemTypes.Series:
case ReportIncludeItemTypes.MusicAlbum:
case ReportIncludeItemTypes.MusicArtist:
case ReportIncludeItemTypes.Game:
break;
case ReportViewType.Movie:
case ReportViewType.BoxSet:
case ReportIncludeItemTypes.Movie:
case ReportIncludeItemTypes.BoxSet:
break;
case ReportViewType.Book:
case ReportViewType.Episode:
case ReportViewType.Video:
case ReportViewType.MusicVideo:
case ReportViewType.Trailer:
case ReportViewType.Audio:
case ReportViewType.BaseItem:
case ReportIncludeItemTypes.Book:
case ReportIncludeItemTypes.Episode:
case ReportIncludeItemTypes.Video:
case ReportIncludeItemTypes.MusicVideo:
case ReportIncludeItemTypes.Trailer:
case ReportIncludeItemTypes.Audio:
case ReportIncludeItemTypes.BaseItem:
default:
break;
}
@ -65,70 +71,116 @@ namespace MediaBrowser.Api.Reports
return result;
}
private ReportStatResult GetResultGenres(ReportStatResult result, BaseItem[] items, int topItem = 5)
#endregion
#region [Protected Internal Methods]
/// <summary> Gets the headers. </summary>
/// <typeparam name="H"> Type of the header. </typeparam>
/// <param name="request"> The request. </param>
/// <returns> The headers. </returns>
/// <seealso cref="M:MediaBrowser.Api.Reports.ReportBuilderBase.GetHeaders{H}(H)"/>
protected internal override List<ReportHeader> GetHeaders<H>(H request)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderGenres"), topItem,
items.SelectMany(x => x.Genres)
throw new NotImplementedException();
}
#endregion
#region [Private Methods]
/// <summary> Gets the groups. </summary>
/// <param name="result"> The result. </param>
/// <param name="header"> The header. </param>
/// <param name="topItem"> The top item. </param>
/// <param name="top"> The top. </param>
private void GetGroups(ReportStatResult result, string header, int topItem, IEnumerable<ReportStatItem> top)
{
if (top.Count() > 0)
{
var group = new ReportStatGroup { Header = ReportStatGroup.FormatedHeader(header, topItem) };
group.Items.AddRange(top);
result.Groups.Add(group);
}
}
/// <summary> Gets resul production locations. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The resul production locations. </returns>
private ReportStatResult GetResulProductionLocations(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderCountries"), topItem,
items.OfType<IHasProductionLocations>()
.Where(x => x.ProductionLocations != null)
.SelectMany(x => x.ProductionLocations)
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
{
Name = x.Key,
Value = x.Count().ToString(),
Id = GetGenreID(x.Key)
}));
return result;
Name = x.Key.ToString(),
Value = x.Count().ToString()
})
);
return result;
}
private ReportStatResult GetResultStudios(ReportStatResult result, BaseItem[] items, int topItem = 5)
/// <summary> Gets result community ratings. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result community ratings. </returns>
private ReportStatResult GetResultCommunityRatings(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderStudios"), topItem,
items.SelectMany(x => x.Studios)
.GroupBy(x => x)
this.GetGroups(result, ReportHelper.GetServerLocalizedString("LabelCommunityRating"), topItem,
items.Where(x => x.CommunityRating != null && x.CommunityRating > 0)
.GroupBy(x => x.CommunityRating)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
{
Name = x.Key,
Value = x.Count().ToString(),
Id = GetStudioID(x.Key)
Name = x.Key.ToString(),
Value = x.Count().ToString()
})
);
return result;
}
private ReportStatResult GetResultPersons(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
List<string> t = new List<string> { PersonType.Actor, PersonType.Composer, PersonType.Director, PersonType.GuestStar, PersonType.Producer, PersonType.Writer, "Artist", "AlbumArtist" };
foreach (var item in t)
/// <summary> Gets result genres. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result genres. </returns>
private ReportStatResult GetResultGenres(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("Option" + item), topItem,
items.SelectMany(x => x.People)
.Where(n => n.Type == item)
.GroupBy(x => x.Name)
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderGenres"), topItem,
items.SelectMany(x => x.Genres)
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
{
Name = x.Key,
Value = x.Count().ToString(),
Id = GetPersonID(x.Key)
})
);
}
Id = GetGenreID(x.Key)
}));
return result;
}
private ReportStatResult GetResultCommunityRatings(ReportStatResult result, BaseItem[] items, int topItem = 5)
/// <summary> Gets result parental ratings. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result parental ratings. </returns>
private ReportStatResult GetResultParentalRatings(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("LabelCommunityRating"), topItem,
items.Where(x => x.CommunityRating != null && x.CommunityRating > 0)
.GroupBy(x => x.CommunityRating)
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderParentalRatings"), topItem,
items.Where(x => x.OfficialRating != null)
.GroupBy(x => x.OfficialRating)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
@ -141,24 +193,39 @@ namespace MediaBrowser.Api.Reports
return result;
}
private ReportStatResult GetResultParentalRatings(ReportStatResult result, BaseItem[] items, int topItem = 5)
/// <summary> Gets result persons. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result persons. </returns>
private ReportStatResult GetResultPersons(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderParentalRatings"), topItem,
items.Where(x => x.OfficialRating != null)
.GroupBy(x => x.OfficialRating)
List<string> t = new List<string> { PersonType.Actor, PersonType.Composer, PersonType.Director, PersonType.GuestStar, PersonType.Producer, PersonType.Writer, "Artist", "AlbumArtist" };
foreach (var item in t)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("Option" + item), topItem,
items.SelectMany(x => x.People)
.Where(n => n.Type == item)
.GroupBy(x => x.Name)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
{
Name = x.Key.ToString(),
Value = x.Count().ToString()
Name = x.Key,
Value = x.Count().ToString(),
Id = GetPersonID(x.Key)
})
);
}
return result;
}
/// <summary> Gets result production years. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result production years. </returns>
private ReportStatResult GetResultProductionYears(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderYears"), topItem,
@ -176,39 +243,31 @@ namespace MediaBrowser.Api.Reports
return result;
}
private ReportStatResult GetResulProductionLocations(ReportStatResult result, BaseItem[] items, int topItem = 5)
/// <summary> Gets result studios. </summary>
/// <param name="result"> The result. </param>
/// <param name="items"> The items. </param>
/// <param name="topItem"> The top item. </param>
/// <returns> The result studios. </returns>
private ReportStatResult GetResultStudios(ReportStatResult result, BaseItem[] items, int topItem = 5)
{
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderCountries"), topItem,
items.OfType<IHasProductionLocations>()
.Where(x => x.ProductionLocations != null)
.SelectMany(x => x.ProductionLocations)
this.GetGroups(result, ReportHelper.GetServerLocalizedString("HeaderStudios"), topItem,
items.SelectMany(x => x.Studios)
.GroupBy(x => x)
.OrderByDescending(x => x.Count())
.Take(topItem)
.Select(x => new ReportStatItem
{
Name = x.Key.ToString(),
Value = x.Count().ToString()
Name = x.Key,
Value = x.Count().ToString(),
Id = GetStudioID(x.Key)
})
);
return result;
}
#endregion
/// <summary> Gets the groups. </summary>
/// <param name="result"> The result. </param>
/// <param name="header"> The header. </param>
/// <param name="topItem"> The top item. </param>
/// <param name="top"> The top. </param>
private void GetGroups(ReportStatResult result, string header, int topItem, IEnumerable<ReportStatItem> top)
{
if (top.Count() > 0)
{
var group = new ReportStatGroup { Header = ReportStatGroup.FormatedHeader(header, topItem) };
group.Items.AddRange(top);
result.Groups.Add(group);
}
}
}
}

@ -1448,6 +1448,7 @@
"OptionReportList": "List View",
"OptionReportStatistics": "Statistics",
"OptionReportGrouping": "Grouping",
"OptionReportActivities": "Activities Log",
"HeaderExport": "Export",
"HeaderColumns": "Columns",
"ButtonReset": "Reset",
@ -1455,5 +1456,9 @@
"ButtonUnlockGuide": "Unlock Guide",
"LabelEnableFullScreen": "Enable fullscreen mode",
"LabelEnableChromecastAc3Passthrough": "Enable Chromecast AC3 Passthrough",
"LabelSyncPath": "Synced content path:"
"LabelSyncPath": "Synced content path:",
"HeaderOverview": "Overview",
"HeaderShortOverview": "Short Overview",
"HeaderType": "Type",
"HeaderSeverity": "Severity"
}

Loading…
Cancel
Save