-
Notifications
You must be signed in to change notification settings - Fork 1
/
twittre.py
333 lines (262 loc) · 10.6 KB
/
twittre.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
import os
import sqlite3
import sys
import time
import calendar
import hashlib
from datetime import datetime
from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash, Markup
secret = open('secret.txt', 'r').read().split('\n')
secret_key = secret[0]
admin_username = secret[1]
admin_password = secret[2]
app = Flask(__name__)
app.config.from_object(__name__)
app.config.update(dict(
DATABASE=os.path.join(app.root_path, 'twittre.db'),
DEBUG=True,
SECRET_KEY=secret_key,
USERNAME='admin',
PASSWORD='default'
))
app.config.from_envvar('TWITTRE_SETTINGS', silent=True)
def connect_db():
rv = sqlite3.connect(app.config['DATABASE'])
rv.row_factory = sqlite3.Row
return rv
def init_db():
with app.app_context():
db = get_db()
with app.open_resource('schema.sql', mode='r') as f:
db.cursor().executescript(f.read())
db.commit()
def get_db():
if not hasattr(g, 'sqlite_db'):
g.sqlite_db = connect_db()
return g.sqlite_db
def query_db(query, args=(), one=False):
db = get_db()
cur = db.execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv
@app.teardown_appcontext
def close_db(error):
if hasattr(g, 'sqlite_db'):
g.sqlite_db.close()
@app.template_filter('inject_hash_tag')
def getSafeTweet(tweet):
safeTweet = str(Markup.escape(tweet))
injectedTweet = ''
# Inject <a href> for hashtags
HASH_TAG_STATE = 1
IGNORE_NEXT_STATE = 2
state = 0
hashTagText = ''
for c in safeTweet:
if state == HASH_TAG_STATE:
if (c < 'A' or c > 'Z') and (c < 'a' or c > 'z') and (c < '0' or c > '9'):
injectedTweet += '<a href="/hashtag/%s">#%s</a>%s' % (hashTagText.lower(), hashTagText, c)
state = 0
else:
hashTagText += c
elif state == IGNORE_NEXT_STATE:
injectedTweet += c
state = 0
else:
if c == '#':
hashTagText = ''
state = HASH_TAG_STATE
elif c == '&':
injectedTweet += c
state = IGNORE_NEXT_STATE
else:
injectedTweet += c
# Close hash if still in hashTagState
if state == HASH_TAG_STATE:
injectedTweet += '<a href="/hashtag/%s">#%s</a>' % (hashTagText.lower(), hashTagText)
state = 0
return Markup(injectedTweet)
def findFirstNonAlphaNum(st, start):
n = len(st)
for i in range(start, n):
c = st[i]
if (c < 'A' or c > 'Z') and (c < 'a' or c > 'z') and (c < '0' or c > '9'):
return i
return n
def trending():
db = get_db()
cur = db.execute('select text, time from tweets')
tweets = cur.fetchall()
# Go through tweets and extract hashtags
hashTags = []
for tweet in tweets:
hashTweets = map(lambda x: x[:findFirstNonAlphaNum(x, 1)], map(lambda x: x[x.find('#'):], filter(lambda x: x.find('#') != -1, tweet['text'].split())))
hashTags += hashTweets
hashTags = map(lambda x: x[1:].lower(), hashTags)
hashTags.sort()
hashTags = map(lambda x: [x, 1], hashTags) # Insert occurence of hashtag amount
n = len(hashTags)
x = 0
y = 0
# Find common hashes and keep track of their occurence
while x < n and y+1 < n:
y += 1
if hashTags[x][0] == hashTags[y][0]:
hashTags[x][1] += hashTags[y][1]
hashTags[y][1] = 0
else:
x = y
hashTags = filter(lambda x: x[1] != 0, hashTags) # Remove duplicates
hashTags.sort(key=lambda x: x[1], reverse=True)
return hashTags
@app.route('/')
def index():
db = get_db()
cur = db.execute('select id, text, user_id, time from tweets order by id desc')
tweets = cur.fetchall()
return render_template('index.html', tweets=tweets, title="Home", trending=trending())
@app.route('/add', methods=['POST'])
def add_entry():
if not session.get('logged_in'):
return redirect(url_for('login'))
# Add the tweet to the database if not empty
if request.form['tweet'].strip() != '':
db = get_db()
db.execute('insert into tweets (text, user_id, time) values (?, ?, ?)', [request.form['tweet'].strip(), session.get('username').lower(), int(round(time.time() * 1000))])
db.commit()
flash('New entry was successfully posted')
else:
flash('Tweet cannot be empty')
return redirect(url_for('index'))
@app.route('/login', methods=['GET', 'POST'])
def login():
if not session.get('logged_in'):
error = None
if request.method == 'POST':
username = request.form['username'].strip().lower()
password = request.form['password']
user = query_db('select * from users where username_lower = ?', [username], one=True)
# Check for valid username and password
# Usually, you shouldn't notify the user the specific input that's invalid
if user is None:
error = 'Invalid username'
elif hashlib.sha512(password + user['salt']).hexdigest() != user['password']:
error = 'Invalid password'
else:
session['logged_in'] = True
session['username'] = user['username']
session['admin'] = False
if user['admin'] == 1:
session['admin'] = True
flash('You were logged in')
return redirect(url_for('index'))
return render_template('login.html', error=error, title="Login")
else:
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('logged_in', None)
session.pop('username', None)
flash('You were logged out')
return redirect(url_for('index'))
def isUsernameValid(username):
for c in username:
if (c < 'a' or c > 'z') and (c < '0' or c > '9'):
return False
return True
@app.route('/register', methods=['GET', 'POST'])
def register():
if not session.get('logged_in'):
error = None
if request.method == 'POST':
username = request.form['username'].strip()
username_lower = username.lower()
password = request.form['password']
password2 = request.form['password2']
# Ceck for valid username and password
if username != '':
if isUsernameValid(username_lower):
user = query_db('select * from users where username_lower = ?', [username_lower], one=True)
if user is None and username_lower != 'adminconsole':
if password != password2:
error = 'Passwords do not match'
else:
salt = os.urandom(64).encode('hex')
hashPassword = hashlib.sha512(password + salt).hexdigest()
db = get_db()
db.execute('insert into users (username, username_lower, password, salt, admin) values (?, ?, ?, ?, ?)', [username, username_lower, hashPassword, salt, 0])
db.commit()
session['logged_in'] = True
session['username'] = username
session['admin'] = False
flash('Welcome to Twittre!')
return redirect(url_for('index'))
else:
error = 'Username has already been taken'
else:
error = 'Username can only contain letters and numbers'
else:
error = 'Username cannot be left blank'
return render_template('register.html', error=error, title="Register")
else:
return redirect(url_for('index'))
@app.route('/<username>', methods=['GET'])
def user(username):
user = query_db('select * from users where username_lower = ?', [username.lower()], one=True)
# Display username's tweets if valid user
if user is None:
return redirect(url_for('index'))
else:
db = get_db()
cur = db.execute('select id, text, user_id, time from tweets where user_id = ? order by id desc', [username.lower()])
tweets = cur.fetchall()
return render_template('user.html', tweets=tweets, username=user['username'], title=user['username'])
@app.route('/tweet/<int:tweet_id>', methods=['GET'])
def tweet(tweet_id):
tweet = query_db('select * from tweets where id = ?', [tweet_id], one=True)
# Display tweet if valid tweet
if tweet is None:
return redirect(url_for('index'))
else:
return render_template('tweet.html', tweet=tweet, title="Tweet #%d" % tweet_id)
@app.route('/hashtag/<hashtag>', methods=['GET'])
def hashTag(hashtag):
db = get_db()
cur = db.execute('select * from tweets order by id desc')
tweets = cur.fetchall()
# Only append tweets that contain the given hashtag
tweetsWithHashTag = []
for tweet in tweets:
if tweet['text'].lower().find('#%s' % hashtag) != -1:
tweetsWithHashTag.append(tweet)
return render_template('hashtag.html', tweets=tweetsWithHashTag, hashtag=hashtag, title="#%s" % hashtag)
@app.route('/adminconsole')
def admin():
# Open admin console if admin is logged in
if not session.get('logged_in') or not session.get('admin'):
return redirect(url_for('index'))
else:
db = get_db()
users = db.execute('select username, username_lower, password, admin from users order by id asc').fetchall()
tweets = db.execute('select id, text, user_id, time from tweets order by id asc').fetchall()
return render_template('admin.html', users=users, tweets=tweets, title="Admin Console")
@app.template_filter('datetime_format')
def formatTime(millis):
d = datetime.fromtimestamp(millis/1000)
return d.strftime('%b %-d, %Y @ %-I:%M %p')
@app.before_first_request
def initialize():
app.logger.debug('Initializing...')
# Initialize database
if len(sys.argv) > 1 and sys.argv[1] == "reset":
init_db()
salt = os.urandom(64).encode('hex')
hashPassword = hashlib.sha512(admin_password + salt).hexdigest()
# Initialize administrator
db = get_db()
db.execute('insert into users (username, username_lower, password, salt, admin) values (?, ?, ?, ?, ?)', [admin_username, admin_username.lower(), hashPassword, salt, 1])
db.commit()
app.logger.debug('Database has been initialized.')
app.logger.debug('Done!')
if __name__ == '__main__':
app.run()