]> git.ipfire.org Git - ipfire.org.git/blame - src/backend/campaigns.py
campaigns: Decrease verbosity when sending emails
[ipfire.org.git] / src / backend / campaigns.py
CommitLineData
d73bba54
MT
1#!/usr/bin/python3
2
3import logging
4
5from .decorators import *
6from .misc import Object
7
8class Campaigns(Object):
18c38597 9 async def launch_manually(self, name, uid):
d73bba54
MT
10 account = self.backend.accounts.get_by_uid(uid)
11 if account:
18c38597 12 self.launch(name, account)
d73bba54 13
18c38597 14 def launch(self, name, account):
d73bba54
MT
15 logging.debug("Launching all campaigns for %s" % account)
16
17 # Update old timestamps first
18 self.db.execute("UPDATE campaign_templates \
19 SET launch_at = launch_at + repeat_after \
20 WHERE (launch_at IS NOT NULL AND launch_at <= CURRENT_TIMESTAMP) \
21 AND repeat_after IS NOT NULL")
22
23 # Launch all campaigns
24 self.db.execute("INSERT INTO campaign_emails(account_uid, template, \
18c38597 25 launch_at, repeat_after) \
d73bba54 26 SELECT %s, template, COALESCE(launch_at, CURRENT_TIMESTAMP + launch_after), \
18c38597
MT
27 repeat_after FROM campaign_templates WHERE name = %s",
28 account.uid, name)
d73bba54
MT
29
30 def _get_campaign_emails(self, query, *args):
31 res = self.db.query(query, *args)
32
33 for row in res:
34 yield CampaignEmail(self.backend, row.id, data=row)
35
36 async def run(self):
37 with self.db.transaction():
38 emails = self._get_campaign_emails("SELECT * FROM campaign_emails \
39 WHERE launch_at <= CURRENT_TIMESTAMP ORDER BY launch_at")
40
41 # Send them all
42 for email in emails:
43 email.send()
44
45
46class CampaignEmail(Object):
47 def init(self, id, data=None):
48 self.id = id
49 self.data = data
50
51 @lazy_property
52 def account(self):
53 return self.backend.accounts.get_by_uid(self.data.account_uid)
54
55 @property
56 def template(self):
57 return self.data.template
58
59 @property
60 def repeat_after(self):
61 return self.data.repeat_after
62
63 def send(self):
64 # Delete if the account does not exist any more
65 if not self.account:
66 return self._delete()
67
54764eeb 68 logging.debug("Sending %s to %s" % (self.template, self.account))
d73bba54
MT
69
70 # Generate the email
71 self.backend.messages.send_template(self.template, account=self.account)
72
73 # Update this email for the next launch
74 self._update()
75
76 def _update(self):
77 # If this email repeats, we will update the timestamp
78 if self.repeat_after:
79 self.db.execute("UPDATE campaign_emails \
80 SET launch_at = launch_at + repeat_after \
81 WHERE id = %s", self.id)
82
83 # Otherwise we will delete it
84 else:
85 self._delete()
86
87 def _delete(self):
88 """
89 Deletes this email
90 """
91 self.db.execute("DELETE FROM campaign_emails WHERE id = %s", self.id)