-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabaseMethods.py
1235 lines (1017 loc) · 44.4 KB
/
databaseMethods.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
# Handles methods for the database
import csv
from re import search
from unicodedata import name
import uuid
from statisticMethods import calculateXP, sortUsersOnLeaderBoard
import datetime
from encryption import readKey, encrypt, decrypt
from sendEmail import sendEmail
from urllib.parse import quote
import hashlib
key = readKey()
def generateNewID (fileToRead) :
highestID = 0
# For every line in the file, if the ID is bigger than the highest ID, set the highestID to the ID found
with open(fileToRead, 'r') as file:
if file == "" :
return 1
else:
for line in file:
if len(line) != 1 :
# The first collum will be the ID
if int(line.split(",")[0]) > highestID:
highestID = int(line.split(",")[0])
# The new user ID is 1 bigger than the highest ID used
return highestID + 1
# Add a user to the database
def addUserToDatabase(username, password, email) :
# Generate a unique user ID
userID = generateNewID("database/users.csv")
with open("database/users.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([userID, username, password, "0", "0", "0", email])
csvfile.close()
# Find a user by their username(1st position in csv file starting from 0) or password (2nd position in csv file)
def searchUsers(searchTerm, collumn, useEncryption) :
matchFound = False
# For every line in users.csv
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
# If the collumn(th) position of the array line = searchTerm (If search term found)
if (len(line) != 0) :
print (decrypt(line[collumn], key))
if useEncryption == True:
if (decrypt(line[collumn], key) == searchTerm) :
matchFound = True
csvfile.close()
# Return the line found
return line
elif (line[collumn] == searchTerm) :
matchFound = True
csvfile.close()
# Return the line found
return line
# If no match found
if (matchFound == False) :
csvfile.close()
return "False"
# Find a chatroom detail by the chatroomName
def locateChatroomCollumn(searchTerm, collumn) :
matchFound = False
# For every line in users.csv
with open("database/chatrooms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
# If the collumn(th) position of the array line = searchTerm (If search term found)
if (line[collumn] == searchTerm) :
matchFound = True
csvfile.close()
# Return the line found
return line
# If no match found
if (matchFound == False) :
csvfile.close()
return "False"
def createChatroom(name, language, username, chatroomType) :
# Generate a unique chatroom ID
chatroomID = generateNewID("database/chatrooms.csv")
# Find the user's userID from their username - we can assume that the userID will be found since the username is passed from a cookie, only created if a user has successfully logged in and thus
# has their details uploaded to the users.csv file
userID = searchUsers(username, 1, True)[0]
#Add the user to the chatroomUsers.csv file
with open("database/chatroomUsers.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([userID, chatroomID])
csvfile.close()
# Add the database to the chatrooms.csv file:
with open("database/chatrooms.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([chatroomID, language, name, chatroomType])
csvfile.close()
# Find the chatrooms which username has joined
def findChatroomsJoined(username) :
chatroomsJoined = []
ChatroomDetails = []
# Convert username to a userID
userID = searchUsers(username, 1, True)[0]
# Search chatroomUsers.csv to find all the chatrooms which userID has joined
with open("database/chatroomUsers.csv", "r") as csvfile:
# For every line in the csv file
csvreader = csv.reader(csvfile)
for line in csvreader:
if (line[0] == userID) :
# Append the database ID to databases joined
chatroomsJoined.append(line[1])
csvfile.close()
# Find the name and language of every chatroom in chatroomsJoined
with open("database/chatrooms.csv", "r") as csvfile:
# For every line in the file:
csvreader = csv.reader(csvfile)
for line in csvreader:
# Look at every chatroomID in chatroomsJoined
for chatroom in range (0, len(chatroomsJoined)):
# If the line in chatrooms.csv being viewed describes a database which the user has joined
if (line[0] == chatroomsJoined[chatroom]) :
# Append the name and language of the chatroom to chatroom details
ChatroomDetails.append(line[1])
ChatroomDetails.append(line[2])
return ChatroomDetails
def searchChatrooms() :
# Get an array of all the chatrooms which have been created
chatrooms = []
# Open the file in read mode
with open("database/chatrooms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For each line in the file
for line in csvreader :
# Add the chatroom name
chatrooms.append(line[2])
return chatrooms
# Return a list of all the chatrooms which have not been joined by the user
def findPublicChatroomsNotJoinedByUser(username) :
chatroomIDs = []
chatroomNames = []
chatroomsJoined = []
# Convert username to a userID
userID = searchUsers(username, 1, True)[0]
# Search chatroomUsers.csv to find all the chatrooms which userID has joined
with open("database/chatroomUsers.csv", "r") as csvfile:
# For every line in the csv file
csvreader = csv.reader(csvfile)
for line in csvreader:
if (line[0] == userID):
# Append the database ID to databases joined
chatroomsJoined.append(line[1])
csvfile.close()
# Open the file in read mode
# chatroomUsers.csv is stored as userID, chatroomID
with open("database/chatrooms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For each line in the file
for line in csvreader :
chatroomIsAlreadyAdded = False
# If the chatroom has not already been added
for i in range(0, len(chatroomIDs)) :
if chatroomIDs[i] == line[0] :
chatroomIsAlreadyAdded = True
if chatroomIsAlreadyAdded == False:
# If it is not owned by the user
chatroomAlreadyJoined = False
for x in range(0, len(chatroomsJoined)) :
if line[0] == chatroomsJoined[x] :
chatroomAlreadyJoined = True
if chatroomAlreadyJoined == False:
# Add the chatroom ID
if line[3] == "public" :
chatroomIDs.append(line[0])
chatroomNames.append(line[2])
return chatroomNames
# Return a list of all the chatrooms which have not been joined by the user
def findPrivateChatroomsNotJoinedByUser(username) :
chatroomIDs = []
chatroomNames = []
chatroomsJoined = []
# Convert username to a userID
userID = searchUsers(username, 1, True)[0]
# Search chatroomUsers.csv to find all the chatrooms which userID has joined
with open("database/chatroomUsers.csv", "r") as csvfile:
# For every line in the csv file
csvreader = csv.reader(csvfile)
for line in csvreader:
if (line[0] == userID):
# Append the database ID to databases joined
chatroomsJoined.append(line[1])
csvfile.close()
# Open the file in read mode
# chatroomUsers.csv is stored as userID, chatroomID
with open("database/chatrooms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For each line in the file
for line in csvreader :
chatroomIsAlreadyAdded = False
# If the chatroom has not already been added
for i in range(0, len(chatroomIDs)) :
if chatroomIDs[i] == line[0] :
chatroomIsAlreadyAdded = True
if chatroomIsAlreadyAdded == False:
# If it is not owned by the user
chatroomAlreadyJoined = False
for x in range(0, len(chatroomsJoined)) :
if line[0] == chatroomsJoined[x] :
chatroomAlreadyJoined = True
if chatroomAlreadyJoined == False:
# Add the chatroom ID
if line[3] == "private" :
chatroomIDs.append(line[0])
chatroomNames.append(line[2])
return chatroomNames
def addUserToChatroom (username, chatroomName) :
# Convert username to the userID
userID = searchUsers(username, 1, True)[0]
# Convert chatroom name to the chatroomID
chatroomID = locateChatroomCollumn(chatroomName, 2)[0]
# Add the userID and chatroomID to the chatroomUsers.csv file
with open("database/chatroomUsers.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([userID, chatroomID])
csvfile.close()
# Add an amount of xp to a user's profile
# note in users.csv, element 3 = total xp and element 4 is streak length, and element 5 is the xp for the given week
def addXPToUser(XP, user) :
# Convert username to a userID
userID = searchUsers(user, 1, True)[0]
userDetails = [[]]
# For every line in users.csv
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
#If the line is not blank
if (len(line) != 0) :
# If the current line contains the information for user
if (line[0] == userID) :
# Add XP to the current XP value
line[3] = str(int(line[3]) + XP)
# Also add xp to the weekly xp value
line[5] = str(int(line[5]) + XP)
userDetails.append(line)
else :
userDetails.append(line)
csvfile.close()
# Replace users.csv with the new edited data in userDetails
with open("database/users.csv", "w") as csvfile:
csvwriter = csv.writer(csvfile)
for i in range(0, len(userDetails)):
csvwriter.writerow(userDetails[i])
csvfile.close()
# Uploads a message to chatroommessages.csv
def uploadMessage(message, chatroomName, user) :
# Convert chatroom name to the chatroomID
chatroomID = locateChatroomCollumn(chatroomName, 2)[0]
messagesList = [[]]
i = 0
xpGained = calculateXP(message)
addXPToUser(xpGained, user)
# Messages are in the format: chatroomID, message
# Save the file to memerory
with open("database/chatroomMessages.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For each line in the file
for line in csvreader :
# If line does not equal nothing
if (len(line) != 0) :
messagesList.append(line)
csvfile.close()
messagesList.append([chatroomID, message, encrypt(user, key)])
# Replace chatroomMessages.csv with the data in messages
with open("database/chatroomMessages.csv", "w") as csvfile:
csvwriter = csv.writer(csvfile)
for i in range(0, len(messagesList)):
csvwriter.writerow(messagesList[i])
csvfile.close()
def readChatroomMessages(chatroomName, numberOfMessages) :
# Convert chatroom name to the chatroomID
chatroomID = locateChatroomCollumn(chatroomName, 2)[0]
messagesList = []
# For every line in chatroomMessages.csv
with open("database/chatroomMessages.csv", "r") as csvfile :
csvreader = csv.reader(csvfile)
for line in csvreader :
# If line is not blank
if (len(line) != 0) :
# If the current line stores the data for chatroomID
if (line[0] == chatroomID) :
# Store the sender and message in line to message list
message = decrypt(line[1], key)
sender = decrypt(line[2], key)
messagesList.append(message + "#" + sender)
# If there are less than or equal to 10 messages, return all of them
# Otherwise, return the 10 most recent messages
if len(messagesList) <= numberOfMessages :
return messagesList
else :
return messagesList[-numberOfMessages:]
# Run when a messages is sent - increment the streak data for the user
def increaseStreak(user) :
# Convert username to a userID
userID = searchUsers(user, 1, True)[0]
userDetails = [[]]
# Increase the streak
# Open the users.csv file where element 3 = total xp and element 4 is streak length, and element 5 is the xp for the given week
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in csvreader
for line in csvreader:
#If the line is not blank
if (len(line) != 0) :
# If the current line contains the information for user
if (line[0] == userID) :
# Add XP to the current XP value
line[4] = str(int(line[4]) + 1)
userDetails.append(line)
else :
userDetails.append(line)
csvfile.close()
# Replace the text in users.csv with the data in userDetails
with open("database/users.csv", "w") as csvfile:
csvwriter = csv.writer(csvfile)
for i in range(0, len(userDetails)):
# If the line is not blank
print ("userdetails" + str(userDetails[i]))
if (userDetails[i] != []) :
# Add the line to users.csv
csvwriter.writerow(userDetails[i])
csvfile.close()
# Reset the streak back to zero
def resetStreak(user) :
# Convert username to a userID
userID = searchUsers(user, 1, True)[0]
userDetails = [[]]
# Increase the streak
# Open the users.csv file where element 3 = total xp and element 4 is streak length, and element 5 is the xp for the given week
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in csvreader
for line in csvreader:
#If the line is not blank
if (len(line) != 0) :
# If the current line contains the information for user
if (line[0] == userID) :
# Add XP to the current XP value
line[4] = "0"
userDetails.append(line)
else :
userDetails.append(line)
csvfile.close()
# Replace the text in users.csv with the data in userDetails
with open("database/users.csv", "w") as csvfile:
csvwriter = csv.writer(csvfile)
for i in range(0, len(userDetails)):
# If the line is not blank
print ("userdetails" + str(userDetails[i]))
if (userDetails[i] != []) :
# Add the line to users.csv
csvwriter.writerow(userDetails[i])
csvfile.close()
# Returns the user's streak
def findStreak(user) :
# Convert username to a userID
userID = searchUsers(user, 1, True)[0]
streak = 0
# Open the users.csv file
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in users.csv
for line in csvreader:
# If the line is not blank
if (len(line) != 0) :
# If the line contains the details for user
if (line[0] == userID) :
# Save the user's streak
streak = line[4]
csvfile.close()
return streak
# Check if the weekly xp count needs to be reset. If so, reset if
def checkIfWeeklyXPNeedsReset(lastResetYear, lastResetMonth, lastResetDay, user) :
# Convert username to a userID
userID = searchUsers(user, 1, True)[0]
reset = False
userDetails = [[]]
# Convert the last reset year, month and day to datetime format
lastReset = datetime.datetime(int(lastResetYear), int(lastResetMonth), int(lastResetDay))
# Get the current date
date = datetime.datetime.now()
# Find how long ago the last streak was
delta = date - lastReset
# If the last reset was more that a week ago
if (delta.days > 6) :
# Open the users.csv file where element 3 = total xp and element 4 is streak length, and element 5 is the xp for the given week
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in csvreader
for line in csvreader:
#If the line is not blank
if (len(line) != 0) :
# If the current line contains the information for user
if (line[0] == userID) :
# Reset the streak
line[5] = "0"
userDetails.append(line)
reset = True
else :
userDetails.append(line)
csvfile.close()
# Replace the text in users.csv with the data in userDetails
with open("database/users.csv", "w") as csvfile:
csvwriter = csv.writer(csvfile)
for i in range(0, len(userDetails)):
# If the line is not blank
print ("userdetails" + str(userDetails[i]))
if (userDetails[i] != []) :
# Add the line to users.csv
csvwriter.writerow(userDetails[i])
csvfile.close()
return reset
# Return a list of users sorted by their weekly xp in the format: user, xp, user, xp...
def sortUsersByXP() :
users = []
usersXP = []
# Fill users and usersXP with the relevant data
# Open the users.csv file
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in the file
for line in csvreader:
# If the line is not blank
if (len(line) != 0) :
# Store the username in users
users.append(decrypt(line[1], key))
# Store the user's xp in usersXP
usersXP.append(line[5])
# Using usersXP, sort users and usersXP in descending order and return th given array - in format user, xp, user, xp...
return sortUsersOnLeaderBoard(users, usersXP)
def findWeeklyXP (username) :
# Convert username to the userID
userID = searchUsers(username, 1, True)[0]
with open("database/users.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
# For every line in the file
for line in csvreader:
if len(line) != 0:
if (line[0] == userID) :
return line[5]
return "* weekly xp could not be calculated *"
def sendNotification(message, chatroom, user, url) :
# Get the email addresses of all people in the chatroom
# Except the user who sent the message
# Then send them the email
usersInTheChatroom = []
userIDWHoSentMessage = ""
chatroomID = ""
emailAddresses = []
# Get the userID of user
userID = searchUsers(user, 1, True)[0]
# Get the ID of the chatroom
with open("database/chatrooms.csv", "r") as chatrooms:
for line in chatrooms:
# The chatroom may have "\n" added on the end - a newline
if line.split(",")[2] == chatroom or line.split(",")[2] == chatroom + "\n":
chatroomID = line.split(",")[0]
# Find all the users who are in the chatroom except user
with open("database/chatroomUsers.csv", "r") as chatroomUsers:
for line in chatroomUsers:
# Remove whitespace
line = line.rstrip("\n")
if line.split(",")[1] == chatroomID and line.split(",")[0] != userID:
usersInTheChatroom.append(line.split(",")[0])
# Find the email addresses of all these users
with open("database/users.csv", "r") as users:
for line in users:
# Remove whitespace
line = line.rstrip("\n")
for chatroomUser in usersInTheChatroom :
if line.split(",")[0] == chatroomUser:
emailAddresses.append(decrypt(line.split(",")[6], key))
# Send the emails
for address in emailAddresses:
if address != "NULL" :
body = """You have a new message in a chatroom!
Someone said, '""" + message + """'
Want to view the message? Go to """ + url + "?chatroomName=" + quote(chatroom)
sendEmail(address, "You have a new message", body)
def updateUserDetails(oldUsername, newUsername, password, email) :
updatedFile = []
# Look through every line in users.csv
# If the old username is found, update the password and email address
# If not, append the line to a csv file
with open("database/users.csv", "r") as file:
csvreader = csv.reader(file)
for line in csvreader:
# If the line contains whitespace
if len(line) != 0:
if decrypt(line[1], key) == oldUsername:
line[1] = newUsername
line[2] = password
line[6] = email
# Save the data to the file array, turning it into a string seperated by a comma
updatedFile.append(",".join(line))
# Read updatedFile into the users.csv file, rewriting it
with open("database/users.csv", "w") as file:
for line in updatedFile:
file.write(line + "\n")
# Create a new flashcard set
def createFlashcardSet(username, name, description) :
# Generate a flashcard ID
flashcardID = generateNewID("database/flashcards.csv")
# Find the user ID
userID = searchUsers(username, 1, True)[0]
# Save flashcardID, userID to flashcardOwners.csv
with open("database/flashcardsOwners.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([flashcardID, userID])
csvfile.close()
# Save flashcardID, name, description to flashcards.csv
with open("database/flashcards.csv", "a") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow([flashcardID, name, description])
csvfile.close()
# Check if the user owns the flashcard set
def checkFlashcardSetOwnership(username, flashcardName) :
# Find the user ID
userID = searchUsers(username, 1, True)[0]
# Find the flashcard ID
flashcardID = ""
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
flashcardID = line[0]
csvfile.close()
# See if userID owns flashcardID by searching flashcardsOwners.csv
with open("database/flashcardsOwners.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] == flashcardID and line[1] == userID:
return True
csvfile.close()
return False
# Find the cards in a flashcard set
def findCardsInFlashcardSet(flashcardName) :
flashcardTerms = []
# Find the flashcard ID
flashcardID = ""
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
flashcardID = line[0]
csvfile.close()
# Find the cards in the flashcard set
with open("database/flashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] == flashcardID:
flashcardTerms.append(line[1] + "#" + line[2])
csvfile.close()
return flashcardTerms
# Find the cards in an uploaded flashcard set
def findCardsInUploadedFlashcardSet(flashcardName) :
flashcardTerms = []
# Find the flashcard ID
flashcardID = ""
with open("database/uploadedFlashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
flashcardID = line[0]
csvfile.close()
# Find the cards in the flashcard set
with open("database/uploadedFlashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] == flashcardID:
flashcardTerms.append(line[1] + "#" + line[2])
csvfile.close()
return flashcardTerms
# Replace the cards in a flashcard set with the values given in the parameter
def replaceCardsInFlashcardSet(flashcardName, cards) :
# Turn cards into an array - takes term1/definition1,term2,definition2
cards = cards.split(",")
cardsToRemove = []
# Remove all items from array which have a value of ""
for i in range(0, len(cards)) :
if cards[i] == "" :
cardsToRemove.append(i)
for i in range(0, len(cardsToRemove)) :
cards.pop(cardsToRemove[i])
flashcards = []
# Find the flashcard ID
flashcardID = ""
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
flashcardID = line[0]
csvfile.close()
# Find the cards in the flashcard set that do not have the ID of flashcardID
with open("database/flashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] != flashcardID:
flashcards.append(line[0] + "," + line[1] + "," + line[2])
csvfile.close()
# Add the edited cards to the flashcards array
for i in range(0, len(cards)):
flashcards.append(flashcardID + "," + cards[i].split("/")[0] + "," + cards[i].split("/")[1])
# Rewrite the flashcardTerms.csv file
with open("database/flashcardTerms.csv", "w") as csvfile:
for line in flashcards:
csvfile.write(line + "\n")
csvfile.close()
# Find flashcards owned by the username
def findFlashcardsOwnedByUser(username) :
flashcardIDs = []
flashcardNames = []
# Get user ID from username
userID = searchUsers(username, 1, True)[0]
# Search flashcardsOwners.csv
with open("database/flashcardsOwners.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
# If the user ID is found, get the flashcard ID and add to flashcard ID array
if line[1] == userID:
flashcardIDs.append(line[0])
csvfile.close()
# Search flashcards.csv for the flashcard ID and add the flashcard name to an array
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] in flashcardIDs:
flashcardNames.append(line[1])
csvfile.close()
return flashcardNames
# Upload a flashcard set
def uploadFlashcardSet(flashcardName) :
# Create an ID for the uploaded flashcard set
flashcardID = str(generateNewID("database/uploadedFlashcards.csv"))
localFlashcardID = ""
# Copy the flashcard data in flashcards.csv to uploadedFlashcards.csv
# Find the description of the flashcard set
description = ""
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
description = line[2]
localFlashcardID = line[0]
csvfile.close()
# Look at uploadedFlashcards.csv. If the name has not been used, append it
uploadedFlashcards = []
nameUsed = False
with open("database/uploadedFlashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
# If the name has been used, just edit the description
uploadedFlashcards.append(line[0] + "," + line[1] + "," + description)
nameUsed = True
flashcardID = line[0]
else :
uploadedFlashcards.append(line[0] + "," + line[1] + "," +line[2])
csvfile.close()
# If name has not been used, append the new set to the array
if nameUsed == False:
uploadedFlashcards.append(flashcardID + "," + flashcardName + "," + description)
# Rewrite the uploadedFlashcards.csv file
with open("database/uploadedFlashcards.csv", "w") as csvfile:
for line in uploadedFlashcards:
csvfile.write(line + "\n")
csvfile.close()
# Copy the flashcard data in flashcardTerms.csv to uploadedFlashcardTerms.csv
# Get the flashcard terms belonging to the flashcard set
terms = []
with open("database/flashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] == localFlashcardID:
terms.append(line[1] + "," + line[2])
csvfile.close()
newFile = []
# If the flashcard set has not been added before
if nameUsed == False:
# Add the flashcard terms to uploadedFlashcardTerms.csv
with open("database/uploadedFlashcardTerms.csv", "a") as csvfile:
writer = csv.writer(csvfile)
for line in terms:
writer.writerow([flashcardID, line.split(",")[0], line.split(",")[1]])
csvfile.close()
# If the flashcard set has been added before
else :
count = 0
with open("database/uploadedFlashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
# If the data does not belong to the flashcard set, add it to the new file
if line[0] != flashcardID:
newFile.append(line[0] + "," + line[1] + "," + line[2])
else:
# If the data belongs to the flashcard set
newFile.append(line[0] + "," + terms[count])
count = count + 1
csvfile.close()
# If there are any more items in terms that haven't been added yet, add them
if count < len(terms) :
for i in range(count, len(terms)):
newFile.append(flashcardID + "," + terms[i])
# Rewrite uploadedFlashcardTerms.csv with the data in newFile
with open("database/uploadedFlashcardTerms.csv", "w") as csvfile:
for line in newFile:
csvfile.write(line + "\n")
csvfile.close()
# Find all the flashcard templates added and return an array of their names
def findFlashcardTemplates() :
flashcardNames = []
# Search uploadedFlashcards.csv and add the names to the array
with open("database/uploadedFlashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
flashcardNames.append(line[1])
csvfile.close()
return flashcardNames
# Find a name to save the flashcard set as when cloning it - recursive
def findNameForClonedFlashcardSet(templateName, number) :
nameUsed = False
nameToCheck = templateName + str(number)
# Look at all the flashcards added
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
# If the name is used, add one to the number and call the function again
if line[1] == nameToCheck:
nameUsed = True
# Increment number or set it to 1 depending on its value
if number == "" :
number = 1
else:
number = number + 1
return findNameForClonedFlashcardSet(templateName, number)
csvfile.close()
# If the name is not used, return it - this is the base condition
if nameUsed == False:
return templateName + str(number)
def cloneTemplate(templateName, username) :
# Find the ID and description of templateName
ID = ""
description = ""
with open("database/uploadedFlashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == templateName:
ID = line[0]
description = line[2]
csvfile.close()
# Find the userID
userID = searchUsers(username, 1, True)[0]
# Get the name of the new set
name = findNameForClonedFlashcardSet(templateName, "")
# Generate a new ID
newID = str(generateNewID("database/flashcards.csv"))
# Find the the terms of the set templateName
terms = []
with open("database/uploadedFlashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] == ID:
terms.append(line[1] + "#" + line[2])
csvfile.close()
# Add newID, name, description to database/flashcards.csv
with open("database/flashcards.csv", "a") as csvfile:
csvfile.write(newID + "," + name + "," + description + "\n")
csvfile.close()
# Add newID, term, definition, to database/flashcardTerms.csv
with open("database/flashcardTerms.csv", "a") as csvfile:
for term in terms:
csvfile.write(newID + "," + term.split("#")[0] + "," + term.split("#")[1] + "\n")
csvfile.close()
# Add flashcardID. ownerID to database/flashcardOwners.csv
with open("database/flashcardsOwners.csv", "a") as csvfile:
csvfile.write(newID + "," + userID + "\n")
csvfile.close()
return name
# Get the flashcard description based on the name - works for flashcard templates and normal flashcards due to the fileToSearch parameter
def getFlashcardDescription(flashcardName, fileToSearch) :
with open(fileToSearch, "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
return line[2]
# This will remove the flashcard as well as its uploaded backup
def deleteFlashcard(flashcardName) :
flashcardID = ""
# Get the ID of the flashcard
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[1] == flashcardName:
flashcardID = line[0]
csvfile.close()
# Delete the flashcard from flashcards.csv
# Read all the data in flashcards.csv into an array except the line to delete
flashcards = []
with open("database/flashcards.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] != flashcardID:
flashcards.append(line[0] + "," + line[1] + "," + line[2])
csvfile.close()
# Rewrite the data in the array to flashcards.csv
with open("database/flashcards.csv", "w") as csvfile:
for line in flashcards:
csvfile.write(line + "\n")
csvfile.close()
# Delete the flashcard from flashcardTerms.csv
# Read all the data in flashcardTerms.csv into an array except the line to delete
flashcardTerms = []
with open("database/flashcardTerms.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)
for line in csvreader:
if line[0] != flashcardID:
flashcardTerms.append(line[0] + "," + line[1] + "," + line[2])
csvfile.close()
# Rewrite the data in the array to flashcardTerms.csv
with open("database/flashcardTerms.csv", "w") as csvfile:
for line in flashcardTerms:
csvfile.write(line + "\n")
csvfile.close()
# Delete the flashcard from flashcardsOwners.csv
# Read all the data in flashcardsOwners.csv into an array except the line to delete
flashcardsOwners = []
with open("database/flashcardsOwners.csv", "r") as csvfile:
csvreader = csv.reader(csvfile)