channel_repo.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package store
  2. import (
  3. "spider/internal/model"
  4. "strings"
  5. "gorm.io/gorm"
  6. )
  7. // UpsertChannel inserts or updates a channel by username.
  8. func (s *Store) UpsertChannel(ch *model.Channel) error {
  9. ch.Username = strings.TrimPrefix(strings.TrimSpace(ch.Username), "@")
  10. if ch.Username == "" {
  11. return nil
  12. }
  13. var existing model.Channel
  14. err := s.DB.Where("username = ?", ch.Username).First(&existing).Error
  15. if err == gorm.ErrRecordNotFound {
  16. return s.DB.Create(ch).Error
  17. }
  18. if err != nil {
  19. return err
  20. }
  21. // already exists, skip
  22. return nil
  23. }
  24. // ListPendingChannels returns channels with status=pending, up to limit.
  25. func (s *Store) ListPendingChannels(limit int) ([]model.Channel, error) {
  26. var channels []model.Channel
  27. q := s.DB.Where("status = ?", "pending")
  28. if limit > 0 {
  29. q = q.Limit(limit)
  30. }
  31. err := q.Find(&channels).Error
  32. return channels, err
  33. }
  34. // UpdateChannelStatus sets the status and optionally last_message_id.
  35. func (s *Store) UpdateChannelStatus(id uint, status string, lastMessageID int) error {
  36. updates := map[string]any{"status": status}
  37. if lastMessageID > 0 {
  38. updates["last_message_id"] = lastMessageID
  39. }
  40. return s.DB.Model(&model.Channel{}).Where("id = ?", id).Updates(updates).Error
  41. }
  42. // UpdateChannelEntity caches the TG entity IDs for a channel.
  43. func (s *Store) UpdateChannelEntity(id uint, channelID, accessHash int64) error {
  44. return s.DB.Model(&model.Channel{}).Where("id = ?", id).
  45. Updates(map[string]any{"channel_id": channelID, "access_hash": accessHash}).Error
  46. }
  47. // IncrementMerchantsFound increments the merchants_found counter.
  48. func (s *Store) IncrementMerchantsFound(id uint) error {
  49. return s.DB.Model(&model.Channel{}).Where("id = ?", id).
  50. Update("merchants_found", gorm.Expr("merchants_found + 1")).Error
  51. }