Encrypted messaging app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.7 KiB

  1. package Database
  2. import (
  3. "database/sql"
  4. "time"
  5. "github.com/gofrs/uuid"
  6. "gorm.io/gorm"
  7. "gorm.io/gorm/clause"
  8. )
  9. // FriendRequest Set with Friend being the requestee, and RequestFromID being the requester
  10. type FriendRequest struct {
  11. Base
  12. UserID uuid.UUID `gorm:"type:uuid;column:user_id;not null;" json:"user_id"`
  13. User User ` json:"user"`
  14. FriendID string `gorm:"not null" json:"friend_id"` // Stored encrypted
  15. FriendUsername string ` json:"friend_username"` // Stored encrypted
  16. FriendImagePath string ` json:"friend_image_path"`
  17. FriendPublicAsymmetricKey string ` json:"asymmetric_public_key"` // Stored encrypted
  18. SymmetricKey string `gorm:"not null" json:"symmetric_key"` // Stored encrypted
  19. AcceptedAt sql.NullTime ` json:"accepted_at"`
  20. CreatedAt time.Time `gorm:"not null" json:"created_at"`
  21. }
  22. type FriendRequestList []FriendRequest
  23. // GetFriendRequestByID gets friend request
  24. func GetFriendRequestByID(id string) (FriendRequest, error) {
  25. var (
  26. friendRequest FriendRequest
  27. err error
  28. )
  29. err = DB.Preload(clause.Associations).
  30. First(&friendRequest, "id = ?", id).
  31. Error
  32. return friendRequest, err
  33. }
  34. // GetFriendRequestsByUserID gets friend request by user id
  35. func GetFriendRequestsByUserID(userID string, page int) ([]FriendRequest, error) {
  36. var (
  37. friends []FriendRequest
  38. offset int
  39. err error
  40. )
  41. offset = page * PageSize
  42. err = DB.Model(FriendRequest{}).
  43. Where("user_id = ?", userID).
  44. Offset(offset).
  45. Limit(PageSize).
  46. Order("created_at DESC").
  47. Find(&friends).
  48. Error
  49. return friends, err
  50. }
  51. // CreateFriendRequest creates friend request
  52. func (friendRequest *FriendRequest) CreateFriendRequest() error {
  53. return DB.Create(friendRequest).
  54. Error
  55. }
  56. // CreateFriendRequests creates multiple friend requests
  57. func (friendRequest *FriendRequestList) CreateFriendRequests() error {
  58. return DB.Create(friendRequest).
  59. Error
  60. }
  61. // UpdateFriendRequest Updates friend request
  62. func (friendRequest *FriendRequest) UpdateFriendRequest() error {
  63. return DB.Where("id = ?", friendRequest.ID).
  64. Updates(friendRequest).
  65. Error
  66. }
  67. // DeleteFriendRequest deletes friend request
  68. func (friendRequest *FriendRequest) DeleteFriendRequest() error {
  69. return DB.Session(&gorm.Session{FullSaveAssociations: true}).
  70. Delete(friendRequest).
  71. Error
  72. }