Skip to content

Commit 3f8c574

Browse files
committed
Merge remote-tracking branch 'giteaofficial/main'
* giteaofficial/main: Refactor view issue & comment list styles (go-gitea#35061) Fix user's sign email check (go-gitea#35045) [skip ci] Updated translations via Crowdin Fix incorrect comment diff hunk parsing, fix github asset ID nil panic (go-gitea#35046) Add Notifications section in User Settings (go-gitea#35008)
2 parents a9ed1ec + 7cc47da commit 3f8c574

File tree

30 files changed

+405
-402
lines changed

30 files changed

+405
-402
lines changed

models/asymkey/ssh_key_fingerprint.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ import (
1313
"xorm.io/builder"
1414
)
1515

16-
// The database is used in checkKeyFingerprint however most of these functions probably belong in a module
16+
// The database is used in checkKeyFingerprint. However, most of these functions probably belong in a module
1717

18-
// checkKeyFingerprint only checks if key fingerprint has been used as public key,
18+
// checkKeyFingerprint only checks if key fingerprint has been used as a public key,
1919
// it is OK to use same key as deploy key for multiple repositories/users.
2020
func checkKeyFingerprint(ctx context.Context, fingerprint string) error {
2121
has, err := db.Exist[PublicKey](ctx, builder.Eq{"fingerprint": fingerprint})

models/fixtures/public_key.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@
99
created_unix: 1559593109
1010
updated_unix: 1565224552
1111
login_source_id: 0
12+
verified: false

modules/git/diff.go

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,9 @@ func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diff
9999
return nil
100100
}
101101

102-
// ParseDiffHunkString parse the diffhunk content and return
103-
func ParseDiffHunkString(diffhunk string) (leftLine, leftHunk, rightLine, righHunk int) {
104-
ss := strings.Split(diffhunk, "@@")
102+
// ParseDiffHunkString parse the diff hunk content and return
103+
func ParseDiffHunkString(diffHunk string) (leftLine, leftHunk, rightLine, rightHunk int) {
104+
ss := strings.Split(diffHunk, "@@")
105105
ranges := strings.Split(ss[1][1:], " ")
106106
leftRange := strings.Split(ranges[0], ",")
107107
leftLine, _ = strconv.Atoi(leftRange[0][1:])
@@ -112,14 +112,19 @@ func ParseDiffHunkString(diffhunk string) (leftLine, leftHunk, rightLine, righHu
112112
rightRange := strings.Split(ranges[1], ",")
113113
rightLine, _ = strconv.Atoi(rightRange[0])
114114
if len(rightRange) > 1 {
115-
righHunk, _ = strconv.Atoi(rightRange[1])
115+
rightHunk, _ = strconv.Atoi(rightRange[1])
116116
}
117117
} else {
118-
log.Debug("Parse line number failed: %v", diffhunk)
118+
log.Debug("Parse line number failed: %v", diffHunk)
119119
rightLine = leftLine
120-
righHunk = leftHunk
120+
rightHunk = leftHunk
121121
}
122-
return leftLine, leftHunk, rightLine, righHunk
122+
if rightLine == 0 {
123+
// FIXME: GIT-DIFF-CUT-BUG search this tag to see details
124+
// this is only a hacky patch, the rightLine&rightHunk might still be incorrect in some cases.
125+
rightLine++
126+
}
127+
return leftLine, leftHunk, rightLine, rightHunk
123128
}
124129

125130
// Example: @@ -1,8 +1,9 @@ => [..., 1, 8, 1, 9]
@@ -270,6 +275,12 @@ func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLi
270275
oldNumOfLines++
271276
}
272277
}
278+
279+
// "git diff" outputs "@@ -1 +1,3 @@" for "OLD" => "A\nB\nC"
280+
// FIXME: GIT-DIFF-CUT-BUG But there is a bug in CutDiffAroundLine, then the "Patch" stored in the comment model becomes "@@ -1,1 +0,4 @@"
281+
// It may generate incorrect results for difference cases, for example: delete 2 line add 1 line, delete 2 line add 2 line etc, need to double check.
282+
// For example: "L1\nL2" => "A\nB", then the patch shows "L2" as line 1 on the left (deleted part)
283+
273284
// construct the new hunk header
274285
newHunk[headerLines] = fmt.Sprintf("@@ -%d,%d +%d,%d @@",
275286
oldBegin, oldNumOfLines, newBegin, newNumOfLines)

options/locale/locale_fr-FR.ini

Lines changed: 79 additions & 63 deletions
Large diffs are not rendered by default.

options/locale/locale_ga-IE.ini

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ files=Comhaid
117117
118118
error=Earráid
119119
error404=Níl an leathanach atá tú ag iarraidh a bhaint amach <strong>ann</strong> nó <strong>níl tú údaraithe</strong> chun é a fheiceáil.
120+
error503=Níorbh fhéidir leis an bhfreastalaí d’iarratas a chomhlánú. Déan iarracht arís ar ball.
120121
go_back=Ar ais
121122
invalid_data=Sonraí neamhbhailí: %v
122123
@@ -130,6 +131,7 @@ unpin=Díphoráil
130131
131132
artifacts=Déantáin
132133
expired=Imithe in éag
134+
confirm_delete_artifact=An bhfuil tú cinnte gur mian leat an déantán '%s' a scriosadh?
133135
134136
archived=Cartlann
135137
@@ -169,6 +171,7 @@ internal_error_skipped=Tharla earráid inmheánach ach éirithe as: %s
169171
search=Cuardaigh...
170172
type_tooltip=Cineál cuardaigh
171173
fuzzy=Doiléir
174+
fuzzy_tooltip=Cuir torthaí san áireamh a mheaitseálann go dlúth leis an téarma cuardaigh
172175
words=Focail
173176
words_tooltip=Ná cuir san áireamh ach torthaí a mheaitseálann na focail téarma cuardaigh
174177
regexp=Nathanna Rialta
@@ -503,6 +506,7 @@ activate_email.text=Cliceáil ar an nasc seo a leanas le do sheoladh ríomhphois
503506
504507
register_notify=Fáilte go dtí %s
505508
register_notify.title=%[1]s, fáilte go %[2]s
509+
register_notify.text_1=Seo do ríomhphost deimhnithe clárúcháin le haghaidh %s!
506510
register_notify.text_2=Is féidir leat logáil isteach anois trí ainm úsáideora: %s.
507511
register_notify.text_3=Má cruthaíodh an cuntas seo duit, <a href="%s">socraigh do phasfhocal</a> ar dtús.
508512
@@ -994,6 +998,7 @@ webauthn_alternative_tip=B'fhéidir gur mhaith leat modh fíordheimhnithe breise
994998
995999
manage_account_links=Bainistigh Cuntais Nasctha
9961000
manage_account_links_desc=Tá na cuntais sheachtracha seo nasctha le do chuntas Gitea.
1001+
account_links_not_available=Níl aon chuntais sheachtracha nasctha le do chuntas Gitea faoi láthair.
9971002
link_account=Cuntas Nasc
9981003
remove_account_link=Bain Cuntas Nasctha
9991004
remove_account_link_desc=Ag baint cuntas nasctha, cuirfear a rochtain ar do chuntas Gitea a chúlghairm. Lean ar aghaidh?
@@ -1030,6 +1035,8 @@ new_repo_helper=Tá gach comhad tionscadail i stór, lena n-áirítear stair ath
10301035
owner=Úinéir
10311036
owner_helper=B'fhéidir nach dtaispeánfar roinnt eagraíochtaí sa anuas mar gheall ar theorainn uasta comhaireamh stórais.
10321037
repo_name=Ainm Stórais
1038+
repo_name_profile_public_hint=Is stóras speisialta é .profile ar féidir leat a úsáid chun README.md a chur le do phróifíl eagraíochta poiblí, le feiceáil ag aon duine. Déan cinnte go bhfuil sé poiblí agus cuir README sa chomhadlann próifíle chun tús a chur leis.
1039+
repo_name_profile_private_hint=Is stóras speisialta é .profile-private ar féidir leat a úsáid chun README.md a chur le próifíl bhall d'eagraíochta, nach mbeidh le feiceáil ach ag baill na heagraíochta. Déan cinnte go bhfuil sé príobháideach agus cuir README sa chomhadlann próifíle chun tús a chur leis.
10331040
repo_name_helper=Úsáideann ainmneacha maith stóras focail eochair gairide, áithnid agus uathúla. D'fhéadfaí stóras darbh ainm '.profile''.profile-private' a úsáid chun README.md a chur leis an bpróifíl úsáideora/eagraíochta.
10341041
repo_size=Méid an Stóras
10351042
template=Teimpléad
@@ -1051,6 +1058,7 @@ fork_branch=Brainse le clónú chuig an bhforc
10511058
all_branches=Gach brainse
10521059
view_all_branches=Féach ar gach brainse
10531060
view_all_tags=Féach ar gach clib
1061+
fork_no_valid_owners=Ní féidir an stóras seo a fhorcadh mar nach bhfuil aon úinéirí bailí ann.
10541062
fork.blocked_user=Ní féidir an stór a fhorcáil toisc go bhfuil úinéir an stórais bac ort.
10551063
use_template=Úsáid an teimpléad seo
10561064
open_with_editor=Oscail le %s
@@ -1747,6 +1755,7 @@ issues.due_date_form=bbbb-mm-ll
17471755
issues.due_date_form_add=Cuir dáta dlite leis
17481756
issues.due_date_form_edit=Cuir in eagar
17491757
issues.due_date_form_remove=Bain
1758+
issues.due_date_not_writer=Ní mór duit rochtain scríbhneoireachta a fháil ar an stóras seo chun dáta dlite saincheiste a nuashonrú.
17501759
issues.due_date_not_set=Níl aon dáta dlite socraithe.
17511760
issues.due_date_added=cuireadh an dáta dlite %s %s
17521761
issues.due_date_modified=d'athraigh an dáta dlite ó %[2]s go %[1]s %[3]s
@@ -2114,6 +2123,7 @@ activity.title.releases_1=Scaoileadh %d
21142123
activity.title.releases_n=Eisiúintí %d
21152124
activity.title.releases_published_by=%s foilsithe ag %s
21162125
activity.published_release_label=Foilsithe
2126+
activity.no_git_activity=Ní raibh aon ghníomhaíocht tiomantais ann sa tréimhse seo.
21172127
activity.git_stats_exclude_merges=Gan cumaisc a áireamh,
21182128
activity.git_stats_author_1=%d údar
21192129
activity.git_stats_author_n=%d údair
@@ -3241,6 +3251,8 @@ auths.oauth2_required_claim_name_helper=Socraigh an t-ainm seo chun logáil iste
32413251
auths.oauth2_required_claim_value=Luach Éilimh Riachtanach
32423252
auths.oauth2_required_claim_value_helper=Socraigh an luach seo chun logáil isteach ón bhfoinse seo a shrianadh chuig úsáideoirí a bhfuil éileamh acu leis an ainm agus an luach seo
32433253
auths.oauth2_group_claim_name=Ainm éileamh ag soláthar ainmneacha grúpa don fhoinse seo (Roghnach)
3254+
auths.oauth2_full_name_claim_name=Ainm Iomlán Éilimh. (Roghnach, má shocraítear é, déanfar ainm iomlán an úsáideora a shioncrónú leis an éileamh seo i gcónaí)
3255+
auths.oauth2_ssh_public_key_claim_name=Ainm Éilimh Eochrach Phoiblí SSH
32443256
auths.oauth2_admin_group=Luach Éilimh Grúpa d'úsáideoirí riarthóra. (Roghnach - teastaíonn ainm éilimh thuas)
32453257
auths.oauth2_restricted_group=Luach Éilimh Grúpa d'úsáideoirí srianta. (Roghnach - teastaíonn ainm éilimh thuas)
32463258
auths.oauth2_map_group_to_team=Map mhaígh grúpaí chuig foirne Eagraíochta. (Roghnach - éilíonn ainm an éilimh thuas)

options/locale/locale_pt-PT.ini

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ files=Ficheiros
117117

118118
error=Erro
119119
error404=A página que pretende aceder <strong>não existe</strong> ou <strong>não tem autorização</strong> para a ver.
120+
error503=O servidor não conseguiu concluir o seu pedido. Tente novamente mais tarde.
120121
go_back=Voltar
121122
invalid_data=Dados inválidos: %v
122123

@@ -130,6 +131,7 @@ unpin=Desafixar
130131

131132
artifacts=Artefactos
132133
expired=Expirado
134+
confirm_delete_artifact=Tem a certeza que quer eliminar este artefacto "%s"?
133135

134136
archived=Arquivado
135137

@@ -169,6 +171,7 @@ internal_error_skipped=Ocorreu um erro interno mas foi ignorado: %s
169171
search=Pesquisar...
170172
type_tooltip=Tipo de pesquisa
171173
fuzzy=Aproximada
174+
fuzzy_tooltip=Incluir também os resultados que estejam próximos do termo de pesquisa
172175
words=Palavras
173176
words_tooltip=Incluir apenas os resultados que correspondam às palavras do termo de pesquisa
174177
regexp=Regexp
@@ -503,6 +506,7 @@ activate_email.text=Por favor clique na seguinte ligação para validar o seu en
503506

504507
register_notify=Bem-vindo(a) a %s
505508
register_notify.title=%[1]s, bem-vindo(a) a %[2]s
509+
register_notify.text_1=Este é o seu email de confirmação de registo para %s!
506510
register_notify.text_2=Agora pode iniciar a sessão com o nome de utilizador: %s.
507511
register_notify.text_3=Se esta conta foi criada para si, <a href="%s">defina a sua senha</a> primeiro.
508512

@@ -994,6 +998,7 @@ webauthn_alternative_tip=Poderá querer configurar um método de autenticação
994998

995999
manage_account_links=Gerir contas vinculadas
9961000
manage_account_links_desc=Estas contas externas estão vinculadas à sua conta do Gitea.
1001+
account_links_not_available=Neste momento não existem contas externas vinculadas à sua conta do Gitea.
9971002
link_account=Vincular conta
9981003
remove_account_link=Remover conta vinculada
9991004
remove_account_link_desc=A remoção de uma conta vinculada revogará o acesso dessa conta à sua conta do Gitea. Quer continuar?
@@ -1030,6 +1035,8 @@ new_repo_helper=Um repositório contém todos os ficheiros do trabalho, incluind
10301035
owner=Proprietário(a)
10311036
owner_helper=Algumas organizações podem não aparecer na lista suspensa devido a um limite máximo de contagem de repositórios.
10321037
repo_name=Nome do repositório
1038+
repo_name_profile_public_hint=.profile é um repositório especial que pode usar para adicionar README.md ao seu perfil público da organização, visível para qualquer pessoa. Certifique-se que é público e inicialize-o com um README na pasta do perfil para começar.
1039+
repo_name_profile_private_hint=.profile-private é um repositório especial que pode usar para adicionar um README.md ao seu perfil de membro da organização, visível apenas para membros da organização. Certifique-se que é privado e inicialize-o com um README na pasta de perfil para começar.
10331040
repo_name_helper=Bons nomes de repositórios usam palavras-chave curtas, memorizáveis e únicas. Um repositório chamado ".profile" ou ".profile-private" pode ser usado para adicionar um README.md ao perfil do utilizador ou da organização.
10341041
repo_size=Tamanho do repositório
10351042
template=Modelo
@@ -1051,6 +1058,7 @@ fork_branch=Ramo a ser clonado para a derivação
10511058
all_branches=Todos os ramos
10521059
view_all_branches=Ver todos os ramos
10531060
view_all_tags=Ver todas as etiquetas
1061+
fork_no_valid_owners=Não pode fazer uma derivação deste repositório porque não existem proprietários válidos.
10541062
fork.blocked_user=Não pode derivar o repositório porque foi bloqueado/a pelo/a proprietário/a do repositório.
10551063
use_template=Usar este modelo
10561064
open_with_editor=Abrir com %s
@@ -1747,6 +1755,7 @@ issues.due_date_form=yyyy-mm-dd
17471755
issues.due_date_form_add=Adicionar data de vencimento
17481756
issues.due_date_form_edit=Editar
17491757
issues.due_date_form_remove=Remover
1758+
issues.due_date_not_writer=Tem que ter acesso de escrita neste repositório para poder modificar a data de vencimento de uma questão.
17501759
issues.due_date_not_set=Sem data de vencimento definida.
17511760
issues.due_date_added=adicionou a data de vencimento %s %s
17521761
issues.due_date_modified=modificou a data de vencimento de %[2]s para %[1]s %[3]s
@@ -2114,6 +2123,7 @@ activity.title.releases_1=%d lançamento
21142123
activity.title.releases_n=%d Lançamentos
21152124
activity.title.releases_published_by=%s publicado por %s
21162125
activity.published_release_label=Publicado
2126+
activity.no_git_activity=Não houve quaisquer cometimentos feitos durante este período.
21172127
activity.git_stats_exclude_merges=Excluindo integrações,
21182128
activity.git_stats_author_1=%d autor
21192129
activity.git_stats_author_n=%d autores
@@ -2324,6 +2334,8 @@ settings.hooks_desc=Os automatismos web fazem pedidos HTTP POST automaticamente
23242334
settings.webhook_deletion=Remover automatismo web
23252335
settings.webhook_deletion_desc=Remover um automatismo web elimina as configurações e o histórico de entrega desse automatismo. Quer continuar?
23262336
settings.webhook_deletion_success=O automatismo web foi removido.
2337+
settings.webhook.test_delivery=Testar o envio
2338+
settings.webhook.test_delivery_desc=Testar este automatismo web com um evento de envio falso.
23272339
settings.webhook.test_delivery_desc_disabled=Para testar este automatismo web com um evento falso, habilite-o.
23282340
settings.webhook.request=Pedido
23292341
settings.webhook.response=Resposta
@@ -3239,6 +3251,8 @@ auths.oauth2_required_claim_name_helper=Defina este nome para restringir o iníc
32393251
auths.oauth2_required_claim_value=Valor de Reivindicação obrigatório
32403252
auths.oauth2_required_claim_value_helper=Defina este valor para restringir o início de sessão desta fonte a utilizadores que tenham uma reivindicação com este nome e este valor
32413253
auths.oauth2_group_claim_name=Reivindicar nome que fornece nomes de grupo para esta fonte. (Opcional)
3254+
auths.oauth2_full_name_claim_name=Nome completo reivindicado (opcional; se for definido, o nome completo do utilizador será sempre sincronizado com este reivindicado).
3255+
auths.oauth2_ssh_public_key_claim_name=Nome reivindicado da chave pública SSH
32423256
auths.oauth2_admin_group=Valor da Reivindicação de Grupo para utilizadores administradores. (Opcional - exige a reivindicação de nome acima)
32433257
auths.oauth2_restricted_group=Valor da Reivindicação de Grupo para utilizadores restritos. (Opcional - exige a reivindicação de nome acima)
32443258
auths.oauth2_map_group_to_team=Mapear grupos reclamados em equipas da organização (opcional — requer nome de reclamação acima).

routers/web/user/setting/account.go

Lines changed: 1 addition & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,14 @@ const (
3535

3636
// Account renders change user's password, user's email and user suicide page
3737
func Account(ctx *context.Context) {
38-
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials, setting.UserFeatureDeletion) && !setting.Service.EnableNotifyMail {
38+
if user_model.IsFeatureDisabledWithLoginType(ctx.Doer, setting.UserFeatureManageCredentials, setting.UserFeatureDeletion) {
3939
ctx.NotFound(errors.New("account setting are not allowed to be changed"))
4040
return
4141
}
4242

4343
ctx.Data["Title"] = ctx.Tr("settings.account")
4444
ctx.Data["PageIsSettingsAccount"] = true
4545
ctx.Data["Email"] = ctx.Doer.Email
46-
ctx.Data["EnableNotifyMail"] = setting.Service.EnableNotifyMail
4746

4847
loadAccountData(ctx)
4948

@@ -61,7 +60,6 @@ func AccountPost(ctx *context.Context) {
6160
ctx.Data["Title"] = ctx.Tr("settings")
6261
ctx.Data["PageIsSettingsAccount"] = true
6362
ctx.Data["Email"] = ctx.Doer.Email
64-
ctx.Data["EnableNotifyMail"] = setting.Service.EnableNotifyMail
6563

6664
if ctx.HasError() {
6765
loadAccountData(ctx)
@@ -112,7 +110,6 @@ func EmailPost(ctx *context.Context) {
112110
ctx.Data["Title"] = ctx.Tr("settings")
113111
ctx.Data["PageIsSettingsAccount"] = true
114112
ctx.Data["Email"] = ctx.Doer.Email
115-
ctx.Data["EnableNotifyMail"] = setting.Service.EnableNotifyMail
116113

117114
// Make email address primary.
118115
if ctx.FormString("_method") == "PRIMARY" {
@@ -172,30 +169,6 @@ func EmailPost(ctx *context.Context) {
172169
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
173170
return
174171
}
175-
// Set Email Notification Preference
176-
if ctx.FormString("_method") == "NOTIFICATION" {
177-
preference := ctx.FormString("preference")
178-
if !(preference == user_model.EmailNotificationsEnabled ||
179-
preference == user_model.EmailNotificationsOnMention ||
180-
preference == user_model.EmailNotificationsDisabled ||
181-
preference == user_model.EmailNotificationsAndYourOwn) {
182-
log.Error("Email notifications preference change returned unrecognized option %s: %s", preference, ctx.Doer.Name)
183-
ctx.ServerError("SetEmailPreference", errors.New("option unrecognized"))
184-
return
185-
}
186-
opts := &user.UpdateOptions{
187-
EmailNotificationsPreference: optional.Some(preference),
188-
}
189-
if err := user.UpdateUser(ctx, ctx.Doer, opts); err != nil {
190-
log.Error("Set Email Notifications failed: %v", err)
191-
ctx.ServerError("UpdateUser", err)
192-
return
193-
}
194-
log.Trace("Email notifications preference made %s: %s", preference, ctx.Doer.Name)
195-
ctx.Flash.Success(ctx.Tr("settings.email_preference_set_success"))
196-
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
197-
return
198-
}
199172

200173
if ctx.HasError() {
201174
loadAccountData(ctx)
@@ -267,7 +240,6 @@ func DeleteAccount(ctx *context.Context) {
267240
ctx.Data["Title"] = ctx.Tr("settings")
268241
ctx.Data["PageIsSettingsAccount"] = true
269242
ctx.Data["Email"] = ctx.Doer.Email
270-
ctx.Data["EnableNotifyMail"] = setting.Service.EnableNotifyMail
271243

272244
if _, _, err := auth.UserSignIn(ctx, ctx.Doer.Name, ctx.FormString("password")); err != nil {
273245
switch {
@@ -342,7 +314,6 @@ func loadAccountData(ctx *context.Context) {
342314
emails[i] = &email
343315
}
344316
ctx.Data["Emails"] = emails
345-
ctx.Data["EmailNotificationsPreference"] = ctx.Doer.EmailNotificationsPreference
346317
ctx.Data["ActivationsPending"] = pendingActivation
347318
ctx.Data["CanAddEmails"] = !pendingActivation || !setting.Service.RegisterEmailConfirm
348319
ctx.Data["UserDisabledFeatures"] = user_model.DisabledFeaturesWithLoginType(ctx.Doer)
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
// Copyright 2025 The Gitea Authors. All rights reserved.
2+
// SPDX-License-Identifier: MIT
3+
4+
package setting
5+
6+
import (
7+
"errors"
8+
"net/http"
9+
10+
user_model "code.gitea.io/gitea/models/user"
11+
"code.gitea.io/gitea/modules/log"
12+
"code.gitea.io/gitea/modules/optional"
13+
"code.gitea.io/gitea/modules/setting"
14+
"code.gitea.io/gitea/modules/templates"
15+
"code.gitea.io/gitea/services/context"
16+
"code.gitea.io/gitea/services/user"
17+
)
18+
19+
const tplSettingsNotifications templates.TplName = "user/settings/notifications"
20+
21+
// Notifications render user's notifications settings
22+
func Notifications(ctx *context.Context) {
23+
if !setting.Service.EnableNotifyMail {
24+
ctx.NotFound(nil)
25+
return
26+
}
27+
28+
ctx.Data["Title"] = ctx.Tr("notifications")
29+
ctx.Data["PageIsSettingsNotifications"] = true
30+
ctx.Data["EmailNotificationsPreference"] = ctx.Doer.EmailNotificationsPreference
31+
32+
ctx.HTML(http.StatusOK, tplSettingsNotifications)
33+
}
34+
35+
// NotificationsEmailPost set user's email notification preference
36+
func NotificationsEmailPost(ctx *context.Context) {
37+
if !setting.Service.EnableNotifyMail {
38+
ctx.NotFound(nil)
39+
return
40+
}
41+
42+
preference := ctx.FormString("preference")
43+
if !(preference == user_model.EmailNotificationsEnabled ||
44+
preference == user_model.EmailNotificationsOnMention ||
45+
preference == user_model.EmailNotificationsDisabled ||
46+
preference == user_model.EmailNotificationsAndYourOwn) {
47+
log.Error("Email notifications preference change returned unrecognized option %s: %s", preference, ctx.Doer.Name)
48+
ctx.ServerError("SetEmailPreference", errors.New("option unrecognized"))
49+
return
50+
}
51+
opts := &user.UpdateOptions{
52+
EmailNotificationsPreference: optional.Some(preference),
53+
}
54+
if err := user.UpdateUser(ctx, ctx.Doer, opts); err != nil {
55+
log.Error("Set Email Notifications failed: %v", err)
56+
ctx.ServerError("UpdateUser", err)
57+
return
58+
}
59+
log.Trace("Email notifications preference made %s: %s", preference, ctx.Doer.Name)
60+
ctx.Flash.Success(ctx.Tr("settings.email_preference_set_success"))
61+
ctx.Redirect(setting.AppSubURL + "/user/settings/notifications")
62+
}

0 commit comments

Comments
 (0)