"
def sample2(a=""):
return "I'm a placeholder"
# Filter a stream of loglines for those that match a course's url / id
def has_course(stream,courseid):
regex = '/courses/%i/' % int(courseid)
while True:
L = stream.readline()
if re.search(regex, L): yield L
def js(s):
return json.dumps(s, indent=2)
def sem_from_array_crn(crn):
if not crn[2]: return ""
if crn[2] == "": return ""
return crn[2][:6]
#################################################################################################################
#################################################################################################################
######
###### db ilearn course / user / hits
######
def user_courses(uid):
return js(user_enrolled_in(uid))
def user_course_history_summary(usr_id):
q = """SELECT r.timeblock, r.viewcount, c.sis, c.code, c.canvasid FROM requests_sum1 AS r
JOIN users AS u ON r.userid=u.id
JOIN courses AS c ON c.id=r.courseid
WHERE u.canvasid=%s
GROUP BY r.courseid ORDER BY r.viewcount DESC;""" % str(usr_id)
(conn,cur) = db()
cur.execute(q)
r = cur.fetchall()
return js(r)
groups = funcy.group_by(sem_from_array_crn, r)
g = {}
for K in groups.keys(): g[K] = [ x[3] for x in groups[K] ]
return js( g )
def roster(crn):
q = """SELECT u.name, u.sortablename, u.canvasid as user_id, c.canvasid as course_id, e.workflow, e."type" FROM enrollment AS e
JOIN users AS u ON e.user_id=u.id
JOIN courses AS c ON c.id=e.course_id
WHERE c.canvasid="%s" ;""" % str(crn)
(conn,cur) = db()
cur.execute(q)
return js(cur.fetchall())
def user_course_hits(usr,courseid):
return list(has_course( codecs.open('cache/users/logs/%s.csv' % usr, 'r', 'utf-8'), courseid))
#return "\n".join( [x for x in next(gen)] )
def profiles(id=1,b=2,c=3):
import os
pics = os.listdir('cache/picsCanvas')
return ''.join([ "" % s for s in pics ])
# Departments, classes in each, and students (with hits) in each of those.
def enrollment(a):
return js(depts_with_classcounts())
# All the classes in this dept, w/ all the students in each, with count of their views.
def dept(d=''):
if not d: return js(dept_with_studentviews())
return js(dept_with_studentviews(d))
def user(canvas_id=None):
info = json.loads( codecs.open( 'cache/users/%s.txt' % canvas_id, 'r', 'utf-8').read() )
return render_template('hello.html', id=canvas_id, name=info['name'])
#################################################################################################################
#################################################################################################################
######
###### podcast feed
######
def lectures():
fi = os.listdir(LECPATH)
doc, tag, text = Doc().tagtext()
doc.asis('')
doc.asis('')
with tag('channel'):
with tag('title'): text("Peter's Lecture Series")
with tag('description'): text("Since 2019")
with tag('link'): text(host)
for f in fi:
if f.endswith('.mp3'):
#print(f)
with tag('item'):
name = f.split('.')[0]
ff = re.sub('\s','%20',f)
with tag('title'): text(name)
with tag('guid'): text(f)
b = os.path.getsize(LECPATH+f)
doc.stag('enclosure', url=host+'/podcast/media/'+urllib.parse.quote(ff), type='audio/mpeg',length=b)
doc.asis('')
#doc.asis('')
return doc.getvalue()
def web_lectures():
fi = os.listdir(LECPATH)
output = "
Lectures
\n"
for f in fi:
if f.endswith('.mp3'):
name = f.split('.')[0]
ff = urllib.parse.quote(f)
#ff = re.sub('\s','%20',f)
output += '%s \n' % ( host + '/podcast/media/' + ff, name)
return output
#################################################################################################################
#################################################################################################################
######
###### editing personnel app
######
# personnel_fetch, personnel_meta
# todo: update: dept, title, any of the other fields.
# insert: new dept, new title,
# update a value: dept id of a personnel id
def update_pers_title(pid, tid):
q = "UPDATE personnel SET `title`='%s' WHERE `id`='%s'" % (str(tid), str(pid))
(conn,cur) = db()
result = cur.execute(q)
conn.commit()
return js( {'result': 'success'} )
# update a value: dept id of a personnel id
def update_pers_dept(pid, did):
q = "UPDATE personnel SET `dept1`='%s' WHERE `id`='%s'" % (str(did), str(pid))
(conn,cur) = db()
result = cur.execute(q)
conn.commit()
return js( {'result': 'success'} )
def user_edit(canvas_id='2'):
info = json.loads( codecs.open( 'cache/users/%s.txt' % str(canvas_id), 'r', 'utf-8').read() )
return render_template('personnel.html', id=canvas_id, name=info['name'])
def staff_dir(search=''):
return render_template('dir.html')
######
###### handling images
######
def find_goo(n):
g = re.search('00(\d\d\d\d\d\d)', n)
if g:
return g.groups()[0]
return ''
def byname(x):
if 'conf_name' in x:
return x['conf_name']
if 'first_name' in x and 'last_name' in x:
return x['first_name'] + " " + x['last_name']
return ''
def fn_to_struct( n, staff ):
g = find_goo(n)
if g:
#print(g)
for s in staff:
cg = s['conf_goo']
if cg == g:
#print("%s - %s - %s" % (n, g, cg) )
return s
return { "conf_goo":g, "conf_name":"unknown - " + n }
return 0
def image_edit(filename=''):
url = "https://hhh.gavilan.edu/phowell/map/dir_api_tester.php?a=list/staffsemester"
staff = json.loads( requests.get(url).text )
badges = 0
web = 1
if web:
files = sorted(os.listdir('cache/picsStaffdir') )
done_files = [ x[:-4] for x in sorted(os.listdir('cache/picsStaffdir/cropped') ) ]
if badges:
files = sorted(os.listdir('cache/picsId/originals_20211022') )
done_files = [ x[:6] for x in sorted(os.listdir('cache/picsId/2021crop') ) ]
files_match = []
files_no_match = []
raw_filenames = files
for f in files:
sa = fn_to_struct(f,staff)
if sa:
ss = sa.copy()
else:
ss = sa
if ss:
ss['filename'] = f
files_match.append(ss)
else: files_no_match.append(f)
fm = json.dumps( sorted(files_match,key=byname) )
fnm = json.dumps(files_no_match)
sm = json.dumps(staff)
return render_template('images.html', staff=sm, matches=fm, nomatches=fnm, checked=done_files)
def image_crop(filename,x,y,w,h,newname=''):
from PIL import Image
import piexif
badges = 0
web = 1
if not newname: newname = filename
if web:
im = Image.open('cache/picsStaffdir/%s' % filename)
savepath = 'cache/picsStaffdir/cropped/%s.jpg' % newname
if badges:
im = Image.open('cache/picsId/originals_20211022/%s' % filename)
savepath = 'cache/picsId/2021crop/%s.jpg' % newname
out = { 'im': str(im) }
x = int(x)
y = int(y)
w = int(w)
h = int(h)
if "exif" in im.info:
exif_dict = piexif.load(im.info['exif'])
#out['exif'] = exif_dict
#print(exif_dict)
if piexif.ImageIFD.Orientation in exif_dict['0th']:
#exif_dict['0th'][piexif.ImageIFD.Orientation] = 3
print(piexif.ImageIFD.Orientation)
print(exif_dict['0th'])
out['rotation'] = 'messed up'
if exif_dict['0th'][piexif.ImageIFD.Orientation] == 6:
im = im.rotate(270, expand=True)
#im.save('cache/picsId/originals_20211022/crotated_%s' % filename, quality=95)
im_crop = im.crop((x,y,x+w,y+h))
img_resize = im_crop.resize((250, 333))
img_resize.save(savepath, quality=95)
return json.dumps( out )
#if filename=='list':
# #return ' \n'.join([ "%s" % ( x,x ) for x in
# return ' \n'.join([ "%s" % ( x,x ) for x in sorted(os.listdir('cache/picsId/originals_20211022')) ])
#################################################################################################################
#################################################################################################################
######
###### server infrastructure
######
def server_save(key,value):
codecs.open(datafile2,'a').write( "%s=%s\n" % (str(key),str(value)))
def server_dispatch_json(function_name,arg='', arg2=''):
print("Looking for function: %s. arg:%s. arg2:%s." % (function_name, arg, arg2))
try:
result = "" + globals()[function_name](arg, arg2)
print("doing 2 args")
return result
except Exception as e:
print("Error with that: %s" % str(e))
try:
result = "" + globals()[function_name](arg) #
print("doing 1 arg")
return result
except Exception as f:
print("Error with that: %s" % str(f))
try:
result = globals()[function_name]()
print("doing 0 arg")
return result
except Exception as gg:
print("Error with that: %s" % str(gg))
return json.dumps({'result':'failed: exception', 'e1':str(e), 'e2':str(f), 'e3':str(gg)}, indent=2)
def server_dispatch(function_name,arg='', arg2=''):
print("Looking for function: %s. arg:%s. arg2:%s." % (function_name, arg, arg2))
try:
result = "" + globals()[function_name](arg, arg2)
print("doing 2 args")
return result
except Exception as e:
print("Error with that: %s" % str(e))
try:
result = "" + globals()[function_name](arg) #
print("doing 1 arg")
return result
except Exception as f:
print("Error with that: %s" % str(f))
try:
result = globals()[function_name]()
print("doing 0 arg")
return result
except Exception as gg:
print("Error with that: %s" % str(gg))
return json.dumps({'result':'failed: exception', 'e1':str(e), 'e2':str(f), 'e3':str(gg)}, indent=2)