-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
executable file
·514 lines (468 loc) · 21.5 KB
/
app.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
import logging
import MySQLdb
import os
import smtplib
import uuid
from datetime import datetime, timedelta
from email.mime.text import MIMEText
from flask import Flask, jsonify, render_template, request, flash, redirect
from flask_cors import CORS
from flask_mysqldb import MySQL
UPLOAD_FOLDER = 'static/images'
ALLOWED_EXTENSIONS = {'jpg', 'jpeg', 'png', 'jfif'}
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "0.0.0.0"}})
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['SECRET_KEY'] = "ola_ke_ase"
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'encuentrame'
app.config['MYSQL_PASSWORD'] = 'password'
app.config['MYSQL_DB'] = 'encuentraMe'
app.url_map.strict_slashes = False
gmail_user = '[email protected]'
gmail_pwd = 'encuentrame'
mysql = MySQL(app)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def logfile(traceback):
with open("traceback.txt", 'a') as f:
send = "-------" + (datetime.utcnow() - timedelta(hours=3)).strftime("%m/%d/%Y, %H:%M:%S") +\
"-------\n" + traceback + "\n"
f.write(send)
f.close()
return False
def date_format(fecha):
fecha_l = fecha.split('-')
fecha = fecha_l[2] + '/' + fecha_l[1] + '/' + fecha_l[0]
return fecha
@app.route('/')
def landing():
"""Landing page"""
return render_template('index.html')
@app.route('/<user_id>/lost_pet', methods=['GET', 'POST'])
def form_lost_pet(user_id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM users WHERE id=%s", [user_id])
user = list(cursor.fetchall())
if not user:
flash("Asegúrate de ingresar con tu usuario", "info")
return redirect("/")
user = user[0]
if user['estado'] == 'blocked':
flash('No tienes permisos para realizar una publicación', "error")
return redirect('/')
if request.method == 'GET':
if user['estado'] == 'blocked':
flash('No tienes permisos para publicar', "error")
return redirect('/')
return render_template('form_lost_pet.html', user_id=user_id)
if request.method == 'POST':
tel = ''
if request.form['telefono']:
tel = request.form['telefono']
if not user['phone']:
cursor.execute("UPDATE users SET phone=%s WHERE id=%s", [request.form['telefono'], user_id])
id = "lost" + str(uuid.uuid4())
estado = "active"
created_at = datetime.utcnow()
updated_at = created_at
mascota = request.form['mascota']
nombre = request.form['nombre']
fecha = date_format(request.form['fecha'])
hora = request.form['hora']
calle_1 = request.form['calle_1']
calle_2 = request.form['calle_2']
barrio = request.form['barrio']
file = request.files['foto']
latitude = request.form['latitude']
longitude = request.form['longitude']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('Debe subir una foto', "info")
return redirect(request.url)
if file and allowed_file(file.filename):
file.filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower()
filename = file.filename
file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
else:
flash('Formatos de imagen soportados: jpg, jpeg, png, jfif.', "info")
return redirect(request.url)
try:
cursor.execute('INSERT INTO lost_pets VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
(id, user_id, user['name'], tel, estado, created_at, updated_at, mascota, nombre, fecha, hora, calle_1, calle_2, barrio, file.filename, latitude, longitude))
except Exception as e:
flash('Ha ocurrido un error, asegúrese de ingresar los datos correctamente', "error")
logfile("form_lost_pet(user_id) - in cursor.execute(INSERT INTO lost_pets):\n" + str(e))
return redirect(request.url)
mysql.connection.commit()
cursor.close()
return redirect('/')
@app.route('/<user_id>/found_pet', methods=['GET', 'POST'])
def form_found_pet(user_id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM users WHERE id=%s", [user_id])
user = list(cursor.fetchall())
if not user:
flash("Asegúrate de ingresar con tu usuario", "info")
return redirect("/")
user = user[0]
if user['estado'] == 'blocked':
flash('No tienes permisos para realizar una publicación', "error")
return redirect('/')
if request.method == 'GET':
if user['estado'] == 'blocked':
flash('No tienes permisos para publicar', "error")
return redirect('/')
return render_template('form_found_pet.html', user_id=user_id)
if request.method == 'POST':
tel = ''
if request.form['telefono']:
tel = request.form['telefono']
if not user['phone']:
cursor.execute("UPDATE users SET phone=%s WHERE id=%s", [request.form['telefono'], user_id])
id = "found" + str(uuid.uuid4())
estado = "active"
created_at = datetime.utcnow()
updated_at = created_at
mascota = request.form['mascota']
fecha = date_format(request.form['fecha'])
hora = request.form['hora']
calle_1 = request.form['calle_1']
calle_2 = request.form['calle_2']
barrio = request.form['barrio']
file = request.files['foto']
latitude = request.form['latitude']
longitude = request.form['longitude']
# If the user does not select a file, the browser submits an
# empty file without a filename.
if file.filename == '':
flash('Debe subir una foto', "info")
return redirect(request.url)
if file and allowed_file(file.filename):
file.filename = str(uuid.uuid4()) + '.' + file.filename.rsplit('.', 1)[1].lower()
filename = file.filename
file.save(os.path.join(app.root_path, app.config['UPLOAD_FOLDER'], filename))
else:
flash('Formatos de imagen soportados: jpg, jpeg, png, jfif.', "info")
return redirect(request.url)
try:
cursor.execute('INSERT INTO found_pets VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',
(id, user_id, user["name"], tel, estado, created_at, updated_at, mascota, fecha, hora, calle_1, calle_2, barrio, file.filename, latitude, longitude))
except Exception as e:
flash('Ha ocurrido un error, asegúrese de ingresar los datos correctamente', "error")
logfile("form_found_pet(user_id) - in cursor.execute(INSERT INTO found_pets):\n" + str(e))
return redirect(request.url)
mysql.connection.commit()
cursor.close()
return redirect('/')
@app.route('/<user_id>/report/<post_id>', methods=['GET', 'POST'])
def form_report(user_id, post_id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT estado FROM users WHERE id=%s', [user_id])
user = list(cursor.fetchall())[0]
if user['estado'] == 'blocked':
flash('No tienes permisos para denunciar una publicación', "error")
return redirect('/')
if request.method == 'GET':
return render_template('form_report.html', user_id=user_id, post_id=post_id)
if request.method == 'POST':
updated_at = datetime.utcnow()
if "lost" in post_id:
cursor.execute("UPDATE lost_pets SET estado = 'reported' WHERE id=%s", [post_id])
cursor.execute("UPDATE lost_pets SET updated_at=%s WHERE id=%s", [updated_at, post_id])
cursor.execute('SELECT user_id FROM lost_pets WHERE id=%s', [post_id])
else:
cursor.execute("UPDATE found_pets SET estado = 'reported' WHERE id=%s", [post_id])
cursor.execute("UPDATE found_pets SET updated_at=%s WHERE id=%s", [updated_at, post_id])
cursor.execute('SELECT user_id FROM found_pets WHERE id=%s', [post_id])
try:
reported_user_id = list(cursor.fetchall())[0]['user_id']
except Exception as e:
logfile("form_report(user_id, post_id) - in reported_user = list(cursor.fetchall())[0]:\n" + str(e))
flash("No es posible acceder a esta publicación", "info")
return redirect('/')
cursor.execute("SELECT name FROM users WHERE id=%s", [user_id])
sender_username = list(cursor.fetchall())[0]['name']
reporte = request.form['reporte']
created_at = datetime.utcnow() - timedelta(hours=3)
try:
cursor.execute('INSERT INTO reports VALUES (%s, %s, %s, %s, %s, %s)',
(created_at, user_id, sender_username, reporte, post_id, reported_user_id))
except Exception as e:
logfile("form_report(user_id, post_id) - in cursor.execute(INSERT INTO reports):\n" + str(e))
mysql.connection.commit()
cursor.close()
recipients = ['[email protected]','[email protected]','[email protected]','[email protected]','[email protected]']
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.starttls()
smtpserver.ehlo
content = '\nNew report received\nUser: '+ user_id + '\nPost: ' + 'https://encuentrame.org.xelar.tech/'+post_id + '\nReport: ' + reporte + '\nDate: ' + str(created_at) + '\nReports: https://encuentrame.org.xelar.tech/posts/reported'
msg = MIMEText(content)
msg['Subject'] = "New Report"
msg['From'] = gmail_user
msg['To'] = ", ".join(recipients)
smtpserver.login(gmail_user, gmail_pwd)
smtpserver.sendmail(gmail_user, recipients, msg.as_string())
smtpserver.quit()
flash('Gracias por denunciar esta publicación, la revisaremos lo antes posible.', "success")
return redirect('/')
@app.route('/<id>')
def show_single_post(id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if "lost" in id:
cursor.execute("SELECT * FROM lost_pets WHERE id=%s", [id])
else:
cursor.execute("SELECT * FROM found_pets WHERE id=%s", [id])
try:
result = list(cursor.fetchall())
if not result:
return redirect('/')
post = result[0]
except Exception as e:
flash("Publicación no encontrada", "info")
logfile("show_single_post(id) - in post = list(cursor.fetchone())[0]:\n" + str(e))
cursor.close()
return redirect('/')
try:
if post['estado'] == 'removed':
flash('No es posible acceder a esta publicación.', "info")
return redirect('/')
post['foto'] = os.path.join(UPLOAD_FOLDER, post['foto'])
except Exception as e:
logfile("show_single_post:\n" + str(e))
pass
cursor.execute("SELECT name, fb_profile FROM users WHERE id=%s", [post['user_id']])
try:
result = list(cursor.fetchall())
if len(result) >= 1:
user = result[0]
except Exception as e:
logfile("show_single_post(id) - in user = list(cursor.fetchall())[0]:\n" + str(e))
pass
cursor.close()
return render_template('post_by_id.html', post=post, user=user)
@app.route('/main_map')
def new_map():
return render_template('main_map.html')
@app.route('/about')
def about():
return render_template('about.html')
@app.route('/politica_de_privacidad')
def politica():
return render_template('politica_de_privacidad.html')
@app.route('/politica_de_cookies')
def cookies():
return render_template('politica_de_cookies.html')
@app.route('/aviso_legal')
def aviso():
return render_template('aviso_legal.html')
@app.route('/profile/<user_id>')
def user_profile(user_id):
"""Render user profile with all owner's posts"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM users WHERE id=%s", [user_id])
user = list(cursor.fetchall())[0]
return render_template('profile.html', user=user)
@app.route('/posts/reported')
def moderate_posts():
return render_template('moderate.html')
# RESTful APIs
@app.route('/api/posts/')
def api_posts():
"""Retrieve all posts from database and return a list of dictionaries in JSON format"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM lost_pets WHERE estado='active' OR estado='reported' ORDER BY created_at DESC")
lost = list(cursor.fetchall())
cursor.execute("SELECT * FROM found_pets WHERE estado='active' OR estado='reported' ORDER BY created_at DESC")
found = list(cursor.fetchall())
cursor.close()
for post in lost:
del post["estado"]
for post in found:
del post["estado"]
all_posts = lost + found
all_posts.sort(key=lambda d: d['created_at'], reverse=True)
return jsonify(all_posts)
@app.route('/api/posts/lost')
def api_posts_lost():
"""Return all lost_pets posts and return a list of dictionaries in JSON format"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM lost_pets WHERE estado='active' OR estado='reported' ORDER BY created_at DESC")
lost = list(cursor.fetchall())
cursor.close()
for post in lost:
del post["estado"]
return jsonify(lost)
@app.route('/api/posts/found')
def api_posts_found():
"""Return all found_pets posts and return a list of dictionaries in JSON format"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM found_pets WHERE estado='active' OR estado='reported' ORDER BY created_at DESC")
found = list(cursor.fetchall())
cursor.close()
for post in found:
del post["estado"]
return jsonify(found)
@app.route('/api/users/', methods=['POST', 'PUT', 'DELETE'])
def api_users():
if request.method == 'POST':
"""Stores new user into database"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
content_type = request.headers.get('Content-Type')
if (content_type != 'application/json'):
return (jsonify("Not a JSON"), 400)
cursor.execute('SELECT * FROM users')
all_users = list(cursor.fetchall())
user = request.get_json()
try:
for u in all_users:
try:
if u['id'] == user['id']:
return jsonify('User already saved')
except Exception as e:
logfile(str(e))
except Exception as e:
logfile(str(e))
return jsonify(str(e))
link = ''
if "link" in user.keys():
link = user['link']
try:
cursor.execute('INSERT INTO users VALUES (%s, %s, %s, %s, %s, %s)', (user['id'], user['name'], user['email'], '', 'active', link))
except Exception as e:
logfile("/api/users - INSERT USER:\n" + str(e))
return jsonify('User already saved')
mysql.connection.commit()
cursor.close()
return jsonify(user)
if request.method == 'DELETE':
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
user = request.get_json()
try:
cursor.execute("UPDATE users SET estado='blocked' WHERE id=%s", [user['id']])
except Exception as e:
logfile("/api/users - UPDATE users:\n" + str(e))
flash("Ha ocurrido un error", "error")
return jsonify("ERROR")
mysql.connection.commit()
cursor.close()
flash('Usuario bloqueado', "info")
return jsonify("Usuario bloqueado")
@app.route('/api/users/<user_id>/posts')
def api_user_posts(user_id):
"""Retrieve all posts from user by user_id and return in JSON format"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM lost_pets WHERE user_id=%s AND estado!=%s AND estado!=%s ORDER BY created_at DESC', [user_id, "resolved", "removed"])
lost = list(cursor.fetchall())
cursor.execute('SELECT * FROM found_pets WHERE user_id=%s AND estado!=%s AND estado!=%s ORDER BY created_at DESC', [user_id, "resolved", "removed"])
found = list(cursor.fetchall())
cursor.close()
for post in lost:
del post["estado"]
del post["user_id"]
for post in found:
del post["estado"]
del post["user_id"]
return jsonify({"lost": lost, "found": found})
@app.route('/api/posts/<id>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def api_post_by_id(id):
"""All user CRUD operations for one single post by ID"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
if "lost" in id:
cursor.execute("SELECT * FROM lost_pets WHERE id=%s", [id])
else:
cursor.execute("SELECT * FROM found_pets WHERE id=%s", [id])
try:
post = list(cursor.fetchall())[0]
del post["estado"]
del post["user_id"]
except Exception as e:
logfile("api_post_by_id(id) - in post = list(cursor.fetchall())[0]:\n" + str(e))
cursor.close()
return redirect('/')
if request.method == 'GET':
cursor.close()
return jsonify(post)
if request.method == 'POST':
if "lost" in id:
cursor.execute("UPDATE lost_pets SET estado = 'active' WHERE id=%s", [id])
else:
cursor.execute("UPDATE found_pets SET estado = 'active' WHERE id=%s", [id])
mysql.connection.commit()
cursor.close()
return jsonify('Publicación activa nuevamente')
if request.method == 'PUT':
updated_at = datetime.utcnow()
if "lost" in id:
cursor.execute("UPDATE lost_pets SET estado = 'resolved' WHERE id=%s", [id])
cursor.execute("UPDATE lost_pets SET updated_at=%s WHERE id=%s", [updated_at, id])
else:
cursor.execute("UPDATE found_pets SET estado = 'resolved' WHERE id=%s", [id])
cursor.execute("UPDATE found_pets SET updated_at=%s WHERE id=%s", [updated_at, id])
mysql.connection.commit()
cursor.close()
flash('¡Felicidades! Nos alegra mucho que hayas encontrado a tu mascota :D', "success")
return jsonify('¡Felicidades! Nos alegra mucho que hayas encontrado a tu mascota :D')
if request.method == 'DELETE':
if "lost" in id:
cursor.execute("UPDATE lost_pets SET estado = 'removed' WHERE id=%s", [id])
else:
cursor.execute("UPDATE found_pets SET estado = 'removed' WHERE id=%s", [id])
mysql.connection.commit()
cursor.close()
flash('Publicación eliminada correctamente', "info")
return jsonify('Publicación eliminada correctamente')
@app.route('/api/posts/reported')
def reported_posts():
"""Retrieve all reported posts and their users"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM lost_pets WHERE estado='reported'")
reported_lost = list(cursor.fetchall())
cursor.execute("SELECT * FROM found_pets WHERE estado='reported'")
reported_found = list(cursor.fetchall())
cursor.execute("SELECT * FROM reports")
all_reports = list(cursor.fetchall())
cursor.close()
reports = {}
for post in reported_lost:
post['comments'] = []
for report in all_reports:
if post['id'] == report['post_id']:
comment = report['sender_uname'] + ": " + report['reporte']
post['comments'].append(comment)
for post in reported_found:
post['comments'] = []
for report in all_reports:
if post['id'] == report['post_id']:
comment = report['sender_uname'] + ": " + report['reporte']
post['comments'].append(comment)
reports['lost'] = reported_lost
reports['found'] = reported_found
return jsonify(reports)
@app.route('/api/posts/completed')
def api_completed():
"""Retrieve all completed (resolved) posts in JSON format"""
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM lost_pets WHERE estado = 'resolved'")
completed_lost = list(cursor.fetchall())
cursor.execute("SELECT * FROM found_pets WHERE estado = 'resolved'")
completed_found = list(cursor.fetchall())
cursor.close()
all_posts_completed = completed_lost + completed_found
all_posts_completed.sort(key=lambda d: d['updated_at'], reverse=True)
return jsonify(all_posts_completed)
@app.route('/api/users/<user_id>')
def api_user_by_id(user_id):
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT name, email, fb_profile FROM users WHERE id=%s', [user_id])
user = list(cursor.fetchall())[0]
cursor.close()
return jsonify(user)
if __name__ == "__main__":
app.run(host="0.0.0.0")
else:
gunicorn_logger = logging.getLogger('gunicorn.error')
app.logger.handlers = gunicorn_logger.handlers
app.logger.setLevel(gunicorn_logger.level)