forked from GoBelieveIO/im_js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo.py
243 lines (178 loc) · 6.19 KB
/
demo.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# -*- coding: utf-8 -*-
from flask import request, Blueprint, redirect, url_for
from flask import render_template, send_from_directory
from flask import Flask
from flask import Response
from flask import g
import flask
from functools import wraps
import flask
import random
import md5
import json
import logging
import sys
import os
import redis
import base64
import requests
import config
app = Flask(__name__)
app.debug = config.DEBUG
def INVALID_PARAM():
e = {"error":"非法输入"}
return make_response(400, e)
def LOGIN_FAIL():
e = {"error":"登陆失败"}
return make_response(400, e)
def FORBIDDEN():
e = {"error":"forbidden"}
return make_response(403, e)
def make_response(status_code, data = None):
if data:
res = flask.make_response(json.dumps(data), status_code)
res.headers['Content-Type'] = "application/json"
else:
res = flask.make_response("", status_code)
return res
error_html = """<!DOCTYPE html>
<html>
<head>
<title>Chat Demo</title>
</head>
<body>
<p>error.</p>
</body>
</html>"""
def login(uid, uname, platform_id, device_id):
url = config.IM_URL + "/auth/grant"
obj = {"uid":uid, "user_name":uname}
logging.debug("platform:%s device:%s", platform_id, device_id)
if platform_id and device_id:
obj['platform_id'] = platform_id
obj['device_id'] = device_id
m = md5.new(config.APP_SECRET)
secret = m.hexdigest()
basic = base64.b64encode(str(config.APP_ID) + ":" + secret)
headers = {'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Basic ' + basic}
res = requests.post(url, data=json.dumps(obj), headers=headers)
if res.status_code != 200:
print res
return None
obj = json.loads(res.text)
return obj["data"]["token"]
@app.route("/login", methods=["POST"])
def login_session():
sender = int(request.form['sender']) if request.form.has_key('sender') else 0
receiver = int(request.form['receiver']) if request.form.has_key('receiver') else 0
if sender == 0 or receiver == 0:
return error_html
token = login(sender, '', None, None)
if not token:
return error_html
response = flask.make_response(redirect(url_for('.chat', sender=sender, receiver=receiver)))
response.set_cookie('token', token)
return response
@app.route("/chat")
def chat():
return render_template('chat.html', host=config.HOST)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/customer/chat')
def customer_chat():
return render_template('customer_chat.html', host=config.HOST)
@app.route('/customer/login', methods=["POST"])
def customer_login():
sender = int(request.form['sender']) if request.form.has_key('sender') else 0
receiver = int(request.form['receiver']) if request.form.has_key('receiver') else 0
if sender == 0 or receiver == 0:
return error_html
token = login(sender, '', None, None)
if not token:
return error_html
response = flask.make_response(redirect(url_for('.customer_chat', sender=sender, receiver=receiver)))
response.set_cookie('token', token)
return response
@app.route('/customer')
def customer():
return render_template('customer.html')
@app.route('/room/chat')
def room_chat():
return render_template('room_chat.html', host=config.HOST)
@app.route('/room/login', methods=["POST"])
def room_login():
sender = int(request.form['sender']) if request.form.has_key('sender') else 0
receiver = int(request.form['receiver']) if request.form.has_key('receiver') else 0
if sender == 0 or receiver == 0:
return error_html
token = login(sender, '', None, None)
if not token:
return error_html
response = flask.make_response(redirect(url_for('.room_chat', sender=sender, receiver=receiver)))
response.set_cookie('token', token)
return response
@app.route('/room')
def room_index():
return render_template('room_index.html')
@app.route('/group/chat')
def group_chat():
return render_template('group_chat.html', host=config.HOST)
@app.route('/group/login', methods=["POST"])
def group_login():
sender = int(request.form['sender']) if request.form.has_key('sender') else 0
receiver = int(request.form['receiver']) if request.form.has_key('receiver') else 0
if sender == 0 or receiver == 0:
return error_html
token = login(sender, '', None, None)
if not token:
return error_html
response = flask.make_response(redirect(url_for('.group_chat', sender=sender, receiver=receiver)))
response.set_cookie('token', token)
return response
@app.route('/group')
def group_index():
return render_template('group_index.html')
@app.route('/voip')
def voip_chat():
sender = int(request.args.get('sender')) if request.args.get('sender') else 0
if not sender:
return error_html
token = login(sender, '', None, None)
if not token:
return error_html
response = flask.make_response(render_template('voip_chat.html', host=config.HOST))
response.set_cookie('token', token)
return response
@app.route('/favicon.ico')
def favicon():
return send_from_directory(app.root_path,
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route("/auth/token", methods=["POST"])
def access_token():
if not request.data:
return INVALID_PARAM()
obj = json.loads(request.data)
uid = obj["uid"] if obj.has_key("uid") else None
user_name = obj["user_name"] if obj.has_key("user_name") else ""
if not uid:
return INVALID_PARAM()
logging.debug("obj:%s", obj)
token = login(uid, user_name, obj.get('platform_id'), obj.get('device_id'))
if not token:
return LOGIN_FAIL()
obj = {"token":token}
return make_response(200, obj)
def init_logger(logger):
root = logger
root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(filename)s:%(lineno)d - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
log = logging.getLogger('')
init_logger(log)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5001)