commit d7e910a379ecf1c2fd4ffc7657b8d16425e6482b
Author: rob <rob@tarina.org>
Date: Sun, 4 Oct 2020 11:28:33 +0300
first
Diffstat:
A | server.py | | | 871 | +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
1 file changed, 871 insertions(+), 0 deletions(-)
diff --git a/server.py b/server.py
@@ -0,0 +1,871 @@
+# -*- coding: utf-8 -*-
+import web
+import json
+import time
+import datetime
+import re
+import base64
+import os
+import subprocess
+import urllib
+from PIL import Image
+import hashlib
+import random
+import bcrypt
+import sys
+basedir = os.path.dirname(os.path.realpath(__file__))
+sys.path.append(basedir)
+import hemligt
+#import cPickle as pickle
+
+urls = (
+ "/", "index",
+ "/login?", "login",
+ "/logout", "logout",
+ "/addevent", "addevent",
+ "/event", "event",
+ "/removeevent/(\d+)", "removeevent",
+ "/editevent/(\d+)", "editevent",
+ "/removepost/(\d+)", "removepost",
+ "/old", "old",
+ "/bilder?", "bilder",
+ "/upload", "upload",
+ "/bild/(.*)?", "bild",
+ "/bildinfo/(.*)?", "bildinfo",
+ "/remove/(.*)?","remove",
+ "/tuning?", "tuning",
+ "/senaste", "senaste",
+ "/admin", "admin",
+ "/register?", "register",
+ "/forgotpass?", "forgotpass",
+ "/ny", "ny",
+ "/protokoll", "protokoll",
+ "/nope", "nope"
+)
+
+allowed = hemligt.allowed
+historikaccess = hemligt.historikaccess
+
+render = web.template.render(basedir + "/public_html/html/", base="base")
+render2 = web.template.render(basedir + "/public_html/html/", base="base2")
+render3 = web.template.render(basedir + "/public_html/html/", base="base3")
+web.config.debug = False
+app = web.application(urls, globals())
+store = web.session.DiskStore(basedir + '/sessions')
+db = web.database(dbn="sqlite", db=basedir + "/db/bygdis.db")
+session = web.session.Session(app,store,initializer={'login': 0, 'user': '', 'backurl': '', 'bildsida': 0, 'search': ''})
+
+def logged():
+ if session.login == 5:
+ return True
+ else:
+ return False
+
+def curdate():
+ today = datetime.datetime.now().date().strftime('%s')
+ return today
+
+def getkalender():
+ events = db.query("SELECT * FROM kalender WHERE datumtid > DATETIME('now') ORDER BY datumtid ASC")
+ #events = db.select('kalender', what='id, datumtid, event', order='datumtid ASC')
+ return events
+
+def getkalenderall():
+ events = db.query("SELECT * FROM kalender ORDER BY datumtid ASC")
+ #events = db.select('kalender', what='id, datumtid, event', order='datumtid ASC')
+ return events
+
+def nyevent(datumtid, event):
+ veckodagar = u'Måndag', u'Tisdag', u'Onsdag', u'Torsdag', u'Fredag', u'Lördag', u'Söndag'
+ veckodag = datumtid.weekday()
+ db.insert('kalender', datumtid=datumtid, veckodag=veckodagar[veckodag], event=event)
+ print("event added to database")
+ return
+
+def getposts():
+ posts = db.query("SELECT * FROM posts ORDER BY datumtid DESC")
+ #events = db.select('kalender', what='id, datumtid, event', order='datumtid ASC')
+ return posts
+
+def nypost(datumtid, post):
+ db.insert('posts', datumtid=datumtid, post=post, likes=0)
+ print("post added to database")
+ return
+
+def getprotokoll(year):
+ listmodtime = []
+ for a in os.scandir(basedir + '/protokoll/' + year):
+ filename = a.name
+ modtime = a.stat().st_mtime
+ listmodtime.append((filename, modtime))
+ listmodtime.sort(key=lambda tup: tup[1])
+ protokoll = []
+ for a in listmodtime:
+ protokoll.append(a[0])
+ return protokoll
+
+def adduser(name, password, mail):
+ password = password.encode("utf-8")
+ salt = bcrypt.gensalt()
+ password_hashed = bcrypt.hashpw(password, salt)
+ db.insert('bildadmin', name=name, displayname=name, password=password_hashed, mail=mail, subscribe='aldrig')
+ print("new user added")
+ return
+
+def bildhistoriker():
+ bildhistoriker = db.query("SELECT name, displayname, mail, password FROM bildadmin")
+ return bildhistoriker
+
+def getdisplayname(user):
+ displayname = db.query("SELECT displayname FROM bildadmin WHERE name='"+user+"';")[0]
+ return displayname.displayname
+
+def getbilder():
+ bilder = db.query("SELECT * FROM bilder ORDER BY uploaddate DESC")
+ return bilder
+
+def addbild(filename, titel, namn, year, fotograf, beskrivning, uppladdare, personer):
+ db.insert('bilder', filename=filename, titel=titel, uploaddate=datetime.datetime.now(), namn=namn, year=year, fotograf=fotograf, beskrivning=beskrivning, uppladdare=uppladdare, personer=personer)
+
+def sendmail(email, subject, msg):
+ #Send mail
+ echomsg = subprocess.Popen(('echo', msg), stdout=subprocess.PIPE)
+ sendmsg = subprocess.check_output(('mail', '-r', 'rob@bygdis.fi', '-s', subject, email), stdin=echomsg.stdout)
+ echomsg.wait()
+ #subprocess.call(['echo', msg, '|', 'mail', '-r', 'rob@tarina.org','-s', subject, email])
+
+def stopflood(ip,referer):
+ try:
+ t = db.select('stopflood', where='ip="'+ip+'"', what='tid')[0]
+ except:
+ pass
+ try:
+ db.update('stopflood', where='ip="'+ip+'"', tid=time.time())
+ except:
+ db.insert('stopflood', ip=ip, tid=time.time())
+ try:
+ senast = time.time() - t.tid
+ print(senast)
+ if senast < 2:
+ return web.seeother(referer)
+ else:
+ return
+ except:
+ return
+
+def stopresetpass(mail):
+ try:
+ t = db.select('stopresetpass', where='mail="'+mail+'"', what='tid')[0]
+ print(t)
+ except Exception as e:
+ print(e)
+ try:
+ db.update('stopresetpass', where='mail="'+mail+'"', tid=time.time())
+ except Exception as e:
+ print(e)
+ db.insert('stopresetpass', mail=mail, tid=time.time())
+ try:
+ senast = time.time() - t.tid
+ print(senast)
+ if senast < 604800:
+ print('mail is in password reset spam filter')
+ return True
+ else:
+ return False
+ except Exception as e:
+ print(e)
+ return True
+
+class admin():
+ form = web.form.Form(
+ web.form.Textarea('post', web.form.notnull, description="", width="500px", height="200px", autocomplete="off"),
+ web.form.Button('skicka'))
+ def GET(self):
+ print(session.login)
+ if session.login == 5:
+ saysomething = self.form()
+ anslagstavla = getposts()
+ return render2.admin(anslagstavla, saysomething)
+ else:
+ raise web.seeother('/login')
+ def POST(self):
+ if session.login == 5:
+ saysomething = self.form()
+ if not saysomething.validates():
+ return render2.admin(anslagstavla, saysomething)
+ else:
+ i = web.input()
+ print('ADDDDDDDDDDDDDING TO database post ' + i.post)
+ now = datetime.datetime.now()
+ print('ADDDDDDDDDDDDDING TO database date' + str(now))
+ nypost(now, i.post)
+ raise web.seeother('/admin')
+ else:
+ raise web.seeother('/login')
+
+class event():
+ def GET(self):
+ if session.login == 5:
+ upcomingevents = getkalender()
+ return render2.event(upcomingevents)
+ else:
+ raise web.seeother('/login')
+
+class addevent():
+ form = web.form.Form(
+ web.form.Textbox('year', web.form.notnull, web.form.regexp('\d+', 'yyyy'), description="år:"),
+ web.form.Textbox('month', web.form.notnull, web.form.regexp('\d+', 'MM'), description="månad:"),
+ web.form.Textbox('day', web.form.notnull, web.form.regexp('\d+', 'dd'), description="dag:", autofocus="autofocus"),
+ web.form.Textbox('tid', web.form.notnull, web.form.regexp('^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$', 'Skriv tiden såhär 07:20'), description="klockslag:"),
+ web.form.Dropdown('upprepa', [u'Nej', u'Varje vecka', u'Varannan vecka', u'Varje månad'], web.form.notnull, description="återkommande"),
+ web.form.Textbox('antal', web.form.regexp('\d+', 'nummer tack'), description="hur många gånger:"),
+ web.form.Textarea('event', description="beskrivning:"),
+ web.form.Textarea('admin', description="synligt för admin:"),
+ web.form.Button('skicka'))
+ def GET(self):
+ if session.login == 5:
+ now = datetime.datetime.now()
+ kalender = self.form()
+ kalender.fill(year=now.year, month=now.month, day=now.day, tid=str(now.hour).zfill(2) + ':00', antal='1')
+ return render.addevent(kalender)
+ else:
+ raise web.seeother('/login')
+ def POST(self):
+ if session.login == 5:
+ kalender = self.form()
+ if not kalender.validates():
+ return render.addevent(kalender)
+ else:
+ i = web.input()
+ try:
+ tidh = int(i.tid[:2])
+ tidm = int(i.tid[-2:])
+ year = int(i.year)
+ month = int(i.month)
+ day = int(i.day)
+ antal = int(i.antal)
+ datum = datetime.datetime(year, month, day, tidh, tidm)
+ except ValueError:
+ return render.nope()
+ manydatum = []
+ dayz = 0
+ c = 0
+ if 'Varje v' in i.upprepa:
+ dayz = 7
+ if 'Varannan' in i.upprepa:
+ dayz = 14
+ if 'Varje m' in i.upprepa:
+ dayz = 28
+ if 'Nej' in i.upprepa:
+ antal = 1
+ for a in range(0, antal):
+ manydatum.append(datum + datetime.timedelta(days=c))
+ c = c + dayz
+ for d in manydatum:
+ nyevent(d, i.event)
+ return web.seeother('/admin')
+ else:
+ raise web.seeother('/login')
+
+class removeevent():
+ def POST(self, id):
+ if session.login == 5:
+ db.delete('kalender', where="id=" + id)
+ raise web.seeother('/event')
+ else:
+ raise web.seeother('/login')
+
+class editevent():
+ def POST(self):
+ s = web.input().signal
+ print(s)
+ if session.login == 5:
+ return
+ else:
+ return
+
+class removepost():
+ def POST(self, id):
+ if session.login == 5:
+ db.delete('posts', where="id=" + id)
+ raise web.seeother('/admin')
+ else:
+ raise web.seeother('/login')
+
+class login():
+ form = web.form.Form(
+ web.form.Textbox('user', web.form.notnull, description="namn eller e-post:"),
+ web.form.Password('password', web.form.notnull, description="lösenord:"),
+ web.form.Button('Logga in'))
+ def GET(self):
+ fejl = ''
+ resetpasslink = False
+ i = web.input(error=None)
+ if i.error == 'fejl':
+ fejl = 'fejl lösenord!'
+ resetpasslink = True
+ if i.error == 'tom':
+ fejl = 'hmm.. he funkka inga!'
+ if session.login < 3:
+ loginform = self.form()
+ return render.login(loginform, fejl, resetpasslink)
+ if session.login == 3:
+ return web.seeother('/bilder')
+ if session.login == 5:
+ raise web.seeother('/admin')
+ def POST(self):
+ referer = web.ctx.env.get('HTTP_REFERER','https://bygdis.fi')
+ ip = web.ctx['ip']
+ stopflood(ip, referer)
+ loginform = self.form()
+ i = web.input()
+ if i.user == '' or i.password == '':
+ raise web.seeother('/login?error=tom')
+ bildadmin = []
+ bildadmins = bildhistoriker()
+ for p in bildadmins:
+ if p.name.lower() == i.user.lower() or p.mail.lower() == i.user.lower():
+ if bcrypt.checkpw(i.password.encode('utf-8'), p.password):
+ if i.user.lower() == 'byyssare':
+ session.login = 2
+ else:
+ session.login = 3
+ session.user = p.name.lower()
+ print('BACKURL: '+session.backurl)
+ if session.backurl != '':
+ backurl = session.backurl
+ session.backurl = ''
+ raise web.seeother(backurl)
+ else:
+ raise web.seeother('/bilder')
+ if (i.user.lower(),i.password) in allowed:
+ session.login = 5
+ session.user = i.user.lower()
+ raise web.seeother('/admin')
+ elif (i.user.lower(),i.password) == historikaccess:
+ session.login = 2
+ session.user = i.user.lower()
+ raise web.seeother('/bilder')
+ else:
+ return web.seeother('/login?error=fejl')
+
+class forgotpass():
+ form = web.form.Form(
+ web.form.Textbox('mail', web.form.notnull, description="e-post:"),
+ web.form.Button('Skicka nytt lösenord!'))
+ def GET(self):
+ fejl = ''
+ i = web.input(error=None)
+ if i.error == 'fejl':
+ fejl = 'hittar inga e-post!'
+ elif i.error == 'done':
+ fejl = 'ditt lösenord e uppdaterat å skickat till din e-post'
+ elif i.error == 'nej':
+ fejl = 'nej hörru dedär gaar inga!'
+ elif i.error == 'stopresetpass':
+ fejl = 'Nytt lösenord ha redan skickats åt dej!! int ha du väl nu igen tappat bort ditt lösen? hmm.. om de e problematiskt ta kontakt med rob@bygdis.fi'
+ if session.login < 3:
+ loginform = self.form()
+ return render.forgotpass(loginform, fejl)
+ if session.login == 3:
+ return web.seeother('/bilder')
+ if session.login == 5:
+ raise web.seeother('/admin')
+ def POST(self):
+ referer = web.ctx.env.get('HTTP_REFERER','https://bygdis.fi')
+ ip = web.ctx['ip']
+ stopflood(ip, referer)
+ sendpassform = self.form()
+ if not sendpassform.validates():
+ return render.login(sendpassform, '')
+ else:
+ i = web.input()
+ bildadmin = []
+ bildadmins = bildhistoriker()
+ if i.mail.lower() == 'byyssare':
+ raise web.seeother('/forgotpass?error=nej')
+ for p in bildadmins:
+ if p.mail.lower() == i.mail.lower():
+ passfilter = stopresetpass(i.mail.lower())
+ if passfilter == True:
+ raise web.seeother('/forgotpass?error=stopresetpass')
+ unencrypted_password = ('%06x' % random.randrange(16**6))
+ password = unencrypted_password.encode("utf-8")
+ salt = bcrypt.gensalt()
+ password_hashed = bcrypt.hashpw(password, salt)
+ db.update('bildadmin', where='name="'+p.name+'"', password=password_hashed)
+ print("lösenordet uppdaterat!")
+ msg = "Ditt nya lösenord till byyns fotoalbum e: " + unencrypted_password + ' , om du vill ändra lösenordet ti någå du kommer ihåg så tryck på namne ditt högst op på ruutån efter du loggat in.'
+ sendmail(p.mail, 'Nytt lösenord till byyns fotoalbum', msg)
+ raise web.seeother('/forgotpass?error=done')
+ raise web.seeother('/forgotpass?error=fejl')
+
+class register():
+ form = web.form.Form(
+ web.form.Textbox('user', description="användarnamn:"),
+ web.form.Password('password', description="lösenord:"),
+ web.form.Textbox('mail', description="e-post:"),
+ web.form.Button('Skapa konto'))
+ def GET(self):
+ registerform = self.form()
+ w = web.input()
+ formfail = ''
+ n = ''
+ m = ''
+ try:
+ if w.fail == 'namn':
+ formfail = 'du måst hiitt opa eitt namn åt te!'
+ if w.namn:
+ n = w.namn
+ if w.epost:
+ m = w.epost
+ elif w.epost == '':
+ formfail = 'tu måst lägg din epost address tär i ruuton, he e nu bara så...'
+ if w.fail == 'notmail':
+ formfail = 'jusså, tetär e no inga nån mejl adress.'
+ elif w.fail == 'nametaken':
+ formfail = 'Nån anan ha tagi de namme, hitt opa någå ana!'
+ elif w.fail == 'mailtaken':
+ formfail = 'tu ha redan laga ett användarnamn me tetta epost konto!'
+ elif w.fail == 'kortlosen':
+ formfail = 'he va no för uuslit lösenord, minst 5 bokstäver'
+ except:
+ pass
+ registerform.fill(user=urllib.parse.unquote_plus(n), mail=urllib.parse.unquote_plus(m))
+ if session.login > 1:
+ return render.register(registerform, formfail)
+ else:
+ raise web.seeother('/')
+ def POST(self):
+ if session.login > 1:
+ registerform = self.form()
+ i = web.input()
+ r = '&namn=' + i.user + '&epost=' + i.mail
+ urllib.parse.quote_plus(r)
+ if i.user == '':
+ raise web.seeother('/register?fail=namn'+r)
+ if '@' not in i.mail:
+ raise web.seeother('/register?fail=notmail'+r)
+ if len(i.password) < 5:
+ raise web.seeother('/register?fail=kortlosen'+r)
+ bildadmins = db.select('bildadmin', what='name, mail')
+ for p in bildadmins:
+ if p.name.lower() == i.user.lower():
+ raise web.seeother('/register?fail=nametaken' +r)
+ if p.mail.lower() == i.mail.lower():
+ raise web.seeother('/register?fail=mailtaken' +r)
+ adduser(i.user, i.password, i.mail.lower())
+ #Send mail to Madbaker
+ msg = "Wowowowoweeewaaa! Ny användare på bygdis.fi! " + i.user + ' ' + i.mail
+ sendmail('rob@bygdis.fi', 'Wowowoweewaaa!', msg)
+ #Send mail to new user
+ msg = "Gratulis " + i.user + ", du har nu ett konto opa bygdis.fi! Logga in med användarnamn å lösenord på sidan https://bygdis.fi/login"
+ sendmail(i.mail, 'Byyns eji fotoalbum', msg)
+ session.login = 3
+ session.user = i.user
+ return web.seeother('/ny')
+
+class ny():
+ def GET(self):
+ if session.login > 2:
+ backurl = ''
+ if session.backurl != '':
+ backurl = session.backurl
+ session.backurl = ''
+ return render.ny(session.user, backurl)
+
+class tuning():
+ form = web.form.Form(
+ web.form.Textbox('user', description="synligt namn:"),
+ web.form.Password('password', description="lösenord:"),
+ web.form.Password('newpassword', description="nytt lösen (ifall du vill byta):"),
+ web.form.Password('newpassword2', description="nytt lösen igen:"),
+ web.form.Textbox('mail', description="epost:"),
+ web.form.Radio('subscribe', ['dagligen', 'aldrig'], description="Få epost brejv ifall de hänt någå"),
+ web.form.Button('Spara'))
+ def GET(self):
+ if session.login > 2:
+ print('asdfasdfasdf')
+ user = db.select('bildadmin', where='name="'+session.user+'"')[0]
+ tuningform = self.form()
+ w = web.input(namn=None,epost=None,fail=None,upd=None)
+ print('asdfasdfasdfkdakkakka')
+ formfail = ''
+ if w.fail == 'wrongpass':
+ formfail = formfail + 'fel lösenord'
+ if w.fail == 'nopass':
+ formfail = formfail + 'Du måst skriv in ditt lösenord!'
+ if w.namn == '':
+ formfail = formfail + 'du måst hiitt opa eitt namn åt te!'
+ if w.epost == '':
+ formfail = formfail + 'tu måst lägg din epost address tär i ruuton, he e nu bara så...'
+ elif w.fail == 'notmail':
+ formfail = formfail + 'jusså, tetär e no inga nån mejl adress.'
+ if w.fail == 'nametaken':
+ formfail = formfail + 'Nån anan ha tagi de namme, hitt opa någå ana!'
+ if w.fail == 'mailtaken':
+ formfail = formfail + 'He finns eitt konto me te epost adressn!'
+ if w.fail == 'kortlosen':
+ formfail = formfail + 'he va no för uuslit lösenord, minst 5 bokstäver'
+ if w.fail == 'newpass':
+ formfail = formfail + 'nya lösenordet stämmer inte överens med varann, pröva pånytt!'
+ if w.upd == 'yes':
+ formfail = 'Yes, ditt konto e tuunat!'
+ tuningform.fill(user=user.displayname, mail=user.mail, subscribe=user.subscribe)
+ return render.tuning(tuningform, formfail, user.name)
+ else:
+ return web.seeother('/register')
+ def POST(self):
+ if session.login > 1:
+ tuningform = self.form()
+ i = web.input()
+ if i.password == '':
+ raise web.seeother('/tuning?fail=nopass')
+ bildadmins = bildhistoriker()
+ for p in bildadmins:
+ print(p)
+ if p.name == session.user:
+ if bcrypt.checkpw(i.password.encode('utf-8'), p.password):
+ #check if display name taken
+ b_displayname = bildhistoriker()
+ for a in b_displayname:
+ if i.user in a.displayname and a.name != session.user:
+ raise web.seeother('/tuning?fail=nametaken')
+ if i.mail in a.mail and i.mail != p.mail:
+ raise web.seeother('/tuning?fail=mailtaken')
+ if i.newpassword != '':
+ if i.newpassword != i.newpassword2:
+ raise web.seeother('/tuning?fail=newpass')
+ if len(i.newpassword) < 5:
+ raise web.seeother('/tuning?fail=kortlosen')
+ else:
+ #update with password change
+ password = i.newpassword.encode("utf-8")
+ salt = bcrypt.gensalt()
+ password_hashed = bcrypt.hashpw(password, salt)
+ db.update('bildadmin', where='name="'+session.user+'"', displayname=i.user, password=password_hashed, mail=i.mail.lower(), subscribe=i.subscribe)
+ return web.seeother('/tuning?upd=yes')
+ if '@' not in i.mail:
+ raise web.seeother('/tuning?fail=notmail')
+ #update without passwordchange
+ db.update('bildadmin', where='name="'+session.user+'"', displayname=i.user, mail=i.mail.lower(), subscribe=i.subscribe)
+ return web.seeother('/tuning?upd=yes')
+ else:
+ raise web.seeother('/tuning?fail=wrongpass')
+
+class bilder():
+ def GET(self):
+ bildpersida = 100
+ i = web.input()
+ bilder_totalt = db.query("SELECT COUNT(*) AS bilder FROM bilder")[0]
+ tot = int(bilder_totalt.bilder)
+ print('bilder alltsomallt: ' + str(tot))
+ print('session search: ' + session.search)
+ try:
+ if i.search == '':
+ session.search = ''
+ session.bildsida = 0
+ elif i.search != "":
+ session.search = urllib.parse.unquote_plus(i.search)
+ session.bildsida = 0
+ except:
+ pass
+ if session.search != '':
+ search_result = []
+ tot = 0
+ b1, b2, b3, b4, b5, = 0,0,0,0,0
+ try:
+ search_result.append(db.query("SELECT * FROM bilder WHERE personer LIKE '%"+session.search+"%';"))
+ tot = db.query("SELECT Count(*) AS bilder FROM bilder WHERE personer LIKE '%"+session.search+"%';")[0]
+ b1 = tot.bilder
+ except:
+ pass
+ try:
+ search_result.append(db.query("SELECT * FROM bilder WHERE fotograf LIKE '%"+session.search+"%';"))
+ tot = db.query("SELECT Count(*) AS bilder FROM bilder WHERE fotograf LIKE '%"+session.search+"%';")[0]
+ b2 = tot.bilder
+ except:
+ pass
+ try:
+ search_result.append(db.query("SELECT * FROM bilder WHERE plats LIKE '%"+session.search+"%';"))
+ tot = db.query("SELECT Count(*) AS bilder FROM bilder WHERE plats LIKE '%"+session.search+"%';")[0]
+ b3 = tot.bilder
+ except:
+ pass
+ try:
+ search_result.append(db.query("SELECT * FROM bilder WHERE titel LIKE '%"+session.search+"%';"))
+ tot = db.query("SELECT Count(*) AS bilder FROM bilder WHERE titel LIKE '%"+session.search+"%';")[0]
+ b4 = tot.bilder
+ except:
+ pass
+ try:
+ search_result.append(db.query("SELECT * FROM bilder WHERE year LIKE '%"+session.search+"%';"))
+ tot = db.query("SELECT Count(*) AS bilder FROM bilder WHERE year LIKE '%"+session.search+"%';")[0]
+ b5 = tot.bilder
+ except:
+ pass
+ tot = b1 + b2 + b3 + b4 + b5
+ try:
+ print(search_result)
+ print('sökta bilder: ' + str(tot))
+ except:
+ pass
+ try:
+ if i.page == "next":
+ if session.bildsida < tot:
+ session.bildsida += bildpersida
+ if i.page == "back":
+ if session.bildsida > bildpersida:
+ session.bildsida -= bildpersida
+ else:
+ session.bildsida = 0
+ except:
+ pass
+ if session.login > 1:
+ limit = session.bildsida + bildpersida
+ offset = session.bildsida
+ print(session.bildsida)
+ if session.search == '':
+ bilder = db.query("SELECT * FROM bilder ORDER BY uploaddate DESC LIMIT " + str(limit) + " OFFSET " + str(offset))
+ else:
+ bilder = search_result
+ if session.login > 3:
+ try:
+ if i.delete != '':
+ return web.seeother('/remove/' + i.delete)
+ except:
+ pass
+ rights = 'admin'
+ elif session.login > 2:
+ rights = 'mod'
+ elif session.login > 1:
+ rights = 'byyssare'
+ return render.bilder(bilder, rights, session.user, tot, limit, bildpersida, session.search, db, str, print)
+ else:
+ return web.seeother('/login')
+
+class remove():
+ def GET(self, imghash):
+ if session.login > 1:
+ referer = web.ctx.env.get('HTTP_REFERER', 'none')
+ i = web.input(sure=None)
+ if i.sure == 'yes':
+ db.delete('bilder', where='filename="' + imghash + '"')
+ db.delete('allaversioner', where='filename="' + imghash + '"')
+ db.delete('likes', where='bild="' + imghash + '"')
+ db.delete('hates', where='bild="' + imghash + '"')
+ db.delete('bildkommentar', where='filename="' + imghash + '"')
+ return web.seeother('/bilder')
+ return render.remove(imghash, referer)
+
+class upload():
+ def GET(self):
+ if session.login == 2:
+ session.backurl = '/upload'
+ return web.seeother('register')
+ elif session.login > 2:
+ return render.upload()
+ else:
+ return web.seeother('/login')
+ def POST(self):
+ if session.login > 2:
+ i = web.input(imgfile={})
+ for p in i:
+ print(p)
+ if i.imgfile != {}:
+ print(i.imgfile.filename)
+ if i.imgfile.filename == '':
+ print('hmmm... no image to upload')
+ raise web.seeother('/upload?fail=noimg')
+ print('YEAH, Upload image!')
+
+ ##---------- UPLOAD IMAGE ----------
+
+ imgdir = basedir + '/public_html/static/bilder/'
+ imgpath=i.imgfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones.
+ #filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension)
+ imghash = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()
+ imgname = imghash + '.jpeg'
+ #imgname = str(len(os.listdir(imgdir))).zfill(3) + '.jpeg'
+ fout = open(imgdir +'/'+ imgname,'wb') # creates the file where the uploaded file should be stored
+ fout.write(i.imgfile.file.read()) # writes the uploaded file to the newly created file.
+ fout.close() # closes the file, upload complete.
+
+ ##---------- OPEN FILE & CHEKC IF JPEG --------
+ image = Image.open(imgdir +'/'+ imgname)
+ if image.format != 'JPEG':
+ os.remove(imgdir +'/'+ imgname)
+ raise web.seeother('/upload?fail=notjpeg')
+
+ ##---------- RESIZE IMAGE -----------
+ image.thumbnail((900,900), Image.ANTIALIAS)
+ image.save(imgdir + '/web/' + imgname)
+ image.thumbnail((300,300), Image.ANTIALIAS)
+ image.save(imgdir + '/thumb/' + imgname)
+
+ db.insert('bilder', filename=imghash, uploaddate=datetime.datetime.now(), uppladdare=session.user, lastmod=datetime.datetime.now(), moddedby=session.user)
+ raise web.seeother('/bildinfo/' + imghash)
+ else:
+ return render.upload()
+ else:
+ session.backurl = '/upload'
+ return render.register()
+
+class bildinfo():
+ form = web.form.Form(
+ web.form.Textbox('titel', web.form.notnull, description="Bild titel:"),
+ web.form.Textbox('year', web.form.notnull, description="År:"),
+ web.form.Textbox('fotograf', web.form.notnull, description="Fotograf:"),
+ web.form.Textbox('plats', web.form.notnull, description="Plats:"),
+ web.form.Textarea('beskrivning', web.form.notnull, description="Beskrivning:"),
+ web.form.Textarea('personer', web.form.notnull, description="Personer fr.v. (lägg ett komma mellan varje typ):"),
+ web.form.Button('Spara'))
+ def GET(self, imghash):
+ if session.login > 2:
+ infoform = self.form()
+ v = web.input()
+ if v:
+ oldinfo = db.select('allaversioner', where="id='" + v.id +"'", what='titel, year, fotograf, beskrivning, personer, moddedby, lastmod, plats')
+ else:
+ oldinfo = db.select('bilder', where="filename='" + imghash +"'", what='titel, year, fotograf, beskrivning, personer, moddedby, lastmod, plats')
+ oldinfo = oldinfo[0]
+ allaversioner = db.select('allaversioner', where="filename='" + imghash +"'", what='id, moddedby, lastmod', order='id DESC')
+ infoform.fill(titel=oldinfo.titel, year=oldinfo.year, fotograf=oldinfo.fotograf, plats=oldinfo.plats, beskrivning=oldinfo.beskrivning, personer=oldinfo.personer)
+ return render.bildinfo(infoform, imghash, oldinfo.moddedby, oldinfo.lastmod, allaversioner)
+ else:
+ session.backurl = '/bildinfo/' + imghash
+ return web.seeother("/register")
+ def POST(self, imghash):
+ ip = web.ctx['ip']
+ referer = web.ctx.env.get('HTTP_REFERER','https://bygdis.fi')
+ stopflood(ip, referer)
+ if session.login > 2:
+ i = web.input()
+ db.update('bilder', where="filename='" + imghash +"'", titel=i.titel, year=i.year, fotograf=i.fotograf, plats=i.plats, beskrivning=i.beskrivning, personer=i.personer, lastmod=datetime.datetime.now(), moddedby=session.user)
+ db.insert('allaversioner', filename=imghash, titel=i.titel, year=i.year, fotograf=i.fotograf, plats=i.plats, beskrivning=i.beskrivning, personer=i.personer, lastmod=datetime.datetime.now(), moddedby=session.user)
+ return web.seeother('/bildinfo/' + imghash)
+
+class bild():
+ form = web.form.Form(
+ web.form.Textarea('kommentar', web.form.notnull, description=""),
+ web.form.Button('kommentera'))
+ def GET(self, imghash):
+ i = web.input(unlike=None, like=None, hate=None, unhate=None)
+ kform = self.form()
+ if session.login > 1:
+ l = db.query("SELECT * FROM likes WHERE bild='"+imghash+"' AND user='"+session.user+"';")
+ h = db.query("SELECT * FROM hates WHERE bild='"+imghash+"' AND user='"+session.user+"';")
+ if l:
+ user_likes = True
+ else:
+ user_likes = False
+ if h:
+ user_hates = True
+ else:
+ user_hates = False
+ try:
+ if i.delete != '':
+ allow_del = db.select('bildkommentar', where="id='"+i.delete+"'", what='user')[0]
+ print(allow_del)
+ if allow_del.user == session.user:
+ db.delete('bildkommentar', where='id="' + i.delete + '"')
+ except:
+ print('something wrong with input in class bild, så att du veit')
+ if i.like != None and user_likes == False:
+ db.insert('likes', user=session.user, bild=imghash, datum=datetime.datetime.now())
+ user_likes = True
+ elif i.unlike != None and user_likes == True:
+ db.query("DELETE FROM likes WHERE bild='"+imghash+"' AND user='"+session.user+"';")
+ user_likes = False
+ if i.hate != None and user_hates == False:
+ db.insert('hates', user=session.user, bild=imghash, datum=datetime.datetime.now())
+ user_hates = True
+ elif i.unhate != None and user_hates == True:
+ db.query("DELETE FROM hates WHERE bild='"+imghash+"' AND user='"+session.user+"';")
+ user_hates = False
+ likes = db.query("SELECT Count(*) AS likes FROM likes WHERE bild='"+imghash+"';")[0]
+ hates = db.query("SELECT Count(*) AS hates FROM hates WHERE bild='"+imghash+"';")[0]
+ b = db.select('bilder', where="filename='" + imghash +"'", what='titel, year, fotograf, plats, beskrivning, personer, moddedby, lastmod, uppladdare')[0]
+ text = db.select('allaversioner', where="filename='" + imghash +"'", what='moddedby')
+ comments = db.select('bildkommentar', where="filename='" + imghash +"'", what='id, user, comment, upvotes, datumtid', order='datumtid DESC')
+ try:
+ personer = b.personer.replace(', ', ',').split(',')
+ except:
+ personer = ''
+ back_next = db.query('SELECT prev, next from (SELECT id, LAG(filename) OVER (ORDER BY id) AS prev, filename, LEAD(filename) OVER (ORDER BY id) AS next FROM bilder) AS t WHERE filename="'+imghash+'";')[0]
+ print(back_next)
+ return render.bild(b, imghash, personer, kform, comments, session.user, user_likes, likes, user_hates, hates, back_next, text, getdisplayname)
+ else:
+ session.backurl="/bild/"+imghash
+ raise web.seeother("/login")
+ def POST(self, imghash):
+ ip = web.ctx['ip']
+ referer = web.ctx.env.get('HTTP_REFERER','https://bygdis.fi')
+ stopflood(ip, referer)
+ komm = self.form()
+ if session.login > 1:
+ i = web.input()
+ if i.kommentar != '':
+ db.insert('bildkommentar', filename=imghash, user=session.user, comment=i.kommentar, datumtid=datetime.datetime.now())
+ raise web.seeother("/bild/"+imghash+"#comments")
+
+class senaste():
+ def GET(self):
+ if session.login > 1:
+ comments = db.select('bildkommentar', what='id, filename, user, comment, upvotes, datumtid', order='datumtid DESC')
+ b = db.select('bilder', what='filename, titel, year, fotograf, plats, beskrivning, personer, moddedby, lastmod, uppladdare, uploaddate', order='lastmod DESC')
+ binfo = db.select('allaversioner', what='filename, titel, year, fotograf, plats, beskrivning, personer, moddedby, lastmod, uppladdare, uploaddate', order='lastmod DESC')
+ return render.senaste(b, comments, binfo, getdisplayname)
+
+class logout():
+ def GET(self):
+ session.login = 1
+ session.backurl = ''
+ session.user = ''
+ session.bildsida = 0
+ print(session.login)
+ raise web.seeother('/')
+
+class index():
+ def GET(self):
+ upcomingevents = getkalender()
+ return render2.index(upcomingevents)
+
+class old():
+ def GET(self):
+ oldevents = getkalenderall()
+ return render2.old(oldevents)
+
+class nope():
+ def GET(self):
+ #print curdate()
+ return render.nope()
+
+class protokoll():
+ def GET(self):
+ if session.login == 5:
+ webdata = web.input(year=None, nr=0)
+ view = ''
+ years = os.listdir(basedir + '/protokoll/')
+ years.sort()
+ if webdata.year:
+ protokoll = getprotokoll(webdata.year)
+ else:
+ protokoll = []
+ if len(protokoll) > 0:
+ #make html from markdown
+ pandoc_html = ['pandoc', basedir + '/protokoll/' + webdata.year + '/' + protokoll[int(webdata.nr)], '-f', 'markdown', '-t', 'html']
+ #make pdf from markdown
+ viewfile = subprocess.check_output(pandoc_html)
+ view = viewfile.decode()
+ pandoc_pdf = ['pandoc', '--verbose', basedir + '/protokoll/' + webdata.year + '/' + protokoll[int(webdata.nr)], '-f', 'markdown', '-V', 'papersize:a4', '-V', 'geometry:margin=0.8in','-s', '-o', basedir + '/public_html/static/pdf/uf-protokoll.pdf']
+ subprocess.Popen(pandoc_pdf, cwd=basedir + '/public_html/static/pdf/')
+ return render3.protokoll(webdata.year, years, protokoll, view)
+ else:
+ raise web.seeother('/login')
+
+class protokollredirect():
+ def GET(self):
+ raise web.seeother('/protokoll/')
+
+application = app.wsgifunc()