예제 #1
0
 /// <summary>
 /// Populates the page with content passed during navigation.  Any saved state is also
 /// provided when recreating a page from a prior session.
 /// </summary>
 /// <param name="sender">
 /// The source of the event; typically <see cref="NavigationHelper"/>
 /// </param>
 /// <param name="e">Event data that provides both the navigation parameter passed to
 /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested and
 /// a dictionary of state preserved by this page during an earlier
 /// session.  The state will be null the first time a page is visited.</param>
 private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
 {
     var jsonObjectString = (string) e.NavigationParameter;
     _forumThread = JsonConvert.DeserializeObject<ForumThreadEntity>(jsonObjectString);
     if (_forumThread == null) return;
     _vm.GetForumPosts(_forumThread);
 }
예제 #2
0
        public async Task<HtmlDocument> GetThread(ForumThreadEntity forumThread, string url)
        {
            WebManager.Result result = await _webManager.GetData(url);
            HtmlDocument doc = result.Document;
            try
            {
                forumThread.ParseFromThread(doc);
            }
            catch (Exception)
            {
                return null;
            }
            string responseUri = result.AbsoluteUri;
            string[] test = responseUri.Split('#');
            if (test.Length > 1 && test[1].Contains("pti"))
            {
                forumThread.ScrollToPost = Int32.Parse(Regex.Match(responseUri.Split('#')[1], @"\d+").Value) - 1;
                forumThread.ScrollToPostString = string.Concat("#", responseUri.Split('#')[1]);
            }

            var query = Extensions.ParseQueryString(url);

            if (!query.ContainsKey("postid")) return doc;

            // If we are going to a post, it won't use #pti but instead uses the post id.

            forumThread.ScrollToPost = Convert.ToInt32(query["postid"]);
            forumThread.ScrollToPostString = "#postId" + query["postid"];
            return doc;

        }
예제 #3
0
        /// <summary>
        ///     Populates the page with content passed during navigation. Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        ///     The source of the event; typically <see cref="NavigationHelper" />
        /// </param>
        /// <param name="e">
        ///     Event data that provides both the navigation parameter passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
        ///     a dictionary of state preserved by this page during an earlier
        ///     session. The state will be null the first time a page is visited.
        /// </param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            loadingProgressBar.Visibility = Visibility.Visible;
            _forumThread = (ForumThreadEntity) e.NavigationParameter;
            pageTitle.Text = _forumThread.Name;

            _threadPosts = await _postManager.GetThreadPosts(_forumThread);
            CurrentPageSelector.ItemsSource = Enumerable.Range(1, _forumThread.TotalPages).ToArray();
            CurrentPageSelector.SelectedValue = _forumThread.CurrentPage;
            BackButton.IsEnabled = _forumThread.CurrentPage > 1;
            ForwardButton.IsEnabled = _forumThread.TotalPages != _forumThread.CurrentPage;
            ReplyButton.IsEnabled = !_forumThread.IsLocked;
            DefaultViewModel["Posts"] = _threadPosts;
            if (_forumThread.ScrollToPost > 0)
            {

                ThreadListFullScreen.ScrollIntoView(_threadPosts[_forumThread.ScrollToPost]);
            }
            loadingProgressBar.Visibility = Visibility.Collapsed;

            // TODO: Remove duplicate buttons and find a better way to handle navigation
            BackButtonSnap.IsEnabled = _forumThread.CurrentPage > 1;
            ForwardButtonSnap.IsEnabled = _forumThread.TotalPages != _forumThread.CurrentPage;
            CurrentPageSelectorSnap.ItemsSource = Enumerable.Range(1, _forumThread.TotalPages).ToArray();
            CurrentPageSelectorSnap.SelectedValue = _forumThread.CurrentPage;
        }
예제 #4
0
        public static async Task<string> FormatThreadHtml(ForumThreadEntity forumThreadEntity )
        {
            ObservableCollection<ForumPostEntity> postEntities = forumThreadEntity.ForumPosts;
            string html = await PathIO.ReadTextAsync("ms-appx:///Assets/thread.html");

            var doc2 = new HtmlDocument();

            doc2.LoadHtml(html);

            
            HtmlNode head = doc2.DocumentNode.Descendants("head").FirstOrDefault();

            switch (forumThreadEntity.ForumId)
            {
                case 219:
                    head.InnerHtml += "<link href=\"ms-appx-web:///Assets/219.css\" type=\"text/css\" media=\"all\" rel=\"stylesheet\">";
                    break;
                case 26:
                    break;

            }

            HtmlNode bodyNode = doc2.DocumentNode.Descendants("body").FirstOrDefault();

            string threadHtml = string.Empty;
            int seenCount = 1;
            if (postEntities == null) return WebUtility.HtmlDecode(WebUtility.HtmlDecode(doc2.DocumentNode.OuterHtml)) ;
            for (int index = 0; index < postEntities.Count; index++)
            {
                ForumPostEntity post = postEntities[index];
                if (seenCount > 2)
                    seenCount = 1;
                string hasSeen = post.HasSeen ? string.Concat("seen", seenCount) : string.Concat("postCount", seenCount);
                seenCount++;
                string userAvatar = string.Empty;
                if (!string.IsNullOrEmpty(post.User.AvatarLink))
                    userAvatar = string.Concat("<img src=\"", post.User.AvatarLink,
                        "\" alt=\"\" class=\"av\" border=\"0\">");
                string username =
                    string.Format(
                        "<h2 class=\"text article-title win-type-ellipsis\"><span class=\"author\">{0}</span><h2>",
                        post.User.Username);
                string postData =
                    string.Format(
                        "<h4 class=\"text article-title win-type-ellipsis\"><span class=\"registered\">{0}</span><h4>",
                        post.PostDate);
                string postBody = string.Format("<div class=\"postbody\">{0}</div>", post.PostHtml);
                string userInfo = string.Format("<div class=\"userinfo\">{0}{1}</div>", username, postData);
                string postButtons = CreateButtons(post);

                string footer = string.Format("<tr class=\"postbar\"><td class=\"postlinks\">{0}</td></tr>", postButtons);
                threadHtml +=
                    string.Format(
                        "<div class={6} id={4}><div id={5}><div id=\"threadView\"><header>{0}{1}</header><article><div class=\"article-content\">{2}</div></article><footer>{3}</footer></div></div></div>",
                        userAvatar, userInfo, postBody, footer, string.Concat("\"pti", index + 1, "\""), string.Concat("\"postId", post.PostId, "\""), string.Concat("\"", hasSeen, "\""));
            }

            bodyNode.InnerHtml = threadHtml;
            return doc2.DocumentNode.OuterHtml;
        }
예제 #5
0
 public async Task<string> GetThread(ForumThreadEntity forumThread)
 {
     string url = string.Format(Constants.REPLY_BASE, forumThread.ThreadId);
     WebManager.Result result = await _webManager.DownloadHtml(url);
     HtmlDocument doc = result.Document;
     return await GetThreadHtml(doc);
 }
예제 #6
0
        /// <summary>
        ///     Populates the page with content passed during navigation. Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        ///     The source of the event; typically <see cref="NavigationHelper" />
        /// </param>
        /// <param name="e">
        ///     Event data that provides both the navigation parameter passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
        ///     a dictionary of state preserved by this page during an earlier
        ///     session. The state will be null the first time a page is visited.
        /// </param>
        private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            _forumPost = e.NavigationParameter as ForumPostEntity;
            if(_forumPost != null)
            ReplyText.Text = string.Format(Constants.QUOTE_EXP, _forumPost.User.Username, _forumPost.PostId, _forumPost.PostFormatted);

            _forumThread = e.NavigationParameter as ForumThreadEntity;
        }
예제 #7
0
        public async Task<ForumThreadEntity> GetThreadPosts(ForumThreadEntity forumThread)
        {
            try
            {
                string url = forumThread.Location;

                if (forumThread.CurrentPage > 0)
                {
                    url = forumThread.Location + string.Format(Constants.PAGE_NUMBER, forumThread.CurrentPage);
                }
                else if (forumThread.HasBeenViewed)
                {
                    url = forumThread.Location + Constants.GOTO_NEW_POST;
                }

                var forumThreadPosts = new ObservableCollection<ForumPostEntity>();

                //TEMP CODE
                var threadManager = new ThreadManager();
                var doc = await threadManager.GetThread(forumThread, url);

                HtmlNode threadNode =
                    doc.DocumentNode.Descendants("div")
                        .FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("thread"));

                foreach (
                    HtmlNode postNode in
                        threadNode.Descendants("table")
                            .Where(node => node.GetAttributeValue("class", string.Empty).Contains("post")))
                {
                    var post = new ForumPostEntity();
                    post.Parse(postNode);
                    forumThreadPosts.Add(post);
                }

                threadNode =
                    doc.DocumentNode.Descendants("div")
                        .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("pages top"));
                if (threadNode != null)
                {
                    threadNode =
        threadNode.Descendants("option")
            .FirstOrDefault(node => node.GetAttributeValue("selected", string.Empty).Contains("selected"));

                    if (forumThread.CurrentPage <= 0)
                    {
                        forumThread.CurrentPage = GetPageNumber(threadNode);
                    }
                }
                forumThread.ForumPosts = forumThreadPosts;
                return forumThread;
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #8
0
 public async void GetForumPosts(ForumThreadEntity forumThreadEntity)
 {
     IsLoading = true;
     ThreadTitle = forumThreadEntity.Name;
     PostManager postManager = new PostManager();
     await postManager.GetThreadPosts(forumThreadEntity);
     Html = await HtmlFormater.FormatThreadHtml(forumThreadEntity);
     ForumThreadEntity = forumThreadEntity;
     PageNumbers = Enumerable.Range(1, forumThreadEntity.TotalPages).ToArray();
     IsLoading = false;
 }
예제 #9
0
        public async Task<ForumReplyEntity> GetReplyCookies(ForumThreadEntity forumThread)
        {
            try
            {
                string url = string.Format(Constants.REPLY_BASE, forumThread.ThreadId);
                WebManager.Result result = await _webManager.DownloadHtml(url);
                HtmlDocument doc = result.Document;

                HtmlNode[] formNodes = doc.DocumentNode.Descendants("input").ToArray();

                HtmlNode formKeyNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("formkey"));

                HtmlNode formCookieNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("form_cookie"));

                HtmlNode bookmarkNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("bookmark"));

                HtmlNode[] textAreaNodes = doc.DocumentNode.Descendants("textarea").ToArray();

                HtmlNode textNode =
                    textAreaNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("message"));

                HtmlNode threadIdNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("threadid"));

                var threadManager = new ThreadManager();

                string htmlThread = await threadManager.GetThreadHtml(doc);

                var forumReplyEntity = new ForumReplyEntity();
                try
                {
                    string formKey = formKeyNode.GetAttributeValue("value", "");
                    string formCookie = formCookieNode.GetAttributeValue("value", "");
                    string quote = WebUtility.HtmlDecode(textNode.InnerText);
                    string threadId = threadIdNode.GetAttributeValue("value", "");
                    forumReplyEntity.MapThreadInformation(formKey, formCookie, quote, threadId);
                    forumReplyEntity.PreviousPostsRaw = htmlThread;
                    return forumReplyEntity;
                }
                catch (Exception)
                {
                    throw new InvalidOperationException("Could not parse newReply form data.");
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #10
0
 public static void CreateBookmarkLiveTile(ForumThreadEntity forumThread)
 {
     XmlDocument tileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Text05);
     XmlNodeList tileAttributes = tileXml.GetElementsByTagName("text");
     tileAttributes[0].AppendChild(tileXml.CreateTextNode(forumThread.Name));
     tileAttributes[1].AppendChild(tileXml.CreateTextNode(string.Format("Killed By: {0}", forumThread.KilledBy)));
     tileAttributes[2].AppendChild(
         tileXml.CreateTextNode(string.Format("Unread Posts: {0}", forumThread.RepliesSinceLastOpened)));
     //var imageElement = tileXml.GetElementsByTagName("image");
     //imageElement[0].Attributes[1].NodeValue = "http://fi.somethingawful.com/forums/posticons/lf-arecountry.gif" ;
     var tileNotification = new TileNotification(tileXml);
     TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);
 }
예제 #11
0
        public async Task<List<ForumPostEntity>> GetThreadPosts(ForumThreadEntity forumThread)
        {
            string url = forumThread.Location;

            if (forumThread.CurrentPage > 0)
            {
                url = forumThread.Location + string.Format(Constants.PAGE_NUMBER, forumThread.CurrentPage);
            }
            else if (forumThread.HasBeenViewed)
            {
                url = forumThread.Location + Constants.GOTO_NEW_POST;
            }

            var forumThreadPosts = new List<ForumPostEntity>();
            
            //TEMP CODE
            var result = await _webManager.DownloadHtml(url);
            HtmlDocument doc = result.Document;
            string responseUri = result.AbsoluteUri;
            
            /* TODO: The following checks the thread URL for "pti" (which indicated which post to scroll to)
             * Having it in the post manager though, is wrong. This needs to be refactored and a better method of 
             * getting this needs to be put in.
             */
            string[] test = responseUri.Split('#');
            if (test.Length > 1 && test[1].Contains("pti"))
            {
                forumThread.ScrollToPost = Int32.Parse(Regex.Match(responseUri.Split('#')[1], @"\d+").Value) - 1;
            }
            HtmlNode threadNode = doc.DocumentNode.Descendants("div").FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("thread"));

            foreach (HtmlNode postNode in threadNode.Descendants("table").Where(node => node.GetAttributeValue("class", string.Empty).Contains("post")))
            {
                var post = new ForumPostEntity();
                post.Parse(postNode);
                forumThreadPosts.Add(post);
            }

            threadNode = doc.DocumentNode.Descendants("div").FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("pages top"));
            threadNode = threadNode.Descendants("option").FirstOrDefault(node => node.GetAttributeValue("selected", string.Empty).Contains("selected"));

            if (forumThread.CurrentPage <= 0)
            {
                forumThread.CurrentPage = GetPageNumber(threadNode);
            }

            HtmlNode pageNode = doc.DocumentNode.Descendants("select").FirstOrDefault();
            forumThread.TotalPages = forumThread.CurrentPage <= 1 ? 1 : Convert.ToInt32(pageNode.Descendants("option").LastOrDefault().GetAttributeValue("value", string.Empty));

            return forumThreadPosts;
        }
예제 #12
0
        public async Task<string> GetThreadPostInformation(ForumThreadEntity forumThread)
        {
            string url = forumThread.Location;

            if (forumThread.CurrentPage > 0)
            {
                url = forumThread.Location + string.Format(Constants.PAGE_NUMBER, forumThread.CurrentPage);
            }
            else if (forumThread.HasBeenViewed)
            {
                url = forumThread.Location + Constants.GOTO_NEW_POST;
            }


            WebManager.Result result = await _webManager.DownloadHtml(url);
            HtmlDocument doc = result.Document;
            string responseUri = result.AbsoluteUri;

            /* TODO: The following checks the thread URL for "pti" (which indicated which post to scroll to)
           * Having it in the post manager though, is wrong. This needs to be refactored and a better method of 
           * getting this needs to be put in.
           */
            string[] test = responseUri.Split('#');
            if (test.Length > 1 && test[1].Contains("pti"))
            {
                forumThread.ScrollToPost = Int32.Parse(Regex.Match(responseUri.Split('#')[1], @"\d+").Value) - 1;
                forumThread.ScrollToPostString = "#" + test[1];
            }

            HtmlNode threadNode =
                doc.DocumentNode.Descendants("div")
                    .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("pages top"));
            threadNode =
                threadNode.Descendants("option")
                    .FirstOrDefault(node => node.GetAttributeValue("selected", string.Empty).Contains("selected"));
            if (forumThread.CurrentPage <= 0)
            {
                forumThread.CurrentPage = GetPageNumber(threadNode);
            }

            HtmlNode[] pageNodes = doc.DocumentNode.Descendants("div").ToArray();
            HtmlNode pageNode =
                pageNodes.FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Equals("pages top"));
            pageNode = pageNode.Descendants("option").LastOrDefault();
            forumThread.TotalPages = pageNode == null
                ? 1
                : Convert.ToInt32(pageNode.GetAttributeValue("value", string.Empty));

            var threadManager = new ThreadManager();
            return await threadManager.GetThreadHtml(doc);
        }
예제 #13
0
 public static void CreateToastNotification(ForumThreadEntity forumThread)
 {
     XmlDocument notificationXml =
       ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);
     XmlNodeList toastElements = notificationXml.GetElementsByTagName("text");
     toastElements[0].AppendChild(notificationXml.CreateTextNode(string.Format("\"{0}\" has {1} unread replies!", forumThread.Name, forumThread.RepliesSinceLastOpened)));
     XmlNodeList imageElement = notificationXml.GetElementsByTagName("image");
     string imageName = string.Empty;
     if (string.IsNullOrEmpty(imageName))
     {
         imageName = @"Assets/Logo.scale-100.png";
     }
     imageElement[0].Attributes[1].NodeValue = imageName;
     IXmlNode toastNode = notificationXml.SelectSingleNode("/toast");
     string test = "{" + string.Format("type:'toast'") + "}";
     var xmlElement = (XmlElement)toastNode;
     if (xmlElement != null) xmlElement.SetAttribute("launch", test);
     var toastNotification = new ToastNotification(notificationXml);
     ToastNotificationManager.CreateToastNotifier().Show(toastNotification);
 }
예제 #14
0
        public async Task<List<ForumThreadEntity>> GetBookmarks(ForumEntity forumCategory)
        {
            var forumSubcategoryList = new List<ForumEntity>();
            var forumThreadList = new List<ForumThreadEntity>();
            String url = forumCategory.Location;
            if (forumCategory.CurrentPage > 0)
            {
                url = forumCategory.Location + string.Format(Constants.PAGE_NUMBER, forumCategory.CurrentPage);
            }

            HtmlDocument doc = (await _webManager.DownloadHtml(url)).Document;
            HtmlNode forumNode = doc.DocumentNode.Descendants().FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("threadlist"));


            foreach (HtmlNode threadNode in forumNode.Descendants("tr").Where(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")))
            {
                var threadEntity = new ForumThreadEntity();
                threadEntity.Parse(threadNode);
                forumThreadList.Add(threadEntity);
            }
            return forumThreadList;
        }
예제 #15
0
        public async Task<ForumThreadEntity> GetThread(string url)
        {
            var forumThread = new ForumThreadEntity();
            WebManager.Result result = await _webManager.GetData(url);
            HtmlDocument doc = result.Document;
            try
            {
                forumThread.ParseFromThread(doc);
            }
            catch (Exception)
            {
                return null;
            }
            var query = Extensions.ParseQueryString(url);
            if (!query.ContainsKey("postid")) return forumThread;

            // If we are going to a post, it won't use #pti but instead uses the post id.

            forumThread.ScrollToPost = Convert.ToInt32(query["postid"]);
            forumThread.ScrollToPostString = "#post" + query["postid"];
            return forumThread;

        }
예제 #16
0
        private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
        {
            if (_vm.ForumThreadEntity == null)
            {
                return;
            }
            if (e == null)
            {
                return;
            }
            string stringJson = e.Value;
            ThreadCommand command = null;
            try
            {
                command = JsonConvert.DeserializeObject<ThreadCommand>(stringJson);
            }
            catch (Exception ex)
            {
                AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex);
            }
            if (command == null)
            {
                return;
            }
            switch (command.Command)
            {
                case "quote":
                    Frame.Navigate(typeof(ReplyPage), command.Id);
                    break;
                case "edit":
                    Frame.Navigate(typeof(EditPage), command.Id);
                    break;
                case "setFont":
                    SetFontSize();
                    break;
                case "scrollToPost":
                    if (!string.IsNullOrEmpty(_vm.ForumThreadEntity.ScrollToPostString))
                        try
                        {
                            await ThreadWebView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString });
                        }
                        catch (Exception ex)
                        {
                            AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex);
                        }
                    break;
                case "markAsLastRead":
                    await _threadManager.MarkPostAsLastRead(_forumThread, Convert.ToInt32(command.Id));
                    int nextPost = Convert.ToInt32(command.Id) + 1;

                    try
                    {
                        await ThreadWebView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) });
                    }
                    catch (Exception ex)
                    {
                        AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex);
                        return;
                    }
                    var message = new MessageDialog("Post marked as last read! Now go on and live your life!")
                        {
                            DefaultCommandIndex = 1
                        };
                    await message.ShowAsync();
                    break;
                case "openThread":
                      var query = Extensions.ParseQueryString(command.Id);
                    if (query.ContainsKey("action") && query["action"].Equals("showPost"))
                    {
                        var postManager = new PostManager();
                        try
                        {
                            var html = await postManager.GetPost(Convert.ToInt32(query["postid"]));
                        }
                        catch (Exception ex)
                        {
                            AwfulDebugger.SendMessageDialogAsync("A thread javascript command failed", ex);
                            return;
                        }
                        return;
                    }
                    var threadManager = new ThreadManager();
                    var threadEntity = new ForumThreadEntity();
                    var thread = await threadManager.GetThread(threadEntity, command.Id);
                    if (thread == null)
                    {
                        var error = new MessageDialog("Specified post was not found in the live forums.")
                        {
                            DefaultCommandIndex = 1
                        };
                        await error.ShowAsync();
                        break;
                    }
                    string jsonObjectString = JsonConvert.SerializeObject(threadEntity);
                    Frame.Navigate(typeof(ThreadPage), jsonObjectString);
                    break;
                default:
                    var msgDlg = new MessageDialog("Not working yet!")
                    {
                        DefaultCommandIndex = 1
                    };
                    await msgDlg.ShowAsync();
                    break;
            }
        }
예제 #17
0
 private async void WebView_ScriptNotify(object sender, NotifyEventArgs e)
 {
     string stringJson = e.Value;
     var command = JsonConvert.DeserializeObject<ReplyView.ThreadCommand>(stringJson);
     switch (command.Command)
     {
         case "profile":
             Frame.Navigate(typeof (UserProfileView), command.Id);
             break;
         case "post_history":
             Frame.Navigate(typeof (UserPostHistoryPage), command.Id);
             break;
         case "rap_sheet":
             Frame.Navigate(typeof (RapSheetView), command.Id);
             break;
         case "quote":
             Frame.Navigate(typeof (ReplyView), command.Id);
             break;
         case "edit":
             Frame.Navigate(typeof (EditReplyPage), command.Id);
             break;
         case "scrollToPost":
             if (command.Id != null)
             {
                 await ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", command.Id) });
                 await ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", command.Id) });
             }
             else if (!string.IsNullOrEmpty(_vm.ForumThreadEntity.ScrollToPostString))
             {
                 ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString });
                 ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { _vm.ForumThreadEntity.ScrollToPostString });
             }
             break;
         case "markAsLastRead":
             await _threadManager.MarkPostAsLastRead(_forumThread, Convert.ToInt32(command.Id));
             int nextPost = Convert.ToInt32(command.Id) + 1;
             await ThreadFullView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) });
             await ThreadSnapView.InvokeScriptAsync("ScrollToDiv", new[] { string.Concat("#postId", nextPost.ToString()) });
             NotifyStatusTile.CreateToastNotification("Post marked as last read! Now smash this computer and live your life!");
             break;
         case "setFont":
             if (_localSettings.Values.ContainsKey("zoomSize"))
             {
                 _zoomSize = Convert.ToInt32(_localSettings.Values["zoomSize"]);
                 ThreadFullView.InvokeScriptAsync("ResizeWebviewFont", new[] { _zoomSize.ToString() });
                 ThreadSnapView.InvokeScriptAsync("ResizeWebviewFont", new[] { _zoomSize.ToString() });
             }
             else
             {
                 _zoomSize = 14;
             }
             break;
         case "openThread":
             // Because we are coming from an existing thread, rather than the thread lists, we need to get the thread information beforehand.
             // However, right now the managers are not set up to support this. The thread is getting downloaded twice, when it really only needs to happen once.
             var threadManager = new ThreadManager();
             var newThreadEntity = new ForumThreadEntity();
             var thread = await threadManager.GetThread(newThreadEntity, command.Id);
             if (thread == null)
             {
                 var error = new MessageDialog("Specified post was not found in the live forums.")
                 {
                     DefaultCommandIndex = 1
                 };
                 await error.ShowAsync();
                 break;
             }
             string jsonObjectString = JsonConvert.SerializeObject(newThreadEntity);
             Frame.Navigate(typeof(ThreadPage), jsonObjectString);
             break;
         default:
             var msgDlg = new MessageDialog("Not working yet!")
             {
                 DefaultCommandIndex = 1
             };
             await msgDlg.ShowAsync();
             break;
     }
 }
예제 #18
0
        /// <summary>
        ///     Populates the page with content passed during navigation. Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        ///     The source of the event; typically <see cref="NavigationHelper" />
        /// </param>
        /// <param name="e">
        ///     Event data that provides both the navigation parameter passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
        ///     a dictionary of state preserved by this page during an earlier
        ///     session. The state will be null the first time a page is visited.
        /// </param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            loadingProgressBar.Visibility = Visibility.Visible;
            var jsonObjectString = (string) e.NavigationParameter;
            long threadId = 0;
            try
            {
                _forumThread = JsonConvert.DeserializeObject<ForumThreadEntity>(jsonObjectString);
            }
            catch (Exception)
            {
                threadId = Convert.ToInt64(jsonObjectString);
            }

            //_forumPost = e.NavigationParameter as ForumPostEntity;
            if (_forumThread != null)
            {
                _forumReply = await _replyManager.GetReplyCookies(_forumThread);
            }
            else
            {
                _forumReply = await _replyManager.GetReplyCookies(threadId);
            }
            if (_forumReply == null)
            {
                var msgDlg = new MessageDialog("Can't reply in this thread!");
                await msgDlg.ShowAsync();
                Frame.GoBack();
                return;
            }
            ReplyText.Text = _forumReply.Quote;
            PreviousPostsWebView.NavigateToString(_forumReply.PreviousPostsRaw);
            loadingProgressBar.Visibility = Visibility.Collapsed;
        }
예제 #19
0
        public async Task<List<ForumThreadEntity>> GetForumThreads(ForumEntity forumCategory, int page)
        {
            // TODO: Remove parsing logic from managers. I don't think they have a place here...
            var url = forumCategory.Location + string.Format(Constants.PAGE_NUMBER, page);

            HtmlDocument doc = (await _webManager.DownloadHtml(url)).Document;

            HtmlNode forumNode = doc.DocumentNode.Descendants().FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("threadlist"));
            var forumThreadList = new List<ForumThreadEntity>();
            foreach (HtmlNode threadNode in forumNode.Descendants("tr").Where(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")))
            {
                var threadEntity = new ForumThreadEntity();
                threadEntity.Parse(threadNode);
                forumThreadList.Add(threadEntity);
            }
            return forumThreadList;
        }
예제 #20
0
        public async Task<ForumReplyEntity> GetReplyCookies(ForumThreadEntity forumThread)
        {
            try
            {
                string url = string.Format(Constants.REPLY_BASE, forumThread.ThreadId);
                WebManager.Result result = await _webManager.GetData(url);
                HtmlDocument doc = result.Document;

                HtmlNode[] formNodes = doc.DocumentNode.Descendants("input").ToArray();

                HtmlNode formKeyNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("formkey"));

                HtmlNode formCookieNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("form_cookie"));

                HtmlNode bookmarkNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("bookmark"));

                HtmlNode[] textAreaNodes = doc.DocumentNode.Descendants("textarea").ToArray();

                HtmlNode textNode =
                    textAreaNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("message"));

                HtmlNode threadIdNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("threadid"));

                var threadManager = new ThreadManager();

                var forumThreadPosts = new ObservableCollection<ForumPostEntity>();

                HtmlNode threadNode =
                   doc.DocumentNode.Descendants("div")
                       .FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("thread"));


                foreach (
                   HtmlNode postNode in
                       threadNode.Descendants("table")
                           .Where(node => node.GetAttributeValue("class", string.Empty).Contains("post")))
                {
                    var post = new ForumPostEntity();
                    post.Parse(postNode);
                    forumThreadPosts.Add(post);
                }

                forumThread.ForumPosts = forumThreadPosts;

                string htmlThread = await HtmlFormater.FormatThreadHtml(forumThread);

                var forumReplyEntity = new ForumReplyEntity();
                try
                {
                    string formKey = formKeyNode.GetAttributeValue("value", "");
                    string formCookie = formCookieNode.GetAttributeValue("value", "");
                    string quote = WebUtility.HtmlDecode(textNode.InnerText);
                    string threadId = threadIdNode.GetAttributeValue("value", "");
                    forumReplyEntity.MapThreadInformation(formKey, formCookie, quote, threadId);
                    forumReplyEntity.PreviousPostsRaw = htmlThread;
                    return forumReplyEntity;
                }
                catch (Exception)
                {
                    throw new InvalidOperationException("Could not parse newReply form data.");
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #21
0
        public async Task<ForumReplyEntity> GetReplyCookiesForEdit(long postId)
        {
            try
            {
                string url = string.Format(Constants.EDIT_BASE, postId);
                WebManager.Result result = await _webManager.GetData(url);
                HtmlDocument doc = result.Document;

                HtmlNode[] formNodes = doc.DocumentNode.Descendants("input").ToArray();

                HtmlNode bookmarkNode =
                    formNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("bookmark"));

                HtmlNode[] textAreaNodes = doc.DocumentNode.Descendants("textarea").ToArray();

                HtmlNode textNode =
                    textAreaNodes.FirstOrDefault(node => node.GetAttributeValue("name", "").Equals("message"));

                var threadManager = new ThreadManager();

                //Get previous posts from quote page.
                string url2 = string.Format(Constants.QUOTE_BASE, postId);
                WebManager.Result result2 = await _webManager.GetData(url2);
                HtmlDocument doc2 = result2.Document;

                var forumThreadPosts = new ObservableCollection<ForumPostEntity>();

                HtmlNode threadNode =
                   doc2.DocumentNode.Descendants("div")
                       .FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("thread"));


                foreach (
                   HtmlNode postNode in
                       threadNode.Descendants("table")
                           .Where(node => node.GetAttributeValue("class", string.Empty).Contains("post")))
                {
                    var post = new ForumPostEntity();
                    post.Parse(postNode);
                    forumThreadPosts.Add(post);
                }

                ForumThreadEntity threadEntity = new ForumThreadEntity()
                {
                    ForumPosts = forumThreadPosts
                };

                string htmlThread = await HtmlFormater.FormatThreadHtml(threadEntity);

                var forumReplyEntity = new ForumReplyEntity();
                try
                {
                    string quote = WebUtility.HtmlDecode(textNode.InnerText);
                    forumReplyEntity.PreviousPostsRaw = htmlThread;
                    string bookmark = bookmarkNode.OuterHtml.Contains("checked") ? "yes" : "no";
                    forumReplyEntity.MapEditPostInformation(quote, postId, bookmark);
                    return forumReplyEntity;
                }
                catch (Exception)
                {
                    throw new InvalidOperationException("Could not parse newReply form data.");
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #22
0
        /// <summary>
        ///     Populates the page with content passed during navigation. Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        ///     The source of the event; typically <see cref="NavigationHelper" />
        /// </param>
        /// <param name="e">
        ///     Event data that provides both the navigation parameter passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
        ///     a dictionary of state preserved by this page during an earlier
        ///     session. The state will be null the first time a page is visited.
        /// </param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var jsonObjectString = (string) e.NavigationParameter;
            _forumThread = JsonConvert.DeserializeObject<ForumThreadEntity>(jsonObjectString);
            if (_forumThread == null) return;
            _vm.GetForumPosts(_forumThread);

            // Set the default focus on the page to either one of the web views.
            CheckOrientation();

        }
예제 #23
0
        public async Task<bool> Initialize(string jsonObjectString)
        {
            IsLoading = true;
            long threadId = 0;
            var replyManager = new ReplyManager();

            try
            {
               _forumThread = JsonConvert.DeserializeObject<ForumThreadEntity>(jsonObjectString);
            }
            catch (Exception)
            {
                threadId = Convert.ToInt64(jsonObjectString);
            }

            if (_forumThread != null)
            {
                ForumReplyEntity = await replyManager.GetReplyCookies(_forumThread);
            }
            else
            {
                ForumReplyEntity = await replyManager.GetReplyCookies(threadId);
            }
            IsLoading = false;
            return ForumReplyEntity != null;

        }
예제 #24
0
 private void GetDarkModeSetting(ForumThreadEntity forumThreadEntity)
 {
     var localSettings = ApplicationData.Current.LocalSettings;
     if (!localSettings.Values.ContainsKey(Constants.DARK_MODE)) return;
     var darkMode = (bool) localSettings.Values[Constants.DARK_MODE];
     switch (darkMode)
     {
         case true:
             forumThreadEntity.PlatformIdentifier = PlatformIdentifier.WindowsPhone;
             break;
         case false:
             forumThreadEntity.PlatformIdentifier = PlatformIdentifier.Windows8;
             break;
     }
 }
예제 #25
0
        public async Task<string> GetPrivateMessageHtml(string url)
        {

            string html = await PathIO.ReadTextAsync("ms-appx:///Assets/thread.html");

            var doc2 = new HtmlDocument();

            doc2.LoadHtml(html);

            HtmlNode bodyNode = doc2.DocumentNode.Descendants("body").FirstOrDefault();

            HtmlDocument doc = (await _webManager.GetData(url)).Document;

            HtmlNode[] replyNodes = doc.DocumentNode.Descendants("div").Where(node => node.GetAttributeValue("id", "").Equals("thread")).ToArray();

            HtmlNode threadNode = replyNodes.FirstOrDefault(node => node.GetAttributeValue("id", "").Equals("thread"));

            int threadId = ParseInt(threadNode.GetAttributeValue("class", string.Empty));

            IEnumerable<HtmlNode> postNodes =
                threadNode.Descendants("table")
                    .Where(node => node.GetAttributeValue("class", string.Empty).Contains("post"));
          ObservableCollection<ForumPostEntity> postList = new ObservableCollection<ForumPostEntity>();
            foreach (
     HtmlNode postNode in
         postNodes)
            {
                var post = new ForumPostEntity();
                post.Parse(postNode);
                postList.Add(post);
            }
            ForumThreadEntity threadEntity = new ForumThreadEntity()
            {
                ForumPosts = postList
            };
            return await HtmlFormater.FormatThreadHtml(threadEntity);
        }
예제 #26
0
 public async Task<bool> MarkPostAsLastRead(ForumThreadEntity threadEntity, int index)
 {
     await _webManager.GetData(string.Format(Constants.LAST_READ, index, threadEntity.ThreadId));
     return true;
 }
예제 #27
0
 private void PopularThreadList_ItemClick(object sender, ItemClickEventArgs e)
 {
     var threadEntity = e.ClickedItem as PopularThreadsTrendsEntity;
     var thread = new ForumThreadEntity();
     if (threadEntity == null) return;
     thread.ParseFromPopularThread(threadEntity.Title, threadEntity.Id);
     string jsonObjectString = JsonConvert.SerializeObject(thread);
     Frame.Navigate(typeof (ThreadPage), jsonObjectString);
 }
예제 #28
0
        public async Task<ObservableCollection<ForumThreadEntity>> GetBookmarks(ForumEntity forumCategory, int page)
        {
            var forumThreadList = new ObservableCollection<ForumThreadEntity>();
            String url = Constants.BOOKMARKS_URL;
            if (forumCategory.CurrentPage > 0)
            {
                url = Constants.BOOKMARKS_URL + string.Format(Constants.PAGE_NUMBER, page);
            }

            HtmlDocument doc = (await _webManager.GetData(url)).Document;

            HtmlNode forumNode =
                doc.DocumentNode.Descendants()
                    .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("threadlist"));


            foreach (
                HtmlNode threadNode in
                    forumNode.Descendants("tr")
                        .Where(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")))
            {
                var threadEntity = new ForumThreadEntity();
                threadEntity.Parse(threadNode);
                threadEntity.IsBookmark = true;
                forumThreadList.Add(threadEntity);
            }
            return forumThreadList;
        }
        private ForumThreadEntity ParseEntity(string html)
        {
            var doc = new HtmlDocument();
            doc.LoadHtml(html);
            var thread = new ForumThreadEntity();

            thread.Parse(
                doc.DocumentNode.Descendants("tr")
                    .First(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")));
            return thread;
        }
예제 #30
0
        public async Task GetForumPosts(ForumThreadEntity forumThreadEntity)
        {
            IsLoading = true;
            bool isSuccess;
            string errorMessage = string.Empty;
            ThreadTitle = forumThreadEntity.Name;
            PostManager postManager = new PostManager();
            try
            {
                await postManager.GetThreadPosts(forumThreadEntity);
                isSuccess = true;
            }
            catch (Exception ex)
            {
                IsLoading = false;
                isSuccess = false;
                errorMessage = ex.Message;
            }
            if (!isSuccess)
            {
                await AwfulDebugger.SendMessageDialogAsync("Failed to get thread posts.", new Exception(errorMessage));
                return;
            }
#if WINDOWS_PHONE_APP
            forumThreadEntity.PlatformIdentifier = PlatformIdentifier.WindowsPhone;
#else
            forumThreadEntity.PlatformIdentifier = PlatformIdentifier.Windows8;
#endif
            try
            {
                GetDarkModeSetting(forumThreadEntity);
                Html = await HtmlFormater.FormatThreadHtml(forumThreadEntity);
                ForumThreadEntity = forumThreadEntity;
                PageNumbers = Enumerable.Range(1, forumThreadEntity.TotalPages).ToArray();
            }
            catch (Exception ex)
            {
                AwfulDebugger.SendMessageDialogAsync("An error occured creating the thread HTML", ex);
            }
        }