11#!/usr/bin/env python3
22
3- from flask import Flask , send_from_directory , request
3+ from flask import Flask , send_from_directory
44import flask_restful as restful
55from flask_cors import CORS
6-
7- import time
6+ from flask_socketio import SocketIO , emit
87
98app = Flask (__name__ )
109CORS (app )
1110api = restful .Api (app )
11+ app .config ['SECRET_KEY' ] = 'secret!'
12+ socketio = SocketIO (app )
1213
1314app .config ['SEND_FILE_MAX_AGE_DEFAULT' ] = 0
1415
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-
3616@app .route ('/' )
3717def index ():
3818 return open ('dev/index.html' ).read ()
@@ -43,29 +23,27 @@ def send_js(path):
4323 return send_from_directory ('dev' , path )
4424
4525
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 }
5326
5427
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 = []
6229
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 )
6636
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 )
6743
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 )
6947
7048if __name__ == '__main__' :
71- app .run (port = 8000 , debug = True )
49+ socketio .run (app )
0 commit comments