forked from venkateshshukla/tpo-forum-notification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send.py
195 lines (157 loc) · 5.12 KB
/
send.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#!/usr/bin/env python
# Send notification to subscribers on finding any new notice.
# For sending notifications, Pushbullet API is used. This gives the benefit of
# multiplatform support (Chrome, android and firefox) and easy implementation.
# For more details on Pushbullet API, look at https://docs.pushbullet.com/
import os
import sys
import json
import requests
import logging
import view
import update
from notice import Notice
from notice_db import NoticeWrapper
root = os.path.abspath(os.path.dirname(__file__))
path = root + "/gen/json/"
def push(title, body):
"""
Given the title and body of notification to be sent, send it to the
pushbullet servers.
params:
title : the title of notification to be sent
body : the body of the notification to be sent
"""
logging.debug("called : %s", __name__)
# Pushbullet needs access token to your account.
# Add environmental variables
# TPO_PB_AUTH - The pushbullet auth token
# TPO_PB_CHANNEL - The pushbullet channel name
logging.info("preparing to send post request to pushbullet")
push_url = "https://api.pushbullet.com/v2/pushes"
auth_token = os.environ.get("TPO_PB_AUTH")
channel_tag = os.environ.get("TPO_PB_CHANNEL")
auth = requests.auth.HTTPBasicAuth(auth_token, '')
headers = {'content-type' : 'application/json'}
payload = {}
payload['type'] = 'note'
payload['title'] = title
payload['body'] = body
payload['channel_tag'] = channel_tag
data = json.dumps(payload)
response = requests.post(push_url, auth=auth, headers=headers,
data=data)
logging.info("Recieved response status code : %d", response.status_code)
if response.status_code == 200:
print "Success"
logging.info("push successfully sent")
return True
else:
print "Failed,", response.status_code, response.reason
logging.error("sending push failed : %d : %s",
response.status_code, response.reason)
return False
def send_json(notice):
'''Send the notification of notice for given json'''
logging.debug("called : %s", __name__)
logging.debug("argument notice : %s", str(notice))
if notice is None:
logging.error("empty notice is recieved")
return
time = notice['time']
title = notice['title']
body = view.get_text_dict(notice, True)
print "Sending notice {} dated {}.".format(title, time)
logging.info("Sending notice %s dated %s.", title, time)
return push(title, body)
def send_notice(notice):
"""
Given a database Notice instance, send its notification.
"""
logging.debug("called : %s", __name__)
if notice is None:
logging.error("empty notice is recieved")
return
time = notice.print_time
title = notice.title
body = view.get_text_notice(notice, True)
print "Sending notice {} dated {}.".format(title, time)
logging.info("Sending notice %s dated %s.", title, time)
return push(title, body)
def send_name(filename):
'''Send the notification for the notice of given json filename'''
logging.debug("called : %s", __name__)
logging.debug("argument filename : %s", filename)
if filename is None:
logging.error("empty filename received")
return
n = Notice(filename)
notice = n.get_json()
# If the notice is not updated, update it.
logging.debug("checking if notice is updated")
if not notice['updated']:
update.update_json(filename)
notice = n.get_json()
# If the notice is not sent, send it.
logging.debug("checking if notice is sent")
if not notice['sent']:
if send_json(notice):
# If notice is sent, save it locally. So that it is not
# sent again.
logging.debug("notice is sent - saving it locally")
notice['sent'] = True
n.save_json(notice)
return True
else:
logging.error("failed sending notice")
return False
else:
logging.debug("notice is already sent")
return False
def send_unsent():
'''Send notifications for all notices that have not been sent yet.'''
logging.debug("called : %s", __name__)
filelist = os.listdir(path)
if 'old' in filelist:
filelist.remove('old')
# Sorted filelist so that older json files are listed earlier. Due to
# this, notices are sent in the order in which they arrive.
filelist.sort()
send_count = 0
for f in filelist:
if send_name(f):
send_count += 1
print "\r%d notifications sent."%send_count
if send_count == 0:
print "0 notifications sent."
else:
print ""
logging.info("%d notifications sent", send_count)
return send_count
def send_unsent_db():
"""
Send notification for all the unsent notices from the database
"""
notices = NoticeWrapper.get_unsent()
send_count = 0
for notice in notices:
if send_notice(notice):
NoticeWrapper.sent(notice)
send_count += 1
print "\r%d notifications sent."%send_count
if send_count == 0:
print "0 notifications sent."
else:
print ""
logging.info("%d notifications sent", send_count)
return send_count
if __name__ == "__main__":
log_level = logging.INFO
log_format = "%(asctime)s\t%(levelname)s\t%(filename)s\t%(funcName)s()\t%(message)s"
logging.basicConfig(format=log_format, level=log_level)
logging.info("starting %s", __file__)
if len(sys.argv) == 2 and sys.argv[1] == 'db':
s = send_unsent_db()
else:
s = send_unsent()
logging.info("finished %s", __file__)