Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
271 lines (239 loc) · 8.85 KB
/
Copy pathutils.py
File metadata and controls
271 lines (239 loc) · 8.85 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
"""
Module containing helper functions
"""
import datetime
import os
import re
import smtplib
from secrets import randbelow
from email.message import EmailMessage
from celery import shared_task
from flask import url_for
from firebase_admin import messaging
import magic
from models.activity import ActivityModel
from models.comment import CommentModel
from models.follower import FollowersModel
from models.post_image import PostImageModel
from models.post_like import PostLikeModel
from models.reply_comment import ReplyCommentModel
from models.token import TokenModel
from models.user import UserModel
from PIL import Image
from socket_utils import send_notification
def allowed_file(file, video=True):
"""Check if filename is an image or video file.
:param file: file object
:param video: boolean value to check if video file
:return: boolean value indicating if file is an image or video file
"""
file_type = magic.Magic(mime=True)
file_content = file.read(2048)
file_mime = file_type.from_buffer(file_content)
res = file_mime.startswith('image/')
file.seek(0)
if video:
res = res or file_mime.startswith('video/')
return res
@shared_task()
def compress_image(file_path):
"""
Compress an image file and replace it with the compressed version
:param file_path: path to the image file
:return: path to the compressed image file
"""
image = Image.open(file_path)
w, h = image.size
if w > h:
width = 1400
height = 1200
else:
height = 1400
width = 1200
if image.mode != 'RGB':
image = image.convert('RGB')
if (w, h) > (width, height):
image = image.resize((width, height))
image.save(file_path, "JPEG", optimize=True, progressive=True, quality=85)
def generate_activity(activity):
"""
Generate a dictionary containing the activity details
:param activity: ActivityModel object
:return: dictionary containing the activity details
"""
model = activity.activity_on
user = UserModel.query.get(activity.action_user_id)
result = {
'created_at': activity.created_at,
'fullname': user.full_name,
'user_dp': generate_media_url(user.profile) if user.profile else None
}
if model == "PostLikeModel":
like = PostLikeModel.query.get(activity.activity_id)
post_image = PostImageModel.query.filter(
PostImageModel.post_id == like.post_id
).first()
post_image = generate_media_url(post_image.photo)
result['action'] = 'Liked your post'
result['image'] = post_image
elif model == "CommentModel":
comment = CommentModel.query.get(activity.activity_id)
post_image = PostImageModel.query.filter(
PostImageModel.post_id == comment.post_id
).first()
post_image = generate_media_url(post_image.photo)
result['action'] = 'Commented on your post'
result['image'] = post_image
elif model == "FollowersModel":
follow = FollowersModel.query.get(activity.activity_id)
user = UserModel.query.get(follow.follows_user_id)
result['action'] = 'Started following you'
result['image'] = generate_media_url(user.profile) if user.profile else None
elif model == "ReplyCommentModel":
reply = ReplyCommentModel.query.get(activity.activity_id)
comment = CommentModel.query.get(reply.comment_id)
post_image = PostImageModel.query.filter(
PostImageModel.post_id == comment.post_id
).first()
post_image = generate_media_url(post_image.photo)
result['action'] = 'Replied to your comment'
result['image'] = post_image
return result
def add_activity(created_at, user_id, action_user_id, activity_on, activity_id):
activity = ActivityModel(
created_at=created_at,
user_id=user_id,
action_user_id=action_user_id,
activity_on=activity_on,
activity_id=activity_id
)
res = generate_activity(activity)
tokens = TokenModel.query.filter(
TokenModel.user_id == user_id
).with_entities(TokenModel.token).all()
tokens = [x[0] for x in tokens]
message = messaging.MulticastMessage(
data=res,
tokens=tokens,
)
response = messaging.send_multicast(message)
if response.failure_count > 0:
responses = response.responses
failed_tokens = []
for idx, resp in enumerate(responses):
if not resp.success:
failed_tokens.append(tokens[idx])
print('List of tokens that caused failures: {0}'.format(failed_tokens))
print('{0} messages were sent successfully'.format(response.success_count))
send_notification(user_id)
return activity
def otp_expiry():
"""Returns otp expiry time"""
return datetime.datetime.now()+datetime.timedelta(minutes=10)
def validate_phone_no(phone_number):
"""Function to validate phone number format"""
phone_number = " ".join(phone_number.split())
phone_number = phone_number.replace(",", ".").replace(";", ".")
phone_number_regex = r"^(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}$"
pattern = re.compile(phone_number_regex)
match = re.search(pattern, phone_number)
return match
def validate_password(password):
"""Function to validate password"""
# Minimum length of 8 characters
if len(password) < 8:
return False
# # Presence of both uppercase and lowercase letters
# if not any(c.isupper() for c in password) or not any(c.islower() for c in password):
# return False
# # Presence of at least one digit
# if not any(c.isdigit() for c in password):
# return False
# Presence of at least one special character
if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password):
return False
return True
def validate_email(email):
"""Function to validate email format"""
email_regex = r'^[A-Za-z0-9._-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,7}$'
pattern = re.compile(email_regex)
match = re.search(pattern, email)
return bool(match) and len(email) <= 70
def validate_username(username):
"""Function to validate username format"""
if len(username) > 20 or len(username) < 3:
return True
username_regex = r"[^A-Za-z0-9.]"
pattern = re.compile(username_regex)
match = re.search(pattern, username)
return match
def generate_otp():
"""Function that generates 4 digit random number"""
return str(randbelow(10000)).zfill(4)
def generate_media_url(filename):
path = os.path.join('uploads', filename)
return url_for('static', _external=True, filename=path)
def respond(status, message, data=None):
"""Function that returns json response in a format"""
if data is not None:
return {
"status": status,
"message": message,
"data": data
}
return {
"status": status,
"message": message,
}
def create_mail(to, subject, username, otp):
"""Function to create an Email"""
email = EmailMessage()
email['Subject'] = subject
email['From'] = os.getenv("SMTP_EMAIL")
email['To'] = to
email.set_content(f'''
<div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;
overflow:auto;line-height:2">
<div style="margin:50px auto;width:70%;padding:20px 0">
<div style="border-bottom:1px solid #eee">
<a href="#" style="font-size:1.4em;color: #00466a;
text-decoration:none;font-weight:600">Instagram Inc.</a>
</div>
<p style="font-size:1.1em">Hi, {username}</p>
<p>Thank you for choosing Instagram.
Use the following OTP to complete your Sign Up procedures.
OTP is only valid for 10 minutes.</p>
<h2 style="background: #00466a;margin: 0 auto;
width: max-content;padding: 0 10px;color: #fff;
border-radius: 4px;">{otp}</h2>
<p style="font-size:0.9em;">Regards,<br />Instagram</p>
<hr style="border:none;border-top:1px solid #eee" />
<div style="float:right;padding:8px 0;color:#aaa;font-size:0.8em;
line-height:1;font-weight:300">
<p>Instagram Inc.</p>
<p>Qburst</p>
<p>Kochi</p>
</div>
</div>
</div>
''', subtype='html')
return email
@shared_task()
def send_mail(to, subject, username, otp):
"""Function sends an email"""
email = create_mail(
to=to,
subject=subject,
username=username,
otp=otp,
)
s = smtplib.SMTP(host=os.getenv("SMTP_SERVER"),
port=os.getenv("SMTP_PORT"))
s.starttls()
s.login(os.getenv("SMTP_EMAIL"), os.getenv("SMTP_KEY"))
s.send_message(email)
s.quit()
def extract_jwt_sig(jwt):
"""Function that extracts jwt signature"""
sig = jwt.split(".")[2]
return sig