This repository was archived by the owner on May 16, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathrestapi.py
809 lines (764 loc) · 36.8 KB
/
restapi.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
__author__ = 'chris'
import json
import os
from binascii import unhexlify
from collections import OrderedDict
from txrestapi.resource import APIResource
from txrestapi.methods import GET, POST, DELETE
from twisted.web import server
from twisted.web.resource import NoResource
from twisted.web import http
from twisted.internet import defer, reactor
from twisted.protocols.basic import FileSender
from constants import DATA_FOLDER
from protos.countries import CountryCode
from protos import objects
from keyutils.keys import KeyChain
from dht.utils import digest
from market.profile import Profile
from market.contracts import Contract
from net.upnp import PortMapper
import db.backuptool
DEFAULT_RECORDS_COUNT = 20
DEFAULT_RECORDS_OFFSET = 0
def str_to_bool(s):
if s.lower() == 'true':
return True
elif s.lower() == 'false':
return False
else:
raise ValueError
class OpenBazaarAPI(APIResource):
"""
This RESTful API allows clients to pull relevant data from the
OpenBazaar daemon for use in a GUI or other application.
"""
def __init__(self, mserver, kserver, protocol):
self.mserver = mserver
self.kserver = kserver
self.protocol = protocol
self.db = mserver.db
self.keychain = KeyChain(self.db)
APIResource.__init__(self)
@GET('^/api/v1/get_image')
def get_image(self, request):
@defer.inlineCallbacks
def _showImage(resp=None):
@defer.inlineCallbacks
def _setContentDispositionAndSend(file_path, extension, content_type):
request.setHeader('content-disposition', 'filename="%s.%s"' % (file_path, extension))
request.setHeader('content-type', content_type)
f = open(file_path, "rb")
yield FileSender().beginFileTransfer(f, request)
f.close()
defer.returnValue(0)
if os.path.exists(image_path):
yield _setContentDispositionAndSend(image_path, "jpg", "image/jpeg")
else:
request.setResponseCode(http.NOT_FOUND)
request.write("No such image '%s'" % request.path)
request.finish()
if "hash" in request.args and len(request.args["hash"][0]) == 40:
if self.db.HashMap().get_file(request.args["hash"][0]) is not None:
image_path = self.db.HashMap().get_file(request.args["hash"][0])
else:
image_path = DATA_FOLDER + "cache/" + request.args["hash"][0]
if not os.path.exists(image_path) and "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.get_image(node, unhexlify(request.args["hash"][0])).addCallback(_showImage)
else:
_showImage()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
_showImage()
else:
request.write(NoResource().render(request))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/profile')
def get_profile(self, request):
def parse_profile(profile):
if profile is not None:
mods = []
for mod in profile.moderator_list:
mods.append(mod.encode("hex"))
profile_json = {
"profile": {
"name": profile.name,
"location": str(CountryCode.Name(profile.location)),
"encryption_key": profile.encryption_key.public_key.encode("hex"),
"nsfw": profile.nsfw,
"vendor": profile.vendor,
"moderator": profile.moderator,
"moderator_list": mods,
"handle": profile.handle,
"about": profile.about,
"website": profile.website,
"email": profile.email,
"primary_color": profile.primary_color,
"secondary_color": profile.secondary_color,
"background_color": profile.background_color,
"text_color": profile.text_color,
"pgp_key": profile.pgp_key.public_key,
"avatar_hash": profile.avatar_hash.encode("hex"),
"header_hash": profile.header_hash.encode("hex"),
"social_accounts": {}
}
}
if "guid" in request.args:
profile_json["profile"]["guid"] = request.args["guid"][0]
else:
profile_json["profile"]["guid"] = self.keychain.guid.encode("hex")
for account in profile.social:
profile_json["profile"]["social_accounts"][str(
objects.Profile.SocialAccount.SocialType.Name(account.type)).lower()] = {
"username": account.username,
"proof_url": account.proof_url
}
request.setHeader('content-type', "application/json")
request.write(json.dumps(profile_json, indent=4))
request.finish()
else:
request.write(json.dumps({}))
request.finish()
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.get_profile(node).addCallback(parse_profile)
else:
request.write(json.dumps({}))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
parse_profile(Profile(self.db).get())
return server.NOT_DONE_YET
@GET('^/api/v1/get_listings')
def get_listings(self, request):
def parse_listings(listings):
if listings is not None:
response = {"listings": []}
for l in listings.listing:
listing_json = {
"title": l.title,
"contract_hash": l.contract_hash.encode("hex"),
"thumbnail_hash": l.thumbnail_hash.encode("hex"),
"category": l.category,
"price": l.price,
"currency_code": l.currency_code,
"nsfw": l.nsfw,
"origin": str(CountryCode.Name(l.origin)),
"ships_to": []
}
for country in l.ships_to:
listing_json["ships_to"].append(str(CountryCode.Name(country)))
response["listings"].append(listing_json)
request.setHeader('content-type', "application/json")
request.write(json.dumps(response, indent=4))
request.finish()
else:
request.write(json.dumps({}))
request.finish()
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.get_listings(node).addCallback(parse_listings)
else:
request.write(json.dumps({}))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
ser = self.db.ListingsStore().get_proto()
if ser is not None:
l = objects.Listings()
l.ParseFromString(ser)
parse_listings(l)
else:
parse_listings(None)
return server.NOT_DONE_YET
@GET('^/api/v1/get_followers')
def get_followers(self, request):
def parse_followers(followers):
if followers is not None:
response = {"followers": []}
for f in followers.followers:
follower_json = {
"guid": f.guid.encode("hex"),
"handle": f.metadata.handle,
"name": f.metadata.name,
"avatar_hash": f.metadata.avatar_hash.encode("hex"),
"nsfw": f.metadata.nsfw
}
response["followers"].append(follower_json)
request.setHeader('content-type', "application/json")
request.write(json.dumps(response, indent=4))
request.finish()
else:
request.write(json.dumps({}))
request.finish()
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.get_followers(node).addCallback(parse_followers)
else:
request.write(json.dumps({}))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
ser = self.db.FollowData().get_followers()
if ser is not None:
f = objects.Followers()
f.ParseFromString(ser)
parse_followers(f)
else:
parse_followers(None)
return server.NOT_DONE_YET
@GET('^/api/v1/get_following')
def get_following(self, request):
def parse_following(following):
if following is not None:
response = {"following": []}
for f in following.users:
user_json = {
"guid": f.guid.encode("hex"),
"handle": f.metadata.handle,
"name": f.metadata.name,
"avatar_hash": f.metadata.avatar_hash.encode("hex"),
"nsfw": f.metadata.nsfw
}
response["following"].append(user_json)
request.setHeader('content-type', "application/json")
request.write(json.dumps(response, indent=4))
request.finish()
else:
request.write(json.dumps({}))
request.finish()
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.get_following(node).addCallback(parse_following)
else:
request.write(json.dumps({}))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
ser = self.db.FollowData().get_following()
if ser is not None:
f = objects.Following()
f.ParseFromString(ser)
parse_following(f)
else:
parse_following(None)
return server.NOT_DONE_YET
@POST('^/api/v1/follow')
def follow(self, request):
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.follow(node)
request.write(json.dumps({"success": True}))
request.finish()
else:
request.write(json.dumps({"success": False, "reason": "could not resolve guid"}, indent=4))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
return server.NOT_DONE_YET
@POST('^/api/v1/unfollow')
def unfollow(self, request):
if "guid" in request.args:
def get_node(node):
if node is not None:
self.mserver.unfollow(node)
request.write(json.dumps({"success": True}))
request.finish()
else:
request.write(json.dumps({"success": False, "reason": "could not resolve guid"}, indent=4))
request.finish()
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
return server.NOT_DONE_YET
# pylint: disable=R0201
@POST('^/api/v1/profile')
def update_profile(self, request):
try:
p = Profile(self.db)
if not p.get().encryption_key \
and "name" not in request.args \
and "location" not in request.args:
request.write(json.dumps({"success": False, "reason": "name or location not included"}, indent=4))
request.finish()
return False
u = objects.Profile()
if "name" in request.args:
u.name = request.args["name"][0]
if "location" in request.args:
# This needs to be formatted. Either here or from the UI.
u.location = CountryCode.Value(request.args["location"][0].upper())
if "handle" in request.args:
u.handle = request.args["handle"][0]
if "about" in request.args:
u.about = request.args["about"][0]
if "short_description" in request.args:
u.short_description = request.args["short_description"][0]
if "nsfw" in request.args:
u.nsfw = str_to_bool(request.args["nsfw"][0])
if "vendor" in request.args:
u.vendor = str_to_bool(request.args["vendor"][0])
if "moderator" in request.args:
u.moderator = str_to_bool(request.args["moderator"][0])
if "moderator_list" in request.args:
p.get().ClearField("moderator_list")
for moderator in request.args["moderator_list"]:
u.moderator_list.append(unhexlify(moderator))
if "website" in request.args:
u.website = request.args["website"][0]
if "email" in request.args:
u.email = request.args["email"][0]
if "primary_color" in request.args:
u.primary_color = int(request.args["primary_color"][0])
if "secondary_color" in request.args:
u.secondary_color = int(request.args["secondary_color"][0])
if "background_color" in request.args:
u.background_color = int(request.args["background_color"][0])
if "text_color" in request.args:
u.text_color = int(request.args["text_color"][0])
if "avatar" in request.args:
u.avatar_hash = unhexlify(request.args["avatar"][0])
if "header" in request.args:
u.header_hash = unhexlify(request.args["header"][0])
if "pgp_key" in request.args and "signature" in request.args:
p.add_pgp_key(request.args["pgp_key"][0], request.args["signature"][0],
self.keychain.guid.encode("hex"))
enc = u.PublicKey()
enc.public_key = self.keychain.encryption_pubkey
enc.signature = self.keychain.signing_key.sign(enc.public_key)[:64]
u.encryption_key.MergeFrom(enc)
p.update(u)
request.write(json.dumps({"success": True}))
request.finish()
self.kserver.node.vendor = p.get().vendor
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/social_accounts')
def add_social_account(self, request):
try:
p = Profile(self.db)
if "account_type" in request.args and "username" in request.args and "proof" in request.args:
p.add_social_account(request.args["account_type"][0], request.args["username"][0],
request.args["proof"][0] if "proof" in request.args else None)
else:
raise Exception("Missing required fields")
request.write(json.dumps({"success": True}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@DELETE('^/api/v1/social_accounts')
def delete_social_account(self, request):
try:
p = Profile(self.db)
if "account_type" in request.args:
p.remove_social_account(request.args["account_type"][0])
request.write(json.dumps({"success": True}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/contracts')
def get_contract(self, request):
def parse_contract(contract):
if contract is not None:
request.setHeader('content-type', "application/json")
request.write(json.dumps(contract, indent=4))
request.finish()
else:
request.write(json.dumps({}))
request.finish()
if "id" in request.args and len(request.args["id"][0]) == 40:
if "guid" in request.args and len(request.args["guid"][0]) == 40:
def get_node(node):
if node is not None:
self.mserver.get_contract(node, unhexlify(request.args["id"][0]))\
.addCallback(parse_contract)
else:
request.write(json.dumps({}))
request.finish()
try:
with open(DATA_FOLDER + "cache/" + request.args["id"][0], "r") as filename:
contract = json.loads(filename.read(), object_pairs_hook=OrderedDict)
parse_contract(contract)
except Exception:
self.kserver.resolve(unhexlify(request.args["guid"][0])).addCallback(get_node)
else:
try:
with open(self.db.HashMap().get_file(request.args["id"][0]), "r") as filename:
contract = json.loads(filename.read(), object_pairs_hook=OrderedDict)
parse_contract(contract)
except Exception:
parse_contract(None)
else:
request.write(json.dumps({}))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/contracts')
def set_contract(self, request):
try:
if "options" in request.args:
options = {}
for option in request.args["options"]:
options[option] = request.args[option]
c = Contract(self.db)
c.create(
str(request.args["expiration_date"][0]),
request.args["metadata_category"][0],
request.args["title"][0],
request.args["description"][0],
request.args["currency_code"][0],
request.args["price"][0],
request.args["process_time"][0],
str_to_bool(request.args["nsfw"][0]),
shipping_origin=request.args["shipping_origin"][0] if "shipping_origin" in request.args else None,
shipping_regions=request.args["ships_to"] if "ships_to" in request.args else None,
est_delivery_domestic=request.args["est_delivery_domestic"][0]
if "est_delivery_domestic" in request.args else None,
est_delivery_international=request.args["est_delivery_international"][0]
if "est_delivery_international" in request.args else None,
terms_conditions=request.args["terms_conditions"][0]
if request.args["terms_conditions"][0] is not "" else None,
returns=request.args["returns"][0] if request.args["returns"][0] is not "" else None,
shipping_currency_code=request.args["shipping_currency_code"][0],
shipping_domestic=request.args["shipping_domestic"][0],
shipping_international=request.args["shipping_international"][0],
keywords=request.args["keywords"] if "keywords" in request.args else None,
category=request.args["category"][0] if request.args["category"][0] is not "" else None,
condition=request.args["condition"][0] if request.args["condition"][0] is not "" else None,
sku=request.args["sku"][0] if request.args["sku"][0] is not "" else None,
images=request.args["images"],
free_shipping=str_to_bool(request.args["free_shipping"][0]),
options=options if "options" in request.args else None,
moderators=request.args["moderators"] if "moderators" in request.args else None)
for keyword in request.args["keywords"]:
self.kserver.set(digest(keyword.lower()), c.get_contract_id(),
self.kserver.node.getProto().SerializeToString())
request.write(json.dumps({"success": True, "id": c.get_contract_id().encode("hex")}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@DELETE('^/api/v1/contracts')
def delete_contract(self, request):
try:
if "id" in request.args:
file_path = self.db.HashMap().get_file(request.args["id"][0])
with open(file_path, 'r') as filename:
contract = json.load(filename, object_pairs_hook=OrderedDict)
c = Contract(self.db, contract=contract)
if "keywords" in c.contract["vendor_offer"]["listing"]["item"]:
for keyword in c.contract["vendor_offer"]["listing"]["item"]["keywords"]:
self.kserver.delete(keyword.lower(), c.get_contract_id(),
self.keychain.signing_key.sign(c.get_contract_id())[:64])
if "delete_images" in request.args:
c.delete(delete_images=True)
else:
c.delete()
request.write(json.dumps({"success": True}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/shutdown')
def shutdown(self, request):
PortMapper().clean_my_mappings(self.kserver.node.port)
self.protocol.shutdown()
reactor.stop()
@POST('^/api/v1/make_moderator')
def make_moderator(self, request):
try:
self.mserver.make_moderator()
request.write(json.dumps({"success": True}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/unmake_moderator')
def unmake_moderator(self, request):
try:
self.mserver.unmake_moderator()
request.write(json.dumps({"success": True}))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/purchase_contract')
def purchase_contract(self, request):
try:
def handle_response(resp, contract):
if resp:
contract.await_funding(self.mserver.protocol.get_notification_listener(),
self.protocol.blockchain, resp)
request.write(json.dumps({"success": True, "payment_address": payment[0],
"amount": payment[1],
"order_id": c.get_contract_id().encode("hex")},
indent=4))
request.finish()
else:
request.write(json.dumps({"success": False, "reason": "seller rejected contract"}, indent=4))
request.finish()
options = None
if "options" in request.args:
options = {}
for option in request.args["options"]:
options[option] = request.args[option][0]
c = Contract(self.db, hash_value=unhexlify(request.args["id"][0]), testnet=self.protocol.testnet)
payment = c.\
add_purchase_info(int(request.args["quantity"][0]),
request.args["ship_to"][0] if "ship_to" in request.args else None,
request.args["address"][0] if "address" in request.args else None,
request.args["city"][0] if "city" in request.args else None,
request.args["state"][0] if "state" in request.args else None,
request.args["postal_code"][0] if "postal_code" in request.args else None,
request.args["country"][0] if "country" in request.args else None,
request.args["moderator"][0] if "moderator" in request.args else None,
options)
def get_node(node):
if node is not None:
self.mserver.purchase(node, c).addCallback(handle_response, c)
else:
request.write(json.dumps({"success": False, "reason": "unable to reach vendor"}, indent=4))
request.finish()
seller_guid = unhexlify(c.contract["vendor_offer"]["listing"]["id"]["guid"])
self.kserver.resolve(seller_guid).addCallback(get_node)
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/confirm_order')
def confirm_order(self, request):
try:
def respond(success):
if success:
request.write(json.dumps({"success": True}))
request.finish()
else:
request.write(json.dumps({"success": False, "reason": "Failed to send order confirmation"}))
request.finish()
file_path = DATA_FOLDER + "store/listings/in progress/" + request.args["id"][0] + ".json"
with open(file_path, 'r') as filename:
order = json.load(filename, object_pairs_hook=OrderedDict)
c = Contract(self.db, contract=order, testnet=self.protocol.testnet)
c.add_order_confirmation(self.protocol.blockchain,
request.args["payout_address"][0],
comments=request.args["comments"][0] if "comments" in request.args else None,
shipper=request.args["shipper"][0] if "shipper" in request.args else None,
tracking_number=request.args["tracking_number"][0]
if "tracking_number" in request.args else None,
est_delivery=request.args["est_delivery"][0]
if "est_delivery" in request.args else None,
url=request.args["url"][0] if "url" in request.args else None,
password=request.args["password"][0] if "password" in request.args else None)
guid = c.contract["buyer_order"]["order"]["id"]["guid"]
self.mserver.confirm_order(guid, c).addCallback(respond)
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/upload_image')
def upload_image(self, request):
try:
ret = []
if "image" in request.args:
for image in request.args["image"]:
img = image.decode('base64')
hash_value = digest(img).encode("hex")
with open(DATA_FOLDER + "store/media/" + hash_value, 'wb') as outfile:
outfile.write(img)
self.db.HashMap().insert(hash_value, DATA_FOLDER + "store/media/" + hash_value)
ret.append(hash_value)
elif "avatar" in request.args:
avi = request.args["avatar"][0].decode("base64")
hash_value = digest(avi).encode("hex")
with open(DATA_FOLDER + "store/avatar", 'wb') as outfile:
outfile.write(avi)
self.db.HashMap().insert(hash_value, DATA_FOLDER + "store/avatar")
ret.append(hash_value)
elif "header" in request.args:
hdr = request.args["header"][0].decode("base64")
hash_value = digest(hdr).encode("hex")
with open(DATA_FOLDER + "store/header", 'wb') as outfile:
outfile.write(hdr)
self.db.HashMap().insert(hash_value, DATA_FOLDER + "store/header")
ret.append(hash_value)
request.write(json.dumps({"success": True, "image_hashes": ret}, indent=4))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/complete_order')
def complete_order(self, request):
def respond(success):
if success:
request.write(json.dumps({"success": True}))
request.finish()
else:
request.write(json.dumps({"success": False, "reason": "Failed to send receipt to vendor"}))
request.finish()
file_path = DATA_FOLDER + "purchases/in progress/" + request.args["id"][0] + ".json"
with open(file_path, 'r') as filename:
order = json.load(filename, object_pairs_hook=OrderedDict)
c = Contract(self.db, contract=order, testnet=self.protocol.testnet)
c.add_receipt(True,
self.protocol.blockchain,
feedback=request.args["feedback"][0] if "feedback" in request.args else None,
quality=request.args["quality"][0] if "quality" in request.args else None,
description=request.args["description"][0] if "description" in request.args else None,
delivery_time=request.args["delivery_time"][0]
if "delivery_time" in request.args else None,
customer_service=request.args["customer_service"][0]
if "customer_service" in request.args else None,
review=request.args["review"][0] if "review" in request.args else "")
guid = c.contract["vendor_offer"]["listing"]["id"]["guid"]
self.mserver.complete_order(guid, c).addCallback(respond)
return server.NOT_DONE_YET
@POST('^/api/v1/settings')
def set_settings(self, request):
try:
settings = self.db.Settings()
settings.update(
request.args["refund_address"][0],
request.args["currency_code"][0],
request.args["country"][0],
request.args["language"][0],
request.args["time_zone"][0],
1 if str_to_bool(request.args["notifications"][0]) else 0,
json.dumps(request.args["shipping_addresses"] if request.args["shipping_addresses"] != "" else []),
json.dumps(request.args["blocked"] if request.args["blocked"] != "" else []),
request.args["libbitcoin_server"][0],
1 if str_to_bool(request.args["ssl"][0]) else 0,
KeyChain(self.db).guid_privkey.encode("hex"),
request.args["terms_conditions"][0],
request.args["refund_policy"][0]
)
request.write(json.dumps({"success": True}, indent=4))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/settings')
def get_settings(self, request):
settings = self.db.Settings().get()
if settings is None:
request.write(json.dumps({}, indent=4))
request.finish()
else:
settings_json = {
"refund_address": settings[1],
"currency_code": settings[2],
"country": settings[3],
"language": settings[4],
"time_zone": settings[5],
"notifications": True if settings[6] == 1 else False,
"shipping_addresses": json.loads(settings[7]),
"blocked_guids": json.loads(settings[8]),
"libbitcoin_server": settings[9],
"ssl": True if settings[10] == 1 else False,
"seed": settings[11],
"terms_conditions": settings[12],
"refund_policy": settings[13]
}
request.write(json.dumps(settings_json, indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/connected_peers')
def get_connected_peers(self, request):
request.write(json.dumps(self.protocol.keys(), indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/routing_table')
def get_routing_table(self, request):
nodes = []
for bucket in self.kserver.protocol.router.buckets:
for node in bucket.nodes.values():
n = {
"guid": node.id.encode("hex"),
"ip": node.ip,
"port": node.port,
"vendor": node.vendor
}
nodes.append(n)
request.write(json.dumps(nodes, indent=4))
request.finish()
return server.NOT_DONE_YET
@GET('^/api/v1/get_notifications')
def get_notifications(self, request):
notifications = self.db.NotificationStore().get_notifications()
notification_list = []
for n in notifications:
notification_json = {
"id": n[0],
"guid": n[1],
"handle": n[2],
"type": n[3],
"order_id": n[4],
"title": n[5],
"timestamp": n[6],
"image_hash": n[7].encode("hex"),
"read": False if n[8] == 0 else True
}
notification_list.append(notification_json)
request.write(json.dumps(notification_list, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/mark_notification_as_read')
def mark_as_read(self, request):
try:
for notif_id in request.args["id"]:
self.db.NotificationStore().mark_as_read(notif_id)
request.write(json.dumps({"success": True}, indent=4))
request.finish()
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/broadcast')
def broadcast(self, request):
try:
def get_response(num):
request.write(json.dumps({"success": True, "peers reached": num}, indent=4))
request.finish()
self.mserver.broadcast(request.args["message"][0]).addCallback(get_response)
return server.NOT_DONE_YET
except Exception, e:
request.write(json.dumps({"success": False, "reason": e.message}, indent=4))
request.finish()
return server.NOT_DONE_YET
@POST('^/api/v1/backup_files')
def backup_files(self, request):
"""Archives OpenBazaar files in a single tar archive."""
output_name = request.args["output_name"][0]
return db.backuptool.backupfiles(output_name)
@POST('^/api/v1/restore_files')
def restore_files(self, request):
"""Restores files of given archive to OpenBazaar folder."""
input_file = request.args["input_file"][0]
return db.backuptool.restorefiles(input_file)