1
1
#!/usr/bin/env python3
2
2
3
- from flask import Flask , send_from_directory , request
3
+ from flask import Flask , send_from_directory
4
4
import flask_restful as restful
5
5
from flask_cors import CORS
6
-
7
- import time
6
+ from flask_socketio import SocketIO , emit
8
7
9
8
app = Flask (__name__ )
10
9
CORS (app )
11
10
api = restful .Api (app )
11
+ app .config ['SECRET_KEY' ] = 'secret!'
12
+ socketio = SocketIO (app )
12
13
13
14
app .config ['SEND_FILE_MAX_AGE_DEFAULT' ] = 0
14
15
15
- history = [1 ] # TODO: use an ordered dict instead
16
- history_patch = {1 : {
17
- 'cursor' : {},
18
- 'dom' : [
19
- {
20
- 'type' : 'add' , 'append' : 1 , 'id' : 1 , 'node' :
21
- {
22
- 'nodeType' : 1 , 'oid' : 1873262997 ,
23
- 'tagName' : 'H1' ,
24
- 'children' : [{
25
- 'nodeType' : 3 , 'oid' : 1550618946 ,
26
- 'textValue' : 'A Collaborative Title'
27
- }],
28
- 'attributes' : {}
29
- }
30
- }
31
- ],
32
- 'id' : 1
33
- }}
34
-
35
-
36
16
@app .route ('/' )
37
17
def index ():
38
18
return open ('dev/index.html' ).read ()
@@ -43,29 +23,27 @@ def send_js(path):
43
23
return send_from_directory ('dev' , path )
44
24
45
25
46
- @app .route ('/history-push' , methods = ['POST' ])
47
- def history_push ():
48
- data = request .get_json ()
49
- print (data )
50
- history .append (data ['id' ])
51
- history_patch [data ['id' ]] = data
52
- return {'status' : 200 }
53
26
54
27
55
- class history_get (restful .Resource ):
56
- def get (self , oid = 0 ):
57
- index = 0
58
- if oid :
59
- index = history .index (oid ) + 1
60
- while index == len (history ):
61
- time .sleep (0.1 )
28
+ history = []
62
29
63
- result = [history_patch [x ] for x in history [index :]]
64
- print ('Get After' , oid , ':' , [x for x in history [index :]])
65
- return result
30
+ @socketio .on ('step' )
31
+ def on_history_step (step ):
32
+ step_index = len (history )
33
+ step ['index' ] = step_index
34
+ history .append (step )
35
+ emit ('step' , step , broadcast = True , json = True )
66
36
37
+ @socketio .on ('init' )
38
+ def on_init (incoming_history ):
39
+ if len (history ) == 0 :
40
+ history .extend (incoming_history )
41
+ else :
42
+ emit ('synchronize' , history , json = True )
67
43
68
- api .add_resource (history_get , '/history-get/<int:oid>' )
44
+ @socketio .on ('needSync' )
45
+ def on_need_sync ():
46
+ emit ('synchronize' , history , json = True )
69
47
70
48
if __name__ == '__main__' :
71
- app .run (port = 8000 , debug = True )
49
+ socketio .run (app )
0 commit comments