~roshless/nnrss

ref: 56574d51756fb77b9ea7e5530e2466338e570861 nnrss/nnrss/views.py -rw-r--r-- 10.0 KiB
56574d51Roshless make session permanent 11 months ago
                                                                                
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
"""Module containing main views for web client"""
import datetime as dt

from flask import Blueprint, Response, flash, render_template, request, session, url_for
from werkzeug.datastructures import CombinedMultiDict
from werkzeug.exceptions import abort
from werkzeug.security import check_password_hash, generate_password_hash
from werkzeug.utils import redirect

from nnrss.background_update import BACKGROUND_TASK
from nnrss.database import RssHandler
from nnrss.decorators import (
    admin_required,
    guest_required,
    login_required,
    registration_enabled,
)
from nnrss.forms import (
    AddFeedForm,
    ExportForm,
    ImportForm,
    LoginForm,
    RegistrationForm,
    SettingsForm,
)
from nnrss.models import User
from nnrss.opml import OPMLWriter
from nnrss.thread_import import ImportThread

DEFAULT_WEB = Blueprint("default_web", __name__)


@DEFAULT_WEB.errorhandler(404)
def page_not_found(error):
    return render_template("errors/404.html", error=error), 404


@DEFAULT_WEB.route("/")
@login_required
def index():
    category = request.args.get("category", None)
    handler = RssHandler()
    if category:
        entries = handler.get_unread_entries(session["logged_in"], category)
        categories = None
    else:
        entries = handler.get_unread_entries(session["logged_in"])
        categories = handler.get_all_categories(session["logged_in"])
    return render_template(
        "unread_entries.html",
        entries=entries,
        category_name=category,
        categories=categories,
    )


@DEFAULT_WEB.route("/list")
@login_required
def feed_list():
    category = request.args.get("category", None)
    handler = RssHandler()
    if category:
        feeds = handler.get_feeds_from_category(session["logged_in"], category)
        categories = None
    else:
        feeds = handler.get_feeds(session["logged_in"])
        categories = handler.get_all_categories(session["logged_in"])
    return render_template(
        "feed_list.html",
        feeds=feeds,
        categories=categories,
        category_name=category,
    )


@DEFAULT_WEB.route("/add", methods=["GET", "POST"])
@login_required
def add_feed():
    form = AddFeedForm(request.form)
    if request.method == "POST" and form.validate():
        handler = RssHandler()
        feed_added = handler.add_feeds(
            [form.url.data], session["logged_in"], [form.category.data]
        )
        if not feed_added or feed_added is None:
            flash("Not a valid feed URL", "error")
        else:
            flash("Feed {} added!".format(form.url.data), "info")
    return render_template("feed_add.html", form=form)


@DEFAULT_WEB.route("/feed/<int:feed_id>")
@login_required
def view_feed_entries(feed_id=None):
    if feed_id is None:
        return "Enter id after URL", 400
    page = int(request.args.get("page", 1))
    handler = RssHandler()
    if not handler.feed_exists(feed_id):
        return abort(404, description="Feed not found")
    entries = handler.get_entries_by_feed_id(feed_id, session["logged_in"])
    selected_feed = handler.get_feed_without_details(feed_id, session["logged_in"])
    return render_template(
        "entries_list.html",
        entries=entries.paginate(page=page),
        feed=selected_feed,
    )


@DEFAULT_WEB.route("/feed/<int:feed_id>/unread")
@login_required
def view_feed_entries_unread(feed_id=None):
    if feed_id is None:
        return "Enter id after URL", 400
    page = int(request.args.get("page", 1))
    handler = RssHandler()
    if not handler.feed_exists(feed_id):
        return abort(404, description="Feed not found")
    entries = handler.get_unread_entries_by_feed_id(feed_id, session["logged_in"])
    selected_feed = handler.get_feed_without_details(feed_id, session["logged_in"])
    return render_template(
        "entries_list_unread.html",
        entries=entries.paginate(page=page),
        feed=selected_feed,
    )


@DEFAULT_WEB.route("/feed/<int:feed_id>/update", methods=["POST"])
@login_required
def update_feed_entries(feed_id=None):
    if feed_id is None:
        return "Enter id after URL", 400
    handler = RssHandler()
    if handler.update_feed(feed_id, session["logged_in"]):
        flash("Feed updated!", "info")
    else:
        return abort(404, description="Feed not found")
    return redirect(url_for("default_web.view_feed_entries", feed_id=feed_id))


@DEFAULT_WEB.route("/feed/<int:feed_id>/set_read")
@login_required
def set_read_entry(feed_id=None, entry_id=None):
    if feed_id is None:
        return "feed_id URL part missing", 400
    entry_id = request.args.get("entry_id")
    if entry_id is None:
        return "entry_id parameter missing", 400
    handler = RssHandler()
    ok, link = handler.set_read_entry(feed_id, entry_id, session["logged_in"])
    if ok:
        return redirect(link, code=302)
    else:
        return abort(404, description="Feed not found")


@DEFAULT_WEB.route("/feed/<int:feed_id>/remove", methods=["GET", "POST"])
@login_required
def remove_feed(feed_id=None):
    handler = RssHandler()
    if request.method == "POST":
        if feed_id is None:
            return "Enter id after URL"
        if handler.remove_feed(feed_id, session["logged_in"]):
            flash("Feed removed!", "info")
        else:
            return abort(404, description="Feed not found")
        return redirect(url_for("default_web.index"))
    selected_feed = handler.get_feed_without_details(feed_id, session["logged_in"])
    return render_template("delete_confirm.html", the_feed=selected_feed)


@DEFAULT_WEB.route("/admin")
@admin_required
def admin_index(feed_id=None):
    handler = RssHandler()
    users = handler.get_users()
    feed_count = [handler.get_feeds_count(user.username) for user in users]
    return render_template(
        "admin_panel.html", users=handler.get_users(), feed_count=feed_count
    )


@DEFAULT_WEB.route("/login", methods=["GET", "POST"])
@guest_required
def login():
    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        handler = RssHandler()
        password = handler.get_user_password(form.username.data)
        if password is not None and check_password_hash(password, form.password.data):
            session["logged_in"] = form.username.data
            session.permanent = True
            flash("Logged in", "info")
        else:
            flash("Wrong credentials", "error")
        return redirect(url_for("default_web.index"))
    return render_template("login.html", form=form)


@DEFAULT_WEB.route("/logout")
@login_required
def logout():
    session.pop("logged_in", None)
    return redirect(url_for("default_web.index"))


@DEFAULT_WEB.route("/register", methods=["GET", "POST"])
@registration_enabled
@guest_required
def register():
    form = RegistrationForm(request.form)
    if request.method == "POST" and form.validate():
        handler = RssHandler()
        new_user = User(
            form.username.data,
            generate_password_hash(form.password.data, method="pbkdf2:sha512"),
        )
        is_ok = handler.add_user(new_user)
        if is_ok:
            flash("Registered", "info")
            BACKGROUND_TASK.add_new_user_job(form.username.data)
            return redirect(url_for("default_web.login"))
        flash("Username taken", "error")
        return redirect(url_for("default_web.register"))
    return render_template("register.html", form=form)


@DEFAULT_WEB.route("/settings", methods=["GET", "POST"])
@login_required
def settings():
    handler = RssHandler()
    user_prefs = handler.get_user(session["logged_in"])
    form = SettingsForm(request.form, user_prefs)
    if request.method == "POST" and form.validate():
        if form.password.data.startswith("pbkdf2"):
            user_prefs.password = form.password.data
        else:
            user_prefs.password = generate_password_hash(
                form.password.data, method="pbkdf2:sha512"
            )
        user_prefs.api_key = form.api_key.data
        user_prefs.update_interval = form.update_interval.data
        handler.add_user(user_prefs)
        flash("Settings updated", "info")
        BACKGROUND_TASK.reschedule(session["logged_in"])
        return redirect(url_for("default_web.settings"))
    return render_template("settings.html", form=form)


import_thread = dict()


@DEFAULT_WEB.route("/import", methods=["GET", "POST"])
@login_required
def import_feeds():
    global import_thread

    form = ImportForm(CombinedMultiDict((request.form, request.files)))
    if request.method == "POST" and form.validate():
        if form.import_file.data.mimetype != "text/x-opml+xml":
            flash("Selected file is not OPML filetype", "error")
            return redirect(url_for("default_web.import_feeds"))
        import_thread[session["logged_in"]] = ImportThread(
            form.import_file.data, session["logged_in"]
        )
        import_thread[session["logged_in"]].start()
        flash("Import started", "info")
        return redirect(url_for("default_web.index"))

    try:
        is_thread_alive = import_thread[session["logged_in"]].isAlive()
    except KeyError:
        is_thread_alive = False
    except AttributeError:
        is_thread_alive = (
            True if import_thread[session["logged_in"]] is not None else False
        )

    if is_thread_alive:
        flash("Import in progress, please wait.", "error")
        return redirect(url_for("default_web.index"))
    else:
        return render_template("import_feeds.html", form=form)


@DEFAULT_WEB.route("/export", methods=["GET", "POST"])
@login_required
def export_feeds():
    form = ExportForm()
    if request.method == "POST" and form.validate():
        handler = RssHandler()
        feeds_list = handler.get_feeds(session["logged_in"])
        writer = OPMLWriter(feeds_list)
        return Response(
            writer.get_exported_feeds(),
            mimetype="text/xml",
            headers={
                "Content-Disposition": "attachment;filename=feeds-"
                + str(dt.date.today())
                + ".opml"
            },
        )
    return render_template("export_feeds.html", form=form)