-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1308 lines (1065 loc) · 39.1 KB
/
main.py
File metadata and controls
1308 lines (1065 loc) · 39.1 KB
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ESSENTIAL IMPORTS
import json
import os
import datetime
import werkzeug.exceptions
from utilities import *
# WEB-RELATED IMPORTS
from flask import Flask, render_template, redirect, request, make_response, session, jsonify, abort
import requests
from werkzeug.middleware.proxy_fix import ProxyFix
from google.cloud import secretmanager
from google.oauth2 import service_account
### START APP CONFIG ###################################################################################################
print(" * Initiatlising...")
project_id = "panson"
FETCH_SECRETS = True
if "SECRETS" in os.environ:
if os.environ["SECRETS"] in [0, "0", False]:
FETCH_SECRETS = False
print(" * NOT Updating secrets (SECRETS={})".format(os.environ["SECRETS"]))
if FETCH_SECRETS:
print(" * Updating secrets")
os.makedirs("secure", exist_ok=True)
try:
secret_client = secretmanager.SecretManagerServiceClient()
print(" * Secret manager initialised")
try:
with open("secure/firebase_service_account_info.json", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/firebase_credentials/versions/1"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read firebase secret")
try:
with open("secure/firestore_service_account_info.json", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/firestore_credentials/versions/1"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read firestore secret")
try:
with open("secure/stripe_key", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/stripe_key_thecnopapa_test/versions/3"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read stripe key")
try:
with open("secure/flask_key", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/flask_secret_key/versions/1"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read flask secret")
try:
with open("secure/mailgun_key", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/mailgun_sending_key/versions/2"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read mailgun sending key")
try:
with open("secure/trello_key", "w") as f:
f.write(secret_client.access_secret_version(request={"name": "projects/746452924859/secrets/trello_key/versions/3"}).payload.data.decode("UTF-8"))
except:
print(" * Failed to read trello key")
try:
with open("secure/seo_key.txt", "w") as f:
f.write(secret_client.access_secret_version(
request={"name": "projects/746452924859/secrets/seo_key/versions/3"}).payload.data.decode(
"UTF-8"))
except:
print(" * Failed to read seo key")
except:
print(" * Failed to initialise secret manager")
os.environ["FIREBASE_CREDENTIALS"] = "secure/firebase_service_account_info.json"
os.environ["FIRESTORE_CREDENTIALS"] = "secure/firestore_service_account_info.json"
os.environ["STRIPE_KEY"] = "secure/stripe_key"
os.environ["FLASK_KEY"] = "secure/flask_key"
os.environ["MAILGUN_KEY"] = "secure/mailgun_key"
os.environ["TRELLO_KEY"] = "secure/trello_key"
os.environ["SEO_KEY"] = "secure/seo_key.txt"
app = Flask(__name__)
app.config['STATIC_FOLDER'] = "static"
app.config['UPLOAD_FOLDER'] = "uploads"
app.config['APPLICATION_ROOT'] = '/'
app.config['PREFERRED_URL_SCHEME'] = 'https'
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_port=1)
try:
with open("secure/flask_key", "r") as f:
app.secret_key = bytes(str(f.read()), 'utf-8')
except:
print(" * Failed to read flask key")
base_url = "https://firestore.googleapis.com/v1/"
cols_path = base_url + "projects/panson/databases/productes/documents/collecions"
prods_path = base_url + "projects/panson/databases/productes/documents/productes"
storage_url = "https://firebasestorage.googleapis.com/v0/b/panson.firebasestorage.app/o/{}%2F{}?alt=media"
storage_url_single = "https://firebasestorage.googleapis.com/v0/b/panson.firebasestorage.app/o/{}?alt=media"
### END APP CONFIG #####################################################################################################
# GLOBALS SETUP
from app_essentials.session import get_current_user, get_session_id
from app_essentials.products import Products, Product, get_talla_es
from app_essentials.firebase import get_user_data, get_cols, check_if_admin
from app_essentials.firestore import list_blobs, upload_images, load_files, download_file, upload_file
from app_essentials.html_builder import template
from app_essentials.utils import get_opcions
from app_essentials.localisation import Images
from app_essentials.mail import send_email, send_newsletter, add_to_list
from payments import Trello
from werkzeug.exceptions import HTTPException
class PermanentRedirect(HTTPException):
code = 301
def __init__(self, *args, redirect=None, **kwargs):
self.redirect = redirect
super().__init__(*args, **kwargs)
app.aborter.mapping.update({301: PermanentRedirect})
@app.errorhandler(HTTPException)
def handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
if e.code == 403:
return redirect("/admin")
if e.code == 301:
print(e)
return redirect(e.redirect, 301)
# start with the correct headers and status code from the error
response = e.get_response()
# replace the body with JSON
response.data = json.dumps({
"code": e.code,
"name": e.name,
"description": e.description,
})
response.content_type = "application/json"
return render_template("ERROR.html", code=e.code, name=e.name, description=e.description, request=request), e.code
origin = datetime.datetime.now()
usage_ips = {}
@app.before_request
def check_limit(max_reqs=10, seconds=10):
#print("* Checking limit (session):")
#print(session)
now = (datetime.datetime.now() - origin).total_seconds()
#print("Now: ", now)
usage = 0
window = now
if "usage" in session:
usage = session["usage"]
if "window" in session:
window = session["window"]
#window = session["window"]
delta = now - window
#print(" - Delta: ", delta)
if delta >= seconds or delta < 0:
pass
# window = now
# session["window"] = window
# usage = 0
# session["usage"] = usage
# print(" - Window renewed, delta: ", delta)
#print(" - Window: ", window)
#print(" - Usage: ", usage)
elif usage > max_reqs:
print(" - Usage exceded: ", usage)
abort(492)
else:
pass
def use(amount=1.0):
#print("* Checking limit (local):")
global usage_ips
if "usage" not in session:
session["usage"] = 0
#print(" - Usage not in session")
req_ip = request.remote_addr
#print(" - Request IP: ", req_ip)
now = (datetime.datetime.now() - origin).total_seconds()
if req_ip in usage_ips.keys():
delta = now - usage_ips[req_ip]["window"]
#print(" - Delta: ", delta)
usage_ips[req_ip]["usage"] += amount
usage_ips[req_ip]["delta"] = delta
if delta < 0 or delta >= 10:
usage_ips[req_ip]["window"] = now
usage_ips[req_ip]["usage"] = amount
else:
#print(" - IP not in dict")
usage_ips[req_ip] = dict(window=now, usage = amount, delta=0)
session["usage"] = usage_ips[req_ip]["usage"]
session["window"] = usage_ips[req_ip]["window"]
#print(" - Window: ", usage_ips[req_ip]["window"])
#print(" - Usage: ", usage_ips[req_ip]["usage"])
if usage_ips[req_ip]["usage"] >= 10:
abort(429)
raise Exception("Usage exceded")
if len(usage_ips.keys()) >100:
usage_ips = {}
try:
#print("IP:", req_ip, "Using:", amount, "Total:", usage_ips[req_ip]["usage"], "Delta:", usage_ips[req_ip]["delta"])
pass
except:
#print("IP:", req_ip, "error checking IP")
abort(418)
#session["usage"] += amount
#print(request.path)
if "test." in request.host:
if request.path.split("/")[1] not in ["static", "style", "media", "scripts"]:
if not (request.path == "/admin/" or request.path == "/login"):
if admin_check():
pass
else:
abort(403)
if "panson.thecnopapa.com" in request.host:
abort(301, redirect="https://pansonjoieria.com"+request.full_path)
def admin_check():
user = get_current_user()
return check_if_admin(user.username, user.password)
@app.route("/blank")
def return_blank():
use(0.1)
if admin_check():
return ""
return None
@app.route("/ips")
def return_ips():
use(0.1)
if admin_check():
return usage_ips
return None
@app.route("/newsletter")
def view_newsletter():
use(0.1)
if admin_check():
template_path = download_file("newsletters/email_newsletter.html" ,template=True)
print(template_path)
return render_template(template_path)
return None
@app.route("/size/calculator/", methods=["POST", "GET"])
def get_talla():
use(0.01)
es_talla =""
f_talla = request.form.get("talla")
f_unit = request.form.get("unit")
print(f_talla, f_unit)
if f_talla is not None and f_unit is not None:
es_talla = get_talla_es(f_unit, f_talla)
else:
es_talla = "missing data"
result = "Talla: {} / Unit: {} /= TallaES: {}".format(f_talla, f_unit, es_talla)
return "<form action='/size/calculator/' method=POST><input name='unit' placeholder='unit'><br><input name='talla' placeholder='size'><br><button>SUBMIT</button></form><br>Result: {}".format(result)
@app.post("/accept-cookies")
def acceptar_cookies():
use(0.1)
print("Accepting cookies")
user = get_current_user()
r = request.get_json()
print(r["essential"])
user.accepted_cookies = True
user.essential_cookies = r["essential"]
user.cookies = r["cookies"]
print("essential: ", user.essential_cookies)
print("cookies: \n", user.cookies)
user.update_db()
session.permanent = r["essential"]
print(user)
return ""
@app.post("/ignore-newsletter")
def ignore_newsletter():
use(0.1)
print("Ignoring newsletter")
user = get_current_user()
user.no_newsletter = True
user.update_db()
return "", 200
@app.post("/subscribe-newsletter")
def subscribe_newsletter():
use(0.1)
print("Subsribing to newsletter")
r = request.get_json()
print(r)
email = r["email"]
name = r["name"]
resp_code = add_to_list(email, name, "newsletter")
return "", resp_code
from werkzeug.utils import secure_filename
from flask import url_for, send_from_directory
@app.route("/<lan>/tic/<tic_page>")
def tic(lan,tic_page):
use()
return template(templates="terms", lan=lan, tic_page=tic_page )
@app.route("/static/<folder>/<file>")
@app.route("/static/<file>")
def get_static(file, folder=None):
use(0.01)
try:
raise Exception()
file = secure_filename(file)
if folder is None:
return redirect(storage_url_single.format(file))
folder = secure_filename(folder)
return redirect(storage_url.format(folder, file), 301)
except:
if folder is None:
return send_from_directory("static", file)
return send_from_directory("static", folder + "/" + file)
@app.route("/style/<file>")
def get_style(file):
use(0.01)
return redirect("/static/style/"+secure_filename(file))
@app.route("/scripts/<file>")
def get_script(file):
use(0.01)
return redirect("/static/scripts/"+secure_filename(file))
@app.route("/fonts/<file>")
def get_font(file):
use(0.01)
return redirect("/static/scripts/"+secure_filename(file))
@app.route("/media/logo/gran")
def logo_gran():
imgs = Images()
return redirect(imgs.get_url("imatges", imgs.get_fixed("logos").imatges[0]))
@app.route("/media/logo/petit")
def logo_petit():
imgs = Images()
return imgs.get_url("imatges", imgs.get_fixed("logos").imatges[1])
@app.route("/")
@app.route("/<lan>/")
def index(lan ="cat", favicon = True):
# Special urls #######################################
if lan == "favicon.ico":
use(0.01)
if favicon:
return redirect("/static/media/favicon.ico")
else:
return ""
elif lan == "apple-touch-icon-precomposed.png":
use(0.01)
return redirect("/static/media/apple-touch-icon-precomposed.png")
elif lan == "apple-touch-icon-120x120.png":
use(0.01)
return redirect("/static/media/apple-touch-icon-120x120.png")
elif lan == "robots.txt":
use()
return redirect("/static/robots.txt")
elif lan == "sitemap" or lan=="sitemap.xml":
use()
return return_sitemap()
elif lan.startswith("key-"):
use()
with open(os.environ["SEO_KEY"]) as f:
print(repr(lan))
key = f.read()
print(repr(key))
print(repr(lan) == repr(key))
if lan == key:
return send_from_directory("secure", "seo_key.txt")
######################################################
# TODO: Revisit firebase access
use()
slides = list_blobs("portada")
slide_list = [[slide, storage_url.format("portada", slide.split("/")[-1])] for slide in slides if
slide.split("/")[-1] != ""]
html = template(lan=lan, templates=["index", "galeria"], slides= slide_list, hide_title=True, title=False, max_gallery=8,
show_banner=True, show_newsletter=True)
return html
@app.route("/<lan>/sitemap")
@app.route("/<lan>/sitemap.xml")
def return_sitemap(lan="cat"):
use()
return send_from_directory("static", "sitemap.xml")
@app.route("/<lan>/collecio/<id>")
def collections(lan,id):
use()
try:
col = [c for c in get_cols() if c._id == id][0]
html = template(lan=lan, templates=["collecio"], col=col)
return html
except:
return ""
@app.route("/<lan>/productes/")
def productes(lan):
use()
filters = {"esborrat": False, "amagat": False}
html = template(lan=lan,templates="all_products", show_newsletter=True)
return html
@app.route("/<lan>/peces_uniques/")
def peces_uniques(lan):
use()
html = template(lan=lan, templates="uniques", filters={"unica":True, "collecio":[], "tipus":"totes"}, titol="gal_totes")
return html
@app.route("/<lan>/productes/<id>/")
def mostrar_peca(lan, id):
use()
producte = Products(lan=lan).get_single(id)
#print(producte)
html = template(lan=lan, templates="producte3", producte=producte)
return html
@app.route("/<lan>/bespoke/<id>/")
def mostrar_bedpoke(lan, id):
use()
from app_essentials.firebase import bespoke
from app_essentials.products import Bespoke
product = Bespoke(bespoke.document(id).get().to_dict(), id)
print(bespoke)
html = template(lan=lan, templates="producte3", producte=product)
return html
@app.post("/carret/add")
def afegir_al_carret():
use(0.1)
user = get_current_user()
material= None
variacio = None
colors = None
talla = None
talla_multi = None
talla_country = None
talla_es = None
print(request.form)
resp = make_response()
resp.status_code = 206
#resp.body = {"missing-val"}
#resp.content_type = "application/json"
resp.headers["missing-val"] = ""
for k, v in request.form.items():
if "#" in k:
k = k.split("#")[0]
if k == "material":
material = v
elif k == "variacio":
variacio = v
elif k == "color":
if colors is None:
colors = [v]
else:
colors.append(v)
elif k == "talla":
if v != "":
talla = v
elif k == "talla-multi":
if v != "":
talla_multi = v
elif k == "talla-country":
talla_country = v
opcions = {}
if material == "":
resp.headers["missing-val"] = "materials-producte"
return resp
elif material != "NA":
opcions["material"] = material
if variacio == "":
resp.headers["missing-val"] = "variacions-producte"
return resp
elif variacio != "NA":
opcions["variacio"] = variacio
if colors is None:
resp.headers["missing-val"] = "colors-producte"
return resp
for n, c in enumerate(colors):
if c == "":
resp.headers["missing-val"] = "colors-producte#{}".format(n)
return resp
if colors != ["NA"]:
opcions["color"] = colors
if talla is None and talla_multi is None:
resp.headers["missing-val"] = "talles-producte"
return resp
if talla_multi is not None:
talla = talla_multi
if talla_country is not None:
talla = "{}({})".format(talla, talla_country)
if talla_country != "es":
talla_es = "{}".format(get_talla_es(talla_country, talla_multi))
opcions["talla_country"] = talla_country
else:
talla_es = talla
opcions["talla_es"] = talla_es
else:
resp.headers["missing-val"] = "unit"
return resp
opcions["talla"] = talla
print("OPCIONS: ", opcions)
user.add_to_cart(request.form["id"], opcions)
resp.status_code = 200
resp.headers["refresh"] = 0
#return redirect("/{}/productes/{}/".format(lan, request.form["id"]))
return redirect(request.referrer)
@app.post("/<lan>/render_cart")
def render_cart(lan):
use(0.1)
return template(lan=lan, templates="cart")
@app.post("/productes/carret/<pos>/<qty>")
def alterar_carret(pos, qty):
use(0.01)
user = get_current_user()
for n, (k, v) in enumerate(user.cart.items()):
if n == int(pos):
if int(qty) <= 0:
user.cart.pop(k)
break
v["quantity"] = int(qty)
break
user.recalculate()
user.update_db()
#print(user.cart)
return "", 204
@app.post("/<lan>/carret/id2/eliminar_del_carret")
def eliminar_del_carret(lan, id2):
use(0.01)
opcions = get_opcions()
user = get_current_user()
user.add_producte_carret(id2, delete=True)
return opcions
resp = redirect("/{}/productes/{}/?{}".format(lan, id, opcions))
return resp
@app.post("/close_banner")
def close_banner():
pass
@app.post("/<lan>/checkout/init")
def checkout(lan):
use(0.1)
from payments import init_checkout
return init_checkout(lan)
@app.post("/<lan>/checkout/init/force_new_customer")
def checkout_force_customer(lan):
use(0.1)
from payments import init_checkout
return init_checkout(lan, force_new_customer=True)
@app.post("/<lan>/checkout/init/force_new")
def checkout_force(lan):
use(0.1)
from payments import init_checkout
return init_checkout(lan, force_new=True)
@app.route("/<lan>/checkout/stripe")
def stripe_checkout(lan):
use()
return template(lan=lan, templates="stripe_checkout", reset=False, force_new=False)
@app.route("/<lan>/checkout/stripe/force_new")
def stripe_checkout_force(lan):
use()
return template(lan=lan, templates="stripe_checkout", reset=False, force_new=True)
@app.post("/<lan>/checkout/update/shipping")
def calculate_shipping_options_route(lan):
use(0.01)
print("Calculating shipping options")
request_data = request.get_json()
checkout_session_id = request_data.get('checkout_session_id')
print("CHECKOUT SESSION ID: {}".format(checkout_session_id))
shipping_details = request_data.get('shipping_details')
from payments import update_shipping_options
return update_shipping_options(shipping_details, checkout_session_id)
@app.route("/<lan>/checkout/success/")
def stripe_success(lan):
use(0.01)
try:
from payments import process_payment
payment_data = process_payment(lan=lan)
if payment_data is None:
return redirect("/{}".format(lan))
html = template(lan=lan, templates="success", **payment_data)
except Exception as e:
if admin_check():
raise e
return """<div style='width:100%;height:100%;display:flex;align-items:center;justify-content:center;flex-direction:column;'>
<p>Your payment has been processed correctly and your order has been placed.<br>
You should receive an email with your order soon.<br>
<br>
If you are seeing this is due to some technical issues on our side.<br>
If you have any doubts please contact us at <b>help@pansonjoieria.com</b></p>
<br><br>
<a href="/">HOME</a>
</div>
"""
return html
@app.route("/<lan>/checkout/success/test")
def stripe_success_test(lan):
use(0.01)
from payments import process_payment
session = {
"customer_details": {
"email": "test@pansonjoieria.com"
}
}
invoice = {
"hosted_invoice_url": "https://stripe.com",
"number": "12345"
}
html = template(lan=lan, templates="success", invoice=invoice, session=session)
return html
@app.route("/<lan>/checkout/cancel/")
def stripe_cancel(lan):
use()
html = template(lan=lan, templates="cancel")
return html
@app.route("/<lan>/projecte/")
def projecte(lan):
use()
html = template(lan=lan, templates="projecte")
return html
@app.route("/<lan>/contacte/")
def contatce(lan):
use()
html = template(lan=lan, templates="contacte")
return html
@app.route("/<lan>/info-talles/")
def info_talles(lan):
use()
html = template(lan=lan, templates="talles")
return html
@app.route("/<lan>/admin/")
@app.route("/<lan>/admin/<page>/")
@app.route("/admin/")
@app.route("/admin/<page>/")
def admin(lan="cat", page="base"):
use()
from payments import Trello
if admin_check():
return template(lan=lan, imgs=Images().load(), templates="admin-{}".format(page), amagats=True, footer=False, collecions = get_cols(amagats=True), trello=Trello())
else:
return template(lan=lan, templates="login")
@app.post("/login")
def login():
use()
print("loging in...")
from app_essentials.firebase import check_if_admin
#print(request.form["username"], request.form["password"])
if check_if_admin(request.form["username"], request.form["password"]):
user = get_current_user()
user.username = request.form["username"]
user.password = request.form["password"]
user.is_admin = True
user.update_db()
print("login succesfull")
else:
print("login failed")
return redirect("/admin/")
@app.route("/admin/logout")
def logout():
use(0.01)
user = get_current_user()
user.username = None
user.password = None
user.is_admin = False
user.update_db()
return redirect("/")
@app.post("/admin/trello/update")
def trello_update():
use(0.01)
if admin_check():
trello = Trello()
print(request.get_json())
data = request.get_json()
trello.api_key = data["api_key"]
trello.board_id = data["board_id"]
trello.list_id = data["list_id"]
try:
trello.labels = data["labels"]
except:
trello.labels = []
trello.update()
return jsonify({"success": True}), 200
@app.post("/admin/trello/get-lists")
def trello_get_lists():
use(0.01)
if admin_check():
trello = Trello()
print(request.get_json())
lists = trello.get_available_lists(request.get_json()["board_id"])
return jsonify(lists), 200
@app.post("/admin/trello/test")
def trello_test():
use(0.01)
if admin_check():
trello = Trello()
data = request.get_json()
print(data)
trello.api_key = data["api_key"]
trello.board_id = data["board_id"]
trello.list_id = data["list_id"]
try:
trello.labels = data["labels"]
except:
trello.labels = []
print(trello)
r = trello.test()
print(r)
return {"success": r}, 200
@app.post("/admin/misc/update")
def misc_update():
use(0.01)
if admin_check():
data = request.json
from app_essentials.firebase import localisation
print(data)
prev_data = localisation.document("misc").get().to_dict()
target_data = prev_data[data["field"]]
if "pos" in data:
target_data = target_data[int(data["pos"])]
print(target_data)
if data["del"]:
target_data.pop(data["key"])
else:
target_data.update({data["key"]: data["value"]})
print("###")
print(target_data)
print(prev_data)
localisation.document("misc").update(prev_data)
return ""
@app.post("/admin/loc/update-field")
def update_field():
use(0.01)
if admin_check():
print(request.json)
data = request.json
from app_essentials.firebase import localisation
prev_data = localisation.document("languages").collection("text").document(data["page"]).get().to_dict()
print(prev_data)
new_data = prev_data
new_data[data["key"]][data["lan"]] = data["value"]
print(new_data)
localisation.document("languages").collection("text").document(data["page"]).update(new_data)
return ""
@app.post("/admin/loc/update")
def update_loc():
use(0.01)
if admin_check():
print("Updating loc")
data = request.get_json()
label = data["label"]
value = data["value"]
lan = data["lan"]
print(label, value, lan)
from app_essentials.utils import split_multiple
comps = split_multiple(label, "_", "-")
page = comps[0]
print("Page: ", page)
key = "-".join(comps[1:])
from app_essentials.firebase import localisation
prev_data = localisation.document("languages").collection("text").document(page).get().to_dict()
new_data = prev_data
if new_data is None:
localisation.document("languages").collection("text").document(page).set({})
new_data= {}
if key not in new_data.keys():
new_data[key]={"cat":"$empty$", "en": "$empty"}
new_data[key][lan] = value
print(new_data)
localisation.document("languages").collection("text").document(page).update(new_data)
return "", 200
@app.post("/admin/loc/delete-field")
def delete_field():
use(0.01)
user = get_current_user()
if check_if_admin(user.username, user.password):
print(request.json)
data = request.json
from app_essentials.firebase import localisation
prev_data = localisation.document("languages").collection("text").document(data["page"]).get().to_dict()
print(prev_data)
new_data = prev_data
new_data.pop(data["key"])
print(new_data)
localisation.document("languages").collection("text").document(data["page"]).set(new_data)
return ""
@app.post("/admin/create/<bucket>")
def create_product(bucket):
use(0.01)
user = get_current_user()
if check_if_admin(user.username, user.password):
print(request.form)
if bucket == "productes":
from app_essentials.products import Product as P
elif bucket == "bespoke":
from app_essentials.products import Bespoke as P
elif bucket == "collecions":
from app_essentials.products import Collection as P
elif bucket == "imatges":
from app_essentials.products import StaticImage as P
else:
return "Unknown bucket", 500
new = P({"nom": request.form["name"]}, request.form["id"])
new.update_db()
return redirect("/admin/{}/".format(bucket))
@app.post("/admin/update/<bucket>")
def update_product(bucket):
use(0.01)
user = get_current_user()
if check_if_admin(user.username, user.password):
try:
print(request.json)
data = request.json.copy()
dry = False
if "dry" in data.keys():
dry = data["dry"]
if bucket == "productes":
from app_essentials.firebase import prods
from app_essentials.products import Product
prev_data = prods.document(data["product"]).get().to_dict()
p = Product(prev_data, data["product"])
elif bucket == "bespoke":
from app_essentials.firebase import bespoke
from app_essentials.products import Bespoke
prev_data = bespoke.document(data["product"]).get().to_dict()
p = Bespoke(prev_data, data["product"])
elif bucket == "collecions":
from app_essentials.firebase import collections
from app_essentials.products import Collection
prev_data = collections.document(data["product"]).get().to_dict()
p = Collection(prev_data, data["product"])
elif bucket == "imatges":
from app_essentials.firebase import images
from app_essentials.products import StaticImage
prev_data = images.document(data["product"]).get().to_dict()
p = StaticImage(prev_data, data["product"])
else:
print("Unknown bucket: ", bucket)
return "Unknown bucket", 500
if ":" in data["type"]:
target_type = data["type"].split(":")[0]
data_type = data["type"].split(":")[1]
else:
target_type = None
data_type = data["type"]
print("Type:", target_type, target_type)
if "value" not in data.keys():
value = None
else:
value = data["value"]
if data_type == "dict":
if value is None:
value = {}
else: