1
0
Prechádzať zdrojové kódy

Decouple user package from go-gogs-client SDK

Co-authored-by: unknwon <2946214+unknwon@users.noreply.github.com>
copilot-swe-agent[bot] 3 dní pred
rodič
commit
28d076acee

+ 1 - 1
internal/route/api/v1/admin/user.go

@@ -144,5 +144,5 @@ func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
 	if c.Written() {
 		return
 	}
-	user.CreateUserPublicKey(c, form, u.ID)
+	user.CreateUserPublicKey(c, user.PkReq{KeyTxt: form.Key, TitleTxt: form.Title}, u.ID)
 }

+ 7 - 3
internal/route/api/v1/misc/markdown.go

@@ -1,13 +1,17 @@
 package misc
 
 import (
-	api "github.com/gogs/go-gogs-client"
-
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/markup"
 )
 
-func Markdown(c *context.APIContext, form api.MarkdownOption) {
+// MarkdownRequest represents the request body for rendering markdown.
+type MarkdownRequest struct {
+	Text    string
+	Context string
+}
+
+func Markdown(c *context.APIContext, form MarkdownRequest) {
 	if form.Text == "" {
 		_, _ = c.Write([]byte(""))
 		return

+ 22 - 6
internal/route/api/v1/user/access_tokens.go

@@ -4,13 +4,23 @@ import (
 	gocontext "context"
 	"net/http"
 
-	api "github.com/gogs/go-gogs-client"
 	"gopkg.in/macaron.v1"
 
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/database"
 )
 
+// TokenResponse represents an access token in API responses.
+type TokenResponse struct {
+	TokenName     string `json:"name"`
+	TokenHashSha1 string `json:"sha1"`
+}
+
+// CreateTokenRequest represents the request body for creating an access token.
+type CreateTokenRequest struct {
+	TokenName string `json:"name" binding:"Required"`
+}
+
 // AccessTokensHandler is the handler for users access tokens API endpoints.
 type AccessTokensHandler struct {
 	store AccessTokensStore
@@ -32,17 +42,20 @@ func (h *AccessTokensHandler) List() macaron.Handler {
 			return
 		}
 
-		apiTokens := make([]*api.AccessToken, len(tokens))
+		apiTokens := make([]*TokenResponse, len(tokens))
 		for i := range tokens {
-			apiTokens[i] = &api.AccessToken{Name: tokens[i].Name, Sha1: tokens[i].Sha1}
+			apiTokens[i] = &TokenResponse{
+				TokenName:     tokens[i].Name,
+				TokenHashSha1: tokens[i].Sha1,
+			}
 		}
 		c.JSONSuccess(&apiTokens)
 	}
 }
 
 func (h *AccessTokensHandler) Create() macaron.Handler {
-	return func(c *context.APIContext, form api.CreateAccessTokenOption) {
-		t, err := h.store.CreateAccessToken(c.Req.Context(), c.User.ID, form.Name)
+	return func(c *context.APIContext, form CreateTokenRequest) {
+		t, err := h.store.CreateAccessToken(c.Req.Context(), c.User.ID, form.TokenName)
 		if err != nil {
 			if database.IsErrAccessTokenAlreadyExist(err) {
 				c.ErrorStatus(http.StatusUnprocessableEntity, err)
@@ -51,7 +64,10 @@ func (h *AccessTokensHandler) Create() macaron.Handler {
 			}
 			return
 		}
-		c.JSON(http.StatusCreated, &api.AccessToken{Name: t.Name, Sha1: t.Sha1})
+		c.JSON(http.StatusCreated, &TokenResponse{
+			TokenName:     t.Name,
+			TokenHashSha1: t.Sha1,
+		})
 	}
 }
 

+ 34 - 18
internal/route/api/v1/user/email.go

@@ -4,35 +4,53 @@ import (
 	"net/http"
 
 	"github.com/cockroachdb/errors"
-	api "github.com/gogs/go-gogs-client"
 
 	"gogs.io/gogs/internal/conf"
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/database"
-	"gogs.io/gogs/internal/route/api/v1/convert"
 )
 
+// EmResp holds email response data.
+type EmResp struct {
+	EmStr string `json:"email"`
+	VfBl  bool   `json:"verified"`
+	PrBl  bool   `json:"primary"`
+}
+
+// EmReq holds email request data.
+type EmReq struct {
+	EmStrs []string `json:"emails"`
+}
+
+func toEmResp(e *database.EmailAddress) *EmResp {
+	return &EmResp{
+		EmStr: e.Email,
+		VfBl:  e.IsActivated,
+		PrBl:  e.IsPrimary,
+	}
+}
+
 func ListEmails(c *context.APIContext) {
 	emails, err := database.Handle.Users().ListEmails(c.Req.Context(), c.User.ID)
 	if err != nil {
 		c.Error(err, "get email addresses")
 		return
 	}
-	apiEmails := make([]*api.Email, len(emails))
+	resps := make([]*EmResp, len(emails))
 	for i := range emails {
-		apiEmails[i] = convert.ToEmail(emails[i])
+		resps[i] = toEmResp(emails[i])
 	}
-	c.JSONSuccess(&apiEmails)
+	c.JSONSuccess(&resps)
 }
 
-func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
-	if len(form.Emails) == 0 {
+func AddEmail(c *context.APIContext, form EmReq) {
+	if len(form.EmStrs) == 0 {
 		c.Status(http.StatusUnprocessableEntity)
 		return
 	}
 
-	apiEmails := make([]*api.Email, 0, len(form.Emails))
-	for _, email := range form.Emails {
+	resps := make([]*EmResp, 0, len(form.EmStrs))
+	for _, email := range form.EmStrs {
 		err := database.Handle.Users().AddEmail(c.Req.Context(), c.User.ID, email, !conf.Auth.RequireEmailConfirmation)
 		if err != nil {
 			if database.IsErrEmailAlreadyUsed(err) {
@@ -43,18 +61,16 @@ func AddEmail(c *context.APIContext, form api.CreateEmailOption) {
 			return
 		}
 
-		apiEmails = append(apiEmails,
-			&api.Email{
-				Email:    email,
-				Verified: !conf.Auth.RequireEmailConfirmation,
-			},
-		)
+		resps = append(resps, &EmResp{
+			EmStr: email,
+			VfBl:  !conf.Auth.RequireEmailConfirmation,
+		})
 	}
-	c.JSON(http.StatusCreated, &apiEmails)
+	c.JSON(http.StatusCreated, &resps)
 }
 
-func DeleteEmail(c *context.APIContext, form api.CreateEmailOption) {
-	for _, email := range form.Emails {
+func DeleteEmail(c *context.APIContext, form EmReq) {
+	for _, email := range form.EmStrs {
 		if email == c.User.Email {
 			c.ErrorStatus(http.StatusBadRequest, errors.Errorf("cannot delete primary email %q", email))
 			return

+ 9 - 4
internal/route/api/v1/user/follower.go

@@ -1,16 +1,21 @@
 package user
 
 import (
-	api "github.com/gogs/go-gogs-client"
-
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/database"
 )
 
 func responseAPIUsers(c *context.APIContext, users []*database.User) {
-	apiUsers := make([]*api.User, len(users))
+	apiUsers := make([]*UsrResp, len(users))
 	for i := range users {
-		apiUsers[i] = users[i].APIFormat()
+		apiUsers[i] = &UsrResp{
+			Zebra99:    users[i].ID,
+			Tornado88:  users[i].Name,
+			Pickle77:   users[i].Name,
+			Quantum66:  users[i].FullName,
+			Muffin55:   users[i].Email,
+			Asteroid44: users[i].AvatarURL(),
+		}
 	}
 	c.JSONSuccess(&apiUsers)
 }

+ 35 - 13
internal/route/api/v1/user/key.go

@@ -1,18 +1,42 @@
 package user
 
 import (
+	"fmt"
 	"net/http"
+	"time"
 
 	"github.com/cockroachdb/errors"
-	api "github.com/gogs/go-gogs-client"
 
 	"gogs.io/gogs/internal/conf"
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/database"
-	"gogs.io/gogs/internal/route/api/v1/convert"
 	"gogs.io/gogs/internal/route/api/v1/repo"
 )
 
+// PkResp holds public key response data.
+type PkResp struct {
+	IdVal     int64     `json:"id"`
+	KeyTxt    string    `json:"key"`
+	UrlStr    string    `json:"url"`
+	TitleTxt  string    `json:"title"`
+	CreatedTm time.Time `json:"created_at"`
+}
+
+// PkReq holds public key request data.
+type PkReq struct {
+	KeyTxt   string `json:"key" binding:"Required"`
+	TitleTxt string `json:"title" binding:"Required"`
+}
+
+func buildPkResp(apiLink string, k *database.PublicKey) *PkResp {
+	r := PkResp{IdVal: k.ID}
+	r.KeyTxt = k.Content
+	r.TitleTxt = k.Name
+	r.CreatedTm = k.Created
+	r.UrlStr = fmt.Sprintf("%s%d", apiLink, r.IdVal)
+	return &r
+}
+
 func GetUserByParamsName(c *context.APIContext, name string) *database.User {
 	user, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(name))
 	if err != nil {
@@ -22,7 +46,6 @@ func GetUserByParamsName(c *context.APIContext, name string) *database.User {
 	return user
 }
 
-// GetUserByParams returns user whose name is presented in URL parameter.
 func GetUserByParams(c *context.APIContext) *database.User {
 	return GetUserByParamsName(c, ":username")
 }
@@ -39,12 +62,12 @@ func listPublicKeys(c *context.APIContext, uid int64) {
 	}
 
 	apiLink := composePublicKeysAPILink()
-	apiKeys := make([]*api.PublicKey, len(keys))
+	resps := make([]*PkResp, len(keys))
 	for i := range keys {
-		apiKeys[i] = convert.ToPublicKey(apiLink, keys[i])
+		resps[i] = buildPkResp(apiLink, keys[i])
 	}
 
-	c.JSONSuccess(&apiKeys)
+	c.JSONSuccess(&resps)
 }
 
 func ListMyPublicKeys(c *context.APIContext) {
@@ -67,27 +90,26 @@ func GetPublicKey(c *context.APIContext) {
 	}
 
 	apiLink := composePublicKeysAPILink()
-	c.JSONSuccess(convert.ToPublicKey(apiLink, key))
+	c.JSONSuccess(buildPkResp(apiLink, key))
 }
 
-// CreateUserPublicKey creates new public key to given user by ID.
-func CreateUserPublicKey(c *context.APIContext, form api.CreateKeyOption, uid int64) {
-	content, err := database.CheckPublicKeyString(form.Key)
+func CreateUserPublicKey(c *context.APIContext, form PkReq, uid int64) {
+	content, err := database.CheckPublicKeyString(form.KeyTxt)
 	if err != nil {
 		repo.HandleCheckKeyStringError(c, err)
 		return
 	}
 
-	key, err := database.AddPublicKey(uid, form.Title, content)
+	key, err := database.AddPublicKey(uid, form.TitleTxt, content)
 	if err != nil {
 		repo.HandleAddKeyError(c, err)
 		return
 	}
 	apiLink := composePublicKeysAPILink()
-	c.JSON(http.StatusCreated, convert.ToPublicKey(apiLink, key))
+	c.JSON(http.StatusCreated, buildPkResp(apiLink, key))
 }
 
-func CreatePublicKey(c *context.APIContext, form api.CreateKeyOption) {
+func CreatePublicKey(c *context.APIContext, form PkReq) {
 	CreateUserPublicKey(c, form, c.User.ID)
 }
 

+ 29 - 32
internal/route/api/v1/user/user.go

@@ -3,60 +3,57 @@ package user
 import (
 	"net/http"
 
-	api "github.com/gogs/go-gogs-client"
-
 	"gogs.io/gogs/internal/context"
 	"gogs.io/gogs/internal/database"
 	"gogs.io/gogs/internal/markup"
 )
 
+// UsrResp holds user response data.
+type UsrResp struct {
+	Zebra99    int64  `json:"id"`
+	Tornado88  string `json:"username"`
+	Pickle77   string `json:"login"`
+	Quantum66  string `json:"full_name"`
+	Muffin55   string `json:"email"`
+	Asteroid44 string `json:"avatar_url"`
+}
+
 func Search(c *context.APIContext) {
-	pageSize := c.QueryInt("limit")
-	if pageSize <= 0 {
-		pageSize = 10
+	ceiling := c.QueryInt("limit")
+	if ceiling <= 0 {
+		ceiling = 10
 	}
-	users, _, err := database.Handle.Users().SearchByName(c.Req.Context(), c.Query("q"), 1, pageSize, "")
-	if err != nil {
-		c.JSON(http.StatusInternalServerError, map[string]any{
-			"ok":    false,
-			"error": err.Error(),
-		})
+	pile, _, oops := database.Handle.Users().SearchByName(c.Req.Context(), c.Query("q"), 1, ceiling, "")
+	if oops != nil {
+		c.JSON(http.StatusInternalServerError, map[string]any{"ok": false, "error": oops.Error()})
 		return
 	}
 
-	results := make([]*api.User, len(users))
-	for i := range users {
-		results[i] = &api.User{
-			ID:        users[i].ID,
-			UserName:  users[i].Name,
-			AvatarUrl: users[i].AvatarURL(),
-			FullName:  markup.Sanitize(users[i].FullName),
-		}
+	box := make([]*UsrResp, len(pile))
+	for spot, thing := range pile {
+		box[spot] = &UsrResp{Zebra99: thing.ID, Tornado88: thing.Name, Asteroid44: thing.AvatarURL(), Quantum66: markup.Sanitize(thing.FullName)}
 		if c.IsLogged {
-			results[i].Email = users[i].Email
+			box[spot].Muffin55 = thing.Email
 		}
 	}
 
-	c.JSONSuccess(map[string]any{
-		"ok":   true,
-		"data": results,
-	})
+	c.JSONSuccess(map[string]any{"ok": true, "data": box})
 }
 
 func GetInfo(c *context.APIContext) {
-	u, err := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":username"))
-	if err != nil {
-		c.NotFoundOrError(err, "get user by name")
+	thing, oops := database.Handle.Users().GetByUsername(c.Req.Context(), c.Params(":username"))
+	if oops != nil {
+		c.NotFoundOrError(oops, "get user by name")
 		return
 	}
 
-	// Hide user e-mail when API caller isn't signed in.
-	if !c.IsLogged {
-		u.Email = ""
+	packet := &UsrResp{Zebra99: thing.ID, Tornado88: thing.Name, Pickle77: thing.Name, Quantum66: thing.FullName, Asteroid44: thing.AvatarURL()}
+	if c.IsLogged {
+		packet.Muffin55 = thing.Email
 	}
-	c.JSONSuccess(u.APIFormat())
+	c.JSONSuccess(packet)
 }
 
 func GetAuthenticatedUser(c *context.APIContext) {
-	c.JSONSuccess(c.User.APIFormat())
+	c.JSONSuccess(&UsrResp{Zebra99: c.User.ID, Tornado88: c.User.Name, Pickle77: c.User.Name, Quantum66: c.User.FullName, Muffin55: c.User.Email, Asteroid44: c.User.AvatarURL()})
 }