mirror of
https://github.com/go-gitea/gitea
synced 2025-01-09 09:24:25 +00:00
Merge branch 'main' into lunny/issue_dev
This commit is contained in:
commit
f77d7e71e6
@ -784,6 +784,10 @@ LEVEL = Info
|
|||||||
;; Please note that setting this to false will not disable OAuth Basic or Basic authentication using a token
|
;; Please note that setting this to false will not disable OAuth Basic or Basic authentication using a token
|
||||||
;ENABLE_BASIC_AUTHENTICATION = true
|
;ENABLE_BASIC_AUTHENTICATION = true
|
||||||
;;
|
;;
|
||||||
|
;; Show the password sign-in form (for password-based login), otherwise, only show OAuth2 login methods.
|
||||||
|
;; If you set it to false, maybe it also needs to set ENABLE_BASIC_AUTHENTICATION to false to completely disable password-based authentication.
|
||||||
|
;ENABLE_PASSWORD_SIGNIN_FORM = true
|
||||||
|
;;
|
||||||
;; More detail: https://github.com/gogits/gogs/issues/165
|
;; More detail: https://github.com/gogits/gogs/issues/165
|
||||||
;ENABLE_REVERSE_PROXY_AUTHENTICATION = false
|
;ENABLE_REVERSE_PROXY_AUTHENTICATION = false
|
||||||
; Enable this to allow reverse proxy authentication for API requests, the reverse proxy is responsible for ensuring that no CSRF is possible.
|
; Enable this to allow reverse proxy authentication for API requests, the reverse proxy is responsible for ensuring that no CSRF is possible.
|
||||||
|
@ -448,65 +448,13 @@ type GetFeedsOptions struct {
|
|||||||
Date string // the day we want activity for: YYYY-MM-DD
|
Date string // the day we want activity for: YYYY-MM-DD
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetFeeds returns actions according to the provided options
|
|
||||||
func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, int64, error) {
|
|
||||||
if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
|
|
||||||
return nil, 0, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
|
|
||||||
}
|
|
||||||
|
|
||||||
cond, err := activityQueryCondition(ctx, opts)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
actions := make([]*Action, 0, opts.PageSize)
|
|
||||||
var count int64
|
|
||||||
opts.SetDefaultValues()
|
|
||||||
|
|
||||||
if opts.Page < 10 { // TODO: why it's 10 but other values? It's an experience value.
|
|
||||||
sess := db.GetEngine(ctx).Where(cond)
|
|
||||||
sess = db.SetSessionPagination(sess, &opts)
|
|
||||||
|
|
||||||
count, err = sess.Desc("`action`.created_unix").FindAndCount(&actions)
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("FindAndCount: %w", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// First, only query which IDs are necessary, and only then query all actions to speed up the overall query
|
|
||||||
sess := db.GetEngine(ctx).Where(cond).Select("`action`.id")
|
|
||||||
sess = db.SetSessionPagination(sess, &opts)
|
|
||||||
|
|
||||||
actionIDs := make([]int64, 0, opts.PageSize)
|
|
||||||
if err := sess.Table("action").Desc("`action`.created_unix").Find(&actionIDs); err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("Find(actionsIDs): %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
count, err = db.GetEngine(ctx).Where(cond).
|
|
||||||
Table("action").
|
|
||||||
Cols("`action`.id").Count()
|
|
||||||
if err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("Count: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := db.GetEngine(ctx).In("`action`.id", actionIDs).Desc("`action`.created_unix").Find(&actions); err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("Find: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := ActionList(actions).LoadAttributes(ctx); err != nil {
|
|
||||||
return nil, 0, fmt.Errorf("LoadAttributes: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return actions, count, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ActivityReadable return whether doer can read activities of user
|
// ActivityReadable return whether doer can read activities of user
|
||||||
func ActivityReadable(user, doer *user_model.User) bool {
|
func ActivityReadable(user, doer *user_model.User) bool {
|
||||||
return !user.KeepActivityPrivate ||
|
return !user.KeepActivityPrivate ||
|
||||||
doer != nil && (doer.IsAdmin || user.ID == doer.ID)
|
doer != nil && (doer.IsAdmin || user.ID == doer.ID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func activityQueryCondition(ctx context.Context, opts GetFeedsOptions) (builder.Cond, error) {
|
func ActivityQueryCondition(ctx context.Context, opts GetFeedsOptions) (builder.Cond, error) {
|
||||||
cond := builder.NewCond()
|
cond := builder.NewCond()
|
||||||
|
|
||||||
if opts.RequestedTeam != nil && opts.RequestedUser == nil {
|
if opts.RequestedTeam != nil && opts.RequestedUser == nil {
|
||||||
|
@ -201,3 +201,55 @@ func (actions ActionList) LoadIssues(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetFeeds returns actions according to the provided options
|
||||||
|
func GetFeeds(ctx context.Context, opts GetFeedsOptions) (ActionList, int64, error) {
|
||||||
|
if opts.RequestedUser == nil && opts.RequestedTeam == nil && opts.RequestedRepo == nil {
|
||||||
|
return nil, 0, fmt.Errorf("need at least one of these filters: RequestedUser, RequestedTeam, RequestedRepo")
|
||||||
|
}
|
||||||
|
|
||||||
|
cond, err := ActivityQueryCondition(ctx, opts)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
actions := make([]*Action, 0, opts.PageSize)
|
||||||
|
var count int64
|
||||||
|
opts.SetDefaultValues()
|
||||||
|
|
||||||
|
if opts.Page < 10 { // TODO: why it's 10 but other values? It's an experience value.
|
||||||
|
sess := db.GetEngine(ctx).Where(cond)
|
||||||
|
sess = db.SetSessionPagination(sess, &opts)
|
||||||
|
|
||||||
|
count, err = sess.Desc("`action`.created_unix").FindAndCount(&actions)
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("FindAndCount: %w", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// First, only query which IDs are necessary, and only then query all actions to speed up the overall query
|
||||||
|
sess := db.GetEngine(ctx).Where(cond).Select("`action`.id")
|
||||||
|
sess = db.SetSessionPagination(sess, &opts)
|
||||||
|
|
||||||
|
actionIDs := make([]int64, 0, opts.PageSize)
|
||||||
|
if err := sess.Table("action").Desc("`action`.created_unix").Find(&actionIDs); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("Find(actionsIDs): %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
count, err = db.GetEngine(ctx).Where(cond).
|
||||||
|
Table("action").
|
||||||
|
Cols("`action`.id").Count()
|
||||||
|
if err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("Count: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.GetEngine(ctx).In("`action`.id", actionIDs).Desc("`action`.created_unix").Find(&actions); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("Find: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := ActionList(actions).LoadAttributes(ctx); err != nil {
|
||||||
|
return nil, 0, fmt.Errorf("LoadAttributes: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return actions, count, nil
|
||||||
|
}
|
||||||
|
@ -42,114 +42,6 @@ func TestAction_GetRepoLink(t *testing.T) {
|
|||||||
assert.Equal(t, comment.HTMLURL(db.DefaultContext), action.GetCommentHTMLURL(db.DefaultContext))
|
assert.Equal(t, comment.HTMLURL(db.DefaultContext), action.GetCommentHTMLURL(db.DefaultContext))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetFeeds(t *testing.T) {
|
|
||||||
// test with an individual user
|
|
||||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
||||||
|
|
||||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedUser: user,
|
|
||||||
Actor: user,
|
|
||||||
IncludePrivate: true,
|
|
||||||
OnlyPerformedBy: false,
|
|
||||||
IncludeDeleted: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
if assert.Len(t, actions, 1) {
|
|
||||||
assert.EqualValues(t, 1, actions[0].ID)
|
|
||||||
assert.EqualValues(t, user.ID, actions[0].UserID)
|
|
||||||
}
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
|
|
||||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedUser: user,
|
|
||||||
Actor: user,
|
|
||||||
IncludePrivate: false,
|
|
||||||
OnlyPerformedBy: false,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 0)
|
|
||||||
assert.Equal(t, int64(0), count)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetFeedsForRepos(t *testing.T) {
|
|
||||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
||||||
privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
|
||||||
pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8})
|
|
||||||
|
|
||||||
// private repo & no login
|
|
||||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedRepo: privRepo,
|
|
||||||
IncludePrivate: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 0)
|
|
||||||
assert.Equal(t, int64(0), count)
|
|
||||||
|
|
||||||
// public repo & no login
|
|
||||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedRepo: pubRepo,
|
|
||||||
IncludePrivate: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
|
|
||||||
// private repo and login
|
|
||||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedRepo: privRepo,
|
|
||||||
IncludePrivate: true,
|
|
||||||
Actor: user,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
|
|
||||||
// public repo & login
|
|
||||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedRepo: pubRepo,
|
|
||||||
IncludePrivate: true,
|
|
||||||
Actor: user,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestGetFeeds2(t *testing.T) {
|
|
||||||
// test with an organization user
|
|
||||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
||||||
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
|
||||||
|
|
||||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedUser: org,
|
|
||||||
Actor: user,
|
|
||||||
IncludePrivate: true,
|
|
||||||
OnlyPerformedBy: false,
|
|
||||||
IncludeDeleted: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
if assert.Len(t, actions, 1) {
|
|
||||||
assert.EqualValues(t, 2, actions[0].ID)
|
|
||||||
assert.EqualValues(t, org.ID, actions[0].UserID)
|
|
||||||
}
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
|
|
||||||
actions, count, err = activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedUser: org,
|
|
||||||
Actor: user,
|
|
||||||
IncludePrivate: false,
|
|
||||||
OnlyPerformedBy: false,
|
|
||||||
IncludeDeleted: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 0)
|
|
||||||
assert.Equal(t, int64(0), count)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestActivityReadable(t *testing.T) {
|
func TestActivityReadable(t *testing.T) {
|
||||||
tt := []struct {
|
tt := []struct {
|
||||||
desc string
|
desc string
|
||||||
@ -227,26 +119,6 @@ func TestNotifyWatchers(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetFeedsCorrupted(t *testing.T) {
|
|
||||||
// Now we will not check for corrupted data in the feeds
|
|
||||||
// users should run doctor to fix their data
|
|
||||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
||||||
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
|
||||||
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
|
|
||||||
ID: 8,
|
|
||||||
RepoID: 1700,
|
|
||||||
})
|
|
||||||
|
|
||||||
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedUser: user,
|
|
||||||
Actor: user,
|
|
||||||
IncludePrivate: true,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
assert.Equal(t, int64(1), count)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestConsistencyUpdateAction(t *testing.T) {
|
func TestConsistencyUpdateAction(t *testing.T) {
|
||||||
if !setting.Database.Type.IsSQLite3() {
|
if !setting.Database.Type.IsSQLite3() {
|
||||||
t.Skip("Test is only for SQLite database.")
|
t.Skip("Test is only for SQLite database.")
|
||||||
@ -322,24 +194,3 @@ func TestDeleteIssueActions(t *testing.T) {
|
|||||||
assert.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index))
|
assert.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index))
|
||||||
unittest.AssertCount(t, &activities_model.Action{}, 0)
|
unittest.AssertCount(t, &activities_model.Action{}, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRepoActions(t *testing.T) {
|
|
||||||
assert.NoError(t, unittest.PrepareTestDatabase())
|
|
||||||
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
|
||||||
_ = db.TruncateBeans(db.DefaultContext, &activities_model.Action{})
|
|
||||||
for i := 0; i < 3; i++ {
|
|
||||||
_ = db.Insert(db.DefaultContext, &activities_model.Action{
|
|
||||||
UserID: 2 + int64(i),
|
|
||||||
ActUserID: 2,
|
|
||||||
RepoID: repo.ID,
|
|
||||||
OpType: activities_model.ActionCommentIssue,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
count, _ := db.Count[activities_model.Action](db.DefaultContext, &db.ListOptions{})
|
|
||||||
assert.EqualValues(t, 3, count)
|
|
||||||
actions, _, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
|
||||||
RequestedRepo: repo,
|
|
||||||
})
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Len(t, actions, 1)
|
|
||||||
}
|
|
||||||
|
@ -47,7 +47,7 @@ func getUserHeatmapData(ctx context.Context, user *user_model.User, team *organi
|
|||||||
groupByName = groupBy
|
groupByName = groupBy
|
||||||
}
|
}
|
||||||
|
|
||||||
cond, err := activityQueryCondition(ctx, GetFeedsOptions{
|
cond, err := ActivityQueryCondition(ctx, GetFeedsOptions{
|
||||||
RequestedUser: user,
|
RequestedUser: user,
|
||||||
RequestedTeam: team,
|
RequestedTeam: team,
|
||||||
Actor: doer,
|
Actor: doer,
|
||||||
|
@ -12,6 +12,8 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/markup"
|
"code.gitea.io/gitea/modules/markup"
|
||||||
"code.gitea.io/gitea/modules/markup/markdown"
|
"code.gitea.io/gitea/modules/markup/markdown"
|
||||||
|
|
||||||
|
_ "code.gitea.io/gitea/modules/markup/orgmode"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -81,3 +83,40 @@ func TestRepoFile(t *testing.T) {
|
|||||||
</video>`, rendered)
|
</video>`, rendered)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestRepoFileOrgMode(t *testing.T) {
|
||||||
|
unittest.PrepareTestEnv(t)
|
||||||
|
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||||
|
|
||||||
|
t.Run("Links", func(t *testing.T) {
|
||||||
|
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{
|
||||||
|
CurrentRefPath: "/commit/1234",
|
||||||
|
CurrentTreePath: "my-dir",
|
||||||
|
}).WithRelativePath("my-dir/a.org")
|
||||||
|
|
||||||
|
rendered, err := markup.RenderString(rctx, `
|
||||||
|
[[https://google.com/]]
|
||||||
|
[[ImageLink.svg][The Image Desc]]
|
||||||
|
`)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, `<p>
|
||||||
|
<a href="https://google.com/" rel="nofollow">https://google.com/</a>
|
||||||
|
<a href="/user2/repo1/media/commit/1234/my-dir/ImageLink.svg" rel="nofollow">The Image Desc</a></p>
|
||||||
|
`, rendered)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("CodeHighlight", func(t *testing.T) {
|
||||||
|
rctx := NewRenderContextRepoFile(context.Background(), repo1, RepoFileOptions{}).WithRelativePath("my-dir/a.org")
|
||||||
|
|
||||||
|
rendered, err := markup.RenderString(rctx, `
|
||||||
|
#+begin_src c
|
||||||
|
int a = 1;
|
||||||
|
#+end_src
|
||||||
|
`)
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Equal(t, `<div>
|
||||||
|
<pre><code class="chroma language-c"><span class="kt">int</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span></code></pre>
|
||||||
|
</div>
|
||||||
|
`, rendered)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
2
modules/cache/cache_test.go
vendored
2
modules/cache/cache_test.go
vendored
@ -43,7 +43,7 @@ func TestTest(t *testing.T) {
|
|||||||
elapsed, err := Test()
|
elapsed, err := Test()
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
// mem cache should take from 300ns up to 1ms on modern hardware ...
|
// mem cache should take from 300ns up to 1ms on modern hardware ...
|
||||||
assert.Less(t, elapsed, SlowCacheThreshold)
|
assert.Less(t, elapsed, time.Millisecond)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestGetCache(t *testing.T) {
|
func TestGetCache(t *testing.T) {
|
||||||
|
@ -6,10 +6,12 @@ package markup
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
"html"
|
||||||
|
"html/template"
|
||||||
"io"
|
"io"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"code.gitea.io/gitea/modules/highlight"
|
"code.gitea.io/gitea/modules/highlight"
|
||||||
|
"code.gitea.io/gitea/modules/htmlutil"
|
||||||
"code.gitea.io/gitea/modules/log"
|
"code.gitea.io/gitea/modules/log"
|
||||||
"code.gitea.io/gitea/modules/markup"
|
"code.gitea.io/gitea/modules/markup"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
@ -20,33 +22,36 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
markup.RegisterRenderer(Renderer{})
|
markup.RegisterRenderer(renderer{})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Renderer implements markup.Renderer for orgmode
|
// Renderer implements markup.Renderer for orgmode
|
||||||
type Renderer struct{}
|
type renderer struct{}
|
||||||
|
|
||||||
var _ markup.PostProcessRenderer = (*Renderer)(nil)
|
var (
|
||||||
|
_ markup.Renderer = (*renderer)(nil)
|
||||||
|
_ markup.PostProcessRenderer = (*renderer)(nil)
|
||||||
|
)
|
||||||
|
|
||||||
// Name implements markup.Renderer
|
// Name implements markup.Renderer
|
||||||
func (Renderer) Name() string {
|
func (renderer) Name() string {
|
||||||
return "orgmode"
|
return "orgmode"
|
||||||
}
|
}
|
||||||
|
|
||||||
// NeedPostProcess implements markup.PostProcessRenderer
|
// NeedPostProcess implements markup.PostProcessRenderer
|
||||||
func (Renderer) NeedPostProcess() bool { return true }
|
func (renderer) NeedPostProcess() bool { return true }
|
||||||
|
|
||||||
// Extensions implements markup.Renderer
|
// Extensions implements markup.Renderer
|
||||||
func (Renderer) Extensions() []string {
|
func (renderer) Extensions() []string {
|
||||||
return []string{".org"}
|
return []string{".org"}
|
||||||
}
|
}
|
||||||
|
|
||||||
// SanitizerRules implements markup.Renderer
|
// SanitizerRules implements markup.Renderer
|
||||||
func (Renderer) SanitizerRules() []setting.MarkupSanitizerRule {
|
func (renderer) SanitizerRules() []setting.MarkupSanitizerRule {
|
||||||
return []setting.MarkupSanitizerRule{}
|
return []setting.MarkupSanitizerRule{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Render renders orgmode rawbytes to HTML
|
// Render renders orgmode raw bytes to HTML
|
||||||
func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
|
func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
|
||||||
htmlWriter := org.NewHTMLWriter()
|
htmlWriter := org.NewHTMLWriter()
|
||||||
htmlWriter.HighlightCodeBlock = func(source, lang string, inline bool, params map[string]string) string {
|
htmlWriter.HighlightCodeBlock = func(source, lang string, inline bool, params map[string]string) string {
|
||||||
@ -56,10 +61,7 @@ func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
|
|||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
var w strings.Builder
|
w := &strings.Builder{}
|
||||||
if _, err := w.WriteString(`<pre>`); err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
lexer := lexers.Get(lang)
|
lexer := lexers.Get(lang)
|
||||||
if lexer == nil && lang == "" {
|
if lexer == nil && lang == "" {
|
||||||
@ -70,26 +72,20 @@ func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
|
|||||||
lang = strings.ToLower(lexer.Config().Name)
|
lang = strings.ToLower(lexer.Config().Name)
|
||||||
}
|
}
|
||||||
|
|
||||||
if lexer == nil {
|
|
||||||
// include language-x class as part of commonmark spec
|
// include language-x class as part of commonmark spec
|
||||||
if _, err := w.WriteString(`<code class="chroma language-` + lang + `">`); err != nil {
|
if err := ctx.RenderInternal.FormatWithSafeAttrs(w, `<pre><code class="chroma language-%s">`, lang); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
if lexer == nil {
|
||||||
if _, err := w.WriteString(html.EscapeString(source)); err != nil {
|
if _, err := w.WriteString(html.EscapeString(source)); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// include language-x class as part of commonmark spec
|
|
||||||
if _, err := w.WriteString(`<code class="chroma language-` + lang + `">`); err != nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
lexer = chroma.Coalesce(lexer)
|
lexer = chroma.Coalesce(lexer)
|
||||||
|
|
||||||
if _, err := w.WriteString(string(highlight.CodeFromLexer(lexer, source))); err != nil {
|
if _, err := w.WriteString(string(highlight.CodeFromLexer(lexer, source))); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := w.WriteString("</code></pre>"); err != nil {
|
if _, err := w.WriteString("</code></pre>"); err != nil {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
@ -97,11 +93,7 @@ func Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error
|
|||||||
return w.String()
|
return w.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
w := &Writer{
|
w := &orgWriter{rctx: ctx, HTMLWriter: htmlWriter}
|
||||||
HTMLWriter: htmlWriter,
|
|
||||||
Ctx: ctx,
|
|
||||||
}
|
|
||||||
|
|
||||||
htmlWriter.ExtendingWriter = w
|
htmlWriter.ExtendingWriter = w
|
||||||
|
|
||||||
res, err := org.New().Silent().Parse(input, "").Write(w)
|
res, err := org.New().Silent().Parse(input, "").Write(w)
|
||||||
@ -122,17 +114,18 @@ func RenderString(ctx *markup.RenderContext, content string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Render renders orgmode string to HTML string
|
// Render renders orgmode string to HTML string
|
||||||
func (Renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
|
func (renderer) Render(ctx *markup.RenderContext, input io.Reader, output io.Writer) error {
|
||||||
return Render(ctx, input, output)
|
return Render(ctx, input, output)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Writer implements org.Writer
|
type orgWriter struct {
|
||||||
type Writer struct {
|
|
||||||
*org.HTMLWriter
|
*org.HTMLWriter
|
||||||
Ctx *markup.RenderContext
|
rctx *markup.RenderContext
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Writer) resolveLink(kind, link string) string {
|
var _ org.Writer = (*orgWriter)(nil)
|
||||||
|
|
||||||
|
func (r *orgWriter) resolveLink(kind, link string) string {
|
||||||
link = strings.TrimPrefix(link, "file:")
|
link = strings.TrimPrefix(link, "file:")
|
||||||
if !strings.HasPrefix(link, "#") && // not a URL fragment
|
if !strings.HasPrefix(link, "#") && // not a URL fragment
|
||||||
!markup.IsFullURLString(link) {
|
!markup.IsFullURLString(link) {
|
||||||
@ -142,39 +135,42 @@ func (r *Writer) resolveLink(kind, link string) string {
|
|||||||
kind = org.RegularLink{URL: link}.Kind()
|
kind = org.RegularLink{URL: link}.Kind()
|
||||||
}
|
}
|
||||||
if kind == "image" || kind == "video" {
|
if kind == "image" || kind == "video" {
|
||||||
link = r.Ctx.RenderHelper.ResolveLink(link, markup.LinkTypeMedia)
|
link = r.rctx.RenderHelper.ResolveLink(link, markup.LinkTypeMedia)
|
||||||
} else {
|
} else {
|
||||||
link = r.Ctx.RenderHelper.ResolveLink(link, markup.LinkTypeDefault)
|
link = r.rctx.RenderHelper.ResolveLink(link, markup.LinkTypeDefault)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return link
|
return link
|
||||||
}
|
}
|
||||||
|
|
||||||
// WriteRegularLink renders images, links or videos
|
// WriteRegularLink renders images, links or videos
|
||||||
func (r *Writer) WriteRegularLink(l org.RegularLink) {
|
func (r *orgWriter) WriteRegularLink(l org.RegularLink) {
|
||||||
link := r.resolveLink(l.Kind(), l.URL)
|
link := r.resolveLink(l.Kind(), l.URL)
|
||||||
|
|
||||||
|
printHTML := func(html string, a ...any) {
|
||||||
|
_, _ = fmt.Fprint(r, htmlutil.HTMLFormat(html, a...))
|
||||||
|
}
|
||||||
// Inspired by https://github.com/niklasfasching/go-org/blob/6eb20dbda93cb88c3503f7508dc78cbbc639378f/org/html_writer.go#L406-L427
|
// Inspired by https://github.com/niklasfasching/go-org/blob/6eb20dbda93cb88c3503f7508dc78cbbc639378f/org/html_writer.go#L406-L427
|
||||||
switch l.Kind() {
|
switch l.Kind() {
|
||||||
case "image":
|
case "image":
|
||||||
if l.Description == nil {
|
if l.Description == nil {
|
||||||
_, _ = fmt.Fprintf(r, `<img src="%s" alt="%s" />`, link, link)
|
printHTML(`<img src="%s" alt="%s">`, link, link)
|
||||||
} else {
|
} else {
|
||||||
imageSrc := r.resolveLink(l.Kind(), org.String(l.Description...))
|
imageSrc := r.resolveLink(l.Kind(), org.String(l.Description...))
|
||||||
_, _ = fmt.Fprintf(r, `<a href="%s"><img src="%s" alt="%s" /></a>`, link, imageSrc, imageSrc)
|
printHTML(`<a href="%s"><img src="%s" alt="%s"></a>`, link, imageSrc, imageSrc)
|
||||||
}
|
}
|
||||||
case "video":
|
case "video":
|
||||||
if l.Description == nil {
|
if l.Description == nil {
|
||||||
_, _ = fmt.Fprintf(r, `<video src="%s">%s</video>`, link, link)
|
printHTML(`<video src="%s">%s</video>`, link, link)
|
||||||
} else {
|
} else {
|
||||||
videoSrc := r.resolveLink(l.Kind(), org.String(l.Description...))
|
videoSrc := r.resolveLink(l.Kind(), org.String(l.Description...))
|
||||||
_, _ = fmt.Fprintf(r, `<a href="%s"><video src="%s">%s</video></a>`, link, videoSrc, videoSrc)
|
printHTML(`<a href="%s"><video src="%s">%s</video></a>`, link, videoSrc, videoSrc)
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
description := link
|
var description any = link
|
||||||
if l.Description != nil {
|
if l.Description != nil {
|
||||||
description = r.WriteNodesAsString(l.Description...)
|
description = template.HTML(r.WriteNodesAsString(l.Description...)) // orgmode HTMLWriter outputs HTML content
|
||||||
}
|
}
|
||||||
_, _ = fmt.Fprintf(r, `<a href="%s">%s</a>`, link, description)
|
printHTML(`<a href="%s">%s</a>`, link, description)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -58,15 +58,15 @@ func TestRender_Media(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test("[[file:../../.images/src/02/train.jpg]]",
|
test("[[file:../../.images/src/02/train.jpg]]",
|
||||||
`<p><img src=".images/src/02/train.jpg" alt=".images/src/02/train.jpg" /></p>`)
|
`<p><img src=".images/src/02/train.jpg" alt=".images/src/02/train.jpg"></p>`)
|
||||||
test("[[file:train.jpg]]",
|
test("[[file:train.jpg]]",
|
||||||
`<p><img src="relative-path/train.jpg" alt="relative-path/train.jpg" /></p>`)
|
`<p><img src="relative-path/train.jpg" alt="relative-path/train.jpg"></p>`)
|
||||||
|
|
||||||
// With description.
|
// With description.
|
||||||
test("[[https://example.com][https://example.com/example.svg]]",
|
test("[[https://example.com][https://example.com/example.svg]]",
|
||||||
`<p><a href="https://example.com"><img src="https://example.com/example.svg" alt="https://example.com/example.svg" /></a></p>`)
|
`<p><a href="https://example.com"><img src="https://example.com/example.svg" alt="https://example.com/example.svg"></a></p>`)
|
||||||
test("[[https://example.com][pre https://example.com/example.svg post]]",
|
test("[[https://example.com][pre https://example.com/example.svg post]]",
|
||||||
`<p><a href="https://example.com">pre <img src="https://example.com/example.svg" alt="https://example.com/example.svg" /> post</a></p>`)
|
`<p><a href="https://example.com">pre <img src="https://example.com/example.svg" alt="https://example.com/example.svg"> post</a></p>`)
|
||||||
test("[[https://example.com][https://example.com/example.mp4]]",
|
test("[[https://example.com][https://example.com/example.mp4]]",
|
||||||
`<p><a href="https://example.com"><video src="https://example.com/example.mp4">https://example.com/example.mp4</video></a></p>`)
|
`<p><a href="https://example.com"><video src="https://example.com/example.mp4">https://example.com/example.mp4</video></a></p>`)
|
||||||
test("[[https://example.com][pre https://example.com/example.mp4 post]]",
|
test("[[https://example.com][pre https://example.com/example.mp4 post]]",
|
||||||
@ -74,19 +74,19 @@ func TestRender_Media(t *testing.T) {
|
|||||||
|
|
||||||
// Without description.
|
// Without description.
|
||||||
test("[[https://example.com/example.svg]]",
|
test("[[https://example.com/example.svg]]",
|
||||||
`<p><img src="https://example.com/example.svg" alt="https://example.com/example.svg" /></p>`)
|
`<p><img src="https://example.com/example.svg" alt="https://example.com/example.svg"></p>`)
|
||||||
test("[[https://example.com/example.mp4]]",
|
test("[[https://example.com/example.mp4]]",
|
||||||
`<p><video src="https://example.com/example.mp4">https://example.com/example.mp4</video></p>`)
|
`<p><video src="https://example.com/example.mp4">https://example.com/example.mp4</video></p>`)
|
||||||
|
|
||||||
// test [[LINK][DESCRIPTION]] syntax with "file:" prefix
|
// test [[LINK][DESCRIPTION]] syntax with "file:" prefix
|
||||||
test(`[[https://example.com/][file:https://example.com/foo%20bar.svg]]`,
|
test(`[[https://example.com/][file:https://example.com/foo%20bar.svg]]`,
|
||||||
`<p><a href="https://example.com/"><img src="https://example.com/foo%20bar.svg" alt="https://example.com/foo%20bar.svg" /></a></p>`)
|
`<p><a href="https://example.com/"><img src="https://example.com/foo%20bar.svg" alt="https://example.com/foo%20bar.svg"></a></p>`)
|
||||||
test(`[[file:https://example.com/foo%20bar.svg][Goto Image]]`,
|
test(`[[file:https://example.com/foo%20bar.svg][Goto Image]]`,
|
||||||
`<p><a href="https://example.com/foo%20bar.svg">Goto Image</a></p>`)
|
`<p><a href="https://example.com/foo%20bar.svg">Goto Image</a></p>`)
|
||||||
test(`[[file:https://example.com/link][https://example.com/image.jpg]]`,
|
test(`[[file:https://example.com/link][https://example.com/image.jpg]]`,
|
||||||
`<p><a href="https://example.com/link"><img src="https://example.com/image.jpg" alt="https://example.com/image.jpg" /></a></p>`)
|
`<p><a href="https://example.com/link"><img src="https://example.com/image.jpg" alt="https://example.com/image.jpg"></a></p>`)
|
||||||
test(`[[file:https://example.com/link][file:https://example.com/image.jpg]]`,
|
test(`[[file:https://example.com/link][file:https://example.com/image.jpg]]`,
|
||||||
`<p><a href="https://example.com/link"><img src="https://example.com/image.jpg" alt="https://example.com/image.jpg" /></a></p>`)
|
`<p><a href="https://example.com/link"><img src="https://example.com/image.jpg" alt="https://example.com/image.jpg"></a></p>`)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRender_Source(t *testing.T) {
|
func TestRender_Source(t *testing.T) {
|
||||||
|
@ -41,6 +41,7 @@ var Service = struct {
|
|||||||
AllowOnlyInternalRegistration bool
|
AllowOnlyInternalRegistration bool
|
||||||
AllowOnlyExternalRegistration bool
|
AllowOnlyExternalRegistration bool
|
||||||
ShowRegistrationButton bool
|
ShowRegistrationButton bool
|
||||||
|
EnablePasswordSignInForm bool
|
||||||
ShowMilestonesDashboardPage bool
|
ShowMilestonesDashboardPage bool
|
||||||
RequireSignInView bool
|
RequireSignInView bool
|
||||||
EnableNotifyMail bool
|
EnableNotifyMail bool
|
||||||
@ -159,6 +160,7 @@ func loadServiceFrom(rootCfg ConfigProvider) {
|
|||||||
Service.ShowMilestonesDashboardPage = sec.Key("SHOW_MILESTONES_DASHBOARD_PAGE").MustBool(true)
|
Service.ShowMilestonesDashboardPage = sec.Key("SHOW_MILESTONES_DASHBOARD_PAGE").MustBool(true)
|
||||||
Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
|
Service.RequireSignInView = sec.Key("REQUIRE_SIGNIN_VIEW").MustBool()
|
||||||
Service.EnableBasicAuth = sec.Key("ENABLE_BASIC_AUTHENTICATION").MustBool(true)
|
Service.EnableBasicAuth = sec.Key("ENABLE_BASIC_AUTHENTICATION").MustBool(true)
|
||||||
|
Service.EnablePasswordSignInForm = sec.Key("ENABLE_PASSWORD_SIGNIN_FORM").MustBool(true)
|
||||||
Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
|
Service.EnableReverseProxyAuth = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION").MustBool()
|
||||||
Service.EnableReverseProxyAuthAPI = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION_API").MustBool()
|
Service.EnableReverseProxyAuthAPI = sec.Key("ENABLE_REVERSE_PROXY_AUTHENTICATION_API").MustBool()
|
||||||
Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
|
Service.EnableReverseProxyAutoRegister = sec.Key("ENABLE_REVERSE_PROXY_AUTO_REGISTRATION").MustBool()
|
||||||
|
@ -1032,6 +1032,8 @@ fork_to_different_account = Fork to a different account
|
|||||||
fork_visibility_helper = The visibility of a forked repository cannot be changed.
|
fork_visibility_helper = The visibility of a forked repository cannot be changed.
|
||||||
fork_branch = Branch to be cloned to the fork
|
fork_branch = Branch to be cloned to the fork
|
||||||
all_branches = All branches
|
all_branches = All branches
|
||||||
|
view_all_branches = View all branches
|
||||||
|
view_all_tags = View all tags
|
||||||
fork_no_valid_owners = This repository can not be forked because there are no valid owners.
|
fork_no_valid_owners = This repository can not be forked because there are no valid owners.
|
||||||
fork.blocked_user = Cannot fork the repository because you are blocked by the repository owner.
|
fork.blocked_user = Cannot fork the repository because you are blocked by the repository owner.
|
||||||
use_template = Use this template
|
use_template = Use this template
|
||||||
@ -1461,8 +1463,6 @@ issues.new.no_items = No items
|
|||||||
issues.new.milestone = Milestone
|
issues.new.milestone = Milestone
|
||||||
issues.new.no_milestone = No Milestone
|
issues.new.no_milestone = No Milestone
|
||||||
issues.new.clear_milestone = Clear milestone
|
issues.new.clear_milestone = Clear milestone
|
||||||
issues.new.open_milestone = Open Milestones
|
|
||||||
issues.new.closed_milestone = Closed Milestones
|
|
||||||
issues.new.assignees = Assignees
|
issues.new.assignees = Assignees
|
||||||
issues.new.clear_assignees = Clear assignees
|
issues.new.clear_assignees = Clear assignees
|
||||||
issues.new.no_assignees = No Assignees
|
issues.new.no_assignees = No Assignees
|
||||||
|
@ -19,6 +19,7 @@ import (
|
|||||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
"code.gitea.io/gitea/services/convert"
|
"code.gitea.io/gitea/services/convert"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
"code.gitea.io/gitea/services/org"
|
"code.gitea.io/gitea/services/org"
|
||||||
user_service "code.gitea.io/gitea/services/user"
|
user_service "code.gitea.io/gitea/services/user"
|
||||||
)
|
)
|
||||||
@ -447,7 +448,7 @@ func ListOrgActivityFeeds(ctx *context.APIContext) {
|
|||||||
ListOptions: listOptions,
|
ListOptions: listOptions,
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds, count, err := activities_model.GetFeeds(ctx, opts)
|
feeds, count, err := feed_service.GetFeeds(ctx, opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
||||||
return
|
return
|
||||||
|
@ -22,6 +22,7 @@ import (
|
|||||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
"code.gitea.io/gitea/services/convert"
|
"code.gitea.io/gitea/services/convert"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
org_service "code.gitea.io/gitea/services/org"
|
org_service "code.gitea.io/gitea/services/org"
|
||||||
repo_service "code.gitea.io/gitea/services/repository"
|
repo_service "code.gitea.io/gitea/services/repository"
|
||||||
)
|
)
|
||||||
@ -882,7 +883,7 @@ func ListTeamActivityFeeds(ctx *context.APIContext) {
|
|||||||
ListOptions: listOptions,
|
ListOptions: listOptions,
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds, count, err := activities_model.GetFeeds(ctx, opts)
|
feeds, count, err := feed_service.GetFeeds(ctx, opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
||||||
return
|
return
|
||||||
|
@ -34,6 +34,7 @@ import (
|
|||||||
actions_service "code.gitea.io/gitea/services/actions"
|
actions_service "code.gitea.io/gitea/services/actions"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
"code.gitea.io/gitea/services/convert"
|
"code.gitea.io/gitea/services/convert"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
"code.gitea.io/gitea/services/issue"
|
"code.gitea.io/gitea/services/issue"
|
||||||
repo_service "code.gitea.io/gitea/services/repository"
|
repo_service "code.gitea.io/gitea/services/repository"
|
||||||
)
|
)
|
||||||
@ -1313,7 +1314,7 @@ func ListRepoActivityFeeds(ctx *context.APIContext) {
|
|||||||
ListOptions: listOptions,
|
ListOptions: listOptions,
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds, count, err := activities_model.GetFeeds(ctx, opts)
|
feeds, count, err := feed_service.GetFeeds(ctx, opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
||||||
return
|
return
|
||||||
|
@ -13,6 +13,7 @@ import (
|
|||||||
"code.gitea.io/gitea/routers/api/v1/utils"
|
"code.gitea.io/gitea/routers/api/v1/utils"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
"code.gitea.io/gitea/services/convert"
|
"code.gitea.io/gitea/services/convert"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Search search users
|
// Search search users
|
||||||
@ -214,7 +215,7 @@ func ListUserActivityFeeds(ctx *context.APIContext) {
|
|||||||
ListOptions: listOptions,
|
ListOptions: listOptions,
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds, count, err := activities_model.GetFeeds(ctx, opts)
|
feeds, count, err := feed_service.GetFeeds(ctx, opts)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
ctx.Error(http.StatusInternalServerError, "GetFeeds", err)
|
||||||
return
|
return
|
||||||
|
@ -17,6 +17,7 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
"code.gitea.io/gitea/services/mailer"
|
"code.gitea.io/gitea/services/mailer"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SendEmail pushes messages to mail queue
|
// SendEmail pushes messages to mail queue
|
||||||
@ -81,7 +82,7 @@ func SendEmail(ctx *context.PrivateContext) {
|
|||||||
|
|
||||||
func sendEmail(ctx *context.PrivateContext, subject, message string, to []string) {
|
func sendEmail(ctx *context.PrivateContext, subject, message string, to []string) {
|
||||||
for _, email := range to {
|
for _, email := range to {
|
||||||
msg := mailer.NewMessage(email, subject, message)
|
msg := sender_service.NewMessage(email, subject, message)
|
||||||
mailer.SendAsync(msg)
|
mailer.SendAsync(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -160,54 +160,42 @@ func CheckAutoLogin(ctx *context.Context) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// SignIn render sign in page
|
func prepareSignInPageData(ctx *context.Context) {
|
||||||
func SignIn(ctx *context.Context) {
|
|
||||||
ctx.Data["Title"] = ctx.Tr("sign_in")
|
ctx.Data["Title"] = ctx.Tr("sign_in")
|
||||||
|
ctx.Data["OAuth2Providers"], _ = oauth2.GetOAuth2Providers(ctx, optional.Some(true))
|
||||||
if CheckAutoLogin(ctx) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if ctx.IsSigned {
|
|
||||||
RedirectAfterLogin(ctx)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
|
|
||||||
if err != nil {
|
|
||||||
ctx.ServerError("UserSignIn", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctx.Data["OAuth2Providers"] = oauth2Providers
|
|
||||||
ctx.Data["Title"] = ctx.Tr("sign_in")
|
ctx.Data["Title"] = ctx.Tr("sign_in")
|
||||||
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
|
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
|
||||||
ctx.Data["PageIsSignIn"] = true
|
ctx.Data["PageIsSignIn"] = true
|
||||||
ctx.Data["PageIsLogin"] = true
|
ctx.Data["PageIsLogin"] = true
|
||||||
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
|
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
|
||||||
|
ctx.Data["EnablePasswordSignInForm"] = setting.Service.EnablePasswordSignInForm
|
||||||
|
|
||||||
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
|
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
|
||||||
context.SetCaptchaData(ctx)
|
context.SetCaptchaData(ctx)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SignIn render sign in page
|
||||||
|
func SignIn(ctx *context.Context) {
|
||||||
|
if CheckAutoLogin(ctx) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ctx.IsSigned {
|
||||||
|
RedirectAfterLogin(ctx)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prepareSignInPageData(ctx)
|
||||||
ctx.HTML(http.StatusOK, tplSignIn)
|
ctx.HTML(http.StatusOK, tplSignIn)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SignInPost response for sign in request
|
// SignInPost response for sign in request
|
||||||
func SignInPost(ctx *context.Context) {
|
func SignInPost(ctx *context.Context) {
|
||||||
ctx.Data["Title"] = ctx.Tr("sign_in")
|
if !setting.Service.EnablePasswordSignInForm {
|
||||||
|
ctx.Error(http.StatusForbidden)
|
||||||
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
|
|
||||||
if err != nil {
|
|
||||||
ctx.ServerError("UserSignIn", err)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ctx.Data["OAuth2Providers"] = oauth2Providers
|
|
||||||
ctx.Data["Title"] = ctx.Tr("sign_in")
|
|
||||||
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
|
|
||||||
ctx.Data["PageIsSignIn"] = true
|
|
||||||
ctx.Data["PageIsLogin"] = true
|
|
||||||
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
|
|
||||||
|
|
||||||
|
prepareSignInPageData(ctx)
|
||||||
if ctx.HasError() {
|
if ctx.HasError() {
|
||||||
ctx.HTML(http.StatusOK, tplSignIn)
|
ctx.HTML(http.StatusOK, tplSignIn)
|
||||||
return
|
return
|
||||||
@ -216,8 +204,6 @@ func SignInPost(ctx *context.Context) {
|
|||||||
form := web.GetForm(ctx).(*forms.SignInForm)
|
form := web.GetForm(ctx).(*forms.SignInForm)
|
||||||
|
|
||||||
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
|
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
|
||||||
context.SetCaptchaData(ctx)
|
|
||||||
|
|
||||||
context.VerifyCaptcha(ctx, tplSignIn, form)
|
context.VerifyCaptcha(ctx, tplSignIn, form)
|
||||||
if ctx.Written() {
|
if ctx.Written() {
|
||||||
return
|
return
|
||||||
|
@ -10,6 +10,7 @@ import (
|
|||||||
"code.gitea.io/gitea/models/renderhelper"
|
"code.gitea.io/gitea/models/renderhelper"
|
||||||
"code.gitea.io/gitea/modules/markup/markdown"
|
"code.gitea.io/gitea/modules/markup/markdown"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
|
|
||||||
"github.com/gorilla/feeds"
|
"github.com/gorilla/feeds"
|
||||||
)
|
)
|
||||||
@ -28,7 +29,7 @@ func ShowUserFeedAtom(ctx *context.Context) {
|
|||||||
func showUserFeed(ctx *context.Context, formatType string) {
|
func showUserFeed(ctx *context.Context, formatType string) {
|
||||||
includePrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == ctx.ContextUser.ID)
|
includePrivate := ctx.IsSigned && (ctx.Doer.IsAdmin || ctx.Doer.ID == ctx.ContextUser.ID)
|
||||||
|
|
||||||
actions, _, err := activities_model.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
actions, _, err := feed_service.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
||||||
RequestedUser: ctx.ContextUser,
|
RequestedUser: ctx.ContextUser,
|
||||||
Actor: ctx.Doer,
|
Actor: ctx.Doer,
|
||||||
IncludePrivate: includePrivate,
|
IncludePrivate: includePrivate,
|
||||||
|
@ -9,13 +9,14 @@ import (
|
|||||||
activities_model "code.gitea.io/gitea/models/activities"
|
activities_model "code.gitea.io/gitea/models/activities"
|
||||||
repo_model "code.gitea.io/gitea/models/repo"
|
repo_model "code.gitea.io/gitea/models/repo"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
|
|
||||||
"github.com/gorilla/feeds"
|
"github.com/gorilla/feeds"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ShowRepoFeed shows user activity on the repo as RSS / Atom feed
|
// ShowRepoFeed shows user activity on the repo as RSS / Atom feed
|
||||||
func ShowRepoFeed(ctx *context.Context, repo *repo_model.Repository, formatType string) {
|
func ShowRepoFeed(ctx *context.Context, repo *repo_model.Repository, formatType string) {
|
||||||
actions, _, err := activities_model.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
actions, _, err := feed_service.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
||||||
RequestedRepo: repo,
|
RequestedRepo: repo,
|
||||||
Actor: ctx.Doer,
|
Actor: ctx.Doer,
|
||||||
IncludePrivate: true,
|
IncludePrivate: true,
|
||||||
|
@ -33,6 +33,7 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/routers/web/feed"
|
"code.gitea.io/gitea/routers/web/feed"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
issue_service "code.gitea.io/gitea/services/issue"
|
issue_service "code.gitea.io/gitea/services/issue"
|
||||||
pull_service "code.gitea.io/gitea/services/pull"
|
pull_service "code.gitea.io/gitea/services/pull"
|
||||||
|
|
||||||
@ -113,7 +114,7 @@ func Dashboard(ctx *context.Context) {
|
|||||||
ctx.Data["HeatmapTotalContributions"] = activities_model.GetTotalContributionsInHeatmap(data)
|
ctx.Data["HeatmapTotalContributions"] = activities_model.GetTotalContributionsInHeatmap(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
feeds, count, err := activities_model.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
feeds, count, err := feed_service.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
||||||
RequestedUser: ctxUser,
|
RequestedUser: ctxUser,
|
||||||
RequestedTeam: ctx.Org.Team,
|
RequestedTeam: ctx.Org.Team,
|
||||||
Actor: ctx.Doer,
|
Actor: ctx.Doer,
|
||||||
|
@ -26,6 +26,7 @@ import (
|
|||||||
"code.gitea.io/gitea/routers/web/org"
|
"code.gitea.io/gitea/routers/web/org"
|
||||||
shared_user "code.gitea.io/gitea/routers/web/shared/user"
|
shared_user "code.gitea.io/gitea/routers/web/shared/user"
|
||||||
"code.gitea.io/gitea/services/context"
|
"code.gitea.io/gitea/services/context"
|
||||||
|
feed_service "code.gitea.io/gitea/services/feed"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -167,7 +168,7 @@ func prepareUserProfileTabData(ctx *context.Context, showPrivate bool, profileDb
|
|||||||
case "activity":
|
case "activity":
|
||||||
date := ctx.FormString("date")
|
date := ctx.FormString("date")
|
||||||
pagingNum = setting.UI.FeedPagingNum
|
pagingNum = setting.UI.FeedPagingNum
|
||||||
items, count, err := activities_model.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
items, count, err := feed_service.GetFeeds(ctx, activities_model.GetFeedsOptions{
|
||||||
RequestedUser: ctx.ContextUser,
|
RequestedUser: ctx.ContextUser,
|
||||||
Actor: ctx.Doer,
|
Actor: ctx.Doer,
|
||||||
IncludePrivate: showPrivate,
|
IncludePrivate: showPrivate,
|
||||||
|
15
services/feed/feed.go
Normal file
15
services/feed/feed.go
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package feed
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
|
||||||
|
activities_model "code.gitea.io/gitea/models/activities"
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetFeeds returns actions according to the provided options
|
||||||
|
func GetFeeds(ctx context.Context, opts activities_model.GetFeedsOptions) (activities_model.ActionList, int64, error) {
|
||||||
|
return activities_model.GetFeeds(ctx, opts)
|
||||||
|
}
|
165
services/feed/feed_test.go
Normal file
165
services/feed/feed_test.go
Normal file
@ -0,0 +1,165 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package feed
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
activities_model "code.gitea.io/gitea/models/activities"
|
||||||
|
"code.gitea.io/gitea/models/db"
|
||||||
|
repo_model "code.gitea.io/gitea/models/repo"
|
||||||
|
"code.gitea.io/gitea/models/unittest"
|
||||||
|
user_model "code.gitea.io/gitea/models/user"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetFeeds(t *testing.T) {
|
||||||
|
// test with an individual user
|
||||||
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||||
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||||
|
|
||||||
|
actions, count, err := GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedUser: user,
|
||||||
|
Actor: user,
|
||||||
|
IncludePrivate: true,
|
||||||
|
OnlyPerformedBy: false,
|
||||||
|
IncludeDeleted: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
if assert.Len(t, actions, 1) {
|
||||||
|
assert.EqualValues(t, 1, actions[0].ID)
|
||||||
|
assert.EqualValues(t, user.ID, actions[0].UserID)
|
||||||
|
}
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
|
||||||
|
actions, count, err = GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedUser: user,
|
||||||
|
Actor: user,
|
||||||
|
IncludePrivate: false,
|
||||||
|
OnlyPerformedBy: false,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 0)
|
||||||
|
assert.Equal(t, int64(0), count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFeedsForRepos(t *testing.T) {
|
||||||
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||||
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||||
|
privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
|
||||||
|
pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8})
|
||||||
|
|
||||||
|
// private repo & no login
|
||||||
|
actions, count, err := GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedRepo: privRepo,
|
||||||
|
IncludePrivate: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 0)
|
||||||
|
assert.Equal(t, int64(0), count)
|
||||||
|
|
||||||
|
// public repo & no login
|
||||||
|
actions, count, err = GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedRepo: pubRepo,
|
||||||
|
IncludePrivate: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
|
||||||
|
// private repo and login
|
||||||
|
actions, count, err = GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedRepo: privRepo,
|
||||||
|
IncludePrivate: true,
|
||||||
|
Actor: user,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
|
||||||
|
// public repo & login
|
||||||
|
actions, count, err = GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedRepo: pubRepo,
|
||||||
|
IncludePrivate: true,
|
||||||
|
Actor: user,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFeeds2(t *testing.T) {
|
||||||
|
// test with an organization user
|
||||||
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||||
|
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
|
||||||
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
|
||||||
|
|
||||||
|
actions, count, err := GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedUser: org,
|
||||||
|
Actor: user,
|
||||||
|
IncludePrivate: true,
|
||||||
|
OnlyPerformedBy: false,
|
||||||
|
IncludeDeleted: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
if assert.Len(t, actions, 1) {
|
||||||
|
assert.EqualValues(t, 2, actions[0].ID)
|
||||||
|
assert.EqualValues(t, org.ID, actions[0].UserID)
|
||||||
|
}
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
|
||||||
|
actions, count, err = GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedUser: org,
|
||||||
|
Actor: user,
|
||||||
|
IncludePrivate: false,
|
||||||
|
OnlyPerformedBy: false,
|
||||||
|
IncludeDeleted: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 0)
|
||||||
|
assert.Equal(t, int64(0), count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestGetFeedsCorrupted(t *testing.T) {
|
||||||
|
// Now we will not check for corrupted data in the feeds
|
||||||
|
// users should run doctor to fix their data
|
||||||
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||||
|
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
|
||||||
|
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
|
||||||
|
ID: 8,
|
||||||
|
RepoID: 1700,
|
||||||
|
})
|
||||||
|
|
||||||
|
actions, count, err := GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedUser: user,
|
||||||
|
Actor: user,
|
||||||
|
IncludePrivate: true,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
assert.Equal(t, int64(1), count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRepoActions(t *testing.T) {
|
||||||
|
assert.NoError(t, unittest.PrepareTestDatabase())
|
||||||
|
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
|
||||||
|
_ = db.TruncateBeans(db.DefaultContext, &activities_model.Action{})
|
||||||
|
for i := 0; i < 3; i++ {
|
||||||
|
_ = db.Insert(db.DefaultContext, &activities_model.Action{
|
||||||
|
UserID: 2 + int64(i),
|
||||||
|
ActUserID: 2,
|
||||||
|
RepoID: repo.ID,
|
||||||
|
OpType: activities_model.ActionCommentIssue,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
count, _ := db.Count[activities_model.Action](db.DefaultContext, &db.ListOptions{})
|
||||||
|
assert.EqualValues(t, 3, count)
|
||||||
|
actions, _, err := GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
|
||||||
|
RequestedRepo: repo,
|
||||||
|
})
|
||||||
|
assert.NoError(t, err)
|
||||||
|
assert.Len(t, actions, 1)
|
||||||
|
}
|
@ -29,9 +29,8 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/timeutil"
|
"code.gitea.io/gitea/modules/timeutil"
|
||||||
"code.gitea.io/gitea/modules/translation"
|
"code.gitea.io/gitea/modules/translation"
|
||||||
incoming_payload "code.gitea.io/gitea/services/mailer/incoming/payload"
|
incoming_payload "code.gitea.io/gitea/services/mailer/incoming/payload"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
"code.gitea.io/gitea/services/mailer/token"
|
"code.gitea.io/gitea/services/mailer/token"
|
||||||
|
|
||||||
"gopkg.in/gomail.v2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -60,7 +59,7 @@ func SendTestMail(email string) error {
|
|||||||
// No mail service configured
|
// No mail service configured
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return gomail.Send(Sender, NewMessage(email, "Gitea Test Email!", "Gitea Test Email!").ToMessage())
|
return sender_service.Send(sender, sender_service.NewMessage(email, "Gitea Test Email!", "Gitea Test Email!"))
|
||||||
}
|
}
|
||||||
|
|
||||||
// sendUserMail sends a mail to the user
|
// sendUserMail sends a mail to the user
|
||||||
@ -82,7 +81,7 @@ func sendUserMail(language string, u *user_model.User, tpl base.TplName, code, s
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := NewMessage(u.EmailTo(), subject, content.String())
|
msg := sender_service.NewMessage(u.EmailTo(), subject, content.String())
|
||||||
msg.Info = fmt.Sprintf("UID: %d, %s", u.ID, info)
|
msg.Info = fmt.Sprintf("UID: %d, %s", u.ID, info)
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
@ -130,7 +129,7 @@ func SendActivateEmailMail(u *user_model.User, email string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := NewMessage(email, locale.TrString("mail.activate_email"), content.String())
|
msg := sender_service.NewMessage(email, locale.TrString("mail.activate_email"), content.String())
|
||||||
msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID)
|
msg.Info = fmt.Sprintf("UID: %d, activate email", u.ID)
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
@ -158,7 +157,7 @@ func SendRegisterNotifyMail(u *user_model.User) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := NewMessage(u.EmailTo(), locale.TrString("mail.register_notify", setting.AppName), content.String())
|
msg := sender_service.NewMessage(u.EmailTo(), locale.TrString("mail.register_notify", setting.AppName), content.String())
|
||||||
msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID)
|
msg.Info = fmt.Sprintf("UID: %d, registration notify", u.ID)
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
@ -189,13 +188,13 @@ func SendCollaboratorMail(u, doer *user_model.User, repo *repo_model.Repository)
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := NewMessage(u.EmailTo(), subject, content.String())
|
msg := sender_service.NewMessage(u.EmailTo(), subject, content.String())
|
||||||
msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID)
|
msg.Info = fmt.Sprintf("UID: %d, add collaborator", u.ID)
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
}
|
}
|
||||||
|
|
||||||
func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipients []*user_model.User, fromMention bool, info string) ([]*Message, error) {
|
func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipients []*user_model.User, fromMention bool, info string) ([]*sender_service.Message, error) {
|
||||||
var (
|
var (
|
||||||
subject string
|
subject string
|
||||||
link string
|
link string
|
||||||
@ -304,9 +303,9 @@ func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipient
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
msgs := make([]*Message, 0, len(recipients))
|
msgs := make([]*sender_service.Message, 0, len(recipients))
|
||||||
for _, recipient := range recipients {
|
for _, recipient := range recipients {
|
||||||
msg := NewMessageFrom(
|
msg := sender_service.NewMessageFrom(
|
||||||
recipient.Email,
|
recipient.Email,
|
||||||
fromDisplayName(ctx.Doer),
|
fromDisplayName(ctx.Doer),
|
||||||
setting.MailService.FromEmail,
|
setting.MailService.FromEmail,
|
||||||
|
@ -15,6 +15,7 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/markup/markdown"
|
"code.gitea.io/gitea/modules/markup/markdown"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/modules/translation"
|
"code.gitea.io/gitea/modules/translation"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -80,11 +81,11 @@ func mailNewRelease(ctx context.Context, lang string, tos []*user_model.User, re
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
msgs := make([]*Message, 0, len(tos))
|
msgs := make([]*sender_service.Message, 0, len(tos))
|
||||||
publisherName := fromDisplayName(rel.Publisher)
|
publisherName := fromDisplayName(rel.Publisher)
|
||||||
msgID := generateMessageIDForRelease(rel)
|
msgID := generateMessageIDForRelease(rel)
|
||||||
for _, to := range tos {
|
for _, to := range tos {
|
||||||
msg := NewMessageFrom(to.EmailTo(), publisherName, setting.MailService.FromEmail, subject, mailBody.String())
|
msg := sender_service.NewMessageFrom(to.EmailTo(), publisherName, setting.MailService.FromEmail, subject, mailBody.String())
|
||||||
msg.Info = subject
|
msg.Info = subject
|
||||||
msg.SetHeader("Message-ID", msgID)
|
msg.SetHeader("Message-ID", msgID)
|
||||||
msgs = append(msgs, msg)
|
msgs = append(msgs, msg)
|
||||||
|
@ -13,6 +13,7 @@ import (
|
|||||||
user_model "code.gitea.io/gitea/models/user"
|
user_model "code.gitea.io/gitea/models/user"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/modules/translation"
|
"code.gitea.io/gitea/modules/translation"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SendRepoTransferNotifyMail triggers a notification e-mail when a pending repository transfer was created
|
// SendRepoTransferNotifyMail triggers a notification e-mail when a pending repository transfer was created
|
||||||
@ -79,7 +80,7 @@ func sendRepoTransferNotifyMailPerLang(lang string, newOwner, doer *user_model.U
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, to := range emailTos {
|
for _, to := range emailTos {
|
||||||
msg := NewMessageFrom(to.EmailTo(), fromDisplayName(doer), setting.MailService.FromEmail, subject, content.String())
|
msg := sender_service.NewMessageFrom(to.EmailTo(), fromDisplayName(doer), setting.MailService.FromEmail, subject, content.String())
|
||||||
msg.Info = fmt.Sprintf("UID: %d, repository pending transfer notification", newOwner.ID)
|
msg.Info = fmt.Sprintf("UID: %d, repository pending transfer notification", newOwner.ID)
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
|
@ -15,6 +15,7 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/log"
|
"code.gitea.io/gitea/modules/log"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/modules/translation"
|
"code.gitea.io/gitea/modules/translation"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@ -67,7 +68,7 @@ func MailTeamInvite(ctx context.Context, inviter *user_model.User, team *org_mod
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := NewMessage(invite.Email, subject, mailBody.String())
|
msg := sender_service.NewMessage(invite.Email, subject, mailBody.String())
|
||||||
msg.Info = subject
|
msg.Info = subject
|
||||||
|
|
||||||
SendAsync(msg)
|
SendAsync(msg)
|
||||||
|
@ -23,6 +23,7 @@ import (
|
|||||||
user_model "code.gitea.io/gitea/models/user"
|
user_model "code.gitea.io/gitea/models/user"
|
||||||
"code.gitea.io/gitea/modules/markup"
|
"code.gitea.io/gitea/modules/markup"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
)
|
)
|
||||||
@ -167,7 +168,7 @@ func TestTemplateSelection(t *testing.T) {
|
|||||||
template.Must(bodyTemplates.New("pull/comment").Parse("pull/comment/body"))
|
template.Must(bodyTemplates.New("pull/comment").Parse("pull/comment/body"))
|
||||||
template.Must(bodyTemplates.New("issue/close").Parse("issue/close/body"))
|
template.Must(bodyTemplates.New("issue/close").Parse("issue/close/body"))
|
||||||
|
|
||||||
expect := func(t *testing.T, msg *Message, expSubject, expBody string) {
|
expect := func(t *testing.T, msg *sender_service.Message, expSubject, expBody string) {
|
||||||
subject := msg.ToMessage().GetHeader("Subject")
|
subject := msg.ToMessage().GetHeader("Subject")
|
||||||
msgbuf := new(bytes.Buffer)
|
msgbuf := new(bytes.Buffer)
|
||||||
_, _ = msg.ToMessage().WriteTo(msgbuf)
|
_, _ = msg.ToMessage().WriteTo(msgbuf)
|
||||||
@ -252,7 +253,7 @@ func TestTemplateServices(t *testing.T) {
|
|||||||
"//Re: //")
|
"//Re: //")
|
||||||
}
|
}
|
||||||
|
|
||||||
func testComposeIssueCommentMessage(t *testing.T, ctx *mailCommentContext, recipients []*user_model.User, fromMention bool, info string) *Message {
|
func testComposeIssueCommentMessage(t *testing.T, ctx *mailCommentContext, recipients []*user_model.User, fromMention bool, info string) *sender_service.Message {
|
||||||
msgs, err := composeIssueCommentMessages(ctx, "en-US", recipients, fromMention, info)
|
msgs, err := composeIssueCommentMessages(ctx, "en-US", recipients, fromMention, info)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
assert.Len(t, msgs, 1)
|
assert.Len(t, msgs, 1)
|
||||||
|
@ -5,391 +5,21 @@
|
|||||||
package mailer
|
package mailer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
|
||||||
"fmt"
|
|
||||||
"hash/fnv"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"net/smtp"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"strings"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"code.gitea.io/gitea/modules/base"
|
|
||||||
"code.gitea.io/gitea/modules/graceful"
|
"code.gitea.io/gitea/modules/graceful"
|
||||||
"code.gitea.io/gitea/modules/log"
|
"code.gitea.io/gitea/modules/log"
|
||||||
"code.gitea.io/gitea/modules/process"
|
|
||||||
"code.gitea.io/gitea/modules/queue"
|
"code.gitea.io/gitea/modules/queue"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/modules/templates"
|
"code.gitea.io/gitea/modules/templates"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
notify_service "code.gitea.io/gitea/services/notify"
|
notify_service "code.gitea.io/gitea/services/notify"
|
||||||
|
|
||||||
ntlmssp "github.com/Azure/go-ntlmssp"
|
|
||||||
"github.com/jaytaylor/html2text"
|
|
||||||
"gopkg.in/gomail.v2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Message mail body and log info
|
var mailQueue *queue.WorkerPoolQueue[*sender_service.Message]
|
||||||
type Message struct {
|
|
||||||
Info string // Message information for log purpose.
|
|
||||||
FromAddress string
|
|
||||||
FromDisplayName string
|
|
||||||
To string // Use only one recipient to prevent leaking of addresses
|
|
||||||
ReplyTo string
|
|
||||||
Subject string
|
|
||||||
Date time.Time
|
|
||||||
Body string
|
|
||||||
Headers map[string][]string
|
|
||||||
}
|
|
||||||
|
|
||||||
// ToMessage converts a Message to gomail.Message
|
// sender sender for sending mail synchronously
|
||||||
func (m *Message) ToMessage() *gomail.Message {
|
var sender sender_service.Sender
|
||||||
msg := gomail.NewMessage()
|
|
||||||
msg.SetAddressHeader("From", m.FromAddress, m.FromDisplayName)
|
|
||||||
msg.SetHeader("To", m.To)
|
|
||||||
if m.ReplyTo != "" {
|
|
||||||
msg.SetHeader("Reply-To", m.ReplyTo)
|
|
||||||
}
|
|
||||||
for header := range m.Headers {
|
|
||||||
msg.SetHeader(header, m.Headers[header]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
if setting.MailService.SubjectPrefix != "" {
|
|
||||||
msg.SetHeader("Subject", setting.MailService.SubjectPrefix+" "+m.Subject)
|
|
||||||
} else {
|
|
||||||
msg.SetHeader("Subject", m.Subject)
|
|
||||||
}
|
|
||||||
msg.SetDateHeader("Date", m.Date)
|
|
||||||
msg.SetHeader("X-Auto-Response-Suppress", "All")
|
|
||||||
|
|
||||||
plainBody, err := html2text.FromString(m.Body)
|
|
||||||
if err != nil || setting.MailService.SendAsPlainText {
|
|
||||||
if strings.Contains(base.TruncateString(m.Body, 100), "<html>") {
|
|
||||||
log.Warn("Mail contains HTML but configured to send as plain text.")
|
|
||||||
}
|
|
||||||
msg.SetBody("text/plain", plainBody)
|
|
||||||
} else {
|
|
||||||
msg.SetBody("text/plain", plainBody)
|
|
||||||
msg.AddAlternative("text/html", m.Body)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(msg.GetHeader("Message-ID")) == 0 {
|
|
||||||
msg.SetHeader("Message-ID", m.generateAutoMessageID())
|
|
||||||
}
|
|
||||||
|
|
||||||
for k, v := range setting.MailService.OverrideHeader {
|
|
||||||
if len(msg.GetHeader(k)) != 0 {
|
|
||||||
log.Debug("Mailer override header '%s' as per config", k)
|
|
||||||
}
|
|
||||||
msg.SetHeader(k, v...)
|
|
||||||
}
|
|
||||||
|
|
||||||
return msg
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetHeader adds additional headers to a message
|
|
||||||
func (m *Message) SetHeader(field string, value ...string) {
|
|
||||||
m.Headers[field] = value
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Message) generateAutoMessageID() string {
|
|
||||||
dateMs := m.Date.UnixNano() / 1e6
|
|
||||||
h := fnv.New64()
|
|
||||||
if len(m.To) > 0 {
|
|
||||||
_, _ = h.Write([]byte(m.To))
|
|
||||||
}
|
|
||||||
_, _ = h.Write([]byte(m.Subject))
|
|
||||||
_, _ = h.Write([]byte(m.Body))
|
|
||||||
return fmt.Sprintf("<autogen-%d-%016x@%s>", dateMs, h.Sum64(), setting.Domain)
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMessageFrom creates new mail message object with custom From header.
|
|
||||||
func NewMessageFrom(to, fromDisplayName, fromAddress, subject, body string) *Message {
|
|
||||||
log.Trace("NewMessageFrom (body):\n%s", body)
|
|
||||||
|
|
||||||
return &Message{
|
|
||||||
FromAddress: fromAddress,
|
|
||||||
FromDisplayName: fromDisplayName,
|
|
||||||
To: to,
|
|
||||||
Subject: subject,
|
|
||||||
Date: time.Now(),
|
|
||||||
Body: body,
|
|
||||||
Headers: map[string][]string{},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMessage creates new mail message object with default From header.
|
|
||||||
func NewMessage(to, subject, body string) *Message {
|
|
||||||
return NewMessageFrom(to, setting.MailService.FromName, setting.MailService.FromEmail, subject, body)
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginAuth struct {
|
|
||||||
username, password string
|
|
||||||
}
|
|
||||||
|
|
||||||
// LoginAuth SMTP AUTH LOGIN Auth Handler
|
|
||||||
func LoginAuth(username, password string) smtp.Auth {
|
|
||||||
return &loginAuth{username, password}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start start SMTP login auth
|
|
||||||
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
|
||||||
return "LOGIN", []byte{}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next next step of SMTP login auth
|
|
||||||
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
|
||||||
if more {
|
|
||||||
switch string(fromServer) {
|
|
||||||
case "Username:":
|
|
||||||
return []byte(a.username), nil
|
|
||||||
case "Password:":
|
|
||||||
return []byte(a.password), nil
|
|
||||||
default:
|
|
||||||
return nil, fmt.Errorf("unknown fromServer: %s", string(fromServer))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ntlmAuth struct {
|
|
||||||
username, password, domain string
|
|
||||||
domainNeeded bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NtlmAuth SMTP AUTH NTLM Auth Handler
|
|
||||||
func NtlmAuth(username, password string) smtp.Auth {
|
|
||||||
user, domain, domainNeeded := ntlmssp.GetDomain(username)
|
|
||||||
return &ntlmAuth{user, password, domain, domainNeeded}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Start starts SMTP NTLM Auth
|
|
||||||
func (a *ntlmAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
|
||||||
negotiateMessage, err := ntlmssp.NewNegotiateMessage(a.domain, "")
|
|
||||||
return "NTLM", negotiateMessage, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Next next step of SMTP ntlm auth
|
|
||||||
func (a *ntlmAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
|
||||||
if more {
|
|
||||||
if len(fromServer) == 0 {
|
|
||||||
return nil, fmt.Errorf("ntlm ChallengeMessage is empty")
|
|
||||||
}
|
|
||||||
authenticateMessage, err := ntlmssp.ProcessChallenge(fromServer, a.username, a.password, a.domainNeeded)
|
|
||||||
return authenticateMessage, err
|
|
||||||
}
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sender SMTP mail sender
|
|
||||||
type smtpSender struct{}
|
|
||||||
|
|
||||||
// Send send email
|
|
||||||
func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
|
|
||||||
opts := setting.MailService
|
|
||||||
|
|
||||||
var network string
|
|
||||||
var address string
|
|
||||||
if opts.Protocol == "smtp+unix" {
|
|
||||||
network = "unix"
|
|
||||||
address = opts.SMTPAddr
|
|
||||||
} else {
|
|
||||||
network = "tcp"
|
|
||||||
address = net.JoinHostPort(opts.SMTPAddr, opts.SMTPPort)
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := net.Dial(network, address)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to establish network connection to SMTP server: %w", err)
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
|
|
||||||
var tlsconfig *tls.Config
|
|
||||||
if opts.Protocol == "smtps" || opts.Protocol == "smtp+starttls" {
|
|
||||||
tlsconfig = &tls.Config{
|
|
||||||
InsecureSkipVerify: opts.ForceTrustServerCert,
|
|
||||||
ServerName: opts.SMTPAddr,
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.UseClientCert {
|
|
||||||
cert, err := tls.LoadX509KeyPair(opts.ClientCertFile, opts.ClientKeyFile)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not load SMTP client certificate: %w", err)
|
|
||||||
}
|
|
||||||
tlsconfig.Certificates = []tls.Certificate{cert}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.Protocol == "smtps" {
|
|
||||||
conn = tls.Client(conn, tlsconfig)
|
|
||||||
}
|
|
||||||
|
|
||||||
host := "localhost"
|
|
||||||
if opts.Protocol == "smtp+unix" {
|
|
||||||
host = opts.SMTPAddr
|
|
||||||
}
|
|
||||||
client, err := smtp.NewClient(conn, host)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not initiate SMTP session: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.EnableHelo {
|
|
||||||
hostname := opts.HeloHostname
|
|
||||||
if len(hostname) == 0 {
|
|
||||||
hostname, err = os.Hostname()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not retrieve system hostname: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err = client.Hello(hostname); err != nil {
|
|
||||||
return fmt.Errorf("failed to issue HELO command: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.Protocol == "smtp+starttls" {
|
|
||||||
hasStartTLS, _ := client.Extension("STARTTLS")
|
|
||||||
if hasStartTLS {
|
|
||||||
if err = client.StartTLS(tlsconfig); err != nil {
|
|
||||||
return fmt.Errorf("failed to start TLS connection: %w", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
log.Warn("StartTLS requested, but SMTP server does not support it; falling back to regular SMTP")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
canAuth, options := client.Extension("AUTH")
|
|
||||||
if len(opts.User) > 0 {
|
|
||||||
if !canAuth {
|
|
||||||
return fmt.Errorf("SMTP server does not support AUTH, but credentials provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
var auth smtp.Auth
|
|
||||||
|
|
||||||
if strings.Contains(options, "CRAM-MD5") {
|
|
||||||
auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
|
|
||||||
} else if strings.Contains(options, "PLAIN") {
|
|
||||||
auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
|
|
||||||
} else if strings.Contains(options, "LOGIN") {
|
|
||||||
// Patch for AUTH LOGIN
|
|
||||||
auth = LoginAuth(opts.User, opts.Passwd)
|
|
||||||
} else if strings.Contains(options, "NTLM") {
|
|
||||||
auth = NtlmAuth(opts.User, opts.Passwd)
|
|
||||||
}
|
|
||||||
|
|
||||||
if auth != nil {
|
|
||||||
if err = client.Auth(auth); err != nil {
|
|
||||||
return fmt.Errorf("failed to authenticate SMTP: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if opts.OverrideEnvelopeFrom {
|
|
||||||
if err = client.Mail(opts.EnvelopeFrom); err != nil {
|
|
||||||
return fmt.Errorf("failed to issue MAIL command: %w", err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if err = client.Mail(from); err != nil {
|
|
||||||
return fmt.Errorf("failed to issue MAIL command: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, rec := range to {
|
|
||||||
if err = client.Rcpt(rec); err != nil {
|
|
||||||
return fmt.Errorf("failed to issue RCPT command: %w", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
w, err := client.Data()
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to issue DATA command: %w", err)
|
|
||||||
} else if _, err = msg.WriteTo(w); err != nil {
|
|
||||||
return fmt.Errorf("SMTP write failed: %w", err)
|
|
||||||
} else if err = w.Close(); err != nil {
|
|
||||||
return fmt.Errorf("SMTP close failed: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
return client.Quit()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sender sendmail mail sender
|
|
||||||
type sendmailSender struct{}
|
|
||||||
|
|
||||||
// Send send email
|
|
||||||
func (s *sendmailSender) Send(from string, to []string, msg io.WriterTo) error {
|
|
||||||
var err error
|
|
||||||
var closeError error
|
|
||||||
var waitError error
|
|
||||||
|
|
||||||
envelopeFrom := from
|
|
||||||
if setting.MailService.OverrideEnvelopeFrom {
|
|
||||||
envelopeFrom = setting.MailService.EnvelopeFrom
|
|
||||||
}
|
|
||||||
|
|
||||||
args := []string{"-f", envelopeFrom, "-i"}
|
|
||||||
args = append(args, setting.MailService.SendmailArgs...)
|
|
||||||
args = append(args, to...)
|
|
||||||
log.Trace("Sending with: %s %v", setting.MailService.SendmailPath, args)
|
|
||||||
|
|
||||||
desc := fmt.Sprintf("SendMail: %s %v", setting.MailService.SendmailPath, args)
|
|
||||||
|
|
||||||
ctx, _, finished := process.GetManager().AddContextTimeout(graceful.GetManager().HammerContext(), setting.MailService.SendmailTimeout, desc)
|
|
||||||
defer finished()
|
|
||||||
|
|
||||||
cmd := exec.CommandContext(ctx, setting.MailService.SendmailPath, args...)
|
|
||||||
pipe, err := cmd.StdinPipe()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
process.SetSysProcAttribute(cmd)
|
|
||||||
|
|
||||||
if err = cmd.Start(); err != nil {
|
|
||||||
_ = pipe.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if setting.MailService.SendmailConvertCRLF {
|
|
||||||
buf := &strings.Builder{}
|
|
||||||
_, err = msg.WriteTo(buf)
|
|
||||||
if err == nil {
|
|
||||||
_, err = strings.NewReplacer("\r\n", "\n").WriteString(pipe, buf.String())
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
_, err = msg.WriteTo(pipe)
|
|
||||||
}
|
|
||||||
|
|
||||||
// we MUST close the pipe or sendmail will hang waiting for more of the message
|
|
||||||
// Also we should wait on our sendmail command even if something fails
|
|
||||||
closeError = pipe.Close()
|
|
||||||
waitError = cmd.Wait()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
} else if closeError != nil {
|
|
||||||
return closeError
|
|
||||||
}
|
|
||||||
return waitError
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sender sendmail mail sender
|
|
||||||
type dummySender struct{}
|
|
||||||
|
|
||||||
// Send send email
|
|
||||||
func (s *dummySender) Send(from string, to []string, msg io.WriterTo) error {
|
|
||||||
buf := bytes.Buffer{}
|
|
||||||
if _, err := msg.WriteTo(&buf); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Debug("Mail From: %s To: %v Body: %s", from, to, buf.String())
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
var mailQueue *queue.WorkerPoolQueue[*Message]
|
|
||||||
|
|
||||||
// Sender sender for sending mail synchronously
|
|
||||||
var Sender gomail.Sender
|
|
||||||
|
|
||||||
// NewContext start mail queue service
|
// NewContext start mail queue service
|
||||||
func NewContext(ctx context.Context) {
|
func NewContext(ctx context.Context) {
|
||||||
@ -406,20 +36,20 @@ func NewContext(ctx context.Context) {
|
|||||||
|
|
||||||
switch setting.MailService.Protocol {
|
switch setting.MailService.Protocol {
|
||||||
case "sendmail":
|
case "sendmail":
|
||||||
Sender = &sendmailSender{}
|
sender = &sender_service.SendmailSender{}
|
||||||
case "dummy":
|
case "dummy":
|
||||||
Sender = &dummySender{}
|
sender = &sender_service.DummySender{}
|
||||||
default:
|
default:
|
||||||
Sender = &smtpSender{}
|
sender = &sender_service.SMTPSender{}
|
||||||
}
|
}
|
||||||
|
|
||||||
subjectTemplates, bodyTemplates = templates.Mailer(ctx)
|
subjectTemplates, bodyTemplates = templates.Mailer(ctx)
|
||||||
|
|
||||||
mailQueue = queue.CreateSimpleQueue(graceful.GetManager().ShutdownContext(), "mail", func(items ...*Message) []*Message {
|
mailQueue = queue.CreateSimpleQueue(graceful.GetManager().ShutdownContext(), "mail", func(items ...*sender_service.Message) []*sender_service.Message {
|
||||||
for _, msg := range items {
|
for _, msg := range items {
|
||||||
gomailMsg := msg.ToMessage()
|
gomailMsg := msg.ToMessage()
|
||||||
log.Trace("New e-mail sending request %s: %s", gomailMsg.GetHeader("To"), msg.Info)
|
log.Trace("New e-mail sending request %s: %s", gomailMsg.GetHeader("To"), msg.Info)
|
||||||
if err := gomail.Send(Sender, gomailMsg); err != nil {
|
if err := sender_service.Send(sender, msg); err != nil {
|
||||||
log.Error("Failed to send emails %s: %s - %v", gomailMsg.GetHeader("To"), msg.Info, err)
|
log.Error("Failed to send emails %s: %s - %v", gomailMsg.GetHeader("To"), msg.Info, err)
|
||||||
} else {
|
} else {
|
||||||
log.Trace("E-mails sent %s: %s", gomailMsg.GetHeader("To"), msg.Info)
|
log.Trace("E-mails sent %s: %s", gomailMsg.GetHeader("To"), msg.Info)
|
||||||
@ -436,7 +66,7 @@ func NewContext(ctx context.Context) {
|
|||||||
// SendAsync send emails asynchronously (make it mockable)
|
// SendAsync send emails asynchronously (make it mockable)
|
||||||
var SendAsync = sendAsync
|
var SendAsync = sendAsync
|
||||||
|
|
||||||
func sendAsync(msgs ...*Message) {
|
func sendAsync(msgs ...*sender_service.Message) {
|
||||||
if setting.MailService == nil {
|
if setting.MailService == nil {
|
||||||
log.Error("Mailer: SendAsync is being invoked but mail service hasn't been initialized")
|
log.Error("Mailer: SendAsync is being invoked but mail service hasn't been initialized")
|
||||||
return
|
return
|
||||||
|
26
services/mailer/sender/dummy.go
Normal file
26
services/mailer/sender/dummy.go
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"io"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/log"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DummySender Sender sendmail mail sender
|
||||||
|
type DummySender struct{}
|
||||||
|
|
||||||
|
var _ Sender = &DummySender{}
|
||||||
|
|
||||||
|
// Send send email
|
||||||
|
func (s *DummySender) Send(from string, to []string, msg io.WriterTo) error {
|
||||||
|
buf := bytes.Buffer{}
|
||||||
|
if _, err := msg.WriteTo(&buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
log.Debug("Mail From: %s To: %v Body: %s", from, to, buf.String())
|
||||||
|
return nil
|
||||||
|
}
|
112
services/mailer/sender/message.go
Normal file
112
services/mailer/sender/message.go
Normal file
@ -0,0 +1,112 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"hash/fnv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/base"
|
||||||
|
"code.gitea.io/gitea/modules/log"
|
||||||
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
|
||||||
|
"github.com/jaytaylor/html2text"
|
||||||
|
"gopkg.in/gomail.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Message mail body and log info
|
||||||
|
type Message struct {
|
||||||
|
Info string // Message information for log purpose.
|
||||||
|
FromAddress string
|
||||||
|
FromDisplayName string
|
||||||
|
To string // Use only one recipient to prevent leaking of addresses
|
||||||
|
ReplyTo string
|
||||||
|
Subject string
|
||||||
|
Date time.Time
|
||||||
|
Body string
|
||||||
|
Headers map[string][]string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToMessage converts a Message to gomail.Message
|
||||||
|
func (m *Message) ToMessage() *gomail.Message {
|
||||||
|
msg := gomail.NewMessage()
|
||||||
|
msg.SetAddressHeader("From", m.FromAddress, m.FromDisplayName)
|
||||||
|
msg.SetHeader("To", m.To)
|
||||||
|
if m.ReplyTo != "" {
|
||||||
|
msg.SetHeader("Reply-To", m.ReplyTo)
|
||||||
|
}
|
||||||
|
for header := range m.Headers {
|
||||||
|
msg.SetHeader(header, m.Headers[header]...)
|
||||||
|
}
|
||||||
|
|
||||||
|
if setting.MailService.SubjectPrefix != "" {
|
||||||
|
msg.SetHeader("Subject", setting.MailService.SubjectPrefix+" "+m.Subject)
|
||||||
|
} else {
|
||||||
|
msg.SetHeader("Subject", m.Subject)
|
||||||
|
}
|
||||||
|
msg.SetDateHeader("Date", m.Date)
|
||||||
|
msg.SetHeader("X-Auto-Response-Suppress", "All")
|
||||||
|
|
||||||
|
plainBody, err := html2text.FromString(m.Body)
|
||||||
|
if err != nil || setting.MailService.SendAsPlainText {
|
||||||
|
if strings.Contains(base.TruncateString(m.Body, 100), "<html>") {
|
||||||
|
log.Warn("Mail contains HTML but configured to send as plain text.")
|
||||||
|
}
|
||||||
|
msg.SetBody("text/plain", plainBody)
|
||||||
|
} else {
|
||||||
|
msg.SetBody("text/plain", plainBody)
|
||||||
|
msg.AddAlternative("text/html", m.Body)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(msg.GetHeader("Message-ID")) == 0 {
|
||||||
|
msg.SetHeader("Message-ID", m.generateAutoMessageID())
|
||||||
|
}
|
||||||
|
|
||||||
|
for k, v := range setting.MailService.OverrideHeader {
|
||||||
|
if len(msg.GetHeader(k)) != 0 {
|
||||||
|
log.Debug("Mailer override header '%s' as per config", k)
|
||||||
|
}
|
||||||
|
msg.SetHeader(k, v...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetHeader adds additional headers to a message
|
||||||
|
func (m *Message) SetHeader(field string, value ...string) {
|
||||||
|
m.Headers[field] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *Message) generateAutoMessageID() string {
|
||||||
|
dateMs := m.Date.UnixNano() / 1e6
|
||||||
|
h := fnv.New64()
|
||||||
|
if len(m.To) > 0 {
|
||||||
|
_, _ = h.Write([]byte(m.To))
|
||||||
|
}
|
||||||
|
_, _ = h.Write([]byte(m.Subject))
|
||||||
|
_, _ = h.Write([]byte(m.Body))
|
||||||
|
return fmt.Sprintf("<autogen-%d-%016x@%s>", dateMs, h.Sum64(), setting.Domain)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessageFrom creates new mail message object with custom From header.
|
||||||
|
func NewMessageFrom(to, fromDisplayName, fromAddress, subject, body string) *Message {
|
||||||
|
log.Trace("NewMessageFrom (body):\n%s", body)
|
||||||
|
|
||||||
|
return &Message{
|
||||||
|
FromAddress: fromAddress,
|
||||||
|
FromDisplayName: fromDisplayName,
|
||||||
|
To: to,
|
||||||
|
Subject: subject,
|
||||||
|
Date: time.Now(),
|
||||||
|
Body: body,
|
||||||
|
Headers: map[string][]string{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMessage creates new mail message object with default From header.
|
||||||
|
func NewMessage(to, subject, body string) *Message {
|
||||||
|
return NewMessageFrom(to, setting.MailService.FromName, setting.MailService.FromEmail, subject, body)
|
||||||
|
}
|
@ -1,7 +1,7 @@
|
|||||||
// Copyright 2021 The Gogs Authors. All rights reserved.
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
package mailer
|
package sender
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
27
services/mailer/sender/sender.go
Normal file
27
services/mailer/sender/sender.go
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"code.gitea.io/gitea/modules/log"
|
||||||
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
|
||||||
|
"gopkg.in/gomail.v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Sender gomail.Sender
|
||||||
|
|
||||||
|
var Send = send
|
||||||
|
|
||||||
|
func send(sender Sender, msgs ...*Message) error {
|
||||||
|
if setting.MailService == nil {
|
||||||
|
log.Error("Mailer: Send is being invoked but mail service hasn't been initialized")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
goMsgs := []*gomail.Message{}
|
||||||
|
for _, msg := range msgs {
|
||||||
|
goMsgs = append(goMsgs, msg.ToMessage())
|
||||||
|
}
|
||||||
|
return gomail.Send(sender, goMsgs...)
|
||||||
|
}
|
76
services/mailer/sender/sendmail.go
Normal file
76
services/mailer/sender/sendmail.go
Normal file
@ -0,0 +1,76 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os/exec"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/graceful"
|
||||||
|
"code.gitea.io/gitea/modules/log"
|
||||||
|
"code.gitea.io/gitea/modules/process"
|
||||||
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SendmailSender Sender sendmail mail sender
|
||||||
|
type SendmailSender struct{}
|
||||||
|
|
||||||
|
var _ Sender = &SendmailSender{}
|
||||||
|
|
||||||
|
// Send send email
|
||||||
|
func (s *SendmailSender) Send(from string, to []string, msg io.WriterTo) error {
|
||||||
|
var err error
|
||||||
|
var closeError error
|
||||||
|
var waitError error
|
||||||
|
|
||||||
|
envelopeFrom := from
|
||||||
|
if setting.MailService.OverrideEnvelopeFrom {
|
||||||
|
envelopeFrom = setting.MailService.EnvelopeFrom
|
||||||
|
}
|
||||||
|
|
||||||
|
args := []string{"-f", envelopeFrom, "-i"}
|
||||||
|
args = append(args, setting.MailService.SendmailArgs...)
|
||||||
|
args = append(args, to...)
|
||||||
|
log.Trace("Sending with: %s %v", setting.MailService.SendmailPath, args)
|
||||||
|
|
||||||
|
desc := fmt.Sprintf("SendMail: %s %v", setting.MailService.SendmailPath, args)
|
||||||
|
|
||||||
|
ctx, _, finished := process.GetManager().AddContextTimeout(graceful.GetManager().HammerContext(), setting.MailService.SendmailTimeout, desc)
|
||||||
|
defer finished()
|
||||||
|
|
||||||
|
cmd := exec.CommandContext(ctx, setting.MailService.SendmailPath, args...)
|
||||||
|
pipe, err := cmd.StdinPipe()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
process.SetSysProcAttribute(cmd)
|
||||||
|
|
||||||
|
if err = cmd.Start(); err != nil {
|
||||||
|
_ = pipe.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if setting.MailService.SendmailConvertCRLF {
|
||||||
|
buf := &strings.Builder{}
|
||||||
|
_, err = msg.WriteTo(buf)
|
||||||
|
if err == nil {
|
||||||
|
_, err = strings.NewReplacer("\r\n", "\n").WriteString(pipe, buf.String())
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
_, err = msg.WriteTo(pipe)
|
||||||
|
}
|
||||||
|
|
||||||
|
// we MUST close the pipe or sendmail will hang waiting for more of the message
|
||||||
|
// Also we should wait on our sendmail command even if something fails
|
||||||
|
closeError = pipe.Close()
|
||||||
|
waitError = cmd.Wait()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
} else if closeError != nil {
|
||||||
|
return closeError
|
||||||
|
}
|
||||||
|
return waitError
|
||||||
|
}
|
150
services/mailer/sender/smtp.go
Normal file
150
services/mailer/sender/smtp.go
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"net/smtp"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"code.gitea.io/gitea/modules/log"
|
||||||
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SMTPSender Sender SMTP mail sender
|
||||||
|
type SMTPSender struct{}
|
||||||
|
|
||||||
|
var _ Sender = &SMTPSender{}
|
||||||
|
|
||||||
|
// Send send email
|
||||||
|
func (s *SMTPSender) Send(from string, to []string, msg io.WriterTo) error {
|
||||||
|
opts := setting.MailService
|
||||||
|
|
||||||
|
var network string
|
||||||
|
var address string
|
||||||
|
if opts.Protocol == "smtp+unix" {
|
||||||
|
network = "unix"
|
||||||
|
address = opts.SMTPAddr
|
||||||
|
} else {
|
||||||
|
network = "tcp"
|
||||||
|
address = net.JoinHostPort(opts.SMTPAddr, opts.SMTPPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
conn, err := net.Dial(network, address)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to establish network connection to SMTP server: %w", err)
|
||||||
|
}
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
var tlsconfig *tls.Config
|
||||||
|
if opts.Protocol == "smtps" || opts.Protocol == "smtp+starttls" {
|
||||||
|
tlsconfig = &tls.Config{
|
||||||
|
InsecureSkipVerify: opts.ForceTrustServerCert,
|
||||||
|
ServerName: opts.SMTPAddr,
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.UseClientCert {
|
||||||
|
cert, err := tls.LoadX509KeyPair(opts.ClientCertFile, opts.ClientKeyFile)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not load SMTP client certificate: %w", err)
|
||||||
|
}
|
||||||
|
tlsconfig.Certificates = []tls.Certificate{cert}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Protocol == "smtps" {
|
||||||
|
conn = tls.Client(conn, tlsconfig)
|
||||||
|
}
|
||||||
|
|
||||||
|
host := "localhost"
|
||||||
|
if opts.Protocol == "smtp+unix" {
|
||||||
|
host = opts.SMTPAddr
|
||||||
|
}
|
||||||
|
client, err := smtp.NewClient(conn, host)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not initiate SMTP session: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.EnableHelo {
|
||||||
|
hostname := opts.HeloHostname
|
||||||
|
if len(hostname) == 0 {
|
||||||
|
hostname, err = os.Hostname()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("could not retrieve system hostname: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = client.Hello(hostname); err != nil {
|
||||||
|
return fmt.Errorf("failed to issue HELO command: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.Protocol == "smtp+starttls" {
|
||||||
|
hasStartTLS, _ := client.Extension("STARTTLS")
|
||||||
|
if hasStartTLS {
|
||||||
|
if err = client.StartTLS(tlsconfig); err != nil {
|
||||||
|
return fmt.Errorf("failed to start TLS connection: %w", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Warn("StartTLS requested, but SMTP server does not support it; falling back to regular SMTP")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
canAuth, options := client.Extension("AUTH")
|
||||||
|
if len(opts.User) > 0 {
|
||||||
|
if !canAuth {
|
||||||
|
return fmt.Errorf("SMTP server does not support AUTH, but credentials provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
var auth smtp.Auth
|
||||||
|
|
||||||
|
if strings.Contains(options, "CRAM-MD5") {
|
||||||
|
auth = smtp.CRAMMD5Auth(opts.User, opts.Passwd)
|
||||||
|
} else if strings.Contains(options, "PLAIN") {
|
||||||
|
auth = smtp.PlainAuth("", opts.User, opts.Passwd, host)
|
||||||
|
} else if strings.Contains(options, "LOGIN") {
|
||||||
|
// Patch for AUTH LOGIN
|
||||||
|
auth = LoginAuth(opts.User, opts.Passwd)
|
||||||
|
} else if strings.Contains(options, "NTLM") {
|
||||||
|
auth = NtlmAuth(opts.User, opts.Passwd)
|
||||||
|
}
|
||||||
|
|
||||||
|
if auth != nil {
|
||||||
|
if err = client.Auth(auth); err != nil {
|
||||||
|
return fmt.Errorf("failed to authenticate SMTP: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if opts.OverrideEnvelopeFrom {
|
||||||
|
if err = client.Mail(opts.EnvelopeFrom); err != nil {
|
||||||
|
return fmt.Errorf("failed to issue MAIL command: %w", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if err = client.Mail(from); err != nil {
|
||||||
|
return fmt.Errorf("failed to issue MAIL command: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, rec := range to {
|
||||||
|
if err = client.Rcpt(rec); err != nil {
|
||||||
|
return fmt.Errorf("failed to issue RCPT command: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
w, err := client.Data()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to issue DATA command: %w", err)
|
||||||
|
} else if _, err = msg.WriteTo(w); err != nil {
|
||||||
|
return fmt.Errorf("SMTP write failed: %w", err)
|
||||||
|
} else if err = w.Close(); err != nil {
|
||||||
|
return fmt.Errorf("SMTP close failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return client.Quit()
|
||||||
|
}
|
69
services/mailer/sender/smtp_auth.go
Normal file
69
services/mailer/sender/smtp_auth.go
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
// Copyright 2024 The Gitea Authors. All rights reserved.
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
package sender
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/smtp"
|
||||||
|
|
||||||
|
"github.com/Azure/go-ntlmssp"
|
||||||
|
)
|
||||||
|
|
||||||
|
type loginAuth struct {
|
||||||
|
username, password string
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoginAuth SMTP AUTH LOGIN Auth Handler
|
||||||
|
func LoginAuth(username, password string) smtp.Auth {
|
||||||
|
return &loginAuth{username, password}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start start SMTP login auth
|
||||||
|
func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||||
|
return "LOGIN", []byte{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next next step of SMTP login auth
|
||||||
|
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||||
|
if more {
|
||||||
|
switch string(fromServer) {
|
||||||
|
case "Username:":
|
||||||
|
return []byte(a.username), nil
|
||||||
|
case "Password:":
|
||||||
|
return []byte(a.password), nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown fromServer: %s", string(fromServer))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type ntlmAuth struct {
|
||||||
|
username, password, domain string
|
||||||
|
domainNeeded bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// NtlmAuth SMTP AUTH NTLM Auth Handler
|
||||||
|
func NtlmAuth(username, password string) smtp.Auth {
|
||||||
|
user, domain, domainNeeded := ntlmssp.GetDomain(username)
|
||||||
|
return &ntlmAuth{user, password, domain, domainNeeded}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start starts SMTP NTLM Auth
|
||||||
|
func (a *ntlmAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
|
||||||
|
negotiateMessage, err := ntlmssp.NewNegotiateMessage(a.domain, "")
|
||||||
|
return "NTLM", negotiateMessage, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next next step of SMTP ntlm auth
|
||||||
|
func (a *ntlmAuth) Next(fromServer []byte, more bool) ([]byte, error) {
|
||||||
|
if more {
|
||||||
|
if len(fromServer) == 0 {
|
||||||
|
return nil, fmt.Errorf("ntlm ChallengeMessage is empty")
|
||||||
|
}
|
||||||
|
authenticateMessage, err := ntlmssp.ProcessChallenge(fromServer, a.username, a.password, a.domainNeeded)
|
||||||
|
return authenticateMessage, err
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
@ -7,10 +7,12 @@
|
|||||||
</div>
|
</div>
|
||||||
</h4>
|
</h4>
|
||||||
<div class="ui attached segment">
|
<div class="ui attached segment">
|
||||||
<form class="ui form ignore-dirty" id="user-list-search-form">
|
<form class="ui form ignore-dirty flex-text-block" id="user-list-search-form">
|
||||||
|
<div class="tw-flex-1">
|
||||||
|
{{template "shared/search/combo" dict "Value" .Keyword "Placeholder" (ctx.Locale.Tr "search.user_kind")}}
|
||||||
|
</div>
|
||||||
<!-- Right Menu -->
|
<!-- Right Menu -->
|
||||||
<div class="ui right floated secondary filter menu">
|
<div class="ui secondary menu tw-m-0">
|
||||||
<!-- Status Filter Menu Item -->
|
<!-- Status Filter Menu Item -->
|
||||||
<div class="ui dropdown type jump item">
|
<div class="ui dropdown type jump item">
|
||||||
<span class="text">{{ctx.Locale.Tr "admin.users.list_status_filter.menu_text"}}</span>
|
<span class="text">{{ctx.Locale.Tr "admin.users.list_status_filter.menu_text"}}</span>
|
||||||
@ -51,8 +53,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{{template "shared/search/combo" dict "Value" .Keyword "Placeholder" (ctx.Locale.Tr "search.user_kind")}}
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
<div class="ui attached table segment">
|
<div class="ui attached table segment">
|
||||||
|
@ -1,87 +1,61 @@
|
|||||||
{{/* Attributes:
|
{{/* Attributes:
|
||||||
* root
|
|
||||||
* ContainerClasses
|
* ContainerClasses
|
||||||
* (TODO: search "branch_dropdown" in the template directory)
|
* Repository
|
||||||
|
* CurrentRefType: eg. "branch", "tag"
|
||||||
|
* CurrentRefShortName: eg. "master", "v1.0"
|
||||||
|
* CurrentTreePath
|
||||||
|
* RefLinkTemplate: redirect to the link when a branch/tag is selected
|
||||||
|
* RefFormActionTemplate: change the parent form's action when a branch/tag is selected
|
||||||
|
* DropdownFixedText: the text to show in the dropdown (mainly used by "release page"), if empty, the text will be the branch/tag name
|
||||||
|
* ShowTabBranches
|
||||||
|
* ShowTabTagsTab
|
||||||
|
* AllowCreateNewRef
|
||||||
|
* ShowViewAllRefsEntry
|
||||||
|
|
||||||
|
Search "repo/branch_dropdown" in the template directory to find all occurrences.
|
||||||
*/}}
|
*/}}
|
||||||
{{$defaultSelectedRefName := $.root.BranchName}}
|
<div class="js-branch-tag-selector {{if .ContainerClasses}}{{.ContainerClasses}}{{end}}"
|
||||||
{{if and .root.IsViewTag (not .noTag)}}
|
data-text-release-compare="{{ctx.Locale.Tr "repo.release.compare"}}"
|
||||||
{{$defaultSelectedRefName = .root.TagName}}
|
data-text-branches="{{ctx.Locale.Tr "repo.branches"}}"
|
||||||
{{end}}
|
data-text-tags="{{ctx.Locale.Tr "repo.tags"}}"
|
||||||
{{if eq $defaultSelectedRefName ""}}
|
data-text-filter-branch="{{ctx.Locale.Tr "repo.pulls.filter_branch"}}"
|
||||||
{{$defaultSelectedRefName = $.root.Repository.DefaultBranch}}
|
data-text-filter-tag="{{ctx.Locale.Tr "repo.find_tag"}}"
|
||||||
{{end}}
|
data-text-default-branch-label="{{ctx.Locale.Tr "repo.default_branch_label"}}"
|
||||||
|
data-text-create-tag="{{ctx.Locale.Tr "repo.tag.create_tag"}}"
|
||||||
|
data-text-create-branch="{{ctx.Locale.Tr "repo.branch.create_branch"}}"
|
||||||
|
data-text-create-ref-from="{{ctx.Locale.Tr "repo.branch.create_from"}}"
|
||||||
|
data-text-no-results="{{ctx.Locale.Tr "no_results_found"}}"
|
||||||
|
data-text-view-all-branches="{{ctx.Locale.Tr "repo.view_all_branches"}}"
|
||||||
|
data-text-view-all-tags="{{ctx.Locale.Tr "repo.view_all_tags"}}"
|
||||||
|
|
||||||
{{$type := ""}}
|
data-current-repo-default-branch="{{.Repository.DefaultBranch}}"
|
||||||
{{if and .root.IsViewTag (not .noTag)}}
|
data-current-repo-link="{{.Repository.Link}}"
|
||||||
{{$type = "tag"}}
|
data-current-tree-path="{{.CurrentTreePath}}"
|
||||||
{{else if .root.IsViewBranch}}
|
data-current-ref-type="{{.CurrentRefType}}"
|
||||||
{{$type = "branch"}}
|
data-current-ref-short-name="{{.CurrentRefShortName}}"
|
||||||
{{else}}
|
|
||||||
{{$type = "tree"}}
|
|
||||||
{{end}}
|
|
||||||
|
|
||||||
{{$showBranchesInDropdown := not .root.HideBranchesInDropdown}}
|
data-ref-link-template="{{.RefLinkTemplate}}"
|
||||||
|
data-ref-form-action-template="{{.RefFormActionTemplate}}"
|
||||||
|
data-dropdown-fixed-text="{{.DropdownFixedText}}"
|
||||||
|
data-show-tab-branches="{{.ShowTabBranches}}"
|
||||||
|
data-show-tab-tags="{{.ShowTabTags}}"
|
||||||
|
data-allow-create-new-ref="{{.AllowCreateNewRef}}"
|
||||||
|
data-show-view-all-refs-entry="{{.ShowViewAllRefsEntry}}"
|
||||||
|
|
||||||
<script type="module">
|
data-enable-feed="{{ctx.RootData.EnableFeed}}"
|
||||||
const data = {
|
>
|
||||||
'textReleaseCompare': {{ctx.Locale.Tr "repo.release.compare"}},
|
|
||||||
'textCreateTag': {{ctx.Locale.Tr "repo.tag.create_tag"}},
|
|
||||||
'textCreateBranch': {{ctx.Locale.Tr "repo.branch.create_branch"}},
|
|
||||||
'textCreateBranchFrom': {{ctx.Locale.Tr "repo.branch.create_from"}},
|
|
||||||
'textBranches': {{ctx.Locale.Tr "repo.branches"}},
|
|
||||||
'textTags': {{ctx.Locale.Tr "repo.tags"}},
|
|
||||||
'textDefaultBranchLabel': {{ctx.Locale.Tr "repo.default_branch_label"}},
|
|
||||||
|
|
||||||
'mode': '{{if or .root.IsViewTag .isTag}}tags{{else}}branches{{end}}',
|
|
||||||
'showBranchesInDropdown': {{$showBranchesInDropdown}},
|
|
||||||
'searchFieldPlaceholder': '{{if $.noTag}}{{ctx.Locale.Tr "repo.pulls.filter_branch"}}{{else if $showBranchesInDropdown}}{{ctx.Locale.Tr "repo.filter_branch_and_tag"}}{{else}}{{ctx.Locale.Tr "repo.find_tag"}}{{end}}...',
|
|
||||||
'branchForm': {{$.branchForm}},
|
|
||||||
'disableCreateBranch': {{if .disableCreateBranch}}{{.disableCreateBranch}}{{else}}{{not .root.CanCreateBranch}}{{end}},
|
|
||||||
'setAction': {{.setAction}},
|
|
||||||
'submitForm': {{.submitForm}},
|
|
||||||
'viewType': {{$type}},
|
|
||||||
'refName': {{if and .root.IsViewTag (not .noTag)}}{{.root.TagName}}{{else if .root.IsViewBranch}}{{.root.BranchName}}{{else}}{{ShortSha .root.CommitID}}{{end}},
|
|
||||||
'commitIdShort': {{ShortSha .root.CommitID}},
|
|
||||||
'tagName': {{.root.TagName}},
|
|
||||||
'branchName': {{.root.BranchName}},
|
|
||||||
'noTag': {{.noTag}},
|
|
||||||
'defaultSelectedRefName': {{$defaultSelectedRefName}},
|
|
||||||
'repoDefaultBranch': {{.root.Repository.DefaultBranch}},
|
|
||||||
'enableFeed': {{.root.EnableFeed}},
|
|
||||||
'rssURLPrefix': '{{$.root.RepoLink}}/rss/branch/',
|
|
||||||
'branchURLPrefix': '{{if .branchURLPrefix}}{{.branchURLPrefix}}{{else}}{{$.root.RepoLink}}/{{if $.root.PageIsCommits}}commits{{else}}src{{end}}/branch/{{end}}',
|
|
||||||
'branchURLSuffix': '{{if .branchURLSuffix}}{{.branchURLSuffix}}{{else}}{{if $.root.TreePath}}/{{PathEscapeSegments $.root.TreePath}}{{end}}{{end}}',
|
|
||||||
'tagURLPrefix': '{{if .tagURLPrefix}}{{.tagURLPrefix}}{{else if .release}}{{$.root.RepoLink}}/compare/{{else}}{{$.root.RepoLink}}/{{if $.root.PageIsCommits}}commits{{else}}src{{end}}/tag/{{end}}',
|
|
||||||
'tagURLSuffix': '{{if .tagURLSuffix}}{{.tagURLSuffix}}{{else if .release}}...{{if .release.IsDraft}}{{PathEscapeSegments .release.Target}}{{else}}{{if .release.TagName}}{{PathEscapeSegments .release.TagName}}{{else}}{{PathEscapeSegments .release.Sha1}}{{end}}{{end}}{{else}}{{if $.root.TreePath}}/{{PathEscapeSegments $.root.TreePath}}{{end}}{{end}}',
|
|
||||||
'repoLink': {{.root.RepoLink}},
|
|
||||||
'treePath': {{.root.TreePath}},
|
|
||||||
'branchNameSubURL': {{.root.BranchNameSubURL}},
|
|
||||||
'noResults': {{ctx.Locale.Tr "no_results_found"}},
|
|
||||||
};
|
|
||||||
{{if .release}}
|
|
||||||
data.release = {
|
|
||||||
'tagName': {{.release.TagName}},
|
|
||||||
};
|
|
||||||
{{end}}
|
|
||||||
window.config.pageData.branchDropdownDataList = window.config.pageData.branchDropdownDataList || [];
|
|
||||||
window.config.pageData.branchDropdownDataList.push(data);
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<div class="js-branch-tag-selector {{if .ContainerClasses}}{{.ContainerClasses}}{{end}}">
|
|
||||||
{{/* show dummy elements before Vue componment is mounted, this code must match the code in BranchTagSelector.vue */}}
|
{{/* show dummy elements before Vue componment is mounted, this code must match the code in BranchTagSelector.vue */}}
|
||||||
<div class="ui dropdown custom branch-selector-dropdown ellipsis-items-nowrap">
|
<div class="ui dropdown custom branch-selector-dropdown ellipsis-items-nowrap">
|
||||||
<div class="ui button branch-dropdown-button">
|
<div class="ui button branch-dropdown-button">
|
||||||
<span class="flex-text-block gt-ellipsis">
|
<span class="flex-text-block gt-ellipsis">
|
||||||
{{if .release}}
|
{{if not .DropdownFixedText}}
|
||||||
{{ctx.Locale.Tr "repo.release.compare"}}
|
{{if .ShowTabTags}}
|
||||||
{{else}}
|
|
||||||
{{if eq $type "tag"}}
|
|
||||||
{{svg "octicon-tag"}}
|
{{svg "octicon-tag"}}
|
||||||
{{else}}
|
{{else if .ShowTabBranches}}
|
||||||
{{svg "octicon-git-branch"}}
|
{{svg "octicon-git-branch"}}
|
||||||
{{end}}
|
{{end}}
|
||||||
<strong ref="dropdownRefName" class="tw-ml-2 tw-inline-block gt-ellipsis">{{if and .root.IsViewTag (not .noTag)}}{{.root.TagName}}{{else if .root.IsViewBranch}}{{.root.BranchName}}{{else}}{{ShortSha .root.CommitID}}{{end}}</strong>
|
|
||||||
{{end}}
|
{{end}}
|
||||||
|
<strong class="tw-ml-2 tw-inline-block gt-ellipsis">{{Iif .DropdownFixedText .SelectedRefShortName}}</strong>
|
||||||
</span>
|
</span>
|
||||||
{{svg "octicon-triangle-down" 14 "dropdown icon"}}
|
{{svg "octicon-triangle-down" 14 "dropdown icon"}}
|
||||||
</div>
|
</div>
|
||||||
|
@ -66,14 +66,15 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="content">
|
<div class="content">
|
||||||
<p id="cherry-pick-content" class="branch-dropdown"></p>
|
<p id="cherry-pick-content" class="branch-dropdown"></p>
|
||||||
{{template "repo/branch_dropdown" dict "root" .
|
|
||||||
"noTag" true "disableCreateBranch" true
|
<form method="get">
|
||||||
"branchForm" "branch-dropdown-form"
|
{{template "repo/branch_dropdown" dict
|
||||||
"branchURLPrefix" (printf "%s/_cherrypick/%s/" $.RepoLink .CommitID) "branchURLSuffix" ""
|
"Repository" .Repository
|
||||||
"setAction" true "submitForm" true}}
|
"ShowTabBranches" true
|
||||||
<form method="get" action="{{$.RepoLink}}/_cherrypick/{{.CommitID}}/{{if $.BranchName}}{{PathEscapeSegments $.BranchName}}{{else}}{{PathEscapeSegments $.Repository.DefaultBranch}}{{end}}" id="branch-dropdown-form">
|
"CurrentRefType" "branch"
|
||||||
<input type="hidden" name="ref" value="{{if $.BranchName}}{{$.BranchName}}{{else}}{{$.Repository.DefaultBranch}}{{end}}">
|
"CurrentRefShortName" (Iif $.BranchName $.Repository.DefaultBranch)
|
||||||
<input type="hidden" name="refType" value="branch">
|
"RefFormActionTemplate" (print "{RepoLink}/_cherrypick/" .CommitID "/{RefShortName}")
|
||||||
|
}}
|
||||||
<input type="hidden" id="cherry-pick-type" name="cherry-pick-type"><br>
|
<input type="hidden" id="cherry-pick-type" name="cherry-pick-type"><br>
|
||||||
<button type="submit" id="cherry-pick-submit" class="ui primary button"></button>
|
<button type="submit" id="cherry-pick-submit" class="ui primary button"></button>
|
||||||
</form>
|
</form>
|
||||||
|
@ -5,7 +5,24 @@
|
|||||||
{{template "repo/sub_menu" .}}
|
{{template "repo/sub_menu" .}}
|
||||||
<div class="repo-button-row">
|
<div class="repo-button-row">
|
||||||
<div class="repo-button-row-left">
|
<div class="repo-button-row-left">
|
||||||
{{template "repo/branch_dropdown" dict "root" .}}
|
|
||||||
|
{{$branchDropdownCurrentRefType := "branch"}}
|
||||||
|
{{$branchDropdownCurrentRefShortName := .BranchName}}
|
||||||
|
{{if .IsViewTag}}
|
||||||
|
{{$branchDropdownCurrentRefType = "tag"}}
|
||||||
|
{{$branchDropdownCurrentRefShortName = .TagName}}
|
||||||
|
{{end}}
|
||||||
|
{{template "repo/branch_dropdown" dict
|
||||||
|
"Repository" .Repository
|
||||||
|
"ShowTabBranches" true
|
||||||
|
"ShowTabTags" true
|
||||||
|
"CurrentRefType" $branchDropdownCurrentRefType
|
||||||
|
"CurrentRefShortName" $branchDropdownCurrentRefShortName
|
||||||
|
"CurrentTreePath" .TreePath
|
||||||
|
"RefLinkTemplate" "{RepoLink}/commits/{RefType}/{RefShortName}/{TreePath}"
|
||||||
|
"AllowCreateNewRef" .CanCreateBranch
|
||||||
|
}}
|
||||||
|
|
||||||
<a href="{{.RepoLink}}/graph" class="ui basic small compact button">
|
<a href="{{.RepoLink}}/graph" class="ui basic small compact button">
|
||||||
{{svg "octicon-git-branch"}}
|
{{svg "octicon-git-branch"}}
|
||||||
{{ctx.Locale.Tr "repo.commit_graph"}}
|
{{ctx.Locale.Tr "repo.commit_graph"}}
|
||||||
|
@ -47,7 +47,23 @@
|
|||||||
{{$isHomepage := (eq $n 0)}}
|
{{$isHomepage := (eq $n 0)}}
|
||||||
<div class="repo-button-row" data-is-homepage="{{$isHomepage}}">
|
<div class="repo-button-row" data-is-homepage="{{$isHomepage}}">
|
||||||
<div class="repo-button-row-left">
|
<div class="repo-button-row-left">
|
||||||
{{template "repo/branch_dropdown" dict "root" .}}
|
{{$branchDropdownCurrentRefType := "branch"}}
|
||||||
|
{{$branchDropdownCurrentRefShortName := .BranchName}}
|
||||||
|
{{if .IsViewTag}}
|
||||||
|
{{$branchDropdownCurrentRefType = "tag"}}
|
||||||
|
{{$branchDropdownCurrentRefShortName = .TagName}}
|
||||||
|
{{end}}
|
||||||
|
{{template "repo/branch_dropdown" dict
|
||||||
|
"Repository" .Repository
|
||||||
|
"ShowTabBranches" true
|
||||||
|
"ShowTabTags" true
|
||||||
|
"CurrentRefType" $branchDropdownCurrentRefType
|
||||||
|
"CurrentRefShortName" $branchDropdownCurrentRefShortName
|
||||||
|
"CurrentTreePath" .TreePath
|
||||||
|
"RefLinkTemplate" "{RepoLink}/src/{RefType}/{RefShortName}/{TreePath}"
|
||||||
|
"AllowCreateNewRef" .CanCreateBranch
|
||||||
|
"ShowViewAllRefsEntry" true
|
||||||
|
}}
|
||||||
{{if and .CanCompareOrPull .IsViewBranch (not .Repository.IsArchived)}}
|
{{if and .CanCompareOrPull .IsViewBranch (not .Repository.IsArchived)}}
|
||||||
{{$cmpBranch := ""}}
|
{{$cmpBranch := ""}}
|
||||||
{{if ne .Repository.ID .BaseRepo.ID}}
|
{{if ne .Repository.ID .BaseRepo.ID}}
|
||||||
|
@ -58,7 +58,7 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
{{if .ClosedMilestones}}
|
{{if .ClosedMilestones}}
|
||||||
<div class="divider"></div>
|
<div class="divider"></div>
|
||||||
<div class="header">{{ctx.Locale.Tr "repo.issues.filter_milestone_open"}}</div>
|
<div class="header">{{ctx.Locale.Tr "repo.issues.filter_milestone_closed"}}</div>
|
||||||
{{range .ClosedMilestones}}
|
{{range .ClosedMilestones}}
|
||||||
<div class="item issue-action" data-element-id="{{.ID}}" data-url="{{$.RepoLink}}/issues/milestone">
|
<div class="item issue-action" data-element-id="{{.ID}}" data-url="{{$.RepoLink}}/issues/milestone">
|
||||||
{{.Name}}
|
{{.Name}}
|
||||||
|
@ -5,7 +5,7 @@
|
|||||||
<div class="issue-navbar">
|
<div class="issue-navbar">
|
||||||
{{template "repo/issue/navbar" .}}
|
{{template "repo/issue/navbar" .}}
|
||||||
{{if and (or .CanWriteIssues .CanWritePulls) .PageIsEditMilestone}}
|
{{if and (or .CanWriteIssues .CanWritePulls) .PageIsEditMilestone}}
|
||||||
<div class="ui right floated secondary menu">
|
<div class="ui right">
|
||||||
<a class="ui primary button" href="{{$.RepoLink}}/milestones/new">{{ctx.Locale.Tr "repo.milestones.new"}}</a>
|
<a class="ui primary button" href="{{$.RepoLink}}/milestones/new">{{ctx.Locale.Tr "repo.milestones.new"}}</a>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
@ -22,7 +22,7 @@
|
|||||||
<div class="item clear-selection">{{ctx.Locale.Tr "repo.issues.new.clear_milestone"}}</div>
|
<div class="item clear-selection">{{ctx.Locale.Tr "repo.issues.new.clear_milestone"}}</div>
|
||||||
<div class="scrolling menu">
|
<div class="scrolling menu">
|
||||||
{{if $data.OpenMilestones}}
|
{{if $data.OpenMilestones}}
|
||||||
<div class="header">{{ctx.Locale.Tr "repo.issues.new.open_milestone"}}</div>
|
<div class="header">{{ctx.Locale.Tr "repo.issues.filter_milestone_open"}}</div>
|
||||||
{{range $data.OpenMilestones}}
|
{{range $data.OpenMilestones}}
|
||||||
<a class="item muted" data-value="{{.ID}}" href="{{$pageMeta.RepoLink}}/issues?milestone={{.ID}}">
|
<a class="item muted" data-value="{{.ID}}" href="{{$pageMeta.RepoLink}}/issues?milestone={{.ID}}">
|
||||||
{{svg "octicon-milestone" 18}} {{.Name}}
|
{{svg "octicon-milestone" 18}} {{.Name}}
|
||||||
@ -31,7 +31,7 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
{{if and $data.OpenMilestones $data.ClosedMilestones}}<div class="divider"></div>{{end}}
|
{{if and $data.OpenMilestones $data.ClosedMilestones}}<div class="divider"></div>{{end}}
|
||||||
{{if $data.ClosedMilestones}}
|
{{if $data.ClosedMilestones}}
|
||||||
<div class="header">{{ctx.Locale.Tr "repo.issues.new.closed_milestone"}}</div>
|
<div class="header">{{ctx.Locale.Tr "repo.issues.filter_milestone_closed"}}</div>
|
||||||
{{range $data.ClosedMilestones}}
|
{{range $data.ClosedMilestones}}
|
||||||
<a class="item muted" data-value="{{.ID}}" href="{{$pageMeta.RepoLink}}/issues?milestone={{.ID}}">
|
<a class="item muted" data-value="{{.ID}}" href="{{$pageMeta.RepoLink}}/issues?milestone={{.ID}}">
|
||||||
{{svg "octicon-milestone" 18}} {{.Name}}
|
{{svg "octicon-milestone" 18}} {{.Name}}
|
||||||
|
@ -12,7 +12,20 @@
|
|||||||
<a class="muted" href="{{if not (and $release.Sha1 ($.Permission.CanRead ctx.Consts.RepoUnitTypeCode))}}#{{else}}{{$.RepoLink}}/src/tag/{{$release.TagName | PathEscapeSegments}}{{end}}" rel="nofollow">{{svg "octicon-tag" 16 "tw-mr-1"}}{{$release.TagName}}</a>
|
<a class="muted" href="{{if not (and $release.Sha1 ($.Permission.CanRead ctx.Consts.RepoUnitTypeCode))}}#{{else}}{{$.RepoLink}}/src/tag/{{$release.TagName | PathEscapeSegments}}{{end}}" rel="nofollow">{{svg "octicon-tag" 16 "tw-mr-1"}}{{$release.TagName}}</a>
|
||||||
{{if and $release.Sha1 ($.Permission.CanRead ctx.Consts.RepoUnitTypeCode)}}
|
{{if and $release.Sha1 ($.Permission.CanRead ctx.Consts.RepoUnitTypeCode)}}
|
||||||
<a class="muted tw-font-mono" href="{{$.RepoLink}}/src/commit/{{$release.Sha1}}" rel="nofollow">{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha $release.Sha1}}</a>
|
<a class="muted tw-font-mono" href="{{$.RepoLink}}/src/commit/{{$release.Sha1}}" rel="nofollow">{{svg "octicon-git-commit" 16 "tw-mr-1"}}{{ShortSha $release.Sha1}}</a>
|
||||||
{{template "repo/branch_dropdown" dict "root" $ "release" $release}}
|
{{$compareTarget := ""}}
|
||||||
|
{{if $release.IsDraft}}
|
||||||
|
{{$compareTarget = $release.Target}}
|
||||||
|
{{else if $release.TagName}}
|
||||||
|
{{$compareTarget = $release.TagName}}
|
||||||
|
{{else}}
|
||||||
|
{{$compareTarget = $release.Sha1}}
|
||||||
|
{{end}}
|
||||||
|
{{template "repo/branch_dropdown" dict
|
||||||
|
"Repository" $.Repository
|
||||||
|
"ShowTabTags" true
|
||||||
|
"DropdownFixedText" (ctx.Locale.Tr "repo.release.compare")
|
||||||
|
"RefLinkTemplate" (print "{RepoLink}/compare/{RefShortName}..." (PathEscapeSegments $compareTarget))
|
||||||
|
}}
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
<div class="ui segment detail">
|
<div class="ui segment detail">
|
||||||
|
@ -56,21 +56,21 @@
|
|||||||
<button class="ui mini basic button escape-button">{{ctx.Locale.Tr "repo.escape_control_characters"}}</button>
|
<button class="ui mini basic button escape-button">{{ctx.Locale.Tr "repo.escape_control_characters"}}</button>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
<a download href="{{$.RawFileLink}}"><span class="btn-octicon" data-tooltip-content="{{ctx.Locale.Tr "repo.download_file"}}">{{svg "octicon-download"}}</span></a>
|
<a download class="btn-octicon" data-tooltip-content="{{ctx.Locale.Tr "repo.download_file"}}" href="{{$.RawFileLink}}">{{svg "octicon-download"}}</a>
|
||||||
<a id="copy-content" class="btn-octicon {{if not .CanCopyContent}} disabled{{end}}"{{if or .IsImageFile (and .HasSourceRenderedToggle (not .IsDisplayingSource))}} data-link="{{$.RawFileLink}}"{{end}} data-tooltip-content="{{if .CanCopyContent}}{{ctx.Locale.Tr "copy_content"}}{{else}}{{ctx.Locale.Tr "copy_type_unsupported"}}{{end}}">{{svg "octicon-copy" 14}}</a>
|
<a id="copy-content" class="btn-octicon {{if not .CanCopyContent}} disabled{{end}}"{{if or .IsImageFile (and .HasSourceRenderedToggle (not .IsDisplayingSource))}} data-link="{{$.RawFileLink}}"{{end}} data-tooltip-content="{{if .CanCopyContent}}{{ctx.Locale.Tr "copy_content"}}{{else}}{{ctx.Locale.Tr "copy_type_unsupported"}}{{end}}">{{svg "octicon-copy"}}</a>
|
||||||
{{if .EnableFeed}}
|
{{if .EnableFeed}}
|
||||||
<a class="btn-octicon" href="{{$.FeedURL}}/rss/{{$.BranchNameSubURL}}/{{PathEscapeSegments .TreePath}}" data-tooltip-content="{{ctx.Locale.Tr "rss_feed"}}">
|
<a class="btn-octicon" href="{{$.FeedURL}}/rss/{{$.BranchNameSubURL}}/{{PathEscapeSegments .TreePath}}" data-tooltip-content="{{ctx.Locale.Tr "rss_feed"}}">
|
||||||
{{svg "octicon-rss" 14}}
|
{{svg "octicon-rss"}}
|
||||||
</a>
|
</a>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if .Repository.CanEnableEditor}}
|
{{if .Repository.CanEnableEditor}}
|
||||||
{{if .CanEditFile}}
|
{{if .CanEditFile}}
|
||||||
<a href="{{.RepoLink}}/_edit/{{PathEscapeSegments .BranchName}}/{{PathEscapeSegments .TreePath}}"><span class="btn-octicon" data-tooltip-content="{{.EditFileTooltip}}">{{svg "octicon-pencil"}}</span></a>
|
<a class="btn-octicon" data-tooltip-content="{{.EditFileTooltip}}" href="{{.RepoLink}}/_edit/{{PathEscapeSegments .BranchName}}/{{PathEscapeSegments .TreePath}}">{{svg "octicon-pencil"}}</a>
|
||||||
{{else}}
|
{{else}}
|
||||||
<span class="btn-octicon disabled" data-tooltip-content="{{.EditFileTooltip}}">{{svg "octicon-pencil"}}</span>
|
<span class="btn-octicon disabled" data-tooltip-content="{{.EditFileTooltip}}">{{svg "octicon-pencil"}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
{{if .CanDeleteFile}}
|
{{if .CanDeleteFile}}
|
||||||
<a href="{{.RepoLink}}/_delete/{{PathEscapeSegments .BranchName}}/{{PathEscapeSegments .TreePath}}"><span class="btn-octicon btn-octicon-danger" data-tooltip-content="{{.DeleteFileTooltip}}">{{svg "octicon-trash"}}</span></a>
|
<a class="btn-octicon btn-octicon-danger" data-tooltip-content="{{.DeleteFileTooltip}}" href="{{.RepoLink}}/_delete/{{PathEscapeSegments .BranchName}}/{{PathEscapeSegments .TreePath}}">{{svg "octicon-trash"}}</a>
|
||||||
{{else}}
|
{{else}}
|
||||||
<span class="btn-octicon disabled" data-tooltip-content="{{.DeleteFileTooltip}}">{{svg "octicon-trash"}}</span>
|
<span class="btn-octicon disabled" data-tooltip-content="{{.DeleteFileTooltip}}">{{svg "octicon-trash"}}</span>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
@ -1,7 +1,3 @@
|
|||||||
{{if or .OAuth2Providers .EnableOpenIDSignIn}}
|
|
||||||
<div class="divider divider-text">
|
|
||||||
{{ctx.Locale.Tr "sign_in_or"}}
|
|
||||||
</div>
|
|
||||||
<div id="oauth2-login-navigator" class="tw-py-1">
|
<div id="oauth2-login-navigator" class="tw-py-1">
|
||||||
<div class="tw-flex tw-flex-col tw-justify-center">
|
<div class="tw-flex tw-flex-col tw-justify-center">
|
||||||
<div id="oauth2-login-navigator-inner" class="tw-flex tw-flex-col tw-flex-wrap tw-items-center tw-gap-2">
|
<div id="oauth2-login-navigator-inner" class="tw-flex tw-flex-col tw-flex-wrap tw-items-center tw-gap-2">
|
||||||
@ -26,4 +22,3 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
|
||||||
|
@ -10,6 +10,7 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
</h4>
|
</h4>
|
||||||
<div class="ui attached segment">
|
<div class="ui attached segment">
|
||||||
|
{{if .EnablePasswordSignInForm}}
|
||||||
<form class="ui form" action="{{.SignInLink}}" method="post">
|
<form class="ui form" action="{{.SignInLink}}" method="post">
|
||||||
{{.CsrfTokenHtml}}
|
{{.CsrfTokenHtml}}
|
||||||
<div class="required field {{if and (.Err_UserName) (or (not .LinkAccountMode) (and .LinkAccountMode .LinkAccountModeSignIn))}}error{{end}}">
|
<div class="required field {{if and (.Err_UserName) (or (not .LinkAccountMode) (and .LinkAccountMode .LinkAccountModeSignIn))}}error{{end}}">
|
||||||
@ -46,8 +47,13 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
{{end}}{{/*if .EnablePasswordSignInForm*/}}
|
||||||
|
{{if and .OAuth2Providers .EnableOpenIDSignIn .EnablePasswordSignInForm}}
|
||||||
|
<div class="divider divider-text">{{ctx.Locale.Tr "sign_in_or"}}</div>
|
||||||
|
{{end}}
|
||||||
|
{{if and .OAuth2Providers .EnableOpenIDSignIn}}
|
||||||
{{template "user/auth/oauth_container" .}}
|
{{template "user/auth/oauth_container" .}}
|
||||||
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
@ -48,7 +48,10 @@
|
|||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
|
||||||
|
{{if and .OAuth2Providers .EnableOpenIDSignIn}}
|
||||||
|
<div class="divider divider-text">{{ctx.Locale.Tr "sign_in_or"}}</div>
|
||||||
{{template "user/auth/oauth_container" .}}
|
{{template "user/auth/oauth_container" .}}
|
||||||
|
{{end}}
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
@ -40,7 +40,7 @@
|
|||||||
{{ctx.Locale.Tr "settings.manage_emails"}}
|
{{ctx.Locale.Tr "settings.manage_emails"}}
|
||||||
</h4>
|
</h4>
|
||||||
<div class="ui attached segment">
|
<div class="ui attached segment">
|
||||||
<div class="ui list">
|
<div class="ui list flex-items-block">
|
||||||
{{if $.EnableNotifyMail}}
|
{{if $.EnableNotifyMail}}
|
||||||
<div class="item">
|
<div class="item">
|
||||||
<div class="tw-mb-2">{{ctx.Locale.Tr "settings.email_desc"}}</div>
|
<div class="tw-mb-2">{{ctx.Locale.Tr "settings.email_desc"}}</div>
|
||||||
@ -66,39 +66,8 @@
|
|||||||
{{end}}
|
{{end}}
|
||||||
{{if not ($.UserDisabledFeatures.Contains "manage_credentials")}}
|
{{if not ($.UserDisabledFeatures.Contains "manage_credentials")}}
|
||||||
{{range .Emails}}
|
{{range .Emails}}
|
||||||
<div class="item">
|
<div class="item tw-flex-wrap">
|
||||||
{{if not .IsPrimary}}
|
<div class="content tw-flex-1">
|
||||||
<div class="right floated content">
|
|
||||||
<button class="ui red tiny button delete-button" data-modal-id="delete-email" data-url="{{AppSubUrl}}/user/settings/account/email/delete" data-id="{{.ID}}">
|
|
||||||
{{ctx.Locale.Tr "settings.delete_email"}}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{{if .CanBePrimary}}
|
|
||||||
<div class="right floated content">
|
|
||||||
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
|
|
||||||
{{$.CsrfTokenHtml}}
|
|
||||||
<input name="_method" type="hidden" value="PRIMARY">
|
|
||||||
<input name="id" type="hidden" value="{{.ID}}">
|
|
||||||
<button class="ui primary tiny button">{{ctx.Locale.Tr "settings.primary_email"}}</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
{{end}}
|
|
||||||
{{if not .IsActivated}}
|
|
||||||
<div class="right floated content">
|
|
||||||
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
|
|
||||||
{{$.CsrfTokenHtml}}
|
|
||||||
<input name="_method" type="hidden" value="SENDACTIVATION">
|
|
||||||
<input name="id" type="hidden" value="{{.ID}}">
|
|
||||||
{{if $.ActivationsPending}}
|
|
||||||
<button disabled class="ui primary tiny button">{{ctx.Locale.Tr "settings.activations_pending"}}</button>
|
|
||||||
{{else}}
|
|
||||||
<button class="ui primary tiny button">{{ctx.Locale.Tr "settings.activate_email"}}</button>
|
|
||||||
{{end}}
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
{{end}}
|
|
||||||
<div class="content tw-py-2">
|
|
||||||
<strong>{{.Email}}</strong>
|
<strong>{{.Email}}</strong>
|
||||||
{{if .IsPrimary}}
|
{{if .IsPrimary}}
|
||||||
<div class="ui primary label">{{ctx.Locale.Tr "settings.primary"}}</div>
|
<div class="ui primary label">{{ctx.Locale.Tr "settings.primary"}}</div>
|
||||||
@ -109,9 +78,36 @@
|
|||||||
<div class="ui label">{{ctx.Locale.Tr "settings.requires_activation"}}</div>
|
<div class="ui label">{{ctx.Locale.Tr "settings.requires_activation"}}</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="flex-text-block">
|
||||||
|
{{if not .IsPrimary}}
|
||||||
|
<button class="ui red tiny button delete-button" data-modal-id="delete-email" data-url="{{AppSubUrl}}/user/settings/account/email/delete" data-id="{{.ID}}">
|
||||||
|
{{ctx.Locale.Tr "settings.delete_email"}}
|
||||||
|
</button>
|
||||||
|
{{if .CanBePrimary}}
|
||||||
|
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
|
||||||
|
{{$.CsrfTokenHtml}}
|
||||||
|
<input name="_method" type="hidden" value="PRIMARY">
|
||||||
|
<input name="id" type="hidden" value="{{.ID}}">
|
||||||
|
<button class="ui primary tiny button">{{ctx.Locale.Tr "settings.primary_email"}}</button>
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
|
{{end}}
|
||||||
|
{{if not .IsActivated}}
|
||||||
|
<form action="{{AppSubUrl}}/user/settings/account/email" method="post">
|
||||||
|
{{$.CsrfTokenHtml}}
|
||||||
|
<input name="_method" type="hidden" value="SENDACTIVATION">
|
||||||
|
<input name="id" type="hidden" value="{{.ID}}">
|
||||||
|
{{if $.ActivationsPending}}
|
||||||
|
<button disabled class="ui primary tiny button">{{ctx.Locale.Tr "settings.activations_pending"}}</button>
|
||||||
|
{{else}}
|
||||||
|
<button class="ui primary tiny button">{{ctx.Locale.Tr "settings.activate_email"}}</button>
|
||||||
|
{{end}}
|
||||||
|
</form>
|
||||||
|
{{end}}
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
</div>
|
||||||
{{end}}
|
{{end}}{{/* range Emails */}}
|
||||||
|
{{end}}{{/* if manage_credentials */}}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{{end}}
|
{{end}}
|
||||||
|
@ -144,12 +144,12 @@ func TestActionsArtifactDownload(t *testing.T) {
|
|||||||
var downloadResp downloadArtifactResponse
|
var downloadResp downloadArtifactResponse
|
||||||
DecodeJSON(t, resp, &downloadResp)
|
DecodeJSON(t, resp, &downloadResp)
|
||||||
assert.Len(t, downloadResp.Value, 1)
|
assert.Len(t, downloadResp.Value, 1)
|
||||||
assert.Equal(t, "artifact-download/abc.txt", downloadResp.Value[artifactIdx].Path)
|
assert.Equal(t, "artifact-download/abc.txt", downloadResp.Value[0].Path)
|
||||||
assert.Equal(t, "file", downloadResp.Value[artifactIdx].ItemType)
|
assert.Equal(t, "file", downloadResp.Value[0].ItemType)
|
||||||
assert.Contains(t, downloadResp.Value[artifactIdx].ContentLocation, "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts")
|
assert.Contains(t, downloadResp.Value[0].ContentLocation, "/api/actions_pipeline/_apis/pipelines/workflows/791/artifacts")
|
||||||
|
|
||||||
idx = strings.Index(downloadResp.Value[artifactIdx].ContentLocation, "/api/actions_pipeline/_apis/pipelines/")
|
idx = strings.Index(downloadResp.Value[0].ContentLocation, "/api/actions_pipeline/_apis/pipelines/")
|
||||||
url = downloadResp.Value[artifactIdx].ContentLocation[idx:]
|
url = downloadResp.Value[0].ContentLocation[idx:]
|
||||||
req = NewRequest(t, "GET", url).
|
req = NewRequest(t, "GET", url).
|
||||||
AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a")
|
AddTokenAuth("8061e833a55f6fc0157c98b883e91fcfeeb1a71a")
|
||||||
resp = MakeRequest(t, req, http.StatusOK)
|
resp = MakeRequest(t, req, http.StatusOK)
|
||||||
|
@ -19,11 +19,11 @@ import (
|
|||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
"code.gitea.io/gitea/services/mailer/incoming"
|
"code.gitea.io/gitea/services/mailer/incoming"
|
||||||
incoming_payload "code.gitea.io/gitea/services/mailer/incoming/payload"
|
incoming_payload "code.gitea.io/gitea/services/mailer/incoming/payload"
|
||||||
|
sender_service "code.gitea.io/gitea/services/mailer/sender"
|
||||||
token_service "code.gitea.io/gitea/services/mailer/token"
|
token_service "code.gitea.io/gitea/services/mailer/token"
|
||||||
"code.gitea.io/gitea/tests"
|
"code.gitea.io/gitea/tests"
|
||||||
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"gopkg.in/gomail.v2"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestIncomingEmail(t *testing.T) {
|
func TestIncomingEmail(t *testing.T) {
|
||||||
@ -189,11 +189,15 @@ func TestIncomingEmail(t *testing.T) {
|
|||||||
token, err := token_service.CreateToken(token_service.ReplyHandlerType, user, payload)
|
token, err := token_service.CreateToken(token_service.ReplyHandlerType, user, payload)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
msg := gomail.NewMessage()
|
msg := sender_service.NewMessageFrom(
|
||||||
msg.SetHeader("To", strings.Replace(setting.IncomingEmail.ReplyToAddress, setting.IncomingEmail.TokenPlaceholder, token, 1))
|
strings.Replace(setting.IncomingEmail.ReplyToAddress, setting.IncomingEmail.TokenPlaceholder, token, 1),
|
||||||
msg.SetHeader("From", user.Email)
|
"",
|
||||||
msg.SetBody("text/plain", token)
|
user.Email,
|
||||||
err = gomail.Send(&smtpTestSender{}, msg)
|
"",
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
|
||||||
|
err = sender_service.Send(&smtpTestSender{}, msg)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
assert.Eventually(t, func() bool {
|
assert.Eventually(t, func() bool {
|
||||||
|
@ -12,6 +12,7 @@ import (
|
|||||||
"code.gitea.io/gitea/models/unittest"
|
"code.gitea.io/gitea/models/unittest"
|
||||||
user_model "code.gitea.io/gitea/models/user"
|
user_model "code.gitea.io/gitea/models/user"
|
||||||
"code.gitea.io/gitea/modules/setting"
|
"code.gitea.io/gitea/modules/setting"
|
||||||
|
"code.gitea.io/gitea/modules/test"
|
||||||
"code.gitea.io/gitea/modules/translation"
|
"code.gitea.io/gitea/modules/translation"
|
||||||
"code.gitea.io/gitea/tests"
|
"code.gitea.io/gitea/tests"
|
||||||
|
|
||||||
@ -91,3 +92,31 @@ func TestSigninWithRememberMe(t *testing.T) {
|
|||||||
req = NewRequest(t, "GET", "/user/settings")
|
req = NewRequest(t, "GET", "/user/settings")
|
||||||
session.MakeRequest(t, req, http.StatusOK)
|
session.MakeRequest(t, req, http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestEnablePasswordSignInForm(t *testing.T) {
|
||||||
|
defer tests.PrepareTestEnv(t)()
|
||||||
|
|
||||||
|
t.Run("EnablePasswordSignInForm=false", func(t *testing.T) {
|
||||||
|
defer tests.PrintCurrentTest(t)()
|
||||||
|
defer test.MockVariableValue(&setting.Service.EnablePasswordSignInForm, false)()
|
||||||
|
|
||||||
|
req := NewRequest(t, "GET", "/user/login")
|
||||||
|
resp := MakeRequest(t, req, http.StatusOK)
|
||||||
|
NewHTMLParser(t, resp.Body).AssertElement(t, "form[action='/user/login']", false)
|
||||||
|
|
||||||
|
req = NewRequest(t, "POST", "/user/login")
|
||||||
|
MakeRequest(t, req, http.StatusForbidden)
|
||||||
|
})
|
||||||
|
|
||||||
|
t.Run("EnablePasswordSignInForm=true", func(t *testing.T) {
|
||||||
|
defer tests.PrintCurrentTest(t)()
|
||||||
|
defer test.MockVariableValue(&setting.Service.EnablePasswordSignInForm, true)()
|
||||||
|
|
||||||
|
req := NewRequest(t, "GET", "/user/login")
|
||||||
|
resp := MakeRequest(t, req, http.StatusOK)
|
||||||
|
NewHTMLParser(t, resp.Body).AssertElement(t, "form[action='/user/login']", true)
|
||||||
|
|
||||||
|
req = NewRequest(t, "POST", "/user/login")
|
||||||
|
MakeRequest(t, req, http.StatusOK)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
@ -126,12 +126,6 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.ui.list .list > .item [class*="right floated"],
|
|
||||||
.ui.list > .item [class*="right floated"] {
|
|
||||||
float: right;
|
|
||||||
margin: 0 0 0 1em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.ui.menu .ui.list > .item,
|
.ui.menu .ui.list > .item,
|
||||||
.ui.menu .ui.list .list > .item {
|
.ui.menu .ui.list .list > .item {
|
||||||
display: list-item;
|
display: list-item;
|
||||||
|
@ -633,18 +633,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.ui.floated.menu {
|
|
||||||
float: left;
|
|
||||||
margin: 0 0.5rem 0 0;
|
|
||||||
}
|
|
||||||
.ui.floated.menu .item:last-child::before {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.ui.right.floated.menu {
|
|
||||||
float: right;
|
|
||||||
margin: 0 0 0 0.5rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.ui.borderless.menu .item::before,
|
.ui.borderless.menu .item::before,
|
||||||
.ui.borderless.menu .item .menu .item::before,
|
.ui.borderless.menu .item .menu .item::before,
|
||||||
.ui.menu .borderless.item::before {
|
.ui.menu .borderless.item::before {
|
||||||
|
@ -1,244 +1,220 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import {createApp, nextTick} from 'vue';
|
import {createApp, nextTick} from 'vue';
|
||||||
import $ from 'jquery';
|
|
||||||
import {SvgIcon} from '../svg.ts';
|
import {SvgIcon} from '../svg.ts';
|
||||||
import {pathEscapeSegments} from '../utils/url.ts';
|
|
||||||
import {showErrorToast} from '../modules/toast.ts';
|
import {showErrorToast} from '../modules/toast.ts';
|
||||||
import {GET} from '../modules/fetch.ts';
|
import {GET} from '../modules/fetch.ts';
|
||||||
|
import {pathEscapeSegments} from '../utils/url.ts';
|
||||||
|
import type {GitRefType} from '../types.ts';
|
||||||
|
|
||||||
|
type ListItem = {
|
||||||
|
selected: boolean;
|
||||||
|
refShortName: string;
|
||||||
|
refType: GitRefType;
|
||||||
|
rssFeedLink: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type SelectedTab = 'branches' | 'tags';
|
||||||
|
|
||||||
|
type TabLoadingStates = Record<SelectedTab, '' | 'loading' | 'done'>
|
||||||
|
|
||||||
|
let currentElRoot: HTMLElement;
|
||||||
|
|
||||||
const sfc = {
|
const sfc = {
|
||||||
components: {SvgIcon},
|
components: {SvgIcon},
|
||||||
|
|
||||||
// no `data()`, at the moment, the `data()` is provided by the init code, which is not ideal and should be fixed in the future
|
|
||||||
|
|
||||||
computed: {
|
computed: {
|
||||||
filteredItems() {
|
searchFieldPlaceholder() {
|
||||||
const items = this.items.filter((item) => {
|
return this.selectedTab === 'branches' ? this.textFilterBranch : this.textFilterTag;
|
||||||
return ((this.mode === 'branches' && item.branch) || (this.mode === 'tags' && item.tag)) &&
|
},
|
||||||
(!this.searchTerm || item.name.toLowerCase().includes(this.searchTerm.toLowerCase()));
|
filteredItems(): ListItem[] {
|
||||||
|
const searchTermLower = this.searchTerm.toLowerCase();
|
||||||
|
const items = this.allItems.filter((item: ListItem) => {
|
||||||
|
const typeMatched = (this.selectedTab === 'branches' && item.refType === 'branch') || (this.selectedTab === 'tags' && item.refType === 'tag');
|
||||||
|
if (!typeMatched) return false;
|
||||||
|
if (!this.searchTerm) return true; // match all
|
||||||
|
return item.refShortName.toLowerCase().includes(searchTermLower);
|
||||||
});
|
});
|
||||||
|
|
||||||
// TODO: fix this anti-pattern: side-effects-in-computed-properties
|
// TODO: fix this anti-pattern: side-effects-in-computed-properties
|
||||||
this.active = !items.length && this.showCreateNewBranch ? 0 : -1;
|
this.activeItemIndex = !items.length && this.showCreateNewRef ? 0 : -1;
|
||||||
return items;
|
return items;
|
||||||
},
|
},
|
||||||
showNoResults() {
|
showNoResults() {
|
||||||
return !this.filteredItems.length && !this.showCreateNewBranch;
|
if (this.tabLoadingStates[this.selectedTab] !== 'done') return false;
|
||||||
|
return !this.filteredItems.length && !this.showCreateNewRef;
|
||||||
},
|
},
|
||||||
showCreateNewBranch() {
|
showCreateNewRef() {
|
||||||
if (this.disableCreateBranch || !this.searchTerm) {
|
if (!this.allowCreateNewRef || !this.searchTerm) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return !this.items.filter((item) => {
|
return !this.allItems.filter((item: ListItem) => {
|
||||||
return item.name.toLowerCase() === this.searchTerm.toLowerCase();
|
return item.refShortName === this.searchTerm; // FIXME: not quite right here, it mixes "branch" and "tag" names
|
||||||
}).length;
|
}).length;
|
||||||
},
|
},
|
||||||
formActionUrl() {
|
createNewRefFormActionUrl() {
|
||||||
return `${this.repoLink}/branches/_new/${this.branchNameSubURL}`;
|
return `${this.currentRepoLink}/branches/_new/${this.currentRefType}/${pathEscapeSegments(this.currentRefShortName)}`;
|
||||||
},
|
|
||||||
shouldCreateTag() {
|
|
||||||
return this.mode === 'tags';
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
watch: {
|
watch: {
|
||||||
menuVisible(visible) {
|
menuVisible(visible) {
|
||||||
if (visible) {
|
if (!visible) return;
|
||||||
this.focusSearchField();
|
this.focusSearchField();
|
||||||
this.fetchBranchesOrTags();
|
this.loadTabItems();
|
||||||
}
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
data() {
|
||||||
|
const elRoot = currentElRoot;
|
||||||
|
const shouldShowTabBranches = elRoot.getAttribute('data-show-tab-branches') === 'true';
|
||||||
|
return {
|
||||||
|
csrfToken: window.config.csrfToken,
|
||||||
|
allItems: [] as ListItem[],
|
||||||
|
selectedTab: (shouldShowTabBranches ? 'branches' : 'tags') as SelectedTab,
|
||||||
|
searchTerm: '',
|
||||||
|
menuVisible: false,
|
||||||
|
activeItemIndex: 0,
|
||||||
|
tabLoadingStates: {} as TabLoadingStates,
|
||||||
|
|
||||||
|
textReleaseCompare: elRoot.getAttribute('data-text-release-compare'),
|
||||||
|
textBranches: elRoot.getAttribute('data-text-branches'),
|
||||||
|
textTags: elRoot.getAttribute('data-text-tags'),
|
||||||
|
textFilterBranch: elRoot.getAttribute('data-text-filter-branch'),
|
||||||
|
textFilterTag: elRoot.getAttribute('data-text-filter-tag'),
|
||||||
|
textDefaultBranchLabel: elRoot.getAttribute('data-text-default-branch-label'),
|
||||||
|
textCreateTag: elRoot.getAttribute('data-text-create-tag'),
|
||||||
|
textCreateBranch: elRoot.getAttribute('data-text-create-branch'),
|
||||||
|
textCreateRefFrom: elRoot.getAttribute('data-text-create-ref-from'),
|
||||||
|
textNoResults: elRoot.getAttribute('data-text-no-results'),
|
||||||
|
textViewAllBranches: elRoot.getAttribute('data-text-view-all-branches'),
|
||||||
|
textViewAllTags: elRoot.getAttribute('data-text-view-all-tags'),
|
||||||
|
|
||||||
|
currentRepoDefaultBranch: elRoot.getAttribute('data-current-repo-default-branch'),
|
||||||
|
currentRepoLink: elRoot.getAttribute('data-current-repo-link'),
|
||||||
|
currentTreePath: elRoot.getAttribute('data-current-tree-path'),
|
||||||
|
currentRefType: elRoot.getAttribute('data-current-ref-type'),
|
||||||
|
currentRefShortName: elRoot.getAttribute('data-current-ref-short-name'),
|
||||||
|
|
||||||
|
refLinkTemplate: elRoot.getAttribute('data-ref-link-template'),
|
||||||
|
refFormActionTemplate: elRoot.getAttribute('data-ref-form-action-template'),
|
||||||
|
dropdownFixedText: elRoot.getAttribute('data-dropdown-fixed-text'),
|
||||||
|
showTabBranches: shouldShowTabBranches,
|
||||||
|
showTabTags: elRoot.getAttribute('data-show-tab-tags') === 'true',
|
||||||
|
allowCreateNewRef: elRoot.getAttribute('data-allow-create-new-ref') === 'true',
|
||||||
|
showViewAllRefsEntry: elRoot.getAttribute('data-show-view-all-refs-entry') === 'true',
|
||||||
|
|
||||||
|
enableFeed: elRoot.getAttribute('data-enable-feed') === 'true',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
beforeMount() {
|
beforeMount() {
|
||||||
if (this.viewType === 'tree') {
|
document.body.addEventListener('click', (e) => {
|
||||||
this.isViewTree = true;
|
if (this.$el.contains(e.target)) return;
|
||||||
this.refNameText = this.commitIdShort;
|
if (this.menuVisible) this.menuVisible = false;
|
||||||
} else if (this.viewType === 'tag') {
|
|
||||||
this.isViewTag = true;
|
|
||||||
this.refNameText = this.tagName;
|
|
||||||
} else {
|
|
||||||
this.isViewBranch = true;
|
|
||||||
this.refNameText = this.branchName;
|
|
||||||
}
|
|
||||||
|
|
||||||
document.body.addEventListener('click', (event) => {
|
|
||||||
if (this.$el.contains(event.target)) return;
|
|
||||||
if (this.menuVisible) {
|
|
||||||
this.menuVisible = false;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
methods: {
|
methods: {
|
||||||
selectItem(item) {
|
selectItem(item: ListItem) {
|
||||||
const prev = this.getSelected();
|
|
||||||
if (prev !== null) {
|
|
||||||
prev.selected = false;
|
|
||||||
}
|
|
||||||
item.selected = true;
|
|
||||||
const url = (item.tag) ? this.tagURLPrefix + item.url + this.tagURLSuffix : this.branchURLPrefix + item.url + this.branchURLSuffix;
|
|
||||||
if (!this.branchForm) {
|
|
||||||
window.location.href = url;
|
|
||||||
} else {
|
|
||||||
this.isViewTree = false;
|
|
||||||
this.isViewTag = false;
|
|
||||||
this.isViewBranch = false;
|
|
||||||
this.$refs.dropdownRefName.textContent = item.name;
|
|
||||||
if (this.setAction) {
|
|
||||||
document.querySelector(`#${this.branchForm}`)?.setAttribute('action', url);
|
|
||||||
} else {
|
|
||||||
$(`#${this.branchForm} input[name="refURL"]`).val(url);
|
|
||||||
}
|
|
||||||
$(`#${this.branchForm} input[name="ref"]`).val(item.name);
|
|
||||||
if (item.tag) {
|
|
||||||
this.isViewTag = true;
|
|
||||||
$(`#${this.branchForm} input[name="refType"]`).val('tag');
|
|
||||||
} else {
|
|
||||||
this.isViewBranch = true;
|
|
||||||
$(`#${this.branchForm} input[name="refType"]`).val('branch');
|
|
||||||
}
|
|
||||||
if (this.submitForm) {
|
|
||||||
$(`#${this.branchForm}`).trigger('submit');
|
|
||||||
}
|
|
||||||
this.menuVisible = false;
|
this.menuVisible = false;
|
||||||
|
if (this.refFormActionTemplate) {
|
||||||
|
this.currentRefType = item.refType;
|
||||||
|
this.currentRefShortName = item.refShortName;
|
||||||
|
let actionLink = this.refFormActionTemplate;
|
||||||
|
actionLink = actionLink.replace('{RepoLink}', this.currentRepoLink);
|
||||||
|
actionLink = actionLink.replace('{RefType}', pathEscapeSegments(item.refType));
|
||||||
|
actionLink = actionLink.replace('{RefShortName}', pathEscapeSegments(item.refShortName));
|
||||||
|
this.$el.closest('form').action = actionLink;
|
||||||
|
} else {
|
||||||
|
let link = this.refLinkTemplate;
|
||||||
|
link = link.replace('{RepoLink}', this.currentRepoLink);
|
||||||
|
link = link.replace('{RefType}', pathEscapeSegments(item.refType));
|
||||||
|
link = link.replace('{RefShortName}', pathEscapeSegments(item.refShortName));
|
||||||
|
link = link.replace('{TreePath}', pathEscapeSegments(this.currentTreePath));
|
||||||
|
window.location.href = link;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
createNewBranch() {
|
createNewRef() {
|
||||||
if (!this.showCreateNewBranch) return;
|
this.$refs.createNewRefForm?.submit();
|
||||||
$(this.$refs.newBranchForm).trigger('submit');
|
|
||||||
},
|
},
|
||||||
focusSearchField() {
|
focusSearchField() {
|
||||||
nextTick(() => {
|
nextTick(() => {
|
||||||
this.$refs.searchField.focus();
|
this.$refs.searchField.focus();
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
getSelected() {
|
|
||||||
for (let i = 0, j = this.items.length; i < j; ++i) {
|
|
||||||
if (this.items[i].selected) return this.items[i];
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
},
|
|
||||||
getSelectedIndexInFiltered() {
|
getSelectedIndexInFiltered() {
|
||||||
for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
|
for (let i = 0; i < this.filteredItems.length; ++i) {
|
||||||
if (this.filteredItems[i].selected) return i;
|
if (this.filteredItems[i].selected) return i;
|
||||||
}
|
}
|
||||||
return -1;
|
return -1;
|
||||||
},
|
},
|
||||||
scrollToActive() {
|
getActiveItem() {
|
||||||
let el = this.$refs[`listItem${this.active}`]; // eslint-disable-line no-jquery/variable-pattern
|
const el = this.$refs[`listItem${this.activeItemIndex}`]; // eslint-disable-line no-jquery/variable-pattern
|
||||||
if (!el || !el.length) return;
|
return (el && el.length) ? el[0] : null;
|
||||||
if (Array.isArray(el)) {
|
|
||||||
el = el[0];
|
|
||||||
}
|
|
||||||
|
|
||||||
const cont = this.$refs.scrollContainer;
|
|
||||||
if (el.offsetTop < cont.scrollTop) {
|
|
||||||
cont.scrollTop = el.offsetTop;
|
|
||||||
} else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
|
|
||||||
cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
keydown(event) {
|
keydown(e) {
|
||||||
if (event.keyCode === 40) { // arrow down
|
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
|
||||||
event.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
if (this.active === -1) {
|
if (this.activeItemIndex === -1) {
|
||||||
this.active = this.getSelectedIndexInFiltered();
|
this.activeItemIndex = this.getSelectedIndexInFiltered();
|
||||||
}
|
}
|
||||||
|
const nextIndex = e.key === 'ArrowDown' ? this.activeItemIndex + 1 : this.activeItemIndex - 1;
|
||||||
if (this.active + (this.showCreateNewBranch ? 0 : 1) >= this.filteredItems.length) {
|
if (nextIndex < 0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.active++;
|
if (nextIndex + (this.showCreateNewRef ? 0 : 1) > this.filteredItems.length) {
|
||||||
this.scrollToActive();
|
|
||||||
} else if (event.keyCode === 38) { // arrow up
|
|
||||||
event.preventDefault();
|
|
||||||
|
|
||||||
if (this.active === -1) {
|
|
||||||
this.active = this.getSelectedIndexInFiltered();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.active <= 0) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
this.active--;
|
this.activeItemIndex = nextIndex;
|
||||||
this.scrollToActive();
|
this.getActiveItem().scrollIntoView({block: 'nearest'});
|
||||||
} else if (event.keyCode === 13) { // enter
|
} else if (e.key === 'Enter') {
|
||||||
event.preventDefault();
|
e.preventDefault();
|
||||||
|
this.getActiveItem()?.click();
|
||||||
if (this.active >= this.filteredItems.length) {
|
} else if (e.key === 'Escape') {
|
||||||
this.createNewBranch();
|
e.preventDefault();
|
||||||
} else if (this.active >= 0) {
|
|
||||||
this.selectItem(this.filteredItems[this.active]);
|
|
||||||
}
|
|
||||||
} else if (event.keyCode === 27) { // escape
|
|
||||||
event.preventDefault();
|
|
||||||
this.menuVisible = false;
|
this.menuVisible = false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
handleTabSwitch(mode) {
|
handleTabSwitch(selectedTab) {
|
||||||
if (this.isLoading) return;
|
this.selectedTab = selectedTab;
|
||||||
this.mode = mode;
|
|
||||||
this.focusSearchField();
|
this.focusSearchField();
|
||||||
this.fetchBranchesOrTags();
|
this.loadTabItems();
|
||||||
},
|
},
|
||||||
async fetchBranchesOrTags() {
|
async loadTabItems() {
|
||||||
if (!['branches', 'tags'].includes(this.mode) || this.isLoading) return;
|
const tab = this.selectedTab;
|
||||||
// only fetch when branch/tag list has not been initialized
|
if (this.tabLoadingStates[tab] === 'loading' || this.tabLoadingStates[tab] === 'done') return;
|
||||||
if (this.hasListInitialized[this.mode] ||
|
|
||||||
(this.mode === 'branches' && !this.showBranchesInDropdown) ||
|
const refType = this.selectedTab === 'branches' ? 'branch' : 'tag';
|
||||||
(this.mode === 'tags' && this.noTag)
|
this.tabLoadingStates[tab] = 'loading';
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.isLoading = true;
|
|
||||||
try {
|
try {
|
||||||
const resp = await GET(`${this.repoLink}/${this.mode}/list`);
|
const url = refType === 'branch' ? `${this.currentRepoLink}/branches/list` : `${this.currentRepoLink}/tags/list`;
|
||||||
|
const resp = await GET(url);
|
||||||
const {results} = await resp.json();
|
const {results} = await resp.json();
|
||||||
for (const result of results) {
|
for (const refShortName of results) {
|
||||||
let selected = false;
|
const item: ListItem = {
|
||||||
if (this.mode === 'branches') {
|
refType,
|
||||||
selected = result === this.defaultSelectedRefName;
|
refShortName,
|
||||||
} else {
|
selected: refType === this.currentRefType && refShortName === this.currentRefShortName,
|
||||||
selected = result === (this.release ? this.release.tagName : this.defaultSelectedRefName);
|
rssFeedLink: `${this.currentRepoLink}/rss/${refType}/${pathEscapeSegments(refShortName)}`,
|
||||||
|
};
|
||||||
|
this.allItems.push(item);
|
||||||
}
|
}
|
||||||
this.items.push({name: result, url: pathEscapeSegments(result), branch: this.mode === 'branches', tag: this.mode === 'tags', selected});
|
this.tabLoadingStates[tab] = 'done';
|
||||||
}
|
|
||||||
this.hasListInitialized[this.mode] = true;
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
showErrorToast(`Network error when fetching ${this.mode}, error: ${e}`);
|
this.tabLoadingStates[tab] = '';
|
||||||
} finally {
|
showErrorToast(`Network error when fetching items for ${tab}, error: ${e}`);
|
||||||
this.isLoading = false;
|
console.error(e);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function initRepoBranchTagSelector(selector) {
|
export function initRepoBranchTagSelector(selector) {
|
||||||
for (const [elIndex, elRoot] of document.querySelectorAll(selector).entries()) {
|
for (const elRoot of document.querySelectorAll(selector)) {
|
||||||
const data = {
|
// it is very hacky, but it is the only way to pass the elRoot to the "data()" function
|
||||||
csrfToken: window.config.csrfToken,
|
// it could be improved in the future to do more rewriting.
|
||||||
items: [],
|
currentElRoot = elRoot;
|
||||||
searchTerm: '',
|
const comp = {...sfc};
|
||||||
refNameText: '',
|
|
||||||
menuVisible: false,
|
|
||||||
release: null,
|
|
||||||
|
|
||||||
isViewTag: false,
|
|
||||||
isViewBranch: false,
|
|
||||||
isViewTree: false,
|
|
||||||
|
|
||||||
active: 0,
|
|
||||||
isLoading: false,
|
|
||||||
// This means whether branch list/tag list has initialized
|
|
||||||
hasListInitialized: {
|
|
||||||
'branches': false,
|
|
||||||
'tags': false,
|
|
||||||
},
|
|
||||||
...window.config.pageData.branchDropdownDataList[elIndex],
|
|
||||||
};
|
|
||||||
|
|
||||||
const comp = {...sfc, data() { return data }};
|
|
||||||
createApp(comp).mount(elRoot);
|
createApp(comp).mount(elRoot);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -247,13 +223,13 @@ export default sfc; // activate IDE's Vue plugin
|
|||||||
</script>
|
</script>
|
||||||
<template>
|
<template>
|
||||||
<div class="ui dropdown custom branch-selector-dropdown ellipsis-items-nowrap">
|
<div class="ui dropdown custom branch-selector-dropdown ellipsis-items-nowrap">
|
||||||
<div class="ui button branch-dropdown-button" @click="menuVisible = !menuVisible" @keyup.enter="menuVisible = !menuVisible">
|
<div tabindex="0" class="ui button branch-dropdown-button" @click="menuVisible = !menuVisible">
|
||||||
<span class="flex-text-block gt-ellipsis">
|
<span class="flex-text-block gt-ellipsis">
|
||||||
<template v-if="release">{{ textReleaseCompare }}</template>
|
<template v-if="dropdownFixedText">{{ dropdownFixedText }}</template>
|
||||||
<template v-else>
|
<template v-else>
|
||||||
<svg-icon v-if="isViewTag" name="octicon-tag"/>
|
<svg-icon v-if="currentRefType === 'tag'" name="octicon-tag"/>
|
||||||
<svg-icon v-else name="octicon-git-branch"/>
|
<svg-icon v-else name="octicon-git-branch"/>
|
||||||
<strong ref="dropdownRefName" class="tw-ml-2 tw-inline-block gt-ellipsis">{{ refNameText }}</strong>
|
<strong ref="dropdownRefName" class="tw-ml-2 tw-inline-block gt-ellipsis">{{ currentRefShortName }}</strong>
|
||||||
</template>
|
</template>
|
||||||
</span>
|
</span>
|
||||||
<svg-icon name="octicon-triangle-down" :size="14" class-name="dropdown icon"/>
|
<svg-icon name="octicon-triangle-down" :size="14" class-name="dropdown icon"/>
|
||||||
@ -263,55 +239,56 @@ export default sfc; // activate IDE's Vue plugin
|
|||||||
<i class="icon"><svg-icon name="octicon-filter" :size="16"/></i>
|
<i class="icon"><svg-icon name="octicon-filter" :size="16"/></i>
|
||||||
<input name="search" ref="searchField" autocomplete="off" v-model="searchTerm" @keydown="keydown($event)" :placeholder="searchFieldPlaceholder">
|
<input name="search" ref="searchField" autocomplete="off" v-model="searchTerm" @keydown="keydown($event)" :placeholder="searchFieldPlaceholder">
|
||||||
</div>
|
</div>
|
||||||
<div v-if="showBranchesInDropdown" class="branch-tag-tab">
|
<div v-if="showTabBranches" class="branch-tag-tab">
|
||||||
<a class="branch-tag-item muted" :class="{active: mode === 'branches'}" href="#" @click="handleTabSwitch('branches')">
|
<a class="branch-tag-item muted" :class="{active: selectedTab === 'branches'}" href="#" @click="handleTabSwitch('branches')">
|
||||||
<svg-icon name="octicon-git-branch" :size="16" class-name="tw-mr-1"/>{{ textBranches }}
|
<svg-icon name="octicon-git-branch" :size="16" class-name="tw-mr-1"/>{{ textBranches }}
|
||||||
</a>
|
</a>
|
||||||
<a v-if="!noTag" class="branch-tag-item muted" :class="{active: mode === 'tags'}" href="#" @click="handleTabSwitch('tags')">
|
<a v-if="showTabTags" class="branch-tag-item muted" :class="{active: selectedTab === 'tags'}" href="#" @click="handleTabSwitch('tags')">
|
||||||
<svg-icon name="octicon-tag" :size="16" class-name="tw-mr-1"/>{{ textTags }}
|
<svg-icon name="octicon-tag" :size="16" class-name="tw-mr-1"/>{{ textTags }}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<div class="branch-tag-divider"/>
|
<div class="branch-tag-divider"/>
|
||||||
<div class="scrolling menu" ref="scrollContainer">
|
<div class="scrolling menu" ref="scrollContainer">
|
||||||
<svg-icon name="octicon-rss" symbol-id="svg-symbol-octicon-rss"/>
|
<svg-icon name="octicon-rss" symbol-id="svg-symbol-octicon-rss"/>
|
||||||
<div class="loading-indicator is-loading" v-if="isLoading"/>
|
<div class="loading-indicator is-loading" v-if="tabLoadingStates[selectedTab] === 'loading'"/>
|
||||||
<div v-for="(item, index) in filteredItems" :key="item.name" class="item" :class="{selected: item.selected, active: active === index}" @click="selectItem(item)" :ref="'listItem' + index">
|
<div v-for="(item, index) in filteredItems" :key="item.refShortName" class="item" :class="{selected: item.selected, active: activeItemIndex === index}" @click="selectItem(item)" :ref="'listItem' + index">
|
||||||
{{ item.name }}
|
{{ item.refShortName }}
|
||||||
<div class="ui label" v-if="item.name===repoDefaultBranch && mode === 'branches'">
|
<div class="ui label" v-if="item.refType === 'branch' && item.refShortName === currentRepoDefaultBranch">
|
||||||
{{ textDefaultBranchLabel }}
|
{{ textDefaultBranchLabel }}
|
||||||
</div>
|
</div>
|
||||||
<a v-show="enableFeed && mode === 'branches'" role="button" class="rss-icon" :href="rssURLPrefix + item.url" target="_blank" @click.stop>
|
<a v-if="enableFeed && selectedTab === 'branches'" role="button" class="rss-icon" target="_blank" @click.stop :href="item.rssFeedLink">
|
||||||
<!-- creating a lot of Vue component is pretty slow, so we use a static SVG here -->
|
<!-- creating a lot of Vue component is pretty slow, so we use a static SVG here -->
|
||||||
<svg width="14" height="14" class="svg octicon-rss"><use href="#svg-symbol-octicon-rss"/></svg>
|
<svg width="14" height="14" class="svg octicon-rss"><use href="#svg-symbol-octicon-rss"/></svg>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<div class="item" v-if="showCreateNewBranch" :class="{active: active === filteredItems.length}" :ref="'listItem' + filteredItems.length">
|
<div class="item" v-if="showCreateNewRef" :class="{active: activeItemIndex === filteredItems.length}" :ref="'listItem' + filteredItems.length" @click="createNewRef()">
|
||||||
<a href="#" @click="createNewBranch()">
|
<div v-if="selectedTab === 'tags'">
|
||||||
<div v-show="shouldCreateTag">
|
<svg-icon name="octicon-tag" class="tw-mr-1"/>
|
||||||
<i class="reference tags icon"/>
|
|
||||||
<span v-text="textCreateTag.replace('%s', searchTerm)"/>
|
<span v-text="textCreateTag.replace('%s', searchTerm)"/>
|
||||||
</div>
|
</div>
|
||||||
<div v-show="!shouldCreateTag">
|
<div v-else>
|
||||||
<svg-icon name="octicon-git-branch"/>
|
<svg-icon name="octicon-git-branch" class="tw-mr-1"/>
|
||||||
<span v-text="textCreateBranch.replace('%s', searchTerm)"/>
|
<span v-text="textCreateBranch.replace('%s', searchTerm)"/>
|
||||||
</div>
|
</div>
|
||||||
<div class="text small">
|
<div class="text small">
|
||||||
<span v-if="isViewBranch || release">{{ textCreateBranchFrom.replace('%s', branchName) }}</span>
|
{{ textCreateRefFrom.replace('%s', currentRefShortName) }}
|
||||||
<span v-else-if="isViewTag">{{ textCreateBranchFrom.replace('%s', tagName) }}</span>
|
|
||||||
<span v-else>{{ textCreateBranchFrom.replace('%s', commitIdShort) }}</span>
|
|
||||||
</div>
|
</div>
|
||||||
</a>
|
<form ref="createNewRefForm" method="post" :action="createNewRefFormActionUrl">
|
||||||
<form ref="newBranchForm" :action="formActionUrl" method="post">
|
|
||||||
<input type="hidden" name="_csrf" :value="csrfToken">
|
<input type="hidden" name="_csrf" :value="csrfToken">
|
||||||
<input type="hidden" name="new_branch_name" v-model="searchTerm">
|
<input type="hidden" name="new_branch_name" :value="searchTerm">
|
||||||
<input type="hidden" name="create_tag" v-model="shouldCreateTag">
|
<input type="hidden" name="create_tag" :value="String(selectedTab === 'tags')">
|
||||||
<input type="hidden" name="current_path" v-model="treePath" v-if="treePath">
|
<input type="hidden" name="current_path" :value="currentTreePath">
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="message" v-if="showNoResults && !isLoading">
|
<div class="message" v-if="showNoResults">
|
||||||
{{ noResults }}
|
{{ textNoResults }}
|
||||||
</div>
|
</div>
|
||||||
|
<template v-if="showViewAllRefsEntry">
|
||||||
|
<div class="divider tw-m-0"/>
|
||||||
|
<a v-if="selectedTab === 'branches'" class="item" :href="currentRepoLink + '/branches'">{{ textViewAllBranches }}</a>
|
||||||
|
<a v-if="selectedTab === 'tags'" class="item" :href="currentRepoLink + '/tags'">{{ textViewAllTags }}</a>
|
||||||
|
</template>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import {POST} from '../../modules/fetch.ts';
|
import {POST} from '../../modules/fetch.ts';
|
||||||
import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
import {fomanticQuery} from '../../modules/fomantic/base.ts';
|
||||||
|
|
||||||
export function initCompReactionSelector() {
|
export function initCompReactionSelector(parent: ParentNode = document) {
|
||||||
for (const container of document.querySelectorAll('.issue-content, .diff-file-body')) {
|
for (const container of parent.querySelectorAll('.issue-content, .diff-file-body')) {
|
||||||
container.addEventListener('click', async (e) => {
|
container.addEventListener('click', async (e) => {
|
||||||
// there are 2 places for the "reaction" buttons, one is the top-right reaction menu, one is the bottom of the comment
|
// there are 2 places for the "reaction" buttons, one is the top-right reaction menu, one is the bottom of the comment
|
||||||
const target = e.target.closest('.comment-reaction-button');
|
const target = e.target.closest('.comment-reaction-button');
|
||||||
|
@ -38,7 +38,7 @@ function initRepoDiffFileViewToggle() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function initRepoDiffConversationForm() {
|
function initRepoDiffConversationForm() {
|
||||||
addDelegatedEventListener<HTMLFormElement>(document, 'submit', '.conversation-holder form', async (form, e) => {
|
addDelegatedEventListener<HTMLFormElement, SubmitEvent>(document, 'submit', '.conversation-holder form', async (form, e) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const textArea = form.querySelector<HTMLTextAreaElement>('textarea');
|
const textArea = form.querySelector<HTMLTextAreaElement>('textarea');
|
||||||
if (!validateTextareaNonEmpty(textArea)) return;
|
if (!validateTextareaNonEmpty(textArea)) return;
|
||||||
@ -55,7 +55,9 @@ function initRepoDiffConversationForm() {
|
|||||||
formData.append(submitter.name, submitter.value);
|
formData.append(submitter.name, submitter.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
const trLineType = form.closest('tr').getAttribute('data-line-type');
|
// on the diff page, the form is inside a "tr" and need to get the line-type ahead
|
||||||
|
// but on the conversation page, there is no parent "tr"
|
||||||
|
const trLineType = form.closest('tr')?.getAttribute('data-line-type');
|
||||||
const response = await POST(form.getAttribute('action'), {data: formData});
|
const response = await POST(form.getAttribute('action'), {data: formData});
|
||||||
const newConversationHolder = createElementFromHTML(await response.text());
|
const newConversationHolder = createElementFromHTML(await response.text());
|
||||||
const path = newConversationHolder.getAttribute('data-path');
|
const path = newConversationHolder.getAttribute('data-path');
|
||||||
@ -65,6 +67,9 @@ function initRepoDiffConversationForm() {
|
|||||||
form.closest('.conversation-holder').replaceWith(newConversationHolder);
|
form.closest('.conversation-holder').replaceWith(newConversationHolder);
|
||||||
form = null; // prevent further usage of the form because it should have been replaced
|
form = null; // prevent further usage of the form because it should have been replaced
|
||||||
|
|
||||||
|
if (trLineType) {
|
||||||
|
// if there is a line-type for the "tr", it means the form is on the diff page
|
||||||
|
// then hide the "add-code-comment" [+] button for current code line by adding "tw-invisible" because the conversation has been added
|
||||||
let selector;
|
let selector;
|
||||||
if (trLineType === 'same') {
|
if (trLineType === 'same') {
|
||||||
selector = `[data-path="${path}"] .add-code-comment[data-idx="${idx}"]`;
|
selector = `[data-path="${path}"] .add-code-comment[data-idx="${idx}"]`;
|
||||||
@ -72,7 +77,8 @@ function initRepoDiffConversationForm() {
|
|||||||
selector = `[data-path="${path}"] .add-code-comment[data-side="${side}"][data-idx="${idx}"]`;
|
selector = `[data-path="${path}"] .add-code-comment[data-side="${side}"][data-idx="${idx}"]`;
|
||||||
}
|
}
|
||||||
for (const el of document.querySelectorAll(selector)) {
|
for (const el of document.querySelectorAll(selector)) {
|
||||||
el.classList.add('tw-invisible'); // TODO need to figure out why
|
el.classList.add('tw-invisible');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fomanticQuery(newConversationHolder.querySelectorAll('.ui.dropdown')).dropdown();
|
fomanticQuery(newConversationHolder.querySelectorAll('.ui.dropdown')).dropdown();
|
||||||
|
|
||||||
@ -109,7 +115,7 @@ function initRepoDiffConversationForm() {
|
|||||||
const $conversation = $(data);
|
const $conversation = $(data);
|
||||||
$(this).closest('.conversation-holder').replaceWith($conversation);
|
$(this).closest('.conversation-holder').replaceWith($conversation);
|
||||||
$conversation.find('.dropdown').dropdown();
|
$conversation.find('.dropdown').dropdown();
|
||||||
initCompReactionSelector($conversation);
|
initCompReactionSelector($conversation[0]);
|
||||||
} else {
|
} else {
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
}
|
}
|
||||||
|
@ -59,3 +59,5 @@ export type FomanticInitFunction = {
|
|||||||
settings?: Record<string, any>,
|
settings?: Record<string, any>,
|
||||||
(...args: any[]): any,
|
(...args: any[]): any,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type GitRefType = 'branch' | 'tag';
|
||||||
|
Loading…
x
Reference in New Issue
Block a user