forked from mrchainman/Gotify-Nextcloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
push_msg.py
executable file
·118 lines (100 loc) · 3.68 KB
/
push_msg.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
#!/usr/bin/env python3
import requests
import time
import logging
try:
from settings import *
except:
print('Please provide a settings.py file')
exit(0)
# Setup logging.
try:
if log_file:
logging.basicConfig(
filename=log_file,
filemode='a',
level=logging.INFO,
format='%(asctime)s %(levelname)8s - %(message)s'
)
except FileNotFoundError:
print('ERROR: Invalid log file path specified in settings.py')
exit(0)
except NameError:
# log_file is an optional, setting and may not be present in older config files
print('INFO: No logfile specified, logging is disabled')
pass
# set nextcloud header
headers = {'OCS-APIRequest': 'true',
'Content-Type': 'application/json',
'Accept': 'application/json'
}
# set gotify header
headerspush = {'X-Gotify-Key': token}
# create empty messages list
# TODO: Could we somehow replace the list with a generator to improve speed?
notifications = []
def get_notifications():
"""Retrieve notifications from nextcloud"""
try:
# retrieve json data from the notifications endpoint
full_url = '%s/ocs/v2.php/apps/notifications/api/v2/notifications' % url
r = requests.get(full_url, headers=headers, auth=(user, pw))
# load the json data
m = (r.json())
if r.status_code < 300:
# only handle success status codes
return m['ocs']['data']
else:
logging.error('failed to retrieve notifications - %s', r.text)
except requests.exceptions.RequestException as err:
logging.info('failed to connect to nextcloud - %s', repr(err))
except (ValueError, KeyError) as err:
logging.error('failed to parse notifications - %s', repr(err))
return []
def push_notification(notification_id, date, title, msg, priority):
"""Send the notification to the gotify server."""
try:
full_urlpush = '%s/message' % urlpush
response = requests.post(
full_urlpush,
headers=headerspush,
data={
'id': notification_id,
'date': date,
'title': title,
'message': msg,
'priority': priority}
)
except requests.exceptions.RequestException as e:
logging.error('push to gotify server failed - %s', repr(e))
return False
if response.status_code < 300:
return True
else:
logging.error('push to gotify server failed with HTTP status %s - %s',
response.status_code, response.text)
return False
# start infinite loop for listening
if __name__ == '__main__':
while True:
new_notification_list = get_notifications()
# Iterate over the notifications
for n in new_notification_list:
try:
n_id = n['notification_id'] # id
title = n['subject']
date = n['datetime']
msg = n['message'] or ' '
except (KeyError, AttributeError):
# invalid or unsupported notification format
logging.warning('Invalid notification object - %s', n)
continue
# check if message was already pushed
if n_id is None or n_id in notifications:
continue
# else send push notification
if push_notification(n_id, date, title, msg, notification_priority):
# Add the message to the list if successfully pushed to the Gotify server
notifications.append(n_id)
# wait before checking again
time.sleep(delay)