-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotifier.py
More file actions
216 lines (190 loc) · 8.13 KB
/
notifier.py
File metadata and controls
216 lines (190 loc) · 8.13 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import xbmc
import xbmcgui
import requests
import os
import time
import unicodedata
# Script constants
SCRIPT_NAME = 'xChat'
BASE_URL = 'https://bsky.social/xrpc/'
CHAT_URL = 'https://api.bsky.chat/xrpc/'
CHECK_INTERVAL = 5 # Interval in seconds to check for new messages and notifications
LOGIN_FILE = os.path.join(os.path.dirname(__file__), 'login.txt')
MESSAGES_FILE = os.path.join(os.path.dirname(__file__), 'messages.txt')
HANDLES_FILE = os.path.join(os.path.dirname(__file__), 'handles.txt')
NOTIFICATIONS_FILE = os.path.join(os.path.dirname(__file__), 'notifications.txt') # File to keep track of notifications
# Load login credentials
def load_credentials():
if os.path.exists(LOGIN_FILE):
with open(LOGIN_FILE, 'r') as f:
lines = f.readlines()
if len(lines) >= 2:
return lines[0].strip(), lines[1].strip()
return None, None
# Authenticate with BlueSky using app password
def authenticate(username, app_password):
url = BASE_URL + 'com.atproto.server.createSession'
data = {
'identifier': username,
'password': app_password
}
try:
response = requests.post(url, json=data)
response.raise_for_status()
xbmc.log("{}: Authentication successful".format(SCRIPT_NAME), xbmc.LOGINFO)
return response.json()
except requests.exceptions.RequestException as e:
xbmc.log("{}: Authentication failed. Error: {}".format(SCRIPT_NAME, str(e)), xbmc.LOGERROR)
return None
# Fetch notifications from BlueSky
def fetch_notifications(session):
url = BASE_URL + 'app.bsky.notification.listNotifications'
headers = {
'Authorization': 'Bearer ' + session['accessJwt']
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # Raise an error for bad status codes
return response.json().get('notifications', [])
except requests.exceptions.RequestException as e:
xbmcgui.Dialog().ok(SCRIPT_NAME, 'Failed to fetch notifications. Error: {}'.format(str(e)))
return []
# Fetch conversations from BlueSky
def fetch_conversations(session):
url = CHAT_URL + 'chat.bsky.convo.listConvos'
headers = {
'Authorization': 'Bearer ' + session['accessJwt']
}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
convos = response.json().get('convos', [])
return convos
except requests.exceptions.RequestException as e:
xbmc.log("{}: Failed to fetch conversations. Error: {}".format(SCRIPT_NAME, str(e)), xbmc.LOGERROR)
return []
# Fetch messages for a conversation from BlueSky
def fetch_messages(session, convo_id):
url = CHAT_URL + 'chat.bsky.convo.getMessages'
headers = {
'Authorization': 'Bearer ' + session['accessJwt']
}
params = {
'convoId': convo_id
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
messages = response.json().get('messages', [])
# Collect all DIDs to fetch profiles in bulk
dids = {message['sender']['did'] for message in messages if 'sender' in message and 'did' in message['sender']}
profiles = load_profiles()
new_profiles = {did: fetch_profile(session, did) for did in dids if did not in profiles}
profiles.update(new_profiles)
save_profiles(new_profiles)
# Ensure each message has the sender's handle
for message in messages:
if 'sender' in message and 'did' in message['sender']:
sender_profile = profiles.get(message['sender']['did'], {})
message['sender']['handle'] = sender_profile.get('handle', 'Unknown')
# Sanitize message text
for message in messages:
if 'text' in message:
message['text'] = sanitize_text(message['text'])
return messages
except requests.exceptions.RequestException as e:
xbmc.log("{}: Failed to fetch messages. Error: {}".format(SCRIPT_NAME, str(e)), xbmc.LOGERROR)
return []
# Fetch profile information from BlueSky
def fetch_profile(session, did):
url = BASE_URL + 'app.bsky.actor.getProfile'
headers = {
'Authorization': 'Bearer ' + session['accessJwt']
}
params = {
'actor': did
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
xbmc.log("{}: Failed to fetch profile. Error: {}".format(SCRIPT_NAME, str(e)), xbmc.LOGERROR)
return {}
# Load profiles from file
def load_profiles():
if os.path.exists(HANDLES_FILE):
with open(HANDLES_FILE, 'r') as f:
return {line.split(",")[0]: {"handle": line.split(",")[1].strip()} for line in f}
return {}
# Save profiles to file
def save_profiles(profiles):
with open(HANDLES_FILE, 'a') as f:
for did, profile in profiles.items():
f.write("{},{}\n".format(did, profile.get('handle', 'Unknown')))
# Load old message IDs from file
def load_old_message_ids():
if os.path.exists(MESSAGES_FILE):
with open(MESSAGES_FILE, 'r') as f:
return set(line.strip() for line in f)
return set()
# Save new message ID to file
def save_message_id(message_id):
with open(MESSAGES_FILE, 'a') as f:
f.write(message_id + '\n')
# Load old notification IDs from file
def load_old_notification_ids():
if os.path.exists(NOTIFICATIONS_FILE):
with open(NOTIFICATIONS_FILE, 'r') as f:
return set(line.strip() for line in f)
return set()
# Save new notification ID to file
def save_notification_id(notification_id):
if notification_id is not None:
with open(NOTIFICATIONS_FILE, 'a') as f:
f.write(str(notification_id) + '\n')
# Sanitize text by removing non-ASCII characters
def sanitize_text(text):
return ''.join(char for char in text if ord(char) < 128)
# Main service loop
def main():
username, app_password = load_credentials()
if not username or not app_password:
xbmc.log("{}: Please enter your BlueSky username and app password in login.txt.".format(SCRIPT_NAME), xbmc.LOGERROR)
return
session = authenticate(username, app_password)
if not session:
return
old_message_ids = load_old_message_ids()
old_notification_ids = load_old_notification_ids()
user_did = session.get('did')
while True:
convos = fetch_conversations(session)
for convo in convos:
messages = fetch_messages(session, convo.get('id'))
for message in messages:
message_id = message.get('id')
if message_id not in old_message_ids:
# Skip messages sent by the logged-in user
if message.get('sender', {}).get('did') == user_did:
continue
old_message_ids.add(message_id)
save_message_id(message_id)
user_handle = message.get('sender', {}).get('handle', 'Unknown')
text = message.get('text', 'No text')
xbmc.executebuiltin('Notification("{0}", "{1}", 5000, "")'.format(user_handle, sanitize_text(text)))
notifications = fetch_notifications(session)
for notification in notifications:
notification_id = notification.get('cid')
if notification_id not in old_notification_ids:
old_notification_ids.add(notification_id)
save_notification_id(notification_id)
reason = notification.get('reason', 'No Title')
author = notification.get('author', {})
user_handle = author.get('handle', 'Unknown user')
message = notification.get('record', {}).get('text', '')
notification_text = "{}: {}".format(reason.capitalize(), user_handle, message)
xbmc.executebuiltin('Notification("xSky", "{}", 5000, "N/A")'.format(sanitize_text(notification_text)))
xbmc.sleep(CHECK_INTERVAL * 1000)
if __name__ == '__main__':
main()