Beispiel #1
0
        protected ContentViewModel(ISessionService sessionService)
        {
            OpenWithCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.SourceItem).Select(x => x != null));
            Theme           = sessionService.Account.CodeEditTheme ?? "idea";

            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>()
            .Select(x => this.CreateViewModel <WebBrowserViewModel>().Init(x))
            .Subscribe(NavigateTo);
        }
Beispiel #2
0
        protected ContentViewModel(IAccountsService accounts)
        {
            OpenWithCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.SourceItem).Select(x => x != null));
            Theme           = accounts.ActiveAccount.CodeEditTheme ?? "idea";

            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>().Subscribe(x =>
            {
                var vm = this.CreateViewModel <WebBrowserViewModel>();
                vm.Url = x;
                NavigateTo(vm);
            });
        }
        protected BaseViewModel()
        {
            _viewModelActivator = new ViewModelActivator();

            DismissCommand = ReactiveCommand.Create();

            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>().Subscribe(x =>
            {
                var vm = CreateViewModel <WebBrowserViewModel>();
                vm.Url = x;
                ShowViewModel(vm);
            });
        }
Beispiel #4
0
        public ReleaseViewModel(IApplicationService applicationService, IMarkdownService markdownService, IShareService shareService)
        {
            ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ReleaseModel).Select(x => x != null));
            ShareCommand.Subscribe(_ => shareService.ShareUrl(ReleaseModel.HtmlUrl));

            GoToGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ReleaseModel).Select(x => x != null));
            GoToGitHubCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(ReleaseModel.HtmlUrl));

            GoToLinkCommand = ReactiveCommand.Create();
            GoToLinkCommand.OfType <string>().Subscribe(x => GoToUrlCommand.ExecuteIfCan(x));

            _contentText = this.WhenAnyValue(x => x.ReleaseModel).IsNotNull()
                           .Select(x => markdownService.Convert(x.Body)).ToProperty(this, x => x.ContentText);

            LoadCommand = ReactiveCommand.CreateAsyncTask(x =>
                                                          this.RequestModel(applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetRelease(ReleaseId),
                                                                            x as bool?, r => ReleaseModel = r.Data));
        }
        public ReadmeViewModel(IApplicationService applicationService, IMarkdownService markdownService, IShareService shareService)
        {
            ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ContentModel).Select(x => x != null));
            ShareCommand.Subscribe(_ => shareService.ShareUrl(ContentModel.HtmlUrl));

            GoToGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.ContentModel).Select(x => x != null));
            GoToGitHubCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(ContentModel.HtmlUrl));

            GoToLinkCommand = ReactiveCommand.Create();
            GoToLinkCommand.OfType <string>().Subscribe(x => GoToUrlCommand.ExecuteIfCan(x));

            LoadCommand = ReactiveCommand.CreateAsyncTask(x =>
                                                          this.RequestModel(applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReadme(), x as bool?, r =>
            {
                ContentModel = r.Data;
                var content  = Convert.FromBase64String(ContentModel.Content);
                ContentText  = markdownService.Convert(Encoding.UTF8.GetString(content, 0, content.Length));
            }));
        }
Beispiel #6
0
        private EventBlock CreateEventTextBlocks(EventModel eventModel)
        {
            var eventBlock = new EventBlock();
            var repoId     = eventModel.Repo != null ? new RepositoryIdentifier(eventModel.Repo.Name) : new RepositoryIdentifier();
            var username   = eventModel.Actor != null ? eventModel.Actor.Login : null;

            // Insert the actor
            eventBlock.Header.Add(new AnchorBlock(username, () => GoToUser(username)));

            var commitCommentEvent = eventModel.PayloadObject as EventModel.CommitCommentEvent;

            if (commitCommentEvent != null)
            {
                var node = commitCommentEvent.Comment.CommitId.Substring(0, commitCommentEvent.Comment.CommitId.Length > 6 ? 6 : commitCommentEvent.Comment.CommitId.Length);
                eventBlock.Tapped = () => GoToChangeset(repoId, commitCommentEvent.Comment.CommitId);
                eventBlock.Header.Add(new TextBlock(" commented on commit "));
                eventBlock.Header.Add(new AnchorBlock(node, eventBlock.Tapped));

                if (ReportRepository)
                {
                    eventBlock.Header.Add(new TextBlock(" in "));
                    eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                }

                eventBlock.Body.Add(new TextBlock(commitCommentEvent.Comment.Body));
                return(eventBlock);
            }

            var createEvent = eventModel.PayloadObject as EventModel.CreateEvent;

            if (createEvent != null)
            {
                if (createEvent.RefType.Equals("repository"))
                {
                    if (ReportRepository)
                    {
                        eventBlock.Tapped = () => GoToRepositoryCommand.Execute(eventModel.Repo);
                        eventBlock.Header.Add(new TextBlock(" created repository "));
                        eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                    }
                    else
                    {
                        eventBlock.Header.Add(new TextBlock(" created this repository"));
                    }
                }
                else if (createEvent.RefType.Equals("branch"))
                {
                    eventBlock.Tapped = () => GoToBranches(repoId);
                    eventBlock.Header.Add(new TextBlock(" created branch "));
                    eventBlock.Header.Add(new AnchorBlock(createEvent.Ref, eventBlock.Tapped));

                    if (ReportRepository)
                    {
                        eventBlock.Header.Add(new TextBlock(" in "));
                        eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                    }
                }
                else if (createEvent.RefType.Equals("tag"))
                {
                    eventBlock.Tapped = () => GoToTags(eventModel.Repo);
                    eventBlock.Header.Add(new TextBlock(" created tag "));
                    eventBlock.Header.Add(new AnchorBlock(createEvent.Ref, eventBlock.Tapped));

                    if (ReportRepository)
                    {
                        eventBlock.Header.Add(new TextBlock(" in "));
                        eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                    }
                }
            }


            var deleteEvent = eventModel.PayloadObject as EventModel.DeleteEvent;

            if (deleteEvent != null)
            {
                if (deleteEvent.RefType.Equals("branch"))
                {
                    eventBlock.Tapped = () => GoToBranches(repoId);
                    eventBlock.Header.Add(new TextBlock(" deleted branch "));
                }
                else if (deleteEvent.RefType.Equals("tag"))
                {
                    eventBlock.Tapped = () => GoToTags(eventModel.Repo);
                    eventBlock.Header.Add(new TextBlock(" deleted tag "));
                }
                else
                {
                    return(null);
                }

                eventBlock.Header.Add(new AnchorBlock(deleteEvent.Ref, eventBlock.Tapped));
                if (!ReportRepository)
                {
                    return(eventBlock);
                }
                eventBlock.Header.Add(new TextBlock(" in "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                return(eventBlock);
            }


            if (eventModel.PayloadObject is EventModel.DownloadEvent)
            {
                // Don't show the download event for now...
                return(null);
            }


            var followEvent = eventModel.PayloadObject as EventModel.FollowEvent;

            if (followEvent != null)
            {
                eventBlock.Tapped = () => GoToUser(followEvent.Target.Login);
                eventBlock.Header.Add(new TextBlock(" started following "));
                eventBlock.Header.Add(new AnchorBlock(followEvent.Target.Login, eventBlock.Tapped));
                return(eventBlock);
            }

            /*
             * FORK EVENT
             */
            else if (eventModel.PayloadObject is EventModel.ForkEvent)
            {
                var forkEvent  = (EventModel.ForkEvent)eventModel.PayloadObject;
                var forkedRepo = new EventModel.RepoModel {
                    Id = forkEvent.Forkee.Id, Name = forkEvent.Forkee.FullName, Url = forkEvent.Forkee.Url
                };
                eventBlock.Tapped = () => GoToRepositoryCommand.Execute(forkedRepo);
                eventBlock.Header.Add(new TextBlock(" forked "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                eventBlock.Header.Add(new TextBlock(" to "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(forkedRepo));
            }

            /*
             * FORK APPLY EVENT
             */
            else if (eventModel.PayloadObject is EventModel.ForkApplyEvent)
            {
                var forkEvent = (EventModel.ForkApplyEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToRepositoryCommand.Execute(eventModel.Repo);
                eventBlock.Header.Add(new TextBlock(" applied fork to "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                eventBlock.Header.Add(new TextBlock(" on branch "));
                eventBlock.Header.Add(new AnchorBlock(forkEvent.Head, () => GoToBranches(repoId)));
            }

            /*
             * GIST EVENT
             */
            else if (eventModel.PayloadObject is EventModel.GistEvent)
            {
                var gistEvent = (EventModel.GistEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToGistCommand.Execute(gistEvent);

                if (string.Equals(gistEvent.Action, "create", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" created Gist #"));
                }
                else if (string.Equals(gistEvent.Action, "update", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" updated Gist #"));
                }
                else if (string.Equals(gistEvent.Action, "fork", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" forked Gist #"));
                }

                eventBlock.Header.Add(new AnchorBlock(gistEvent.Gist.Id, eventBlock.Tapped));
                eventBlock.Body.Add(new TextBlock(gistEvent.Gist.Description.Replace('\n', ' ').Replace("\r", "").Trim()));
            }

            /*
             * GOLLUM EVENT (WIKI)
             */
            else if (eventModel.PayloadObject is EventModel.GollumEvent)
            {
                var gollumEvent = eventModel.PayloadObject as EventModel.GollumEvent;
                eventBlock.Header.Add(new TextBlock(" modified the wiki in "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));

                if (gollumEvent != null && gollumEvent.Pages != null)
                {
                    foreach (var page in gollumEvent.Pages)
                    {
                        var p = page;
                        eventBlock.Body.Add(new AnchorBlock(page.PageName, () => GoToUrlCommand.Execute(p.HtmlUrl)));
                        eventBlock.Body.Add(new TextBlock(" - " + page.Action + "\n"));
                    }

                    eventBlock.Multilined = true;
                }
            }

            /*
             * ISSUE COMMENT EVENT
             */
            else if (eventModel.PayloadObject is EventModel.IssueCommentEvent)
            {
                var commentEvent = (EventModel.IssueCommentEvent)eventModel.PayloadObject;

                if (commentEvent.Issue.PullRequest != null && !string.IsNullOrEmpty(commentEvent.Issue.PullRequest.HtmlUrl))
                {
                    eventBlock.Tapped = () => GoToPullRequest(repoId, commentEvent.Issue.Number);
                    eventBlock.Header.Add(new TextBlock(" commented on pull request "));
                }
                else
                {
                    eventBlock.Tapped = () => GoToIssue(repoId, commentEvent.Issue.Number);
                    eventBlock.Header.Add(new TextBlock(" commented on issue "));
                }

                eventBlock.Header.Add(new AnchorBlock("#" + commentEvent.Issue.Number, eventBlock.Tapped));
                eventBlock.Header.Add(new TextBlock(" in "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));

                eventBlock.Body.Add(new TextBlock(commentEvent.Comment.Body.Replace('\n', ' ').Replace("\r", "").Trim()));
            }

            /*
             * ISSUES EVENT
             */
            else if (eventModel.PayloadObject is EventModel.IssuesEvent)
            {
                var issueEvent = (EventModel.IssuesEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToIssue(repoId, issueEvent.Issue.Number);

                if (string.Equals(issueEvent.Action, "opened", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" opened issue "));
                }
                else if (string.Equals(issueEvent.Action, "closed", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" closed issue "));
                }
                else if (string.Equals(issueEvent.Action, "reopened", StringComparison.OrdinalIgnoreCase))
                {
                    eventBlock.Header.Add(new TextBlock(" reopened issue "));
                }

                eventBlock.Header.Add(new AnchorBlock("#" + issueEvent.Issue.Number, eventBlock.Tapped));
                eventBlock.Header.Add(new TextBlock(" in "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                eventBlock.Body.Add(new TextBlock(issueEvent.Issue.Title.Trim()));
            }

            /*
             * MEMBER EVENT
             */
            else if (eventModel.PayloadObject is EventModel.MemberEvent)
            {
                var memberEvent = (EventModel.MemberEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToRepositoryCommand.Execute(eventModel.Repo);

                if (memberEvent.Action.Equals("added"))
                {
                    eventBlock.Header.Add(new TextBlock(" added as a collaborator"));
                }
                else if (memberEvent.Action.Equals("removed"))
                {
                    eventBlock.Header.Add(new TextBlock(" removed as a collaborator"));
                }

                if (ReportRepository)
                {
                    eventBlock.Header.Add(new TextBlock(" to "));
                    eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                }
            }

            /*
             * PUBLIC EVENT
             */
            else if (eventModel.PayloadObject is EventModel.PublicEvent)
            {
                eventBlock.Tapped = () => GoToRepositoryCommand.Execute(eventModel.Repo);
                if (ReportRepository)
                {
                    eventBlock.Header.Add(new TextBlock(" has open sourced "));
                    eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                }
                else
                {
                    eventBlock.Header.Add(new TextBlock(" has been open sourced this repository!"));
                }
            }

            /*
             * PULL REQUEST EVENT
             */
            else if (eventModel.PayloadObject is EventModel.PullRequestEvent)
            {
                var pullEvent = (EventModel.PullRequestEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToPullRequest(repoId, pullEvent.Number);

                if (pullEvent.Action.Equals("closed"))
                {
                    eventBlock.Header.Add(new TextBlock(" closed pull request "));
                }
                else if (pullEvent.Action.Equals("opened"))
                {
                    eventBlock.Header.Add(new TextBlock(" opened pull request "));
                }
                else if (pullEvent.Action.Equals("synchronize"))
                {
                    eventBlock.Header.Add(new TextBlock(" synchronized pull request "));
                }
                else if (pullEvent.Action.Equals("reopened"))
                {
                    eventBlock.Header.Add(new TextBlock(" reopened pull request "));
                }

                eventBlock.Header.Add(new AnchorBlock("#" + pullEvent.PullRequest.Number, eventBlock.Tapped));
                eventBlock.Header.Add(new TextBlock(" in "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));

                eventBlock.Body.Add(new TextBlock(pullEvent.PullRequest.Title));
            }

            /*
             * PULL REQUEST REVIEW COMMENT EVENT
             */
            else if (eventModel.PayloadObject is EventModel.PullRequestReviewCommentEvent)
            {
                var commentEvent = (EventModel.PullRequestReviewCommentEvent)eventModel.PayloadObject;
                eventBlock.Tapped = () => GoToPullRequests(repoId);
                eventBlock.Header.Add(new TextBlock(" commented on pull request "));
                if (ReportRepository)
                {
                    eventBlock.Header.Add(new TextBlock(" in "));
                    eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                }

                eventBlock.Body.Add(new TextBlock(commentEvent.Comment.Body.Replace('\n', ' ').Replace("\r", "").Trim()));
            }

            /*
             * PUSH EVENT
             */
            else if (eventModel.PayloadObject is EventModel.PushEvent)
            {
                var pushEvent = (EventModel.PushEvent)eventModel.PayloadObject;

                string branchRef = null;
                if (!string.IsNullOrEmpty(pushEvent.Ref))
                {
                    var lastSlash = pushEvent.Ref.LastIndexOf("/", StringComparison.Ordinal) + 1;
                    branchRef = pushEvent.Ref.Substring(lastSlash);
                }

                if (eventModel.Repo != null)
                {
                    eventBlock.Tapped = () => GoToCommits(eventModel.Repo, pushEvent.Ref);
                }

                eventBlock.Header.Add(new TextBlock(" pushed to "));
                if (branchRef != null)
                {
                    eventBlock.Header.Add(new AnchorBlock(branchRef, () => GoToBranches(repoId)));
                }

                if (ReportRepository)
                {
                    eventBlock.Header.Add(new TextBlock(" at "));
                    eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                }

                if (pushEvent.Commits != null)
                {
                    foreach (var commit in pushEvent.Commits)
                    {
                        var desc         = (commit.Message ?? "");
                        var sha          = commit.Sha;
                        var firstNewLine = desc.IndexOf("\n");
                        if (firstNewLine <= 0)
                        {
                            firstNewLine = desc.Length;
                        }

                        desc = desc.Substring(0, firstNewLine);
                        var shortSha = commit.Sha;
                        if (shortSha.Length > 6)
                        {
                            shortSha = shortSha.Substring(0, 6);
                        }

                        eventBlock.Body.Add(new AnchorBlock(shortSha, () => GoToChangeset(repoId, sha)));
                        eventBlock.Body.Add(new TextBlock(" - " + desc + "\n"));
                        eventBlock.Multilined = true;
                    }
                }
            }


            var teamAddEvent = eventModel.PayloadObject as EventModel.TeamAddEvent;

            if (teamAddEvent != null)
            {
                eventBlock.Header.Add(new TextBlock(" added "));

                if (teamAddEvent.User != null)
                {
                    eventBlock.Header.Add(new AnchorBlock(teamAddEvent.User.Login, () => GoToUser(teamAddEvent.User.Login)));
                }
                else if (teamAddEvent.Repo != null)
                {
                    eventBlock.Header.Add(CreateRepositoryTextBlock(new EventModel.RepoModel {
                        Id = teamAddEvent.Repo.Id, Name = teamAddEvent.Repo.FullName, Url = teamAddEvent.Repo.Url
                    }));
                }
                else
                {
                    return(null);
                }

                if (teamAddEvent.Team == null)
                {
                    return(eventBlock);
                }
                eventBlock.Header.Add(new TextBlock(" to team "));
                eventBlock.Header.Add(new AnchorBlock(teamAddEvent.Team.Name, () => { }));
                return(eventBlock);
            }


            var watchEvent = eventModel.PayloadObject as EventModel.WatchEvent;

            if (watchEvent != null)
            {
                eventBlock.Tapped = () => GoToRepositoryCommand.Execute(eventModel.Repo);
                eventBlock.Header.Add(watchEvent.Action.Equals("started") ?
                                      new TextBlock(" starred ") : new TextBlock(" unstarred "));
                eventBlock.Header.Add(CreateRepositoryTextBlock(eventModel.Repo));
                return(eventBlock);
            }

            var releaseEvent = eventModel.PayloadObject as EventModel.ReleaseEvent;

            if (releaseEvent != null)
            {
                eventBlock.Tapped = () => GoToUrlCommand.Execute(releaseEvent.Release.HtmlUrl);
                eventBlock.Header.Add(new TextBlock(" " + releaseEvent.Action + " release " + releaseEvent.Release.Name));
                return(eventBlock);
            }

            return(eventBlock);
        }
Beispiel #7
0
        public GistViewModel(IApplicationService applicationService, IShareService shareService)
        {
            _applicationService = applicationService;
            Comments            = new ReactiveList <GistCommentModel>();

            ShareCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null));
            ShareCommand.Subscribe(_ => shareService.ShareUrl(Gist.HtmlUrl));

            ToggleStarCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue),
                async t =>
            {
                try
                {
                    if (!IsStarred.HasValue)
                    {
                        return;
                    }
                    var request = IsStarred.Value ? _applicationService.Client.Gists[Id].Unstar() : _applicationService.Client.Gists[Id].Star();
                    await _applicationService.Client.ExecuteAsync(request);
                    IsStarred = !IsStarred.Value;
                }
                catch (Exception e)
                {
                    throw new Exception("Unable to start gist. Please try again.", e);
                }
            });

            ForkCommand = ReactiveCommand.CreateAsyncTask(async t =>
            {
                var data       = await _applicationService.Client.ExecuteAsync(_applicationService.Client.Gists[Id].ForkGist());
                var forkedGist = data.Data;
                var vm         = CreateViewModel <GistViewModel>();
                vm.Id          = forkedGist.Id;
                vm.Gist        = forkedGist;
                ShowViewModel(vm);
            });

            GoToViewableFileCommand = ReactiveCommand.Create();
            GoToViewableFileCommand.OfType <GistFileModel>().Subscribe(x =>
            {
                var vm      = CreateViewModel <GistViewableFileViewModel>();
                vm.GistFile = x;
                ShowViewModel(vm);
            });

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null && !string.IsNullOrEmpty(x.HtmlUrl)));
            GoToHtmlUrlCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Gist.HtmlUrl));

            GoToFileSourceCommand = ReactiveCommand.Create();
            GoToFileSourceCommand.OfType <GistFileModel>().Subscribe(x =>
            {
                var vm      = CreateViewModel <GistFileViewModel>();
                vm.Id       = Id;
                vm.GistFile = x;
                vm.Filename = x.Filename;
                ShowViewModel(vm);
            });

            GoToUserCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Gist).Select(x => x != null));
            GoToUserCommand.Subscribe(x =>
            {
                var vm      = CreateViewModel <UserViewModel>();
                vm.Username = Gist.Owner.Login;
                ShowViewModel(vm);
            });

            GoToForksCommand = ReactiveCommand.Create();

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;
                var t1 = this.RequestModel(_applicationService.Client.Gists[Id].Get(), forceCacheInvalidation, response => Gist = response.Data);
                this.RequestModel(_applicationService.Client.Gists[Id].IsGistStarred(), forceCacheInvalidation, response => IsStarred = response.Data).FireAndForget();
                Comments.SimpleCollectionLoad(_applicationService.Client.Gists[Id].GetComments(), forceCacheInvalidation).FireAndForget();
                return(t1);
            });
        }
Beispiel #8
0
        protected BaseIssueViewModel(
            IApplicationService applicationService,
            IMarkdownService markdownService)
        {
            _applicationService = applicationService;

            var issuePresenceObservable = this.WhenAnyValue(x => x.Issue, x => x.CanModify)
                                          .Select(x => x.Item1 != null && x.Item2);

            Events = InternalEvents.CreateDerivedCollection(x => x);

            _participants = Events.Changed
                            .Select(_ => Events.Select(y => y.Actor).Distinct().Count())
                            .Select(x => x == 0 ? 1 : x)
                            .ToProperty(this, x => x.Participants);

            GoToAssigneesCommand = ReactiveCommand.Create(issuePresenceObservable)
                                   .WithSubscription(_ => Assignees.LoadCommand.ExecuteIfCan());

            GoToLabelsCommand = ReactiveCommand.Create(issuePresenceObservable)
                                .WithSubscription(_ => Labels.LoadCommand.ExecuteIfCan());

            GoToMilestonesCommand = ReactiveCommand.Create(issuePresenceObservable)
                                    .WithSubscription(_ => Milestones.LoadCommand.ExecuteIfCan());

            _assignedUser = this.WhenAnyValue(x => x.Issue.Assignee)
                            .ToProperty(this, x => x.AssignedUser);

            _assignedMilestone = this.WhenAnyValue(x => x.Issue.Milestone)
                                 .ToProperty(this, x => x.AssignedMilestone);

            _assignedLabels = this.WhenAnyValue(x => x.Issue.Labels)
                              .ToProperty(this, x => x.AssignedLabels);

            _isClosed = this.WhenAnyValue(x => x.Issue.State)
                        .Select(x => x == Octokit.ItemState.Closed)
                        .ToProperty(this, x => x.IsClosed);

            Assignees = new IssueAssigneeViewModel(
                () => applicationService.GitHubClient.Issue.Assignee.GetForRepository(RepositoryOwner, RepositoryName),
                () => Task.FromResult(Issue.Assignee),
                x => UpdateIssue(new Octokit.IssueUpdate
            {
                Assignee  = x.With(y => y.Login),
                Milestone = AssignedMilestone.With(y => (int?)y.Number)
            }));

            Milestones = new IssueMilestonesViewModel(
                () => applicationService.GitHubClient.Issue.Milestone.GetForRepository(RepositoryOwner, RepositoryName),
                () => Task.FromResult(Issue.Milestone),
                x => UpdateIssue(new Octokit.IssueUpdate
            {
                Assignee  = AssignedUser.With(y => y.Login),
                Milestone = x.With(y => (int?)y.Number)
            }));

            Labels = new IssueLabelsViewModel(
                () => applicationService.GitHubClient.Issue.Labels.GetForRepository(RepositoryOwner, RepositoryName),
                () => Task.FromResult((IReadOnlyList <Octokit.Label>) new ReadOnlyCollection <Octokit.Label>(Issue.Labels.ToList())),
                x =>
            {
                var update = new Octokit.IssueUpdate
                {
                    Assignee  = AssignedUser.With(y => y.Login),
                    Milestone = AssignedMilestone.With(y => (int?)y.Number),
                };

                foreach (var label in x.Select(y => y.Name))
                {
                    update.AddLabel(label);
                }
                return(UpdateIssue(update));
            });

            _markdownDescription = this.WhenAnyValue(x => x.Issue)
                                   .Select(x => ((x == null || string.IsNullOrEmpty(x.Body)) ? null : markdownService.Convert(x.Body)))
                                   .ToProperty(this, x => x.MarkdownDescription);

            LoadCommand = ReactiveCommand.CreateAsyncTask(t => Load(applicationService));

            GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null));
            GoToOwnerCommand.Select(_ => Issue.User).Subscribe(x =>
            {
                var vm      = this.CreateViewModel <UserViewModel>();
                vm.Username = x.Login;
                NavigateTo(vm);
            });

            ToggleStateCommand = ReactiveCommand.CreateAsyncTask(issuePresenceObservable, async t =>
            {
                try
                {
                    Issue = await applicationService.GitHubClient.Issue.Update(RepositoryOwner, RepositoryName, Id, new Octokit.IssueUpdate {
                        State = (Issue.State == Octokit.ItemState.Open) ? Octokit.ItemState.Closed : Octokit.ItemState.Open
                    });
                }
                catch (Exception e)
                {
                    var close = (Issue.State == Octokit.ItemState.Open) ? "close" : "open";
                    throw new Exception("Unable to " + close + " the item. " + e.Message, e);
                }
            });

            AddCommentCommand = ReactiveCommand.Create()
                                .WithSubscription(_ =>
            {
                var vm             = this.CreateViewModel <IssueCommentViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.Id = Id;
                vm.SaveCommand.Subscribe(x => InternalEvents.Add(new IssueCommentItemViewModel(x)));
                NavigateTo(vm);
            });


            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>().Subscribe(x =>
            {
                var vm = this.CreateViewModel <WebBrowserViewModel>();
                vm.Url = x;
                NavigateTo(vm);
            });
            GoToUrlCommand.OfType <Uri>().Subscribe(x =>
            {
                var vm = this.CreateViewModel <WebBrowserViewModel>();
                vm.Url = x.AbsoluteUri;
                NavigateTo(vm);
            });
        }
        protected BaseRepositoryViewModel(IApplicationService applicationService, INetworkActivityService networkActivity)
        {
            LikeCommand = ReactiveCommand.Create();
            LikeCommand.Subscribe(_ =>
            {
                if (StumbledRepository == null)
                {
                    var repo   = CreateStumbledRepository();
                    repo.Liked = true;
                    applicationService.Account.StumbledRepositories.Insert(repo);
                    StumbledRepository = repo;
                }
                else
                {
                    StumbledRepository.Liked       = true;
                    StumbledRepository.Description = Repository.Description;
                    StumbledRepository.Forks       = Repository.ForksCount;
                    StumbledRepository.Stars       = Repository.WatchersCount;
                    StumbledRepository.ImageUrl    = Repository.Owner.AvatarUrl;
                    applicationService.Account.StumbledRepositories.Update(StumbledRepository);
                }

                if (applicationService.Account.SyncWithGitHub)
                {
                    applicationService.Client.Activity.Starring.StarRepo(Repository.Owner.Login, Repository.Name);
                }

                Liked = true;
            });

            DislikeCommand = ReactiveCommand.Create();
            DislikeCommand.Subscribe(_ =>
            {
                if (StumbledRepository == null)
                {
                    var repo   = CreateStumbledRepository();
                    repo.Liked = false;
                    applicationService.Account.StumbledRepositories.Insert(repo);
                    StumbledRepository = repo;
                }
                else
                {
                    StumbledRepository.Liked       = false;
                    StumbledRepository.Description = Repository.Description;
                    StumbledRepository.Forks       = Repository.ForksCount;
                    StumbledRepository.Stars       = Repository.WatchersCount;
                    StumbledRepository.ImageUrl    = Repository.Owner.AvatarUrl;
                    applicationService.Account.StumbledRepositories.Update(StumbledRepository);
                }

                if (applicationService.Account.SyncWithGitHub)
                {
                    applicationService.Client.Activity.Starring.RemoveStarFromRepo(Repository.Owner.Login, Repository.Name);
                }

                Liked = false;
            });

            this.WhenAnyValue(x => x.RepositoryIdentifier)
            .Where(x => x != null)
            .Subscribe(x =>
            {
                StumbledRepository = applicationService.Account.StumbledRepositories.FindByFullname(x.Owner, x.Name);
            });

            this.WhenAnyValue(x => x.StumbledRepository)
            .Where(x => x != null)
            .Subscribe(x => Liked = x.Liked);

            GoToGitHubCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null));
            GoToGitHubCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Repository.HtmlUrl));

            LoadCommand = ReactiveCommand.CreateAsyncTask(this.WhenAnyValue(x => x.RepositoryIdentifier).Select(x => x != null), async t =>
            {
                Repository       = (await applicationService.Client.Repository.Get(RepositoryIdentifier.Owner, RepositoryIdentifier.Name));
                ContributorCount = (await applicationService.Client.Repository.GetAllContributors(RepositoryIdentifier.Owner, RepositoryIdentifier.Name)).Count;

                try
                {
                    Readme = await applicationService.Client.Repository.GetReadmeHtml(RepositoryIdentifier.Owner, RepositoryIdentifier.Name);
                }
                catch (Exception e)
                {
                    Readme = "<center>There is no readme for this repository :(</center>";
                    Debug.WriteLine(e.Message + " for " + RepositoryIdentifier.Owner + "/" + RepositoryIdentifier.Name);
                }
            });

            LoadCommand.TriggerNetworkActivity(networkActivity);
        }
Beispiel #10
0
        public RepositoryViewModel(IApplicationService applicationService, IAccountsService accountsService)
        {
            ApplicationService = applicationService;
            _accountsService   = accountsService;

            ToggleStarCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue), t => ToggleStar());

            ToggleWatchCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.IsWatched, x => x.HasValue), t => ToggleWatch());

            GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null));
            GoToOwnerCommand.Select(_ => Repository.Owner).Subscribe(x =>
            {
                if (string.Equals(x.Type, "organization", StringComparison.OrdinalIgnoreCase))
                {
                    var vm      = CreateViewModel <OrganizationViewModel>();
                    vm.Username = RepositoryOwner;
                    ShowViewModel(vm);
                }
                else
                {
                    var vm      = CreateViewModel <UserViewModel>();
                    vm.Username = RepositoryOwner;
                    ShowViewModel(vm);
                }
            });

            PinCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null));
            PinCommand.Subscribe(x => PinRepository());

            GoToForkParentCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && x.Fork && x.Parent != null));
            GoToForkParentCommand.Subscribe(x =>
            {
                var vm             = CreateViewModel <RepositoryViewModel>();
                vm.RepositoryOwner = Repository.Parent.Owner.Login;
                vm.RepositoryName  = Repository.Parent.Name;
                vm.Repository      = Repository.Parent;
                ShowViewModel(vm);
            });

            GoToStargazersCommand = ReactiveCommand.Create();
            GoToStargazersCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryStargazersViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToWatchersCommand = ReactiveCommand.Create();
            GoToWatchersCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryWatchersViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToEventsCommand = ReactiveCommand.Create();
            GoToEventsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryEventsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToIssuesCommand = ReactiveCommand.Create();
            GoToIssuesCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <IssuesViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToReadmeCommand = ReactiveCommand.Create();
            GoToReadmeCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <ReadmeViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToBranchesCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = CreateViewModel <CommitBranchesViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToCommitsCommand = ReactiveCommand.Create();
            GoToCommitsCommand.Subscribe(_ =>
            {
                if (Branches != null && Branches.Count == 1)
                {
                    var vm             = CreateViewModel <ChangesetsViewModel>();
                    vm.RepositoryOwner = RepositoryOwner;
                    vm.RepositoryName  = RepositoryName;
                    vm.Branch          = Repository == null ? null : Repository.DefaultBranch;
                    ShowViewModel(vm);
                }
                else
                {
                    GoToBranchesCommand.ExecuteIfCan();
                }
            });

            GoToPullRequestsCommand = ReactiveCommand.Create();
            GoToPullRequestsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <PullRequestsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToSourceCommand = ReactiveCommand.Create();
            GoToSourceCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <BranchesAndTagsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToContributors = ReactiveCommand.Create();
            GoToContributors.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryContributorsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToForksCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = CreateViewModel <RepositoryForksViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToReleasesCommand = ReactiveCommand.Create().WithSubscription(_ =>
            {
                var vm             = CreateViewModel <ReleasesViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl)));
            GoToHtmlUrlCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Repository.HtmlUrl));

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;

                var t1 = this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Get(),
                                           forceCacheInvalidation, response => Repository = response.Data);

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReadme(),
                                  forceCacheInvalidation, response => Readme = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetBranches(),
                                  forceCacheInvalidation, response => Branches = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsWatching(),
                                  forceCacheInvalidation, response => IsWatched = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsStarred(),
                                  forceCacheInvalidation, response => IsStarred = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetContributors(),
                                  forceCacheInvalidation, response => Contributors = response.Data.Count).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetLanguages(),
                                  forceCacheInvalidation, response => Languages = response.Data.Count).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReleases(),
                                  forceCacheInvalidation, response => Releases = response.Data.Count).FireAndForget();

                return(t1);
            });
        }
Beispiel #11
0
        public RepositoryViewModel(IApplicationService applicationService, IAccountsService accountsService)
        {
            ApplicationService = applicationService;
            _accountsService   = accountsService;

            ToggleStarCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.IsStarred).Select(x => x.HasValue), t => ToggleStar());

            ToggleWatchCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.IsWatched, x => x.HasValue), t => ToggleWatch());

            GoToOwnerCommand = ReactiveCommand.Create();
            GoToOwnerCommand.Subscribe(_ =>
            {
                var vm      = CreateViewModel <ProfileViewModel>();
                vm.Username = RepositoryOwner;
                ShowViewModel(vm);
            });

            PinCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository).Select(x => x != null));
            PinCommand.Subscribe(x => PinRepository());

            GoToForkParentCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && x.Fork && x.Parent != null));
            GoToForkParentCommand.Subscribe(x =>
            {
                var vm             = CreateViewModel <RepositoryViewModel>();
                vm.RepositoryOwner = Repository.Parent.Owner.Login;
                vm.RepositoryName  = Repository.Parent.Name;
                vm.Repository      = Repository.Parent;
                ShowViewModel(vm);
            });

            GoToStargazersCommand = ReactiveCommand.Create();
            GoToStargazersCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryStargazersViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToWatchersCommand = ReactiveCommand.Create();
            GoToWatchersCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryWatchersViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToEventsCommand = ReactiveCommand.Create();
            GoToEventsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryEventsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToIssuesCommand = ReactiveCommand.Create();
            GoToIssuesCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <IssuesViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToReadmeCommand = ReactiveCommand.Create();
            GoToReadmeCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <ReadmeViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToCommitsCommand = ReactiveCommand.Create();
            GoToCommitsCommand.Subscribe(_ =>
            {
                if (Branches != null && Branches.Count == 1)
                {
                    var vm             = CreateViewModel <ChangesetsViewModel>();
                    vm.RepositoryOwner = RepositoryOwner;
                    vm.RepositoryName  = RepositoryName;
                    ShowViewModel(vm);
                }
                else
                {
                    var vm             = CreateViewModel <ChangesetBranchesViewModel>();
                    vm.RepositoryOwner = RepositoryOwner;
                    vm.RepositoryName  = RepositoryName;
                    ShowViewModel(vm);
                }
            });

            GoToPullRequestsCommand = ReactiveCommand.Create();
            GoToPullRequestsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <PullRequestsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToSourceCommand = ReactiveCommand.Create();
            GoToSourceCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <BranchesAndTagsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            GoToCollaboratorsCommand = ReactiveCommand.Create();
            GoToCollaboratorsCommand.Subscribe(_ =>
            {
                var vm             = CreateViewModel <RepositoryCollaboratorsViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                ShowViewModel(vm);
            });

            this.WhenAnyValue(x => x.Repository).Subscribe(x =>
            {
                if (x == null)
                {
                    RepositorySize = null;
                }
                else
                {
                    if (x.Size / 1024f < 1)
                    {
                        RepositorySize = string.Format("{0:0.##}KB", x.Size);
                    }
                    else if ((x.Size / 1024f / 1024f) < 1)
                    {
                        RepositorySize = string.Format("{0:0.##}MB", x.Size / 1024f);
                    }
                    else
                    {
                        RepositorySize = string.Format("{0:0.##}GB", x.Size / 1024f / 1024f);
                    }
                }
            });

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Repository, x => x != null && !string.IsNullOrEmpty(x.HtmlUrl)));
            GoToHtmlUrlCommand.Subscribe(_ => GoToUrlCommand.ExecuteIfCan(Repository.HtmlUrl));

            LoadCommand = ReactiveCommand.CreateAsyncTask(t =>
            {
                var forceCacheInvalidation = t as bool?;

                var t1 = this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Get(),
                                           forceCacheInvalidation, response => Repository = response.Data);

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetReadme(),
                                  forceCacheInvalidation, response => Readme = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetBranches(),
                                  forceCacheInvalidation, response => Branches = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsWatching(),
                                  forceCacheInvalidation, response => IsWatched = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].IsStarred(),
                                  forceCacheInvalidation, response => IsStarred = response.Data).FireAndForget();

                this.RequestModel(ApplicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].GetCollaborators(),
                                  forceCacheInvalidation, response => Collaborators = response.Data.Count).FireAndForget();

                return(t1);
            });
        }
Beispiel #12
0
        protected BaseIssueViewModel(
            ISessionService applicationService,
            IMarkdownService markdownService,
            IActionMenuFactory actionMenuFactory,
            IAlertDialogFactory alertDialogFactory)
        {
            _applicationService = applicationService;
            _markdownService    = markdownService;
            _alertDialogFactory = alertDialogFactory;

            _assigneesCache = new Lazy <Task <IReadOnlyList <Octokit.User> > >(() =>
                                                                               _applicationService.GitHubClient.Issue.Assignee.GetAllForRepository(RepositoryOwner, RepositoryName));
            _milestonesCache = new Lazy <Task <IReadOnlyList <Octokit.Milestone> > >(() =>
                                                                                     _applicationService.GitHubClient.Issue.Milestone.GetAllForRepository(RepositoryOwner, RepositoryName));
            _labelsCache = new Lazy <Task <IReadOnlyList <Octokit.Label> > >(() =>
                                                                             _applicationService.GitHubClient.Issue.Labels.GetAllForRepository(RepositoryOwner, RepositoryName));

            IssueUpdated.Subscribe(x => Issue = x);

            _avatar = this.WhenAnyValue(x => x.Issue.User.AvatarUrl)
                      .Select(x => new GitHubAvatar(x))
                      .ToProperty(this, x => x.Avatar);

            var issuePresenceObservable = this.WhenAnyValue(x => x.Issue, x => x.CanModify)
                                          .Select(x => x.Item1 != null && x.Item2);

            Events = InternalEvents.CreateDerivedCollection(x => x);

            this.WhenAnyValue(x => x.Issue.Comments)
            .ToProperty(this, x => x.CommentCount, out _commentsCount);

            _participants = Events.Changed
                            .Select(_ => Events.Select(y => y.Actor).Distinct().Count())
                            .Select(x => x == 0 ? 1 : x)
                            .ToProperty(this, x => x.Participants);

            GoToAssigneesCommand  = ReactiveCommand.Create(issuePresenceObservable);
            GoToLabelsCommand     = ReactiveCommand.Create(issuePresenceObservable);
            GoToMilestonesCommand = ReactiveCommand.Create(issuePresenceObservable);

            _assignedUser = this.WhenAnyValue(x => x.Issue.Assignee)
                            .ToProperty(this, x => x.AssignedUser);

            _assignedMilestone = this.WhenAnyValue(x => x.Issue.Milestone)
                                 .ToProperty(this, x => x.AssignedMilestone);

            _assignedLabels = this.WhenAnyValue(x => x.Issue.Labels)
                              .ToProperty(this, x => x.AssignedLabels);

            _isClosed = this.WhenAnyValue(x => x.Issue.State)
                        .Select(x => x == Octokit.ItemState.Closed)
                        .ToProperty(this, x => x.IsClosed);

            _markdownDescription = this.WhenAnyValue(x => x.Issue)
                                   .Select(x => ((x == null || string.IsNullOrEmpty(x.Body)) ? null : x.Body))
                                   .Where(x => x != null)
                                   .Select(x => GetMarkdownDescription().ToObservable())
                                   .Switch()
                                   .ToProperty(this, x => x.MarkdownDescription, null, RxApp.MainThreadScheduler);

            LoadCommand = ReactiveCommand.CreateAsyncTask(t => Load(applicationService));

            GoToOwnerCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Issue).Select(x => x != null));
            GoToOwnerCommand
            .Select(_ => this.CreateViewModel <UserViewModel>())
            .Select(x => x.Init(Issue.User.Login))
            .Subscribe(NavigateTo);

            ToggleStateCommand = ReactiveCommand.CreateAsyncTask(issuePresenceObservable, async t => {
                try
                {
                    var updatedIssue = await applicationService.GitHubClient.Issue.Update(RepositoryOwner, RepositoryName, Id, new Octokit.IssueUpdate {
                        State = (Issue.State == Octokit.ItemState.Open) ? Octokit.ItemState.Closed : Octokit.ItemState.Open
                    });
                    _issueUpdatedObservable.OnNext(updatedIssue);
                }
                catch (Exception e)
                {
                    var close = (Issue.State == Octokit.ItemState.Open) ? "close" : "open";
                    throw new Exception("Unable to " + close + " the item. " + e.Message, e);
                }

                RetrieveEvents().ToBackground(x => InternalEvents.Reset(x));
            });

            AddCommentCommand = ReactiveCommand.Create().WithSubscription(_ => {
                var vm = new ComposerViewModel(async s => {
                    var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Issues[Id].CreateComment(s);
                    var comment = (await applicationService.Client.ExecuteAsync(request)).Data;
                    InternalEvents.Add(new IssueCommentItemViewModel(comment));
                    _commentAddedSubject.OnNext(comment);
                }, alertDialogFactory);
                NavigateTo(vm);
            });

            ShowMenuCommand = ReactiveCommand.CreateAsyncTask(
                this.WhenAnyValue(x => x.Issue).Select(x => x != null),
                sender => {
                var menu = actionMenuFactory.Create();
                menu.AddButton("Edit", GoToEditCommand);
                menu.AddButton(Issue.State == Octokit.ItemState.Closed ? "Open" : "Close", ToggleStateCommand);
                menu.AddButton("Comment", AddCommentCommand);
                menu.AddButton("Share", ShareCommand);
                menu.AddButton("Show in GitHub", GoToHtmlUrlCommand);
                return(menu.Show(sender));
            });

            GoToEditCommand = ReactiveCommand.Create().WithSubscription(_ => {
                var vm             = this.CreateViewModel <IssueEditViewModel>();
                vm.RepositoryOwner = RepositoryOwner;
                vm.RepositoryName  = RepositoryName;
                vm.Id    = Id;
                vm.Issue = Issue;
                vm.SaveCommand.Subscribe(_issueUpdatedObservable.OnNext);
                NavigateTo(vm);
            });

            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>().Subscribe(GoToUrl);
            GoToUrlCommand.OfType <Uri>().Subscribe(x => GoToUrl(x.AbsoluteUri));

            var hasHtmlObservable = this.WhenAnyValue(x => x.HtmlUrl).Select(x => x != null);

            ShareCommand = ReactiveCommand.Create(hasHtmlObservable);
            ShareCommand.Subscribe(sender => actionMenuFactory.ShareUrl(sender, HtmlUrl));

            GoToHtmlUrlCommand = ReactiveCommand.Create(hasHtmlObservable);
            GoToHtmlUrlCommand.Subscribe(_ => GoToUrl(HtmlUrl.AbsoluteUri));
        }
Beispiel #13
0
        public CommitViewModel(ISessionService applicationService, IActionMenuFactory actionMenuService, IAlertDialogFactory alertDialogFactory)
        {
            Title = "Commit";

            var comments = new ReactiveList <CommentModel>();

            Comments = comments.CreateDerivedCollection(x => new CommitCommentItemViewModel(x));

            this.WhenAnyValue(x => x.Commit)
            .Select(x => new GitHubAvatar(x.GenerateGravatarUrl()))
            .ToProperty(this, x => x.Avatar, out _avatar);

            var files = this.WhenAnyValue(x => x.Commit.Files).IsNotNull();

            files.Select(x => x.Count(y => string.Equals(y.Status, "added")))
            .ToProperty(this, x => x.DiffAdditions, out _diffAdditions);

            files.Select(x => x.Count(y => string.Equals(y.Status, "removed")))
            .ToProperty(this, x => x.DiffDeletions, out _diffDeletions);

            files.Select(x => x.Count(y => string.Equals(y.Status, "modified")))
            .ToProperty(this, x => x.DiffModifications, out _diffModifications);

            GoToAddedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffAdditions).Select(x => x > 0));
            GoToAddedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Added", Commit.Files.Where(x => string.Equals(x.Status, "added"))))
            .Subscribe(NavigateTo);

            GoToRemovedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffDeletions).Select(x => x > 0));
            GoToRemovedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Removed", Commit.Files.Where(x => string.Equals(x.Status, "removed"))))
            .Subscribe(NavigateTo);

            GoToModifiedFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.DiffModifications).Select(x => x > 0));
            GoToModifiedFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "Modified", Commit.Files.Where(x => string.Equals(x.Status, "modified"))))
            .Subscribe(NavigateTo);

            GoToAllFiles = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit.Files).Select(x => x != null));
            GoToAllFiles
            .Select(_ => new CommitFilesViewModel())
            .Select(y => y.Init(RepositoryOwner, RepositoryName, Node, "All Changes", Commit.Files))
            .Subscribe(NavigateTo);

            this.WhenAnyValue(x => x.Commit)
            .IsNotNull()
            .Select(x => x.GenerateCommiterName())
            .ToProperty(this, x => x.CommiterName, out _commiterName);

            this.WhenAnyValue(x => x.Commit)
            .IsNotNull()
            .Select(x => x.Commit.Message ?? string.Empty)
            .Select(x => Emojis.FindAndReplace(x))
            .ToProperty(this, x => x.CommitMessage, out _commitMessage);

            this.WhenAnyValue(x => x.CommitMessage)
            .IsNotNull()
            .Select(x => {
                var firstNewLine = x.IndexOf("\n", StringComparison.Ordinal);
                return(firstNewLine > 0 ? x.Substring(0, firstNewLine) : x);
            })
            .ToProperty(this, x => x.CommitMessageSummary, out _commitMessageSummary);

            GoToHtmlUrlCommand = ReactiveCommand.Create(this.WhenAnyValue(x => x.Commit).Select(x => x != null));
            GoToHtmlUrlCommand
            .Select(_ => this.CreateViewModel <WebBrowserViewModel>())
            .Select(x => x.Init(Commit.HtmlUrl))
            .Subscribe(NavigateTo);

            GoToRepositoryCommand = ReactiveCommand.Create();
            GoToRepositoryCommand.Subscribe(_ => {
                var vm = this.CreateViewModel <RepositoryViewModel>();
                vm.Init(RepositoryOwner, RepositoryName);
                NavigateTo(vm);
            });

            AddCommentCommand = ReactiveCommand.Create().WithSubscription(_ => {
                var vm = new ComposerViewModel(async s => {
                    var request = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.Create(s);
                    comments.Add((await applicationService.Client.ExecuteAsync(request)).Data);
                }, alertDialogFactory);
                NavigateTo(vm);
            });

            GoToUrlCommand = ReactiveCommand.Create();
            GoToUrlCommand.OfType <string>()
            .Select(x => this.CreateViewModel <WebBrowserViewModel>().Init(x))
            .Subscribe(NavigateTo);

            var validCommitObservable = this.WhenAnyValue(x => x.Commit).Select(x => x != null);

            var copyShaCommand = ReactiveCommand.Create(validCommitObservable)
                                 .WithSubscription(x => actionMenuService.SendToPasteBoard(this.Commit.Sha));

            var shareCommand = ReactiveCommand.Create(validCommitObservable)
                               .WithSubscription(sender => actionMenuService.ShareUrl(sender, this.Commit.HtmlUrl));

            var browseCodeCommand = ReactiveCommand.Create(validCommitObservable)
                                    .WithSubscription(x => {
                var vm = this.CreateViewModel <SourceTreeViewModel>();
                vm.Init(RepositoryOwner, RepositoryName, Commit.Sha, trueBranch: false);
                NavigateTo(vm);
            });

            ShowMenuCommand = ReactiveCommand.CreateAsyncTask(sender => {
                var menu = actionMenuService.Create();
                menu.AddButton("Add Comment", AddCommentCommand);
                menu.AddButton("Copy SHA", copyShaCommand);
                menu.AddButton("Browse Code", browseCodeCommand);
                menu.AddButton("Goto Repository", GoToRepositoryCommand);
                menu.AddButton("Share", shareCommand);
                menu.AddButton("Show in GitHub", GoToHtmlUrlCommand);
                return(menu.Show(sender));
            });

            LoadCommand = ReactiveCommand.CreateAsyncTask(async t => {
                var commentRequest = applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.GetAll();
                applicationService.Client.ExecuteAsync(commentRequest).ToBackground(x => comments.Reset(x.Data.Where(y => y.Position.HasValue)));
                Commit = await applicationService.GitHubClient.Repository.Commits.Get(RepositoryOwner, RepositoryName, Node);
            });
        }
Beispiel #14
0
        protected async Task Startup()
        {
            if (!_applicationService.Accounts.Any())
            {
                GoToNewAccount.Execute(null);
                return;
            }

            var accounts = GetService <IAccountsService>();
            var account  = accounts.GetDefault();

            if (account == null)
            {
                GoToAccounts.Execute(null);
                return;
            }

            var isEnterprise = account.IsEnterprise || !string.IsNullOrEmpty(account.Password);

            if (account.DontRemember)
            {
                GoToAccounts.Execute(null);
                return;
            }

            //Lets login!
            try
            {
                ImageUrl    = null;
                Status      = null;
                IsLoggingIn = true;

                Uri accountAvatarUri = null;
                Uri.TryCreate(account.AvatarUrl, UriKind.Absolute, out accountAvatarUri);
                ImageUrl = accountAvatarUri;
                Status   = "Logging in as " + account.Username;

                var client = await _loginFactory.LoginAccount(account);

                _applicationService.ActivateUser(account, client);

                if (!isEnterprise)
                {
                    StarOrWatch();
                }

                GoToMenu.Execute(typeof(MenuViewModel));
            }
            catch (GitHubSharp.UnauthorizedException e)
            {
                DisplayAlert("The credentials for the selected account are incorrect. " + e.Message);

                if (isEnterprise)
                {
                    GoToUrlCommand.Execute(new AddAccountViewModel.NavObject {
                        AttemptedAccountId = account.Id
                    });
                }
                else
                {
                    GoToUrlCommand.Execute(LoginViewModel.NavObject.CreateDontRemember(account));
                }

                StarOrWatch();
            }
            catch (Exception e)
            {
                DisplayAlert(e.Message);
                GoToAccounts.Execute(null);
            }
            finally
            {
                IsLoggingIn = false;
            }
        }