webforwarding.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package repository
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/go-nunu/nunu-layout-advanced/internal/model"
  8. "github.com/qiniu/qmgo"
  9. "go.mongodb.org/mongo-driver/bson"
  10. "go.mongodb.org/mongo-driver/bson/primitive"
  11. "go.mongodb.org/mongo-driver/mongo"
  12. "time"
  13. )
  14. type WebForwardingRepository interface {
  15. GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error)
  16. AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error)
  17. EditWebForwarding(ctx context.Context, req *model.WebForwarding) error
  18. DeleteWebForwarding(ctx context.Context, id int64) error
  19. GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error)
  20. GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error)
  21. GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error)
  22. AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error)
  23. EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error
  24. GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error)
  25. DeleteWebForwardingIpsById(ctx context.Context, webId int) error
  26. // 获取域名数量
  27. GetDomainCount(ctx context.Context, hostId int, domain string) (int, error)
  28. // 获取IP数量等于1的IP
  29. GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error)
  30. }
  31. func NewWebForwardingRepository(
  32. repository *Repository,
  33. ) WebForwardingRepository {
  34. return &webForwardingRepository{
  35. Repository: repository,
  36. }
  37. }
  38. type webForwardingRepository struct {
  39. *Repository
  40. }
  41. func (r *webForwardingRepository) GetWebForwarding(ctx context.Context, id int64) (*model.WebForwarding, error) {
  42. var webForwarding model.WebForwarding
  43. if err := r.db.WithContext(ctx).Where("id = ?", id).First(&webForwarding).Error; err != nil {
  44. return nil, err
  45. }
  46. return &webForwarding, nil
  47. }
  48. func (r *webForwardingRepository) AddWebForwarding(ctx context.Context, req *model.WebForwarding) (int, error) {
  49. if err := r.db.WithContext(ctx).Create(req).Error; err != nil {
  50. return 0, err
  51. }
  52. return req.Id, nil
  53. }
  54. func (r *webForwardingRepository) EditWebForwarding(ctx context.Context, req *model.WebForwarding) error {
  55. forceUpdateFields := map[string]interface{}{
  56. "domain": req.Domain,
  57. }
  58. // 核心逻辑:
  59. // 1. Model(req): 定位要更新的记录。
  60. // 2. Updates(req): 先用 struct 更新。GORM 会自动忽略 req 中的零值字段。
  61. // - 如果 req.Domain 是 "abc",它会被更新。
  62. // - 如果 req.Domain 是 "",它会被忽略。
  63. // - 如果 req.TargetURL 是 "xyz",它会被更新。
  64. // - 如果 req.TargetURL 是 "",它会被忽略。
  65. // 3. Updates(forceUpdateFields): 接着用 map 更新。这会无视零值,强制更新 map 中指定的字段。
  66. // - 它会用 req.Domain 的值(无论是 "abc" 还是 "")覆盖上一步的结果。
  67. //
  68. // 最终效果:
  69. // - Domain 字段总能被正确更新(无论新值是不是 "")。
  70. // - 其他字段遵循 GORM 的默认行为(非零值才更新)。
  71. // - 这一切都在一个 UPDATE 语句中完成。
  72. db := r.db.WithContext(ctx).Model(req).Updates(req).Updates(forceUpdateFields)
  73. if db.Error != nil {
  74. return db.Error
  75. }
  76. return nil
  77. }
  78. func (r *webForwardingRepository) DeleteWebForwarding(ctx context.Context, id int64) error {
  79. if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&model.WebForwarding{}).Error; err != nil {
  80. return err
  81. }
  82. return nil
  83. }
  84. func (r *webForwardingRepository) GetWebForwardingPortCountByHostId(ctx context.Context, hostId int) (int64, error) {
  85. var count int64
  86. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Count(&count).Error; err != nil {
  87. return 0, err
  88. }
  89. return count, nil
  90. }
  91. func (r *webForwardingRepository) GetWebForwardingDomainCountByHostId(ctx context.Context, hostId int) (int64, []string, error) {
  92. var distinctDomains []string
  93. err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).
  94. Distinct(). // 确保我们只获取唯一的 domain 值
  95. Where("host_id = ? AND domain IS NOT NULL AND domain != ''", hostId). // 额外添加 domain != '' 以排除空字符串
  96. Pluck("domain", &distinctDomains).Error
  97. if err != nil {
  98. return 0, nil, err
  99. }
  100. count := int64(len(distinctDomains))
  101. return count, distinctDomains, nil
  102. }
  103. func (r *webForwardingRepository) GetWebForwardingWafWebAllIds(ctx context.Context, hostId int) ([]int, error) {
  104. var ids []int
  105. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ?", hostId).Select("id").Find(&ids).Error; err != nil {
  106. return nil, err
  107. }
  108. return ids, nil
  109. }
  110. // mongodb 插入
  111. func (r *webForwardingRepository) AddWebForwardingIps(ctx context.Context, req model.WebForwardingRule) (primitive.ObjectID, error) {
  112. collection := r.mongoDB.Collection("web_forwarding_rules")
  113. req.CreatedAt = time.Now()
  114. result, err := collection.InsertOne(ctx, req)
  115. if err != nil {
  116. return primitive.NilObjectID, fmt.Errorf("插入MongoDB失败: %w", err)
  117. }
  118. // 返回插入文档的ID
  119. return result.InsertedID.(primitive.ObjectID), nil
  120. }
  121. func (r *webForwardingRepository) EditWebForwardingIps(ctx context.Context, req model.WebForwardingRule) error {
  122. collection := r.mongoDB.Collection("web_forwarding_rules")
  123. updateData := bson.M{}
  124. if req.Uid != 0 {
  125. updateData["uid"] = req.Uid
  126. }
  127. if req.HostId != 0 {
  128. updateData["host_id"] = req.HostId
  129. }
  130. if req.WebId != 0 {
  131. updateData["web_id"] = req.WebId
  132. }
  133. if len(req.BackendList) > 0 {
  134. updateData["backend_list"] = req.BackendList
  135. }
  136. updateData["cdn_origin_ids"] = req.CdnOriginIds
  137. // 始终更新更新时间
  138. updateData["updated_at"] = time.Now()
  139. // 如果没有任何字段需要更新,则直接返回
  140. if len(updateData) == 0 {
  141. return nil
  142. }
  143. // 执行更新
  144. update := bson.M{"$set": updateData}
  145. err := collection.UpdateOne(ctx, bson.M{"web_id": req.WebId}, update)
  146. if err != nil {
  147. return fmt.Errorf("更新MongoDB文档失败: %w", err)
  148. }
  149. return nil
  150. }
  151. func (r *webForwardingRepository) GetWebForwardingIpsByID(ctx context.Context, webId int) (*model.WebForwardingRule, error) {
  152. // 获取集合
  153. collection := r.mongoDB.Collection("web_forwarding_rules")
  154. // 创建一个结构体来存储查询到的文档
  155. var rule model.WebForwardingRule
  156. // 使用 FindByID 方法来查找文档
  157. // FindByID 是 QMgo 封装的一个方便的方法,它内部会构建查询 _id = id
  158. err := collection.Find(ctx, qmgo.M{"web_id": webId}).One(&rule) // QMgo 的 FindOne 返回一个 QueryBuilder,接着调用 .One() 来执行查询并解码到 rule
  159. if err != nil {
  160. if errors.Is(err, mongo.ErrNoDocuments) {
  161. return nil, fmt.Errorf("记录不存在")
  162. }
  163. // 其他错误
  164. return nil, fmt.Errorf("查询MongoDB失败: %w", err)
  165. }
  166. // 返回找到的文档
  167. return &rule, nil
  168. }
  169. func (r *webForwardingRepository) DeleteWebForwardingIpsById(ctx context.Context, webId int) error {
  170. collection := r.mongoDB.Collection("web_forwarding_rules")
  171. err := collection.Remove(ctx, bson.M{"web_id": webId})
  172. if err != nil {
  173. if errors.Is(err, mongo.ErrNoDocuments) {
  174. return fmt.Errorf("记录不存在")
  175. }
  176. return fmt.Errorf("删除MongoDB文档失败: %w", err)
  177. }
  178. return nil
  179. }
  180. // 获取域名数量
  181. func (r *webForwardingRepository) GetDomainCount(ctx context.Context, hostId int, domain string) (int, error) {
  182. var count int64
  183. if err := r.db.Model(&model.WebForwarding{}).WithContext(ctx).Where("host_id = ? AND domain = ?", hostId, domain).Count(&count).Error; err != nil {
  184. return 0, err
  185. }
  186. return int(count), nil
  187. }
  188. // 获取IP数量等于1的IP
  189. func (r *webForwardingRepository) GetIpCountByIp(ctx context.Context, ips []string) ([]v1.IpCountResult, error) {
  190. if len(ips) == 0 {
  191. return []v1.IpCountResult{}, nil
  192. }
  193. pipeline := []bson.M{
  194. {
  195. "$match": bson.M{
  196. "ip": bson.M{"$in": ips},
  197. },
  198. },
  199. {
  200. "$group": bson.M{
  201. "_id": "$ip",
  202. "count": bson.M{"$sum": 1},
  203. },
  204. },
  205. {
  206. "$project": bson.M{
  207. "_id": 0, // 不输出默认的_id
  208. "ip": "$_id", // 将分组的_id字段重命名为ip
  209. "count": 1, // 保留count字段
  210. },
  211. },
  212. }
  213. var results []v1.IpCountResult
  214. // 使用 qmgo 执行聚合查询
  215. err := r.mongoDB.Collection("web_forwarding_rules").Aggregate(ctx, pipeline).All(&results)
  216. if err != nil {
  217. return nil, fmt.Errorf("聚合查询失败: %w", err)
  218. }
  219. return results, nil
  220. }