-
Notifications
You must be signed in to change notification settings - Fork 0
/
webdmp.py
executable file
·283 lines (229 loc) · 7.98 KB
/
webdmp.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
#! /usr/bin/env python2
from argon2 import PasswordHasher
from flask import (
g,
redirect,
render_template,
request,
send_from_directory,
session,
Flask
)
import json
import os
import sqlite3
app = Flask(__name__)
app.config.from_object('config.DevelConfig')
def get_sqlite_database():
return sqlite3.connect(app.config['DATABASE'])
def insert_bookmark(name='', url=''):
try:
g.db.execute(
'insert into bookmarks (name, url) values (?, ?)', (name, url,)
)
g.db.commit()
except sqlite3.IntegrityError, e:
# in case of an existing url return the bookmark id
# todo: replace this hack in favor of more atomic functions
return g.db.execute(
'select id from bookmarks where url = ?', (url,)
).fetchone()[0]
return g.db.execute('select last_insert_rowid()').fetchone()[0]
def insert_tag(name=''):
g.db.execute('insert into tags (name) values (?)', (name,))
g.db.commit()
return g.db.execute('select last_insert_rowid()').fetchone()[0]
def get_tag_id(tag_name=''):
tag_id = g.db.execute(
'select id from tags where name = ?', (tag_name,)
).fetchone()
if tag_id is not None:
return tag_id[0]
else:
return insert_tag(name=tag_name)
def insert_bookmark_tag(bookmark_id, tag_id):
g.db.execute(
'insert into bookmark_tags (bookmark_id, tag_id) values (?, ?)',
(bookmark_id, tag_id,)
)
g.db.commit()
def select_bookmark(name=''):
try:
return g.db.execute(
'select url from bookmarks where name = ?', (name,)
).fetchone()[0]
except:
return 'not found'
def get_bookmark_record(url=''):
try:
bookmark_id = g.db.execute(
'select id from bookmarks where url = ?', (url,)
).fetchone()[0]
cursor = g.db.execute(
'''select name from tags
where id in (
select tag_id from bookmark_tags where bookmark_id = ?
)
''', (bookmark_id,)
)
tags = [{'tag': row[0]} for row in cursor.fetchall()]
bookmark_tuple = g.db.execute(
'select name, url from bookmarks where url = ?',
(url,)
).fetchone()
bookmark_record = {
'name': bookmark_tuple[0],
'url': bookmark_tuple[1],
'tags': tags
}
return bookmark_record
except Exception, e:
return False
def select_bookmark_tag_id(bookmark_id, tag_id):
return g.db.execute(
'select id from bookmark_tags where bookmark_id = ? and tag_id = ?',
(bookmark_id, tag_id,)
).fetchone()
def make_value_list_query_string(len=0):
return ', '.join('?' * len)
def select_bookmarks_on_tagnames(tagnames):
tagnames_len = len(tagnames)
cursor = g.db.execute(
'''select b.url, b.name from bookmarks as b
join bookmark_tags as bt where b.id = bt.bookmark_id
and bt.tag_id in (select id from tags where name in ({0}))
group by b.url having count (b.url) = ?
'''.format(make_value_list_query_string(tagnames_len)),
tuple(tagnames) + (tagnames_len,)
)
return [{'url': row[0], 'title': row[1]} for row in cursor.fetchall()]
def select_bookmark_id(url=''):
try:
return g.db.execute(
'select id from bookmarks where url = ?', (url,)
).fetchone()[0]
except TypeError:
return None
def select_bookmarktags_tagids(bookmark_id=0):
return [
x[0] for x in g.db.execute(
'select tag_id from bookmark_tags where bookmark_id = ?',
(bookmark_id,)
).fetchall()
]
def delete_bookmark_tag(bookmark_id, tag_id):
g.db.execute(
'delete from bookmark_tags where bookmark_id = ? and tag_id = ?',
(bookmark_id, tag_id,)
)
g.db.commit()
@app.before_request
def before_request():
g.db = get_sqlite_database()
@app.teardown_request
def teardown_request(exception):
db = getattr(g, 'db', None)
if db is not None:
db.close()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/bookmark', methods=['GET', 'POST'])
def bookmark():
if 'authenticated' in session:
if request.method == 'POST':
name = request.form['name']
url = request.form['url']
tags = request.form.getlist('tag-list')
bookmark_id = select_bookmark_id(url)
# update bookmark
# todo: update bookmark name
if bookmark_id:
tagids_old = select_bookmarktags_tagids(bookmark_id)
tagids_new = [get_tag_id(tag) for tag in tags]
# tags to delete
for tag_id in set(tagids_old) - set(tagids_new):
delete_bookmark_tag(bookmark_id, tag_id)
# tags to insert
for tag_id in set(tagids_new) - set(tagids_old):
insert_bookmark_tag(bookmark_id, tag_id)
# insert bookmark
else:
bookmark_id = insert_bookmark(name, url)
if not tags:
tag_id = get_tag_id(tag_name='notag')
insert_bookmark_tag(bookmark_id, tag_id)
else:
for tag in tags:
tag_id = get_tag_id(tag)
bookmark_tag_id = select_bookmark_tag_id(
bookmark_id,
tag_id
)
if bookmark_tag_id is None:
insert_bookmark_tag(bookmark_id, tag_id)
return redirect(url)
else:
bookmark_record = get_bookmark_record(url=request.args['url'])
if bookmark_record:
return render_template(
'bookmark.html',
options=bookmark_record['tags'],
items=[item['tag'] for item in bookmark_record['tags']],
page=bookmark_record['url'],
name=bookmark_record['name']
)
else:
return render_template(
'bookmark.html',
page=request.args['url'],
name=request.args['name']
)
else:
return render_template('base.html')
@app.route('/tag', methods=['GET', 'POST'])
def tag():
if 'authenticated' in session:
if request.method == 'POST':
g.db.execute(
'insert into tags (name) values (?)', (request.form['name'],)
)
return '{} saved'.format(request.form['name'])
else:
query = request.args.get('query')
cursor = g.db.execute(
'select name from tags where name like ?', ('%' + query + '%',)
)
tags = [{'tag': row[0]} for row in cursor.fetchall()]
return json.dumps(tags)
@app.route('/search')
def search():
if 'authenticated' in session:
if 'tag_names' in request.args:
tag_names = request.args.get('tag_names').split(',')
return json.dumps(select_bookmarks_on_tagnames(tag_names))
@app.route('/login', methods=['POST'])
def login():
username = request.form['login_username']
password = request.form['login_password']
redirect_location = request.form['redirect_location']
try:
if PasswordHasher().verify(app.config['PASSWD'][username], password):
session['authenticated'] = True
except:
print('login for {0} failed with wrong password'.format(username))
return redirect(redirect_location)
@app.route('/logout')
def logout():
if 'authenticated' in session:
session.pop('authenticated')
return 'logout successful'
@app.route('/favicon.ico')
def favicon():
return send_from_directory(
os.path.join(app.root_path, 'static'),
'favicon.ico',
mimetype='image/x-icon'
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9999)