Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refresh button when branch changes #20511

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions options/locale/locale_en-US.ini
Original file line number Diff line number Diff line change
Expand Up @@ -1615,6 +1615,8 @@ pulls.auto_merge_canceled_schedule_comment = `canceled auto merging this pull re
pulls.delete.title = Delete this pull request?
pulls.delete.text = Do you really want to delete this pull request? (This will permanently remove all content. Consider closing it instead, if you intend to keep it archived)

pulls.refresh = Refresh

milestones.new = New Milestone
milestones.closed = Closed %s
milestones.update_ago = Updated %s ago
Expand Down
67 changes: 67 additions & 0 deletions routers/private/event.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

// Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead.
package private

import (
access_model "code.gitea.io/gitea/models/perm/access"
user_model "code.gitea.io/gitea/models/user"
gitea_context "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/eventsource"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/private"
"code.gitea.io/gitea/modules/web"
)

type BranchUpdateEvent struct {
CommitID string
Branch string
BranchDeleted bool
Owner string
RefFullName string
Repository string
}

func SendBranchUpdateEvent(readers []*user_model.User, commitID, branchName, repoName, refFullName, ownerName string) {
manager := eventsource.GetManager()

for _, reader := range readers {
manager.SendMessage(reader.ID, &eventsource.Event{
Name: "branch-update",
Data: BranchUpdateEvent{
CommitID: commitID,
Branch: branchName,
BranchDeleted: commitID == git.EmptySHA,
Repository: repoName,
RefFullName: refFullName,
Owner: ownerName,
},
})
}
}

func SendContextBranchUpdateEvents(ctx *gitea_context.PrivateContext) error {
opts := web.GetForm(ctx).(*private.HookOptions)

ownerName := ctx.Params(":owner")
repoName := ctx.Params(":repo")

repo := loadRepository(ctx, ownerName, repoName)

readers, err := access_model.GetRepoReaders(repo)
if err != nil {
return err
}

for i := range opts.OldCommitIDs {
branch := git.RefEndName(opts.RefFullNames[i])
commitID := opts.NewCommitIDs[i]
refFullName := opts.RefFullNames[i]

SendBranchUpdateEvent(readers, commitID, branch, repoName, refFullName, ownerName)
}

return nil
}
13 changes: 13 additions & 0 deletions routers/private/hook_post_receive.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,19 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) {
}
}
}

// Notify users with read access via eventsource that a change
// has been made
if err := SendContextBranchUpdateEvents(ctx); err != nil {
log.Error("Failed to Send Branch Update Events: %s/%s Error: %v", ownerName, repoName, err)

ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
Err: fmt.Sprintf("Failed to Send Branch Update Events: %s/%s Error: %v", ownerName, repoName, err),
})

return
}

ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
Results: results,
RepoWasEmpty: wasEmpty,
Expand Down
1 change: 1 addition & 0 deletions routers/web/repo/issue.go
Original file line number Diff line number Diff line change
Expand Up @@ -1171,6 +1171,7 @@ func ViewIssue(ctx *context.Context) {
}
ctx.Data["PageIsPullList"] = true
ctx.Data["PageIsPullConversation"] = true
ctx.Data["Reponame"] = ctx.Repo.Repository.Name
} else {
MustEnableIssues(ctx)
if ctx.Written() {
Expand Down
3 changes: 3 additions & 0 deletions templates/repo/issue/view_title.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
<div id="edit-title" class="ui basic secondary not-in-edit button">{{.locale.Tr "repo.issues.edit"}}</div>
</div>
{{end}}
<div class="edit-button not-in-edit refresh-pull-request" data-base-target="{{$.BaseTarget}}" data-head-target="{{$.HeadTarget}}" data-owner-name="{{$.Username}}" data-repository-name="{{$.Reponame}}">
<button class="ui inverted orange button">{{.locale.Tr "repo.pulls.refresh"}}</button>
</div>
<h1>
<span id="issue-title">{{RenderIssueTitle $.Context .Issue.Title $.RepoLink $.Repository.ComposeMetas}}</span>
<span class="index">#{{.Issue.Index}}</span>
Expand Down
1 change: 1 addition & 0 deletions web_src/js/features/eventsource.sharedworker.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class Source {
this.listen('notification-count');
this.listen('stopwatches');
this.listen('error');
this.listen('branch-update');
}

register(port) {
Expand Down
42 changes: 4 additions & 38 deletions web_src/js/features/notification.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import $ from 'jquery';
import getMemoizedSharedWorker from './shared-worker.js';

const {appSubUrl, csrfToken, notificationSettings} = window.config;
let notificationSequenceNumber = 0;
Expand Down Expand Up @@ -49,54 +50,19 @@ export function initNotificationCount() {
return;
}

if (notificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) {
let worker;

if (notificationSettings.EventSourceUpdateTime > 0 && (worker = getMemoizedSharedWorker())) {
// Try to connect to the event source via the shared worker first
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker');
worker.addEventListener('error', (event) => {
console.error(event);
});
worker.port.addEventListener('messageerror', () => {
console.error('Unable to deserialize message');
});
worker.port.postMessage({
type: 'start',
url: `${window.location.origin}${appSubUrl}/user/events`,
});
worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) {
console.error(event);
return;
}
if (event.data.type === 'notification-count') {
const _promise = receiveUpdateCount(event.data);
} else if (event.data.type === 'error') {
console.error(event.data);
} else if (event.data.type === 'logout') {
if (event.data.data !== 'here') {
return;
}
worker.port.postMessage({
type: 'close',
});
worker.port.close();
window.location.href = appSubUrl;
} else if (event.data.type === 'close') {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
}
});
worker.port.addEventListener('error', (e) => {
console.error(e);
});
worker.port.start();
window.addEventListener('beforeunload', () => {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
});

return;
}
Expand Down
56 changes: 56 additions & 0 deletions web_src/js/features/repo-refresh-pr.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import $ from 'jquery';
import getMemoizedSharedWorker from './shared-worker.js';

async function receiveBranchUpdated(event) {
try {
const data = JSON.parse(event.data);

const refreshPullRequest = document.querySelector('.refresh-pull-request');

if (!refreshPullRequest) {
return;
}

const baseTarget = $(refreshPullRequest).data('baseTarget');
const headTarget = $(refreshPullRequest).data('headTarget');
const ownerName = $(refreshPullRequest).data('ownerName');
const repositoryName = $(refreshPullRequest).data('repositoryName');

if (
[baseTarget, headTarget].includes(data.Branch) &&
data.Owner === ownerName &&
data.Repository === repositoryName
) {
refreshPullRequest.classList.add('active');
}
} catch (error) {
console.error(error, event);
}
}

export function initRepoRefreshPullRequest() {
const staleBranchAlert = $('.refresh-pull-request');

if (!staleBranchAlert.length) {
return;
}

$(staleBranchAlert).on('click', () => {
window.location.reload();
});

const worker = getMemoizedSharedWorker();

if (worker) {
worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) {
return;
}
if (event.data.type === 'branch-update') {
receiveBranchUpdated(event.data);
}
});
} else {
console.error('Service workers not available');
}
}
70 changes: 70 additions & 0 deletions web_src/js/features/shared-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
const {appSubUrl} = window.config;

let worker;

function getMemoizedSharedWorker() {
if (!window.EventSource || !window.SharedWorker) {
return null;
}

if (!worker) {
worker = new SharedWorker(
`${__webpack_public_path__}js/eventsource.sharedworker.js`,
'notification-worker'
);

worker.addEventListener('error', (event) => {
console.error(event);
});

worker.port.addEventListener('messageerror', () => {
console.error('Unable to deserialize message');
});

worker.port.postMessage({
type: 'start',
url: `${window.location.origin}${appSubUrl}/user/events`,
});

worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) {
console.error(event);
return;
}
if (event.data.type === 'error') {
console.error(event.data);
} else if (event.data.type === 'logout') {
if (event.data.data !== 'here') {
return;
}
worker.port.postMessage({
type: 'close',
});
worker.port.close();
window.location.href = appSubUrl;
} else if (event.data.type === 'close') {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
}
});

worker.port.addEventListener('error', (e) => {
console.error(e);
});

worker.port.start();

window.addEventListener('beforeunload', () => {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
});
}

return worker;
}

export default getMemoizedSharedWorker;
43 changes: 4 additions & 39 deletions web_src/js/features/stopwatch.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import $ from 'jquery';
import prettyMilliseconds from 'pretty-ms';
import getMemoizedSharedWorker from './shared-worker.js';

const {appSubUrl, csrfToken, notificationSettings, enableTimeTracking} = window.config;
let updateTimeInterval = null; // holds setInterval id when active
Expand All @@ -26,54 +27,18 @@ export function initStopwatch() {
$(this).parent().trigger('submit');
});

if (notificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) {
let worker;

if (notificationSettings.EventSourceUpdateTime > 0 && (worker = getMemoizedSharedWorker())) {
// Try to connect to the event source via the shared worker first
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker');
worker.addEventListener('error', (event) => {
console.error(event);
});
worker.port.addEventListener('messageerror', () => {
console.error('Unable to deserialize message');
});
worker.port.postMessage({
type: 'start',
url: `${window.location.origin}${appSubUrl}/user/events`,
});
worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) {
console.error(event);
return;
}
if (event.data.type === 'stopwatches') {
updateStopwatchData(JSON.parse(event.data.data));
} else if (event.data.type === 'error') {
console.error(event.data);
} else if (event.data.type === 'logout') {
if (event.data.data !== 'here') {
return;
}
worker.port.postMessage({
type: 'close',
});
worker.port.close();
window.location.href = appSubUrl;
} else if (event.data.type === 'close') {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
}
});
worker.port.addEventListener('error', (e) => {
console.error(e);
});
worker.port.start();
window.addEventListener('beforeunload', () => {
worker.port.postMessage({
type: 'close',
});
worker.port.close();
});

return;
}
Expand Down
2 changes: 2 additions & 0 deletions web_src/js/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ import {initInstall} from './features/install.js';
import {initCompWebHookEditor} from './features/comp/WebHookEditor.js';
import {initCommonIssue} from './features/common-issue.js';
import {initRepoBranchButton} from './features/repo-branch.js';
import {initRepoRefreshPullRequest} from './features/repo-refresh-pr.js';
import {initCommonOrganization} from './features/common-organization.js';
import {initRepoWikiForm} from './features/repo-wiki.js';
import {initRepoCommentForm, initRepository} from './features/repo-legacy.js';
Expand Down Expand Up @@ -176,6 +177,7 @@ $(document).ready(() => {
initRepoSettingGitHook();
initRepoSettingSearchTeamBox();
initRepoSettingsCollaboration();
initRepoRefreshPullRequest();
initRepoTemplateSearch();
initRepoTopicBar();
initRepoWikiForm();
Expand Down
Loading