forked from ultide/ultide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
executable file
·150 lines (118 loc) · 4.37 KB
/
server.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
#!/usr/bin/env python
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best option based on available packages.
async_mode = None
if async_mode is None:
try:
import eventlet
async_mode = 'eventlet'
except ImportError:
pass
if async_mode is None:
try:
from gevent import monkey
async_mode = 'gevent'
except ImportError:
pass
if async_mode is None:
async_mode = 'threading'
print('async_mode is ' + async_mode)
# monkey patching is necessary because this application uses a background
# thread
if async_mode == 'eventlet':
import eventlet
eventlet.monkey_patch()
elif async_mode == 'gevent':
from gevent import monkey
monkey.patch_all()
import time
from flask import Flask, render_template, session, request, send_from_directory, make_response
from functools import wraps, update_wrapper
from flask_socketio import SocketIO, emit, disconnect
import ultide.config as config
from flask_user import login_required, UserManager, UserMixin, SQLAlchemyAdapter
from datetime import datetime
from ultide.models import db, User
import os
import os.path
import ultide.core as core
import uuid
import ultide.common as common
import json
from datetime import datetime
import sys
app = Flask(__name__)
app.config.from_object(config)
socketio = SocketIO(app, async_mode=async_mode)
thread = None
db.app = app
db.init_app(app)
# Create all database tables
db.create_all()
# Setup Flask-User
db_adapter = SQLAlchemyAdapter(db, User) # Register the User model
common.user_manager = UserManager(db_adapter, app) # Initialize Flask-User
if not User.query.filter(User.username=='root').first():
user1 = User(username='root', email='[email protected]', confirmed_at=datetime.now(), active=True,
password=common.user_manager.hash_password('root'))
db.session.add(user1)
db.session.commit()
sessions_data = {}
def nocache(view):
@wraps(view)
def no_cache(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers['Last-Modified'] = datetime.now()
response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '-1'
return response
return update_wrapper(no_cache, view)
def get_init_session_data():
data = {}
data['modules_infos'] = {'core': {'main': core, 'path': 'ultide'}}
return data
@app.route('/')
def index():
session['uuid'] = str(uuid.uuid4())
return render_template('index.html')
@socketio.on('msg', namespace='/uide')
def msg_received(message):
session_data = sessions_data[session['uuid']]
request_id = message['request_id']
method = 'on_' + message['request']
response = {'request_id': request_id}
if ('user' in session_data or method == 'on_login'):
data = message['data']
response_data = {}
for module_key in session_data['modules_infos']:
print 'module:', module_key
module_infos = session_data['modules_infos'][module_key]
if ('main' in module_infos):
module_py = module_infos['main']
if (hasattr(module_py, method)):
print 'module method', module_key, method
getattr(module_py, method)(data, response_data, session_data)
print response
response['data'] = response_data
else:
response['auth_error'] = True
emit('msg', response)
@app.route('/static/modules/<path:path>', methods=['GET'])
@nocache
def modules_static(path):
session_data = sessions_data[session['uuid']]
splitted_path = path.split('/')
module = splitted_path.pop(0)
module_path = session_data['modules_infos'][module]['path'] + os.path.sep + 'static'
return send_from_directory(module_path, '/'.join(splitted_path))
@socketio.on('connect', namespace='/uide')
def test_connect():
sessions_data[session['uuid']] = get_init_session_data()
@socketio.on('disconnect', namespace='/uide')
def test_disconnect():
sessions_data.pop(session['uuid'], None)
print('Client disconnected', request.sid, session['uuid'])
if __name__ == '__main__':
socketio.run(app, debug=True)