-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmuesli.py
333 lines (253 loc) · 12.4 KB
/
muesli.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
from bs4 import BeautifulSoup
import re
import requests
import sys
from account_exceptions import LoginException
from account_exceptions import LogoutException
from account_exceptions import TutNotFoundException
from util import getMaximumColumnSizes
from student import cmpNameParts
from student import compareNames
def createCreditDictionary(creditFile):
result = {}
with open(creditFile, 'r') as cFile:
for line in cFile:
cols = [x.strip() for x in line.split('|')[1:-1]]
result[cols[0]] = cols[1:]
return result
class MuesliApi(object):
def __init__ (self, acc = ('user', 'passw')):
self.__acc = acc
self.baseURL = 'https://muesli.mathi.uni-heidelberg.de'
self.session = None
self.curURL = None
def login (self):
print('MÜSLI - login()')
self.session = requests.Session()
website = self.baseURL + "/user/login"
r = self.session.post(website, data = dict(email = self.__acc[0], password = self.__acc[1]))
if r.url == website or r.status_code != requests.codes.ok:
raise LoginException('Login failed! - Check ur internet connection, username and password')
self.curURL = str(r.url)
def __enter__ (self):
self.login()
return self
def logout (self):
print('MÜSLI - logout')
website = self.baseURL + '/user/logout'
resultWeb = "https://muesli.mathi.uni-heidelberg.de/"
r = self.session.post(website)
self.session.close()
self.session = None
self.curURL = None
if r.url != resultWeb or r.status_code != requests.codes.ok:
raise LogoutException('Logout Failed - Session was closed!')
def __exit__ (self, type, value, traceback):
self.logout()
def moveToStart (self):
self.curURL = self.baseURL + '/start'
def moveToTutorium (self, day, time):
self.curURL = self.getTutorialInfoForDay(day, time)['Link']
def moveToExcercise (self, day, time, sheetNr, link = None):
if link == None:
self.moveToTutorium(day, time)
else:
self.curURL = link
soup = BeautifulSoup(self.session.get(self.curURL).text, 'html.parser')
anchors = soup.findAll("a", href = re.compile("/exam/enter_points/.*"),
text=re.compile("(.*ü|Ü)bung " + str(sheetNr)))
self.curURL = self.baseURL + anchors[0].get("href")
def moveToPresented (self, day, time):
self.moveToTutorium(day, time)
soup = BeautifulSoup(self.session.get(self.curURL).text, 'html.parser')
anchors = soup.findAll("a", href=re.compile("/exam/enter_points/.*"), text='Vorrechnen')
self.curURL = self.baseURL + anchors[0].get("href")
def getCurrentTutorialLinks (self):
self.moveToStart()
r = self.session.post(self.curURL)
soup = BeautifulSoup(r.text, 'html.parser')
anchors = soup.findAll("a", href=re.compile("/tutorial/view/\d*"), title=False)
result = []
for i in range(0, len(anchors)):
result.append(self.baseURL + anchors[i].get("href"))
return result
#==========================================================================
# Advanced stuff for cross-over shit
#==========================================================================
def moveToTutorialMainPage (self, name):
self.moveToStart()
r = self.session.post(self.curURL)
soup = BeautifulSoup(r.text, 'html.parser')
anchors = []
for anchor in soup.findAll("a", href=re.compile("/lecture/view/\d*")):
if anchor.text.strip() == name:
anchors.append(anchor)
self.curURL = self.baseURL + anchors[0].get("href")
def findExternalTutorialData (self, subjectName, myName):
self.moveToTutorialMainPage(subjectName)
print(self.curURL)
r = self.session.post(self.curURL)
soup = BeautifulSoup(r.text, 'html.parser')
table = soup.find('table')
res = []
days = {"Mo" : "Montag",
"Di" : "Dienstag",
"Mi" : "Mittwoch",
"Do" : "Donnerstag",
"Fr" : "Freitag",
"Sa" : "Samstag",
"So" : "Sonntag"
}
keys = ['Day', 'Time', 'Place', 'Tutor', 'Link']
for row in table.findAll('tr'):
tds = row.findAll('td')
if len(tds) == 0:
continue
entries = tds[0].text.strip().split(' ')\
+ [tds[1].text.strip(),
tds[3].text.strip(),
self.baseURL + tds[5].find('a', href = True)['href']]
entries[0] = days[entries[0]]
if not compareNames(entries[3], myName):
tutInfo = {}
for i in range(len(entries)):
tutInfo[keys[i]] = entries[i]
res.append(tutInfo)
print(res)
return res
def moveToExternalTutorium (self, infos = [], tutor = '', day = '', time = '', tid = None):
for info in infos:
if tid != None and info['TID'] == tid:
self.curURL = info['Link']
break
elif compareNames(info['ExtTut'], tutor) \
and info['Day'] == day \
and info['Time'] == time:
self.curURL = info['Link']
break
def moveToExternalExcercise (self, subjectName, tutor, day, time, sheetNr):
self.moveToExternalTutorium(subjectName, tutor, day, time)
soup = BeautifulSoup(self.session.get(self.curURL).text, 'html.parser')
anchors = soup.findAll("a", href = re.compile("/exam/enter_points/.*"),
text=re.compile("(.*ü|Ü)bung " + str(sheetNr)))
self.curURL = self.baseURL + anchors[0].get("href")
#==========================================================================
def extractTutorialInfo (self, tutoralLink):
r = self.session.post(tutoralLink)
soup = BeautifulSoup(r.text, 'html.parser')
headers = soup.findAll("h2")
pattern = re.compile("Übungsgruppe .*")
result = {}
days = {"Mo" : "Montag",
"Di" : "Dienstag",
"Mi" : "Mittwoch",
"Do" : "Donnerstag",
"Fr" : "Freitag",
"Sa" : "Samstag",
"So" : "Sonntag"}
for header in headers:
if pattern.match(header.text):
words = header.text.split(' ')
for i in range(0, len(words)):
if "Vorlesung" == words[i]:
result["Subject"] = (words[i + 1] + ' ' + words[i + 2] + ' ' + words[i + 3]).replace('\n', '')
elif "am" == words[i]:
result["Day"] = days[words[i + 1]]
result["Time"] = words[i + 2]
elif re.compile("\(.*,").match(words[i]):
result["Place"] = (words[i] + ' ' + words[i + 1] + ' ' + words[i + 2]).replace('\n','')[1:-1]
result["Link"] = tutoralLink
return result
def extractAllTutorialsInfo (self, tutLinks):
result = []
for link in tutLinks:
result.append(self.extractTutorialInfo(link))
return result
def getCurrentTutorials(self):
return self.extractAllTutorialsInfo(self.getCurrentTutorialLinks())
def getTutorialInfoForDay (self, day, time):
for info in self.extractAllTutorialsInfo(x['Link'] for x in self.getCurrentTutorials()):
if info["Day"] == day and info["Time"] == time:
return info
raise TutNotFoundException('The Tutorium %s %s was not found!' % (day, time))
def getStudentsMetaData (self, tutorialside):
r = self.session.post(tutorialside)
soup = BeautifulSoup(r.text, 'html.parser')
tables = soup.findAll("table", attrs={"class":"colored"})
students = []
if len(tables) != 1:
print("On", tutorialside, "there where", len(tables), "colored tables (1 expected)!")
for row in tables[0].findAll('tr'):
cols = row.find_all('td')
if len(cols) > 0:
#(name, mail, subject)
students.append({'Name':cols[0].text, 'Mail':cols[0].find('a')['href'][len('mailto:'):], 'Subject':cols[1].text})
return sorted(students, key=lambda x: x['Name'])
def generateMetadataTable (self, info, stream = sys.stdout):
students = self.getStudentsMetaData(info["Link"])
maxs = getMaximumColumnSizes(students)
divider = '+' + '-' * (maxs[0] + 2) + '+' + '-' * (maxs[1] + 2) + '+' + '-' * (maxs[2] + 2) + '+\n'
headerDiv = '+' + '=' * (maxs[0] + 2) + '+' + '=' * (maxs[1] + 2) + '+' + '=' * (maxs[2] + 2) + '+\n'
stream.write(headerDiv)
stream.write('| ' + "NAME".rjust(maxs[0]) + ' | ' + "MAIL".rjust(maxs[1]) + ' | ' + "FACH".rjust(maxs[2]) + ' |\n')
stream.write(headerDiv)
for student in students:
stream.write('| ' + student['Name'].rjust(maxs[0]) + ' | ' + student['Mail'].rjust(maxs[1]) + ' | ' + student['Subject'].rjust(maxs[2]) + ' |\n')
stream.write(divider)
def uploadCredits (self, info, creditFile, sheetNr):
müsliStudents = self.getStudentsMetaData(info['Link'])
self.moveToExcercise(info['Day'], info['Time'], sheetNr, link = info['Link'])
payload = {"submit":"1"}
cData = createCreditDictionary(creditFile)
idData = {}
notMatched = []
soup = BeautifulSoup(self.session.get(self.curURL).text, 'html.parser')
tables = soup.findChildren('table')
rows = tables[0].findChildren(['th', 'tr'])
for row in rows:
if re.compile('<tr id=\"row-\d\d\d\d\">.*').match(str(row)):
idData[row.findAll('td')[0].text] = [x['name'] for x in row.findAll('input', {"name":True})]
#print(cData)
#print(idData)
result = {}
for cStudentName, creds in cData.items():
nameTuple = None
for iStudentName, ids in idData.items():
#if 'Maria' in iStudentName and 'Kag' in iStudentName:
#print(cStudentName)
if compareNames(cStudentName, iStudentName):
nameTuple = (iStudentName, cStudentName)
print('Matched %s from file with %s from MÜSLI' % (cStudentName, iStudentName))
break
if nameTuple != None:
ids = idData[nameTuple[0]]
for i, cred in enumerate(cData[nameTuple[1]]):
payload[ids[i]] = cred
#payload[nameTuple[0]] = cData[nameTuple[1]]
result[nameTuple[0]] = cData[nameTuple[1]]
del idData[nameTuple[0]]
#for k,v in payload.items():
# print(k, v)
#print('\n[ WARNING ] Uploading not implemented!\n')
r = self.session.post(self.curURL, data=payload)
return (result, idData)
def setPresentedState (self, student, day = '', time = '', date = None, presented = True):
if date != None:
day = date[0]
time = date[1]
self.moveToPresented(day, time)
payload = {"submit":"1"}
rowId = ''
soup = BeautifulSoup(self.session.get(self.curURL).text, 'html.parser')
tables = soup.findChildren('table')
rows = tables[0].findChildren(['th', 'tr'])
for row in rows:
if re.compile('<tr id=\"row-\d\d\d\d\">.*').match(str(row)):
if student['Name'] == str(row).split('\n')[1][4:-5]:
rowId = [x['name'] for x in row.findAll('input', {'class':'points', 'name':True})][0]
break
if rowId == '':
raise ValueError('No Entry found for %s (@%s, %s)' % (student['Name'], day, time))
else:
payload[rowId] = '1' if presented else ''
self.session.post(self.curURL, data=payload)