-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapplication.py
executable file
·2244 lines (1969 loc) · 66.7 KB
/
application.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 python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import sys
import time
import json
import pickle
import socket
import struct
import jwt
from glob import glob
from inspect import stack
from flask_sslify import SSLify
from datetime import datetime, timedelta
from sqlalchemy.sql import func, update, text
from functools import wraps
from traceback import print_exc
from werkzeug.serving import WSGIRequestHandler
from base64 import b64decode
from PIL import Image
try:
from cStringIO import StringIO
except ImportError:
from io import BytesIO
from flask import (
abort,
Flask,
jsonify,
make_response,
redirect,
request,
Response
)
try:
from httplib import (
NO_CONTENT,
UNAUTHORIZED,
BAD_REQUEST,
NOT_FOUND,
OK,
FORBIDDEN,
INTERNAL_SERVER_ERROR,
CREATED,
CONFLICT,
FOUND
)
except ImportError:
from http.client import (
NO_CONTENT,
UNAUTHORIZED,
BAD_REQUEST,
NOT_FOUND,
OK,
FORBIDDEN,
INTERNAL_SERVER_ERROR,
CREATED,
CONFLICT,
FOUND
)
try:
from paypalrestsdk.notifications import WebhookEvent
except ImportError:
pass
from update import *
from utils import *
from vpns import *
from bitcoin_payments import *
from paypal import *
from model import *
from resin import *
from country import *
from config import *
application = Flask(__name__)
application.config.from_object('config')
application.debug = DEBUGGER
sslify = SSLify(
application, skips=[
'api/v{}/ping'.format(API_VERSION),
'status',
'ddwrt',
'api/v{}/ddwrt'.format(API_VERSION),
'api/v{}/vpnprovider'.format(API_VERSION)
]
)
# set HTTP/1.1
WSGIRequestHandler.protocol_version = 'HTTP/1.1'
# initialise globals and cache
if not os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
print('cache_flush: {}'.format(cache_flush()))
print('init_cache: {}'.format(init_cache()))
BLACKBOX = load_blackbox_data()
@application.teardown_appcontext
def shutdown_session(exception=None):
session.commit()
session.remove()
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
if not 'X-Auth-Token' in request.headers:
abort(UNAUTHORIZED)
if API_SECRET == request.headers.get('X-Auth-Token'):
return f(*args, **kwargs)
else:
abort(UNAUTHORIZED)
return decorated
def add_response_headers(headers={}):
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
resp = make_response(f(*args, **kwargs))
h = resp.headers
for header, value in headers.items():
h[header] = value
return resp
return decorated_function
return decorator
def add_cors_header(f):
return add_response_headers(
{
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'origin, content-type, accept'
}
)(f)
def add_download_headers(f):
return add_response_headers(
{
'Content-Disposition': 'attachment; filename="blackbox.ovpn"',
'Content-Type': 'application/x-openvpn-profile',
'X-Content-Type-Options': 'nosniff'
}
)(f)
def add_cache_control_max_age_1hr(f):
return add_response_headers(
{
'Cache-Control': 'max-age=3600'
}
)(f)
@application.route('/api/v{}/ping'.format(API_VERSION))
@application.route('/status')
def _ping_pong():
return json.dumps({'ping': 'pong'})
################
# PayPal views #
################
@application.route('/api/v{}/paypal/billing-<string:btype>'.format(API_VERSION), methods=['GET'], defaults={'bid': None})
@application.route('/api/v{}/paypal/billing-<string:btype>/<string:bid>'.format(API_VERSION), methods=['GET'])
@requires_auth
def _get_billing(bid, btype):
if btype.lower() not in ['agreements', 'plans']: abort(NOT_FOUND)
try:
res = get_pp_billing(bid=bid, btype=btype)
if DEBUG: print('{}: status_code={} content={}'.format(
stack()[0][3],
res.status_code,
res.content
))
if res.status_code not in [OK]: abort(res.status_code)
try:
payload = json.loads(res.content.decode('utf-8'))
except:
payload = json.loads(res.content)
return jsonify(payload)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
@application.route('/api/v{}/paypal/billing-agreements/<string:baid>/confirm'.format(API_VERSION), methods=['GET'])
@requires_auth
def _confirm_active_billing_agreement(baid):
try:
res = get_pp_billing(bid=baid, btype='agreements')
if DEBUG: print('{}: status_code={} content={}'.format(
stack()[0][3],
res.status_code,
res.content
))
if res.status_code not in [OK]: abort(res.status_code)
try:
payload = json.loads(res.content.decode('utf-8'))
except:
payload = json.loads(res.content)
state = payload['state'].lower()
if state in ['active']:
return jsonify({'agreement_state': state})
else:
return abort(NOT_FOUND)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
@application.route('/api/v{}/paypal/billing-plans/create/<string:bptype>'.format(API_VERSION), methods=['GET'])
@requires_auth
def _create_billing_plan(bptype):
if not bptype.lower() in ['trial', 'regular']: abort(BAD_REQUEST)
result = create_pp_billing_plan(bptype=bptype)
if result.status_code in [OK, CREATED, NO_CONTENT]:
try:
try:
payload = json.loads(result.content.decode('utf-8'))
except:
payload = json.loads(result.content)
if DEBUG: print('{}: {}'.format(stack()[0][3], result.content))
return jsonify(payload)
except ValueError as e:
print(repr(e))
if DEBUG: print_exc()
return json.dumps({'pp_status_code': result.status_code}), result.status_code
@application.route('/api/v{}/paypal/billing-plans/<string:bpid>/activate'.format(API_VERSION), methods=['GET'])
@requires_auth
def _activate_billing_plan(bpid):
result = update_pp_billing_plan_status(id=bpid)
if result.status_code in [OK, CREATED, NO_CONTENT]:
try:
try:
payload = json.loads(result.content.decode('utf-8'))
except:
payload = json.loads(result.content)
if DEBUG: print('{}: {}'.format(stack()[0][3], result.content))
return jsonify(payload)
except ValueError as e:
print(repr(e))
return json.dumps({'pp_status_code': result.status_code}), result.status_code
@application.route('/api/v{}/paypal/billing-plans/<string:bpid>/delete'.format(API_VERSION), methods=['GET'])
@requires_auth
def _delete_billing_plan(bpid):
result = update_pp_billing_plan_status(id=bpid, status='DELETED')
if result.status_code in [OK, CREATED, NO_CONTENT]:
try:
try:
payload = json.loads(result.content.decode('utf-8'))
except:
payload = json.loads(result.content)
if DEBUG: print('{}: {}'.format(stack()[0][3], result.content))
return jsonify(payload)
except ValueError as e:
print(repr(e))
return json.dumps(
{'pp_status_code': result.status_code}
), result.status_code
@application.route('/api/v{}/paypal/billing-agreements/<string:payload>/create/<string:bptype>'.format(API_VERSION), methods=['GET'])
def _create_billing_agreement(payload, bptype):
if not bptype.lower() in ['trial', 'regular']: abort(BAD_REQUEST)
try:
res = create_pp_billing_agreement(payload=payload, bptype=bptype)
if res.status_code in [OK, CREATED, NO_CONTENT]:
try:
payload = json.loads(res.content.decode('utf-8'))
except:
payload = json.loads(res.content)
location = [link['href'] for link in payload['links'] if link['rel'] == 'approval_url'][0]
return redirect(location, code=302)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
# create regular PayPal subscription by clicking a web link
@application.route('/api/v{}/paypal/billing-agreement/create'.format(API_VERSION), methods=['GET'])
def _create_billing_agreement_by_link():
try:
data = {
'i': generate_hash_key()[:32],
'p': generate_hash_key()[:16],
't': 'OTHER', 'u': ''
}
hdr = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[0]
sig = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[2]
payload = jwt.encode(data, data['p'], algorithm='HS256').decode('utf-8').split('.')[1]
print('{}: hdr={} sig={} data={} payload={}'.format(
stack()[0][3],
hdr,
sig,
data,
payload
))
res = create_pp_billing_agreement(payload=payload, bptype='regular')
if res.status_code in [OK, CREATED, NO_CONTENT]:
try:
payload = json.loads(res.content.decode('utf-8'))
except:
payload = json.loads(res.content)
location = [link['href'] for link in payload['links'] if link['rel'] == 'approval_url'][0]
return redirect(location, code=302)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
# PayPal call-back URL
@application.route('/api/v{}/paypal/billing-agreements/execute'.format(API_VERSION), methods=['GET'])
def _execute_billing_agreement():
args = request.args.to_dict()
if DEBUG: print('{}: {}'.format(stack()[0][3], args))
try:
# execute billing agreement and get billing agreement id and customer details
token = args['token']
res = execute_pp_billing_agreement(token=token)
assert res.status_code in [OK, CREATED, NO_CONTENT]
try:
payload = json.loads(res.content.decode('utf-8'))
except:
payload = json.loads(res.content)
description = payload['description']
# check JWT token or use GUID
try:
hdr = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[0]
sig = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[2]
jwtoken = jwt.decode('{}.{}.{}'.format(hdr, description, sig), verify=False)
print('{}: hdr={} sig={} jwt={}'.format(
stack()[0][3],
hdr,
sig,
jwtoken
))
device_type = jwtoken['t']
guid = jwtoken['i']
tun_passwd = jwtoken['p']
try:
ip = socket.inet_ntoa(struct.pack('!L', int(jwtoken['u'])))
except:
ip = None
except:
guid = description
device_type = None
tun_passwd = None
ip = None
if DEBUG: print('{}: guid={} device_type={} ip={} tun_passwd={}'.format(
stack()[0][3],
guid,
device_type,
ip,
tun_passwd
))
baid = payload['id']
payer_id = payload['payer']['payer_info']['payer_id']
payer_email = payload['payer']['payer_info']['email']
start_date = payload['start_date']
payment_defs = payload['plan']['payment_definitions']
if DEBUG: print('{}: token={} baid={} guid={} payer_id={} start_date={}'.format(
stack()[0][3],
token,
baid,
guid,
payer_id,
start_date
))
# check subscription billing plan type
bptype = 'REGULAR'
for payment_def in payment_defs:
if DEBUG: print('{}: payment_def={} type={}'.format(
stack()[0][3],
payment_def,
payment_def['type']
))
if payment_def['type'].upper() in ['TRIAL']:
bptype = payment_def['type'].upper()
break
# subscription from DD-WRT or TOMATO router
if device_type in ['DDWRT', 'DD-WRT', 'DD_WRT', 'TOMAT']:
if bptype in ['REGULAR']:
alert_type = 'success'
if device_type in ['DDWRT', 'DD-WRT', 'DD_WRT']:
alert_msg = 'Subscribed successfully, dismiss alert to continue.'
location = 'http://{}/MyPage.asp?1&type={}&msg={}&billingid={}&payerid={}&payeremail={}'.format(
ip,
alert_type,
alert_msg,
baid,
payer_id,
payer_email
)
else:
# cancel billing agreement (TRIAL not supported on 'dumb' routers)
if DEBUG: print('{}: bptype={} ip={}'.format(
stack()[0][3],
payment_def['type'],
ip
))
res = cancel_pp_billing_agreement(id=baid)
assert res.status_code in [OK, CREATED, NO_CONTENT]
if DEBUG: print('cancel_pp_billing_agreement({}): {}'.format(baid, res))
alert_type = 'warning'
alert_msg = 'Free trial period is not available on {} device type.'.format(device_type)
location = 'http://{}/?1&type={}&msg={}'.format(ip, alert_type, alert_msg)
return redirect(location, code=302)
# subscription from URL
if device_type in ['OTHER']:
if bptype in ['REGULAR']:
alert_type = 'success'
alert_msg = 'Subscribed successfully.'
location = '{}/sub?type={}&msg={}&jwtoken={}&billing_id={}'.format(
BLACKBOX_RETURN_URL,
alert_type,
alert_msg,
description,
baid
)
else:
# cancel billing agreement (TRIAL not supported)
if DEBUG: print('{}: bptype={} ip={}'.format(
stack()[0][3],
payment_def['type'],
ip
))
res = cancel_pp_billing_agreement(id=baid)
assert res.status_code in [OK, CREATED, NO_CONTENT]
if DEBUG: print('cancel_pp_billing_agreement({}): {}'.format(baid, res))
alert_type = 'warning'
alert_msg = 'Free trial period is not available on {} device type.'.format(device_type)
location = '{}/sub?type={}&msg={}'.format(
BLACKBOX_RETURN_URL,
alert_type,
alert_msg
)
return redirect(location, code=302)
# trial subscription from resin dot io device (legacy)
trial_expired = False
trial_start_date = start_date
if bptype == 'TRIAL':
res = get_resin_device_envs_by(guid)
assert res.status_code in [OK]
try:
evs = json.loads(res.content.decode('utf-8'))
except:
evs = json.loads(res.content)
# check if trial expired (existing device)
for ev in evs['d']:
if ev['env_var_name'] == 'PAYPAL_TRIAL_START_DATE':
trial_start_date = ev['value']
trial_expires = datetime.strptime(
trial_start_date,
'%Y-%m-%dT%H:%M:%SZ'
) + timedelta(days=365/12)
today = datetime.utcnow()
if today > trial_expires: trial_expired = True
break
# record trial start date
res = create_update_resin_device_env(
guid=guid,
name='PAYPAL_TRIAL_START_DATE',
value=trial_start_date
)
if DEBUG: print('{}: guid={} trial_start_date={}'.format(
stack()[0][3],
guid,
trial_start_date
))
if trial_expired:
# record expired buyer id
res = create_update_resin_device_env(
guid=guid,
name='PAYPAL_TRIAL_EXPIRED',
value=payer_id
)
if DEBUG: print('{}: guid={} payer_id={}'.format(
stack()[0][3],
guid,
payer_id
))
# cancel billing agreement
if DEBUG: print('{}: baid={} payer_id={} today={} trial_expires={} trial_expired={} trial_start_date={}'.format(
stack()[0][3],
baid,
payer_id,
today,
trial_expires,
trial_expired,
trial_start_date
))
res = cancel_pp_billing_agreement(id=baid)
assert res.status_code in [OK, CREATED, NO_CONTENT]
if DEBUG: print('cancel_pp_billing_agreement({}): {}'.format(baid, res))
# default to regular subscription
location = '{}/?guid={}&result=402'.format(BLACKBOX_RETURN_URL, guid)
return redirect(location, code=302)
# return to dashboard
location = '{}/?guid={}&result=200'.format(BLACKBOX_RETURN_URL, guid)
time.sleep(5) # wait 5 seconds for PayPal WebHook to fire (unreliable)
return redirect(location, code=302)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
# PayPal call-back URL (payment flow errors or user abort)
@application.route('/api/v{}/paypal/billing-agreements/cancel'.format(
API_VERSION
), methods=['GET'])
def __cancel_billing_agreement__():
args = request.args.to_dict()
if DEBUG: print('{}: {}'.format(stack()[0][3], args))
return redirect('http://{}/'.format(LOCAL_DEVICE, code=302))
@application.route('/api/v{}/paypal/billing-agreements/<string:baid>/cancel'.format(
API_VERSION
), methods=['GET'])
@requires_auth
def _cancel_billing_agreement(baid):
if not baid: abort(BAD_REQUEST)
result = cancel_pp_billing_agreement(id=baid)
if result.status_code in [OK, CREATED, NO_CONTENT]:
try:
try:
payload = json.loads(result.content.decode('utf-8'))
except:
payload = json.loads(result.content)
if DEBUG: print('{}: {}'.format(stack()[0][3], result.content))
return jsonify(payload)
except ValueError as e:
print(repr(e))
if DEBUG: print_exc()
return json.dumps({'pp_status_code': result.status_code}), result.status_code
# PayPal call-back URL, WebHook(s)
@application.route('/api/v{}/paypal/webhook'.format(API_VERSION), methods=['POST'])
def _paypal_webhook_receive():
try:
headers = request.headers.__dict__
request.get_data()
try:
raw_post_body = request.data.decode('utf-8')
except:
raw_post_body = request.data
json_post_body = json.loads(request.data)
if DEBUG:
print('request.headers.__dict__: {}'.format(headers))
print('{}: {}'.format(stack()[0][3], json_post_body))
res = True
if PAYPAL_VERIFY_WEBHOOK:
if DEBUG:
print('WebhookEvent.verify({}, {}, {}, {}, {}, {}, {})'.format(
headers['environ']['HTTP_PAYPAL_TRANSMISSION_ID'],
headers['environ']['HTTP_PAYPAL_TRANSMISSION_TIME'],
PAYPAL_WEBHOOK_ID,
raw_post_body,
headers['environ']['HTTP_PAYPAL_CERT_URL'],
headers['environ']['HTTP_PAYPAL_TRANSMISSION_SIG'],
headers['environ']['HTTP_PAYPAL_AUTH_ALGO']
))
res = WebhookEvent.verify(
headers['environ']['HTTP_PAYPAL_TRANSMISSION_ID'],
headers['environ']['HTTP_PAYPAL_TRANSMISSION_TIME'],
PAYPAL_WEBHOOK_ID,
raw_post_body,
headers['environ']['HTTP_PAYPAL_CERT_URL'],
headers['environ']['HTTP_PAYPAL_TRANSMISSION_SIG'],
headers['environ']['HTTP_PAYPAL_AUTH_ALGO']
)
print('WebhookEvent.verify: {}'.format(res))
if not res: return json.dumps({'WebhookEvent.verify': res}), 401
try:
description = json_post_body['resource']['description']
except KeyError as e:
print(repr(e))
if DEBUG: print_exc()
return jsonify(json_post_body)
try:
# check for JWT token
try:
hdr = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[0]
sig = jwt.encode({}, '', algorithm='HS256').decode('utf-8').split('.')[2]
jwtoken = jwt.decode(
'{}.{}.{}'.format(
hdr,
description,
sig
),
verify=False
)
guid = jwtoken['i']
device_type = jwtoken['t']
print('{}: hdr={} sig={} jwt={}'.format(
stack()[0][3],
hdr,
sig,
jwtoken
))
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
device_type = None
guid = description
baid = json_post_body['resource']['id']
start_date = json_post_body['resource']['start_date']
payer_id = json_post_body['resource']['payer']['payer_info']['payer_id'].upper()
email = json_post_body['resource']['payer']['payer_info']['email']
evtid = json_post_body['id']
payment_defs = json_post_body['resource']['plan']['payment_definitions']
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
return jsonify(raw_post_body)
# nothing further to do for router devices or web subscriptions
if device_type in ['DD-WRT', 'DDWRT', 'DD_WRT', 'OTHER', 'TOMAT']:
return jsonify(raw_post_body)
# resin dot io device, continue with processing
bptype = 'REGULAR'
for payment_def in payment_defs:
if payment_def['type'].upper() in ['TRIAL']:
bptype = payment_def['type'].upper()
break
res = get_resin_device_envs_by(guid)
assert res.status_code in [OK]
try:
evs = json.loads(res.content.decode('utf-8'))
except:
evs = json.loads(res.content)
if json_post_body['event_type'] in [
'BILLING.SUBSCRIPTION.CREATED',
'BILLING.SUBSCRIPTION.RE-ACTIVATED',
'BILLING.SUBSCRIPTION.UPDATED'
]:
original_start_date = None
for ev in evs['d']:
if ev['env_var_name'] == 'PAYPAL_TRIAL_START_DATE':
original_start_date = ev['value']
break
# keep original trial date from previous device(s)
if original_start_date and bptype in ['TRIAL']:
start_date = original_start_date
for ev in [
{'name': 'PAYPAL_PAYER_ID', 'value': payer_id},
{'name': 'PAYPAL_PAYER_EMAIL', 'value': email},
{'name': 'PAYPAL_BILLING_AGREEMENT_START_DATE', 'value': start_date},
{'name': 'PAYPAL_BILLING_AGREEMENT', 'value': baid}
]:
res = create_update_resin_device_env(
guid=guid,
name=ev['name'],
value=ev['value']
)
return jsonify({
'GUID': guid,
'PAYPAL_BILLING_PLAN_TYPE': bptype,
'PAYPAL_PAYER_ID': payer_id,
'PAYPAL_PAYER_EMAIL': email,
'PAYPAL_BILLING_AGREEMENT_START_DATE': start_date,
'PAYPAL_BILLING_AGREEMENT': baid
})
elif json_post_body['event_type'] in [
'BILLING.SUBSCRIPTION.CANCELLED',
'BILLING.SUBSCRIPTION.SUSPENDED'
]:
response = {'GUID': guid}
for ev in evs['d']:
if ev['env_var_name'] == 'PAYPAL_BILLING_AGREEMENT' and ev['value'] == baid:
# delete env var
res = delete_resin_device_env_by_name(
guid=guid,
name='PAYPAL_BILLING_AGREEMENT'
)
response['PAYPAL_BILLING_AGREEMENT'] = baid
break
return jsonify(response)
else:
return jsonify(raw_post_body)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
#################
# Bitcoin views #
#################
@application.route('/api/v{}/bitcoin/btc_price/<string:currency>'.format(API_VERSION))
def _blocktrail_btc_price(currency):
try:
btc_price = get_btc_price(currency=currency)
return jsonify(btc_price)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
@application.route('/api/v{}/bitcoin/payment_address/guid/<string:guid>'.format(API_VERSION))
@requires_auth
def _blockcypher_new_payment_address(guid):
try:
(payment_address, webhook_id) = generate_new_payment_address(guid=guid)
return jsonify({
'payment_address': payment_address,
'webhook_id': webhook_id
})
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
@application.route('/api/v{}/blockcypher/webhook/{}'.format(API_VERSION, BLOCKCYPHER_WEBHOOK_TOKEN), methods=['POST'])
def _blockcypher_webhook_receive():
try:
headers = request.headers.__dict__
request.get_data()
raw_post_body = request.data
json_post_body = json.loads(request.data)
if DEBUG:
print('request.headers.__dict__: {}'.format(headers))
print('{}: {}'.format(stack()[0][3], json_post_body))
if headers['environ']['HTTP_X_EVENTTYPE'] in ['confirmed-tx', 'unconfirmed-tx']:
devices = get_resin_devices()
assert devices.status_code in [OK]
try:
devices = json.loads(devices.content.decode('utf-8'))
except:
devices = json.loads(devices.content)
(payment_address, guid, btc_amount) = [(
out['addresses'][0],
cache_get(key=out['addresses'][0]),
int(out['value'])
) for out in json_post_body['outputs'] if cache_get(key=out['addresses'][0])][0]
last_payment_date = datetime.strftime(
datetime.utcnow(),
'%Y-%m-%dT%H:%M:%SZ'
)
transaction_id = json_post_body['hash']
confirmation = json_post_body['confirmations']
try:
guid = guid.decode('utf-8')
except:
pass
last_txn_id = get_resin_device_env_by_name(
guid=guid,
name='BITCOIN_LAST_TRANSACTION_ID'
)
confirmations = confirmation + int(
get_resin_device_env_by_name(
guid=guid,
name='BITCOIN_CONFIRMATIONS',
default=0
)
)
res = create_update_resin_device_env(
guid=guid,
name='BITCOIN_CONFIRMATIONS',
value=str(confirmations)
)
if DEBUG: print('{}: guid={} payment_address={} btc_amount={} last_payment_date={} hash={} last_hash={} conf={} confs={}'.format(
stack()[0][3],
guid,
payment_address,
btc_amount,
last_payment_date,
transaction_id,
last_txn_id,
confirmation,
confirmations
))
if guid and last_txn_id != transaction_id:
# calculate new expiry date if a new payment arrives
prev_last_payment_date = get_resin_device_env_by_name(guid=guid, name='BITCOIN_LAST_PAYMENT_DATE')
prev_last_payment_amount = get_resin_device_env_by_name(guid=guid, name='BITCOIN_LAST_PAYMENT_AMOUNT')
btc_daily_amount = get_resin_device_env_by_name(guid=guid, name='BITCOIN_DAILY_AMOUNT')
if prev_last_payment_date and prev_last_payment_amount and btc_daily_amount:
btc_expiry_date = datetime.strptime(prev_last_payment_date, '%Y-%m-%dT%H:%M:%SZ') + timedelta(days=float(prev_last_payment_amount) / float(btc_daily_amount))
today = datetime.utcnow()
if today <= btc_expiry_date:
remain_days = float(timedelta(seconds=(btc_expiry_date - today).total_seconds()).total_seconds()) / float(86400)
remain_amount = int(float(remain_days) * int(btc_daily_amount))
btc_amount = btc_amount + remain_amount
msg = '{}: prev_last_payment_date={} prev_last_payment_amount={} btc_daily_amount={} btc_expiry_date={} remain_days={} remain_amount={} btc_amount={}'.format(
stack()[0][3],
prev_last_payment_date,
prev_last_payment_amount,
btc_daily_amount,
btc_expiry_date,
remain_days,
remain_amount,
btc_amount
)
for ev in [
{'name': 'BITCOIN_LAST_PAYMENT_AMOUNT', 'value': str(btc_amount)},
{'name': 'BITCOIN_LAST_PAYMENT_DATE', 'value': last_payment_date},
{'name': 'BITCOIN_LAST_TRANSACTION_ID', 'value': transaction_id}
]:
res = create_update_resin_device_env(
guid=guid,
name=ev['name'],
value=ev['value']
)
response = {
'GUID': guid,
'BITCOIN_LAST_TRANSACTION_ID': transaction_id,
'BITCOIN_LAST_PAYMENT_DATE': last_payment_date,
'BITCOIN_PAYMENT_ADDRESS': payment_address,
'BITCOIN_LAST_PAYMENT_AMOUNT': btc_amount
}
body = json.dumps(
{
'WebHook': json_post_body,
'api_response': response
},
indent=4
)
print('body={}'.format(body))
background_smtp_send(
subject='{} payment of {} Satoshi received from {}'.format(
BLOCKCYPHER_COIN_SYMBOL,
btc_amount,
guid
),
body=body,
preamble='Bitcoin payment notification'
)
return jsonify(response)
return jsonify(json_post_body)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
##################
# resin.io views #
##################
@application.route('/api/v{}/devices/purge/<string:app_id>'.format(API_VERSION), methods=['GET'])
@requires_auth
def _purge_expired_devices(app_id):
try:
expired_devices = purge_resin_devices(app_id=app_id)
return jsonify(expired_devices)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
@application.route('/api/v{}/device/<string:guid>'.format(API_VERSION), methods=['GET', 'POST'])
@requires_auth
def _get_resin_device(guid):
device = None
try:
device = get_resin_device(guid=guid)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
if device:
return jsonify(device)
else:
abort(NOT_FOUND)
@application.route('/api/v{}/device/<string:guid>/<string:action>'.format(API_VERSION), methods=['GET'])
@requires_auth
def _device_action(guid, action):
if action not in ['restart', 'reboot', 'shutdown']: abort(BAD_REQUEST)
try:
res = resin_device_action(guid=guid, action=action)
except Exception as e:
print(repr(e))
if DEBUG: print_exc()
abort(BAD_REQUEST)
try:
return jsonify(res.content.decode('utf-8')), res.status_code
except:
return jsonify(res.content), res.status_code
@application.route('/api/v{}/device/<string:guid>/env'.format(API_VERSION), methods=['PUT'])
@requires_auth
def _put_device_env(guid):
try:
guid = guid.decode('utf-8')
except:
pass
devices = get_resin_devices()
if devices.status_code in [OK]:
try:
devices = json.loads(devices.content.decode('utf-8'))
except:
devices = json.loads(devices.content)
else:
abort(devices.status_code)
for device in devices['d']:
if device['uuid'].startswith(guid):
try:
data = json.loads(request.data.decode('utf-8'))
except:
data = json.loads(request.data)
data['device'] = device['id']