コード例 #1
0
        public IActionResult RecentBooks(int?pageNumber)
        {
            string xml = new OpenSearch().Search("", "recentbooks", acceptFB2(), pageNumber ?? 0).ToString();

            xml = getHeader(xml);
            return(OPDSResult(xml));
        }
コード例 #2
0
        public IActionResult Search(string searchTerm, string searchType, int?pageNumber)
        {
            string xml = new OpenSearch().Search(searchTerm ?? "", searchType ?? "", acceptFB2(), pageNumber ?? 0).ToString();

            xml = getHeader(xml);
            return(OPDSResult(xml));
        }
コード例 #3
0
        private string getOpensearchHeader()
        {
            string xml0 = new OpenSearch().OpenSearchDescription(HttpContext.Request.Headers["Host"]).ToString();
            string xml  = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + xml0.Insert(22, " xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"");

            return(absoluteUri(xml));
        }
コード例 #4
0
ファイル: FormOfSelect.cs プロジェクト: MArtGen/BigData2
 //Обработка кнопки перехода к форме поиска (временное решение)
 private void SelectSort_button_Click(object sender, EventArgs e)
 {
     if (SelectOfSort_box.Text == "Учет электроэнергии")
     {
         Hide();
         OpenSearch?.Invoke(this, EventArgs.Empty);
     }
     else
     {
         MessageBox.Show("Интерфейс в разработке");
     }
 }
コード例 #5
0
        internal static Transaction2FindNext2Response GetSubcommandResponse(SMB1Header header, uint maxDataCount, Transaction2FindNext2Request subcommand, ISMBShare share, SMB1ConnectionState state)
        {
            SMB1Session session    = state.GetSession(header.UID);
            OpenSearch  openSearch = session.GetOpenSearch(subcommand.SID);

            if (openSearch == null)
            {
                state.LogToServer(Severity.Verbose, "FindNext2 failed. Invalid SID.");
                header.Status = NTStatus.STATUS_INVALID_HANDLE;
                return(null);
            }

            bool returnResumeKeys = (subcommand.Flags & FindFlags.SMB_FIND_RETURN_RESUME_KEYS) > 0;
            int  maxLength        = (int)maxDataCount;
            int  maxCount         = Math.Min(openSearch.Entries.Count - openSearch.EnumerationLocation, subcommand.SearchCount);
            List <QueryDirectoryFileInformation> segment = openSearch.Entries.GetRange(openSearch.EnumerationLocation, maxCount);
            FindInformationList findInformationList;

            try
            {
                findInformationList = FindInformationHelper.ToFindInformationList(segment, header.UnicodeFlag, maxLength);
            }
            catch (UnsupportedInformationLevelException)
            {
                state.LogToServer(Severity.Verbose, "FindNext2: Unsupported information level: {0}.", subcommand.InformationLevel);
                header.Status = NTStatus.STATUS_OS2_INVALID_LEVEL;
                return(null);
            }
            int returnCount = findInformationList.Count;
            Transaction2FindNext2Response response = new Transaction2FindNext2Response();

            response.SetFindInformationList(findInformationList, header.UnicodeFlag);
            openSearch.EnumerationLocation += returnCount;
            response.EndOfSearch            = (openSearch.EnumerationLocation == openSearch.Entries.Count);
            if (response.EndOfSearch)
            {
                session.RemoveOpenSearch(subcommand.SID);
            }
            return(response);
        }
コード例 #6
0
ファイル: OPDSServer.cs プロジェクト: saa1963/TinyOPDS
        /// <summary>
        /// POST requests handler
        /// </summary>
        /// <param name="p"></param>
        public override void HandleGETRequest(HttpProcessor processor)
        {
            Log.WriteLine("HTTP GET request from {0}: {1}", ((System.Net.IPEndPoint)processor.Socket.Client.RemoteEndPoint).Address, processor.HttpUrl);
            try
            {
                // Parse request
                string xml     = string.Empty;
                string request = processor.HttpUrl;
                // Remove prefix if any
                if (!string.IsNullOrEmpty(Properties.Settings.Default.RootPrefix))
                {
                    request = request.Replace(Properties.Settings.Default.RootPrefix, "/");
                }

                while (request.IndexOf("//") >= 0)
                {
                    request = request.Replace("//", "/");
                }

                string   ext         = Path.GetExtension(request);
                string[] http_params = request.Split(new Char[] { '?', '=', '&' });

                // User-agent check: some e-book readers can handle fb2 files (no conversion is  needed)
                string userAgent = processor.HttpHeaders["User-Agent"] as string;
                bool   acceptFB2 = Utils.DetectFB2Reader(userAgent);

                // Is it OPDS request?
                if (string.IsNullOrEmpty(ext) || !new string[] { ".ico", ".jpeg", ".epub", ".zip", ".xml" }.Contains(ext))
                {
                    try
                    {
                        // Is it root node requested?
                        if (request.Equals("/"))
                        {
                            xml = new RootCatalog().Catalog.ToString();
                        }
                        else if (request.StartsWith("/authorsindex"))
                        {
                            int numChars = request.StartsWith("/authorsindex/") ? 14 : 13;
                            xml = new AuthorsCatalog().GetCatalog(request.Substring(numChars)).ToString();
                        }
                        else if (request.StartsWith("/author/"))
                        {
                            xml = new BooksCatalog().GetCatalogByAuthor(request.Substring(8), acceptFB2).ToString();
                        }
                        else if (request.StartsWith("/sequencesindex"))
                        {
                            int numChars = request.StartsWith("/sequencesindex/") ? 16 : 15;
                            xml = new SequencesCatalog().GetCatalog(request.Substring(numChars)).ToString();
                        }
                        else if (request.Contains("/sequence/"))
                        {
                            xml = new BooksCatalog().GetCatalogBySequence(request.Substring(10), acceptFB2).ToString();
                        }
                        else if (request.StartsWith("/genres"))
                        {
                            int numChars = request.Contains("/genres/") ? 8 : 7;
                            xml = new GenresCatalog().GetCatalog(request.Substring(numChars)).ToString();
                        }
                        else if (request.StartsWith("/genre/"))
                        {
                            xml = new BooksCatalog().GetCatalogByGenre(request.Substring(7), acceptFB2).ToString();
                        }
                        else if (request.StartsWith("/search"))
                        {
                            if (http_params[1].Equals("searchTerm"))
                            {
                                xml = new OpenSearch().Search(http_params[2], "", acceptFB2).ToString();
                            }
                            else if (http_params[1].Equals("searchType"))
                            {
                                int pageNumber = 0;
                                if (http_params.Length > 6 && http_params[5].Equals("pageNumber"))
                                {
                                    int.TryParse(http_params[6], out pageNumber);
                                }
                                xml = new OpenSearch().Search(http_params[4], http_params[2], acceptFB2, pageNumber).ToString();
                            }
                        }

                        if (string.IsNullOrEmpty(xml))
                        {
                            processor.WriteFailure();
                            return;
                        }

                        // Modify and send xml back to the client app
                        xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + xml.Insert(5, " xmlns=\"http://www.w3.org/2005/Atom\"");

                        if (Properties.Settings.Default.UseAbsoluteUri)
                        {
                            try
                            {
                                string host = processor.HttpHeaders["Host"].ToString();
                                xml = xml.Replace("href=\"", "href=\"http://" + host.UrlCombine(Properties.Settings.Default.RootPrefix));
                            }
                            catch { }
                        }

#if USE_GZIP_ENCODING
                        /// Unfortunately, current OPDS-enabled apps don't support this feature, even those that pretend to (like FBReader for Android)

                        // Compress xml if compression supported
                        if (!processor.HttpHeaders.ContainsValue("gzip"))
                        {
                            byte[] temp = Encoding.UTF8.GetBytes(xml);
                            using (MemoryStream inStream = new MemoryStream(temp))
                                using (MemoryStream outStream = new MemoryStream())
                                    using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
                                    {
                                        inStream.CopyTo(gzipStream);
                                        outStream.Position = 0;
                                        processor.WriteSuccess("application/atom+xml;charset=utf=8", true);
                                        outStream.CopyTo(processor.OutputStream.BaseStream);
                                    }
                        }
                        else
#endif
                        {
                            processor.WriteSuccess("application/atom+xml;charset=utf-8");
                            processor.OutputStream.Write(xml);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogLevel.Error, "OPDS catalog exception {0}", e.Message);
                    }
                    return;
                }
                else if (request.Contains("opds-opensearch.xml"))
                {
                    xml = new OpenSearch().OpenSearchDescription().ToString();
                    xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + xml.Insert(22, " xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"");

                    if (Properties.Settings.Default.UseAbsoluteUri)
                    {
                        try
                        {
                            string host = processor.HttpHeaders["Host"].ToString();
                            xml = xml.Replace("href=\"", "href=\"http://" + host.UrlCombine(Properties.Settings.Default.RootPrefix));
                        }
                        catch { }
                    }

                    processor.WriteSuccess("application/atom+xml;charset=utf-8");
                    processor.OutputStream.Write(xml);
                    return;
                }
                // fb2.zip book request
                else if (request.Contains(".fb2.zip"))
                {
                    MemoryStream memStream = null;
                    try
                    {
                        memStream = new MemoryStream();
                        Book book = LibraryFactory.GetLibrary().GetBook(request.Substring(1, request.IndexOf('/', 1) - 1));

                        if (book.FilePath.ToLower().Contains(".zip@"))
                        {
                            string[] pathParts = book.FilePath.Split('@');
                            using (ZipFile zipFile = new ZipFile(pathParts[0]))
                            {
                                ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                if (entry != null)
                                {
                                    entry.Extract(memStream);
                                }
                            }
                        }
                        else
                        {
                            using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                stream.CopyTo(memStream);
                        }
                        memStream.Position = 0;

                        // Compress fb2 document to zip
                        using (ZipFile zip = new ZipFile())
                        {
                            zip.AddEntry(Transliteration.Front(string.Format("{0}_{1}.fb2", book.Authors.First(), book.Title)), memStream);
                            using (MemoryStream outputStream = new MemoryStream())
                            {
                                zip.Save(outputStream);
                                outputStream.Position = 0;
                                processor.WriteSuccess("application/fb2+zip");
                                outputStream.CopyTo(processor.OutputStream.BaseStream);
                            }
                        }
                        HttpServer.ServerStatistics.BooksSent++;
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogLevel.Error, "FB2 file exception {0}", e.Message);
                    }
                    finally
                    {
                        processor.OutputStream.BaseStream.Flush();
                        if (memStream != null)
                        {
                            memStream.Dispose();
                        }
                    }
                    return;
                }
                // epub book request
                else if (ext.Contains(".epub"))
                {
                    MemoryStream memStream = null;
                    try
                    {
                        memStream = new MemoryStream();
                        Book book = LibraryFactory.GetLibrary().GetBook(request.Substring(1, request.IndexOf('/', 1) - 1));

                        if (book.FilePath.ToLower().Contains(".zip@"))
                        {
                            string[] pathParts = book.FilePath.Split('@');
                            using (ZipFile zipFile = new ZipFile(pathParts[0]))
                            {
                                ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                if (entry != null)
                                {
                                    entry.Extract(memStream);
                                }
                                entry = null;
                            }
                        }
                        else
                        {
                            using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                stream.CopyTo(memStream);
                        }
                        memStream.Position = 0;
                        // At this moment, memStream has a copy of requested book
                        // For fb2, we need convert book to epub
                        if (book.BookType == BookType.FB2)
                        {
                            // No convertor found, return an error
                            if (string.IsNullOrEmpty(Properties.Settings.Default.ConvertorPath))
                            {
                                Log.WriteLine(LogLevel.Error, "No FB2 to EPUB convertor found, file request can not be completed!");
                                processor.WriteFailure();
                                return;
                            }

                            // Save fb2 book to the temp folder
                            string inFileName = Path.Combine(Path.GetTempPath(), book.ID + ".fb2");
                            using (FileStream stream = new FileStream(inFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                                memStream.CopyTo(stream);

                            // Run converter
                            string outFileName = Path.Combine(Path.GetTempPath(), book.ID + ".epub");
                            string command     = Path.Combine(Properties.Settings.Default.ConvertorPath, Utils.IsLinux ? "fb2toepub" : "Fb2ePub.exe");
                            string arguments   = string.Format(Utils.IsLinux ? "{0} {1}" : "\"{0}\" \"{1}\"", inFileName, outFileName);

                            using (ProcessHelper converter = new ProcessHelper(command, arguments))
                            {
                                converter.Run();

                                if (File.Exists(outFileName))
                                {
                                    memStream = new MemoryStream();
                                    using (FileStream fileStream = new FileStream(outFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                                        fileStream.CopyTo(memStream);

                                    // Cleanup temp folder
                                    try { File.Delete(inFileName); }
                                    catch { }
                                    try { File.Delete(outFileName); }
                                    catch { }
                                }
                                else
                                {
                                    string converterError = string.Empty;
                                    foreach (string s in converter.ProcessOutput)
                                    {
                                        converterError += s + " ";
                                    }
                                    Log.WriteLine(LogLevel.Error, "EPUB conversion error on file {0}. Error description: {1}", inFileName, converterError);
                                    processor.WriteFailure();
                                    return;
                                }
                            }
                        }

                        // At this moment, memStream has a copy of epub
                        processor.WriteSuccess("application/epub+zip");
                        memStream.Position = 0;
                        memStream.CopyTo(processor.OutputStream.BaseStream);
                        HttpServer.ServerStatistics.BooksSent++;
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogLevel.Error, "EPUB file exception {0}", e.Message);
                    }
                    finally
                    {
                        processor.OutputStream.BaseStream.Flush();
                        if (memStream != null)
                        {
                            memStream.Dispose();
                        }
                    }
                    return;
                }
                // Cover image or thumbnail request
                else if (ext.Contains(".jpeg"))
                {
                    bool   getCover = true;
                    string bookID   = string.Empty;
                    if (request.Contains("/cover/"))
                    {
                        bookID = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/cover/") + 7));
                    }
                    else if (request.Contains("/thumbnail/"))
                    {
                        bookID   = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/thumbnail/") + 11));
                        getCover = false;
                    }

                    if (!string.IsNullOrEmpty(bookID))
                    {
                        CoverImage image = null;
                        Book       book  = LibraryFactory.GetLibrary().GetBook(bookID);

                        if (book != null)
                        {
                            if (ImagesCache.HasImage(bookID))
                            {
                                image = ImagesCache.GetImage(bookID);
                            }
                            else
                            {
                                image = new CoverImage(book);
                                if (image != null && image.HasImages)
                                {
                                    ImagesCache.Add(image);
                                }
                            }

                            if (image != null && image.HasImages)
                            {
                                processor.WriteSuccess("image/jpeg");
                                (getCover ? image.CoverImageStream : image.ThumbnailImageStream).CopyTo(processor.OutputStream.BaseStream);
                                processor.OutputStream.BaseStream.Flush();
                                HttpServer.ServerStatistics.ImagesSent++;
                                return;
                            }
                        }
                    }
                }
                // favicon.ico request
                else if (ext.Contains(".ico"))
                {
                    string icon   = Path.GetFileName(request);
                    Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("TinyOPDS.Icons." + icon);
                    if (stream != null && stream.Length > 0)
                    {
                        processor.WriteSuccess("image/x-icon");
                        stream.CopyTo(processor.OutputStream.BaseStream);
                        processor.OutputStream.BaseStream.Flush();
                        return;
                    }
                }
                processor.WriteFailure();
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, ".HandleGETRequest() exception {0}", e.Message);
                processor.WriteFailure();
            }
        }
コード例 #7
0
ファイル: OPDSServer.cs プロジェクト: wheeliemow/tinyopds
        /// <summary>
        /// POST requests handler
        /// </summary>
        /// <param name="p"></param>
        public override void HandleGETRequest(HttpProcessor processor)
        {
            Log.WriteLine("HTTP GET request from {0}: {1}", ((System.Net.IPEndPoint)processor.Socket.Client.RemoteEndPoint).Address, processor.HttpUrl);
            try
            {
                // Parse request
                string xml     = string.Empty;
                string request = processor.HttpUrl;

                // Check for www request
                bool isWWWRequest = request.StartsWith("/" + TinyOPDS.Properties.Settings.Default.HttpPrefix) && !request.StartsWith("/" + TinyOPDS.Properties.Settings.Default.RootPrefix) ? true : false;

                // Remove prefix if any
                if (!request.Contains("opds-opensearch.xml") && !string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.RootPrefix))
                {
                    request = request.Replace(TinyOPDS.Properties.Settings.Default.RootPrefix, "/");
                }
                if (!string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.HttpPrefix))
                {
                    request = request.Replace(TinyOPDS.Properties.Settings.Default.HttpPrefix, "/");
                }

                while (request.IndexOf("//") >= 0)
                {
                    request = request.Replace("//", "/");
                }

                // Remove any parameters from request except TinyOPDS params
                int paramPos = request.IndexOf('?');
                if (paramPos >= 0)
                {
                    int ourParamPos = request.IndexOf("pageNumber") + request.IndexOf("searchTerm");
                    if (ourParamPos >= 0)
                    {
                        ourParamPos = request.IndexOf('&', ourParamPos + 10);
                        if (ourParamPos >= 0)
                        {
                            request = request.Substring(0, ourParamPos);
                        }
                    }
                    else
                    {
                        request = request.Substring(0, paramPos);
                    }
                }

                string ext = Path.GetExtension(request).ToLower();
                if (!_extensions.Contains(ext))
                {
                    ext = string.Empty;
                }

                string[] http_params = request.Split(new Char[] { '?', '=', '&' });

                // User-agent check: some e-book readers can handle fb2 files (no conversion is  needed)
                string userAgent = processor.HttpHeaders["User-Agent"] as string;
                bool   acceptFB2 = Utils.DetectFB2Reader(userAgent) || isWWWRequest;
                int    threshold = (int)(isWWWRequest ? TinyOPDS.Properties.Settings.Default.ItemsPerWebPage : TinyOPDS.Properties.Settings.Default.ItemsPerOPDSPage);

                // Is it OPDS request?
                if (string.IsNullOrEmpty(ext))
                {
                    try
                    {
                        // Is it root node requested?
                        if (request.Equals("/"))
                        {
                            xml = new RootCatalog().GetCatalog().ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/newdate"))
                        {
                            xml = new NewBooksCatalog().GetCatalog(request.Substring(8), true, acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/newtitle"))
                        {
                            xml = new NewBooksCatalog().GetCatalog(request.Substring(9), false, acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/authorsindex"))
                        {
                            int numChars = request.StartsWith("/authorsindex/") ? 14 : 13;
                            xml = new AuthorsCatalog().GetCatalog(request.Substring(numChars), false, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/author/"))
                        {
                            xml = new BooksCatalog().GetCatalogByAuthor(request.Substring(8), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/sequencesindex"))
                        {
                            int numChars = request.StartsWith("/sequencesindex/") ? 16 : 15;
                            xml = new SequencesCatalog().GetCatalog(request.Substring(numChars), threshold).ToStringWithDeclaration();
                        }
                        else if (request.Contains("/sequence/"))
                        {
                            xml = new BooksCatalog().GetCatalogBySequence(request.Substring(10), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/genres"))
                        {
                            int numChars = request.Contains("/genres/") ? 8 : 7;
                            xml = new GenresCatalog().GetCatalog(request.Substring(numChars)).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/genre/"))
                        {
                            xml = new BooksCatalog().GetCatalogByGenre(request.Substring(7), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/search"))
                        {
                            if (http_params.Length > 1 && http_params[1].Equals("searchTerm"))
                            {
                                xml = new OpenSearch().Search(http_params[2], "", acceptFB2).ToStringWithDeclaration();
                            }
                            else if (http_params[1].Equals("searchType"))
                            {
                                int pageNumber = 0;
                                if (http_params.Length > 6 && http_params[5].Equals("pageNumber"))
                                {
                                    int.TryParse(http_params[6], out pageNumber);
                                }
                                xml = new OpenSearch().Search(http_params[4], http_params[2], acceptFB2, pageNumber).ToStringWithDeclaration();
                            }
                        }

                        if (string.IsNullOrEmpty(xml))
                        {
                            processor.WriteFailure();
                            return;
                        }

                        // Fix for the root namespace
                        // TODO: fix with standard way (how?)
                        xml = xml.Insert(xml.IndexOf("<feed ") + 5, " xmlns=\"http://www.w3.org/2005/Atom\"");

                        if (TinyOPDS.Properties.Settings.Default.UseAbsoluteUri)
                        {
                            try
                            {
                                string host = processor.HttpHeaders["Host"].ToString();
                                xml = xml.Replace("href=\"", "href=\"http://" + (isWWWRequest ? host.UrlCombine(TinyOPDS.Properties.Settings.Default.HttpPrefix) : host.UrlCombine(TinyOPDS.Properties.Settings.Default.RootPrefix)));
                            }
                            catch { }
                        }
                        else
                        {
                            string prefix = isWWWRequest ? TinyOPDS.Properties.Settings.Default.HttpPrefix : TinyOPDS.Properties.Settings.Default.RootPrefix;
                            if (!string.IsNullOrEmpty(prefix))
                            {
                                prefix = "/" + prefix;
                            }
                            xml = xml.Replace("href=\"", "href=\"" + prefix);
                            // Fix open search link
                            xml = xml.Replace(prefix + "/opds-opensearch.xml", "/opds-opensearch.xml");
                        }

                        // Apply xsl transform
                        if (isWWWRequest)
                        {
                            string html = string.Empty;

                            MemoryStream htmlStream = new MemoryStream();
                            using (StringReader stream = new StringReader(xml))
                            {
                                XPathDocument myXPathDoc = new XPathDocument(stream);

// for easy debug of xsl transform, we'll reload external file in DEBUG build
#if DEBUG
                                string xslFileName = Path.Combine(Utils.ServiceFilesLocation, "xml2html.xsl");
                                _xslTransform = new XslCompiledTransform();
                                if (File.Exists(xslFileName))
                                {
                                    _xslTransform.Load(xslFileName);
                                }
                                else
                                {
                                    using (Stream resStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".xml2html.xsl"))
                                    {
                                        using (XmlReader reader = XmlReader.Create(resStream))
                                            _xslTransform.Load(reader);
                                    }
                                }
#endif
                                XmlTextWriter myWriter = new XmlTextWriter(htmlStream, null);
                                _xslTransform.Transform(myXPathDoc, null, myWriter);
                                htmlStream.Position = 0;
                                using (StreamReader sr = new StreamReader(htmlStream)) html = sr.ReadToEnd();
                            }

                            processor.WriteSuccess("text/html");
                            processor.OutputStream.Write(html);
                        }
                        else
                        {
                            processor.WriteSuccess("application/atom+xml;charset=utf-8");
                            processor.OutputStream.Write(xml);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogLevel.Error, "OPDS catalog exception {0}", e.Message);
                    }
                    return;
                }
                else if (request.Contains("opds-opensearch.xml"))
                {
                    xml = new OpenSearch().OpenSearchDescription().ToStringWithDeclaration();
                    xml = xml.Insert(xml.IndexOf("<OpenSearchDescription") + 22, " xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"");

                    if (TinyOPDS.Properties.Settings.Default.UseAbsoluteUri)
                    {
                        try
                        {
                            string host = processor.HttpHeaders["Host"].ToString();
                            xml = xml.Replace("href=\"", "href=\"http://" + host.UrlCombine(TinyOPDS.Properties.Settings.Default.RootPrefix));
                        }
                        catch { }
                    }

                    processor.WriteSuccess("application/atom+xml;charset=utf-8");
                    processor.OutputStream.Write(xml);
                    return;
                }

                // fb2.zip book request
                else if ((request.Contains(".fb2.zip") && ext.Equals(".zip")) || ext.Equals(".epub"))
                {
                    string bookID = request.Substring(1, request.IndexOf('/', 1) - 1).Replace("%7B", "{").Replace("%7D", "}");
                    Book   book   = Library.GetBook(bookID);

                    if (book != null)
                    {
                        MemoryStream memStream = null;
                        memStream = new MemoryStream();

                        if (request.Contains(".fb2.zip"))
                        {
                            try
                            {
                                if (book.FilePath.ToLower().Contains(".zip@"))
                                {
                                    string[] pathParts = book.FilePath.Split('@');
                                    using (ZipFile zipFile = new ZipFile(pathParts[0]))
                                    {
                                        ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                        if (entry != null)
                                        {
                                            entry.Extract(memStream);
                                        }
                                    }
                                }
                                else
                                {
                                    using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                        stream.CopyTo(memStream);
                                }
                                memStream.Position = 0;

                                // Compress fb2 document to zip
                                using (ZipFile zip = new ZipFile())
                                {
                                    zip.AddEntry(Transliteration.Front(string.Format("{0}_{1}.fb2", book.Authors.First(), book.Title)), memStream);
                                    using (MemoryStream outputStream = new MemoryStream())
                                    {
                                        zip.Save(outputStream);
                                        outputStream.Position = 0;
                                        processor.WriteSuccess("application/fb2+zip");
                                        outputStream.CopyTo(processor.OutputStream.BaseStream);
                                    }
                                }
                                HttpServer.ServerStatistics.BooksSent++;
                            }
                            catch (Exception e)
                            {
                                Log.WriteLine(LogLevel.Error, "FB2 file exception {0}", e.Message);
                            }
                        }
                        else if (ext.Equals(".epub"))
                        {
                            try
                            {
                                if (book.FilePath.ToLower().Contains(".zip@"))
                                {
                                    string[] pathParts = book.FilePath.Split('@');
                                    using (ZipFile zipFile = new ZipFile(pathParts[0]))
                                    {
                                        ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                        if (entry != null)
                                        {
                                            entry.Extract(memStream);
                                        }
                                        entry = null;
                                    }
                                }
                                else
                                {
                                    using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                        stream.CopyTo(memStream);
                                }
                                memStream.Position = 0;
                                // At this moment, memStream has a copy of requested book
                                // For fb2, we need convert book to epub
                                if (book.BookType == BookType.FB2)
                                {
                                    // No convertor found, return an error
                                    if (string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.ConvertorPath))
                                    {
                                        Log.WriteLine(LogLevel.Error, "No FB2 to EPUB convertor found, file request can not be completed!");
                                        processor.WriteFailure();
                                        return;
                                    }

                                    // Save fb2 book to the temp folder
                                    string inFileName = Path.Combine(Path.GetTempPath(), book.ID + ".fb2");
                                    using (FileStream stream = new FileStream(inFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                                        memStream.CopyTo(stream);

                                    // Run converter
                                    string outFileName = Path.Combine(Path.GetTempPath(), book.ID + ".epub");
                                    string command     = Path.Combine(TinyOPDS.Properties.Settings.Default.ConvertorPath, Utils.IsLinux ? "fb2toepub" : "Fb2ePub.exe");
                                    string arguments   = string.Format(Utils.IsLinux ? "{0} {1}" : "\"{0}\" \"{1}\"", inFileName, outFileName);

                                    using (ProcessHelper converter = new ProcessHelper(command, arguments))
                                    {
                                        converter.Run();

                                        if (File.Exists(outFileName))
                                        {
                                            memStream = new MemoryStream();
                                            using (FileStream fileStream = new FileStream(outFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                                                fileStream.CopyTo(memStream);

                                            // Cleanup temp folder
                                            try { File.Delete(inFileName); }
                                            catch { }
                                            try { File.Delete(outFileName); }
                                            catch { }
                                        }
                                        else
                                        {
                                            string converterError = string.Empty;
                                            foreach (string s in converter.ProcessOutput)
                                            {
                                                converterError += s + " ";
                                            }
                                            Log.WriteLine(LogLevel.Error, "EPUB conversion error on file {0}. Error description: {1}", inFileName, converterError);
                                            processor.WriteFailure();
                                            return;
                                        }
                                    }
                                }

                                // At this moment, memStream has a copy of epub
                                processor.WriteSuccess("application/epub+zip");
                                memStream.Position = 0;
                                memStream.CopyTo(processor.OutputStream.BaseStream);
                                HttpServer.ServerStatistics.BooksSent++;
                            }

                            catch (Exception e)
                            {
                                Log.WriteLine(LogLevel.Error, "EPUB file exception {0}", e.Message);
                            }
                        }

                        processor.OutputStream.BaseStream.Flush();
                        if (memStream != null)
                        {
                            memStream.Dispose();
                        }
                    }
                    else
                    {
                        Log.WriteLine(LogLevel.Error, "Book {0} not found in library.", bookID);
                    }
                }
                // Cover image or thumbnail request
                else if (ext.Contains(".jpeg"))
                {
                    bool   getCover = true;
                    string bookID   = string.Empty;
                    if (request.Contains("/cover/"))
                    {
                        bookID = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/cover/") + 7));
                    }
                    else if (request.Contains("/thumbnail/"))
                    {
                        bookID   = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/thumbnail/") + 11));
                        getCover = false;
                    }

                    bookID = bookID.Replace("%7B", "{").Replace("%7D", "}");

                    if (!string.IsNullOrEmpty(bookID))
                    {
                        CoverImage image = null;
                        Book       book  = Library.GetBook(bookID);

                        if (book != null)
                        {
                            if (ImagesCache.HasImage(bookID))
                            {
                                image = ImagesCache.GetImage(bookID);
                            }
                            else
                            {
                                image = new CoverImage(book);
                                if (image != null && image.HasImages)
                                {
                                    ImagesCache.Add(image);
                                }
                            }

                            if (image != null && image.HasImages)
                            {
                                processor.WriteSuccess("image/jpeg");
                                (getCover ? image.CoverImageStream : image.ThumbnailImageStream).CopyTo(processor.OutputStream.BaseStream);
                                processor.OutputStream.BaseStream.Flush();
                                HttpServer.ServerStatistics.ImagesSent++;
                                return;
                            }
                        }
                    }
                }
                // favicon.ico request
                else if (ext.Contains(".ico"))
                {
                    string icon   = Path.GetFileName(request);
                    Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".Icons." + icon);
                    if (stream != null && stream.Length > 0)
                    {
                        processor.WriteSuccess("image/x-icon");
                        stream.CopyTo(processor.OutputStream.BaseStream);
                        processor.OutputStream.BaseStream.Flush();
                        return;
                    }
                }
                processor.WriteFailure();
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, ".HandleGETRequest() exception {0}", e.Message);
                processor.WriteFailure();
            }
        }
コード例 #8
0
        internal static SMB2Command GetQueryDirectoryResponse(QueryDirectoryRequest request, ISMBShare share, SMB2ConnectionState state)
        {
            SMB2Session    session  = state.GetSession(request.Header.SessionID);
            OpenFileObject openFile = session.GetOpenFileObject(request.FileId);

            if (openFile == null)
            {
                state.LogToServer(Severity.Verbose, "Query Directory failed. Invalid FileId. (SessionID: {0}, TreeID: {1}, FileId: {2})", request.Header.SessionID, request.Header.TreeID, request.FileId.Volatile);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_FILE_CLOSED));
            }

            if (!((FileSystemShare)share).HasReadAccess(session.SecurityContext, openFile.Path))
            {
                state.LogToServer(Severity.Verbose, "Query Directory on '{0}{1}' failed. User '{2}' was denied access.", share.Name, openFile.Path, session.UserName);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_ACCESS_DENIED));
            }

            FileSystemShare fileSystemShare = (FileSystemShare)share;

            FileID     fileID     = request.FileId;
            OpenSearch openSearch = session.GetOpenSearch(fileID);

            if (openSearch == null || request.Reopen)
            {
                if (request.Reopen)
                {
                    session.RemoveOpenSearch(fileID);
                }
                List <QueryDirectoryFileInformation> entries;
                NTStatus searchStatus = share.FileStore.QueryDirectory(out entries, openFile.Handle, request.FileName, request.FileInformationClass);
                if (searchStatus != NTStatus.STATUS_SUCCESS)
                {
                    state.LogToServer(Severity.Verbose, "Query Directory on '{0}{1}', Searched for '{2}', NTStatus: {3}", share.Name, openFile.Path, request.FileName, searchStatus.ToString());
                    return(new ErrorResponse(request.CommandName, searchStatus));
                }
                state.LogToServer(Severity.Information, "Query Directory on '{0}{1}', Searched for '{2}', found {3} matching entries", share.Name, openFile.Path, request.FileName, entries.Count);
                openSearch = session.AddOpenSearch(fileID, entries, 0);
            }

            if (request.Restart || request.Reopen)
            {
                openSearch.EnumerationLocation = 0;
            }

            if (openSearch.Entries.Count == 0)
            {
                // [MS-SMB2] If there are no entries to return [..] the server MUST fail the request with STATUS_NO_SUCH_FILE.
                session.RemoveOpenSearch(fileID);
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_NO_SUCH_FILE));
            }

            if (openSearch.EnumerationLocation == openSearch.Entries.Count)
            {
                return(new ErrorResponse(request.CommandName, NTStatus.STATUS_NO_MORE_FILES));
            }

            List <QueryDirectoryFileInformation> page = new List <QueryDirectoryFileInformation>();
            int pageLength = 0;

            for (int index = openSearch.EnumerationLocation; index < openSearch.Entries.Count; index++)
            {
                QueryDirectoryFileInformation fileInformation = openSearch.Entries[index];
                if (fileInformation.FileInformationClass != request.FileInformationClass)
                {
                    // We do not support changing FileInformationClass during a search (unless SMB2_REOPEN is set).
                    return(new ErrorResponse(request.CommandName, NTStatus.STATUS_INVALID_PARAMETER));
                }

                int entryLength = fileInformation.Length;
                if (pageLength + entryLength <= request.OutputBufferLength)
                {
                    page.Add(fileInformation);
                    int paddedLength = (int)Math.Ceiling((double)entryLength / 8) * 8;
                    pageLength += paddedLength;
                    openSearch.EnumerationLocation = index + 1;
                }
                else
                {
                    break;
                }

                if (request.ReturnSingleEntry)
                {
                    break;
                }
            }

            QueryDirectoryResponse response = new QueryDirectoryResponse();

            response.SetFileInformationList(page);
            return(response);
        }
コード例 #9
0
        void ReleaseDesignerOutlets()
        {
            if (ActionBar != null)
            {
                ActionBar.Dispose();
                ActionBar = null;
            }

            if (AddressOK != null)
            {
                AddressOK.Dispose();
                AddressOK = null;
            }

            if (BottomConstraint != null)
            {
                BottomConstraint.Dispose();
                BottomConstraint = null;
            }

            if (BottomSeparator != null)
            {
                BottomSeparator.Dispose();
                BottomSeparator = null;
            }

            if (DistanceFilters != null)
            {
                DistanceFilters.Dispose();
                DistanceFilters = null;
            }

            if (DistanceFiltersOpenClose != null)
            {
                DistanceFiltersOpenClose.Dispose();
                DistanceFiltersOpenClose = null;
            }

            if (DistanceLimit != null)
            {
                DistanceLimit.Dispose();
                DistanceLimit = null;
            }

            if (DistanceLimitInput != null)
            {
                DistanceLimitInput.Dispose();
                DistanceLimitInput = null;
            }

            if (DistanceSourceAddress != null)
            {
                DistanceSourceAddress.Dispose();
                DistanceSourceAddress = null;
            }

            if (DistanceSourceAddressLabel != null)
            {
                DistanceSourceAddressLabel.Dispose();
                DistanceSourceAddressLabel = null;
            }

            if (DistanceSourceAddressText != null)
            {
                DistanceSourceAddressText.Dispose();
                DistanceSourceAddressText = null;
            }

            if (DistanceSourceCurrent != null)
            {
                DistanceSourceCurrent.Dispose();
                DistanceSourceCurrent = null;
            }

            if (DistanceSourceCurrentLabel != null)
            {
                DistanceSourceCurrentLabel.Dispose();
                DistanceSourceCurrentLabel = null;
            }

            if (DistanceUnitText != null)
            {
                DistanceUnitText.Dispose();
                DistanceUnitText = null;
            }

            if (FilterLayout != null)
            {
                FilterLayout.Dispose();
                FilterLayout = null;
            }

            if (ListType != null)
            {
                ListType.Dispose();
                ListType = null;
            }

            if (ListView != null)
            {
                ListView.Dispose();
                ListView = null;
            }

            if (ListViewMap != null)
            {
                ListViewMap.Dispose();
                ListViewMap = null;
            }

            if (LoaderCircle != null)
            {
                LoaderCircle.Dispose();
                LoaderCircle = null;
            }

            if (LoaderCircleLeftConstraint != null)
            {
                LoaderCircleLeftConstraint.Dispose();
                LoaderCircleLeftConstraint = null;
            }

            if (LoadNext != null)
            {
                LoadNext.Dispose();
                LoadNext = null;
            }

            if (LoadPrevious != null)
            {
                LoadPrevious.Dispose();
                LoadPrevious = null;
            }

            if (MapSatellite != null)
            {
                MapSatellite.Dispose();
                MapSatellite = null;
            }

            if (MapStreet != null)
            {
                MapStreet.Dispose();
                MapStreet = null;
            }

            if (MapView != null)
            {
                MapView.Dispose();
                MapView = null;
            }

            if (MenuAbout != null)
            {
                MenuAbout.Dispose();
                MenuAbout = null;
            }

            if (MenuChatList != null)
            {
                MenuChatList.Dispose();
                MenuChatList = null;
            }

            if (MenuChatListBg != null)
            {
                MenuChatListBg.Dispose();
                MenuChatListBg = null;
            }

            if (MenuChatListBgCorner != null)
            {
                MenuChatListBgCorner.Dispose();
                MenuChatListBgCorner = null;
            }

            if (MenuContainer != null)
            {
                MenuContainer.Dispose();
                MenuContainer = null;
            }

            if (MenuHelpCenter != null)
            {
                MenuHelpCenter.Dispose();
                MenuHelpCenter = null;
            }

            if (MenuIcon != null)
            {
                MenuIcon.Dispose();
                MenuIcon = null;
            }

            if (MenuLayer != null)
            {
                MenuLayer.Dispose();
                MenuLayer = null;
            }

            if (MenuLocation != null)
            {
                MenuLocation.Dispose();
                MenuLocation = null;
            }

            if (MenuLogIn != null)
            {
                MenuLogIn.Dispose();
                MenuLogIn = null;
            }

            if (MenuLogOut != null)
            {
                MenuLogOut.Dispose();
                MenuLogOut = null;
            }

            if (MenuRegister != null)
            {
                MenuRegister.Dispose();
                MenuRegister = null;
            }

            if (MenuSettings != null)
            {
                MenuSettings.Dispose();
                MenuSettings = null;
            }

            if (NoResult != null)
            {
                NoResult.Dispose();
                NoResult = null;
            }

            if (OpenFilters != null)
            {
                OpenFilters.Dispose();
                OpenFilters = null;
            }

            if (OpenSearch != null)
            {
                OpenSearch.Dispose();
                OpenSearch = null;
            }

            if (OrderBy != null)
            {
                OrderBy.Dispose();
                OrderBy = null;
            }

            if (RefreshDistance != null)
            {
                RefreshDistance.Dispose();
                RefreshDistance = null;
            }

            if (ResultSet != null)
            {
                ResultSet.Dispose();
                ResultSet = null;
            }

            if (RippleMain != null)
            {
                RippleMain.Dispose();
                RippleMain = null;
            }

            if (RippleRefreshDistance != null)
            {
                RippleRefreshDistance.Dispose();
                RippleRefreshDistance = null;
            }

            if (RoundBottom != null)
            {
                RoundBottom.Dispose();
                RoundBottom = null;
            }

            if (SearchIn != null)
            {
                SearchIn.Dispose();
                SearchIn = null;
            }

            if (SearchLayout != null)
            {
                SearchLayout.Dispose();
                SearchLayout = null;
            }

            if (SearchTerm != null)
            {
                SearchTerm.Dispose();
                SearchTerm = null;
            }

            if (Snackbar != null)
            {
                Snackbar.Dispose();
                Snackbar = null;
            }

            if (SnackBottomConstraint != null)
            {
                SnackBottomConstraint.Dispose();
                SnackBottomConstraint = null;
            }

            if (SnackTopConstraint != null)
            {
                SnackTopConstraint.Dispose();
                SnackTopConstraint = null;
            }

            if (SortBy_LastActiveDate != null)
            {
                SortBy_LastActiveDate.Dispose();
                SortBy_LastActiveDate = null;
            }

            if (SortBy_RegisterDate != null)
            {
                SortBy_RegisterDate.Dispose();
                SortBy_RegisterDate = null;
            }

            if (SortBy_ResponseRate != null)
            {
                SortBy_ResponseRate.Dispose();
                SortBy_ResponseRate = null;
            }

            if (SortByCaption != null)
            {
                SortByCaption.Dispose();
                SortByCaption = null;
            }

            if (StatusBar != null)
            {
                StatusBar.Dispose();
                StatusBar = null;
            }

            if (StatusImage != null)
            {
                StatusImage.Dispose();
                StatusImage = null;
            }

            if (StatusText != null)
            {
                StatusText.Dispose();
                StatusText = null;
            }

            if (UseGeoContainer != null)
            {
                UseGeoContainer.Dispose();
                UseGeoContainer = null;
            }

            if (UseGeoNo != null)
            {
                UseGeoNo.Dispose();
                UseGeoNo = null;
            }

            if (UseGeoNoLabel != null)
            {
                UseGeoNoLabel.Dispose();
                UseGeoNoLabel = null;
            }

            if (UseGeoYes != null)
            {
                UseGeoYes.Dispose();
                UseGeoYes = null;
            }

            if (UseGeoYesLabel != null)
            {
                UseGeoYesLabel.Dispose();
                UseGeoYesLabel = null;
            }

            if (UserSearchList != null)
            {
                UserSearchList.Dispose();
                UserSearchList = null;
            }
        }