This repository has been archived by the owner on Apr 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
server.py
1922 lines (1566 loc) · 60.5 KB
/
server.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
import atexit
import datetime
import httpx
import json
import pgeocode
import os
import re
import time
import urllib3
import xmltodict
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, request, jsonify, send_file, render_template, session, redirect, url_for, send_from_directory, Markup
from flask_wtf import FlaskForm, Form
from flask_wtf.file import FileField, FileRequired, FileAllowed
from kijijiapi import *
from wtforms.fields.html5 import DateField, TimeField
from wtforms import SelectField, SelectMultipleField, TextField, TextAreaField, validators, StringField, SubmitField, FieldList, FormField, BooleanField, IntegerField, widgets
from werkzeug.utils import secure_filename
app = Flask(__name__)
# Set Absolute Path
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
# Change this to your secret key (can be anything, it's for extra protection)
app.secret_key = 'your secret key'
# Class Declarations:
# Creates Custom MultiCheckboxField used for Optional Enum Type Attributes
class MultiCheckboxField(SelectMultipleField):
widget = widgets.ListWidget(prefix_label=False)
option_widget = widgets.CheckboxInput()
# Persistent Forms used when Posting Ad
class PostForm(FlaskForm):
class Meta:
csrf = False
adtitle = TextField(id='adtitle', label= 'Ad Title', validators=[validators.DataRequired(), validators.Length(max=64)])
adtype = SelectField(id='adtype', label='Ad Type', choices=[])
cat1 = SelectField(id='cat1', label='Category')
cat2 = SelectField(id='cat2')
cat3 = SelectField(id='cat3')
description = TextAreaField(id='description', label='Description', validators=[validators.DataRequired()])
loc1 = SelectField(id='loc1', label='Location')
loc2 = SelectField(id='loc2')
loc3 = SelectField(id='loc3')
price = TextField(id='price', label='Price')
pricetype = SelectField(id='pricetype', label='Price Type', choices = ['SPECIFIED_AMOUNT', 'PLEASE_CONTACT', 'SWAP_TRADE', 'FREE'])
postalcode = TextField(id='postalcode',label='Postal Code', validators=[validators.DataRequired()])
phone = TextField(id='phone', label='Phone')
file1 = FileField(id='file1', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file2 = FileField(id='file2', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file3 = FileField(id='file3', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file4 = FileField(id='file4', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file5 = FileField(id='file5', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file6 = FileField(id='file6', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file7 = FileField(id='file7', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file8 = FileField(id='file8', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file9 = FileField(id='file9', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
file10 = FileField(id='file10', label='Pictures', validators=[FileAllowed(['jpg', 'jpeg', 'png'], 'Images only!')])
repost = BooleanField(id='repost', label='Repost')
time1 = TimeField(id='time1', label='Time')
time2 = TimeField(id='time2', label='Time')
time3 = TimeField(id='time3', label='Time')
time4 = TimeField(id='time4', label='Time')
time5 = TimeField(id='time5', label='Time')
time6 = TimeField(id='time6', label='Time')
time7 = TimeField(id='time7', label='Time')
time8 = TimeField(id='time8', label='Time')
password = TextField(id='password', label='Password')
class ConversationForm(FlaskForm):
class Meta:
csrf = False
reply = TextAreaField(id='reply', label='Reply', validators=[validators.DataRequired()])
class SearchForm(FlaskForm):
class Meta:
csrf = False
cat1 = SelectField(id='cat1', label='Category')
cat2 = SelectField(id='cat2')
cat3 = SelectField(id='cat3')
postal_code = TextField(id='postal_code', label='Postal Code', validators=[validators.DataRequired(), validators.Length(max=8)])
search = TextField(id='search', label='Search', validators=[validators.DataRequired(), validators.Length(max=64)])
radius = TextField(id='radius', label='Radius', validators=[validators.DataRequired(), validators.Length(max=10)])
# Functions:
def getXML(filename):
#retrievs parsed xml file
with open(filename, 'r') as f:
content = f.read()
f.close()
parsed = xmltodict.parse(content)
return parsed
def timeValidator(time):
# reformats timestamp into valid / usable format
if time != None and time != '':
validTime = time.strftime("%H:%M")
return validTime
else:
return None
def timeSubtractor(time):
if time != None and time != '':
delta = datetime.timedelta(minutes=3)
converted = datetime.datetime.strptime(time,"%H:%M")
minus = (converted - delta).strftime("%H:%M")
return minus
else:
return None
def chooseCategory(cat1, cat2, cat3):
if cat3 != None and cat3 != '':
return cat3
elif (cat3 is None or cat3 == '') and (cat2 != None and cat2 != ''):
return cat2
else:
if cat1 == 'Kijiji Village':
return '36611001'
elif cat1 == 'Buy & Sell':
return '10'
elif cat1 == 'Cars & Vehicles':
return '27'
elif cat1 == 'Real Estate':
return '34'
elif cat1 == 'Jobs':
return '45'
elif cat1 == 'Services':
return '72'
elif cat1 == 'Pets':
return '112'
elif cat1 == 'Community':
return '1'
elif cat1 == 'Vacation Rentals':
return '800'
elif cat1 == 'Free Stuff':
return '17220001'
def chooseLocation(loc1, loc2, loc3):
if loc3 != None and loc3 != '':
return loc3
elif (loc3 is None or loc3 == '') and (loc2 != None and loc2 != ''):
return loc2
elif (loc3 is None or loc3 == '') and (loc2 is None or loc2 == '') and (loc1 != None and loc1 != ''):
return loc1
else:
# default to Canada '0'
return '0'
def picLink(data, session):
if data != None and data != '' and data != b'':
file = data
fileData = file.read()
picLink = picUpload(fileData, session)
return picLink
else:
return None
def testListInstance(data):
if isinstance(data,list):
return True
def testDictInstance(data):
if isinstance(data,dict):
return True
def reposter():
#delete then repost
writeActivate = False
scheduleFile = os.path.join(THIS_FOLDER, 'static/schedules.json')
with open(scheduleFile, 'r') as jsonFile:
data = json.load(jsonFile)
for item in data['schedules']:
# Time Calcualtions
now = datetime.datetime.now()
current_time = now.strftime("%H:%M") #"%H:%M:%S"
try:
# Delete Ad 3 Minutes Before Repost Time
if (timeSubtractor(item['time1']) == current_time) or (timeSubtractor(item['time2']) == current_time) or (timeSubtractor(item['time3']) == current_time) or (timeSubtractor(item['time4']) == current_time) or (timeSubtractor(item['time5']) == current_time) or (timeSubtractor(item['time6']) == current_time) or (timeSubtractor(item['time7']) == current_time) or (timeSubtractor(item['time8']) == current_time):
email = item['useremail']
password = item['userpassword']
adID = item['current_ad_id']
# Retry 20 times if exception raised
tries = 20
for i in range(tries):
try:
# Login
userID, userToken = loginFunction(kijijiSession, email, password)
# Delete Old Ad
deleteAd(kijijiSession, userID, adID, userToken)
print('3 minute delay until repost ', now)
except:
print('Error: Deletion Failed at: ', now)
print('Retry Attempt:', i)
if i < tries - 1: # i is zero indexed
time.sleep(5)
continue
else:
# exit loop if successful
break
# Repost at current time
# Check if Deleted
if (item['time1'] == current_time) or (item['time2'] == current_time) or (item['time3'] == current_time) or (item['time4'] == current_time) or (item['time5'] == current_time) or (item['time6'] == current_time) or (item['time7'] == current_time) or (item['time8'] == current_time):
#repost
email = item['useremail']
password = item['userpassword']
adFile = item['ad_file']
adID = item['current_ad_id']
# Retry 20 times if exception raised
tries = 20
for i in range(tries):
try:
# Login
userID, userToken = loginFunction(kijijiSession, email, password)
# Check if Ad exists, if not, then deletion was successful
exists = adExists(kijijiSession, userID, userToken, adID)
if exists == False:
# Open file / Get payload
with open(adFile, 'r') as f:
payload = f.read()
# Post Ad
parsed = submitFunction(kijijiSession, userID, userToken, payload)
new_adID = parsed['ad:ad']['@id']
# Edit ad id in json file to match new ad id
item['current_ad_id'] = new_adID
writeActivate = True
print('Reposting Completed at: ', now)
except:
print('Error: Reposting Failed at: ', now)
print('Retry Attempt:', i)
if i < tries - 1: # i is zero indexed
time.sleep(5)
continue
else:
# exit loop if successful
break
except:
print('No Valid Schedules Found')
# Write updates to json file if successful reposting has occurred
if writeActivate == True:
print('Updating Schedules')
with open(scheduleFile, 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
def messageAutoReplier():
print('Message Auto Replier: Checking Messages')
messageFile = os.path.join(THIS_FOLDER, 'static/messages.json')
with open(messageFile, 'r') as jsonFile:
data = json.load(jsonFile)
if len(data['users']) != 0:
for user in data['users']:
if len(user['rules']) != 0:
email = user['useremail']
password = user['userpassword']
page = '0' #0 = first 25
# Retry 20 times if exception raised
tries = 20
for i in range(tries):
try:
# Login
userID, userToken = loginFunction(kijijiSession, email, password)
# Get 25 Most recent Conversations
conversations = getConversations(kijijiSession, userID, userToken, page)
except:
now = datetime.datetime.now()
print('Error Auto Replier Unable to Login or Get Conversations at:', now)
print('Retry Attempt:', i)
if i < tries - 1: # i is zero indexed
time.sleep(5)
continue
else:
for rule in user['rules']:
if 'user:user-conversation' in conversations['user:user-conversations']:
# Initialize Reply Variables
direction = ''
replyName = ''
replyEmail = ''
content = ''
conversationID = ''
adID = ''
messageRead = ''
answered = ''
isList = testListInstance(conversations['user:user-conversations']['user:user-conversation'])
# only 1 conversation if not list
if isList == False:
for key, value in conversations['user:user-conversations']['user:user-conversation'].items():
sendMessage = False
unread = False
if key == '@uid':
conversationID = value
if key == 'user:num-unread-msg':
if value != '0':
unread = True
conversation = getConversation(kijijiSession, userID, userToken, conversationID)
adID = conversation['user:user-conversation']['user:ad-id']
ownerUserID = conversation['user:user-conversation']['user:ad-owner-id']
ownerEmail = conversation['user:user-conversation']['user:ad-owner-email']
ownerName = conversation['user:user-conversation']['user:ad-owner-name']
replierUserID = conversation['user:user-conversation']['user:ad-replier-id']
replierEmail = conversation['user:user-conversation']['user:ad-replier-email']
replierName = conversation['user:user-conversation']['user:ad-replier-name']
# Calculate Message Direction
if ownerUserID == userID:
replyName = ownerName
replyEmail = ownerEmail
direction = 'TO_BUYER'
elif replierUserID == userID:
replyName = replierName
replyEmail = replierEmail
direction = 'TO_OWNER'
if key == 'user:user-message':
for element, attribute in value.items():
if element == 'user:msg-content':
content = attribute
if element == 'user:read':
messageRead = attribute
if element == 'user:answered':
answered = attribute
if element == 'user:sender-id':
senderID = attribute
for index, message in rule.items():
#if message in content and unread == True:
if (re.search(r"\b{}\b".format(message), content, re.IGNORECASE) is not None) and unread == True and senderID != userID and answered == 'false':
sendMessage = True
if index == 'response' and sendMessage == True:
reply = message
finalPayload = createReplyPayload(adID, replyName, replyEmail, reply, conversationID, direction)
now = datetime.datetime.now()
sendReply(kijijiSession, userID, userToken, finalPayload)
print('Auto replied', direction, 'in conversation', conversationID, 'at', now)
# Reset Variables for next iteration
sendMessage = False
unread = False
direction = ''
replyName = ''
replyEmail = ''
content = ''
conversationID = ''
adID = ''
messageRead = ''
answered = ''
# multiple conversations
else:
for item in conversations['user:user-conversations']['user:user-conversation']:
sendMessage = False
unread = False
conversationID = item['@uid']
if item['user:num-unread-msg'] != '0':
unread = True
conversation = getConversation(kijijiSession, userID, userToken, conversationID)
adID = conversation['user:user-conversation']['user:ad-id']
ownerUserID = conversation['user:user-conversation']['user:ad-owner-id']
ownerEmail = conversation['user:user-conversation']['user:ad-owner-email']
ownerName = conversation['user:user-conversation']['user:ad-owner-name']
replierUserID = conversation['user:user-conversation']['user:ad-replier-id']
replierEmail = conversation['user:user-conversation']['user:ad-replier-email']
replierName = conversation['user:user-conversation']['user:ad-replier-name']
# Calculate Message Direction
if ownerUserID == userID:
replyName = ownerName
replyEmail = ownerEmail
direction = 'TO_BUYER'
elif replierUserID == userID:
replyName = replierName
replyEmail = replierEmail
direction = 'TO_OWNER'
for element, attribute in item['user:user-message'].items():
messageID = item['user:user-message']['@id']
if element == 'user:msg-content':
content = attribute
if element == 'user:read':
messageRead = attribute
if element == 'user:answered':
answered = attribute
if element == 'user:sender-id':
senderID = attribute
for index, message in rule.items():
#if message in content and unread == True:
if (re.search(r"\b{}\b".format(message), content, re.IGNORECASE) is not None) and unread == True and senderID != userID and answered == 'false':
sendMessage = True
if index == 'response' and sendMessage == True:
reply = message
finalPayload = createReplyPayload(adID, replyName, replyEmail, reply, conversationID, direction)
now = datetime.datetime.now()
sendReply(kijijiSession, userID, userToken, finalPayload)
print('Auto replied', direction, 'in conversation', conversationID, 'at', now)
# Reset Variables for next iteration
sendMessage = False
unread = False
direction = ''
replyName = ''
replyEmail = ''
content = ''
conversationID = ''
adID = ''
messageRead = ''
answered = ''
break
# Create Session with Http2.0 compatability for Kijiji separate from Flask local session
# SSL verification disabled to avoid ConnectionPool Max retries exception
# Need to impliment this in future (httpx module still in alpha)
urllib3.disable_warnings()
timeout = httpx.Timeout(15.0, connect=30.0)
kijijiSession = httpx.Client(verify=False, timeout=timeout)
# Initialize global Variables
# category and location global variables are used to store temporary dynamic data during ad posting
categoriesData = ''
locationsData = ''
# Routes:
# http://localhost:5000/ - this will be the login page, we need to use both GET and POST requests
@app.route('/', methods=['GET', 'POST'])
def login():
# Initialize output message if something goes wrong...
msg = ''
# Check if "email" and "password" POST requests exist (user submitted form)
if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
# Create variables for easy access
email = request.form['email']
password = request.form['password']
try:
userID, userToken = loginFunction(kijijiSession, email, password)
# Create local session data accessible to other routes
session['loggedin'] = True
session['user_id'] = userID
#session['user_email'] = userEmail #redundant
session['user_email'] = email
session['user_token'] = userToken
# Redirect to home page
return redirect(url_for('home'))
except:
# Account doesnt exist or email/password incorrect
msg = 'Unable to Access Kijiji Account'
print('Login Error: Unable to Access Kijiji Account')
return render_template('index.html', msg=msg)
else:
# Show the login form with message (if any)
return render_template('index.html', msg=msg)
# http://localhost:5000/logout - this will be the logout page
@app.route('/logout')
def logout():
# Remove session data, this will log the user out
session.pop('loggedin', None)
session.pop('user_id', None)
session.pop('user_email', None)
session.pop('user_token', None)
# Redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/home - this will be the home page, only accessible for loggedin users
@app.route('/home')
def home():
# Check if user is loggedin
if 'loggedin' in session:
# Retrieve Current Ad List
userID = session['user_id']
token = session['user_token']
parsed = getAdList(kijijiSession, userID, token)
# User is loggedin show them the home page
return render_template('home.html', email = session['user_email'], data=parsed) #, profileData=profileData)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/profile - this will be the profile page, only accessible for loggedin users
@app.route('/profile')
def profile():
# Check if user is loggedin
if 'loggedin' in session:
# Retrieve Profile Data
userID = session['user_id']
token = session['user_token']
parsed = getProfile(kijijiSession, userID, token)
# Show the profile page with account info
return render_template('profile.html', data=parsed)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/ad
@app.route('/ad/<adID>')
def ad(adID):
# Check if user is loggedin
if 'loggedin' in session:
# View Ad from kijiji account
userID = session['user_id']
token = session['user_token']
parsed = getAd(kijijiSession, userID, token, adID)
# Show the profile page with account info
return render_template('ad.html', data=parsed, adID=adID, userID=userID)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/ad
@app.route('/viewad/<adID>')
def viewad(adID):
# Check if user is loggedin
if 'loggedin' in session:
# View Ad from kijiji account
userID = session['user_id']
token = session['user_token']
parsed = getSearchedAd(kijijiSession, userID, token, adID)
form = ConversationForm()
# Show the profile page with account info
return render_template('ad.html', data=parsed, adID=adID, userID=userID, form=form)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/search
@app.route('/search', methods=['GET', 'POST'])
def search():
# Check if user is loggedin
if 'loggedin' in session:
# Search for an Ad - Stage 1 - Select Category
userID = session['user_id']
token = session['user_token']
global categoriesData
categoriesData = getCategories(kijijiSession, userID, token)
choiceList = []
for x in categoriesData['cat:categories']['cat:category']['cat:category']:
choiceList.append(x['cat:id-name'])
form = SearchForm()
form.cat1.choices = choiceList
return render_template('search.html', form=form)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/results
@app.route('/results', methods=['GET', 'POST'])
def results():
# Check if user is loggedin
if 'loggedin' in session:
userID = session['user_id']
token = session['user_token']
# reset category data
global categoriesData
categoriesData = ''
form = SearchForm()
catChoice = chooseCategory(form.cat1.data, form.cat2.data, form.cat3.data)
postal_code = checkPostalCodeLength(form.postal_code.data)
nomi = pgeocode.Nominatim('ca')
location = nomi.query_postal_code(postal_code)
# need to add category field to narrow results
searched = searchFunction(kijijiSession, userID, token, location.longitude, location.latitude, '100', postal_code, '0', form.radius.data, catChoice, form.search.data)
class Results:
def __init__(self, id, price, title, description, address, seller_id, pics, cover_img):
self.id = id
self.price = price
self.title = title
self.description = description
self.address = address
self.seller_id = seller_id
self.pics = pics
self.cover_img = cover_img
searchResults = []
try:
for results in searched['ad:ads']['ad:ad']:
id = ''
price = ''
title = ''
description = ''
address = ''
seller_id = ''
pics = []
cover_img = ''
for key, value in results.items():
if key == '@id':
id = value
if key == 'ad:price':
for element, attribute in value.items():
if element == 'types:amount':
price = attribute
if key == 'ad:title':
title = value
if key == 'ad:description':
description = value
if key == 'ad:ad-address':
for element, attribute in value.items():
if element == 'types:full-address':
address = attribute
if key == 'ad:user-id':
seller_id = value
if key == 'pic:pictures':
try:
for item in value['pic:picture']:
for element, attribute in item.items():
for sub_element in attribute:
for sub_key, sub_value in sub_element.items():
if sub_key == '@href':
pics.append(sub_value)
except:
pass
try:
for item in value['pic:picture']['pic:link']:
for key, value in item.items():
if key == '@href':
pics.append(value)
except:
pass
for item in pics:
if '$_14' in item:
cover_img = item
break
#sort pic list for cover image. fix class to contain single image for imparse in jinja
searchResults.append(Results(id, price, title, description, address, seller_id, pics, cover_img))
except:
print('Search Failed or No Results Returned')
return render_template('results.html', data=searchResults)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
# http://localhost:5000/post
@app.route('/post', methods=['GET', 'POST'])
def post():
# Check if user is loggedin
if 'loggedin' in session:
# Post An Ad - Stage 1 - Select Category
userID = session['user_id']
token = session['user_token']
global categoriesData
categoriesData = getCategories(kijijiSession, userID, token)
choiceList = []
for x in categoriesData['cat:categories']['cat:category']['cat:category']:
choiceList.append(x['cat:id-name'])
form = PostForm()
form.cat1.choices = choiceList
return render_template('post.html', form=form)
else:
# User is not loggedin redirect to login page
return redirect(url_for('login'))
@app.route('/submit', methods=['GET', 'POST'])
def submit():
if 'loggedin' in session:
# Submit Ad for Posting - Final Stage
#reset locationsData
global locationsData
locationsData = ''
# Need to get name from profile
userID = session['user_id']
token = session['user_token']
parsed = getProfile(kijijiSession, userID, token)
session['user_displayname'] = parsed['user:user-profile']['user:user-display-name']
# Process Form Data
form = PostForm()
attributes = {}
attributesPayload = {}
picturesPayload = {}
remainders = {}
locChoice = chooseLocation(form.loc1.data, form.loc2.data, form.loc3.data)
# get submitted form items
f = request.form
for key in f.keys():
for value in f.getlist(key):
# gather attributes (AttributeForm items)
# filter out persistent form items to determine dynamic attributes
if key != 'adtype' and key != 'adtitle' and key != 'cat1' and key != 'cat2' and key != 'cat3' and key != 'description' and key != 'pricetype' and key != 'price' and key != 'loc1' and key != 'loc2' and key != 'loc3' and key != 'postalcode' and key != 'phone' and key != 'file1' and key != 'file2' and key != 'file3' and key != 'file4' and key != 'file5' and key != 'file6' and key != 'file7' and key != 'file8' and key != 'file9' and key != 'file10' and key != 'repost' and key != 'time1' and key != 'time2' and key != 'time3' and key != 'time4' and key != 'time5' and key != 'time6' and key != 'time7' and key != 'time8' and key != 'password':
# For Multipart Attributes like MultiCheckbox Enum
if key in attributes:
oldKey = attributes[key]
attributes[key] = oldKey + ',' + value
# For Standard Enum Attributes
if key not in attributes:
attributes[key] = value
# gathter PostForm items
else:
remainders[key] = value
# Build Attributes Payload
if len(attributes) != 0:
attributesPayload = {'attr:attributes':{'attr:attribute': []}}
for key, value in attributes.items():
# Correct BOOLEAN Attritubes into correct formatting for kijiji
if value == True or value == 'y':
attributesPayload['attr:attributes']['attr:attribute'].append({'@type': '', '@localized-label': '', '@name': key, 'attr:value': 'true'})
# If above conditions do not apply, and value is not None, append attribute
if (value != True or value != 'y') and (value != False or value != 'n') and (value != None and value != ''):
attributesPayload['attr:attributes']['attr:attribute'].append({'@type': '', '@localized-label': '', '@name': key, 'attr:value': value})
# set xml type variable for Date based attributes
if 'date' in key:
attributesPayload['attr:attributes']['attr:attribute'].append({'@type': 'DATE', '@localized-label': '', '@name': key, 'attr:value': value+'T00:00:00Z'})
# Collect items from remainders
#Variable initialization
adtitle = ''
description = ''
adtype = ''
postalcode = ''
fulladdress = ''
pricetype = ''
price = ''
fileData1 = b''
fileData2 = b''
fileData3 = b''
fileData4 = b''
fileData5 = b''
fileData6 = b''
fileData7 = b''
fileData8 = b''
fileData9 = b''
fileData10 = b''
pic1Link = ''
pic2Link = ''
pic3Link = ''
pic4Link = ''
pic5Link = ''
pic6Link = ''
pic7Link = ''
pic8Link = ''
pic9Link = ''
pic10Link = ''
adID = ''
# put remainig form data into appropriate variables
for key, value in remainders.items():
if key == 'adtitle':
adtitle = value
elif key == 'description':
description = value
elif key == 'adtype':
adtype = value
elif key == 'postalcode':
postalcode = value
elif key == 'fulladdress': # still yet to be implimented
fulladdress = value
elif key == 'pricetype':
pricetype = value
elif key == 'price':
price = value
# Begin assembling entire Payload
responsePayload = {
'ad:ad': {
'@xmlns:types': 'http://www.ebayclassifiedsgroup.com/schema/types/v1',
'@xmlns:cat': 'http://www.ebayclassifiedsgroup.com/schema/category/v1',
'@xmlns:loc': 'http://www.ebayclassifiedsgroup.com/schema/location/v1',
'@xmlns:ad': 'http://www.ebayclassifiedsgroup.com/schema/ad/v1',
'@xmlns:attr': 'http://www.ebayclassifiedsgroup.com/schema/attribute/v1',
'@xmlns:pic': 'http://www.ebayclassifiedsgroup.com/schema/picture/v1',
'@xmlns:user': 'http://www.ebayclassifiedsgroup.com/schema/user/v1',
'@xmlns:rate': 'http://www.ebayclassifiedsgroup.com/schema/rate/v1',
'@xmlns:reply': 'http://www.ebayclassifiedsgroup.com/schema/reply/v1',
'@locale': 'en-CA'}}
if adtitle != None and adtitle != '':
responsePayload['ad:ad'].update({'ad:title': adtitle})
if description != None and description != '':
responsePayload['ad:ad'].update({'ad:description': description})
if locChoice != None and locChoice != '':
responsePayload['ad:ad'].update({'loc:locations': {'loc:location': {'@id': locChoice}}})
if adtype != None and adtype != '':
responsePayload['ad:ad'].update({'ad:ad-type': {'ad:value': adtype}})
if session['cat'] != None and session['cat'] != '':
responsePayload['ad:ad'].update({'cat:category': {'@id': session['cat']}})
if session['user_email'] != None and session['user_email'] != '':
responsePayload['ad:ad'].update({'ad:email': session['user_email']})
if session['user_displayname'] != None and session['user_displayname'] != '':
responsePayload['ad:ad'].update({'ad:poster-contact-name': session['user_displayname']})
if session['user_id'] != None and session['user_id'] != '':
responsePayload['ad:ad'].update({'ad:account-id': session['user_id']})
if (postalcode != None and postalcode != '') or (fulladdress != None and fulladdress != ''):
responsePayload['ad:ad'].update({'ad:ad-address': {}})
# Generate GeoLocation
postal_code = checkPostalCodeLength(postalcode)
nomi = pgeocode.Nominatim('ca')
location = nomi.query_postal_code(postal_code)
if fulladdress != None and fulladdress != '':
responsePayload['ad:ad']['ad:ad-address'].update({'types:full-address': fulladdress})
if postalcode != None and postalcode != '':
responsePayload['ad:ad']['ad:ad-address'].update({'types:zip-code': postalcode})
responsePayload['ad:ad']['ad:ad-address'].update({'types:longitude': location.longitude})
responsePayload['ad:ad']['ad:ad-address'].update({'types:latitude': location.latitude})
responsePayload['ad:ad'].update({'ad:visible-on-map': 'true'})
if (pricetype != None and pricetype != '') or (price != None and price != ''):
responsePayload['ad:ad'].update({'ad:price': {}})
if pricetype != None and pricetype != '':
responsePayload['ad:ad']['ad:price'].update({'types:price-type':{'types:value': pricetype}})
if price != None and price != '':
responsePayload['ad:ad']['ad:price'].update({'types:amount': price})
# add attributes payload if attributes payload exist
if len(attributesPayload) != 0:
responsePayload['ad:ad'].update(attributesPayload)
# Verify and Upload Pictures
# Retreive Uploaded Picure Link
# picLink function calls #picUpload function
if (form.file1.data != None and form.file1.data != '' and form.file1.data != b'') or (form.file2.data != None and form.file2.data != '' and form.file2.data != b'') or (form.file3.data != None and form.file3.data != '' and form.file3.data != b'') or (form.file4.data != None and form.file4.data != '' and form.file4.data != b'') or (form.file5.data != None and form.file5.data != '' and form.file5.data != b'') or (form.file6.data != None and form.file6.data != '' and form.file6.data != b'') or (form.file7.data != None and form.file7.data != '' and form.file7.data != b'') or (form.file8.data != None and form.file8.data != '' and form.file8.data != b'') or (form.file9.data != None and form.file9.data != '' and form.file9.data != b'') or (form.file10.data != None and form.file10.data != '' and form.file10.data != b''):
pic1Link = picLink(form.file1.data, kijijiSession)
pic2Link = picLink(form.file2.data, kijijiSession)
pic3Link = picLink(form.file3.data, kijijiSession)
pic4Link = picLink(form.file4.data, kijijiSession)
pic5Link = picLink(form.file5.data, kijijiSession)
pic6Link = picLink(form.file6.data, kijijiSession)
pic7Link = picLink(form.file7.data, kijijiSession)
pic8Link = picLink(form.file8.data, kijijiSession)
pic9Link = picLink(form.file9.data, kijijiSession)
pic10Link = picLink(form.file10.data, kijijiSession)
# Create Picture Payload
if (pic1Link != None and pic1Link != '') or (pic2Link != None and pic2Link != '') or (pic3Link != None and pic3Link != '') or (pic4Link != None and pic4Link != '') or (pic5Link != None and pic5Link != '') or (pic6Link != None and pic6Link != '') or (pic7Link != None and pic7Link != '') or (pic8Link != None and pic8Link != '') or (pic9Link != None and pic9Link != '') or (pic10Link != None and pic10Link != ''):
picturesPayload = {'pic:pictures':{'pic:picture': []}}
if pic1Link != None and pic1Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic1Link}})
if pic2Link != None and pic2Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic2Link}})
if pic3Link != None and pic3Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic3Link}})
if pic4Link != None and pic4Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic4Link}})
if pic5Link != None and pic5Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic5Link}})
if pic6Link != None and pic6Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic6Link}})
if pic7Link != None and pic7Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic7Link}})
if pic8Link != None and pic8Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic8Link}})
if pic9Link != None and pic9Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic9Link}})
if pic10Link != None and pic10Link != '':
picturesPayload['pic:pictures']['pic:picture'].append({'pic:link': { '@rel': 'saved', '@href': pic10Link}})
# add attributes payload if attributes payload exist
if len(picturesPayload) != 0:
responsePayload['ad:ad'].update(picturesPayload)
# Parse final payload into XML
finalPayload = xmltodict.unparse(responsePayload, short_empty_elements=True, pretty=True)
# Debug Option to evaluate Submissions
# if debugMode = True, will not submit final payload
# and instead prints to console for evaluation
debugMode = False
if debugMode == True:
print(finalPayload)
if debugMode == False:
# Submit Final Payload
parsed = submitFunction(kijijiSession, userID, token, finalPayload)
# Retreive Ad ID# for newly posted Ad
adID = parsed['ad:ad']['@id']
# Create Repost Data
if form.repost.data == True:
# check if user path exists
# if not create it
# write ad file to user directory
path = 'user/' + session['user_id']
userDir = os.path.exists(path)
if userDir == True:
# write ad to file
with open(path + '/' + adID + '.xml', 'w') as w:
w.write(finalPayload)
else:
#create directory
os.makedirs(path)
#write ad to file
with open(path + '/' + adID + '.xml', 'w') as w:
w.write(finalPayload)
# Update schedules.json with repost information
useremail = session['user_email']
userpassword = form.password.data