· 6 years ago · Jun 14, 2019, 12:41 AM
1#handle a POST request
2from flask import Flask, render_template, request, url_for, jsonify,session
3app = Flask(__name__)
4
5import json
6import requests
7import math
8import random
9from _hashlib import pbkdf2_hmac
10from base64 import b64encode, urlsafe_b64encode, b64decode, urlsafe_b64decode
11from datetime import datetime, timedelta
12from os import urandom
13
14from Crypto.Cipher import AES, DES
15
16
17__API_KEY = 'd4eee068-272a-4aec-9681-5e16dcef6fbd'
18__DES_KEY = 'co.vmob.sdk.android.encrypt.key'
19
20def generate_plexure_api_key(password):
21 message = '{}|{}'.format(__API_KEY, __get_current_time())
22 return __encrypt_aes(message, password)
23
24def generate_password(device_id):
25 return __encrypt_des('DevicePasswordPrefix{}'.format(device_id))
26
27def __encrypt_des(message):
28 des = DES.new(__DES_KEY[:8].encode(), DES.MODE_ECB)
29 return urlsafe_b64encode(des.encrypt(__pad(message, 8).encode())).decode() + '_'
30
31def __get_current_time():
32 return (datetime.utcnow() - timedelta(minutes=10)).isoformat() + '0Z'
33
34def __encrypt_aes(message, password):
35 salt = urandom(8)
36 encoded_password = pbkdf2_hmac('sha1', password.encode(), salt, 100, 48)
37
38 aes = AES.new(encoded_password[:32], AES.MODE_CBC, encoded_password[32:48])
39
40 return b64encode(aes.encrypt(__pad(message, 16).encode()) + salt).decode()
41
42def __unpad(src):
43 return src[:-src[-1]]
44
45
46def __pad(src, block_size):
47 no_of_blocks = math.ceil(len(src) / float(block_size))
48 pad_value = int(no_of_blocks * block_size - len(src))
49
50 if pad_value == 0:
51 return src + chr(block_size) * block_size
52 else:
53 return src + chr(pad_value) * pad_value
54
55
56
57
58
59
60
61
62
63
64
65@app.route('/off-mcdapi/loyaltycards', methods=['GET'])
66def my_test_endpoint8():
67
68 # force=True, above, is necessary if another developer
69 # forgot to set the MIME type to 'application/json'
70 #http://192.168.1.77:5000/pidiri
71 originaluid=request.headers.get('x-vmob-uid')
72 customoff=mannicciuucosumodificatu(originaluid)
73 with open('spacchiicosunonva.json') as json_file:
74 ciao = json.load(json_file)
75 return jsonify(ciao)
76
77
78
79@app.route('/off-mcdapi/offers', methods=['GET'])
80def my_test_endpoint7():
81
82 # force=True, above, is necessary if another developer
83 # forgot to set the MIME type to 'application/json'
84 #http://192.168.1.77:5000/pidiri
85 originaluid=request.headers.get('x-vmob-uid')
86 customoff=mannicciuucosumodificatu(originaluid)
87 with open('spacchiicosunonva.json') as json_file:
88 ciao = json.load(json_file)
89 return jsonify(ciao)
90
91@app.route('/pidiri/consumers/redeemedOffers', methods=['GET'])
92def my_test_endpoint9():
93
94 # force=True, above, is necessary if another developer
95 # forgot to set the MIME type to 'application/json'
96 #http://192.168.1.77:5000/pidiri
97 originaluid=request.headers.get('x-vmob-uid')
98 with open('autrubuddellu.json') as json_file:
99 ciao = json.load(json_file)
100 return jsonify(ciao[originaluid])
101
102@app.route('/pidiri/consumers/redeemedOffers', methods=['POST'])
103def my_test_endpoint1():
104 input_json = request.get_json(force=True)
105 # force=True, above, is necessary if another developer
106 # forgot to set the MIME type to 'application/json'
107 #http://192.168.1.77:5000/pidiri
108 originaluid=request.headers.get('x-vmob-uid')
109 with open('buddellu.json') as buddillinu:
110 buddellu = json.load(buddillinu)
111 tiramuniID(originaluid)
112 ciao=(piddirimanna(input_json["offerId"],input_json["offerId"],originaluid))
113 with open('offers2.json') as json_file:
114 ciao = json.load(json_file)
115 return jsonify(ciao)
116
117@app.route('/pidiri/consumers', methods=['GET', 'PUT'])
118def consumers():
119 #android_id = coupon.get_random_device_id()
120 #vmob_uid = coupon.generate_vmob_uid(android_id)
121 #plexure_api_key = coupon.generate_plexure_api_key(vmob_uid)
122
123
124 user = "bearer 33520b507ea8a7fc5a4ac4f80f9874c39e8d279cd4a5ad2879c83ef9380fdbb0"
125 uid = str(uuid.uuid4()).upper()
126 rid = str(uuid.uuid4()).upper()
127 pid = str(uuid.uuid4()).upper()
128 headers = {
129 'Content-Type': 'application/json',
130 'Accept': 'application/json',
131 'Accept-Language': 'it-IT',
132 'Authorization': 'Bearer %s' % (user),
133 'Connection': 'keep-alive',
134 'X-Request-id': '%s' % (rid),
135 'x-vmob-application_version': '2683',
136 'x-vmob-authorization': 'Bearer %s' % (user),
137 'x-vmob-beacons': '',
138 'x-vmob-cost-center': 'merchantId587',
139 'x-vmob-device': 'iPhone',
140 'x-vmob-device_network_type': 'wifi',
141 'x-vmob-device_os_version': '11.3.1',
142 'x-vmob-device_screen_resolution': '2436x1125',
143 'x-vmob-device_timezone_id': 'Europe/Rome',
144 'x-vmob-device_type': 'i_p',
145 'x-vmob-device_utc_offset': '+02:00',
146 'x-vmob-location_accuracy': '',
147 'x-vmob-location_latitude': '',
148 'x-vmob-location_longitude': '',
149 'x-vmob-mobile_operator': 'Telenor DK',
150 'x-vmob-sdk_version': '4.36.0',
151 'x-vmob-uid': '%s' % (uid),
152 'x-plexure-api-key': getPlexure(uid).decode('ascii'),
153 'User-Agent': 'GMAL/1.2.18 (iPhone; iOS 11.3.1; Scale/3.00)',
154 }
155 headers['Authorization'] = request.headers['Authorization']
156 if request.method == 'GET':
157 r = requests.get('https://con-west-europe-gma.vmobapps.com/v3/consumers', headers=headers)
158 print(r.content)
159 return r.content
160 elif request.method == 'PUT':
161 r = requests.put('https://con-west-europe-gma.vmobapps.com/v3/consumers', data=request.data,
162 headers=headers)
163
164 return r.content
165
166
167@app.route('/pidiri/consumers/consent', methods=['GET', 'POST'])
168def consent():
169 user = "bearer 33520b507ea8a7fc5a4ac4f80f9874c39e8d279cd4a5ad2879c83ef9380fdbb0"
170 uid = str(uuid.uuid4()).upper()
171 rid = str(uuid.uuid4()).upper()
172 pid = str(uuid.uuid4()).upper()
173 headers = {
174 'Content-Type': 'application/json',
175 'Accept': 'application/json',
176 'Accept-Language': 'it-IT',
177 'Authorization': 'Bearer %s' % (user),
178 'Connection': 'keep-alive',
179 'X-Request-id': '%s' % (rid),
180 'x-vmob-application_version': '2683',
181 'x-vmob-authorization': 'Bearer %s' % (user),
182 'x-vmob-beacons': '',
183 'x-vmob-cost-center': 'merchantId587',
184 'x-vmob-device': 'iPhone',
185 'x-vmob-device_network_type': 'wifi',
186 'x-vmob-device_os_version': '11.3.1',
187 'x-vmob-device_screen_resolution': '2436x1125',
188 'x-vmob-device_timezone_id': 'Europe/Rome',
189 'x-vmob-device_type': 'i_p',
190 'x-vmob-device_utc_offset': '+02:00',
191 'x-vmob-location_accuracy': '',
192 'x-vmob-location_latitude': '',
193 'x-vmob-location_longitude': '',
194 'x-vmob-mobile_operator': 'Telenor DK',
195 'x-vmob-sdk_version': '4.36.0',
196 'x-vmob-uid': '%s' % (uid),
197 'x-plexure-api-key': getPlexure(uid).decode('ascii'),
198 'User-Agent': 'GMAL/1.2.18 (iPhone; iOS 11.3.1; Scale/3.00)',
199 }
200 headers['Authorization'] = request.headers['Authorization']
201 resetoffers(request.headers['x-vmob-uid'])
202 if request.method == 'GET':
203 r = requests.get('https://con-west-europe-gma.vmobapps.com/v3/consumers/consent', headers=headers)
204
205 return r.content
206 elif request.method == 'POST':
207 r = requests.post('https://con-west-europe-gma.vmobapps.com/v3/consumers/consent', data=request.data,
208 headers=headers)
209
210 return r.content
211
212
213
214def resetoffers(uid):
215 with open('buddellu.json') as buddillinu:
216 buddellu = json.load(buddillinu)
217 if uid in buddellu.keys():
218 print("ok stamu abbulannu,procedo")
219 del buddellu[uid]
220 with open("buddellu.json", "w") as l:
221 l.write(json.dumps(buddellu))
222 with open('autrubuddellu.json') as burdilluni:
223 buddelluassai = json.load(burdilluni)
224 if uid in buddelluassai.keys():
225 print("ok stamu abbulannu,procedo")
226 del buddelluassai[uid]
227 with open("autrubuddellu.json", "w") as l:
228 l.write(json.dumps(buddelluassai))
229
230
231
232
233
234
235
236
237
238@app.route('/pidiri/DeviceRegistration', methods=['POST'])
239def my_test_endpoint():
240 input_json = request.get_json(force=True)
241 # force=True, above, is necessary if another developer
242 # forgot to set the MIME type to 'application/json'
243 print( input_json)
244 dictToReturn = {'answer':42}
245 return jsonify(quantustimu())
246
247@app.route('/pidiri/emailRegistrations', methods=['POST'])
248def my_test_endpoint3():
249 input_json = request.get_json(force=True)
250 # force=True, above, is necessary if another developer
251 # forgot to set the MIME type to 'application/json'
252 print( input_json)
253 dictToReturn = {'answer':42}
254 return jsonify(quantustimu())
255
256import requests
257import json
258import re
259import uuid
260
261import json
262import datetime
263import pytz
264
265def tiramuniID(uid):
266 with open('buddellu.json') as buddillinu:
267 buddellu = json.load(buddillinu)
268
269
270 if uid in buddellu.keys():
271 print("ok stamu abbulannu")
272 else:
273 print("non c'è u restu i nenti,lo creo")
274 buddellu[uid] = []
275
276
277 with open("buddellu.json", "w") as l:
278 l.write(json.dumps(buddellu))
279
280
281
282
283def aggiungiofferta(uid,offerID,jsonoff):
284 now = datetime.datetime.now(pytz.timezone('Europe/Rome')).strftime('%Y-%m-%dT%H:%M:%SZ')
285 print(now)
286 with open('buddellu.json') as buddillinu:
287 buddellu = json.load(buddillinu)
288
289
290 if uid in buddellu.keys():
291 print("ok stamu abbulannu,procedo")
292
293 buddellu[uid].append(
294 { "id":offerID, "timestamp":now})
295
296 else:
297 print("non c'è u restu i nenti,ma chi cumminasti?")
298
299
300
301 with open("buddellu.json", "w") as l:
302 l.write(json.dumps(buddellu))
303
304 with open('autrubuddellu.json') as burdilluni:
305 offsave = json.load(burdilluni)
306 print(jsonoff)
307 if uid in offsave.keys():
308 print("ok stamu abbulannu,procedo")
309
310 offsave[uid].append(jsonoff)
311
312 else:
313 print("non c'è u restu i nenti,ma chi cumminasti?")
314 offsave[uid] = []
315 offsave[uid].append(jsonoff)
316 print (offsave)
317 with open("autrubuddellu.json", "w") as l:
318 l.write(json.dumps(offsave))
319 return json.dumps(offsave)
320
321def mannicciuucosumodificatu(uid):
322 with open('offers.json') as offerteoriginali:
323 offerteoriginalimammo = json.load(offerteoriginali)
324 with open('buddellu.json') as offerteutilizzate:
325 offerteutilizzatemammo = json.load(offerteutilizzate)
326
327 if uid in offerteutilizzatemammo.keys():
328 print("ok stamu abbulannu")
329 print(offerteutilizzatemammo[uid])
330 print (len(offerteutilizzatemammo[uid]))
331 for x in range(0, len(offerteutilizzatemammo[uid])):
332 offeridusato=offerteutilizzatemammo[uid][x]["id"]
333
334 timestampidusato=offerteutilizzatemammo[uid][x]["timestamp"]
335
336 for d in range(0, len(offerteoriginalimammo)):
337 print(offeridusato)
338 print(offerteoriginalimammo[d]["offerInstanceUniqueId"])
339 if(int(offeridusato) == int(offerteoriginalimammo[d]["offerInstanceUniqueId"])):
340 print("modifico")
341 offerteoriginalimammo[d]["redemptionCount"]=1
342 offerteoriginalimammo[d]["lastRedeemedAt"]=timestampidusato
343 with open("spacchiicosunonva.json", "w") as l:
344 l.write(json.dumps(offerteoriginalimammo))
345 return json.dumps(offerteoriginalimammo)
346
347
348
349def getPlexure(uid):
350 import subprocess
351 return subprocess.check_output(["java", "Try", uid])
352
353
354
355def piddirimanna(coupon1,coupon,originaluid):
356 print("piddirimanna")
357 codice=quantustimu()
358 print("prima")
359 print(codice["access_token"])
360 print("dopo")
361 user = codice["access_token"]
362 print(codice)
363 uid = str(uuid.uuid4()).upper()
364 rid = str(uuid.uuid4()).upper()
365 pid = str(uuid.uuid4()).upper()
366 #print("Using random UID: %s" % (uid))
367 #print("Using random RID: %s" % (rid))
368 headers = {
369 'Content-Type': 'application/json',
370 'Accept': 'application/json',
371 'Accept-Language': 'it-IT',
372 'Authorization': 'Bearer %s' % (user),
373 'Connection': 'keep-alive',
374 'X-Request-id': '%s' % (rid),
375 'x-vmob-application_version': '2683',
376 'x-vmob-authorization': 'Bearer %s' % (user),
377 'x-vmob-beacons': '',
378 'x-vmob-cost-center': 'merchantId587',
379 'x-vmob-device': 'iPhone',
380 'x-vmob-device_network_type': 'wifi',
381 'x-vmob-device_os_version': '11.3.1',
382 'x-vmob-device_screen_resolution': '2436x1125',
383 'x-vmob-device_timezone_id': 'Europe/Rome',
384 'x-vmob-device_type': 'i_p',
385 'x-vmob-device_utc_offset': '+02:00',
386 'x-vmob-location_accuracy': '',
387 'x-vmob-location_latitude': '',
388 'x-vmob-location_longitude': '',
389 'x-vmob-mobile_operator': 'Telenor DK',
390 'x-vmob-sdk_version': '4.36.0',
391 'x-vmob-uid': '%s' % (uid),
392 'x-plexure-api-key': getPlexure(uid).decode('ascii'),
393 'User-Agent': 'GMAL/1.2.18 (iPhone; iOS 11.3.1; Scale/3.00)',
394 }
395
396 # print headers
397 #print("Using random Transaction ID: %s" % (pid))
398 payload = {"loyaltyCardId": 481, "pointsRequested": 1, "autoActivateReward": False,
399 "fillMultipleCards": True, "transactionId": "Campaign_Activation:%s" % (pid)}
400
401 k = requests.post("https://con-west-europe-gma.vmobapps.com/v3/consumers/redeemedOffers" ,
402 headers=headers, data="{\"offerId\":%s}" %(coupon))
403 with open("offers2.json", "w") as l:
404 l.write(json.dumps(k.json()))
405 print (k)
406 aggiungiofferta(originaluid,coupon,k.json())
407 return json.dumps(k.json())
408
409
410
411
412
413def quantustimu():
414 # accounts to create
415 amount = 1
416 for i in range(amount):
417 uid = str(uuid.uuid4()).upper()
418 rid = str(uuid.uuid4()).upper()
419 pid = str(uuid.uuid4()).upper()
420 print("Using random UID: %s" % (uid))
421 print("Using random RID: %s" % (rid))
422 print("Pleasure id: %s" % getPlexure(uid).decode('ascii'))
423 print("Pleasure id: %s" % getPlexure(uid).decode('ascii'))
424
425 emailprefix = uid[:8]
426
427 headers = {
428 'x-vmob-location_accuracy': '',
429 'x-vmob-beacons': '',
430 'Accept': 'application/json',
431 'x-vmob-device_os_version': '',
432 'x-vmob-device_type': 'a',
433 'x-vmob-cost-center': 'merchantId587',
434 'x-vmob-device_timezone_id': 'GMT',
435 'x-vmob-device_screen_resolution': '',
436 'x-vmob-mobile_operator': 'Telenor DK',
437 'Authorization': 'bearer 33520b507ea8a7fc5a4ac4f80f9874c39e8d279cd4a5ad2879c83ef9380fdbb0',
438 'x-vmob-device': 'iPhone',
439 'x-vmob-location_longitude': '',
440 'x-vmob-location_latitude': '',
441 'x-vmob-sdk_version': '4.36.3',
442 'x-vmob-device_network_type': '',
443 'Accept-Language': 'it-IT',
444 'x-vmob-device_utc_offset': '+2:00',
445 'x-vmob-application_version': '2530',
446 'Content-Type': 'application/json',
447 'User-Agent': 'GMAL/1.2.18 (iPhone; iOS 12.1.1; Scale/3.00)',
448 'Host': 'con-west-europe-gma.vmobapps.com',
449 'X-Request-id': '%s' % (rid),
450 'x-vmob-sdk_version': '4.36.0',
451 'x-vmob-uid': '%s' % (uid),
452 'x-plexure-api-key': getPlexure(uid).decode('ascii'),
453
454 }
455
456
457 data = '{"password":"Mammoriri1","username":"%s@gmail.com" ,"emailRegistration":{"password":"Mammoriri1","firstName":"Ronald","emailAddress":"%s@gmail.com","lastName":"McDonald","gender":"","tagValueAddReferenceCodes":["merchantId587"]},"grant_type":"password"}' % (
458 emailprefix, emailprefix)
459
460 r = requests.post(
461 'https://con-west-europe-gma.vmobapps.com/v3/emailRegistrations', headers=headers, data=data)
462 if r.status_code == 200:
463 json = r.json()
464 # print(json)
465 bearer = json["access_token"]
466 # print(bearer)
467 s1 = emailprefix
468 s2 = '@gmail.com'
469 emailacc = s1 + s2
470 password = 'Mammoriri1'
471 fc = '{"username": "%s", "password": "%s", "token": "%s"}' % (
472 emailacc, password, bearer)
473 json1=json
474
475 else:
476 print(r.status_code)
477 # print r.json()
478 return json
479
480if __name__ == '__main__':
481 app.run(host= '0.0.0.0')