-
Notifications
You must be signed in to change notification settings - Fork 21
/
axismundi.py
executable file
·1763 lines (1620 loc) · 80.5 KB
/
axismundi.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
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
#!/usr/bin/env python
import Queue
import datetime
import hashlib
import json
import multiprocessing.forking
import os
import random
import string
import webbrowser
from collections import defaultdict
from flask import Flask, render_template, request, redirect, url_for, session, flash, g, make_response
from flask_login import LoginManager, UserMixin, login_user, current_user, logout_user, login_required
from multiprocessing import Process, freeze_support
from os import makedirs, sys, unsetenv, putenv, sep
from os.path import expanduser, isfile, isdir, dirname
from platform import system as get_os
from time import sleep
import axismundi_client.pydenticon
from axismundi_client.storage import Storage, SqlalchemyOrmPage, memory_cache
from axismundi_client.client_backend import messaging_loop
from axismundi_client.constants import *
from axismundi_client.defaults import create_defaults
from axismundi_client.utilities import queue_task, encode_image, generate_seed, get_age, resource_path, os_is_tails, find_gpg
from axismundi_client.btc_utils import is_btc_address
app = Flask(__name__)
# (8Mb maximum upload to local webserver) - make sure we dont need to use the disk
app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024
#app.config['SESSION_COOKIE_DOMAIN'] = 'xxxxxxxx.onion'
looking_glass = False
messageQueue = Queue.Queue() # work Queue for mqtt client thread
messageQueue_res = Queue.Queue() # Results Queue for mqtt client thread
# Profile and Listing Results Queue for mqtt client thread
login_manager = LoginManager()
login_manager.login_view = "login"
login_manager.init_app(app)
pager_items = 12 # default of 12 items per page when paginating
class User(UserMixin):
def __init__(self, id):
self.id = id
@classmethod
def get(self_class, id):
try:
return self_class(id)
except:
return None # This should not happen
@login_manager.user_loader
def load_user(userid):
return User.get(userid)
########## CSRF protection ###############################
@app.before_request
def csrf_protect():
if request.method == "POST":
token = session.pop('_csrf_token', None)
if not token or token != request.form.get('_csrf_token'):
flash('Invalid CSRF token, please try again.', category="error")
# FIXME: This is not doing what it should
redirect(request.endpoint, 302)
def generate_csrf_token():
if '_csrf_token' not in session:
session['_csrf_token'] = ''.join(random.SystemRandom().choice(
string.ascii_uppercase + string.digits) for _ in range(16))
return session['_csrf_token']
######## STATUS, PAGE GLOBALS AND UPDATES ################################
@app.before_request
def looking_glass_session(): # this session cookie will be used for looking glass mode
if session.get('lg') == '':
session['lg']= ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(16))
print "Info: Setting new sessionid..."
@app.before_request
# return a dict with the current exchange rates
def get_btc_x(): # TODO: Move this somewhere where it doesnt run on every request - for now check db no more than once every 60 secs
if app.SetupDone:
if get_age(app.btc_x_rates['updated']) > 60:
btc_x=dict()
try:
dbsession = app.roStorageDB.DBSession()
except:
return
currency_res = dbsession.query(app.roStorageDB.currencies).all()
for currency in currency_res:
rate = round(float(currency.exchange_rate),2)
code = currency.code
btc_x[code]=rate
btc_x['updated']=datetime.datetime.utcnow()
app.btc_x_rates = btc_x
g.btc_x = app.btc_x_rates
@app.before_request
def get_connection_status():
checkEvents()
g.connection_status = app.connection_status
# If we are running in Looking Glass mode then check the backend is running - if not redirect to login screen (for now)
if app.looking_glass and app.SetupDone:
try:
x= app.roStorageDB.DBSession()
except:
return login()
@app.after_request
def add_header(response):
#response.cache_control.max_age = 0
if app.looking_glass:
return response
if not str(request).find('main.css'): # ok to cache the CSS - disable this for slightly enhanced deniability
response.headers[
'Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
return response
######### JINJA FILTERS ##################################
@app.context_processor
def inject_mykey():
return dict(mykey=app.pgp_keyid)
@app.context_processor
def inject_current_broker():
return dict(current_broker=app.current_broker)
@app.context_processor
def inject_is_online():
return dict(online = app.connection_status)
@app.context_processor
def inject_looking_glass():
return dict(looking_glass=app.looking_glass)
@app.template_filter('from_json')
def from_json(value):
return (json.loads(value))
@app.template_filter('display_name')
# take a pgp keyid and return the displayname alongside the pgp key and any flags
def display_name(value):
if value == '':
return
dbsession = app.memory_cache.DBSession()
filter = value
dname = dbsession.query(app.memory_cache.cacheFullDirectory).filter_by(key_id=filter).first()
# print dname.__dict__
return (dname.display_name) # TODO - check the contacts list and also add status flags/verfication/trust status
@app.template_filter('key_to_feedback_label')
# take a pgp keyid and return a feedback label html block
def key_to_feedback_label(value):
if value == '':
return
dbsession = app.memory_cache.DBSession()
filter = value
# feedback = dbsession.query(app.roStorageDB.cacheDirectory).filter_by(key_id=filter).first()# TODO - aggregate feedback from UPLs
# TODO query UPL filtering on keyid and listtype=notary (or do this as part of the directry cache creation which may be more efficient)
dname = dbsession.query(app.memory_cache.cacheFullDirectory).filter_by(key_id=filter).first()
########
rating = "N"
txcount = "A"
color = "gray"
return (rating,txcount,color) # shitty tuple - lazy '
@app.template_filter('key_to_identicon')
# take a pgp keyid and return an identicon PNG
def key_to_identicon(value,size=20):
if value == '':
return
else:
size = int(size)
foreground = [ "rgb(45,79,255)",
"rgb(254,180,44)",
"rgb(226,121,234)",
"rgb(30,179,253)",
"rgb(232,77,65)",
"rgb(49,203,115)",
"rgb(141,69,170)"]
background = "rgba(255,255,255,0)"
generator = axismundi_client.pydenticon.Generator(5, 5, digest=hashlib.sha256, foreground=foreground, background=background, )
identicon_png = generator.generate(value, size, size, output_format="png")
image=encode_image(identicon_png,(size,size))
return (image)
@app.template_filter('to_btc')
# convert a given amount in a given currency to btc
def to_btc(value,currency_code):
dbsession = app.roStorageDB.DBSession()
currency_rec = dbsession.query(app.roStorageDB.currencies).filter_by(code=currency_code).first()
rate = currency_rec.exchange_rate
btc_val = str(round(float(value) / float(rate),5))
return (btc_val) # c
########## Flask Routes ##################################
#@app.route('/')
@login_required
def home():
cachedbsession = app.memory_cache.DBSession()
directory_entry = cachedbsession.query(app.memory_cache.cacheFullDirectory).filter(app.memory_cache.cacheFullDirectory.key_id == app.pgp_keyid).first()
dbsession = app.roStorageDB.DBSession()
unpaid_count = dbsession.query(app.roStorageDB.Orders).filter_by(buyer_key=app.pgp_keyid).filter_by(payment_status='unpaid').count()
unread_count = dbsession.query(app.roStorageDB.PrivateMessaging).filter_by(recipient_key=app.pgp_keyid).filter_by(message_read=False).filter_by(message_sent=False).count()
unprocessed_orders_count = dbsession.query(app.roStorageDB.Orders).filter_by(seller_key=app.pgp_keyid).filter_by(order_status='submitted').count()
unshipped_orders_count = dbsession.query(app.roStorageDB.Orders).filter_by(seller_key=app.pgp_keyid).filter_by(order_status='processing').count()
checkEvents()
return render_template('home.html',entry=directory_entry, unpaid_orders=unpaid_count, unread_messages=unread_count,unprocessed_orders=unprocessed_orders_count,unshipped_orders=unshipped_orders_count)
def lg_home():
checkEvents()
return render_template('looking_glass/home.html')
@app.route('/orders', methods=["GET", "POST"])
@app.route('/orders/<int:page>')
@app.route('/orders/<string:view_type>')
@app.route('/orders/<string:view_type>/<int:page>')
@login_required
def orders(view_type='buying', page=1):
checkEvents()
dbsession = app.roStorageDB.DBSession()
page_results = None
if request.method == "POST":
# User is updating the order
id = request.form.get('id')
seller_key = request.form.get('seller_key')
action = request.form.get('action')
if action == 'mark_paid':
print "Info: Front end marking as paid"
cmd_data = {"id": id,"command":"order_mark_paid", "sessionid": session.get('lg','')}
task = queue_task(1, 'update_order', cmd_data)
messageQueue.put(task)
sleep(0.2)
if action == 'order_shipped':
print "Info: Front end marking as shipped"
cmd_data = {"id": id,"command":"order_shipped", "sessionid": session.get('lg','')}
task = queue_task(1, 'update_order', cmd_data)
messageQueue.put(task)
sleep(0.2)
if action == 'order_finalize':
print "Info: Front end marking as finalized"
cmd_data = {"id": id,"command":"order_finalize", "sessionid": session.get('lg','')}
task = queue_task(1, 'update_order', cmd_data)
messageQueue.put(task)
sleep(0.2)
checkEvents()
redirect('/orders/view/' + id)
if view_type == 'buying':
orders_buying = dbsession.query(app.roStorageDB.Orders).filter_by(buyer_key=app.pgp_keyid).order_by(
app.roStorageDB.Orders.order_date.desc())
page_results = SqlalchemyOrmPage(
orders_buying, page=page, items_per_page=pager_items)
return render_template('orders.html', orders=page_results, view=view_type)
elif view_type == 'selling':
orders_selling = dbsession.query(app.roStorageDB.Orders).filter_by(seller_key=app.pgp_keyid).order_by(
app.roStorageDB.Orders.order_date.desc())
page_results = SqlalchemyOrmPage(
orders_selling, page=page, items_per_page=pager_items)
return render_template('orders.html', orders=page_results, view=view_type)
elif view_type == 'view':
order = dbsession.query(app.roStorageDB.Orders).filter_by(id=page).first()
return render_template('order.html', order=order)
@app.route
@app.route('/listings/publish')
@login_required
def publish_listings():
if app.workoffline:
return redirect(url_for('listings'))
task = queue_task(1, 'publish_listings', app.pgp_keyid)
messageQueue.put(task)
return redirect(url_for('listings'))
@app.route
@app.route('/listings/export')
@login_required
def export_listings():
task = queue_task(1, 'export_listings', app.pgp_keyid)
messageQueue.put(task)
return redirect(url_for('listings'))
@app.route('/listings/view', methods=["GET", "POST"])
@app.route('/listings/view/<string:keyid>')
@app.route('/listings/view/<string:keyid>/<string:id>')
#@login_required
def external_listings(keyid='none', id='none'):
if not current_user.is_authenticated and not app.looking_glass:
return app.login_manager.unauthorized()
#todo remove listingscache (completely) and just work with itemcache
# View another users listings or listing
dbsession = app.roStorageDB.DBSession()
if keyid=='none':
# return all listings held in the cache (regardless of age) - used for looking_glass mostly
if request.method == 'POST':
filter = request.form['search_item']
if filter:
listings_data = dbsession.query(app.roStorageDB.cacheItems).filter(app.roStorageDB.cacheItems.title.like("%"+filter+"%")).order_by(
app.roStorageDB.cacheItems.title.asc())
else:
listings_data = dbsession.query(app.roStorageDB.cacheItems).order_by(app.roStorageDB.cacheItems.title.asc())
else:
listings_data = dbsession.query(app.roStorageDB.cacheItems).order_by(app.roStorageDB.cacheItems.title.asc())
if not listings_data:
return render_template('no_listing.html')
else:
return render_template('listings.html', listings=listings_data, pgp_key='')
if id == 'none':
# This is a request for a users listings (all items)
listings_cache = dbsession.query(app.roStorageDB.cacheListings).filter_by(key_id=keyid).first()
if not listings_cache:
if not request.args.get('wait'):
# We don't have anythng in the cache, make a request
cmd_data = {"keyid": keyid, "id": id}
task = queue_task(1, 'get_listings', cmd_data)
messageQueue.put(task)
timer = 0
return redirect('/listings/view/'+keyid+'?wait='+str(timer),302)
else:
timer=int(request.args.get('wait')) + 1
if timer > 20:
resp = make_response("Listings request timed out", 200)
return resp
else:
url=str(request).split()[1].strip("'")
url=url.rsplit('?')[0]
url = url + '?wait='+str(timer)
return render_template('wait.html',url=url) # return waiting page
else:
# There is a listings entry already in the cache - is it ok?
age = get_age(listings_cache.updated)
if age > CACHE_EXPIRY_LIMIT:
# Expired cached entry found
if app.workoffline:
flash('Cached listings for this seller have expired, you should go online to get the latest listings.',category='message')
else:
cmd_data = {"keyid": keyid, "id": id}
task = queue_task(1, 'get_listings', cmd_data)
messageQueue.put(task)
flash('Cached listings for this seller have expired, the latest listings have been requested in the background. Refresh the page.', category='message')
# Even if listings are expired then show the items
if request.args.get('wait'):
return redirect('/listings/view/' + keyid) # Extra redirect to remove the ?wait=x from the URL
listings_data = dbsession.query(app.roStorageDB.cacheItems).filter_by(key_id=keyid).all()
if not listings_data:
return render_template('no_listing.html')
else:
return render_template('listings.html', listings=listings_data, pgp_key=keyid)
else:
# This is a request for a single item
item_cache = dbsession.query(app.roStorageDB.cacheItems).filter_by(key_id=keyid).filter_by(id=id).first()
if not item_cache:
if not request.args.get('wait'):
# We don't have anythng in the cache, make a request
cmd_data = {"keyid": keyid, "id": id}
task = queue_task(1, 'get_listings', cmd_data)
messageQueue.put(task)
timer = 0
return redirect('/listings/view/'+keyid+'/'+id+'?wait='+str(timer),302)
else:
timer=int(request.args.get('wait')) + 1
if timer > 20:
resp = make_response("Listings request timed out", 200)
return resp
else:
url=str(request).split()[1].strip("'")
url=url.rsplit('?')[0]
url = url + '?wait='+str(timer)
return render_template('wait.html',url=url) # return waiting page
else:
# There are items already in the cache - is it ok?
age = get_age(item_cache.updated)
if age > CACHE_EXPIRY_LIMIT:
# Expired cached entry found
if app.workoffline:
flash('Cached listings for this seller have expired, you should go online to get the latest listings.',category='message')
else:
cmd_data = {"keyid": keyid, "id": id}
task = queue_task(1, 'get_listings', cmd_data)
messageQueue.put(task)
flash('Cached listings for this seller have expired, the latest listings have been requested in the background. Refresh the page.', category='message')
# Even if listings are expired then show the item
if request.args.get('wait'):
return redirect('/listings/view/' + keyid + '/' + id) # Extra redirect to remove the ?wait=x from the URL
return render_template('listing.html', item=item_cache, pgp_key=keyid)
@app.route('/cart', methods=["GET", "POST"])
#@login_required
def cart(action=''):
if not current_user.is_authenticated and not app.looking_glass:
return app.login_manager.unauthorized()
# todo check items from same seller are in same currency or deal with it
dbsession = app.roStorageDB.DBSession()
cart_items = dbsession.query(app.roStorageDB.Cart).order_by(
app.roStorageDB.Cart.seller_key_id.asc())
if request.method == 'POST':
action = request.form['action']
if action == 'add':
# New item in cart - add it to database along with default quantity & shipping options unless
# quantuty and shipping were selected on the listings page TODO add
# qty and shipping to listing page
seller_key = request.form['pgpkey_id']
item_id = request.form['listing_id']
new_item = {"key_id": seller_key, "item_id": item_id, "sessionid": session.get('lg','')}
task = queue_task(1, 'add_to_cart', new_item)
# todo - do this from bakend so that item naem can be included
flash("Item added to cart", category="message")
elif action == 'remove':
# delete sellers items from cart - remove them from database
print "Info: Front end requesting to delete sellers items from cart"
seller_key = request.form['pgpkey_id']
del_seller = {"key_id": seller_key, "sessionid": session.get('lg','')}
task = queue_task(1, 'remove_from_cart', del_seller)
elif action == 'update':
# User is updating something in the cart - find out what and then update db
# possible changes are Quantity or shipping
seller_key = request.form['pgpkey_id']
# Loop through each item in the cart and recover form values
seller_cart_items = dbsession.query(app.roStorageDB.Cart).filter_by(seller_key_id = seller_key)
cart_item_list = {}
for seller_cart_item in seller_cart_items:
item_id = seller_cart_item.item_id
cart_item_list[item_id]=(request.form['quantity_' + item_id],request.form['shipping_' + item_id])
cart_updates = {"key_id": seller_key, "items": cart_item_list, "sessionid": session.get('lg','')}
task = queue_task(1, 'update_cart', cart_updates)
elif str(action).startswith("checkout|"):
# user is checking out their cart from a single seller
seller_key = request.form['pgpkey_id']
transaction_type = str(action).split('|')[1]
#transaction_type = request.form['data-value'] # TODO: check selected transaction type is allowed for each cart item
print "Info: User is checking out from a cart from seller " + seller_key + " with a transaction type of " + transaction_type
seller_cart_items = dbsession.query(app.roStorageDB.Cart).filter_by(seller_key_id = seller_key)
cart_item_list = {}
for seller_cart_item in seller_cart_items:
item_id = seller_cart_item.item_id
cart_item_list[item_id]=(request.form['quantity_' + item_id],request.form['shipping_' + item_id])
cart_checkout = {"key_id": seller_key, "transaction_type": transaction_type, "items": cart_item_list, "sessionid": session.get('lg','')}
task = queue_task(1, 'checkout', cart_checkout)
# return redirect(url_for('checkout'))
# TODO : find a better way to do this
messageQueue.put(task)
checkEvents()
sleep(0.5)
cart_items = dbsession.query(app.roStorageDB.Cart).filter_by(seller_key_id = seller_key)
checkEvents()
return render_template('checkout.html', cart_items=cart_items, seller_key=seller_key)
elif action == "create_order":
seller_key = request.form['pgpkey_id']
buyer_address = request.form['address']
buyer_note = request.form['note']
order_details = {"key_id": seller_key, "buyer_address": buyer_address, "buyer_note": buyer_note, "sessionid": session.get('lg','')}
task = queue_task(1, 'create_order', order_details)
messageQueue.put(task)
# order is submitted to backend - order must be built, wallet addresses generated, order message created, order committed to db
# TODO - when in looking glass mode ensure that a lack of lg/session cookie does not result in all placed orders displayed
orders = dbsession.query(app.roStorageDB.Orders).filter_by(session_id=session.get('lg','')).filter_by(seller_key=seller_key).order_by(app.roStorageDB.Orders.order_status.asc())
if orders:
sleep(0.5)
# This query includes the lg sessionid because evem if lg is not enabled, it is necessary to track the user move from cart to order
orders = dbsession.query(app.roStorageDB.Orders).filter_by(session_id=session.get('lg','')).filter_by(seller_key=seller_key).order_by(app.roStorageDB.Orders.order_status.asc()) # one or more ordered items
else:
print "Info: Order not yet ready...waiting..."
return render_template('ordered.html', order=orders, seller_key=seller_key)
# Now send the relevant cart_update message to backend and await
# response - then return page
messageQueue.put(task)
sleep(0.25)
return redirect(url_for('cart'))
checkEvents()
return render_template('cart.html',cart_items=cart_items)
@app.route('/wait', methods=["GET", "POST"])
@login_required
def wait():
make_response()
return render_template('wait.html')
@app.route('/not_yet', methods=["GET", "POST"])
@login_required
def not_yet():
return render_template('not_yet.html')
@app.route('/directory', methods=["GET", "POST"])
@app.route('/directory/<int:page>',methods=["GET", "POST"])
#@login_required
def directory(page=1,filter=''):
if not current_user.is_authenticated and not app.looking_glass:
return app.login_manager.unauthorized()
filter_sellers = False
filter_active=False
dbsession = app.memory_cache.DBSession()
if request.method == "POST":
filter = request.form['search_name']
if filter:
directory = dbsession.query(app.memory_cache.cacheFullDirectory).filter(app.memory_cache.cacheFullDirectory.display_name.like("%"+filter+"%")).order_by(
app.memory_cache.cacheFullDirectory.display_name.asc())
pass
else:
directory = dbsession.query(app.memory_cache.cacheFullDirectory).order_by(
app.memory_cache.cacheFullDirectory.display_name.asc())
try:
filter_sellers = bool(request.form['filter_sellers'])
directory = directory.filter(app.memory_cache.cacheFullDirectory.is_seller==True)
except:
pass
try:
filter_active = bool(request.form['filter_active'])
directory = directory.filter(app.memory_cache.cacheFullDirectory.is_active_user==True)
except:
pass
page_results = SqlalchemyOrmPage(directory, page=page, items_per_page=pager_items * 2)
checkEvents()
return render_template('directory.html', directory=page_results,search_filter=filter,filter_sellers=filter_sellers,filter_active=filter_active)
@app.route('/listings')
@app.route('/listings/<int:page>')
@login_required
def listings(page=1):
checkEvents()
dbsession = app.roStorageDB.DBSession()
listings = dbsession.query(app.roStorageDB.Listings)
page_results = SqlalchemyOrmPage(
listings, page=page, items_per_page=pager_items)
return render_template('mylistings.html', listings=page_results)
@app.route('/lists', methods=["GET", "POST"])
@app.route('/lists/<int:page>')
@login_required
def upl(page=1):
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
type = request.form['type']
list_details = {"name": name, "description": description, "type": type}
task = queue_task(1, 'create_list', list_details)
messageQueue.put(task)
dbsession = app.roStorageDB.DBSession()
my_lists = dbsession.query(app.roStorageDB.UPL_lists).filter_by(author_key_id=app.pgp_keyid)
subscribed_lists = dbsession.query(app.roStorageDB.UPL_lists).filter(app.roStorageDB.UPL_lists.author_key_id != app.pgp_keyid)
checkEvents()
if subscribed_lists:
page_results = SqlalchemyOrmPage(
subscribed_lists, page=page, items_per_page=pager_items)
return render_template('lists.html', my_lists=my_lists, subscribed_lists=page_results)
else:
return render_template('lists.html', my_lists=my_lists, subscribed_lists=subscribed_lists)
@app.route('/lists/user/<string:key>/<int:id>', methods=["GET", "POST"])
@app.route('/lists/user/<string:key>/<int:id>/<int:page>')
@login_required
def upl_detail(key='',id=0,page=1):
if request.method == 'POST':
pass
dbsession = app.roStorageDB.DBSession()
list_info = dbsession.query(app.roStorageDB.UPL_lists).filter_by(author_key_id=key,id=id).first()
if list_info:
list_rows = dbsession.query(app.roStorageDB.UPL).filter_by(upl_list=id)
else:
list_rows = False
checkEvents()
if list_rows:
page_results = SqlalchemyOrmPage(
list_rows, page=page, items_per_page=pager_items)
return render_template('list.html', list_info=list_info, list_rows=page_results)
else:
return render_template('list.html', list_info=list_info, list_rows=list_rows)
@app.route('/profile/')
@app.route('/profile/<string:keyid>')
#@login_required
def profile(keyid=None):
if not current_user.is_authenticated and not app.looking_glass:
return app.login_manager.unauthorized()
# TODO:Check to see if this user is in our contacts list
# TODO:Message to client_backend to SUB target user profile and target
# user listings
if keyid is None:
keyid = app.pgp_keyid # if no key specified by user then look up our own profile
# task = queue_task(1,'get_profile',keyid)
# messageQueue.put(task)
# for now wait for the response for up to [timeout] seconds
dbsession = app.roStorageDB.DBSession()
profile = dbsession.query(app.roStorageDB.cacheProfiles).filter_by(
key_id=keyid).first()
checkEvents()
if not profile: # no existing profile found in cache, request it
if not request.args.get('wait'):
timer = 0
key = {"keyid": keyid}
task = queue_task(1, 'get_profile', key)
messageQueue.put(task)
return redirect('/profile/'+keyid+'?wait='+str(timer),302)
else:
timer=int(request.args.get('wait')) + 1
if timer > 20:
resp = make_response("Warning: Profile not found", 200)
return resp
else:
url=str(request).split()[1].strip("'")
url=url.rsplit('?')[0]
url = url + '?wait='+str(timer)
return render_template('wait.html',url=url) # return waiting page
else: # we have returned an existing profile from the cache
print "Info: Existing entry found in profile cache..."
# how old is the cached data
age = get_age(profile.updated)
if age > CACHE_EXPIRY_LIMIT:
print 'Info: Cached profile is too old, requesting latest copy'
key = {"keyid": keyid}
task = queue_task(1, 'get_profile', key)
messageQueue.put(task)
flash("Cached profile has expired, the latest profile has been requested in the background. Refresh the page.", category="message")
if request.args.get('wait'):
return redirect('/profile/' + keyid) # Extra redirect to remove the ?wait=x from the URL
cachedbsession = app.memory_cache.DBSession()
directory_entry = cachedbsession.query(app.memory_cache.cacheFullDirectory).filter(app.memory_cache.cacheFullDirectory.key_id == keyid).first()
# TODO make sure is_notary and is_arbiter are derived from the (signed) profile and not from the (unsigned) directory entry
if app.looking_glass:
listings_data = dbsession.query(app.roStorageDB.cacheItems).filter_by(key_id=keyid).all()
return render_template('profile.html', profile=profile,listings=listings_data,entry=directory_entry) # pass list of seller items if any in looking glass mode
else:
return render_template('profile.html', profile=profile, entry=directory_entry)
@app.route('/contacts')
@app.route('/contacts/<int:page>')
@login_required
def contacts(page=1):
checkEvents()
dbsession = app.roStorageDB.DBSession()
contacts = dbsession.query(app.roStorageDB.Contacts)
page_results = SqlalchemyOrmPage(
contacts, page=page, items_per_page=pager_items)
return render_template('contacts.html', contacts=page_results)
@app.route('/contacts/new/', methods=["GET", "POST"])
@login_required
def new_contact(contact_pgpkey=""):
checkEvents()
if request.method == "POST":
# TODO: Validate these inputs
# TODO: Don't store pgpkeyblock in contact, just store id and store
# keyblock in the pgpkeycache table
name = request.form['name']
pgpkey = request.form['pgpkey_block']
contact_pgpkey = request.form['pgpkey_id']
if contact_pgpkey: # We are adding by pgp key id
contact = {"displayname": "" + name + "", "pgpkeyid": "" +
contact_pgpkey + "", "pgpkey": ""} # TODO: add flags
print contact
else: # We are adding by pgp key block
contact = {"displayname": "" + name + "", "pgpkey": "" +
pgpkey + "", "pgpkeyid": ""} # TODO: add flags
task = queue_task(1, 'new_contact', contact)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on
# the next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough
# to get the queue response back
checkEvents()
app.memory_cache.rebuild() # TODO - we don't need to do a full rebuild necessarily
return redirect(url_for('contacts'))
else:
dbsession = app.roStorageDB.DBSession()
contacts = dbsession.query(app.roStorageDB.Contacts).all()
return render_template('contact-new.html', contacts=contacts, contact_pgpkey=contact_pgpkey)
@app.route('/messages')
@app.route('/messages/<int:page>')
@login_required
def messages(page=1):
checkEvents()
dbsession = app.roStorageDB.DBSession()
# inbox_messages = dbsession.query(app.roStorageDB.PrivateMessaging).filter_by(recipient_key=app.pgp_keyid,message_direction="In").order_by(
# app.roStorageDB.PrivateMessaging.message_date.asc())
inbox_messages = dbsession.query(app.roStorageDB.PrivateMessaging).filter_by(recipient_key=app.pgp_keyid, message_direction="In").order_by(
app.roStorageDB.PrivateMessaging.message_date.asc())
page_results = SqlalchemyOrmPage(
inbox_messages, page=page, items_per_page=pager_items)
# inbox_messages)
return render_template('messages.html', inbox_messages=page_results)
@app.route('/messages/sent')
@app.route('/messages/sent/<int:page>')
@login_required
def messages_sent(page=1):
checkEvents()
dbsession = app.roStorageDB.DBSession()
sent_messages = dbsession.query(app.roStorageDB.PrivateMessaging).filter_by(sender_key=app.pgp_keyid, message_direction="Out").order_by(
app.roStorageDB.PrivateMessaging.message_date.asc())
page_results = SqlalchemyOrmPage(
sent_messages, page=page, items_per_page=pager_items)
return render_template('messages-sent.html', sent_messages=page_results)
@app.route('/messages/view/<string:id>/',)
@login_required
def view_message(id):
dbsession = app.roStorageDB.DBSession()
message = dbsession.query(
app.roStorageDB.PrivateMessaging).filter_by(id=id).one()
data = {"id": id}
task = queue_task(1, 'read_pm', data) # mark as read in the database
messageQueue.put(task)
return render_template('message.html', message=message)
@app.route('/messages/reply/<string:id>/', methods=["GET", "POST"])
@login_required
def reply_message(id):
checkEvents()
if request.method == "POST":
# TODO: Validate these inputs
recipient = request.form['recipient']
subject = request.form['subject']
body = request.form['body']
sign_msg = request.form['sign-message']
message = {"recipient": recipient, "subject": subject, "body": body}
task = queue_task(1, 'send_pm', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on
# the next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough
# to get the queue response back
checkEvents()
return redirect(url_for('messages'))
else:
dbsession = app.roStorageDB.DBSession()
message = dbsession.query(
app.roStorageDB.PrivateMessaging).filter_by(id=id).one()
return render_template('message-reply.html', message=message)
@app.route('/listings/new/', methods=["GET", "POST"])
@login_required
def new_listing(id=0):
checkEvents()
if request.method == "POST":
# TODO: Validate these inputs
title = request.form['title']
description = request.form['description']
category = request.form['category']
print category
price = request.form['price']
currency_code = request.form['currency']
qty_available = request.form['quantity']
max_order = request.form['max_order']
if request.form.get('is_public') == 'True':
is_public = 'True'
else:
is_public = 'False'
if request.form.get('order_direct') == 'True':
order_direct = 'True'
else:
order_direct = 'False'
if request.form.get('order_escrow') == 'True':
order_escrow = 'True'
else:
order_escrow = 'False'
listing_image_file = request.files['listing_image']
if listing_image_file and listing_image_file.filename.rsplit('.', 1)[1] in {'png', 'jpg'}:
# TODO - maintain aspect ratio
image = str(encode_image(listing_image_file.read(), (128, 128)))
else:
image = ''
print "Checking shipping options..."
# Now shipping options
shipping = defaultdict()
for x in range(1, 4):
if request.form.get('shipping_enabled_' + str(x)) == 'True':
s_type = request.form.get('shipping_' + str(x))
s_cost = request.form.get('shipping_cost_' + str(x))
if s_type and s_cost:
# TODO additional sanity checks on shipping options
shipping[x] = (s_type, s_cost)
# crete message for backend
message = {"category": category, "title": title, "description": description, "price": price, "currency": currency_code, "image": image, "is_public": is_public,
"quantity": qty_available, "max_order": max_order, "order_direct": order_direct, "order_escrow": order_escrow, "shipping_options": json.dumps(shipping)}
print message
task = queue_task(1, 'new_listing', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on
# the next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough
# to get the queue response back
checkEvents()
return redirect(url_for('listings'))
else:
dbsession = app.roStorageDB.DBSession()
# dbsession.query(app.roStorageDB.Contacts).all() # TODO: Query list of
# categories currently known
categories = None
currencies = dbsession.query(app.roStorageDB.currencies).all()
return render_template('listing-new.html', categories=categories, currencies=currencies)
@app.route('/listings/edit/<int:id>', methods=["GET", "POST"])
@login_required
def edit_listing(id=0):
checkEvents()
if request.method == "POST":
# TODO: Validate these inputs
title = request.form['title']
description = request.form['description']
category = request.form['category']
price = request.form['price']
currency_code = request.form['currency']
qty_available = request.form['quantity']
max_order = request.form['max_order']
if request.form.get('is_public') == 'True':
is_public = 'True'
else:
is_public = 'False'
if request.form.get('order_direct') == 'True':
order_direct = 'True'
else:
order_direct = 'False'
if request.form.get('order_escrow') == 'True':
order_escrow = 'True'
else:
order_escrow = 'False'
listing_image_file = request.files['listing_image']
if listing_image_file and listing_image_file.filename.rsplit('.', 1)[1] in {'png', 'jpg'}:
# TODO - maintain aspect ratio
image = str(encode_image(listing_image_file.read(), (128, 128)))
else:
image = ''
print "Info: Checking shipping options..."
# Now shipping options
shipping = defaultdict()
for x in range(1, 4):
if request.form.get('shipping_enabled_' + str(x)) == 'True':
s_type = request.form.get('shipping_' + str(x))
s_cost = request.form.get('shipping_cost_' + str(x))
if s_type and s_cost:
# TODO additional sanity checks on shipping options
shipping[x] = (s_type, s_cost)
message = {"id": id, "category": category, "title": title, "description": description, "price": price, "currency": currency_code, "image": image, "is_public": is_public,
"quantity": qty_available, "max_order": max_order, "order_direct": order_direct, "order_escrow": order_escrow, "shipping_options": json.dumps(shipping)}
print "Info: Update Listing message: " + message.__str__()
task = queue_task(1, 'update_listing', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on
# the next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough
# to get the queue response back
checkEvents()
return redirect(url_for('listings'))
else:
dbsession = app.roStorageDB.DBSession()
# dbsession.query(app.roStorageDB.Contacts).all() # TODO: Query list of
# categories currently known
categories = None
currencies = dbsession.query(app.roStorageDB.currencies).all()
listing_item = dbsession.query(
app.roStorageDB.Listings).filter_by(id=id).first()
listing_shipping_options = json.loads(listing_item.shipping_options)
return render_template('listing-edit.html', categories=categories, currencies=currencies, listing=listing_item, shipping_options=listing_shipping_options)
@app.route('/listings/delete/<int:id>', methods=["GET"])
@login_required
def delete_listing(id=0):
message = {"id": str(id)}
task = queue_task(1, 'delete_listing', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on the
# next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough to
# get the queue response back
checkEvents()
return redirect(url_for('listings'))
@app.route('/messages/new/', methods=["GET", "POST"])
# TODO CSRF protection required
@app.route('/messages/new/<string:recipient_key>', methods=["GET", "POST"])
@login_required
def new_message(recipient_key=""):
checkEvents()
if request.method == "POST":
# TODO: Validate these inputs
recipient = str(request.form['recipient']).strip()
subject = request.form['subject']
body = request.form['body']
sign_msg = request.form['sign-message']
message = {"recipient": recipient, "subject": subject, "body": body}
task = queue_task(1, 'send_pm', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on
# the next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough
# to get the queue response back
checkEvents()
return redirect(url_for('messages'))
else:
dbsession = app.roStorageDB.DBSession()
contacts = dbsession.query(app.roStorageDB.Contacts).all()
return render_template('message-compose.html', contacts=contacts, recipient_key=recipient_key)
@app.route('/messages/delete/<string:id>/',) # TODO CSRF protection required
@login_required
def delete_message(id):
message = {"id": "" + id + ""}
task = queue_task(1, 'delete_pm', message)
messageQueue.put(task)
# it's better for the user to get a flashed message now rather than on the
# next page load so
sleep(0.1)
# we will wait for 0.1 seconds here because usually this is long enough to
# get the queue response back
checkEvents()
return redirect(url_for('messages'))
@app.route('/wallet', methods=['GET','POST'])
@app.route('/wallet/<int:page>', methods=['GET','POST'])
@login_required
# TODO- Implement a simplistic bitcoin wallet...
def wallet(page=1):
if request.method == "POST":
# get btc_destination
btc_destination = request.form['btc_destination']
# TODO : Allow user to select transaction addresses to include in the withdrawal - for now all transaction addresses will be emptied and paid to the user specified destination address
btc_sources = []
# TODO ; Check we have a valid BTC address
if not is_btc_address(btc_destination):
flash("You supplied an invalid withdrawal address - " + btc_destination, category="error")
else:
# Form message for backend
# TODO
# message = {"btc_sources": btc_sources} # list of source addresses
message = {"btc_destination": btc_destination, "btc_sources": btc_sources} # list of source addresses
task = queue_task(1, 'btc_withdrawal', message)
messageQueue.put(task)
flash("Withdrawing funds to " + btc_destination, category="message")
checkEvents()
dbsession = app.roStorageDB.DBSession()
addresses = dbsession.query(app.roStorageDB.Orders.payment_btc_address, app.roStorageDB.Orders.payment_btc_balance_confirmed, app.roStorageDB.Orders.payment_btc_balance_unconfirmed).filter((app.roStorageDB.Orders.payment_btc_balance_confirmed<>'0.0')|(app.roStorageDB.Orders.payment_btc_balance_unconfirmed<>'0.0'))
page_results = SqlalchemyOrmPage(
addresses, page=page, items_per_page=pager_items)
return render_template('wallet.html', btc_confirmed_funds=app.btc_confirmed_funds, btc_unconfirmed_funds=app.btc_unconfirmed_funds, addresses=page_results)
@app.route('/load-identity', methods=['POST'])
# load existing app data from a non-default location
def loadidentity():
if app.SetupDone:
return redirect(url_for('home'))
app.appdir = dirname(request.form['app_dir']) # strip off the file-name
print "Info: application directory is " + app.appdir
if isfile(app.appdir + "/secret") and isfile(app.appdir + "/storage.db"):
app.SetupDone = True # TODO: A better check is needed here
else:
flash("Could not load application data from " +
app.appdir, category="error")
return redirect(url_for('login'))
@app.route('/create-identity', methods=['POST'])
def createidentity(): # This is a bit of a mess, TODO: clean up
if app.SetupDone:
return redirect(url_for('home'))
app.pgp_keyid = request.form['keyid']
app.display_name = request.form['displayname']