-
Notifications
You must be signed in to change notification settings - Fork 0
/
g4l_rlms_vascak.py
289 lines (222 loc) · 9.08 KB
/
g4l_rlms_vascak.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# -*-*- encoding: utf-8 -*-*-
import os
import re
import sys
import time
import sys
import urlparse
import json
import datetime
import uuid
import hashlib
import threading
import Queue
import functools
import traceback
import pprint
import requests
from bs4 import BeautifulSoup
from flask import Blueprint, request, url_for
from flask.ext.wtf import TextField, PasswordField, Required, URL, ValidationError
from labmanager.forms import AddForm
from labmanager.rlms import register, Laboratory, CacheDisabler, LabNotFoundError, register_blueprint
from labmanager.rlms.base import BaseRLMS, BaseFormCreator, Capabilities, Versions
from labmanager.rlms.queue import QueueTask, run_tasks
def dbg(msg):
if DEBUG:
print "[%s]" % time.asctime(), msg
sys.stdout.flush()
def dbg_lowlevel(msg, scope):
if DEBUG_LOW_LEVEL:
print "[%s][%s][%s]" % (time.asctime(), threading.current_thread().name, scope), msg
sys.stdout.flush()
class VascakAddForm(AddForm):
DEFAULT_URL = 'https://www.vascak.cz'
DEFAULT_LOCATION = 'Czech Republic'
DEFAULT_PUBLICLY_AVAILABLE = True
DEFAULT_PUBLIC_IDENTIFIER = 'vascak'
DEFAULT_AUTOLOAD = True
def __init__(self, add_or_edit, *args, **kwargs):
super(VascakAddForm, self).__init__(*args, **kwargs)
self.add_or_edit = add_or_edit
@staticmethod
def process_configuration(old_configuration, new_configuration):
return new_configuration
class VascakFormCreator(BaseFormCreator):
def get_add_form(self):
return VascakAddForm
class ObtainVascakLabDataTask(QueueTask):
def __init__(self, laboratory_id, session):
self.session = session
self.result = {}
super(ObtainVascakLabDataTask, self).__init__(laboratory_id)
def task(self):
text = self.session.get(self.laboratory_id).text
soup = BeautifulSoup(text, 'lxml')
# TODO
self.result = {
'url' : base_url + '?' + args,
'sim_url': simulator_link
}
MIN_TIME = datetime.timedelta(hours=24)
def get_laboratories():
laboratories = VASCAK.rlms_cache.get('get_laboratories', min_time = MIN_TIME)
if laboratories:
return laboratories
index = requests.get('https://www.vascak.cz/physicsanimations.php?l=en').text
soup = BeautifulSoup(index, 'lxml')
identifiers = {
# identifier: name
}
for anchor_link in soup.find_all('a'):
if anchor_link.get('href', '').startswith('data/android/physicsatschool/templateimg'):
href = anchor_link['href']
query = urlparse.urlparse(href).query
params = dict(urlparse.parse_qsl(query))
identifier = params.get('s')
if identifier:
images = anchor_link.find_all('img')
if images and identifier not in identifiers:
title = images[0].get('title') or identifier
identifiers[identifier] = title
labs = []
for identifier, name in identifiers.items():
lab = Laboratory(name=name, laboratory_id=identifier, description=identifier)
labs.append(lab)
VASCAK.rlms_cache['get_laboratories'] = labs
return labs
FORM_CREATOR = VascakFormCreator()
CAPABILITIES = [ Capabilities.WIDGET, Capabilities.URL_FINDER, Capabilities.TRANSLATION_LIST, Capabilities.CHECK_URLS ]
class RLMS(BaseRLMS):
def __init__(self, configuration, *args, **kwargs):
self.configuration = json.loads(configuration or '{}')
def get_version(self):
return Versions.VERSION_1
def get_capabilities(self):
return CAPABILITIES
def get_laboratories(self, **kwargs):
return get_laboratories()
def get_base_urls(self):
return [ 'http://www.vascak.cz', 'https://www.vascak.cz' ]
def get_lab_by_url(self, url):
query = urlparse.urlparse(url).query
params = dict(urlparse.parse_qsl(query))
identifier = params.get('s')
if not identifier:
return None
laboratories = get_laboratories()
for lab in laboratories:
if lab.laboratory_id == identifier:
return lab
return None
def get_translation_list(self, laboratory_id):
KEY = 'languages'
languages = VASCAK.cache.get(KEY)
if languages is None:
languages = set([])
index = requests.get('https://www.vascak.cz/physicsanimations.php?l=en').text
soup = BeautifulSoup(index, 'lxml')
for anchor in soup.find_all('a'):
href = anchor.get('href') or ''
query = urlparse.urlparse(href).query
params = dict(urlparse.parse_qsl(query))
language = params.get('language')
if language:
if language == 'ua':
language = 'uk'
languages.add(language)
VASCAK.cache[KEY] = list(languages)
return {
'supported_languages' : languages
}
def get_check_urls(self, laboratory_id):
return [ 'https://www.vascak.cz/data/android/physicsatschool/canvas/{identifier}_Canvas.html?l=en'.format(identifier=laboratory_id) ]
def reserve(self, laboratory_id, username, institution, general_configuration_str, particular_configurations, request_payload, user_properties, *args, **kwargs):
locale = kwargs.get('locale', 'en')
if '_' in locale:
locale = locale.split('_')[0]
url = create_url(laboratory_id, locale)
response = {
'reservation_id' : laboratory_id,
'load_url' : url,
}
return response
def load_widget(self, reservation_id, widget_name, **kwargs):
locale = kwargs.get('locale', 'en')
if '_' in locale:
locale = locale.split('_')[0]
return {
'url' : create_url(reservation_id, locale)
}
def list_widgets(self, laboratory_id, **kwargs):
default_widget = dict( name = 'default', description = 'Default widget' )
return [ default_widget ]
class VascakTaskQueue(QueueTask):
RLMS_CLASS = RLMS
def populate_cache(rlms):
rlms.get_laboratories()
VASCAK = register("Vascak", ['1.0'], __name__)
VASCAK.add_local_periodic_task('Populating cache', populate_cache, hours = 23)
DEBUG = VASCAK.is_debug() or (os.environ.get('G4L_DEBUG') or '').lower() == 'true' or False
DEBUG_LOW_LEVEL = DEBUG and (os.environ.get('G4L_DEBUG_LOW') or '').lower() == 'true'
if DEBUG:
print("Debug activated")
if DEBUG_LOW_LEVEL:
print("Debug low level activated")
vascak_blueprint = Blueprint('vascak', __name__)
def create_url(identifier, locale):
# vascak uses 'ua' to identify Ukranian language.
# In reality, the standard identifier is 'uk'.
# So when we see 'uk' we change it to 'ua'
if locale == 'uk':
locale = 'ua'
return "https://www.vascak.cz/data/android/physicsatschool/canvas/{identifier}_Canvas.html?l={language}".format(identifier=identifier, language=locale)
register_blueprint(vascak_blueprint, url='vascak')
sys.stdout.flush()
def main():
index = requests.get('http://www.vascak.cz/physicsanimations.php?l=en').text
soup = BeautifulSoup(index, 'lxml')
identifiers = set()
for anchor_link in soup.find_all('a'):
if anchor_link.get('href', '').startswith('data/android/physicsatschool/templateimg'):
href = anchor_link['href']
query = urlparse.urlparse(href).query
params = dict(urlparse.parse_qsl(query))
identifier = params.get('s')
if identifier:
print(anchor_link.find_all('img'))
identifiers.add(identifier)
for identifier in identifiers:
print identifier,
swf_file = [ line for line in requests.get('https://www.vascak.cz/data/android/physicsatschool/template.php?s={}&l=es&zoom=0'.format(identifier)).text.splitlines() if '<param name=movie' in line ][0].split('"')[1]
if swf_file != '{}.swf?language=es'.format(identifier):
print "*" * 20
print swf_file
print "*" * 20
else:
print "ok"
return
with CacheDisabler():
rlms = RLMS("{}")
t0 = time.time()
laboratories = rlms.get_laboratories()
tf = time.time()
print len(laboratories), (tf - t0), "seconds"
print
print laboratories[:10]
print
# print rlms.reserve('http://phet.colorado.edu/en/simulation/beers-law-lab', 'tester', 'foo', '', '', '', '', locale = 'es_ALL')
try:
rlms.reserve('identifier-not-found', 'tester', 'foo', '', '', '', '', locale = 'xx_ALL')
except LabNotFoundError:
print "Captured error successfully"
print rlms.get_base_urls()
# print rlms.get_lab_by_url("https://phet.colorado.edu/en/simulation/acid-base-solutions")
return
for lab in laboratories[:5]:
t0 = time.time()
print rlms.reserve(lab.laboratory_id, 'tester', 'foo', '', '', '', '', locale = lang)
tf = time.time()
print tf - t0, "seconds"
if __name__ == '__main__':
main()