Esempio n. 1
0
        private bool ProcessCssFile(IRequestInfo info, string localPath)
        {
            // BL-2219: "OriginalImages" means we're generating a pdf and want full images,
            // but it has nothing to do with css files and defeats the following 'if'
            localPath = localPath.Replace(OriginalImageMarker + "/", "");
            // is this request the full path to a real file?
            if (RobustFile.Exists(localPath) && Path.IsPathRooted(localPath))
            {
                // Typically this will be files in the book or collection directory, since the browser
                // is supplying the path.

                // currently this only applies to settingsCollectionStyles.css, and customCollectionStyles.css
                var cssFile = Path.GetFileName(localPath);
                if ((cssFile == "settingsCollectionStyles.css") || (cssFile == "customCollectionStyles.css"))
                {
                    info.ContentType = "text/css";
                    info.ReplyWithFileContent(localPath);
                    return(true);
                }
            }

            // if not a full path, try to find the correct file
            var fileName = Path.GetFileName(localPath);

            // try to find the css file in the xmatter and templates
            if (_fileLocator == null)
            {
                _fileLocator = Program.OptimizedFileLocator;
            }
            var path = _fileLocator.LocateFile(fileName);

            // if still not found, and localPath is an actual file path, use it
            if (string.IsNullOrEmpty(path) && RobustFile.Exists(localPath))
            {
                path = localPath;
            }

            if (string.IsNullOrEmpty(path))
            {
                // it's just possible we need to add BloomBrowserUI to the path (in the case of the AddPage dialog)
                var lastTry = FileLocator.GetFileDistributedWithApplication(true, BloomFileLocator.BrowserRoot, localPath);
                if (RobustFile.Exists(lastTry))
                {
                    path = lastTry;
                }
            }

            // return false if the file was not found
            if (string.IsNullOrEmpty(path))
            {
                return(false);
            }

            info.ContentType = "text/css";
            info.ReplyWithFileContent(path);
            return(true);
        }
Esempio n. 2
0
        protected override bool ProcessRequest(IRequestInfo info)
        {
            if (base.ProcessRequest(info))
            {
                return(true);
            }

            var          r = CorrectedLocalPath(info);
            const string slashBloomSlash = "/bloom/";

            if (r.StartsWith(slashBloomSlash))
            {
                r = r.Substring(slashBloomSlash.Length);
            }
            r = r.Replace("library/", "");
            if (r.Contains("libraryContents"))
            {
                GetLibraryBooks(info);
            }
            else if (r == "libraryName")
            {
                info.WriteCompleteOutput(_collectionSettings.CollectionName + " Library");
            }
            else if (r.Contains("SourceCollectionsList"))
            {
                GetStoreBooks(info);
            }
            else if (r.StartsWith("thumbnails/"))
            {
                r = r.Replace("thumbnails/", "");
                r = r.Replace("%5C", "/");
                r = r.Replace("%20", " ");
                if (File.Exists(r))
                {
                    info.ReplyWithImage(r);
                }
            }
            else if (r.EndsWith(".png") && r.Contains("thumbnail"))
            {
                r = r.Replace("thumbnail", "");
                //if (r.Contains("thumb"))
                {
                    if (File.Exists(r))
                    {
                        info.ReplyWithImage(r);
                    }
                    else
                    {
                        var imgPath = BloomFileLocator.GetBrowserFile("book.png");
                        info.ReplyWithImage(imgPath);
                        //book.GetThumbNailOfBookCoverAsync(book.Type != Book.Book.BookType.Publication,image => RefreshOneThumbnail(book, image));
                    }
                }
//				else
//				{
//					var imgPath = FileLocator.GetFileDistributedWithApplication("root", "ui", "book.png");
//					info.ReplyWithImage(imgPath);
//				}
            }
            else
            {
                info.ContentType = GetContentType(Path.GetExtension(r));
                string path = BloomFileLocator.GetBrowserFile(r);


                //request.QueryString.GetValues()
                info.ReplyWithFileContent(path);
            }
            return(true);
        }
Esempio n. 3
0
 private static void ReplyWithFileContentAndType(IRequestInfo info, string path)
 {
     info.ContentType = GetContentType(Path.GetExtension(path));
     info.ReplyWithFileContent(path);
 }
        private bool ProcessCssFile(IRequestInfo info, string localPath)
        {
            // BL-2219: "OriginalImages" means we're generating a pdf and want full images,
            // but it has nothing to do with css files and defeats the following 'if'
            localPath = localPath.Replace("OriginalImages/", "");
            // is this request the full path to a real file?
            if (RobustFile.Exists(localPath) && Path.IsPathRooted(localPath))
            {
                // Typically this will be files in the book or collection directory, since the browser
                // is supplying the path.

                // currently this only applies to settingsCollectionStyles.css, and customCollectionStyles.css
                var cssFile = Path.GetFileName(localPath);
                if ((cssFile == "settingsCollectionStyles.css") || (cssFile == "customCollectionStyles.css"))
                {
                    info.ContentType = "text/css";
                    info.ReplyWithFileContent(localPath);
                    return true;
                }
            }

            // if not a full path, try to find the correct file
            var fileName = Path.GetFileName(localPath);

            // try to find the css file in the xmatter and templates
            if (_fileLocator == null)
            {
                _fileLocator = Program.OptimizedFileLocator;
            }
            var path = _fileLocator.LocateFile(fileName);

            // if still not found, and localPath is an actual file path, use it
            if (string.IsNullOrEmpty(path) && RobustFile.Exists(localPath)) path = localPath;

            if (string.IsNullOrEmpty(path))
            {
                // it's just possible we need to add BloomBrowserUI to the path (in the case of the AddPage dialog)
                var lastTry = FileLocator.GetFileDistributedWithApplication(true, BloomFileLocator.BrowserRoot, localPath);
                if(RobustFile.Exists(lastTry)) path = lastTry;
            }

            // return false if the file was not found
            if (string.IsNullOrEmpty(path)) return false;

            info.ContentType = "text/css";
            info.ReplyWithFileContent(path);
            return true;
        }
Esempio n. 5
0
        private bool ProcessAnyFileContent(IRequestInfo info, string localPath)
        {
            string modPath = localPath;
            string path    = null;
            // When JavaScript inserts our path into the html it replaces the three magic html characters with these substitutes.
            // We need to convert back in order to match our key. Then, reverse the change we made to deal with quotation marks.
            string tempPath = UnescapeUrlQuotes(modPath.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&"));

            if (RobustFile.Exists(tempPath))
            {
                modPath = tempPath;
            }
            try
            {
                if (localPath.Contains("favicon.ico"))                 //need something to pacify Chrome
                {
                    path = FileLocator.GetFileDistributedWithApplication("BloomPack.ico");
                }

                // Is this request the full path to an image file? For most images, we just have the filename. However, in at
                // least one use case, the image we want isn't in the folder of the PDF we're looking at. That case is when
                // we are looking at a "folio", a book that gathers up other books into one big PDF. In that case, we want
                // to find the image in the correct book folder.  See AddChildBookContentsToFolio();
                var possibleFullImagePath = localPath;
                // "OriginalImages/" at the beginning means we're generating a pdf and want full images,
                // but it has nothing to do with the actual file location.
                if (localPath.StartsWith(OriginalImageMarker + "/"))
                {
                    possibleFullImagePath = localPath.Substring(15);
                }
                if (RobustFile.Exists(possibleFullImagePath) && Path.IsPathRooted(possibleFullImagePath))
                {
                    path = possibleFullImagePath;
                }
                else
                {
                    // Surprisingly, this method will return localPath unmodified if it is a fully rooted path
                    // (like C:\... or \\localhost\C$\...) to a file that exists. So this execution path
                    // can return contents of any file that exists if the URL gives its full path...even ones that
                    // are generated temp files most certainly NOT distributed with the application.
                    path = FileLocator.GetFileDistributedWithApplication(BloomFileLocator.BrowserRoot, modPath);
                }
            }
            catch (ApplicationException e)
            {
                // Might be from GetFileDistributedWithApplication above, but we could be checking templates that
                // are NOT distributed with the application.
                // Otherwise ignore. Assume this means that this class/method cannot serve that request,
                // but something else may.
                if (e.Message.StartsWith("Could not locate the required file"))
                {
                    // LocateFile includes userInstalledSearchPaths (e.g. a shortcut to a collection in a non-standard location)
                    path = BloomFileLocator.sTheMostRecentBloomFileLocator.LocateFile(localPath);
                }
            }

            //There's probably a eventual way to make this problem go away,
            // but at the moment FF, looking for source maps to go with css, is
            // looking for those maps where we said the css was, which is in the actual
            // book folders. So instead redirect to our browser file folder.
            if (string.IsNullOrEmpty(path) || !RobustFile.Exists(path))
            {
                var startOfBookLayout = localPath.IndexOf("bookLayout");
                if (startOfBookLayout > 0)
                {
                    path = BloomFileLocator.GetBrowserFile(localPath.Substring(startOfBookLayout));
                }
                var startOfBookEdit = localPath.IndexOf("bookEdit");
                if (startOfBookEdit > 0)
                {
                    path = BloomFileLocator.GetBrowserFile(localPath.Substring(startOfBookEdit));
                }
            }

            if (!RobustFile.Exists(path) && localPath.StartsWith("pageChooser/") && IsImageTypeThatCanBeReturned(localPath))
            {
                // if we're in the page chooser dialog and looking for a thumbnail representing an image in a
                // template page, look for that thumbnail in the book that is the template source,
                // rather than in the folder that stores the page choose dialog HTML and code.
                var templateBook = _bookSelection.CurrentSelection.FindTemplateBook();
                if (templateBook != null)
                {
                    var pathMinusPrefix = localPath.Substring("pageChooser/".Length);
                    var templatePath    = Path.Combine(templateBook.FolderPath, pathMinusPrefix);
                    if (RobustFile.Exists(templatePath))
                    {
                        info.ReplyWithImage(templatePath);
                        return(true);
                    }
                    // Might be a page from a different template than the one we based this book on
                    path = BloomFileLocator.sTheMostRecentBloomFileLocator.LocateFile(pathMinusPrefix);
                    if (!string.IsNullOrEmpty(path))
                    {
                        info.ReplyWithImage(path);
                        return(true);
                    }
                }
            }
            // Use '%25' to detect that the % in a Url encoded character (for example space encoded as %20) was encoded as %25.
            // In this example we would have %2520 in info.RawUrl and %20 in localPath instead of a space.  Note that if an
            // image has a % in the filename, like 'The other 50%', and it isn't doubly encoded, then this shouldn't be a
            // problem because we're triggering here only if the file isn't found.
            if (!RobustFile.Exists(localPath) && info.RawUrl.Contains("%25"))
            {
                // possibly doubly encoded?  decode one more time and try.  See https://silbloom.myjetbrains.com/youtrack/issue/BL-3835.
                // Some existing books have somehow acquired Url encoded coverImage data like the following:
                // <div data-book="coverImage" lang="*">
                //     The%20Moon%20and%20The%20Cap_Cover.png
                // </div>
                // This leads to data being stored doubly encoded in the program's run-time data.  The coverImage data is supposed to be
                // Html/Xml encoded (using &), not Url encoded (using %).
                path = System.Web.HttpUtility.UrlDecode(localPath);
            }
            if (!RobustFile.Exists(path) && IsImageTypeThatCanBeReturned(localPath))
            {
                // last resort...maybe we are in the process of renaming a book (BL-3345) and something mysteriously is still using
                // the old path. For example, I can't figure out what hangs on to the old path when an image is changed after
                // altering the main book title.
                var currentFolderPath = Path.Combine(_bookSelection.CurrentSelection.FolderPath, Path.GetFileName(localPath));
                if (RobustFile.Exists(currentFolderPath))
                {
                    info.ReplyWithImage(currentFolderPath);
                    return(true);
                }
            }

            if (!RobustFile.Exists(path))
            {
                // On developer machines, we can lose part of path earlier.  Try one more thing.
                path = info.LocalPathWithoutQuery.Substring(7);                 // skip leading "/bloom/");
            }
            if (!RobustFile.Exists(path))
            {
                ReportMissingFile(localPath, path);
                return(false);
            }
            info.ContentType = GetContentType(Path.GetExtension(modPath));
            info.ReplyWithFileContent(path);
            return(true);
        }
        private bool ProcessAnyFileContent(IRequestInfo info, string localPath)
        {
            string modPath = localPath;
            string path = null;
            // When JavaScript inserts our path into the html it replaces the three magic html characters with these substitutes.
            // We need to convert back in order to match our key. Then, reverse the change we made to deal with quotation marks.
            string tempPath = UnescapeUrlQuotes(modPath.Replace("&lt;", "<").Replace("&gt;", ">").Replace("&amp;", "&"));
            if (RobustFile.Exists(tempPath))
                modPath = tempPath;
            try
            {
                if (localPath.Contains("favicon.ico")) //need something to pacify Chrome
                    path = FileLocator.GetFileDistributedWithApplication("BloomPack.ico");

                // Is this request the full path to an image file? For most images, we just have the filename. However, in at
                // least one use case, the image we want isn't in the folder of the PDF we're looking at. That case is when
                // we are looking at a "folio", a book that gathers up other books into one big PDF. In that case, we want
                // to find the image in the correct book folder.  See AddChildBookContentsToFolio();
                var possibleFullImagePath = localPath;
                // "OriginalImages/" at the beginning means we're generating a pdf and want full images,
                // but it has nothing to do with the actual file location.
                if (localPath.StartsWith("OriginalImages/"))
                    possibleFullImagePath = localPath.Substring(15);
                if(RobustFile.Exists(possibleFullImagePath) && Path.IsPathRooted(possibleFullImagePath))
                {
                    path = possibleFullImagePath;
                }
                else
                {
                    // Surprisingly, this method will return localPath unmodified if it is a fully rooted path
                    // (like C:\... or \\localhost\C$\...) to a file that exists. So this execution path
                    // can return contents of any file that exists if the URL gives its full path...even ones that
                    // are generated temp files most certainly NOT distributed with the application.
                    path = FileLocator.GetFileDistributedWithApplication(BloomFileLocator.BrowserRoot, modPath);
                }
            }
            catch (ApplicationException)
            {
                // ignore. Assume this means that this class/method cannot serve that request, but something else may.
            }

            //There's probably a eventual way to make this problem go away,
            // but at the moment FF, looking for source maps to go with css, is
            // looking for those maps where we said the css was, which is in the actual
            // book folders. So instead redirect to our browser file folder.
            if (string.IsNullOrEmpty(path) || !RobustFile.Exists(path))
            {
                var startOfBookLayout = localPath.IndexOf("bookLayout");
                if (startOfBookLayout > 0)
                    path = BloomFileLocator.GetBrowserFile(localPath.Substring(startOfBookLayout));
                var startOfBookEdit = localPath.IndexOf("bookEdit");
                if (startOfBookEdit > 0)
                    path = BloomFileLocator.GetBrowserFile(localPath.Substring(startOfBookEdit));
            }

            if (!RobustFile.Exists(path) && localPath.StartsWith("pageChooser/") && IsImageTypeThatCanBeReturned(localPath))
            {
                // if we're in the page chooser dialog and looking for a thumbnail representing an image in a
                // template page, look for that thumbnail in the book that is the template source,
                // rather than in the folder that stores the page choose dialog HTML and code.
                var templatePath = Path.Combine(_bookSelection.CurrentSelection.FindTemplateBook().FolderPath,
                    localPath.Substring("pageChooser/".Length));
                if (RobustFile.Exists(templatePath))
                {
                    info.ReplyWithImage(templatePath);
                    return true;
                }
            }
            // Use '%25' to detect that the % in a Url encoded character (for example space encoded as %20) was encoded as %25.
            // In this example we would have %2520 in info.RawUrl and %20 in localPath instead of a space.  Note that if an
            // image has a % in the filename, like 'The other 50%', and it isn't doubly encoded, then this shouldn't be a
            // problem because we're triggering here only if the file isn't found.
            if (!RobustFile.Exists(localPath) && info.RawUrl.Contains("%25"))
            {
                // possibly doubly encoded?  decode one more time and try.  See https://silbloom.myjetbrains.com/youtrack/issue/BL-3835.
                // Some existing books have somehow acquired Url encoded coverImage data like the following:
                // <div data-book="coverImage" lang="*">
                //     The%20Moon%20and%20The%20Cap_Cover.png
                // </div>
                // This leads to data being stored doubly encoded in the program's run-time data.  The coverImage data is supposed to be
                // Html/Xml encoded (using &), not Url encoded (using %).
                path = System.Web.HttpUtility.UrlDecode(localPath);
            }
            if (!RobustFile.Exists(path) && IsImageTypeThatCanBeReturned(localPath))
            {
                // last resort...maybe we are in the process of renaming a book (BL-3345) and something mysteriously is still using
                // the old path. For example, I can't figure out what hangs on to the old path when an image is changed after
                // altering the main book title.
                var currentFolderPath = Path.Combine(_bookSelection.CurrentSelection.FolderPath, Path.GetFileName(localPath));
                if (RobustFile.Exists(currentFolderPath))
                {
                    info.ReplyWithImage(currentFolderPath);
                    return true;
                }
            }

            if (!RobustFile.Exists(path))
            {
                // On developer machines, we can lose part of path earlier.  Try one more thing.
                path = info.LocalPathWithoutQuery.Substring(7); // skip leading "/bloom/");
            }
            if (!File.Exists(path))
            {
                ReportMissingFile(localPath,path);
                return false;
            }
            info.ContentType = GetContentType(Path.GetExtension(modPath));
            info.ReplyWithFileContent(path);
            return true;
        }
 private static void ReplyWithFileContentAndType(IRequestInfo info, string path)
 {
     info.ContentType = GetContentType(Path.GetExtension(path));
     info.ReplyWithFileContent(path);
 }
Esempio n. 8
0
        protected override bool ProcessRequest(IRequestInfo info)
        {
            if (base.ProcessRequest(info))
                return true;

            var r = CorrectedLocalPath(info);
            const string slashBloomSlash = "/bloom/";
            if (r.StartsWith(slashBloomSlash))
                r = r.Substring(slashBloomSlash.Length);
            r = r.Replace("library/", "");
            if (r.Contains("libraryContents"))
            {
                GetLibraryBooks(info);
            }
            else if (r == "libraryName")
            {
                info.WriteCompleteOutput(_collectionSettings.CollectionName + " Library");
            }
            else if (r.Contains("SourceCollectionsList"))
            {
                GetStoreBooks(info);
            }
            else if(r.StartsWith("thumbnails/"))
            {
                r = r.Replace("thumbnails/", "");
                r = r.Replace("%5C", "/");
                r = r.Replace("%20", " ");
                if (File.Exists(r))
                {
                    info.ReplyWithImage(r);
                }
            }
            else if (r.EndsWith(".png") && r.Contains("thumbnail"))
            {
                r = r.Replace("thumbnail", "");
                //if (r.Contains("thumb"))
                {
                    if (File.Exists(r))
                    {
                        info.ReplyWithImage(r);
                    }
                    else
                    {
                        var imgPath = BloomFileLocator.GetBrowserFile("book.png");
                        info.ReplyWithImage(imgPath);
                        //book.GetThumbNailOfBookCoverAsync(book.Type != Book.Book.BookType.Publication,image => RefreshOneThumbnail(book, image));
                    }
                }
            //				else
            //				{
            //					var imgPath = FileLocator.GetFileDistributedWithApplication("root", "ui", "book.png");
            //					info.ReplyWithImage(imgPath);
            //				}
            }
            else
            {
                info.ContentType = GetContentType(Path.GetExtension(r));
                string path = BloomFileLocator.GetBrowserFile(r);

                //request.QueryString.GetValues()
                info.ReplyWithFileContent(path);
            }
            return true;
        }
Esempio n. 9
0
 public void ReplyWithAudioFileContents(string path)
 {
     _requestInfo.ResponseContentType = path.EndsWith(".mp3") ? "audio/mpeg" : "audio/wav";
     _requestInfo.ReplyWithFileContent(path);
 }
		// Every path should return false or send a response.
		// Otherwise we can get a timeout error as the browser waits for a response.
		protected override bool ProcessRequest(IRequestInfo info)
		{
			if (base.ProcessRequest(info))
				return true;

			var localPath = GetLocalPathWithoutQuery(info);

			// routing
			if (localPath.StartsWith("readers/"))
			{
				if (ReadersHandler.HandleRequest(localPath, info, CurrentCollectionSettings))
					return true;
			}
			else if (localPath.StartsWith("i18n/"))
			{
				if (I18NHandler.HandleRequest(localPath, info, CurrentCollectionSettings))
					return true;
			}
			else if (localPath.StartsWith("directoryWatcher/"))
			{
				var dirName = info.GetPostData()["dir"];

				if (dirName == "Sample Texts")
				{
					if (CheckForSampleTextChanges(info))
						return true;
				}

				return false;
			}
			else if (localPath.StartsWith("leveledRTInfo/"))
			{
				var queryPart = string.Empty;
				if (info.RawUrl.Contains("?"))
					queryPart = "#" + info.RawUrl.Split('?')[1];
				var langCode = LocalizationManager.UILanguageId;
				var completeEnglishPath = FileLocator.GetFileDistributedWithApplication(localPath);
				var completeUiLangPath = GetUiLanguageFileVersion(completeEnglishPath, langCode);
				string url;
				if (langCode != "en" && File.Exists(completeUiLangPath))
					url = completeUiLangPath;
				else
					url = completeEnglishPath;
				var cleanUrl = url.Replace("\\", "/"); // allows jump to file to work

				string browser = string.Empty;
				if (Palaso.PlatformUtilities.Platform.IsLinux)
				{
					// REVIEW: This opens HTML files in the browser. Do we have any non-html
					// files that this code needs to open in the browser? Currently they get
					// opened in whatever application the user has selected for that file type
					// which might well be an editor.
					browser = "xdg-open";
				}
				else
				{
					// If we don't provide the path of the browser, i.e. Process.Start(url + queryPart), we get file not found exception.
					// If we prepend "file:///", the anchor part of the link (#xxx) is not sent unless we provide the browser path too.
					// This is the same behavior when simply typing a url into the Run command on Windows.
					// If we fail to get the browser path for some reason, we still load the page, just without navigating to the anchor.
					string defaultBrowserPath;
					if (TryGetDefaultBrowserPath(out defaultBrowserPath))
					{
						browser = defaultBrowserPath;
					}
				}

				if (!string.IsNullOrEmpty(browser))
				{
					try
					{
						Process.Start(browser, "\"file:///" + cleanUrl + queryPart + "\"");
						return false;
					}
					catch (Exception)
					{
						Debug.Fail("Jumping to browser with anchor failed.");
						// Don't crash Bloom because we can't open an external file.
					}
				}

				// If the above failed, either for lack of default browser or exception, try this:
				Process.Start("\"" + cleanUrl + "\"");
				return false;
			}

			switch (localPath)
			{
				case "currentPageContent":
					info.ContentType = "text/html";
					info.WriteCompleteOutput(CurrentPageContent ?? "");
					return true;

				case "accordionContent":
					info.ContentType = "text/html";
					info.WriteCompleteOutput(AccordionContent ?? "");
					return true;

				case "availableFontNames":
					InstalledFontCollection installedFontCollection = new InstalledFontCollection();
					info.WriteCompleteOutput(string.Join(",", installedFontCollection.Families.Select(f => f.Name)));
					return true;

				case "help":
					var post = info.GetPostData();
					HelpLauncher.Show(null, post["data"]);
					return true;

				case "getNextBookStyle":
					info.ContentType = "text/html";
					info.WriteCompleteOutput(CurrentBook.NextStyleNumber.ToString(CultureInfo.InvariantCulture));
					return true;
			}

			string path = null;
			try
			{
				path = FileLocator.GetFileDistributedWithApplication("BloomBrowserUI", localPath);
			}
			catch (ApplicationException)
			{
				// ignore
			}

			if (!File.Exists(path)) return false;

			info.ContentType = GetContentType(Path.GetExtension(localPath));
			info.ReplyWithFileContent(path);
			return true;
		}