diff options
author | Jeroen Walter <jeroen@enormkansloos.nl> | 2013-02-11 15:53:36 +0100 |
---|---|---|
committer | Jeroen Walter <jeroen@enormkansloos.nl> | 2013-02-11 15:53:36 +0100 |
commit | f726f429d7a103deac8955b76170796ed53482a7 (patch) | |
tree | d78d43cadb5763a2610f800f3fe6d1be6df333e2 /ComicRackWebViewer/Modules/BCRModule.cs | |
parent | 1cece8263e7dd9ee2ddd34abe82e89e6091c24da (diff) | |
download | ComicRackWeb-f726f429d7a103deac8955b76170796ed53482a7.zip ComicRackWeb-f726f429d7a103deac8955b76170796ed53482a7.tar.gz ComicRackWeb-f726f429d7a103deac8955b76170796ed53482a7.tar.bz2 |
- disabled webcomics, as they cause comicrack to hang
- cleanup op some code
Diffstat (limited to 'ComicRackWebViewer/Modules/BCRModule.cs')
-rw-r--r-- | ComicRackWebViewer/Modules/BCRModule.cs | 363 |
1 files changed, 57 insertions, 306 deletions
diff --git a/ComicRackWebViewer/Modules/BCRModule.cs b/ComicRackWebViewer/Modules/BCRModule.cs index 007c47f..28fd423 100644 --- a/ComicRackWebViewer/Modules/BCRModule.cs +++ b/ComicRackWebViewer/Modules/BCRModule.cs @@ -8,317 +8,23 @@ using System.IO; using System.Linq; using System.Reflection; using System.Diagnostics; -using cYo.Common; -using cYo.Common.IO; +//using cYo.Common; +//using cYo.Common.IO; using cYo.Projects.ComicRack.Engine; using cYo.Projects.ComicRack.Engine.IO.Provider; using cYo.Projects.ComicRack.Viewer; using Nancy; -//using Nancy.OData; using Nancy.ModelBinding; using Nancy.Responses; using ComicRackWebViewer; using System.Text.RegularExpressions; - - using Linq2Rest.Parser; -namespace BCR -{ - public class NaturalSortComparer<T> : IComparer<string>, IDisposable - { - private bool isAscending; - - public NaturalSortComparer(bool inAscendingOrder = true) - { - this.isAscending = inAscendingOrder; - } - - #region IComparer<string> Members - - public int Compare(string x, string y) - { - throw new NotImplementedException(); - } - - #endregion - - #region IComparer<string> Members - - int IComparer<string>.Compare(string x, string y) - { - if (x == y) - return 0; - - string[] x1, y1; - - if (!table.TryGetValue(x, out x1)) - { - x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)"); - table.Add(x, x1); - } - - if (!table.TryGetValue(y, out y1)) - { - y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)"); - table.Add(y, y1); - } - - int returnVal; - - for (int i = 0; i < x1.Length && i < y1.Length; i++) - { - if (x1[i] != y1[i]) - { - returnVal = PartCompare(x1[i], y1[i]); - return isAscending ? returnVal : -returnVal; - } - } - - if (y1.Length > x1.Length) - { - returnVal = 1; - } - else if (x1.Length > y1.Length) - { - returnVal = -1; - } - else - { - returnVal = 0; - } - - return isAscending ? returnVal : -returnVal; - } - - private static int PartCompare(string left, string right) - { - int x, y; - if (!int.TryParse(left, out x)) - return left.CompareTo(right); - - if (!int.TryParse(right, out y)) - return left.CompareTo(right); - - return x.CompareTo(y); - } - - #endregion - - private Dictionary<string, string[]> table = new Dictionary<string, string[]>(); - - public void Dispose() - { - table.Clear(); - table = null; - } - } - - public static class ODataExtensions - { - private const string ODATA_URI_KEY = "OData_Uri"; - - private static NameValueCollection MyParseUriOptions(NancyContext context) - { - object item; - if (context.Items.TryGetValue(ODATA_URI_KEY, out item)) - { - return item as NameValueCollection; - } - NameValueCollection nv = new NameValueCollection(); - context.Items.Add(ODATA_URI_KEY, nv); - var queryString = context.Request.Url.Query; - if (string.IsNullOrWhiteSpace(queryString)) - { - return nv; - } - if (!queryString.StartsWith("?")) - { - throw new InvalidOperationException("Invalid OData query string " + queryString); - } - var parameters = queryString.Substring(1).Split('&', '='); - if (parameters.Length % 2 != 0) - { - throw new InvalidOperationException("Invalid OData query string " + queryString); - } - for (int i = 0; i < parameters.Length; i += 2) - { - nv.Add(parameters[i], Uri.UnescapeDataString(parameters[i + 1])); - } - return nv; - } - - public static string GetReflectedPropertyValue(this object subject, string field) - { - object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null); - return reflectedValue != null ? reflectedValue.ToString() : ""; - } - - public static IEnumerable<object> ApplyODataUriFilter<T>(this NancyContext context, IEnumerable<T> modelItems, ref int totalCount) - { - var nv = MyParseUriOptions(context); - - - // $select is broken somehow....remove it for now - //NameValueCollection selectNV = new NameValueCollection(); - //selectNV.Add("$select", nv.Get("$select")); - nv.Remove("$select"); - - NameValueCollection pagingNV = new NameValueCollection(); - // We want the total count of the query before limiting the result set with $top and $skip - if (null != nv.Get("$skip")) - { - pagingNV.Add("$skip", nv.Get("$skip")); - nv.Remove("$skip"); - } - - if (null != nv.Get("$top")) - { - pagingNV.Add("$top", nv.Get("$top")); - nv.Remove("$top"); - } - - // perform sorting ourselves, because linq2rest doesn't allow custom comparers. - NameValueCollection sortNV = new NameValueCollection(); - if (null != nv.Get("$orderby")) - { - sortNV.Add("$orderby", nv.Get("$orderby")); - nv.Remove("$orderby"); - } - - // Now do a query that returns all records - var parser = new ParameterParser<T>(); - var filter = parser.Parse(nv); - var objects = filter.Filter(modelItems); - totalCount = objects.Count(); - - // Now sort - // Right now, only a single sort term is supported. - if (null != sortNV.Get("$orderby")) - { - char[] delimiterChars = {','}; - string[] orderby = sortNV.Get("$orderby").Split(delimiterChars); - char[] delimiterSpace = {' '}; - string[] terms = orderby[0].Split(delimiterSpace); - bool ascending = true; - if (terms.Count() == 2) - ascending = terms[1] != "desc"; - - if (orderby.Count() == 1) - { - objects = objects.OrderBy(item => item.GetReflectedPropertyValue(terms[0]), new NaturalSortComparer<string>(ascending)); - } - else - if (orderby.Count() > 1) - { - // get the second orderby - string[] terms2 = orderby[1].Split(delimiterSpace); - bool ascending2 = true; - if (terms2.Count() == 2) - ascending2 = terms2[1] != "desc"; - - objects = objects.OrderBy(item => item.GetReflectedPropertyValue(terms[0]), new NaturalSortComparer<string>(ascending)) - .ThenBy(item => item.GetReflectedPropertyValue(terms2[0]), new NaturalSortComparer<string>(ascending2)); - } - - } - - - // Now limit the resultset - var parser2 = new ParameterParser<T>(); - var filter2 = parser2.Parse(pagingNV); - var objects2 = filter2.Filter(objects.Cast<T>()); - return objects2; - } - - public static Response AsOData<T>(this IResponseFormatter formatter, IEnumerable<T> modelItems, HttpStatusCode code = HttpStatusCode.OK) - { - bool isJson = formatter.Context.Request.Headers.Accept.Select(x => x.Item1).Where(x => x.StartsWith("application/json", StringComparison.InvariantCultureIgnoreCase)).Any(); - - var nv = MyParseUriOptions(formatter.Context); - string value = nv.Get("$format"); - if (string.Compare(value, "json", true) == 0) - { - isJson = true; - } - - // BCR only supports json, no need to supply the $format every time.... - isJson = true; - - if (isJson) - { - int totalCount = 0; - return formatter.AsJson(formatter.Context.ApplyODataUriFilter(modelItems, ref totalCount), code); - } - throw new NotImplementedException("Atom feeds not implemented"); - } - } -} namespace BCR { - public static class BCRExtensions - { - public static Response AsError(this IResponseFormatter formatter, HttpStatusCode statusCode, string message, Request request) - { - return new Response - { - StatusCode = statusCode, - ContentType = "text/plain", - Contents = stream => (new StreamWriter(stream) { AutoFlush = true }).Write("Request: " + request.Url + "\nError: " + message) - }; - } - - - public static List<ComicBook> GetFolderBookList(string folder, bool includeSubFolders) - { - List<ComicBook> list = new List<ComicBook>(); - try - { - IEnumerable<string> fileExtensions = Providers.Readers.GetFileExtensions(); - foreach (string file in FileUtility.GetFiles(folder, includeSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, new string[0])) - { - string f = file; - if (Enumerable.Any<string>(fileExtensions, (Func<string, bool>) (ext => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))) - { - ComicBook comicBook = Program.BookFactory.Create(file, CreateBookOption.AddToTemporary, list.Count > 100 ? RefreshInfoOptions.DontReadInformation : RefreshInfoOptions.None); - if (comicBook != null) - list.Add(comicBook); - } - } - } - catch - { - } - return list; - } - - public static List<string> GetFolderBookList2(string folder, bool includeSubFolders) - { - List<string> list = new List<string>(); - try - { - IEnumerable<string> fileExtensions = Providers.Readers.GetFileExtensions(); - foreach (string file in FileUtility.GetFiles(folder, includeSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly, new string[0])) - { - string f = file; - if (Enumerable.Any<string>(fileExtensions, (Func<string, bool>) (ext => f.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))) - { - list.Add(file); - } - } - } - catch - { - } - return list; - } - } - - - public class BCRModule : NancyModule { public BCRModule() @@ -326,6 +32,8 @@ namespace BCR { Get["/"] = x => { return Response.AsRedirect("/tablet/index.html", RedirectResponse.RedirectType.Permanent); }; + /////////////////////////////////////////////////////////////////////////////////////////////// + // Retrieve a list of all (smart)lists. Get["/Lists"] = x => { try { @@ -338,7 +46,9 @@ namespace BCR } }; - + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Retrieve the contents of the specified list. Get["/Lists/{id}"] = x => { try { @@ -357,6 +67,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // For OData compatibility, count should be $count, but I don't know how to parse the $ with Nancy.... Get["/Lists/{id}/Comics/count"] = x => { try @@ -370,6 +82,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Return the comics of the specified list using OData to filter the comic properties and the list paging. Get["/Lists/{id}/Comics"] = x => { try @@ -389,6 +103,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Returns a list of all the comics as comic excerpts Get["/Comics"] = x => { try { @@ -403,6 +120,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Return the comicbook info as an OData filtered bag of properties. Get["/Comics/{id}"] = x => { try @@ -421,6 +140,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve the specified page as a jpg file with the specified dimensions. Get["/Comics/{id}/Pages/{page}"] = x => { try @@ -439,6 +160,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get["/Comics/{id}/Pages/{page}/size"] = x => { try { @@ -453,6 +177,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Get one property. Get["/Comics/{id}/{property}"] = x => { try @@ -474,6 +200,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Update properties of the specified comicbook. Put["/Comics/{id}"] = x => { try @@ -502,7 +230,7 @@ namespace BCR }; - + /////////////////////////////////////////////////////////////////////////////////////////////// // Update one property Put["/Comics/{id}/{property}"] = x => { try @@ -530,6 +258,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Get the BCR settings. Get["/Settings"] = x => { try @@ -542,6 +272,8 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// // Update the BCR settings. Put["/Settings"] = x => { @@ -558,6 +290,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get a list of series Get["/Series"] = x => { try { @@ -573,6 +308,8 @@ namespace BCR }; + /////////////////////////////////////////////////////////////////////////////////////////////// + // Retrieve a list of all comics in the specified list Get["/Series/{id}"] = x => { try { @@ -587,6 +324,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Retrieve the number of comics in the specified list Get["/Series/{id}/count"] = x => { try { @@ -599,6 +339,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get["/Series/{id}/Volumes"] = x => { try { @@ -610,6 +353,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get["/Series/{id}/Volumes/{volume}"] = x => { try { @@ -624,8 +370,8 @@ namespace BCR }; - - + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get a list of publishers Get["/Publishers"] = x => { try { @@ -637,6 +383,9 @@ namespace BCR } }; + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get["/Log"] = x => { try { @@ -653,7 +402,10 @@ namespace BCR } }; - Get["/Folder"] = x => { + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get the list of watched folders. + Get["/WatchFolder"] = x => { try { //return Response.AsOData(BCR.GetPublishers(), HttpStatusCode.OK); @@ -664,10 +416,6 @@ namespace BCR return Response.AsJson(books, HttpStatusCode.OK); //return Response.AsRedirect("/tablet/resources/images/empty_1x1.png", RedirectResponse.RedirectType.Permanent); - - - - } catch(Exception e) { @@ -675,7 +423,10 @@ namespace BCR } }; - Get["/Folder/{id}"] = x => { + + /////////////////////////////////////////////////////////////////////////////////////////////// + // Get list of all files in the folder + Get["/WatchFolder/{folder}"] = x => { try { return Response.AsRedirect("/tablet/resources/images/empty_1x1.png", RedirectResponse.RedirectType.Permanent); |