-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.py
83 lines (70 loc) · 2.87 KB
/
client.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
from flask import Flask, request, render_template, url_for, redirect
import requests
import urllib.parse
import datetime
app = Flask(__name__)
HUB_AUTHKEY = '1234567890'
HUB_URL = 'http://localhost:5555'
CHANNELS = None
LAST_CHANNEL_UPDATE = None
def update_channels():
global CHANNELS, LAST_CHANNEL_UPDATE
if CHANNELS and LAST_CHANNEL_UPDATE and (datetime.datetime.now() - LAST_CHANNEL_UPDATE).seconds < 60:
return CHANNELS
# fetch list of channels from server
response = requests.get(HUB_URL + '/channels', headers={'Authorization': 'authkey ' + HUB_AUTHKEY})
if response.status_code != 200:
return "Error fetching channels: "+str(response.text), 400
channels_response = response.json()
if not 'channels' in channels_response:
return "No channels in response", 400
CHANNELS = channels_response['channels']
LAST_CHANNEL_UPDATE = datetime.datetime.now()
return CHANNELS
@app.route('/')
def home_page():
# fetch list of channels from server
return render_template("home.html", channels=update_channels())
@app.route('/show')
def show_channel():
# fetch list of messages from channel
show_channel = request.args.get('channel', None)
if not show_channel:
return "No channel specified", 400
channel = None
for c in update_channels():
if c['endpoint'] == urllib.parse.unquote(show_channel):
channel = c
break
if not channel:
return "Channel not found", 404
response = requests.get(channel['endpoint'], headers={'Authorization': 'authkey ' + channel['authkey']})
if response.status_code != 200:
return "Error fetching messages: "+str(response.text), 400
messages = response.json()
return render_template("channel.html", channel=channel, messages=messages)
@app.route('/post', methods=['POST'])
def post_message():
# send message to channel
post_channel = request.form['channel']
if not post_channel:
return "No channel specified", 400
channel = None
for c in update_channels():
if c['endpoint'] == urllib.parse.unquote(post_channel):
channel = c
break
if not channel:
return "Channel not found", 404
message_content = request.form['content']
message_sender = request.form['sender']
message_timestamp = datetime.datetime.now().isoformat()
response = requests.post(channel['endpoint'],
headers={'Authorization': 'authkey ' + channel['authkey']},
json={'content': message_content, 'sender': message_sender, 'timestamp': message_timestamp})
if response.status_code != 200:
return "Error posting message: "+str(response.text), 400
return redirect(url_for('show_channel')+'?channel='+urllib.parse.quote(post_channel))
# Start development web server
if __name__ == '__main__':
app.run(port=5005, debug=True)