/// <summary>
        /// Создаётся HttpListener, после чего заполняются его .Prefixes ссылками на директории.
        /// </summary>
        /// <returns></returns>
        private HttpListener GetConfiguredListener()
        {
            HttpListener httpListener = new HttpListener();

            // Добавляем url верхнего уровня в список префиксов.
            foreach (string url in uriHelper.UrlBeginings)
            {
                httpListener.Prefixes.Add(String.Format("{0}/", url));
            }

            // Ищем только директории, содержание файлы *.html, после чего меняем разделитель с '\' на '/'.
            List <string> prefixes = DirectoryWorker.GetDirectoriesWithDotHTML();

            prefixes = HttpUriHelper.ChangeSeparatorToUrlLike(prefixes);

            // Добавляем отобранные директории к url верхнего уровня и закидываем в список префиксов.
            foreach (string path in prefixes)
            {
                foreach (string startUrl in uriHelper.UrlBeginings)
                {
                    httpListener.Prefixes.Add(String.Format("{0}{1}", startUrl, path));
                }
            }

            // Вывод всех добавленных префиксов
            this.PrintPrefixes(httpListener);

            return(httpListener);
        }
Exemple #2
0
        /// <summary>
        /// Отправка ответа на запрос; это может быть что угодно: картинка, html-файл, js-файл, css-файл.
        /// </summary>
        /// <param name="context"></param>
        private void SendResponce(HttpListenerContext context)
        {
            string needPath = context.Request.RawUrl;

            // Частный случай запроса - когда не пишется конкретный html файл.
            if (needPath.EndsWith(HttpUriHelper.UrlPathChar))
            {
                needPath = String.Format("{0}index.html", needPath);
            }

            needPath = HttpUriHelper.ChangeUrlLikeToSeparator(needPath);

            // Получение и проверка данных по указанной дирректории.
            byte[] file = DirectoryWorker.filebuffer.GetValueByKey(needPath);
            if (file == null)
            {
                //ConsoleColorPrinter.WriteLine($"Can not find file for responce by way [{needPath}]", ConsoleColor.DarkGreen);
                logger.Warn($"Can not find file for responce by way [{needPath}]");
                return;
            }

            // Отправка запроса
            //ConsoleColorPrinter.WriteLine($"Responcing file by way [{needPath}]", ConsoleColor.DarkGreen);
            logger.Info($"Responcing file by way [{needPath}]");
            HttpListenerResponse response = context.Response;
            Stream output = response.OutputStream;

            output.Write(file, 0, file.Length);
            output.Close();
            response.Close();
        }
 /// <summary>
 /// Handles the submission of an URL by the user
 /// Will validate and sanitize said URL or prompt an error dialog
 /// </summary>
 /// <param name="sender">Not important</param>
 /// <param name="e">Contains the URL to submit</param>
 public void UrlInputFormSubmittedEventHandler(object sender, UrlSentEventArgs e)
 {
     if (HttpUriHelper.TryCreateHttpUri(e.Url, out Uri uri))
     {
         this.UrlInputFormSubmittedEvent(this, new UrlSentEventArgs(uri));
     }
     else
     {
         this.view.ErrorDialog("The URL was incorrect. Please input a valid URL.");
     }
 }
 /// <summary>
 /// Tests the provided URL and either enables the submission controls or orders to prompt an error
 /// </summary>
 /// <param name="sender">Not important</param>
 /// <param name="e">Contains the URL to validate</param>
 public void UrlSentEventHandler(object sender, UrlSentEventArgs e)
 {
     if (HttpUriHelper.TryCreateHttpUri(e.Url, out Uri uri))
     {
         this.view.UpdateUrl(uri.AbsoluteUri);
     }
     else
     {
         this.view.ErrorDialog("Please input a valid URL.");
     }
 }
        /* ==================================
         * INTERNAL METHODS
         * ==================================*/

        /// <summary>
        /// Handles to user's request to test an URL
        /// Will validate said URL and update the view in consequence
        /// </summary>
        /// <param name="sender">Not important</param>
        /// <param name="e">Contains the URL to test</param>
        public void UrlSentEventHandler(object sender, UrlSentEventArgs e)
        {
            if (HttpUriHelper.TryCreateHttpUri(e.Url, out Uri uri))
            {
                this.view.UpdateUrl(uri.AbsoluteUri);
                this.view.SetUrlFeedback("The URL has been sucessfully verified !");
            }
            else
            {
                this.view.SetUrlFeedback("Please input a valid URL.");
            }
        }
Exemple #6
0
        /// <summary>
        /// Asks to load a page
        /// Will sanitize the provided URI before calling the next method
        /// </summary>
        /// <param name="sender">Arguments containing the target URL</param>
        /// <param name="e">Empty</param>
        private async void UrlQueriedEventHandlerAsync(object sender, UrlSentEventArgs e)
        {
            if (HttpUriHelper.TryCreateHttpUri(e.Url, out Uri uri))
            {
                HttpQuery query = new HttpQuery(uri);
                this.AddToHistory(query);

                await Task.Factory.StartNew(() => this.LoadPageAsync(query));
            }
            else
            {
                this.view.ErrorDialog("Invalid URL");
            }
        }
        public HttpServer(string ip, int port, DirectoryInfo directory)
        {
            this.IP   = ip;
            this.Port = port;
            uriHelper = new HttpUriHelper(ip, port);

            // Настроим логгер
            this.LoadLogger();

            // Настройка буффера и анализатора дирректории
            this.DirectoryWorker = new DirectoryAnalyser(directory);

            // Добавим обработчик события создания нового файла
            this.DirectoryWorker.NotifyAboutCreate += OnNewFile;

            // Добавим обработчик события удаления файла
            this.DirectoryWorker.NotifyAboutDelete += OnDeleteFile;
        }
 /// <summary>
 /// Validates the URL one last time, checks if the submitted <see cref="Fav"/> already exists in the repository
 /// Then raises a <see cref="FavInputSubmittedEvent"/>
 /// </summary>
 /// <param name="sender">Not important</param>
 /// <param name="e">Contains the <see cref="Fav"/> to add</param>
 public void FavInputSubmittedEventHandler(object sender, FavSubmittedEventArgs e)
 {
     if (HttpUriHelper.TryCreateHttpUri(e.Uri, out Uri uri))
     {
         try
         {
             if (this.mode == InputFavMode.MODIFICATION)
             {
                 this.favorites.Remove(this.toEdit);
             }
             this.favorites.Add(new Fav(uri, e.Name));
             this.FavInputSubmittedEvent(this, EventArgs.Empty);
             this.view.Close();
         } catch (FavAlreadyExistsException)
         {
             this.view.ErrorDialog("There is already a favorite with these name and URL.");
         }
     }
     else
     {
         this.view.ErrorDialog("Please input a valid URL.");
     }
 }