-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUser.py
68 lines (57 loc) · 2.38 KB
/
User.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
# User.py
import pika
import json
import sys
from functools import partial
class UserClient:
def __init__(self, user, action=None, youtuber=None, host='127.0.0.1'):
self.user = user
self.action = action
self.youtuber = youtuber
credentials = pika.PlainCredentials('user', 'user')
parameters = pika.ConnectionParameters(host, credentials=credentials)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
self.channel.queue_declare(queue='user_requests')
def updateSubscription(self):
if self.action is None:
self.action = 'login'
elif self.action == 's':
self.action = 'subscribe'
elif self.action == 'u':
self.action = 'unsubscribe'
request = json.dumps({
'user': self.user,
'action': self.action,
'youtuber': self.youtuber
})
self.channel.basic_publish(exchange='', routing_key='user_requests', body=request)
print(f"SUCCESS: {self.user} sent a {self.action} request")
def receiveNotifications(self):
user_queue = f"{self.user}_notifications"
self.channel.queue_declare(queue=user_queue)
on_message_callback_with_user = partial(self.print_notification, user=self.user)
self.channel.basic_consume(queue=user_queue, on_message_callback=on_message_callback_with_user, auto_ack=True)
print("Waiting for notifications...")
self.channel.start_consuming()
@staticmethod
def print_notification(ch, method, properties, body, user):
notification = json.loads(body)
youtuber = notification['youtuber']
video = notification['video']
print(f"New Notification: {youtuber} uploaded {video}")
if __name__ == "__main__":
try:
if len(sys.argv) < 2:
print("Usage: python User.py <user> [<action>] [<youtuber>]")
sys.exit(1)
user = sys.argv[1]
action = sys.argv[2] if len(sys.argv) > 2 else None
youtuber = sys.argv[3] if len(sys.argv) > 3 else None
client = UserClient(user, action, youtuber, '10.190.0.2')
client.updateSubscription()
client.receiveNotifications()
except KeyboardInterrupt:
print("\nInterrupted by user. Closing connection...")
client.connection.close()
sys.exit(0)