You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

579 lines
17 KiB

9 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "strings"
  7. "time"
  8. "code.gitea.io/git"
  9. "code.gitea.io/gitea/models"
  10. "code.gitea.io/gitea/modules/auth"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/context"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/modules/util"
  16. "code.gitea.io/gitea/routers/utils"
  17. )
  18. const (
  19. tplSettingsOptions base.TplName = "repo/settings/options"
  20. tplCollaboration base.TplName = "repo/settings/collaboration"
  21. tplBranches base.TplName = "repo/settings/branches"
  22. tplGithooks base.TplName = "repo/settings/githooks"
  23. tplGithookEdit base.TplName = "repo/settings/githook_edit"
  24. tplDeployKeys base.TplName = "repo/settings/deploy_keys"
  25. tplProtectedBranch base.TplName = "repo/settings/protected_branch"
  26. )
  27. // Settings show a repository's settings page
  28. func Settings(ctx *context.Context) {
  29. ctx.Data["Title"] = ctx.Tr("repo.settings")
  30. ctx.Data["PageIsSettingsOptions"] = true
  31. ctx.HTML(200, tplSettingsOptions)
  32. }
  33. // SettingsPost response for changes of a repository
  34. func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
  35. ctx.Data["Title"] = ctx.Tr("repo.settings")
  36. ctx.Data["PageIsSettingsOptions"] = true
  37. repo := ctx.Repo.Repository
  38. switch ctx.Query("action") {
  39. case "update":
  40. if ctx.HasError() {
  41. ctx.HTML(200, tplSettingsOptions)
  42. return
  43. }
  44. isNameChanged := false
  45. oldRepoName := repo.Name
  46. newRepoName := form.RepoName
  47. // Check if repository name has been changed.
  48. if repo.LowerName != strings.ToLower(newRepoName) {
  49. isNameChanged = true
  50. if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil {
  51. ctx.Data["Err_RepoName"] = true
  52. switch {
  53. case models.IsErrRepoAlreadyExist(err):
  54. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
  55. case models.IsErrNameReserved(err):
  56. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplSettingsOptions, &form)
  57. case models.IsErrNamePatternNotAllowed(err):
  58. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form)
  59. default:
  60. ctx.ServerError("ChangeRepositoryName", err)
  61. }
  62. return
  63. }
  64. err := models.NewRepoRedirect(ctx.Repo.Owner.ID, repo.ID, repo.Name, newRepoName)
  65. if err != nil {
  66. ctx.ServerError("NewRepoRedirect", err)
  67. return
  68. }
  69. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  70. }
  71. // In case it's just a case change.
  72. repo.Name = newRepoName
  73. repo.LowerName = strings.ToLower(newRepoName)
  74. repo.Description = form.Description
  75. repo.Website = form.Website
  76. // Visibility of forked repository is forced sync with base repository.
  77. if repo.IsFork {
  78. form.Private = repo.BaseRepo.IsPrivate
  79. }
  80. visibilityChanged := repo.IsPrivate != form.Private
  81. repo.IsPrivate = form.Private
  82. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  83. ctx.ServerError("UpdateRepository", err)
  84. return
  85. }
  86. log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  87. if isNameChanged {
  88. if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil {
  89. log.Error(4, "RenameRepoAction: %v", err)
  90. }
  91. }
  92. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  93. ctx.Redirect(repo.Link() + "/settings")
  94. case "mirror":
  95. if !repo.IsMirror {
  96. ctx.NotFound("", nil)
  97. return
  98. }
  99. interval, err := time.ParseDuration(form.Interval)
  100. if err != nil || interval < setting.Mirror.MinInterval {
  101. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  102. } else {
  103. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  104. ctx.Repo.Mirror.Interval = interval
  105. ctx.Repo.Mirror.NextUpdateUnix = util.TimeStampNow().AddDuration(interval)
  106. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  107. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  108. return
  109. }
  110. }
  111. if err := ctx.Repo.Mirror.SaveAddress(form.MirrorAddress); err != nil {
  112. ctx.ServerError("SaveAddress", err)
  113. return
  114. }
  115. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  116. ctx.Redirect(repo.Link() + "/settings")
  117. case "mirror-sync":
  118. if !repo.IsMirror {
  119. ctx.NotFound("", nil)
  120. return
  121. }
  122. go models.MirrorQueue.Add(repo.ID)
  123. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  124. ctx.Redirect(repo.Link() + "/settings")
  125. case "advanced":
  126. var units []models.RepoUnit
  127. for _, tp := range models.MustRepoUnits {
  128. units = append(units, models.RepoUnit{
  129. RepoID: repo.ID,
  130. Type: tp,
  131. Config: new(models.UnitConfig),
  132. })
  133. }
  134. if form.EnableWiki {
  135. if form.EnableExternalWiki {
  136. if !strings.HasPrefix(form.ExternalWikiURL, "http://") && !strings.HasPrefix(form.ExternalWikiURL, "https://") {
  137. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  138. ctx.Redirect(repo.Link() + "/settings")
  139. return
  140. }
  141. units = append(units, models.RepoUnit{
  142. RepoID: repo.ID,
  143. Type: models.UnitTypeExternalWiki,
  144. Config: &models.ExternalWikiConfig{
  145. ExternalWikiURL: form.ExternalWikiURL,
  146. },
  147. })
  148. } else {
  149. units = append(units, models.RepoUnit{
  150. RepoID: repo.ID,
  151. Type: models.UnitTypeWiki,
  152. Config: new(models.UnitConfig),
  153. })
  154. }
  155. }
  156. if form.EnableIssues {
  157. if form.EnableExternalTracker {
  158. if !strings.HasPrefix(form.ExternalTrackerURL, "http://") && !strings.HasPrefix(form.ExternalTrackerURL, "https://") {
  159. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  160. ctx.Redirect(repo.Link() + "/settings")
  161. return
  162. }
  163. units = append(units, models.RepoUnit{
  164. RepoID: repo.ID,
  165. Type: models.UnitTypeExternalTracker,
  166. Config: &models.ExternalTrackerConfig{
  167. ExternalTrackerURL: form.ExternalTrackerURL,
  168. ExternalTrackerFormat: form.TrackerURLFormat,
  169. ExternalTrackerStyle: form.TrackerIssueStyle,
  170. },
  171. })
  172. } else {
  173. units = append(units, models.RepoUnit{
  174. RepoID: repo.ID,
  175. Type: models.UnitTypeIssues,
  176. Config: &models.IssuesConfig{
  177. EnableTimetracker: form.EnableTimetracker,
  178. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  179. },
  180. })
  181. }
  182. }
  183. if form.EnablePulls {
  184. units = append(units, models.RepoUnit{
  185. RepoID: repo.ID,
  186. Type: models.UnitTypePullRequests,
  187. Config: &models.PullRequestsConfig{
  188. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  189. AllowMerge: form.PullsAllowMerge,
  190. AllowRebase: form.PullsAllowRebase,
  191. AllowSquash: form.PullsAllowSquash,
  192. },
  193. })
  194. }
  195. if err := models.UpdateRepositoryUnits(repo, units); err != nil {
  196. ctx.ServerError("UpdateRepositoryUnits", err)
  197. return
  198. }
  199. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  200. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  201. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  202. case "convert":
  203. if !ctx.Repo.IsOwner() {
  204. ctx.Error(404)
  205. return
  206. }
  207. if repo.Name != form.RepoName {
  208. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  209. return
  210. }
  211. if !repo.IsMirror {
  212. ctx.Error(404)
  213. return
  214. }
  215. repo.IsMirror = false
  216. if _, err := models.CleanUpMigrateInfo(repo); err != nil {
  217. ctx.ServerError("CleanUpMigrateInfo", err)
  218. return
  219. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  220. ctx.ServerError("DeleteMirrorByRepoID", err)
  221. return
  222. }
  223. log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  224. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  225. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
  226. case "transfer":
  227. if !ctx.Repo.IsOwner() {
  228. ctx.Error(404)
  229. return
  230. }
  231. if repo.Name != form.RepoName {
  232. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  233. return
  234. }
  235. newOwner := ctx.Query("new_owner_name")
  236. isExist, err := models.IsUserExist(0, newOwner)
  237. if err != nil {
  238. ctx.ServerError("IsUserExist", err)
  239. return
  240. } else if !isExist {
  241. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  242. return
  243. }
  244. if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
  245. if models.IsErrRepoAlreadyExist(err) {
  246. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  247. } else {
  248. ctx.ServerError("TransferOwnership", err)
  249. }
  250. return
  251. }
  252. log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  253. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
  254. ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
  255. case "delete":
  256. if !ctx.Repo.IsOwner() {
  257. ctx.Error(404)
  258. return
  259. }
  260. if repo.Name != form.RepoName {
  261. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  262. return
  263. }
  264. if err := models.DeleteRepository(ctx.User, ctx.Repo.Owner.ID, repo.ID); err != nil {
  265. ctx.ServerError("DeleteRepository", err)
  266. return
  267. }
  268. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  269. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  270. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  271. case "delete-wiki":
  272. if !ctx.Repo.IsOwner() {
  273. ctx.Error(404)
  274. return
  275. }
  276. if repo.Name != form.RepoName {
  277. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  278. return
  279. }
  280. repo.DeleteWiki()
  281. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  282. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  283. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  284. default:
  285. ctx.NotFound("", nil)
  286. }
  287. }
  288. // Collaboration render a repository's collaboration page
  289. func Collaboration(ctx *context.Context) {
  290. ctx.Data["Title"] = ctx.Tr("repo.settings")
  291. ctx.Data["PageIsSettingsCollaboration"] = true
  292. users, err := ctx.Repo.Repository.GetCollaborators()
  293. if err != nil {
  294. ctx.ServerError("GetCollaborators", err)
  295. return
  296. }
  297. ctx.Data["Collaborators"] = users
  298. ctx.HTML(200, tplCollaboration)
  299. }
  300. // CollaborationPost response for actions for a collaboration of a repository
  301. func CollaborationPost(ctx *context.Context) {
  302. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  303. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  304. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  305. return
  306. }
  307. u, err := models.GetUserByName(name)
  308. if err != nil {
  309. if models.IsErrUserNotExist(err) {
  310. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  311. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  312. } else {
  313. ctx.ServerError("GetUserByName", err)
  314. }
  315. return
  316. }
  317. // Organization is not allowed to be added as a collaborator.
  318. if u.IsOrganization() {
  319. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  320. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  321. return
  322. }
  323. // Check if user is organization member.
  324. if ctx.Repo.Owner.IsOrganization() {
  325. isMember, err := ctx.Repo.Owner.IsOrgMember(u.ID)
  326. if err != nil {
  327. ctx.ServerError("IsOrgMember", err)
  328. return
  329. } else if isMember {
  330. ctx.Flash.Info(ctx.Tr("repo.settings.user_is_org_member"))
  331. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  332. return
  333. }
  334. }
  335. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  336. ctx.ServerError("AddCollaborator", err)
  337. return
  338. }
  339. if setting.Service.EnableNotifyMail {
  340. models.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  341. }
  342. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  343. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  344. }
  345. // ChangeCollaborationAccessMode response for changing access of a collaboration
  346. func ChangeCollaborationAccessMode(ctx *context.Context) {
  347. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  348. ctx.QueryInt64("uid"),
  349. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  350. log.Error(4, "ChangeCollaborationAccessMode: %v", err)
  351. }
  352. }
  353. // DeleteCollaboration delete a collaboration for a repository
  354. func DeleteCollaboration(ctx *context.Context) {
  355. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  356. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  357. } else {
  358. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  359. }
  360. ctx.JSON(200, map[string]interface{}{
  361. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  362. })
  363. }
  364. // parseOwnerAndRepo get repos by owner
  365. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  366. owner, err := models.GetUserByName(ctx.Params(":username"))
  367. if err != nil {
  368. if models.IsErrUserNotExist(err) {
  369. ctx.NotFound("GetUserByName", err)
  370. } else {
  371. ctx.ServerError("GetUserByName", err)
  372. }
  373. return nil, nil
  374. }
  375. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  376. if err != nil {
  377. if models.IsErrRepoNotExist(err) {
  378. ctx.NotFound("GetRepositoryByName", err)
  379. } else {
  380. ctx.ServerError("GetRepositoryByName", err)
  381. }
  382. return nil, nil
  383. }
  384. return owner, repo
  385. }
  386. // GitHooks hooks of a repository
  387. func GitHooks(ctx *context.Context) {
  388. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  389. ctx.Data["PageIsSettingsGitHooks"] = true
  390. hooks, err := ctx.Repo.GitRepo.Hooks()
  391. if err != nil {
  392. ctx.ServerError("Hooks", err)
  393. return
  394. }
  395. ctx.Data["Hooks"] = hooks
  396. ctx.HTML(200, tplGithooks)
  397. }
  398. // GitHooksEdit render for editing a hook of repository page
  399. func GitHooksEdit(ctx *context.Context) {
  400. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  401. ctx.Data["PageIsSettingsGitHooks"] = true
  402. name := ctx.Params(":name")
  403. hook, err := ctx.Repo.GitRepo.GetHook(name)
  404. if err != nil {
  405. if err == git.ErrNotValidHook {
  406. ctx.NotFound("GetHook", err)
  407. } else {
  408. ctx.ServerError("GetHook", err)
  409. }
  410. return
  411. }
  412. ctx.Data["Hook"] = hook
  413. ctx.HTML(200, tplGithookEdit)
  414. }
  415. // GitHooksEditPost response for editing a git hook of a repository
  416. func GitHooksEditPost(ctx *context.Context) {
  417. name := ctx.Params(":name")
  418. hook, err := ctx.Repo.GitRepo.GetHook(name)
  419. if err != nil {
  420. if err == git.ErrNotValidHook {
  421. ctx.NotFound("GetHook", err)
  422. } else {
  423. ctx.ServerError("GetHook", err)
  424. }
  425. return
  426. }
  427. hook.Content = ctx.Query("content")
  428. if err = hook.Update(); err != nil {
  429. ctx.ServerError("hook.Update", err)
  430. return
  431. }
  432. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  433. }
  434. // DeployKeys render the deploy keys list of a repository page
  435. func DeployKeys(ctx *context.Context) {
  436. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  437. ctx.Data["PageIsSettingsKeys"] = true
  438. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  439. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  440. if err != nil {
  441. ctx.ServerError("ListDeployKeys", err)
  442. return
  443. }
  444. ctx.Data["Deploykeys"] = keys
  445. ctx.HTML(200, tplDeployKeys)
  446. }
  447. // DeployKeysPost response for adding a deploy key of a repository
  448. func DeployKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  449. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  450. ctx.Data["PageIsSettingsKeys"] = true
  451. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  452. if err != nil {
  453. ctx.ServerError("ListDeployKeys", err)
  454. return
  455. }
  456. ctx.Data["Deploykeys"] = keys
  457. if ctx.HasError() {
  458. ctx.HTML(200, tplDeployKeys)
  459. return
  460. }
  461. content, err := models.CheckPublicKeyString(form.Content)
  462. if err != nil {
  463. if models.IsErrSSHDisabled(err) {
  464. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  465. } else if models.IsErrKeyUnableVerify(err) {
  466. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  467. } else {
  468. ctx.Data["HasError"] = true
  469. ctx.Data["Err_Content"] = true
  470. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  471. }
  472. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  473. return
  474. }
  475. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  476. if err != nil {
  477. ctx.Data["HasError"] = true
  478. switch {
  479. case models.IsErrKeyAlreadyExist(err):
  480. ctx.Data["Err_Content"] = true
  481. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  482. case models.IsErrKeyNameAlreadyUsed(err):
  483. ctx.Data["Err_Title"] = true
  484. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  485. default:
  486. ctx.ServerError("AddDeployKey", err)
  487. }
  488. return
  489. }
  490. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  491. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  492. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  493. }
  494. // DeleteDeployKey response for deleting a deploy key
  495. func DeleteDeployKey(ctx *context.Context) {
  496. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  497. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  498. } else {
  499. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  500. }
  501. ctx.JSON(200, map[string]interface{}{
  502. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  503. })
  504. }