thiswebshoprules

git clone https://git.tarina.org/thiswebshoprules
Log | Files | Refs

commit 6cebe6413cba1ca3d3267f60bb3b80f9ad1fb591
Author: rob <rob@tarina.org>
Date:   Sat, 16 Oct 2021 07:45:16 +0300

first

Diffstat:
Aserver.py | 673+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 673 insertions(+), 0 deletions(-)

diff --git a/server.py b/server.py @@ -0,0 +1,673 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- + +import time, datetime, os, sys + +file_dir = os.path.dirname(__file__) +sys.path.append(file_dir) + +import json +import requests +import subprocess +import web +import hashlib +import random +import time +import shutil +import settings +from PIL import Image +from forex_python.bitcoin import BtcConverter +from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException + +urls = ( + '/?', 'index', + '/putinbag/(.*)', 'putinbag', + '/dropitem/(.*)?', 'dropitem', + '/payln/(.*)', 'payln', + '/paybtc/(.*)', 'paybtc', + '/payment/(.*)', 'payment', + '/checkout/(.*)', 'checkout', + '/pending/(.*)', 'pending', + '/thankyou', 'thankyou', + '/login', 'login', + '/logout', 'logout', + '/products/(.*)?', 'products', + '/bigpic/(.*)?', 'bigpic', + '/categories?', 'categories', + '/op', 'op', + '/bitcoin', 'bitcoin', + '/shipping/(.*)', 'shipping', + '/payments?', 'payments') + +allowed = (("rbckman", "secret"), + ("brkhelle", "topsecret")) + +productsbad = (("GetDaFuckOuttaHere", 420.00), + ("GetDaFuckOuttaHere Viewfinder", 80.00), + ("Picamera", 30.00), + ("Donation", 0.005)) + +bag = '' + +#Load from settings + +rpcauth = settings.rpcauth +charge_url = settings.charge_url +webmaster = settings.webmaster +baseurl = settings.baseurl + + +basedir = os.path.dirname(os.path.realpath(__file__)) +templatedir = basedir + '/public_html/templates/' +staticdir = basedir + '/public_html/static/' +web.config.debug = False +app = web.application(urls, globals()) +store = web.session.DiskStore(basedir + '/sessions') +render = web.template.render(templatedir, base="base") +renderop = web.template.render(templatedir, base="op") +db = web.database(dbn='sqlite', db=basedir + "/db/cyberpunkcafe.db") +session = web.session.Session(app,store,initializer={'login':0, 'privilege':0, 'bag':[], 'sessionkey':0}) + +#----------- Database setup ------------- + +#Remeber to store Euros in cents + +#CREATE TABLE products (id integer PRIMARY KEY, name text NOT NULL, description text, price integer NOT NULL, available integer, sold integer, priority integer, dateadded integer, datelastsold integer, daterunout integer, dateavailable integer); + +#CREATE TABLE shipping (id integer PRIMARY KEY, country text NOT NULL, cost integer NOT NULL, days integer NOT NULL); + +#should rename to customer +#CREATE TABLE pending (id integer PRIMARY KEY, invoice_key text NOT NULL, country text NOT NULL, firstname text NOT NULL, lastname text NOT NULL, address text NOT NULL, town text NOT NULL, postalcode integer NOT NULL, email text NOT NULL, dateadded integer) + +#CREATE TABLE invoices (id INT AUTO_INCREMENT, invoice_key TEXT, btc TEXT, ln TEXT, products TEXT, payment TEXT, amount INT, totsats INT, timestamp TIMESTAMP, status TEXT, datepaid TIMESTAMP, dateshipped TIMESTAMP); + + +def logged(): + if session.login == 1: + return True + else: + return False + +def sendmail(email, subject, msg): + #Send mail + echomsg = subprocess.Popen(('echo', msg), stdout=subprocess.PIPE) + sendmsg = subprocess.check_output(('mail', '-r', 'rob@tarina.org', '-s', subject, email), stdin=echomsg.stdout) + echomsg.wait() + #subprocess.call(['echo', msg, '|', 'mail', '-r', 'rob@tarina.org','-s', subject, email]) + +def createinvoice(amount, description, invoice_key): + #Cents to EUR + amount = str(amount*1000) + invoice_details = {"msatoshi":amount, "description": "{}".format(description)} + print(invoice_details) + resp = requests.post(charge_url+'/invoice/', json=invoice_details) + #print(resp.json()) + return resp.json() + +def getinvoice(id): + resp = requests.get(charge_url+'/invoice/'+id) + print(resp.json()) + return resp.json() + +def callsubprocess(cmd): + subprocess.call(cmd.split()) + +def dropitems(d): + i = getproduct(d) + db.update('products', where="id='"+str(i.id)+"'", available=i.available+1) + product = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"' AND product='"+str(i.id)+"';")[0] + if product.quantity > 1: + db.update('customerbag', where="sessionkey='" + session.sessionkey +"' and product='"+str(i.id)+"'", quantity=product.quantity-1) + else: + db.query("DELETE FROM customerbag WHERE sessionkey='" + session.sessionkey +"' AND product='"+str(i.id)+"';") + +def addtobag(p): + i = getproduct(p) + if i.available > 0: + #session.bag += (i.name, i.price, i.id), + db.update('products', where="id='"+str(i.id)+"'", available=i.available-1) + product = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"' AND product='"+str(i.id)+"';") + if product: + product = product[0] + print(product) + db.update('customerbag', where="sessionkey='" + session.sessionkey +"' and product='"+str(i.id)+"'", quantity=product.quantity+1) + print('gwtdafaakouttahere') + else: + db.insert('customerbag', sessionkey=session.sessionkey, product=i.id, price=i.price, quantity=1, timeadded=datetime.datetime.now()) + +def productname(productid): + try: + name = db.query("SELECT name FROM products WHERE id='"+str(productid)+"';")[0] + except: + return '' + return name.name + +def getproduct(productid): + try: + product = db.query("SELECT * FROM products WHERE id='"+str(productid)+"';")[0] + except: + return '' + return product + +def getavailable(productid): + try: + name = db.query("SELECT available FROM products WHERE id='"+str(productid)+"';")[0] + except: + return '' + return name.available + +def checkforoldbags(): + print('checking for old bags') + bags = db.select('customerbag') + for bag in bags: + if datetime.datetime.now() - bag.timeadded > datetime.timedelta(hours=1): + print(datetime.datetime.now() - bag.timeadded) + print(datetime.timedelta(hours=1)) + print("Fuck") + product = getproduct(bag.product) + print('found a bag at door! goddamit, got to put ' + str(bag.quantity) + ' x ' + product.name + ' back on the shelf') + if product.available > 1: + q = product.available + bag.quantity + else: + q = bag.quantity + db.update('products', where="id='"+str(bag.product)+"'", available=str(q)) + db.query("DELETE FROM customerbag WHERE sessionkey='" + bag.sessionkey + "'") + +def checkavailable(): + print('check items from availability') + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey + "'") + for i in bag: + q = getavailable(i.product) + soldout = q - i.quantity + if soldout < 0: + web.seeother('/?error=soldout') + else: + return + +def sold(): + print('remove items from availability') + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey + "'") + for i in bag: + q = getavailable(i.product) + soldout = q - i.quantity + if soldout < 0: + web.seeother('/?error=soldout') + else: + db.update('products', where="id='"+str(i.product)+"'", available=str(q - i.quantity)) + + +def organizepics(product): + imgdir = basedir+'/public_html/static/img/' + str(product) + '/' + imgdirlist = [imgdir, imgdir + 'web/', imgdir + 'thumb/'] + for d in imgdirlist: + pics = next(os.walk(d))[2] + organized_nr = 0 + for s in sorted(pics): + if '.jpeg' in s: + #print(s) + unorganized_nr = int(s[0:3]) + if organized_nr == unorganized_nr: + print('correcto pic numbering') + pass + if organized_nr != unorganized_nr: + print('false, correcting pic from ' + str(unorganized_nr) + ' to ' + str(organized_nr)) + mv = 'mv ' + d + str(unorganized_nr).zfill(3) + '.jpeg' + mv2 = ' ' + d + str(organized_nr).zfill(3) + '.jpeg' + os.system(mv + mv2) + organized_nr += 1 + +class index(): + def GET(self): + checkforoldbags() + i = web.input(dropitem=None, putinbag=None) + if session.sessionkey == 0: + session.sessionkey = hashlib.sha256(str(random.getrandbits(256)).encode('utf-8')).hexdigest() + if i.dropitem != None: + session.bag = dropitems(int(i.dropitem)) + print(session.bag) + if i.putinbag != None: + addtobag(i.putinbag) + return web.seeother('/#' + i.putinbag) + print('Cyberpunk cafe') + #print(session.bag) + b = BtcConverter() + listproducts = db.query("SELECT * FROM products ORDER BY priority DESC") + imgfiles = [] + products = [] + # Search product images + for i in listproducts: + productimages = [''] + imgdir = staticdir + 'img/' + str(i.id) + '/web/' + try: + productimages = sorted(os.listdir(imgdir)) + if len(productimages) == 0: + productimages = [''] + print(productimages) + except FileNotFoundError: + print('No product images') + pass + i.update({'images':productimages}) + products.append(i) + try: + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"';") + except: + bag = [] + return render.index(products, b, bag, str, int, float, session.sessionkey, productname) + +class putinbag: + def GET(self, p): + addtobag(p) + raise web.seeother('/') + +class dropitem(): + def GET(self, d): + p = web.input() + i = 0 + dropitems(int(d)) + return web.seeother('/#'+d) + +class bigpic(): + def GET(self, i): + print('faaaakyeee ' + i) + p = web.input(pic=None) + if p.pic != None: + return render.bigpic(p.pic, i) + +class checkout: + t = [] + shippingcountries = db.select('shipping', what='country', order='country ASC') + shippingcountries = list(shippingcountries) + t.append('NO-SHIPPING') + for i in shippingcountries: + if i.country != 'NO-SHIPPING': + t.append(i.country) + form = web.form.Form( + web.form.Dropdown('country', t, web.form.notnull, description="Country"), + web.form.Textbox('firstname', web.form.notnull, description="First Name:"), + web.form.Textbox('lastname', web.form.notnull, description="Last Name:"), + web.form.Textbox('address', web.form.notnull, description="Shipping Address:"), + web.form.Textbox('town', web.form.notnull, description="Town / City:"), + web.form.Textbox('postalcode', web.form.regexp('\d+', 'number thanx!'), web.form.notnull, description="Postalcode / zip"), + web.form.Textbox('email', web.form.notnull, description="Email:"), + web.form.Button('Calculate shipping cost')) + def GET(self, pending_key): + #checkavailable() + checkoutform = self.form() + if pending_key: + oldinfo = db.select('pending', where="invoice_key='" + pending_key + "'", what='country, firstname, lastname, address, town, postalcode, email') + oldinfo = oldinfo[0] + checkoutform.fill(country=oldinfo.country, firstname=oldinfo.firstname, lastname=oldinfo.lastname, address=oldinfo.address, town=oldinfo.town, postalcode=oldinfo.postalcode, email=oldinfo.email) + b = BtcConverter() + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"';") + return render.checkout(checkoutform, bag, b, productname, float) + def POST(self, pending_key): + checkoutform = self.form() + i = web.input() + if i.country != 'NO-SHIPPING': + if not checkoutform.validates(): + b = BtcConverter() + return render.checkout(checkoutform, session.bag, b) + if pending_key: + db.update('pending', where="invoice_key='" + pending_key +"'", country=i.country, firstname=i.firstname, lastname=i.lastname, address=i.address, town=i.town, postalcode=i.postalcode, email=i.email, dateadded=datetime.datetime.now()) + else: + pending_key = session.sessionkey + db.insert('pending', invoice_key=pending_key, country=i.country, firstname=i.firstname, lastname=i.lastname, address=i.address, town=i.town, postalcode=i.postalcode, email=i.email, dateadded=datetime.datetime.now()) + raise web.seeother('/pending/' + pending_key) + +class pending: + form = web.form.Form( + web.form.Dropdown('payment', ['Bitcoin Lightning', 'Bitcoin'], web.form.notnull, description="Select payment method"), + web.form.Button('Pay')) + def GET(self, pending_key): + #checkavailable() + pendingform = self.form() + if pending_key: + pendinginfo = db.select('pending', where="invoice_key='" + pending_key + "'", what='country, firstname, lastname, address, town, postalcode, email') + pendinginfo = pendinginfo[0] + shippinginfo = db.select('shipping', where="country='" + pendinginfo.country + "'", what='price, days') + shippinginfo = shippinginfo[0] + b = BtcConverter() + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"';") + return render.pending(pending_key, pendingform, pendinginfo, shippinginfo, bag, b, productname, float) + def POST(self, pending_key): + pendingform = self.form() + if pending_key: + pendinginfo = db.select('pending', where="invoice_key='" + pending_key + "'", what='country, firstname, lastname, address, town, postalcode, email') + pendinginfo = pendinginfo[0] + shippinginfo = db.select('shipping', where="country='" + pendinginfo.country + "'", what='price, days') + shippinginfo = shippinginfo[0] + i = web.input() + #if session.bag != []: + totalamount = 0 + description = '' + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"';") + comma = '' + for s in bag: + totalamount += s.price + description += comma + str(s.quantity) + ' x ' + productname(s.product) + comma = ', ' + totalamount += shippinginfo.price + b = BtcConverter() + totsats = int(b.convert_to_btc(float(totalamount/100), 'EUR') * 100000000) + totbtc = int(b.convert_to_btc(float(totalamount/100), 'EUR')) + print(str(totalamount) + ' | ' + description) + print(str(totsats) + ' | ' + description) + #else: + # web.seeother('/') + #make lightning invoice + invoice = createinvoice(totsats, description, pending_key) + callsubprocess('qrencode -s 5 -o '+ staticdir + 'qr/' + invoice['id']+'.png ' + invoice['payreq']) + #make bitcoin address + bitcoinrpc = AuthServiceProxy(rpcauth) + newaddress = bitcoinrpc.getnewaddress('GetDaFuckOuttaHere Butik') + bitcoinrpc = None + btcuri = 'bitcoin:' + newaddress + '?amount=' + str(totbtc) + '&label=' + description + callsubprocess('qrencode -s 5 -o '+ staticdir + 'qr/' + newaddress +'.png ' + btcuri) + try: + db.query("DELETE FROM invoices WHERE invoice_key='" + session.sessionkey +"';") + except: + print('no old invoices to delete') + db.insert('invoices', invoice_key=pending_key, btc=newaddress, ln=invoice['id'], products=description, payment=i.payment, amount=totalamount, totsats=totsats, timestamp=time.strftime('%Y-%m-%d %H:%M:%S')) + # send mail to op + msg = 'You got a new order, from ' + pendinginfo.firstname + ' ' + pendinginfo.lastname + ' from ' + pendinginfo.country + ' email: ' + pendinginfo.email + ' this dude wantz ' + description + ' for ' + str(int(totalamount/100)) + '€ ' + ' with ' + i.payment + sendmail(webmaster, 'GetDaFuckOuttaHere Shop', msg) + # send mail to customer + if i.payment == 'Bitcoin': + paymentlink = 'paybtc/' + if i.payment == 'Bitcoin Lightning': + paymentlink = 'payln/' + if pendinginfo.email != '': + msg = "Thank you for ordering " + description + " at GetDaFuckOuttaHere Shop, we'll be processing your order as soon as possible and send it to " + pendinginfo.firstname + ' ' + pendinginfo.lastname + ', ' + pendinginfo.address + ', ' + str(pendinginfo.postalcode) + ', ' + pendinginfo.town + ', ' + pendinginfo.country + '. To pay/view status of your order please visit ' + baseurl + paymentlink + pending_key + sendmail(pendinginfo.email, 'GetDaFuckOuttaHere Shop', msg) + if i.payment == 'Bitcoin': + return web.seeother('/paybtc/' + pending_key) + if i.payment == 'Bitcoin Lightning': + return web.seeother('/payln/' + pending_key) + else: + return web.seeother('/') + +class payln: + def GET(self, invoice_key): + #checkavailable() + invoice = db.select('invoices', where="invoice_key='" + invoice_key + "'", what='invoice_key, btc, ln, products, payment, amount, totsats, timestamp, status, datepaid, dateshipped')[0] + lninvoice = getinvoice(invoice.ln) + bag = db.query("SELECT * FROM customerbag WHERE sessionkey='" + session.sessionkey +"';") + if invoice_key == session.sessionkey: + return render.payln(lninvoice, invoice, bag, productname, float) + else: + raise web.seeother('/?error=timeout') + def POST(self, id): + data = web.data() + data = data.decode('utf8').replace("'", '"') + data = json.loads(data) + print(data) + if data['status'] == 'paid': + print("Hurray it worked") + sold() + return render.thankyou(id) + +class paybtc: + def GET(self, invoice_key): + invoice = db.select('invoices', where="invoice_key='" + invoice_key + "'", what='invoice_key, btc, ln, products, payment, amount, totsats, timestamp, status, datepaid, dateshipped')[0] + totbtc = float(invoice.totsats * 0.00000001) + btcaddress = invoice.btc + btcuri = 'bitcoin:' + btcaddress + '?amount=' + str(totbtc) + '&label=' + invoice.products + bitcoinrpc = AuthServiceProxy(rpcauth) + showpayment = bitcoinrpc.listreceivedbyaddress(0, True, True, btcaddress) + bitcoinrpc = None + if showpayment: + for i in showpayment: + confirmations = int(i['confirmations']) + print(str(confirmations)) + if invoice.datepaid == None and confirmations > 6: + msg = 'GetDaFuckOuttaHere order update! someone sent you Bitcoin! ' + baseurl + '/paybtc/' + invoice.invoice_key + print(msg) + sendmail(webmaster, 'GetDaFuckOuttaHere Shop', msg) + db.update('invoices', where="invoice_key='" + invoice.invoice_key + "'", status='paid', datepaid=time.strftime('%Y-%m-%d %H:%M:%S')) + return render.paybtc(invoice, btcaddress, btcuri, showpayment) + +class payments: + def GET(self): + w = web.input() + if w: + db.update('invoices', where="invoice_key='" + w.key + "'", status=w.status) + #get the right invoice send mail + customer = db.select('pending', where="invoice_key='" + w.key + "'", what='country, firstname, lastname, address, town, postalcode, email')[0] + payment = db.select('invoices', where="invoice_key='" + w.key + "'", what='btc, ln, invoice_key, products, payment, amount, totsats, timestamp, status, datepaid, dateshipped')[0] + if payment.payment == 'Bitcoin': + paylink = 'paybtc/' + elif payment.payment == 'Bitcoin Lightning': + paylink = 'payln/' + if w.status == 'thankyou': + msg="Hi " + customer.firstname + " " + customer.lastname + ", thank you for ordering. You can track the status of your order at " + baseurl + paylink + payment.invoice_key + sendmail(customer.email, 'GetDaFuckOuttaHere Shop, a thank you!', msg) + elif w.status == 'shipped': + msg="Hi " + customer.firstname + " " + customer.lastname + ", your order has been shipped!. You can track the status of your order at " + baseurl + paylink + payment.invoice_key + sendmail(customer.email, 'GetDaFuckOuttaHere Shop, order shipped!', msg) + paymentdict = {} + listpayments = [] + payments = db.select('invoices', what='btc, ln, invoice_key, products, payment, amount, totsats, timestamp, status, datepaid, dateshipped', order='timestamp DESC') + for i in payments: + pending = db.select('pending', where="invoice_key='" + i.invoice_key + "'", what='country, firstname, lastname, address, town, postalcode, email') + i.update(pending[0]) + listpayments.append(i) + return renderop.payments(listpayments) + +class payment: + def GET(self, invoice_key): + id = db.where('invoices', invoice_key=invoice_key)[0]['ln'] + invoice = getinvoice(id) + return render.payment(invoice) + +class thankyou: + def GET(self, id): + return render.thankyou(id) + +class login: + form = web.form.Form( + web.form.Textbox('user', web.form.notnull, description="User"), + web.form.Password('password', web.form.notnull, description="Passcode"), + web.form.Button('Login')) + def GET(self): + if not logged(): + loginform = self.form() + return render.login(loginform) + else: + raise web.seeother('/op') + def POST(self): + loginform = self.form() + if not loginform.validates(): + return render.login(loginform) + else: + i = web.input() + if (i.user,i.password) in allowed: + session.login = 1 + raise web.seeother('/op') + else: + return render.login(loginform) + +class logout: + def GET(self): + session.login = 0 + raise web.seeother('/') + +class op: + def GET(self): + if logged(): + return renderop.operator() + else: + raise web.seeother('/login') + +class categories: + form = web.form.Form( + web.form.Textbox('category', web.form.notnull, description="Add Category:"), + web.form.Button('Add')) + def GET(self): + if logged(): + i = web.input(delete=None) + if i.delete: + db.delete('categories', where='id='+i.delete) + listcategories = db.query("SELECT * FROM categories ORDER BY id DESC") + addcategory = self.form() + return renderop.categories(listcategories,addcategory) + else: + raise web.seeother('/login') + def POST(self): + addcategory = self.form() + i = web.input() + db.insert('categories', category=i.category) + raise web.seeother('/categories') + + +class products: + listcategories = db.query("SELECT * FROM categories ORDER BY id DESC") + p = [] + for i in listcategories: + p.append(i.category) + #p = listcategories[0] + form = web.form.Form( + web.form.Dropdown('category', p, web.form.notnull, description="Category:"), + web.form.Textbox('name', web.form.notnull, description="Name:"), + web.form.Textarea('description', web.form.notnull, description="Description:"), + web.form.Textbox('price', web.form.regexp('\d+', 'number thanx!'), web.form.notnull, description="Price in cents"), + web.form.Textbox('available', web.form.notnull, web.form.regexp('\d+', 'number dumbass!'), description="Available"), + web.form.Textbox('priority', web.form.notnull, web.form.regexp('\d+', 'number dumbass!'), description="Priority (high value more priority)"), + web.form.Button('Save')) + def GET(self, idvalue): + if logged(): + i = web.input() + if i: + if i.cmd == 'del': + db.delete('products', where='id=' + idvalue) + imgdir = staticdir + 'img/' + idvalue + try: + shutil.rmtree(imgdir,ignore_errors=True,onerror=None) + except: + print('no picture folder, nothing to remove...') + pass + raise web.seeother('/products/') + if i.cmd == 'removeimg': + os.remove(staticdir + '/img/' + idvalue + '/' + i.img) + os.remove(staticdir + '/img/' + idvalue + '/web/' + i.img) + os.remove(staticdir + '/img/' + idvalue + '/thumb/' + i.img) + raise web.seeother('/products/' + idvalue) + organizepics(idvalue) + addproduct = self.form() + addproduct.fill(available='1', priority='1') + if idvalue: + oldinfo = db.select('products', where="id=" + idvalue, what='name, description, price, available, priority, category') + oldinfo = oldinfo[0] + addproduct.fill(name=oldinfo.name, description=oldinfo.description, price=oldinfo.price, available=oldinfo.available, priority=oldinfo.priority, category=oldinfo.category) + listproducts = db.query("SELECT * FROM products ORDER BY priority DESC") + imgdir = staticdir + 'img/' + idvalue + '/web/' + try: + productimages = sorted(os.listdir(imgdir)) + print(productimages) + except: + productimages = [] + print('No productimages for this product') + return renderop.products(addproduct, listproducts, productimages, idvalue) + else: + raise web.seeother('/login') + def POST(self, idvalue): + listproducts = db.query("SELECT * FROM products ORDER BY priority DESC") + addproduct = self.form() + if logged(): + i = web.input(imgfile={}) + for p in i: + print(p) + if i.imgfile != {}: + if idvalue == '': + print('cant upload a picture to a non existing product') + raise web.seeother('/products/') + print(i.imgfile.filename) + if i.imgfile.filename == '': + print('hmmm... no image to upload') + raise web.seeother('/products/' + idvalue) + print('YEAH, Upload image!') + + ##---------- UPLOAD IMAGE ---------- + + imgdir = staticdir + 'img/' + idvalue + os.makedirs(imgdir, exist_ok=True) + 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) + #filename = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest() + '.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('/products/' + idvalue) + + ##---------- RESIZE IMAGE ----------- + try: + os.makedirs(imgdir + '/web/', exist_ok=True) + os.makedirs(imgdir + '/thumb/', exist_ok=True) + except: + print('Folders is') + image.thumbnail((900,900), Image.ANTIALIAS) + image.save(imgdir + '/web/' + imgname) + image.thumbnail((300,300), Image.ANTIALIAS) + image.save(imgdir + '/thumb/' + imgname) + + organizepics(idvalue) + raise web.seeother('/products/' + idvalue) + if not addproduct.validates(): + raise web.seeother('/products/' + idvalue) + else: + if idvalue: + db.update('products', where='id=' + idvalue, category=i.category, name=i.name, description=i.description, price=i.price, available=i.available, sold=0, priority=i.priority, dateadded=datetime.datetime.now()) + else: + db.insert('products', category=i.category, name=i.name, description=i.description, price=i.price, available=i.available, sold=0, priority=i.priority, dateadded=datetime.datetime.now()) + raise web.seeother('/products/' + idvalue) + else: + raise web.seeother('/login') + +class shipping: + form = web.form.Form( + web.form.Textbox('country', web.form.notnull, description="Country:"), + web.form.Textbox('price', web.form.regexp('\d+', 'number thanx!'), web.form.notnull, description="Price in cents"), + web.form.Textbox('days', web.form.regexp('\d+', 'number thanx!'), web.form.notnull, description="Shipping in days"), + web.form.Button('Add shipping country')) + def GET(self, idvalue): + if logged(): + addcountry = self.form() + if idvalue: + oldinfo = db.select('shipping', where="id=" + idvalue, what='country, price, days') + oldinfo = oldinfo[0] + addcountry.fill(country=oldinfo.country, price=oldinfo.price, days=oldinfo.days) + listcountries = db.query("SELECT * FROM shipping ORDER BY country DESC") + return renderop.shipping(addcountry, listcountries) + else: + raise web.seeother('/login') + def POST(self, idvalue): + if logged(): + addcountry = self.form() + if not addcountry.validates(): + listcountries = db.query("SELECT * FROM shipping ORDER BY country DESC") + return renderop.shipping(addcountry, listcountries) + else: + i = web.input() + if idvalue: + db.update('shipping', where='id=' + idvalue, country=i.country, price=i.price, days=i.days) + else: + db.insert('shipping', country=i.country, price=i.price, days=i.days) + raise web.seeother('/shipping/') + else: + raise web.seeother('/login') + +class bitcoin: + def GET(self): + if logged(): + bitcoinrpc = AuthServiceProxy(rpcauth) + wallet = bitcoinrpc.getwalletinfo() + bitcoinrpc = None + return renderop.bitcoin(wallet) + +application = app.wsgifunc()