webforwarding.go 9.7 KB

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