Coverage for src/expo_notifications/models/message.py: 100%

1 from django.db import models

2 from django.utils import timezone

3 from exponent_server_sdk import PushMessage

4

5 from expo_notifications.managers import MessageManager

6

7

8 class Message(models.Model):

9 objects = MessageManager()

10

11 device = models.ForeignKey(

12 to="expo_notifications.Device",

13 on_delete=models.CASCADE,

14 related_name="messages",

15 )

16

17 data = models.JSONField(

18 blank=True,

19 null=True,

20 )

21

22 title = models.CharField(

23 max_length=64,

24 blank=True,

25 )

26

27 body = models.CharField(

28 max_length=256,

29 blank=True,

30 )

31

32 ttl = models.DurationField(

33 blank=True,

34 null=True,

35 )

36

37 expiration = models.DateTimeField(

38 blank=True,

39 null=True,

40 )

41

42 PRIORITY_DEFAULT = "default"

43 PRIORITY_NORMAL = "normal"

44 PRIORITY_HIGH = "high"

45 PRIORITY_CHOICES = (

46 (PRIORITY_DEFAULT, "Default"),

47 (PRIORITY_NORMAL, "Normal"),

48 (PRIORITY_HIGH, "High"),

49 )

50

51 priority = models.CharField(

52 max_length=7,

53 blank=True,

54 null=True,

55 choices=PRIORITY_CHOICES,

56 )

57

58 subtitle = models.CharField(

59 max_length=64,

60 blank=True,

61 )

62

63 sound = models.CharField(

64 max_length=64,

65 blank=True,

66 )

67

68 badge = models.PositiveSmallIntegerField(

69 blank=True,

70 null=True,

71 )

72

73 channel_id = models.CharField(

74 max_length=32,

75 blank=True,

76 )

77

78 category_id = models.CharField(

79 max_length=64,

80 blank=True,

81 )

82

83 mutable_content = models.BooleanField(

84 default=False,

85 )

86

87 date_created = models.DateTimeField(

88 default=timezone.now,

89 )

90

91 def __str__(self) -> str:

92 return f"Message #{self.pk}"

93

94 def to_push_message(self) -> PushMessage:

95 return PushMessage(

96 to=self.device.push_token,

97 data=self.data,

98 title=self.title or None,

99 body=self.body or None,

100 sound=self.sound or None,

101 ttl=self.ttl.total_seconds() if self.ttl else None,

102 expiration=self.expiration.timestamp() if self.expiration else None,

103 priority=self.priority or None,

104 badge=self.badge,

105 category=self.category_id or None,

106 display_in_foreground=None,

107 channel_id=self.channel_id or None,

108 subtitle=self.subtitle or None,

109 mutable_content=self.mutable_content,

110 )

111

112 def send(self) -> None:

113 from expo_notifications.tasks import send_messages

114

115 send_messages.delay_on_commit([self.pk])