webforwarding.go 8.7 KB

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