-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
338 lines (264 loc) · 9.25 KB
/
model.py
File metadata and controls
338 lines (264 loc) · 9.25 KB
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
import bcrypt
from pymongo import collection
from bson import ObjectId
from backend.user import User
from backend.admin import Admin
from backend.post import Post
from backend.group import Group
# -- MODEL functions --
'''
Controller
'''
def authenticate_user(user:User,users:collection,errors:dict):
""" Retrieves a user from the Data Base
Args:
user (user.User):a user to be searched for in the DB
users (collection): Existing users in the DB
message (_type_): message to return if an error occurs
"""
# get the user from the database
# login_user = users.find_one({"email":user.email})
login_user = get_user_by_email(user, users)
# if the user is in the database
if login_user:
# update the username to the existing user username
user.username = login_user["username"]
# grab the password in the DB
password_in_db = login_user["password"]
# encode the password for security purposes
encoded_password = user.getPW().encode("utf-8")
# compare if the hashed user password is the same as the one in the db
if not bcrypt.checkpw(encoded_password,password_in_db):
# if we arrive here it means the password was invalid
errors["message"] = "Password is incorrect."
else:
errors["message"] = "Incorrect User/User does not exist."
# -- MONGODB CRUD Functions --
'''
CREATE user
'''
def add_user(user:User,users:collection,errors:dict):
""" Adds a user to the users collection in the DB
Args:
user (User): user to be added, if it doesnt exist
users (collection): DB collection of existing users
message (dict): dictionary of error messages to be used in case an error occurrs
"""
# check if there exists a user with the given email
# if users.find_one({"email":user.email}):
if get_user_by_email(user, users):
errors["message"] = "There already exists an account with this email"
return
# check if there exists a user with the given username
# if users.find_one({"username":user.username}):
if get_user(user, users):
errors["message"] = "This username is already taken/Username already exists"
return
# DB Insert error handling
try:
users.insert_one(user.to_document())
except:
errors["message"] = "Could not sign up at the moment. Please make sure the field are correct or try again later."
'''
CREATE post
'''
def create_post(post: Post, posts: collection, errors: dict):
"""Adds a post to the posts collection in the DB
Args:
post (Post): _description_
posts (collection): _description_
errors (dict): _description_
"""
print(post.to_document())
try:
posts.insert_one(post.to_document())
except:
errors["message"] = "Could not create a Post at the moment."
'''
CREATE group
'''
def add_group(group: Group, groups: collection, errors: dict):
"""Adds a Group to the group collection in the DB
Args:
group (Group): Group object to insert to the DB
groups (collection): Reference to the groups collection from the DB
message (dict): dictionary of error messages to be used in case an error occurrs
"""
# Check for an existing group
try:
existing_groups = get_groups(groups, errors)
except:
errors["message"] = "Couldn't retrieve groups. Please try again later."
return
for existing in existing_groups:
if existing['name'].lower() == group.name.lower():
errors["message"] = f'There already exists a group named "{existing["name"]}"'
return
# DB insert handler
try:
groups.insert_one(group.to_document())
except:
errors["message"] = "Could not create a Group at the moment. Please make sure the information is correct or try again later."
"""
READ user
"""
"""
Get User from the DB by username
"""
def get_user(user: User, users: collection):
try:
user = users.find_one({'username': user.username})
except:
print('An exception occurred')
return
return user
"""
Get User from the DB by Email
"""
def get_user_by_email(user: User, users: collection):
try:
user = users.find_one({'email': user.email})
except:
print('An exception occurred')
return
return user
"""
Get User from the DB by ID
"""
def get_user_by_id(id: ObjectId, users: collection):
try:
user = users.find_one({'_id': id})
except:
print('An exception occurred')
return
return user
def following(username: str, users:collection):
'''
Get's a list of the usernames that the current user follows
'''
user_info = users.find_one({'username':username})
result = []
for user_id in user_info['following']:
result.append(users.find_one({'_id':user_id})['username'])
return result
def get_recent_posts(username: str, users:collection, posts:collection):
'''
Gets the most recent posts of the people the user follows
'''
current_user = users.find_one({'username':username})
follow = current_user['following']
result = []
for user_id in follow:
recent_post = posts.find_one({'author':user_id})
recent_post = Post.from_document(recent_post)
recent_post.author = get_user_by_id(user_id, users)['username']
result.append(recent_post)
return result
"""
Method that returns all the posts from a specific group
"""
def get_posts_from_group(group: Group, groups:collection, posts: collection, errors: dict):
try:
group_name = get_group(group, groups, errors)['name']
group_posts = posts.find({'group': group_name}).sort("date", -1)
except:
errors['message'] = 'Could not retrieve posts at the moment. Please try again later.'
return
return group_posts
"""
Method that returns all the posts from a specific user
"""
def get_posts_from_user(user: User, users: collection, posts: collection, errors: dict):
try:
user_id = get_user(user, users)['_id']
user_posts = posts.find({'author': user_id})
except:
errors['message'] = 'Could not retrieve posts at the moment. Please try again later.'
return
return user_posts
"""
Method that returns all the posts from the DB
"""
def get_posts(posts: collection, errors: dict):
try:
posts_docs = posts.find()
except:
errors["message"] = "Couldn't perform this action. Please try again later"
return
return posts_docs
"""
Method that returns all the posts from a specific ID
"""
def get_post_by_id(id: ObjectId, posts: collection):
try:
post = posts.find_one({'_id': id})
except:
print('An exception occurred')
return
return post
def get_group(group: Group, groups: collection, errors: dict):
"""Gets a specific group from the DB by name
Args:
group (Group): Group object
groups (collection): Reference to the groups collection from the DB
"""
try:
group = groups.find_one({'name': group.name})
except:
errors["message"] = "Couldn't perform this action. Please try again later"
return
return group
def get_groups(groups: collection, errors: dict):
"""Retrieves every group available
Args:
groups (collection): Reference to the groups collection from the DB
"""
try:
groups = groups.find()
except:
errors["message"] = "Couldn't perform this action. Please try again later"
return
return groups
def get_group_by_id(id: ObjectId, groups: collection, errors: dict):
"""Gets a specific group from the DB by its id
Args:
id (ObjectId): Group ObjectId
groups (collection): Reference to the groups collection from the DB
"""
try:
group = groups.find_one({'_id': id})
except:
errors["message"] = "Couldn't perform this action. Please try again later"
return
return group
'''
Delete a user from the DB (hard delete)
'''
def delete_user(user: User, users: collection, errors: dict):
try:
users.delete_one({'username': user.username})
except:
errors["message"] = "Couldn't perform this action. Please try again later"
'''
Delete all posts wherre the delete used was present
'''
def delete_posts_from_user(user: User,users: collection, posts: collection, errors: dict):
try:
author_id = get_user(user, users)['_id']
posts.delete_many({'author': author_id})
except:
errors["message"] = "Couldn't perform this action. Please try again later"
'''
Gets the most recent posts of the people the user follows
'''
def get_recent_posts(username: str, users:collection, posts:collection):
current_user = users.find_one({'username':username})
follow = current_user['following']
result = []
for user_id in follow:
recent_post = posts.find_one({'$query':{'author':user_id}, '$orderby': {'date':-1}})
recent_post = Post.from_document(recent_post)
recent_post.author = get_user_by_id(user_id, users)['username']
recent_post.date = recent_post.date.strftime('%Y %m %d')
result.append(recent_post)
return result