forked from aidankmcl/futureboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
204 lines (162 loc) · 6.64 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
"""
A Flask server that presents a digital bulletin board
authors: Aidan McLaughlin <[email protected]> and Sean Foley <[email protected]>
date : 2017-01-18
license: MIT
"""
import os
import json
import sys
import re
from datetime import datetime
from bson import json_util
from bs4 import BeautifulSoup
from flask import Flask, redirect, render_template, request, url_for
from jinja2 import evalcontextfilter, Markup, escape
import requests as r
from pymongo import MongoClient
import parsedatetime as pdt
from pprint import PrettyPrinter
from flask_socketio import SocketIO, emit
from twilio.rest import Client
from app.factory import create_app
from app.models import get_date_format, identify_events
pp = PrettyPrinter()
_paragraph_re = re.compile(r'(?:\r\n|\r|\n){2,}')
cal = pdt.Calendar()
# MONGO
MONGO_URI = os.environ.get('MONGODB_URI')
if not MONGO_URI:
sys.exit("\nMONGODB_URI environment variable not set, see https://docs.mongodb.com/manual/reference/connection-string/\n")
CLIENT = MongoClient(MONGO_URI)
EMAIL_COLLECTION = CLIENT.heroku_s2k6dn06.emails
TEXT_COLLECTION = CLIENT.heroku_s2k6dn06.texts
EVENT_COLLECTION = CLIENT.heroku_s2k6dn06.events
# FOR IMAGE SEARCHING
GOOGLE_BASE = "https://www.google.com/search?tbm=isch&q=%s"
# TWILIO
try:
TWILIO_CLIENT = Client(os.environ['TWILIO_ACCOUNT_SID'], os.environ['TWILIO_AUTH_TOKEN'])
except KeyError:
sys.exit("\nYou need to add TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN to your environment variables.\n\
See the FUTUREBOARD README to learn more: https://github.com/aidankmcl/futureboard\n")
def gmail_to_mongo(email_data):
"""
This will be updated to actually parse data
coming from Google once we have GMail API set up.
"""
data = {
"message_id": email_data["id"],
"text": email_data["text"],
"subject": email_data["subject"],
"date": get_date_format(re.split('\s\-|\s\+', email_data["date"])[0]),
"author_email": email_data["author_email"],
"author_name": email_data["author_name"],
"replying_to": email_data["replying_to"]
}
return data
app = create_app()
socketio = SocketIO(app)
COUNT = 0
@socketio.on('connect', namespace='/text')
def handle_new_connection():
global COUNT
COUNT += 1
emit('connection', {'data': 'Connected', 'count': COUNT})
@socketio.on('disconnect', namespace='/text')
def handle_dropped_connection():
global COUNT
COUNT -= 1
emit('connection', {'data': 'Disconnected', 'count': COUNT})
@socketio.on('my_event', namespace='/text')
def handle_my_custom_event(json):
emit('response', json)
@app.route('/health')
def health():
socketio.emit('response',
{'data': 'Server is healthy!'},
namespace='/text')
return 'ok'
@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n')) for p in _paragraph_re.split(escape(value)))
if eval_ctx.autoescape:
result = Markup(result)
return result
@app.route('/')
def home_page():
# dates = sorted(set(map(lambda fname: re.findall('\d+', fname)[0], os.listdir('parsed_data'))))
# emails = EMAIL_COLLECTION.find().limit(10)
return render_template('board.html')
@app.route('/texts')
def get_texts():
start_date = cal.parseDT(request.args.get('start'))[0]
end_date = cal.parseDT(request.args.get('end'))[0]
texts = TEXT_COLLECTION.find({"date": {"$gte": start_date, "$lte": end_date}})
return json.dumps(list(texts), default=json_util.default)
@app.route('/events')
def get_events():
start_date = cal.parseDT(request.args.get('start'))[0]
end_date = cal.parseDT(request.args.get('end'))[0]
events = EVENT_COLLECTION.find({"date": {"$gte": start_date, "$lte": end_date}})
return json.dumps(list(events), default=json_util.default)
@app.route('/twilio', methods=["GET", "POST"])
def twilio_text():
if request.form.get('From', '') not in TEXT_COLLECTION.distinct("from"):
TWILIO_CLIENT.messages.create(
to=request.form.get('From', ''),
from_="+16174465859",
body="WELCOME TO FUTUREBOARD\n\nThanks for the text! To use FUTUREBOARD, write me words or feed me a link (I'll read anything from Youtube, Vimeo or URLs that end in .jpg, .png, and of course .gif).\n\n :)")
data = request.form.get('Body', '')
date = datetime.now()
src_id = TEXT_COLLECTION.insert({
'from': request.form.get('From', ''),
'data': data,
'date': date})
is_event = identify_events(data, src_id, date, "texts")
socketio.emit('response',
{'data': request.form.get('Body', request.form.values()),
'date': {'$date': date.isoformat() + 'Z'}, # Mimicing Mongo return format
'event': is_event},
namespace='/text')
return json.dumps(request.form.get('Body'))
@app.route('/test-twilio', methods=["GET", "POST"])
def test_twilio_text():
TEXT_COLLECTION.insert({
'from': request.form.get('From'),
'data': request.form.get('Body'),
'date': datetime.now()})
socketio.emit('response',
{'data': request.form.get('Body', request.form.values())},
namespace='/text')
return json.dumps(request.form.get('Body'))
@app.route('/images/<search_term>')
def query_google(search_term):
html_doc = r.get(GOOGLE_BASE % "cats").content
soup = BeautifulSoup(html_doc, 'html.parser')
res = soup.find(id="res").find_all('img')[0].attrs.get('src')
return json.dumps(res)
@app.route('/email/<id>')
def single_email_view(id):
email = EMAIL_COLLECTION.find_one({"message_id": id})
return render_template('single.html', email=email)
@app.route('/emails', methods=["POST"])
def filter_emails():
dates = request.form.get("date_range", "01/01/2005 - 01/31/2005").split(" - ") # sets default to Jan 2005
start_date, end_date = datetime.strptime(dates[0], '%m/%d/%Y'), datetime.strptime(dates[1], '%m/%d/%Y')
emails = EMAIL_COLLECTION.find({"date": {"$gt": start_date, "$lt": end_date}})
dates = []
for email in emails:
subject = email['subject']
date = email['date']
text = re.sub(re.compile("[^a-zA-Z0-9 /:]*"), "", email['text'])
subj_date = cal.parseDT(email["subject"], date)
body_date = cal.parseDT(text, date)
return json.dumps([email[0] for email in dates], default=json_util.default)
if __name__ == '__main__':
port = int(os.environ.get('PORT', 5000))
host = "127.0.0.1" if port == 5000 else "0.0.0.0"
# app.run(host=host, debug=True, port=port)
print("Starting app!")
socketio.run(app, host=host, port=port)