0
0
Fork 0
mirror of https://github.com/go-gitea/gitea synced 2024-11-12 13:01:19 +01:00

Convert all API handers to use *context.APIContext

This commit is contained in:
Unknwon 2016-03-13 18:49:16 -04:00
parent db4da7beec
commit dd6faf7f9b
20 changed files with 204 additions and 196 deletions

View file

@ -206,12 +206,6 @@ func runWeb(ctx *cli.Context) {
Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost) Post(bindIgnErr(auth.InstallForm{}), routers.InstallPost)
m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues) m.Get("/^:type(issues|pulls)$", reqSignIn, user.Issues)
// ***** START: API *****
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
}, ignSignIn)
// ***** END: API *****
// ***** START: User ***** // ***** START: User *****
m.Group("/user", func() { m.Group("/user", func() {
m.Get("/login", user.SignIn) m.Get("/login", user.SignIn)
@ -550,6 +544,10 @@ func runWeb(ctx *cli.Context) {
}) })
// ***** END: Repository ***** // ***** END: Repository *****
m.Group("/api", func() {
apiv1.RegisterRoutes(m)
}, ignSignIn)
// robots.txt // robots.txt
m.Get("/robots.txt", func(ctx *context.Context) { m.Get("/robots.txt", func(ctx *context.Context) {
if setting.HasRobotsTxt { if setting.HasRobotsTxt {

View file

@ -6,12 +6,35 @@ package context
import ( import (
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/log"
) )
type APIContext struct { type APIContext struct {
*Context *Context
} }
// Error responses error message to client with given message.
// If status is 500, also it prints error to log.
func (ctx *APIContext) Error(status int, title string, obj interface{}) {
var message string
if err, ok := obj.(error); ok {
message = err.Error()
} else {
message = obj.(string)
}
if status == 500 {
log.Error(4, "%s: %s", title, message)
}
ctx.JSON(status, map[string]string{
"message": message,
"url": base.DOC_URL,
})
}
func APIContexter() macaron.Handler { func APIContexter() macaron.Handler {
return func(c *Context) { return func(c *Context) {
ctx := &APIContext{ ctx := &APIContext{

View file

@ -52,7 +52,9 @@ func Toggle(options *ToggleOptions) macaron.Handler {
if !ctx.IsSigned { if !ctx.IsSigned {
// Restrict API calls with error message. // Restrict API calls with error message.
if auth.IsAPIPath(ctx.Req.URL.Path) { if auth.IsAPIPath(ctx.Req.URL.Path) {
ctx.APIError(403, "", "Only signed in user is allowed to call APIs.") ctx.JSON(403, map[string]string{
"message": "Only signed in user is allowed to call APIs.",
})
return return
} }

View file

@ -112,25 +112,6 @@ func (ctx *Context) HandleText(status int, title string) {
ctx.PlainText(status, []byte(title)) ctx.PlainText(status, []byte(title))
} }
// APIError logs error with title if status is 500.
func (ctx *Context) APIError(status int, title string, obj interface{}) {
var message string
if err, ok := obj.(error); ok {
message = err.Error()
} else {
message = obj.(string)
}
if status == 500 {
log.Error(4, "%s: %s", title, message)
}
ctx.JSON(status, map[string]string{
"message": message,
"url": base.DOC_URL,
})
}
func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) { func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
modtime := time.Now() modtime := time.Now()
for _, p := range params { for _, p := range params {

View file

@ -14,7 +14,7 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization // https://github.com/gogits/go-gogs-client/wiki/Administration-Organizations#create-a-new-organization
func CreateOrg(ctx *context.Context, form api.CreateOrgOption) { func CreateOrg(ctx *context.APIContext, form api.CreateOrgOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -33,9 +33,9 @@ func CreateOrg(ctx *context.Context, form api.CreateOrgOption) {
if models.IsErrUserAlreadyExist(err) || if models.IsErrUserAlreadyExist(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.APIError(422, "CreateOrganization", err) ctx.Error(422, "CreateOrganization", err)
} else { } else {
ctx.APIError(500, "CreateOrganization", err) ctx.Error(500, "CreateOrganization", err)
} }
return return
} }

View file

@ -13,7 +13,7 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository // https://github.com/gogits/go-gogs-client/wiki/Administration-Repositories#create-a-new-repository
func CreateRepo(ctx *context.Context, form api.CreateRepoOption) { func CreateRepo(ctx *context.APIContext, form api.CreateRepoOption) {
owner := user.GetUserByParams(ctx) owner := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return

View file

@ -16,7 +16,7 @@ import (
"github.com/gogits/gogs/routers/api/v1/user" "github.com/gogits/gogs/routers/api/v1/user"
) )
func parseLoginSource(ctx *context.Context, u *models.User, sourceID int64, loginName string) { func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, loginName string) {
if sourceID == 0 { if sourceID == 0 {
return return
} }
@ -24,9 +24,9 @@ func parseLoginSource(ctx *context.Context, u *models.User, sourceID int64, logi
source, err := models.GetLoginSourceByID(sourceID) source, err := models.GetLoginSourceByID(sourceID)
if err != nil { if err != nil {
if models.IsErrAuthenticationNotExist(err) { if models.IsErrAuthenticationNotExist(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "GetLoginSourceByID", err) ctx.Error(500, "GetLoginSourceByID", err)
} }
return return
} }
@ -37,7 +37,7 @@ func parseLoginSource(ctx *context.Context, u *models.User, sourceID int64, logi
} }
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-new-user
func CreateUser(ctx *context.Context, form api.CreateUserOption) { func CreateUser(ctx *context.APIContext, form api.CreateUserOption) {
u := &models.User{ u := &models.User{
Name: form.Username, Name: form.Username,
Email: form.Email, Email: form.Email,
@ -56,9 +56,9 @@ func CreateUser(ctx *context.Context, form api.CreateUserOption) {
models.IsErrEmailAlreadyUsed(err) || models.IsErrEmailAlreadyUsed(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "CreateUser", err) ctx.Error(500, "CreateUser", err)
} }
return return
} }
@ -66,14 +66,14 @@ func CreateUser(ctx *context.Context, form api.CreateUserOption) {
// Send e-mail notification. // Send e-mail notification.
if form.SendNotify && setting.MailService != nil { if form.SendNotify && setting.MailService != nil {
mailer.SendRegisterNotifyMail(ctx.Context, u) mailer.SendRegisterNotifyMail(ctx.Context.Context, u)
} }
ctx.JSON(201, convert.ToApiUser(u)) ctx.JSON(201, convert.ToApiUser(u))
} }
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#edit-an-existing-user
func EditUser(ctx *context.Context, form api.EditUserOption) { func EditUser(ctx *context.APIContext, form api.EditUserOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -110,9 +110,9 @@ func EditUser(ctx *context.Context, form api.EditUserOption) {
if err := models.UpdateUser(u); err != nil { if err := models.UpdateUser(u); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "UpdateUser", err) ctx.Error(500, "UpdateUser", err)
} }
return return
} }
@ -122,7 +122,7 @@ func EditUser(ctx *context.Context, form api.EditUserOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#delete-a-user
func DeleteUser(ctx *context.Context) { func DeleteUser(ctx *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -131,9 +131,9 @@ func DeleteUser(ctx *context.Context) {
if err := models.DeleteUser(u); err != nil { if err := models.DeleteUser(u); err != nil {
if models.IsErrUserOwnRepos(err) || if models.IsErrUserOwnRepos(err) ||
models.IsErrUserHasOrgs(err) { models.IsErrUserHasOrgs(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "DeleteUser", err) ctx.Error(500, "DeleteUser", err)
} }
return return
} }
@ -143,7 +143,7 @@ func DeleteUser(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user // https://github.com/gogits/go-gogs-client/wiki/Administration-Users#create-a-public-key-for-user
func CreatePublicKey(ctx *context.Context, form api.CreateKeyOption) { func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return

View file

@ -23,7 +23,7 @@ import (
) )
func RepoAssignment() macaron.Handler { func RepoAssignment() macaron.Handler {
return func(ctx *context.Context) { return func(ctx *context.APIContext) {
userName := ctx.Params(":username") userName := ctx.Params(":username")
repoName := ctx.Params(":reponame") repoName := ctx.Params(":reponame")
@ -39,9 +39,9 @@ func RepoAssignment() macaron.Handler {
owner, err = models.GetUserByName(userName) owner, err = models.GetUserByName(userName)
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetUserByName", err) ctx.Error(500, "GetUserByName", err)
} }
return return
} }
@ -52,19 +52,19 @@ func RepoAssignment() macaron.Handler {
repo, err := models.GetRepositoryByName(owner.Id, repoName) repo, err := models.GetRepositoryByName(owner.Id, repoName)
if err != nil { if err != nil {
if models.IsErrRepoNotExist(err) { if models.IsErrRepoNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetRepositoryByName", err) ctx.Error(500, "GetRepositoryByName", err)
} }
return return
} else if err = repo.GetOwner(); err != nil { } else if err = repo.GetOwner(); err != nil {
ctx.APIError(500, "GetOwner", err) ctx.Error(500, "GetOwner", err)
return return
} }
mode, err := models.AccessLevel(ctx.User, repo) mode, err := models.AccessLevel(ctx.User, repo)
if err != nil { if err != nil {
ctx.APIError(500, "AccessLevel", err) ctx.Error(500, "AccessLevel", err)
return return
} }
@ -72,7 +72,7 @@ func RepoAssignment() macaron.Handler {
// Check access. // Check access.
if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE {
ctx.Error(404) ctx.Status(404)
return return
} }
@ -193,6 +193,10 @@ func RegisterRoutes(m *macaron.Macaron) {
m.Combo("/:id").Get(repo.GetDeployKey). m.Combo("/:id").Get(repo.GetDeployKey).
Delete(repo.DeleteDeploykey) Delete(repo.DeleteDeploykey)
}) })
m.Group("/issue", func() {
m.Combo("").Get().Post()
m.Combo("/:index").Get().Patch()
})
}, RepoAssignment()) }, RepoAssignment())
}, ReqToken()) }, ReqToken())
@ -218,5 +222,5 @@ func RegisterRoutes(m *macaron.Macaron) {
}) })
}) })
}, ReqAdmin()) }, ReqAdmin())
}) }, context.APIContexter())
} }

View file

@ -12,9 +12,9 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-an-arbitrary-markdown-document
func Markdown(ctx *context.Context, form api.MarkdownOption) { func Markdown(ctx *context.APIContext, form api.MarkdownOption) {
if ctx.HasApiError() { if ctx.HasApiError() {
ctx.APIError(422, "", ctx.GetErrMsg()) ctx.Error(422, "", ctx.GetErrMsg())
return return
} }
@ -32,10 +32,10 @@ func Markdown(ctx *context.Context, form api.MarkdownOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode // https://github.com/gogits/go-gogs-client/wiki/Miscellaneous#render-a-markdown-document-in-raw-mode
func MarkdownRaw(ctx *context.Context) { func MarkdownRaw(ctx *context.APIContext) {
body, err := ctx.Req.Body().Bytes() body, err := ctx.Req.Body().Bytes()
if err != nil { if err != nil {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
return return
} }
ctx.Write(markdown.RenderRaw(body, "")) ctx.Write(markdown.RenderRaw(body, ""))

View file

@ -13,9 +13,9 @@ import (
"github.com/gogits/gogs/routers/api/v1/user" "github.com/gogits/gogs/routers/api/v1/user"
) )
func listUserOrgs(ctx *context.Context, u *models.User, all bool) { func listUserOrgs(ctx *context.APIContext, u *models.User, all bool) {
if err := u.GetOrganizations(all); err != nil { if err := u.GetOrganizations(all); err != nil {
ctx.APIError(500, "GetOrganizations", err) ctx.Error(500, "GetOrganizations", err)
return return
} }
@ -27,12 +27,12 @@ func listUserOrgs(ctx *context.Context, u *models.User, all bool) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-your-organizations
func ListMyOrgs(ctx *context.Context) { func ListMyOrgs(ctx *context.APIContext) {
listUserOrgs(ctx, ctx.User, true) listUserOrgs(ctx, ctx.User, true)
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations // https://github.com/gogits/go-gogs-client/wiki/Organizations#list-user-organizations
func ListUserOrgs(ctx *context.Context) { func ListUserOrgs(ctx *context.APIContext) {
u := user.GetUserByParams(ctx) u := user.GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -41,7 +41,7 @@ func ListUserOrgs(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization // https://github.com/gogits/go-gogs-client/wiki/Organizations#get-an-organization
func Get(ctx *context.Context) { func Get(ctx *context.APIContext) {
org := user.GetUserByParamsName(ctx, ":orgname") org := user.GetUserByParamsName(ctx, ":orgname")
if ctx.Written() { if ctx.Written() {
return return
@ -50,14 +50,14 @@ func Get(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization // https://github.com/gogits/go-gogs-client/wiki/Organizations#edit-an-organization
func Edit(ctx *context.Context, form api.EditOrgOption) { func Edit(ctx *context.APIContext, form api.EditOrgOption) {
org := user.GetUserByParamsName(ctx, ":orgname") org := user.GetUserByParamsName(ctx, ":orgname")
if ctx.Written() { if ctx.Written() {
return return
} }
if !org.IsOwnedBy(ctx.User.Id) { if !org.IsOwnedBy(ctx.User.Id) {
ctx.Error(403) ctx.Status(403)
return return
} }
@ -66,7 +66,7 @@ func Edit(ctx *context.Context, form api.EditOrgOption) {
org.Website = form.Website org.Website = form.Website
org.Location = form.Location org.Location = form.Location
if err := models.UpdateUser(org); err != nil { if err := models.UpdateUser(org); err != nil {
ctx.APIError(500, "UpdateUser", err) ctx.Error(500, "UpdateUser", err)
return return
} }

View file

@ -12,16 +12,16 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch // https://github.com/gogits/go-gogs-client/wiki/Repositories#get-branch
func GetBranch(ctx *context.Context) { func GetBranch(ctx *context.APIContext) {
branch, err := ctx.Repo.Repository.GetBranch(ctx.Params(":branchname")) branch, err := ctx.Repo.Repository.GetBranch(ctx.Params(":branchname"))
if err != nil { if err != nil {
ctx.APIError(500, "GetBranch", err) ctx.Error(500, "GetBranch", err)
return return
} }
c, err := branch.GetCommit() c, err := branch.GetCommit()
if err != nil { if err != nil {
ctx.APIError(500, "GetCommit", err) ctx.Error(500, "GetCommit", err)
return return
} }
@ -29,10 +29,10 @@ func GetBranch(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-branches
func ListBranches(ctx *context.Context) { func ListBranches(ctx *context.APIContext) {
branches, err := ctx.Repo.Repository.GetBranches() branches, err := ctx.Repo.Repository.GetBranches()
if err != nil { if err != nil {
ctx.APIError(500, "GetBranches", err) ctx.Error(500, "GetBranches", err)
return return
} }
@ -40,7 +40,7 @@ func ListBranches(ctx *context.Context) {
for i := range branches { for i := range branches {
c, err := branches[i].GetCommit() c, err := branches[i].GetCommit()
if err != nil { if err != nil {
ctx.APIError(500, "GetCommit", err) ctx.Error(500, "GetCommit", err)
return return
} }
apiBranches[i] = convert.ToApiBranch(branches[i], c) apiBranches[i] = convert.ToApiBranch(branches[i], c)

View file

@ -13,35 +13,35 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-raw-content
func GetRawFile(ctx *context.Context) { func GetRawFile(ctx *context.APIContext) {
if !ctx.Repo.HasAccess() { if !ctx.Repo.HasAccess() {
ctx.Error(404) ctx.Status(404)
return return
} }
blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName) blob, err := ctx.Repo.Commit.GetBlobByPath(ctx.Repo.TreeName)
if err != nil { if err != nil {
if git.IsErrNotExist(err) { if git.IsErrNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetBlobByPath", err) ctx.Error(500, "GetBlobByPath", err)
} }
return return
} }
if err = repo.ServeBlob(ctx, blob); err != nil { if err = repo.ServeBlob(ctx.Context, blob); err != nil {
ctx.APIError(500, "ServeBlob", err) ctx.Error(500, "ServeBlob", err)
} }
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive // https://github.com/gogits/go-gogs-client/wiki/Repositories-Contents#download-archive
func GetArchive(ctx *context.Context) { func GetArchive(ctx *context.APIContext) {
repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame")) repoPath := models.RepoPath(ctx.Params(":username"), ctx.Params(":reponame"))
gitRepo, err := git.OpenRepository(repoPath) gitRepo, err := git.OpenRepository(repoPath)
if err != nil { if err != nil {
ctx.APIError(500, "OpenRepository", err) ctx.Error(500, "OpenRepository", err)
return return
} }
ctx.Repo.GitRepo = gitRepo ctx.Repo.GitRepo = gitRepo
repo.Download(ctx) repo.Download(ctx.Context)
} }

View file

@ -17,10 +17,10 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-hooks
func ListHooks(ctx *context.Context) { func ListHooks(ctx *context.APIContext) {
hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID) hooks, err := models.GetWebhooksByRepoID(ctx.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.APIError(500, "GetWebhooksByRepoID", err) ctx.Error(500, "GetWebhooksByRepoID", err)
return return
} }
@ -33,19 +33,19 @@ func ListHooks(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#create-a-hook // https://github.com/gogits/go-gogs-client/wiki/Repositories#create-a-hook
func CreateHook(ctx *context.Context, form api.CreateHookOption) { func CreateHook(ctx *context.APIContext, form api.CreateHookOption) {
if !models.IsValidHookTaskType(form.Type) { if !models.IsValidHookTaskType(form.Type) {
ctx.APIError(422, "", "Invalid hook type") ctx.Error(422, "", "Invalid hook type")
return return
} }
for _, name := range []string{"url", "content_type"} { for _, name := range []string{"url", "content_type"} {
if _, ok := form.Config[name]; !ok { if _, ok := form.Config[name]; !ok {
ctx.APIError(422, "", "Missing config option: "+name) ctx.Error(422, "", "Missing config option: "+name)
return return
} }
} }
if !models.IsValidHookContentType(form.Config["content_type"]) { if !models.IsValidHookContentType(form.Config["content_type"]) {
ctx.APIError(422, "", "Invalid content type") ctx.Error(422, "", "Invalid content type")
return return
} }
@ -70,7 +70,7 @@ func CreateHook(ctx *context.Context, form api.CreateHookOption) {
if w.HookTaskType == models.SLACK { if w.HookTaskType == models.SLACK {
channel, ok := form.Config["channel"] channel, ok := form.Config["channel"]
if !ok { if !ok {
ctx.APIError(422, "", "Missing config option: channel") ctx.Error(422, "", "Missing config option: channel")
return return
} }
meta, err := json.Marshal(&models.SlackMeta{ meta, err := json.Marshal(&models.SlackMeta{
@ -80,17 +80,17 @@ func CreateHook(ctx *context.Context, form api.CreateHookOption) {
Color: form.Config["color"], Color: form.Config["color"],
}) })
if err != nil { if err != nil {
ctx.APIError(500, "slack: JSON marshal failed", err) ctx.Error(500, "slack: JSON marshal failed", err)
return return
} }
w.Meta = string(meta) w.Meta = string(meta)
} }
if err := w.UpdateEvent(); err != nil { if err := w.UpdateEvent(); err != nil {
ctx.APIError(500, "UpdateEvent", err) ctx.Error(500, "UpdateEvent", err)
return return
} else if err := models.CreateWebhook(w); err != nil { } else if err := models.CreateWebhook(w); err != nil {
ctx.APIError(500, "CreateWebhook", err) ctx.Error(500, "CreateWebhook", err)
return return
} }
@ -98,13 +98,13 @@ func CreateHook(ctx *context.Context, form api.CreateHookOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook // https://github.com/gogits/go-gogs-client/wiki/Repositories#edit-a-hook
func EditHook(ctx *context.Context, form api.EditHookOption) { func EditHook(ctx *context.APIContext, form api.EditHookOption) {
w, err := models.GetWebhookByID(ctx.ParamsInt64(":id")) w, err := models.GetWebhookByID(ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrWebhookNotExist(err) { if models.IsErrWebhookNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetWebhookByID", err) ctx.Error(500, "GetWebhookByID", err)
} }
return return
} }
@ -115,7 +115,7 @@ func EditHook(ctx *context.Context, form api.EditHookOption) {
} }
if ct, ok := form.Config["content_type"]; ok { if ct, ok := form.Config["content_type"]; ok {
if !models.IsValidHookContentType(ct) { if !models.IsValidHookContentType(ct) {
ctx.APIError(422, "", "Invalid content type") ctx.Error(422, "", "Invalid content type")
return return
} }
w.ContentType = models.ToHookContentType(ct) w.ContentType = models.ToHookContentType(ct)
@ -130,7 +130,7 @@ func EditHook(ctx *context.Context, form api.EditHookOption) {
Color: form.Config["color"], Color: form.Config["color"],
}) })
if err != nil { if err != nil {
ctx.APIError(500, "slack: JSON marshal failed", err) ctx.Error(500, "slack: JSON marshal failed", err)
return return
} }
w.Meta = string(meta) w.Meta = string(meta)
@ -148,7 +148,7 @@ func EditHook(ctx *context.Context, form api.EditHookOption) {
w.Create = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE)) w.Create = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_CREATE))
w.Push = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH)) w.Push = com.IsSliceContainsStr(form.Events, string(models.HOOK_EVENT_PUSH))
if err = w.UpdateEvent(); err != nil { if err = w.UpdateEvent(); err != nil {
ctx.APIError(500, "UpdateEvent", err) ctx.Error(500, "UpdateEvent", err)
return return
} }
@ -157,7 +157,7 @@ func EditHook(ctx *context.Context, form api.EditHookOption) {
} }
if err := models.UpdateWebhook(w); err != nil { if err := models.UpdateWebhook(w); err != nil {
ctx.APIError(500, "UpdateWebhook", err) ctx.Error(500, "UpdateWebhook", err)
return return
} }

View file

@ -20,10 +20,10 @@ func composeDeployKeysAPILink(repoPath string) string {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#list-deploy-keys
func ListDeployKeys(ctx *context.Context) { func ListDeployKeys(ctx *context.APIContext) {
keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID) keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
if err != nil { if err != nil {
ctx.Handle(500, "ListDeployKeys", err) ctx.Error(500, "ListDeployKeys", err)
return return
} }
@ -31,7 +31,7 @@ func ListDeployKeys(ctx *context.Context) {
apiKeys := make([]*api.DeployKey, len(keys)) apiKeys := make([]*api.DeployKey, len(keys))
for i := range keys { for i := range keys {
if err = keys[i].GetContent(); err != nil { if err = keys[i].GetContent(); err != nil {
ctx.APIError(500, "GetContent", err) ctx.Error(500, "GetContent", err)
return return
} }
apiKeys[i] = convert.ToApiDeployKey(apiLink, keys[i]) apiKeys[i] = convert.ToApiDeployKey(apiLink, keys[i])
@ -41,19 +41,19 @@ func ListDeployKeys(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#get-a-deploy-key
func GetDeployKey(ctx *context.Context) { func GetDeployKey(ctx *context.APIContext) {
key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id")) key, err := models.GetDeployKeyByID(ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrDeployKeyNotExist(err) { if models.IsErrDeployKeyNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.Handle(500, "GetDeployKeyByID", err) ctx.Error(500, "GetDeployKeyByID", err)
} }
return return
} }
if err = key.GetContent(); err != nil { if err = key.GetContent(); err != nil {
ctx.APIError(500, "GetContent", err) ctx.Error(500, "GetContent", err)
return return
} }
@ -61,27 +61,27 @@ func GetDeployKey(ctx *context.Context) {
ctx.JSON(200, convert.ToApiDeployKey(apiLink, key)) ctx.JSON(200, convert.ToApiDeployKey(apiLink, key))
} }
func HandleCheckKeyStringError(ctx *context.Context, err error) { func HandleCheckKeyStringError(ctx *context.APIContext, err error) {
if models.IsErrKeyUnableVerify(err) { if models.IsErrKeyUnableVerify(err) {
ctx.APIError(422, "", "Unable to verify key content") ctx.Error(422, "", "Unable to verify key content")
} else { } else {
ctx.APIError(422, "", fmt.Errorf("Invalid key content: %v", err)) ctx.Error(422, "", fmt.Errorf("Invalid key content: %v", err))
} }
} }
func HandleAddKeyError(ctx *context.Context, err error) { func HandleAddKeyError(ctx *context.APIContext, err error) {
switch { switch {
case models.IsErrKeyAlreadyExist(err): case models.IsErrKeyAlreadyExist(err):
ctx.APIError(422, "", "Key content has been used as non-deploy key") ctx.Error(422, "", "Key content has been used as non-deploy key")
case models.IsErrKeyNameAlreadyUsed(err): case models.IsErrKeyNameAlreadyUsed(err):
ctx.APIError(422, "", "Key title has been used") ctx.Error(422, "", "Key title has been used")
default: default:
ctx.APIError(500, "AddKey", err) ctx.Error(500, "AddKey", err)
} }
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#add-a-new-deploy-key
func CreateDeployKey(ctx *context.Context, form api.CreateKeyOption) { func CreateDeployKey(ctx *context.APIContext, form api.CreateKeyOption) {
content, err := models.CheckPublicKeyString(form.Key) content, err := models.CheckPublicKeyString(form.Key)
if err != nil { if err != nil {
HandleCheckKeyStringError(ctx, err) HandleCheckKeyStringError(ctx, err)
@ -100,12 +100,12 @@ func CreateDeployKey(ctx *context.Context, form api.CreateKeyOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key // https://github.com/gogits/go-gogs-client/wiki/Repositories-Deploy-Keys#remove-a-deploy-key
func DeleteDeploykey(ctx *context.Context) { func DeleteDeploykey(ctx *context.APIContext) {
if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if err := models.DeleteDeployKey(ctx.User, ctx.ParamsInt64(":id")); err != nil {
if models.IsErrKeyAccessDenied(err) { if models.IsErrKeyAccessDenied(err) {
ctx.APIError(403, "", "You do not have access to this key") ctx.Error(403, "", "You do not have access to this key")
} else { } else {
ctx.APIError(500, "DeleteDeployKey", err) ctx.Error(500, "DeleteDeployKey", err)
} }
return return
} }

View file

@ -20,7 +20,7 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories // https://github.com/gogits/go-gogs-client/wiki/Repositories#search-repositories
func Search(ctx *context.Context) { func Search(ctx *context.APIContext) {
opts := &models.SearchRepoOptions{ opts := &models.SearchRepoOptions{
Keyword: path.Base(ctx.Query("q")), Keyword: path.Base(ctx.Query("q")),
OwnerID: com.StrTo(ctx.Query("uid")).MustInt64(), OwnerID: com.StrTo(ctx.Query("uid")).MustInt64(),
@ -81,17 +81,17 @@ func Search(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#list-your-repositories // https://github.com/gogits/go-gogs-client/wiki/Repositories#list-your-repositories
func ListMyRepos(ctx *context.Context) { func ListMyRepos(ctx *context.APIContext) {
ownRepos, err := models.GetRepositories(ctx.User.Id, true) ownRepos, err := models.GetRepositories(ctx.User.Id, true)
if err != nil { if err != nil {
ctx.APIError(500, "GetRepositories", err) ctx.Error(500, "GetRepositories", err)
return return
} }
numOwnRepos := len(ownRepos) numOwnRepos := len(ownRepos)
accessibleRepos, err := ctx.User.GetRepositoryAccesses() accessibleRepos, err := ctx.User.GetRepositoryAccesses()
if err != nil { if err != nil {
ctx.APIError(500, "GetRepositoryAccesses", err) ctx.Error(500, "GetRepositoryAccesses", err)
return return
} }
@ -113,7 +113,7 @@ func ListMyRepos(ctx *context.Context) {
ctx.JSON(200, &repos) ctx.JSON(200, &repos)
} }
func CreateUserRepo(ctx *context.Context, owner *models.User, opt api.CreateRepoOption) { func CreateUserRepo(ctx *context.APIContext, owner *models.User, opt api.CreateRepoOption) {
repo, err := models.CreateRepository(owner, models.CreateRepoOptions{ repo, err := models.CreateRepository(owner, models.CreateRepoOptions{
Name: opt.Name, Name: opt.Name,
Description: opt.Description, Description: opt.Description,
@ -127,14 +127,14 @@ func CreateUserRepo(ctx *context.Context, owner *models.User, opt api.CreateRepo
if models.IsErrRepoAlreadyExist(err) || if models.IsErrRepoAlreadyExist(err) ||
models.IsErrNameReserved(err) || models.IsErrNameReserved(err) ||
models.IsErrNamePatternNotAllowed(err) { models.IsErrNamePatternNotAllowed(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
if repo != nil { if repo != nil {
if err = models.DeleteRepository(ctx.User.Id, repo.ID); err != nil { if err = models.DeleteRepository(ctx.User.Id, repo.ID); err != nil {
log.Error(4, "DeleteRepository: %v", err) log.Error(4, "DeleteRepository: %v", err)
} }
} }
ctx.APIError(500, "CreateRepository", err) ctx.Error(500, "CreateRepository", err)
} }
return return
} }
@ -143,35 +143,35 @@ func CreateUserRepo(ctx *context.Context, owner *models.User, opt api.CreateRepo
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#create // https://github.com/gogits/go-gogs-client/wiki/Repositories#create
func Create(ctx *context.Context, opt api.CreateRepoOption) { func Create(ctx *context.APIContext, opt api.CreateRepoOption) {
// Shouldn't reach this condition, but just in case. // Shouldn't reach this condition, but just in case.
if ctx.User.IsOrganization() { if ctx.User.IsOrganization() {
ctx.APIError(422, "", "not allowed creating repository for organization") ctx.Error(422, "", "not allowed creating repository for organization")
return return
} }
CreateUserRepo(ctx, ctx.User, opt) CreateUserRepo(ctx, ctx.User, opt)
} }
func CreateOrgRepo(ctx *context.Context, opt api.CreateRepoOption) { func CreateOrgRepo(ctx *context.APIContext, opt api.CreateRepoOption) {
org, err := models.GetOrgByName(ctx.Params(":org")) org, err := models.GetOrgByName(ctx.Params(":org"))
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "GetOrgByName", err) ctx.Error(500, "GetOrgByName", err)
} }
return return
} }
if !org.IsOwnedBy(ctx.User.Id) { if !org.IsOwnedBy(ctx.User.Id) {
ctx.APIError(403, "", "Given user is not owner of organization.") ctx.Error(403, "", "Given user is not owner of organization.")
return return
} }
CreateUserRepo(ctx, org, opt) CreateUserRepo(ctx, org, opt)
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate // https://github.com/gogits/go-gogs-client/wiki/Repositories#migrate
func Migrate(ctx *context.Context, form auth.MigrateRepoForm) { func Migrate(ctx *context.APIContext, form auth.MigrateRepoForm) {
ctxUser := ctx.User ctxUser := ctx.User
// Not equal means context user is an organization, // Not equal means context user is an organization,
// or is another user/organization if current user is admin. // or is another user/organization if current user is admin.
@ -179,9 +179,9 @@ func Migrate(ctx *context.Context, form auth.MigrateRepoForm) {
org, err := models.GetUserByID(form.Uid) org, err := models.GetUserByID(form.Uid)
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "GetUserByID", err) ctx.Error(500, "GetUserByID", err)
} }
return return
} }
@ -189,14 +189,14 @@ func Migrate(ctx *context.Context, form auth.MigrateRepoForm) {
} }
if ctx.HasError() { if ctx.HasError() {
ctx.APIError(422, "", ctx.GetErrMsg()) ctx.Error(422, "", ctx.GetErrMsg())
return return
} }
if ctxUser.IsOrganization() && !ctx.User.IsAdmin { if ctxUser.IsOrganization() && !ctx.User.IsAdmin {
// Check ownership of organization. // Check ownership of organization.
if !ctxUser.IsOwnedBy(ctx.User.Id) { if !ctxUser.IsOwnedBy(ctx.User.Id) {
ctx.APIError(403, "", "Given user is not owner of organization.") ctx.Error(403, "", "Given user is not owner of organization.")
return return
} }
} }
@ -207,16 +207,16 @@ func Migrate(ctx *context.Context, form auth.MigrateRepoForm) {
addrErr := err.(models.ErrInvalidCloneAddr) addrErr := err.(models.ErrInvalidCloneAddr)
switch { switch {
case addrErr.IsURLError: case addrErr.IsURLError:
ctx.APIError(422, "", err) ctx.Error(422, "", err)
case addrErr.IsPermissionDenied: case addrErr.IsPermissionDenied:
ctx.APIError(422, "", "You are not allowed to import local repositories.") ctx.Error(422, "", "You are not allowed to import local repositories.")
case addrErr.IsInvalidPath: case addrErr.IsInvalidPath:
ctx.APIError(422, "", "Invalid local path, it does not exist or not a directory.") ctx.Error(422, "", "Invalid local path, it does not exist or not a directory.")
default: default:
ctx.APIError(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error()) ctx.Error(500, "ParseRemoteAddr", "Unknown error type (ErrInvalidCloneAddr): "+err.Error())
} }
} else { } else {
ctx.APIError(500, "ParseRemoteAddr", err) ctx.Error(500, "ParseRemoteAddr", err)
} }
return return
} }
@ -234,7 +234,7 @@ func Migrate(ctx *context.Context, form auth.MigrateRepoForm) {
log.Error(4, "DeleteRepository: %v", errDelete) log.Error(4, "DeleteRepository: %v", errDelete)
} }
} }
ctx.APIError(500, "MigrateRepository", models.HandleCloneUserCredentials(err.Error(), true)) ctx.Error(500, "MigrateRepository", models.HandleCloneUserCredentials(err.Error(), true))
return return
} }
@ -242,13 +242,13 @@ func Migrate(ctx *context.Context, form auth.MigrateRepoForm) {
ctx.JSON(201, convert.ToApiRepository(ctxUser, repo, api.Permission{true, true, true})) ctx.JSON(201, convert.ToApiRepository(ctxUser, repo, api.Permission{true, true, true}))
} }
func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) { func parseOwnerAndRepo(ctx *context.APIContext) (*models.User, *models.Repository) {
owner, err := models.GetUserByName(ctx.Params(":username")) owner, err := models.GetUserByName(ctx.Params(":username"))
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.APIError(422, "", err) ctx.Error(422, "", err)
} else { } else {
ctx.APIError(500, "GetUserByName", err) ctx.Error(500, "GetUserByName", err)
} }
return nil, nil return nil, nil
} }
@ -256,9 +256,9 @@ func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository)
repo, err := models.GetRepositoryByName(owner.Id, ctx.Params(":reponame")) repo, err := models.GetRepositoryByName(owner.Id, ctx.Params(":reponame"))
if err != nil { if err != nil {
if models.IsErrRepoNotExist(err) { if models.IsErrRepoNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetRepositoryByName", err) ctx.Error(500, "GetRepositoryByName", err)
} }
return nil, nil return nil, nil
} }
@ -267,7 +267,7 @@ func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository)
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#get // https://github.com/gogits/go-gogs-client/wiki/Repositories#get
func Get(ctx *context.Context) { func Get(ctx *context.APIContext) {
owner, repo := parseOwnerAndRepo(ctx) owner, repo := parseOwnerAndRepo(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -277,19 +277,19 @@ func Get(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Repositories#delete // https://github.com/gogits/go-gogs-client/wiki/Repositories#delete
func Delete(ctx *context.Context) { func Delete(ctx *context.APIContext) {
owner, repo := parseOwnerAndRepo(ctx) owner, repo := parseOwnerAndRepo(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
if owner.IsOrganization() && !owner.IsOwnedBy(ctx.User.Id) { if owner.IsOrganization() && !owner.IsOwnedBy(ctx.User.Id) {
ctx.APIError(403, "", "Given user is not owner of organization.") ctx.Error(403, "", "Given user is not owner of organization.")
return return
} }
if err := models.DeleteRepository(owner.Id, repo.ID); err != nil { if err := models.DeleteRepository(owner.Id, repo.ID); err != nil {
ctx.APIError(500, "DeleteRepository", err) ctx.Error(500, "DeleteRepository", err)
return return
} }

View file

@ -12,10 +12,10 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user // https://github.com/gogits/go-gogs-client/wiki/Users#list-access-tokens-for-a-user
func ListAccessTokens(ctx *context.Context) { func ListAccessTokens(ctx *context.APIContext) {
tokens, err := models.ListAccessTokens(ctx.User.Id) tokens, err := models.ListAccessTokens(ctx.User.Id)
if err != nil { if err != nil {
ctx.APIError(500, "ListAccessTokens", err) ctx.Error(500, "ListAccessTokens", err)
return return
} }
@ -27,13 +27,13 @@ func ListAccessTokens(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token // https://github.com/gogits/go-gogs-client/wiki/Users#create-a-access-token
func CreateAccessToken(ctx *context.Context, form api.CreateAccessTokenOption) { func CreateAccessToken(ctx *context.APIContext, form api.CreateAccessTokenOption) {
t := &models.AccessToken{ t := &models.AccessToken{
UID: ctx.User.Id, UID: ctx.User.Id,
Name: form.Name, Name: form.Name,
} }
if err := models.NewAccessToken(t); err != nil { if err := models.NewAccessToken(t); err != nil {
ctx.APIError(500, "NewAccessToken", err) ctx.Error(500, "NewAccessToken", err)
return return
} }
ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1}) ctx.JSON(201, &api.AccessToken{t.Name, t.Sha1})

View file

@ -14,10 +14,10 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#list-email-addresses-for-a-user
func ListEmails(ctx *context.Context) { func ListEmails(ctx *context.APIContext) {
emails, err := models.GetEmailAddresses(ctx.User.Id) emails, err := models.GetEmailAddresses(ctx.User.Id)
if err != nil { if err != nil {
ctx.Handle(500, "GetEmailAddresses", err) ctx.Error(500, "GetEmailAddresses", err)
return return
} }
apiEmails := make([]*api.Email, len(emails)) apiEmails := make([]*api.Email, len(emails))
@ -28,7 +28,7 @@ func ListEmails(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#add-email-addresses
func AddEmail(ctx *context.Context, form api.CreateEmailOption) { func AddEmail(ctx *context.APIContext, form api.CreateEmailOption) {
if len(form.Emails) == 0 { if len(form.Emails) == 0 {
ctx.Status(422) ctx.Status(422)
return return
@ -45,9 +45,9 @@ func AddEmail(ctx *context.Context, form api.CreateEmailOption) {
if err := models.AddEmailAddresses(emails); err != nil { if err := models.AddEmailAddresses(emails); err != nil {
if models.IsErrEmailAlreadyUsed(err) { if models.IsErrEmailAlreadyUsed(err) {
ctx.APIError(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email) ctx.Error(422, "", "Email address has been used: "+err.(models.ErrEmailAlreadyUsed).Email)
} else { } else {
ctx.APIError(500, "AddEmailAddresses", err) ctx.Error(500, "AddEmailAddresses", err)
} }
return return
} }
@ -60,7 +60,7 @@ func AddEmail(ctx *context.Context, form api.CreateEmailOption) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses // https://github.com/gogits/go-gogs-client/wiki/Users-Emails#delete-email-addresses
func DeleteEmail(ctx *context.Context, form api.CreateEmailOption) { func DeleteEmail(ctx *context.APIContext, form api.CreateEmailOption) {
if len(form.Emails) == 0 { if len(form.Emails) == 0 {
ctx.Status(204) ctx.Status(204)
return return
@ -74,7 +74,7 @@ func DeleteEmail(ctx *context.Context, form api.CreateEmailOption) {
} }
if err := models.DeleteEmailAddresses(emails); err != nil { if err := models.DeleteEmailAddresses(emails); err != nil {
ctx.APIError(500, "DeleteEmailAddresses", err) ctx.Error(500, "DeleteEmailAddresses", err)
return return
} }
ctx.Status(204) ctx.Status(204)

View file

@ -12,7 +12,7 @@ import (
"github.com/gogits/gogs/routers/api/v1/convert" "github.com/gogits/gogs/routers/api/v1/convert"
) )
func responseApiUsers(ctx *context.Context, users []*models.User) { func responseApiUsers(ctx *context.APIContext, users []*models.User) {
apiUsers := make([]*api.User, len(users)) apiUsers := make([]*api.User, len(users))
for i := range users { for i := range users {
apiUsers[i] = convert.ToApiUser(users[i]) apiUsers[i] = convert.ToApiUser(users[i])
@ -20,21 +20,21 @@ func responseApiUsers(ctx *context.Context, users []*models.User) {
ctx.JSON(200, &apiUsers) ctx.JSON(200, &apiUsers)
} }
func listUserFollowers(ctx *context.Context, u *models.User) { func listUserFollowers(ctx *context.APIContext, u *models.User) {
users, err := u.GetFollowers(ctx.QueryInt("page")) users, err := u.GetFollowers(ctx.QueryInt("page"))
if err != nil { if err != nil {
ctx.APIError(500, "GetUserFollowers", err) ctx.Error(500, "GetUserFollowers", err)
return return
} }
responseApiUsers(ctx, users) responseApiUsers(ctx, users)
} }
func ListMyFollowers(ctx *context.Context) { func ListMyFollowers(ctx *context.APIContext) {
listUserFollowers(ctx, ctx.User) listUserFollowers(ctx, ctx.User)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-followers-of-a-user
func ListFollowers(ctx *context.Context) { func ListFollowers(ctx *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -42,21 +42,21 @@ func ListFollowers(ctx *context.Context) {
listUserFollowers(ctx, u) listUserFollowers(ctx, u)
} }
func listUserFollowing(ctx *context.Context, u *models.User) { func listUserFollowing(ctx *context.APIContext, u *models.User) {
users, err := u.GetFollowing(ctx.QueryInt("page")) users, err := u.GetFollowing(ctx.QueryInt("page"))
if err != nil { if err != nil {
ctx.APIError(500, "GetFollowing", err) ctx.Error(500, "GetFollowing", err)
return return
} }
responseApiUsers(ctx, users) responseApiUsers(ctx, users)
} }
func ListMyFollowing(ctx *context.Context) { func ListMyFollowing(ctx *context.APIContext) {
listUserFollowing(ctx, ctx.User) listUserFollowing(ctx, ctx.User)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#list-users-followed-by-another-user
func ListFollowing(ctx *context.Context) { func ListFollowing(ctx *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -64,16 +64,16 @@ func ListFollowing(ctx *context.Context) {
listUserFollowing(ctx, u) listUserFollowing(ctx, u)
} }
func checkUserFollowing(ctx *context.Context, u *models.User, followID int64) { func checkUserFollowing(ctx *context.APIContext, u *models.User, followID int64) {
if u.IsFollowing(followID) { if u.IsFollowing(followID) {
ctx.Status(204) ctx.Status(204)
} else { } else {
ctx.Error(404) ctx.Status(404)
} }
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-you-are-following-a-user
func CheckMyFollowing(ctx *context.Context) { func CheckMyFollowing(ctx *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -82,7 +82,7 @@ func CheckMyFollowing(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#check-if-one-user-follows-another
func CheckFollowing(ctx *context.Context) { func CheckFollowing(ctx *context.APIContext) {
u := GetUserByParams(ctx) u := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -95,26 +95,26 @@ func CheckFollowing(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#follow-a-user
func Follow(ctx *context.Context) { func Follow(ctx *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
if err := models.FollowUser(ctx.User.Id, target.Id); err != nil { if err := models.FollowUser(ctx.User.Id, target.Id); err != nil {
ctx.APIError(500, "FollowUser", err) ctx.Error(500, "FollowUser", err)
return return
} }
ctx.Status(204) ctx.Status(204)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Followers#unfollow-a-user
func Unfollow(ctx *context.Context) { func Unfollow(ctx *context.APIContext) {
target := GetUserByParams(ctx) target := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
if err := models.UnfollowUser(ctx.User.Id, target.Id); err != nil { if err := models.UnfollowUser(ctx.User.Id, target.Id); err != nil {
ctx.APIError(500, "UnfollowUser", err) ctx.Error(500, "UnfollowUser", err)
return return
} }
ctx.Status(204) ctx.Status(204)

View file

@ -14,13 +14,13 @@ import (
"github.com/gogits/gogs/routers/api/v1/repo" "github.com/gogits/gogs/routers/api/v1/repo"
) )
func GetUserByParamsName(ctx *context.Context, name string) *models.User { func GetUserByParamsName(ctx *context.APIContext, name string) *models.User {
user, err := models.GetUserByName(ctx.Params(name)) user, err := models.GetUserByName(ctx.Params(name))
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetUserByName", err) ctx.Error(500, "GetUserByName", err)
} }
return nil return nil
} }
@ -28,7 +28,7 @@ func GetUserByParamsName(ctx *context.Context, name string) *models.User {
} }
// GetUserByParams returns user whose name is presented in URL paramenter. // GetUserByParams returns user whose name is presented in URL paramenter.
func GetUserByParams(ctx *context.Context) *models.User { func GetUserByParams(ctx *context.APIContext) *models.User {
return GetUserByParamsName(ctx, ":username") return GetUserByParamsName(ctx, ":username")
} }
@ -36,10 +36,10 @@ func composePublicKeysAPILink() string {
return setting.AppUrl + "api/v1/user/keys/" return setting.AppUrl + "api/v1/user/keys/"
} }
func listPublicKeys(ctx *context.Context, uid int64) { func listPublicKeys(ctx *context.APIContext, uid int64) {
keys, err := models.ListPublicKeys(uid) keys, err := models.ListPublicKeys(uid)
if err != nil { if err != nil {
ctx.APIError(500, "ListPublicKeys", err) ctx.Error(500, "ListPublicKeys", err)
return return
} }
@ -53,12 +53,12 @@ func listPublicKeys(ctx *context.Context, uid int64) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-your-public-keys
func ListMyPublicKeys(ctx *context.Context) { func ListMyPublicKeys(ctx *context.APIContext) {
listPublicKeys(ctx, ctx.User.Id) listPublicKeys(ctx, ctx.User.Id)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#list-public-keys-for-a-user
func ListPublicKeys(ctx *context.Context) { func ListPublicKeys(ctx *context.APIContext) {
user := GetUserByParams(ctx) user := GetUserByParams(ctx)
if ctx.Written() { if ctx.Written() {
return return
@ -67,13 +67,13 @@ func ListPublicKeys(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#get-a-single-public-key
func GetPublicKey(ctx *context.Context) { func GetPublicKey(ctx *context.APIContext) {
key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id")) key, err := models.GetPublicKeyByID(ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
if models.IsErrKeyNotExist(err) { if models.IsErrKeyNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.Handle(500, "GetPublicKeyByID", err) ctx.Error(500, "GetPublicKeyByID", err)
} }
return return
} }
@ -83,7 +83,7 @@ func GetPublicKey(ctx *context.Context) {
} }
// CreateUserPublicKey creates new public key to given user by ID. // CreateUserPublicKey creates new public key to given user by ID.
func CreateUserPublicKey(ctx *context.Context, form api.CreateKeyOption, uid int64) { func CreateUserPublicKey(ctx *context.APIContext, form api.CreateKeyOption, uid int64) {
content, err := models.CheckPublicKeyString(form.Key) content, err := models.CheckPublicKeyString(form.Key)
if err != nil { if err != nil {
repo.HandleCheckKeyStringError(ctx, err) repo.HandleCheckKeyStringError(ctx, err)
@ -100,17 +100,17 @@ func CreateUserPublicKey(ctx *context.Context, form api.CreateKeyOption, uid int
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#create-a-public-key
func CreatePublicKey(ctx *context.Context, form api.CreateKeyOption) { func CreatePublicKey(ctx *context.APIContext, form api.CreateKeyOption) {
CreateUserPublicKey(ctx, form, ctx.User.Id) CreateUserPublicKey(ctx, form, ctx.User.Id)
} }
// https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key // https://github.com/gogits/go-gogs-client/wiki/Users-Public-Keys#delete-a-public-key
func DeletePublicKey(ctx *context.Context) { func DeletePublicKey(ctx *context.APIContext) {
if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil { if err := models.DeletePublicKey(ctx.User, ctx.ParamsInt64(":id")); err != nil {
if models.IsErrKeyAccessDenied(err) { if models.IsErrKeyAccessDenied(err) {
ctx.APIError(403, "", "You do not have access to this key") ctx.Error(403, "", "You do not have access to this key")
} else { } else {
ctx.APIError(500, "DeletePublicKey", err) ctx.Error(500, "DeletePublicKey", err)
} }
return return
} }

View file

@ -14,7 +14,7 @@ import (
) )
// https://github.com/gogits/go-gogs-client/wiki/Users#search-users // https://github.com/gogits/go-gogs-client/wiki/Users#search-users
func Search(ctx *context.Context) { func Search(ctx *context.APIContext) {
opts := &models.SearchUserOptions{ opts := &models.SearchUserOptions{
Keyword: ctx.Query("q"), Keyword: ctx.Query("q"),
Type: models.USER_TYPE_INDIVIDUAL, Type: models.USER_TYPE_INDIVIDUAL,
@ -53,13 +53,13 @@ func Search(ctx *context.Context) {
} }
// https://github.com/gogits/go-gogs-client/wiki/Users#get-a-single-user // https://github.com/gogits/go-gogs-client/wiki/Users#get-a-single-user
func GetInfo(ctx *context.Context) { func GetInfo(ctx *context.APIContext) {
u, err := models.GetUserByName(ctx.Params(":username")) u, err := models.GetUserByName(ctx.Params(":username"))
if err != nil { if err != nil {
if models.IsErrUserNotExist(err) { if models.IsErrUserNotExist(err) {
ctx.Error(404) ctx.Status(404)
} else { } else {
ctx.APIError(500, "GetUserByName", err) ctx.Error(500, "GetUserByName", err)
} }
return return
} }