code.gitea.io/gitea@v1.21.7/models/activities/action_list.go (about) 1 // Copyright 2018 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package activities 5 6 import ( 7 "context" 8 "fmt" 9 10 "code.gitea.io/gitea/models/db" 11 repo_model "code.gitea.io/gitea/models/repo" 12 user_model "code.gitea.io/gitea/models/user" 13 "code.gitea.io/gitea/modules/container" 14 ) 15 16 // ActionList defines a list of actions 17 type ActionList []*Action 18 19 func (actions ActionList) getUserIDs() []int64 { 20 userIDs := make(container.Set[int64], len(actions)) 21 for _, action := range actions { 22 userIDs.Add(action.ActUserID) 23 } 24 return userIDs.Values() 25 } 26 27 func (actions ActionList) loadUsers(ctx context.Context) (map[int64]*user_model.User, error) { 28 if len(actions) == 0 { 29 return nil, nil 30 } 31 32 userIDs := actions.getUserIDs() 33 userMaps := make(map[int64]*user_model.User, len(userIDs)) 34 err := db.GetEngine(ctx). 35 In("id", userIDs). 36 Find(&userMaps) 37 if err != nil { 38 return nil, fmt.Errorf("find user: %w", err) 39 } 40 41 for _, action := range actions { 42 action.ActUser = userMaps[action.ActUserID] 43 } 44 return userMaps, nil 45 } 46 47 func (actions ActionList) getRepoIDs() []int64 { 48 repoIDs := make(container.Set[int64], len(actions)) 49 for _, action := range actions { 50 repoIDs.Add(action.RepoID) 51 } 52 return repoIDs.Values() 53 } 54 55 func (actions ActionList) loadRepositories(ctx context.Context) error { 56 if len(actions) == 0 { 57 return nil 58 } 59 60 repoIDs := actions.getRepoIDs() 61 repoMaps := make(map[int64]*repo_model.Repository, len(repoIDs)) 62 err := db.GetEngine(ctx).In("id", repoIDs).Find(&repoMaps) 63 if err != nil { 64 return fmt.Errorf("find repository: %w", err) 65 } 66 67 for _, action := range actions { 68 action.Repo = repoMaps[action.RepoID] 69 } 70 return nil 71 } 72 73 func (actions ActionList) loadRepoOwner(ctx context.Context, userMap map[int64]*user_model.User) (err error) { 74 if userMap == nil { 75 userMap = make(map[int64]*user_model.User) 76 } 77 78 for _, action := range actions { 79 if action.Repo == nil { 80 continue 81 } 82 repoOwner, ok := userMap[action.Repo.OwnerID] 83 if !ok { 84 repoOwner, err = user_model.GetUserByID(ctx, action.Repo.OwnerID) 85 if err != nil { 86 if user_model.IsErrUserNotExist(err) { 87 continue 88 } 89 return err 90 } 91 userMap[repoOwner.ID] = repoOwner 92 } 93 action.Repo.Owner = repoOwner 94 } 95 96 return nil 97 } 98 99 // loadAttributes loads all attributes 100 func (actions ActionList) loadAttributes(ctx context.Context) error { 101 userMap, err := actions.loadUsers(ctx) 102 if err != nil { 103 return err 104 } 105 106 if err := actions.loadRepositories(ctx); err != nil { 107 return err 108 } 109 110 return actions.loadRepoOwner(ctx, userMap) 111 }