public CommentViewModel(IBaconProvider baconProvider, Thing comment, string linkId, bool oddNesting, int depth = 0)
        {
            _isMinimized = false;
            _comment = new TypedThing<Comment>(comment);
            _baconProvider = baconProvider;
            _redditService = _baconProvider.GetService<IRedditService>();
            _navigationService = _baconProvider.GetService<INavigationService>();
            _userService = _baconProvider.GetService<IUserService>();
            _dynamicViewLocator = _baconProvider.GetService<IDynamicViewLocator>();
            _markdownProcessor = _baconProvider.GetService<IMarkdownProcessor>();
            _linkId = linkId;
            OddNesting = oddNesting;
			Depth = depth;
            AuthorFlair = _redditService.GetUsernameModifiers(_comment.Data.Author, _linkId, _comment.Data.Subreddit);
            AuthorFlairText = _comment.Data.AuthorFlairText;
            _showExtendedView = new RelayCommand(ShowExtendedViewImpl);
            _gotoReply = new RelayCommand(GotoReplyImpl);
            _save = new RelayCommand(SaveImpl);
            _report = new RelayCommand(ReportImpl);
            _gotoFullLink = new RelayCommand(GotoFullLinkImpl);
            _gotoContext = new RelayCommand(GotoContextImpl);
            _gotoUserDetails = new RelayCommand(GotoUserDetailsImpl);
            _gotoEdit = new RelayCommand(GotoEditImpl);
            _minimizeCommand = new RelayCommand(() => IsMinimized = !IsMinimized);
            Body = _comment.Data.Body;
        }
        private async void GotoContextImpl()
        {
            try
            {
                if (_comment.Data.ParentId == null)
                {
                    return;
                }

                MessengerInstance.Send <LoadingMessage>(new LoadingMessage {
                    Loading = true
                });
                var linkThing   = new TypedThing <Link>(await _redditService.GetThingById(_comment.Data.LinkId));
                var parentThing = await _redditService.GetLinkByUrl("http://www.reddit.com/" + linkThing.Data.Permalink + _comment.Data.ParentId.Substring(3));

                var commentTree = new SelectCommentTreeMessage {
                    LinkThing = new TypedThing <Link>(parentThing)
                };
                MessengerInstance.Send <LoadingMessage>(new LoadingMessage {
                    Loading = false
                });
                _navigationService.Navigate(_dynamicViewLocator.CommentsView, commentTree);
            }
            catch (Exception ex)
            {
                _baconProvider.GetService <INotificationService>().CreateErrorNotification(ex);
            }
        }
        public MessageViewModel(IBaconProvider baconProvider, Thing message)
        {
            _baconProvider = baconProvider;
            _message = new TypedThing<Message>(message);
            _userService = baconProvider.GetService<IUserService>();
            _redditService = baconProvider.GetService<IRedditService>();
            _navigationService = baconProvider.GetService<INavigationService>();
            _dynamicViewLocator = baconProvider.GetService<IDynamicViewLocator>();

            if (message.Data is CommentMessage)
            {
                var commentMessage = new TypedThing<CommentMessage>(message);
                if (!String.IsNullOrEmpty(commentMessage.Data.Subject))
                {
                    if (commentMessage.Data.LinkTitle.Contains("post"))
                    {
                        isPostReply = true;
                    }
                    else
                    {
                        isPostReply = false;
                    }
                    _message.Data.Subject = commentMessage.Data.LinkTitle;
                }
            }

            _isNew = _message.Data.New;
        }
        public LinkViewModel(Thing linkThing, IBaconProvider baconProvider, bool? wasStreamed = null)
        {
            _linkThing = new TypedThing<Link>(linkThing);
            _baconProvider = baconProvider;
            _redditService = _baconProvider.GetService<IRedditService>();
            _navigationService = _baconProvider.GetService<INavigationService>();
            _imagesService = _baconProvider.GetService<IImagesService>();
            _dynamicViewLocator = _baconProvider.GetService<IDynamicViewLocator>();
            _settingsService = _baconProvider.GetService<ISettingsService>();
            _isPreviewShown = false;
			_isExtendedOptionsShown = false;
            _loading = false;
            _registeredLongNav = false;
            ShowPreview = new RelayCommand(() => IsPreviewShown = !IsPreviewShown);
			ShowExtendedOptions = new RelayCommand(() => IsExtendedOptionsShown = !IsExtendedOptionsShown);
            WasStreamed = wasStreamed ?? false;

            ContentIsFocused = !WasStreamed;

            if (Url != null)
            {
                if (_imagesService.MightHaveImagesFromUrl(Url) && !Url.EndsWith(".jpg") && !Url.EndsWith(".gif") && !Url.EndsWith(".png"))
                {
                    MessengerInstance.Register<LongNavigationMessage>(this, OnLongNav);
                    _registeredLongNav = true;
                }
            }
        }
 public VotableViewModel(Thing votableThing, IBaconProvider baconProvider, Action propertyChanged)
 {
     _votableThing = new TypedThing<IVotable>(votableThing);
     _redditService = baconProvider.GetService<IRedditService>();
     _propertyChanged = propertyChanged;
     originalVoteModifier = (Like ? 1 : 0) + (Dislike ? -1 : 0);
 }
 public AboutSubredditViewModel(IBaconProvider baconProvider, Thing thing, bool subscribed)
 {
     _baconProvider = baconProvider;
     Thing          = new TypedThing <Subreddit>(thing);
     _redditService = _baconProvider.GetService <IRedditService>();
     _subscribed    = subscribed;
 }
 public AboutSubredditViewModel(IBaconProvider baconProvider, Thing thing, bool subscribed)
 {
     _baconProvider = baconProvider;
     Thing = new TypedThing<Subreddit>(thing);
     _redditService = _baconProvider.GetService<IRedditService>();
     _userService = _baconProvider.GetService<IUserService>();
     _subscribed = subscribed;
 }
        // Take a subreddit thing and generate a pinned secondary tile. Use the display
        // name and subreddit header image in the tile.
        public async Task CreateSecondaryTileForSubreddit(TypedThing <Subreddit> subreddit)
        {
            //try
            // {
            //    // Download and create a local copy of the header image
            //    var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");
            //    // Generate a square tile appropriate image
            //    var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

            //    string id = "";
            //    if (subreddit != null)
            //        id = subreddit.Data.DisplayName;


            //    var properties = (await squareImage.Properties.RetrievePropertiesAsync(new string[] { "System.ParsingPath" }));


            //    var tile = ShellTile.Create(new Uri(""), new StandardTileData { Title = subreddit.Data.Title, BackgroundImage = new Uri(properties["System.ParsingPath"] as string) );
            //    var tileSchedule = new ShellTileSchedule(tile);
            //    tileSchedule.
            //    SecondaryTile tile = new SecondaryTile();
            //    tile.TileOptions = TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo;
            //    tile.DisplayName = "Baconography";
            //    tile.ShortName = "/r/" + id;
            //    if (subreddit != null)
            //    {

            //        // Download and create a local copy of the header image
            //        var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");
            //        // Generate a square tile appropriate image
            //        var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

            //        tile.WideLogo = new Uri("ms-appdata:///local/Images/" + wideImage.Name);
            //        tile.Logo = new Uri("ms-appdata:///local/Images/" + squareImage.Name);
            //        subreddit.Data.PublicDescription = null;
            //        subreddit.Data.Description = null;
            //        subreddit.Data.Headertitle = null;
            //        tile.Arguments = JsonConvert.SerializeObject(subreddit);
            //    }
            //    else
            //    {
            //        Uri logo = new Uri("ms-appx:///Assets/Logo.png");
            //        Uri wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
            //        tile.Arguments = "/r/";
            //        tile.Logo = logo;
            //        tile.WideLogo = wideLogo;
            //    }
            //    tile.TileId = "r" + id;

            //    // Ask the user to authorize creation of the tile
            //    bool isPinned = await tile.RequestCreateAsync();
            //}
            //catch (Exception)
            //{
            //    // TODO: Do something with exceptions
            //}
        }
 public void SetEditorMode(TypedThing<Link> link)
 {
     Kind = link.Kind;
     Subreddit = link.Data.Subreddit;
     Title = link.Data.Title;
     Text = link.Data.Selftext;
     _name = link.Data.Name;
     Editing = true;
 }
 public void MergeVotable(Thing votableThing)
 {
     _votableThing = new TypedThing<IVotable>(votableThing);
     originalVoteModifier = (Like ? 1 : 0) + (Dislike ? -1 : 0);
     RaisePropertyChanged("Like");
     RaisePropertyChanged("Dislike");
     RaisePropertyChanged("TotalVotes");
     RaisePropertyChanged("LikeStatus");
 }
        /// <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="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary <String, Object> pageState)
        {
            if (pageState != null && pageState.ContainsKey("ScrollOffset"))
            {
                _scrollOffset = pageState["ScrollOffset"] as Nullable <double> ?? 0.0;

                linksView.Loaded += linksView_Loaded;
            }

            if (pageState != null && pageState.ContainsKey("SelectedSubredditMessage"))
            {
                _selectedSubredditMessage = pageState["SelectedSubredditMessage"] as SelectSubredditMessage;
                Messenger.Default.Send <SelectSubredditMessage>(_selectedSubredditMessage);
            }
            else if (navigationParameter != null)
            {
                if (navigationParameter is SelectSubredditMessage)
                {
                    _selectedSubredditMessage = navigationParameter as SelectSubredditMessage;
                    Messenger.Default.Send <SelectSubredditMessage>(_selectedSubredditMessage);
                }
                else if (navigationParameter is string)
                {
                    var navString = navigationParameter as string;
                    var thing     = JsonConvert.DeserializeObject <Thing>(navString);
                    if (thing != null)
                    {
                        var link      = thing.Data as Link;
                        var subreddit = thing.Data as Subreddit;

                        if (link != null)
                        {
                            var linkMessage = new NavigateToUrlMessage();
                            linkMessage.TargetUrl = link.Url;
                            linkMessage.Title     = link.Title;
                            Messenger.Default.Send <NavigateToUrlMessage>(linkMessage);
                        }
                        else if (subreddit != null)
                        {
                            var selectSubreddit = new SelectSubredditMessage();
                            var typedSubreddit  = new TypedThing <Subreddit>(new Thing {
                                Kind = "t5", Data = subreddit
                            });
                            selectSubreddit.Subreddit = new TypedThing <Subreddit>(typedSubreddit);
                            Messenger.Default.Send <SelectSubredditMessage>(selectSubreddit);
                        }
                    }
                }
            }
            else
            {
                Messenger.Default.Send <SelectSubredditMessage>(null);
            }
        }
 public override void Cleanup()
 {
     base.Cleanup();
     if (Comments != null)
     {
         Comments.Clear();
         Comments.Dispose();
     }
     Comments   = null;
     _linkThing = null;
 }
Exemple #13
0
 public LinkViewModel(Thing linkThing, IBaconProvider baconProvider)
 {
     _linkThing              = new TypedThing <Link>(linkThing);
     _baconProvider          = baconProvider;
     _redditService          = _baconProvider.GetService <IRedditService>();
     _navigationService      = _baconProvider.GetService <INavigationService>();
     _imagesService          = _baconProvider.GetService <IImagesService>();
     _dynamicViewLocator     = _baconProvider.GetService <IDynamicViewLocator>();
     _isPreviewShown         = false;
     _isExtendedOptionsShown = false;
     ShowPreview             = new RelayCommand(() => IsPreviewShown = !IsPreviewShown);
     ShowExtendedOptions     = new RelayCommand(() => IsExtendedOptionsShown = !IsExtendedOptionsShown);
 }
        // Take a subreddit thing and generate a pinned secondary tile. Use the display
        // name and subreddit header image in the tile.
        public async Task CreateSecondaryTileForSubreddit(TypedThing <Subreddit> subreddit)
        {
            try
            {
                string id = "";
                if (subreddit != null)
                {
                    id = subreddit.Data.DisplayName;
                }

                SecondaryTile tile = new SecondaryTile();
                tile.TileOptions = TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo;
                tile.DisplayName = "Baconography";
                tile.ShortName   = "/r/" + id;
                if (subreddit != null)
                {
                    // Download and create a local copy of the header image
                    var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");

                    // Generate a wide tile appropriate image
                    var wideImage = await _imagesService.GenerateResizedImage(rawImage, 310, 150) as StorageFile;

                    // Generate a square tile appropriate image
                    var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

                    tile.WideLogo = new Uri("ms-appdata:///local/Images/" + wideImage.Name);
                    tile.Logo     = new Uri("ms-appdata:///local/Images/" + squareImage.Name);
                    subreddit.Data.PublicDescription = null;
                    subreddit.Data.Description       = null;
                    subreddit.Data.Headertitle       = null;
                    tile.Arguments = JsonConvert.SerializeObject(subreddit);
                }
                else
                {
                    Uri logo     = new Uri("ms-appx:///Assets/Logo.png");
                    Uri wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
                    tile.Arguments = "/r/";
                    tile.Logo      = logo;
                    tile.WideLogo  = wideLogo;
                }
                tile.TileId = "r" + id;

                // Ask the user to authorize creation of the tile
                bool isPinned = await tile.RequestCreateAsync();
            }
            catch (Exception)
            {
                // TODO: Do something with exceptions
            }
        }
        // Take a subreddit thing and generate a pinned secondary tile. Use the display
        // name and subreddit header image in the tile.
        public async Task CreateSecondaryTileForSubreddit(TypedThing<Subreddit> subreddit)
        {
            try
            {
                string id = "";
                if (subreddit != null)
                    id = subreddit.Data.DisplayName;

                SecondaryTile tile = new SecondaryTile();
                tile.TileOptions = TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo;
                tile.DisplayName = "Baconography";
                tile.ShortName = "/r/" + id;
                if (subreddit != null)
                {

                    // Download and create a local copy of the header image
                    var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");
                    // Generate a wide tile appropriate image
                    var wideImage = await _imagesService.GenerateResizedImage(rawImage, 310, 150) as StorageFile;
                    // Generate a square tile appropriate image
                    var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

                    tile.WideLogo = new Uri("ms-appdata:///local/Images/" + wideImage.Name);
                    tile.Logo = new Uri("ms-appdata:///local/Images/" + squareImage.Name);
                    subreddit.Data.PublicDescription = null;
                    subreddit.Data.Description = null;
                    subreddit.Data.Headertitle = null;
                    tile.Arguments = JsonConvert.SerializeObject(subreddit);
                }
                else
                {
                    Uri logo = new Uri("ms-appx:///Assets/Logo.png");
                    Uri wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
                    tile.Arguments = "/r/";
                    tile.Logo = logo;
                    tile.WideLogo = wideLogo;
                }
                tile.TileId = "r" + id;

                // Ask the user to authorize creation of the tile
                bool isPinned = await tile.RequestCreateAsync();
            }
            catch (Exception)
            {
                // TODO: Do something with exceptions
            }
        }
Exemple #16
0
        private async void OnSubredditChanged(SelectSubredditMessage message)
        {
            if (_selectedSubreddit == null && message == null)
            {
                return;
            }
            if (message != null)
            {
                if (message.Subreddit == _selectedSubreddit)
                {
                    return;
                }

                _selectedSubreddit = message.Subreddit;
                SelectedLink       = null;
                RefreshLinks();

                Heading = _selectedSubreddit.Data.DisplayName;

                RaisePropertyChanged("DisplayingSubreddit");
                var currentUser = await _userService.GetUser();

                if (currentUser != null && currentUser.Me != null)
                {
                    _subscribed = (await _redditService.GetSubscribedSubreddits()).Contains(_selectedSubreddit.Data.Name);
                    RaisePropertyChanged("NotSubscribed");
                    RaisePropertyChanged("Subscribed");
                }
            }
            else
            {
                //set us back to default state
                _selectedSubreddit = null;
                SelectedLink       = null;
                _links             = null;
                Heading            = null;
                RaisePropertyChanged("DisplayingSubreddit");
                _subscribed = false;
                RaisePropertyChanged("NotSubscribed");
                RaisePropertyChanged("Subscribed");
            }
        }
        //get the thumbnail url, the processed image url and the typed link thing
        private async Task <Tuple <string, string, TypedThing <Link> > > MapLink(Thing link)
        {
            var    linkThing         = new TypedThing <Link>(link);
            string processedImageUrl = null;
            string thumbnail         = null;
            var    imagesTpls        = await _imagesService.GetImagesFromUrl("", linkThing.Data.Url);

            var imageTpl = imagesTpls.FirstOrDefault();

            if (imageTpl != null)
            {
                processedImageUrl = imageTpl.Item2;
            }

            if (linkThing.Data.Thumbnail != "default" && linkThing.Data.Thumbnail != "nsfw" && linkThing.Data.Thumbnail != "self")
            {
                thumbnail = linkThing.Data.Thumbnail;
            }

            return(Tuple.Create(thumbnail, processedImageUrl, linkThing));
        }
 public CommentViewModel(IBaconProvider baconProvider, Thing comment, string linkId, bool oddNesting, int depth = 0)
 {
     _isMinimized        = false;
     _comment            = new TypedThing <Comment>(comment);
     _baconProvider      = baconProvider;
     _redditService      = _baconProvider.GetService <IRedditService>();
     _navigationService  = _baconProvider.GetService <INavigationService>();
     _userService        = _baconProvider.GetService <IUserService>();
     _dynamicViewLocator = _baconProvider.GetService <IDynamicViewLocator>();
     _linkId             = linkId;
     OddNesting          = oddNesting;
     Depth             = depth;
     AuthorFlair       = _redditService.GetUsernameModifiers(_comment.Data.Author, _linkId, _comment.Data.Subreddit);
     _showExtendedView = new RelayCommand(ShowExtendedViewImpl);
     _gotoReply        = new RelayCommand(GotoReplyImpl);
     _save             = new RelayCommand(SaveImpl);
     _report           = new RelayCommand(ReportImpl);
     _gotoFullLink     = new RelayCommand(GotoFullLinkImpl);
     _gotoContext      = new RelayCommand(GotoContextImpl);
     _gotoUserDetails  = new RelayCommand(GotoUserDetailsImpl);
     _minimizeCommand  = new RelayCommand(() => IsMinimized = !IsMinimized);
     //MessengerInstance.Register<ToggleCommentTreeMessage>(this, OnToggleCommentTreeMessage);
 }
        public static async void GotoLinkImpl(string str)
        {
            var baconProvider     = ServiceLocator.Current.GetInstance <IBaconProvider>();
            var navigationService = baconProvider.GetService <INavigationService>();

            if (_commentRegex.IsMatch(str))
            {
                var lastSlash       = str.LastIndexOf('/');
                var commentRoot     = str.Remove(lastSlash);
                var targetLinkThing = await baconProvider.GetService <IRedditService>().GetLinkByUrl(str);

                await baconProvider.GetService <IOfflineService>().StoreHistory(commentRoot);

                if (targetLinkThing != null)
                {
                    var typedLinkThing = new TypedThing <Link>(targetLinkThing);
                    typedLinkThing.Data.Permalink = str;
                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().CommentsView, new SelectCommentTreeMessage {
                        LinkThing = typedLinkThing
                    });
                }
                else
                {
                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage {
                        TargetUrl = str, Title = str
                    });
                }
            }
            else if (_commentsPageRegex.IsMatch(str))
            {
                var targetLinkThing = await baconProvider.GetService <IRedditService>().GetLinkByUrl(str);

                if (targetLinkThing != null)
                {
                    var typedLinkThing = new TypedThing <Link>(targetLinkThing);
                    await baconProvider.GetService <IOfflineService>().StoreHistory(typedLinkThing.Data.Permalink);

                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().CommentsView, new SelectCommentTreeMessage {
                        LinkThing = typedLinkThing
                    });
                }
                else
                {
                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage {
                        TargetUrl = str, Title = str
                    });
                }
            }
            else if (_subredditRegex.IsMatch(str))
            {
                var nameIndex     = str.LastIndexOf("/r/");
                var subredditName = str.Substring(nameIndex + 3);

                TypedThing <Subreddit> subreddit = null;

                var settingsService = ServiceLocator.Current.GetInstance <ISettingsService>();
                var offlineService  = ServiceLocator.Current.GetInstance <IOfflineService>();
                if (settingsService.IsOnline())
                {
                    subreddit = await baconProvider.GetService <IRedditService>().GetSubreddit(subredditName);
                }
                else
                {
                    var thing = await offlineService.GetSubreddit(subredditName);

                    if (thing != null)
                    {
                        subreddit = new TypedThing <Subreddit>(thing);
                    }
                }

                if (subreddit != null)
                {
                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().RedditView, new SelectSubredditMessage {
                        Subreddit = subreddit
                    });
                }
                else
                {
                    ServiceLocator.Current.GetInstance <INotificationService>().CreateNotification("This subreddit is not available in offline mode");
                }
            }
            else if (_userRegex.IsMatch(str))
            {
                var    nameIndex = str.LastIndexOf("/u/");
                string userName  = "";
                if (nameIndex < 0)
                {
                    nameIndex = str.LastIndexOf("/user/");
                    userName  = str.Substring(nameIndex + 6);
                }
                else
                {
                    userName = str.Substring(nameIndex + 3);
                }

                TypedThing <Account> account = null;

                var settingsService = ServiceLocator.Current.GetInstance <ISettingsService>();
                var offlineService  = ServiceLocator.Current.GetInstance <IOfflineService>();
                if (settingsService.IsOnline())
                {
                    account = await baconProvider.GetService <IRedditService>().GetAccountInfo(userName);

                    if (account != null)
                    {
                        navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().AboutUserView, new SelectUserAccountMessage {
                            Account = account
                        });
                    }
                    else
                    {
                        ServiceLocator.Current.GetInstance <INotificationService>().CreateNotification("This account does not exist.");
                    }
                }
                else
                {
                    ServiceLocator.Current.GetInstance <INotificationService>().CreateNotification("Cannot access user info in offline mode.");
                }
            }
            else
            {
                await baconProvider.GetService <IOfflineService>().StoreHistory(str);

                var imageResults = await baconProvider.GetService <IImagesService>().GetImagesFromUrl("", str);

                if (imageResults != null && imageResults.Count() > 0)
                {
                    navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().LinkedPictureView, imageResults);
                }
                else
                {
                    var videoResults = await baconProvider.GetService <IVideoService>().GetPlayableStreams(str);

                    if (videoResults != null)
                    {
                        navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().LinkedVideoView, videoResults);
                    }
                    else
                    {
                        //its not an image/video url we can understand so whatever it is just show it in the browser
                        navigationService.Navigate(baconProvider.GetService <IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage {
                            TargetUrl = str, Title = str
                        });
                    }
                }
            }
        }
        public async void GotoLink(object contextObj, string url)
        {
			var context = contextObj as ViewModelBase;
            if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
            {
                return;
            }

            var task = SnooStreamViewModel.NotificationService.ModalReportWithCancelation(string.Format("navigating to {0}", url), async (token) =>
            {
                var sourceLink = context is LinkViewModel ? ((LinkViewModel)context).Link : null;
                var linkContext = context as LinkViewModel;
                var riverContext = linkContext != null ? linkContext.Context : null;

				if (context is LinkViewModel)
				{
					var linkRiver = ((LinkViewModel)context).Context as LinkRiverViewModel;
					if(linkRiver != null)
						linkRiver.CurrentlyFocused = context as ViewModelBase;
				}

                if (CommentRegex.IsMatch(url))
                {
                    var targetLinkThing = sourceLink == null ? await SnooStreamViewModel.RedditService.GetLinkByUrl(url) :
                        new Thing { Kind = "t3", Data = new Link { Permalink = url, Url = url, Title = url, Name = "", Author = "", Selftext = "" } };

                    token.ThrowIfCancellationRequested();

                    if (targetLinkThing != null && targetLinkThing.Data is Link)
                        SnooStreamViewModel.NavigationService.NavigateToComments(new CommentsViewModel(context, targetLinkThing.Data as Link));
                    else
                    {
                        SnooStreamViewModel.NavigationService.NavigateToWeb(url);
                    }
                }
                else if (CommentsPageRegex.IsMatch(url))
                {
                    if (sourceLink != null)
                    {
                        var realTarget = await SnooStreamViewModel.RedditService.GetLinkByUrl(url);
                        if (realTarget != null)
                        {
                            sourceLink = realTarget.Data as Link;
                        }
                    }

                    var targetLinkThing = sourceLink == null ? await SnooStreamViewModel.RedditService.GetLinkByUrl(url) : new Thing { Kind = "t3", Data = sourceLink };

                    token.ThrowIfCancellationRequested();

                    if (targetLinkThing != null)
                    {
                        SnooStreamViewModel.OfflineService.AddHistory(((Link)targetLinkThing.Data).Permalink);
                        SnooStreamViewModel.NavigationService.NavigateToComments(new CommentsViewModel(context, targetLinkThing.Data as Link));
                    }
                    else
                    {
                        SnooStreamViewModel.NavigationService.NavigateToWeb(url);
                    }
                }
                else if (ShortCommentsPageRegex.IsMatch(url))
                {
                    var thingId = "t3_" + url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
                    var targetLinkThing = sourceLink == null ? await SnooStreamViewModel.RedditService.GetThingById(thingId) : new Thing { Kind = "t3", Data = sourceLink };

                    token.ThrowIfCancellationRequested();

                    if (targetLinkThing != null)
                    {
                        SnooStreamViewModel.OfflineService.AddHistory(((Link)targetLinkThing.Data).Permalink);
                        SnooStreamViewModel.NavigationService.NavigateToComments(new CommentsViewModel(context, targetLinkThing.Data as Link));
                    }
                    else
                    {
                        SnooStreamViewModel.NavigationService.NavigateToWeb(url);
                    }
                }
                else if (SubredditRegex.IsMatch(url))
                {
                    var nameIndex = url.LastIndexOf("/r/");
                    var subredditName = url.Substring(nameIndex + 3);

                    TypedThing<Subreddit> subreddit = null;

                    if (SnooStreamViewModel.SystemServices.IsHighPriorityNetworkOk)
                    {
                        subreddit = await SnooStreamViewModel.RedditService.GetSubredditAbout(subredditName);
                    }
                    else
                    {
                        var thing = await SnooStreamViewModel.OfflineService.GetSubreddit(subredditName);
                        if (thing != null)
                            subreddit = new TypedThing<Subreddit>(thing);
                    }

                    token.ThrowIfCancellationRequested();

                    if (subreddit != null)
                        SnooStreamViewModel.NavigationService.NavigateToLinkRiver(new LinkRiverViewModel(null, "", subreddit.Data, null, null, null));
                    else
                        throw new RedditException("subreddit unavailable");
                }
                else if (UserMultiredditRegex.IsMatch(url))
                {
                    var nameIndex = url.LastIndexOf("/u/");
                    string subredditName = "";
                    if (nameIndex < 0)
                    {
                        nameIndex = url.LastIndexOf("/user/");
                        subredditName = url.Substring(nameIndex);
                    }
                    else
                    {
                        subredditName = url.Substring(nameIndex);
                    }

                    subredditName = subredditName.Replace("/u/", "/user/");

                    TypedThing<Subreddit> subreddit = null;

                    if (SnooStreamViewModel.SystemServices.IsHighPriorityNetworkOk)
                    {
                        subreddit = await SnooStreamViewModel.RedditService.GetSubredditAbout(subredditName);
                    }
                    else
                    {
                        var thing = await SnooStreamViewModel.OfflineService.GetSubreddit(subredditName);
                        if (thing != null)
                            subreddit = new TypedThing<Subreddit>(thing);
                    }

                    token.ThrowIfCancellationRequested();

                    if (subreddit != null)
                        SnooStreamViewModel.NavigationService.NavigateToLinkRiver(new LinkRiverViewModel(null, "", subreddit.Data, null, null, null));
                    else
                        throw new RedditException("subreddit unavailable");
                }
                else if (UserRegex.IsMatch(url))
                {
                    var nameIndex = url.LastIndexOf("/u/");
                    string userName = "";
                    if (nameIndex < 0)
                    {
                        nameIndex = url.LastIndexOf("/user/");
                        userName = url.Substring(nameIndex + 6);
                    }
                    else
                    {
                        userName = url.Substring(nameIndex + 3);
                    }

                    if (SnooStreamViewModel.SystemServices.IsHighPriorityNetworkOk)
                    {
                        SnooStreamViewModel.NavigationService.NavigateToAboutUser(new AboutUserViewModel(userName));
                    }
                    else
                    {
                        throw new RedditException("userinfo unavailable");
                    }
                }
                else
                {
					if (context is LinkViewModel)
					{
						var linkRiver = ((LinkViewModel)context).Context as LinkRiverViewModel;
						SnooStreamViewModel.NavigationService.NavigateToContentRiver(linkRiver);
					}
					else if (contextObj is Tuple<CommentsViewModel, CommentViewModel, string>)
					{
						var contextTpl = contextObj as Tuple<CommentsViewModel, CommentViewModel, string>;
						var contentStream = contextTpl.Item1.CommentsContentStream;
                        var targetContent = contentStream.Links.FirstOrDefault(item => (contextTpl.Item2 == null || item.Id == contextTpl.Item2.Id) && item.Url == contextTpl.Item3);
						if (targetContent != null)
							contentStream.CurrentlyFocused = targetContent as ViewModelBase;

						SnooStreamViewModel.NavigationService.NavigateToContentRiver(contentStream);
					}
                }
            });
            await task;
        }
 private void LoadAccount(TypedThing<Account> accountThing)
 {
     _accountThing = accountThing;
     Things = new UserActivityViewModelCollection(_baconProvider, _accountThing.Data.Name);
 }
Exemple #22
0
 public VotableViewModel(Thing votableThing, IBaconProvider baconProvider)
 {
     _votableThing  = new TypedThing <IVotable>(votableThing);
     _redditService = baconProvider.GetService <IRedditService>();
 }
        public static async void GotoLinkImpl(string str, TypedThing<Link> sourceLink)
        {
            if (!Uri.IsWellFormedUriString(str, UriKind.RelativeOrAbsolute))
            {
                return;
            }
            try
            {
                var settingsService = ServiceLocator.Current.GetInstance<ISettingsService>();
                _longNavWatcher.ClearInFlight();
                var baconProvider = ServiceLocator.Current.GetInstance<IBaconProvider>();
                var navigationService = baconProvider.GetService<INavigationService>();

                if (CommentRegex.IsMatch(str))
                {
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = true });
                    var targetLinkThing = sourceLink == null ? await baconProvider.GetService<IRedditService>().GetLinkByUrl(str) :
                        new Thing { Kind = "t3", Data = new Link { Permalink = str, Url = str, Title = str, Name = "", Author = "", Selftext = "" } };
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = false });
                    if (targetLinkThing != null && targetLinkThing.Data is Link)
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().CommentsView, new SelectCommentTreeMessage { LinkThing = new TypedThing<Link>(targetLinkThing) });
                    else
                    {
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage { TargetUrl = str, Title = str });
                    }
                }
                else if (CommentsPageRegex.IsMatch(str))
                {
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = true });
                    var targetLinkThing = sourceLink == null ? await baconProvider.GetService<IRedditService>().GetLinkByUrl(str) : sourceLink;
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = false });
                    if (targetLinkThing != null)
                    {
                        var typedLinkThing = new TypedThing<Link>(targetLinkThing);
                        await baconProvider.GetService<IOfflineService>().StoreHistory(typedLinkThing.Data.Permalink);
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().CommentsView, new SelectCommentTreeMessage { LinkThing = typedLinkThing });
                    }
                    else
                    {
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage { TargetUrl = str, Title = str });
                    }
                }
                else if (ShortCommentsPageRegex.IsMatch(str))
                {
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = true });
                    var thingId = "t3_" + str.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();
                    var targetLinkThing = sourceLink == null ? await baconProvider.GetService<IRedditService>().GetThingById(thingId) : sourceLink;
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = false });
                    if (targetLinkThing != null)
                    {
                        var typedLinkThing = new TypedThing<Link>(targetLinkThing);
                        await baconProvider.GetService<IOfflineService>().StoreHistory(typedLinkThing.Data.Permalink);
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().CommentsView, new SelectCommentTreeMessage { LinkThing = typedLinkThing });
                    }
                    else
                    {
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage { TargetUrl = str, Title = str });
                    }
                }
                else if (SubredditRegex.IsMatch(str))
                {
                    var nameIndex = str.LastIndexOf("/r/");
                    var subredditName = str.Substring(nameIndex + 3);

                    TypedThing<Subreddit> subreddit = null;

                    var offlineService = ServiceLocator.Current.GetInstance<IOfflineService>();
                    if (settingsService.IsOnline())
                    {
                        subreddit = await baconProvider.GetService<IRedditService>().GetSubreddit(subredditName);
                    }
                    else
                    {
                        var thing = await offlineService.GetSubreddit(subredditName);
                        if (thing != null)
                            subreddit = new TypedThing<Subreddit>(thing);
                    }

                    if (subreddit != null)
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().RedditView, new SelectSubredditMessage { Subreddit = subreddit });
                    else
                        ServiceLocator.Current.GetInstance<INotificationService>().CreateNotification("This subreddit is not available in offline mode");
                }
                else if (UserMultiredditRegex.IsMatch(str))
                {
                    var nameIndex = str.LastIndexOf("/u/");
                    string subredditName = "";
                    if (nameIndex < 0)
                    {
                        nameIndex = str.LastIndexOf("/user/");
                        subredditName = str.Substring(nameIndex);
                    }
                    else
                    {
                        subredditName = str.Substring(nameIndex);
                    }

                    subredditName = subredditName.Replace("/u/", "/user/");

                    TypedThing<Subreddit> subreddit = null;

                    var offlineService = ServiceLocator.Current.GetInstance<IOfflineService>();
                    if (settingsService.IsOnline())
                    {
                        subreddit = await baconProvider.GetService<IRedditService>().GetSubreddit(subredditName);
                    }
                    else
                    {
                        var thing = await offlineService.GetSubreddit(subredditName);
                        if (thing != null)
                            subreddit = new TypedThing<Subreddit>(thing);
                    }

                    if (subreddit != null)
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().RedditView, new SelectSubredditMessage { Subreddit = subreddit });
                    else
                        ServiceLocator.Current.GetInstance<INotificationService>().CreateNotification("This subreddit is not available in offline mode");
                }
                else if (UserRegex.IsMatch(str))
                {
                    var nameIndex = str.LastIndexOf("/u/");
                    string userName = "";
                    if (nameIndex < 0)
                    {
                        nameIndex = str.LastIndexOf("/user/");
                        userName = str.Substring(nameIndex + 6);
                    }
                    else
                    {
                        userName = str.Substring(nameIndex + 3);
                    }

                    TypedThing<Account> account = null;

                    var offlineService = ServiceLocator.Current.GetInstance<IOfflineService>();
                    if (settingsService.IsOnline())
                    {
                        account = await baconProvider.GetService<IRedditService>().GetAccountInfo(userName);

                        if (account != null)
                            navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().AboutUserView, new SelectUserAccountMessage { Account = account });
                        else
                            ServiceLocator.Current.GetInstance<INotificationService>().CreateNotification("This account does not exist.");
                    }
                    else
                    {
                        ServiceLocator.Current.GetInstance<INotificationService>().CreateNotification("Cannot access user info in offline mode.");
                    }
                }
                else
                {
                    var smartOfflineService = baconProvider.GetService<ISmartOfflineService>();
                    smartOfflineService.NavigatedToOfflineableThing(sourceLink, false);
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = true });
                    Messenger.Default.Send<LongNavigationMessage>(new LongNavigationMessage { Finished = false, TargetUrl = str });
                    await baconProvider.GetService<IOfflineService>().StoreHistory(str);
                    var imageResults = await baconProvider.GetService<IImagesService>().GetImagesFromUrl(sourceLink == null ? "" : sourceLink.Data.Title, str);
                    Messenger.Default.Send<LoadingMessage>(new LoadingMessage { Loading = false });

                    if (imageResults != null && imageResults.Count() > 0 && !_longNavWatcher.GetTerminatedClearInFlight(str))
                    {
                        var imageTuple = new Tuple<string, IEnumerable<Tuple<string, string>>, string>(sourceLink != null ? sourceLink.Data.Title : "", imageResults, sourceLink != null ? sourceLink.Data.Id : "");
                        Messenger.Default.Send<LongNavigationMessage>(new LongNavigationMessage { Finished = true, TargetUrl = str });
                        navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedPictureView, imageTuple);
                    }
                    else
                    {
                        var uri = new Uri(str);
                        var targetHost = uri.DnsSafeHost.ToLower();

                        Messenger.Default.Send<LongNavigationMessage>(new LongNavigationMessage { Finished = true, TargetUrl = str });
                        var videoResults = await baconProvider.GetService<IVideoService>().GetPlayableStreams(str);
                        if (videoResults != null)
                        {
                            navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedVideoView, videoResults);
                        }
                        else if (settingsService.ApplyReadabliltyToLinks && LinkGlyphUtility.GetLinkGlyph(str) == LinkGlyphUtility.WebGlyph)
                        {
                            navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedReadabilityView, Tuple.Create<string, string>(str, sourceLink != null ? sourceLink.Data.Id : ""));
                        }
                        else
                        {
                            //its not an image/video url we can understand so whatever it is just show it in the browser
                            navigationService.Navigate(baconProvider.GetService<IDynamicViewLocator>().LinkedWebView, new NavigateToUrlMessage { TargetUrl = str, Title = str });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ServiceLocator.Current.GetInstance<INotificationService>().CreateNotification(string.Format("failed to navigate to {0}, due to {1}", str, ex.ToString()));
            }
        }
 public bool MaybeMerge(ViewModelBase thing)
 {
     if (thing is LinkViewModel && ((LinkViewModel)thing).Id == Id)
     {
         _linkThing = ((LinkViewModel)thing).LinkThing;
         Votable.MergeVotable(_linkThing);
         RaisePropertyChanged("CommentCount");
         RaisePropertyChanged("CreatedUTC");
         return true;
     }
     else
         return false;
 }
 public TypedSubreddit(TypedThing<Subreddit> thing)
 {
     _thing = thing;
 }
        private async void GotoContextImpl()
        {
            try
            {
                if (_comment.Data.ParentId == null)
                    return;

                MessengerInstance.Send<LoadingMessage>(new LoadingMessage { Loading = true });
                var linkThing = new TypedThing<Link>(await _redditService.GetThingById(_comment.Data.LinkId));
                var parentThing = await _redditService.GetLinkByUrl("http://www.reddit.com/" + linkThing.Data.Permalink + _comment.Data.ParentId.Substring(3));
                var commentTree = new SelectCommentTreeMessage { LinkThing = new TypedThing<Link>(parentThing) };
                MessengerInstance.Send<LoadingMessage>(new LoadingMessage { Loading = false });
                _navigationService.Navigate(_dynamicViewLocator.CommentsView, commentTree);
            }
            catch (Exception ex)
            {
                _baconProvider.GetService<INotificationService>().CreateErrorNotification(ex);
            }
        }
 public override void Cleanup()
 {
     base.Cleanup();
     if (Comments != null)
     {
         Comments.Clear();
         Comments.Dispose();
     }
     Comments = null;
     _linkThing = null;
 }
 private void LoadLink(TypedThing<Link> link, TypedThing<Comment> rootComment)
 {
     _linkThing = link;
     if(_linkThing.Data.IsSelf)
         SelfText = _baconProvider.GetService<IMarkdownProcessor>().Process(_linkThing.Data.Selftext);
     SortOrder = "hot"; //load the hot comments
     //Comments = new CommentViewModelCollection(_baconProvider, _linkThing.Data.Permalink, _linkThing.Data.Subreddit, _linkThing.Data.SubredditId, _linkThing.Data.Name);
 }
        // Take a subreddit thing and generate a pinned secondary tile. Use the display
        // name and subreddit header image in the tile.
        public async Task CreateSecondaryTileForSubreddit(TypedThing<Subreddit> subreddit)
        {
            //try
           // {
            //    // Download and create a local copy of the header image
            //    var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");
            //    // Generate a square tile appropriate image
            //    var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

            //    string id = "";
            //    if (subreddit != null)
            //        id = subreddit.Data.DisplayName;


            //    var properties = (await squareImage.Properties.RetrievePropertiesAsync(new string[] { "System.ParsingPath" }));
                

            //    var tile = ShellTile.Create(new Uri(""), new StandardTileData { Title = subreddit.Data.Title, BackgroundImage = new Uri(properties["System.ParsingPath"] as string) );
            //    var tileSchedule = new ShellTileSchedule(tile);
            //    tileSchedule.
            //    SecondaryTile tile = new SecondaryTile();
            //    tile.TileOptions = TileOptions.ShowNameOnWideLogo | TileOptions.ShowNameOnLogo;
            //    tile.DisplayName = "Baconography";
            //    tile.ShortName = "/r/" + id;
            //    if (subreddit != null)
            //    {

            //        // Download and create a local copy of the header image
            //        var rawImage = await _imagesService.SaveFileFromUriAsync(new Uri(subreddit.Data.HeaderImage), subreddit.Data.DisplayName + ".jpg", "Images");
            //        // Generate a square tile appropriate image
            //        var squareImage = await _imagesService.GenerateResizedImage(rawImage, 150, 150) as StorageFile;

            //        tile.WideLogo = new Uri("ms-appdata:///local/Images/" + wideImage.Name);
            //        tile.Logo = new Uri("ms-appdata:///local/Images/" + squareImage.Name);
            //        subreddit.Data.PublicDescription = null;
            //        subreddit.Data.Description = null;
            //        subreddit.Data.Headertitle = null;
            //        tile.Arguments = JsonConvert.SerializeObject(subreddit);
            //    }
            //    else
            //    {
            //        Uri logo = new Uri("ms-appx:///Assets/Logo.png");
            //        Uri wideLogo = new Uri("ms-appx:///Assets/WideLogo.png");
            //        tile.Arguments = "/r/";
            //        tile.Logo = logo;
            //        tile.WideLogo = wideLogo;
            //    }
            //    tile.TileId = "r" + id;

            //    // Ask the user to authorize creation of the tile
            //    bool isPinned = await tile.RequestCreateAsync();
            //}
            //catch (Exception)
            //{
            //    // TODO: Do something with exceptions
            //}
        }
 private void LoadAccount(TypedThing <Account> accountThing)
 {
     _accountThing = accountThing;
     Things        = new UserActivityViewModelCollection(_baconProvider, _accountThing.Data.Name);
 }
        public async Task<TypedThing<Subreddit>> GetSubreddit(string name)
        {
            //no info for the front page
            if (name == "/")
                return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = name } });
            else if (name == "all")
                return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = "all", Url = "/r/all", Name = "all", DisplayName="all", Title="all", Id="t5_fakeid" } });

            string targetUri;
            if (!name.Contains("/m/"))
            {
                targetUri = string.Format("http://www.reddit.com/r/{0}/about.json", name);
                try
                {
                    var comments = await _simpleHttpService.SendGet(await GetCurrentLoginCookie(), targetUri);
                    //error page
                    if (comments.ToLower().StartsWith("<!doctype html>"))
                    {
                        return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = name, Title = name, Url = string.Format("r/{0}", name), Created = DateTime.Now, CreatedUTC = DateTime.UtcNow, DisplayName = name, Description = "there doesnt seem to be anything here", Name = name, Over18 = false, PublicDescription = "there doesnt seem to be anything here", Subscribers = 0 } });
                    }
                    else
                    {
                        return new TypedThing<Subreddit>(JsonConvert.DeserializeObject<Thing>(comments));
                    }
                }
                catch (Exception ex)
                {
                    //_notificationService.CreateErrorNotification(ex);
                    return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = name, Title = name, Url = string.Format("r/{0}", name), Created = DateTime.Now, CreatedUTC = DateTime.UtcNow, DisplayName = name, Description = "there doesnt seem to be anything here", Name = name, Over18 = false, PublicDescription = "there doesnt seem to be anything here", Subscribers = 0 } });
                }
            }
            else
            {
                var currentUser = await _userService.GetUser();
                if (name.StartsWith("/"))
                    name = name.TrimStart('/');

                if (name.StartsWith("me/"))
                {
                   name = name.Replace("me/", "user/" + currentUser.Username + "/");
                }

                targetUri = string.Format("http://www.reddit.com/api/multi/{0}.json", name);
                try
                {
                    var comments = await _simpleHttpService.SendGet(await GetCurrentLoginCookie(), targetUri);
                    //error page
                    if (comments.ToLower().StartsWith("<!doctype html>"))
                    {
                        return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = name, Title = name, Url = string.Format("r/{0}", name), Created = DateTime.Now, CreatedUTC = DateTime.UtcNow, DisplayName = name, Description = "there doesnt seem to be anything here", Name = name, Over18 = false, PublicDescription = "there doesnt seem to be anything here", Subscribers = 0 } });
                    }
                    else
                    {
                        
                        var labeledMulti = new TypedThing<LabeledMulti>(JsonConvert.DeserializeObject<Thing>(comments));
                        var multiPath = labeledMulti.Data.Path;

                        if(!string.IsNullOrWhiteSpace(currentUser.Username))
                            multiPath = multiPath.Replace("/user/" + currentUser.Username, "/me");

                        return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { DisplayName = labeledMulti.Data.Name, Title = labeledMulti.Data.Name, Url = multiPath, Headertitle = labeledMulti.Data.Name, Over18 = false } });
                    }
                }
                catch (Exception ex)
                {
                    //_notificationService.CreateErrorNotification(ex);
                    return new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = new Subreddit { Headertitle = name, Title = name, Url = string.Format("r/{0}", name), Created = DateTime.Now, CreatedUTC = DateTime.UtcNow, DisplayName = name, Description = "there doesnt seem to be anything here", Name = name, Over18 = false, PublicDescription = "there doesnt seem to be anything here", Subscribers = 0 } });
                }
            }

            
        }
		protected override async void OnNavigatedFrom(NavigationEventArgs e)
		{
			if (e.NavigationMode == NavigationMode.Back)
			{
				if (pinnedSubredditList.Items.Count == 0)
				{
					var frontPage = new TypedThing<Subreddit>(ThingUtility.GetFrontPageThing());
					Messenger.Default.Send<SelectSubredditMessage>(new SelectSubredditMessage { Subreddit = frontPage });
				}
				else
				{
					Messenger.Default.Send<ReorderSubredditMessage>(new ReorderSubredditMessage());
				}
			}
		}
        private async Task<Listing> GetUserMultis(Listing listing)
        {
            var targetUri = string.Format("http://www.reddit.com/api/multi/mine.json");

            try
            {
                var subreddits = await _simpleHttpService.SendGet(await GetCurrentLoginCookie(), targetUri);
                if (subreddits == "[]")
                    return listing;
                else
                {
                    var currentUser = await _userService.GetUser();
                    var userMultis = JsonConvert.DeserializeObject<Thing[]>(subreddits);
                    foreach (var thing in userMultis)
                    {
                        var labeledMulti = new TypedThing<LabeledMulti>(thing);
                        var multiPath = labeledMulti.Data.Path;

                        multiPath = multiPath.Replace("/user/" + currentUser.Username, "/me");

                        listing.Data.Children.Insert(0, (new Thing { Kind = "t5", Data = new Subreddit { DisplayName = labeledMulti.Data.Name, HeaderImage = "/Assets/multireddit.png", Title = labeledMulti.Data.Name, Url = multiPath, Headertitle = labeledMulti.Data.Name, Over18 = false } }));
                    }
                }
            }
                //this api is most likely still in flux just silently fail if they break us down the line
            catch {}
            return listing;
        }
        public async void GotoSubreddit(string subreddit)
        {
            await SnooStreamViewModel.NotificationService.ModalReportWithCancelation(string.Format("navigating to {0}", subreddit), async (token) =>
            {
                TypedThing<Subreddit> subredditThing = null;
                if (SnooStreamViewModel.SystemServices.IsHighPriorityNetworkOk)
                {
                    subredditThing = await SnooStreamViewModel.RedditService.GetSubredditAbout(subreddit);
                }
                else
                {
                    var thing = await SnooStreamViewModel.OfflineService.GetSubreddit(subreddit);
                    if (thing != null)
                        subredditThing = new TypedThing<Subreddit>(thing);
                }

                token.ThrowIfCancellationRequested();

                if (subredditThing != null)
                    SnooStreamViewModel.NavigationService.NavigateToLinkRiver(new LinkRiverViewModel(null, "", subredditThing.Data, null, null, null));
                else
                    throw new RedditException("subreddit unavailable");
            });
        }
 private void LoadLink(TypedThing <Link> link, TypedThing <Comment> rootComment)
 {
     _linkThing = link;
     Comments   = new CommentViewModelCollection(_baconProvider, _linkThing.Data.Permalink, _linkThing.Data.Subreddit, _linkThing.Data.SubredditId, _linkThing.Data.Name);
 }
 public async Task StoreSubreddit(TypedThing<Subreddit> subreddit)
 {
     await Initialize();
     if (_terminateSource.IsCancellationRequested)
         return;
     await _subreddits.StoreSubreddit(subreddit);
 }
        /// <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="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            if (pageState != null && pageState.ContainsKey("ScrollOffset"))
            {
                _scrollOffset = pageState["ScrollOffset"] as Nullable<double> ?? 0.0;

                linksView.Loaded += linksView_Loaded;
            }

            if (pageState != null && pageState.ContainsKey("SelectedSubredditMessage"))
            {
                _selectedSubredditMessage = pageState["SelectedSubredditMessage"] as SelectSubredditMessage;
                Messenger.Default.Send<SelectSubredditMessage>(_selectedSubredditMessage);
            }
            else if (navigationParameter != null)
            {
                if (navigationParameter is SelectSubredditMessage)
                {
                    _selectedSubredditMessage = navigationParameter as SelectSubredditMessage;
                    Messenger.Default.Send<SelectSubredditMessage>(_selectedSubredditMessage);
                }
                else if (navigationParameter is string)
                {
                    var navString = navigationParameter as string;
                    var thing = JsonConvert.DeserializeObject<Thing>(navString);
                    if (thing != null)
                    {
                        var link = thing.Data as Link;
                        var subreddit = thing.Data as Subreddit;

                        if (link != null)
                        {
                            var linkMessage = new NavigateToUrlMessage();
                            linkMessage.TargetUrl = link.Url;
                            linkMessage.Title = link.Title;
                            Messenger.Default.Send<NavigateToUrlMessage>(linkMessage);
                        }
                        else if (subreddit != null)
                        {
                            var selectSubreddit = new SelectSubredditMessage();
                            var typedSubreddit = new TypedThing<Subreddit>(new Thing { Kind = "t5", Data = subreddit });
                            selectSubreddit.Subreddit = new TypedThing<Subreddit>(typedSubreddit);
                            Messenger.Default.Send<SelectSubredditMessage>(selectSubreddit);
                        }
                    }
                }
            }
            else
            {
                Messenger.Default.Send<SelectSubredditMessage>(null);
            }
        }
        public async Task StoreLinks(Listing listing)
        {
            await Initialize();

            try
            {
                await _links.StoreLinks(listing);

                foreach (var link in listing.Data.Children)
                {
                    if (link.Data is Link)
                    {
                        await _subreddits.StoreSubreddit(((Link)link.Data).SubredditId, ((Link)link.Data).Subreddit);

                        Messenger.Default.Send <OfflineStatusMessage>(new OfflineStatusMessage {
                            LinkId = ((Link)link.Data).Id, Status = OfflineStatusMessage.OfflineStatus.Initial
                        });
                    }
                }


                _notificationService.CreateKitaroDBNotification(string.Format("{0} Links now available offline", listing.Data.Children.Count));
                //this is where we should kick off the non reddit content getter/converter on a seperate thread

                var remainingMoreThings = new List <Tuple <Link, TypedThing <More> > >();


                foreach (var link in listing.Data.Children)
                {
                    bool finishedLink = true;
                    var  linkData     = link.Data as Link;
                    if (linkData != null)
                    {
                        var comments = await _redditService.GetCommentsOnPost(linkData.Subreddit, linkData.Permalink, null);

                        if (comments != null)
                        {
                            if (comments.Data.Children.Count == 0)
                            {
                                throw new Exception();
                            }
                            await(await Comments.GetInstance()).StoreComments(comments);
                            var moreChild = comments.Data.Children.LastOrDefault(comment => comment.Data is More);
                            if (moreChild != null)
                            {
                                TypedThing <More> moreThing = new TypedThing <More>(moreChild);
                                if (moreThing != null && moreThing.Data.Children.Count > 0)
                                {
                                    if (moreThing.Data.Children.Count > _settingsService.MaxTopLevelOfflineComments)
                                    {
                                        moreThing.Data.Children.RemoveRange(_settingsService.MaxTopLevelOfflineComments, moreThing.Data.Children.Count - _settingsService.MaxTopLevelOfflineComments - 1);
                                    }
                                    finishedLink = false;
                                    remainingMoreThings.Add(Tuple.Create(linkData, moreThing));
                                }
                            }
                        }
                    }
                    Messenger.Default.Send <OfflineStatusMessage>(new OfflineStatusMessage {
                        LinkId = linkData.Id, Status = finishedLink ? OfflineStatusMessage.OfflineStatus.AllComments : OfflineStatusMessage.OfflineStatus.TopComments
                    });
                }

                _notificationService.CreateKitaroDBNotification("Inital comments for offline links now available");

                //we've seperated getting the links and initial comments because we want to prioritize getting some data for all of the links instead of all the data for a very small number of links
                //ex, someone getting on a plane in 5 minutes wants to get what they can on a broad a selection of links as possible, rather than all of the comments on the latest 10 bazilion comment psy ama

                if (!_settingsService.OfflineOnlyGetsFirstSet)
                {
                    uint commentCount = 0;
                    foreach (var moreThingTpl in remainingMoreThings)
                    {
                        var moreThing = moreThingTpl.Item2;
                        var linkData  = moreThingTpl.Item1;

                        while (moreThing != null && moreThing.Data.Children.Count > 0)
                        {
                            var moreChildren = moreThing.Data.Children.Take(500).ToList();
                            var moreComments = await _redditService.GetMoreOnListing(moreChildren, linkData.Name, linkData.Subreddit);

                            var moreMoreComments = moreComments.Data.Children.FirstOrDefault(thing => thing.Data is More);
                            if (moreMoreComments != null)
                            {
                                //we asked for more then reddit was willing to give us back
                                //just make sure we dont lose anyone
                                moreChildren.RemoveAll((str) => ((More)moreMoreComments.Data).Children.Contains(str));
                                //all thats left is what was returned so remove them by value from the moreThing
                                moreThing.Data.Children.RemoveAll((str) => moreChildren.Contains(str));
                                commentCount += (uint)((More)moreMoreComments.Data).Children.Count;
                            }
                            else
                            {
                                moreThing.Data.Children.RemoveRange(0, moreChildren.Count);
                            }
                            await(await Comments.GetInstance()).StoreComments(moreComments);
                        }
                        Messenger.Default.Send <OfflineStatusMessage>(new OfflineStatusMessage {
                            LinkId = linkData.Id, Status = OfflineStatusMessage.OfflineStatus.AllComments
                        });
                    }
                    _notificationService.CreateKitaroDBNotification(string.Format("{0} Top level comments for offline links now available", commentCount));
                }
            }
            catch (Exception ex)
            {
                _notificationService.CreateErrorNotification(ex);
            }
        }
        private async void OnSubredditChanged(SelectSubredditMessage message)
        {
            if (_selectedSubreddit == null && message == null)
                return;
            if (message != null)
            {
                if (message.Subreddit == _selectedSubreddit)
                {
                    return;
                }

                _selectedSubreddit = message.Subreddit;
                SelectedLink = null;
				if (!message.DontRefresh)
				{
					_links = null;
					RefreshLinks();
				}

				Heading = _selectedSubreddit.Data.DisplayName;

                RaisePropertyChanged("DisplayingSubreddit");
                var currentUser = await _userService.GetUser();
                if (currentUser != null && currentUser.Me != null)
                {
                    _subscribed = (await _redditService.GetSubscribedSubreddits()).Contains(_selectedSubreddit.Data.Name);
                    RaisePropertyChanged("NotSubscribed");
                    RaisePropertyChanged("Subscribed");
                }
            }
            else
            {
                //set us back to default state
                _selectedSubreddit = null;
                SelectedLink = null;
                _links = null;
                Heading = null;
                RaisePropertyChanged("DisplayingSubreddit");
                _subscribed = false;
                RaisePropertyChanged("NotSubscribed");
                RaisePropertyChanged("Subscribed");

            }
        }