Skip to content

Commit c6970ce

Browse files
authored
Speed up load times (#404)
* Speed up load times * Rectified function comment
1 parent ab3b949 commit c6970ce

File tree

1 file changed

+16
-131
lines changed

1 file changed

+16
-131
lines changed

kano_draw/server.py

Lines changed: 16 additions & 131 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,7 @@
1717
from kano_world.share_helpers import login_and_share
1818
from kano.network import is_internet
1919
from kano.utils.audio import play_sound
20-
from kano.utils.file_operations import empty_directory, ensure_dir, \
21-
recursively_copy
20+
from kano.utils.file_operations import ensure_dir
2221
from kano.logging import logger
2322

2423

@@ -30,140 +29,22 @@
3029
STATIC_ASSET_DIR = os.path.join(os.path.expanduser('~'),
3130
'.make-art-assets')
3231

32+
# Create the directories if necessary
3333
ensure_dir(CHALLENGE_DIR)
3434
ensure_dir(WALLPAPER_DIR)
3535
ensure_dir(STATIC_ASSET_DIR)
3636

37-
38-
def _copy_package_assets():
39-
# Use abs paths for both src and dest for subsequent replacements to work
40-
src_dir = os.path.abspath(_get_package_static_dir())
41-
dest_dir = os.path.abspath(STATIC_ASSET_DIR)
42-
43-
# First Clear this cache
44-
empty_directory(dest_dir)
45-
46-
# Now copy the static assets
47-
recursively_copy(src_dir, dest_dir)
48-
49-
logger.info('Successfully copied over static assets')
50-
51-
52-
def _get_package_static_dir():
53-
bin_path = os.path.abspath(os.path.dirname(__file__))
54-
55-
if bin_path.startswith('/usr'):
56-
return '/usr/share/kano-draw'
57-
else:
58-
return os.path.abspath(os.path.join(bin_path, '../www'))
59-
60-
61-
def _get_co_assets():
62-
from kano_content.api import ContentManager
63-
64-
cm = ContentManager.from_local()
65-
66-
co_index = {}
67-
68-
for co in cm.list_local_objects(spec='make-art-assets'):
69-
co_files = co.get_data('').get_content()
70-
if len(co_files) != 2:
71-
logger.warning(
72-
'Count of files other than 2 in co[{}], skipping'.format(
73-
co.get_data('').get_dir()
74-
)
75-
)
76-
continue
77-
78-
# Check whether the first file is the index
79-
index_no = _get_co_index_apply_order(co_files[0])
80-
if index_no is not None:
81-
co_index[index_no] = co_files[1]
82-
else:
83-
# It wasn't the first one, go for the second one
84-
index_no = _get_co_index_apply_order(co_files[1])
85-
if index_no is not None:
86-
co_index[index_no] = co_files[0]
87-
else:
88-
err_msg = 'None of the files contained in co have apply index'
89-
logger.error(err_msg)
90-
continue
91-
92-
return co_index
93-
94-
95-
def _apply_co_packages(dest_dir):
96-
import tarfile
97-
98-
co_index = _get_co_assets()
99-
100-
for order in sorted(co_index.iterkeys()):
101-
tar_file = co_index[order]
102-
# First try to open the file
103-
try:
104-
tarball = tarfile.open(tar_file)
105-
except (IOError, OSError) as exc:
106-
err_msg = "Couldn't open file '{}', [{}]".format(tar_file, exc)
107-
logger.error(err_msg)
108-
continue
109-
except tarfile.ReadError as exc:
110-
err_msg = 'Error parsing tarfile "{}", [{}]'.format(tar_file, exc)
111-
logger.error(err_msg)
112-
continue
113-
else:
114-
# Now try to extract the files one by one
115-
with tarball:
116-
for tarred_file in tarball:
117-
try:
118-
tarball.extract(tarred_file, path=dest_dir)
119-
except IOError as exc:
120-
# This is to guard against weird tar behaviour when
121-
# trying to ovewrite symlinks
122-
bad_filename = os.path.join(dest_dir, tarred_file.name)
123-
if os.path.islink(bad_filename):
124-
logger.debug(
125-
'Remove link and ovewrite "{}"'.format(
126-
bad_filename)
127-
)
128-
os.remove(os.path.join(dest_dir, tarred_file.name))
129-
tarball.extract(tarred_file, path=dest_dir)
130-
131-
132-
def _get_co_index_apply_order(fname):
133-
index_no = None
134-
# Files names have absolute path
135-
if os.path.basename(fname) == 'index.json':
136-
try:
137-
index_fh = open(fname)
138-
except (IOError, OSError) as exc:
139-
err_msg = 'Error opening file "{}". [{}]'.format(
140-
fname,
141-
exc
142-
)
143-
logger.error(err_msg)
144-
else:
145-
with index_fh:
146-
try:
147-
ind_data = json.load(index_fh)
148-
index_no = ind_data['apply_order']
149-
except KeyError as exc:
150-
err_msg = ("JSON in '{}' doesn't contain right key: "
151-
"[{}]").format(fname, exc)
152-
logger.error(err_msg)
153-
except ValueError as exc:
154-
err_msg = 'File "{}" is not a valid JSON: [{}]'.format(
155-
fname,
156-
exc
157-
)
158-
logger.error(err_msg)
159-
return index_no
160-
161-
16237
def _get_static_dir():
163-
return STATIC_ASSET_DIR
38+
'''
39+
Returns directory where http server content is located
40+
'''
41+
return '/usr/share/kano-draw'
16442

16543

16644
def _get_image_from_str(img_str):
45+
'''
46+
Returns a base64 encoded data of the img_str image file.
47+
'''
16748
import base64
16849

16950
image_b64 = img_str.split(',')[-1]
@@ -173,6 +54,9 @@ def _get_image_from_str(img_str):
17354

17455

17556
def _save(data):
57+
'''
58+
Save the current creation in the user home directory
59+
'''
17660
filename = data['filename']
17761
try:
17862
desc = data['description']
@@ -202,13 +86,15 @@ def _save(data):
20286
return (filename, filepath)
20387

20488

205-
_copy_package_assets()
206-
_apply_co_packages(STATIC_ASSET_DIR)
89+
# Start the http server now
90+
20791
server = Flask(__name__, static_folder=_get_static_dir(), static_url_path='/')
20892
server_logger = logging.getLogger('werkzeug')
20993
server_logger.setLevel(logging.ERROR)
21094

21195

96+
# Server backend methods
97+
21298
@server.route('/')
21399
# Return the homepage for pages routed through Angular
214100
@server.route('/localLoad/<path:path>')
@@ -406,7 +292,6 @@ def page_not_found(err):
406292

407293
@server.route('/play_sound/<path:filename>', methods=['POST'])
408294
def play_sounds(filename):
409-
print os.path.realpath(os.path.join(_get_static_dir(), filename))
410295
sound_file = os.path.realpath(os.path.join(_get_static_dir(), filename))
411296
play_sound(sound_file)
412297

0 commit comments

Comments
 (0)