|
| 1 | +// Copyright 2026 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package mention |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + |
| 9 | + "code.gitea.io/gitea/models/organization" |
| 10 | + user_model "code.gitea.io/gitea/models/user" |
| 11 | +) |
| 12 | + |
| 13 | +// Mention is the JSON structure returned by mention autocomplete endpoints. |
| 14 | +type Mention struct { |
| 15 | + Key string `json:"key"` |
| 16 | + Value string `json:"value"` |
| 17 | + Name string `json:"name"` |
| 18 | + FullName string `json:"fullname"` |
| 19 | + Avatar string `json:"avatar"` |
| 20 | +} |
| 21 | + |
| 22 | +// Collector builds a deduplicated list of Mention entries. |
| 23 | +type Collector struct { |
| 24 | + seen map[string]bool |
| 25 | + Result []Mention |
| 26 | +} |
| 27 | + |
| 28 | +// NewCollector creates a new Collector. |
| 29 | +func NewCollector() *Collector { |
| 30 | + return &Collector{seen: make(map[string]bool)} |
| 31 | +} |
| 32 | + |
| 33 | +// AddUsers adds user mentions, skipping duplicates. |
| 34 | +func (c *Collector) AddUsers(ctx context.Context, users []*user_model.User) { |
| 35 | + for _, u := range users { |
| 36 | + if !c.seen[u.Name] { |
| 37 | + c.seen[u.Name] = true |
| 38 | + c.Result = append(c.Result, Mention{ |
| 39 | + Key: u.Name + " " + u.FullName, |
| 40 | + Value: u.Name, |
| 41 | + Name: u.Name, |
| 42 | + FullName: u.FullName, |
| 43 | + Avatar: u.AvatarLink(ctx), |
| 44 | + }) |
| 45 | + } |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +// AddMentionableTeams loads and adds team mentions for the given owner (if it's an org). |
| 50 | +func (c *Collector) AddMentionableTeams(ctx context.Context, doer, owner *user_model.User) error { |
| 51 | + if doer == nil || !owner.IsOrganization() { |
| 52 | + return nil |
| 53 | + } |
| 54 | + |
| 55 | + org := organization.OrgFromUser(owner) |
| 56 | + isAdmin := doer.IsAdmin |
| 57 | + if !isAdmin { |
| 58 | + var err error |
| 59 | + isAdmin, err = org.IsOwnedBy(ctx, doer.ID) |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + var teams []*organization.Team |
| 66 | + var err error |
| 67 | + if isAdmin { |
| 68 | + teams, err = org.LoadTeams(ctx) |
| 69 | + } else { |
| 70 | + teams, err = org.GetUserTeams(ctx, doer.ID) |
| 71 | + } |
| 72 | + if err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + |
| 76 | + for _, team := range teams { |
| 77 | + key := owner.Name + "/" + team.Name |
| 78 | + if !c.seen[key] { |
| 79 | + c.seen[key] = true |
| 80 | + c.Result = append(c.Result, Mention{ |
| 81 | + Key: key, |
| 82 | + Value: key, |
| 83 | + Name: key, |
| 84 | + Avatar: owner.AvatarLink(ctx), |
| 85 | + }) |
| 86 | + } |
| 87 | + } |
| 88 | + return nil |
| 89 | +} |
0 commit comments