]> git.gir.st - subscriptionfeed.git/blob - app/browse/__init__.py
avoid int(request.args.get('page'))
[subscriptionfeed.git] / app / browse / __init__.py
1 import requests
2 from flask import Blueprint, render_template, request, flash, g, url_for, redirect
3 from flask_login import current_user
4 from werkzeug.exceptions import BadRequest, NotFound
5
6 from ..common.common import *
7 from ..common.innertube import *
8 from .lib import *
9 from .protobuf import make_sp, make_channel_params, make_playlist_params, Filters
10
11 frontend = Blueprint('browse', __name__,
12 template_folder='templates',
13 static_folder='static',
14 static_url_path='/static/ys')
15
16 @frontend.route('/results')
17 @frontend.route('/search')
18 def search():
19 #token = getattr(current_user, 'token', 'guest')
20 q = request.args.get('q') or request.args.get('search_query')
21 page = request.args.get('page', 1, type=int)
22
23 sp = make_sp(page, **{
24 k:v for k,v in request.args.items()
25 if k in ['sort','date','type','len']
26 }, features=[
27 f for f in request.args.getlist('feature')
28 if f in Filters.__dataclass_fields__.keys()
29 ], extras=[
30 e for e in request.args.getlist('feature')
31 if e in ['verbatim']
32 ])
33
34 if q:
35 yt_results = fetch_searchresults(q, sp)
36
37 results, extras = prepare_searchresults(yt_results)
38
39 for extra in extras:
40 flash(extra, 'info')
41 else:
42 results = None
43
44 return render_template('search.html.j2', rows=results, query=q, page=page)
45
46 @frontend.route('/channel/<channel_id>/')
47 @frontend.route('/channel/<channel_id>/<subpage>')
48 def channel(channel_id, subpage="videos"):
49 token = getattr(current_user, 'token', 'guest')
50 if subpage == "videos":
51 page = request.args.get('page', 1, type=int)
52 sort_by = request.args.get('sort') or "newest"
53 query = None
54 elif subpage == "playlists":
55 page = request.args.get('page', 1, type=int)
56 sort_by = request.args.get('sort', "modified")
57 query = None
58 elif subpage == "search":
59 query = request.args.get('q')
60 page = request.args.get('page', 1, type=int)
61 sort_by = None
62 else: # we don't support /home, /about, ..., so redirect to /videos.
63 return redirect(url_for('.channel', channel_id=channel_id))
64
65 # best effort; if it fails, it fails in the redirect.
66 if not re.match(r"(UC[A-Za-z0-9_-]{22})", channel_id):
67 return redirect(url_for('.channel_redirect', user=channel_id))
68
69 result = fetch_ajax(make_channel_params(channel_id, subpage, page, sort_by, query, v3=(subpage != "search")))
70 error = find_and_parse_error(result)
71
72 if result is None: # if fetching from innertube failed, fall back to xmlfeed:
73 flash("unable to fetch results from ajax; displaying fallback results (15 newest)", "error")
74 return fallback_route(channel_id, subpage)
75
76 if error:
77 return error, 400 # todo: ugly
78
79 title, descr, thumb, rows, more = prepare_channel(result, channel_id)
80 if not rows: # overran end of list, or is special channel (e.g. music topic)
81 flash("ajax returned nothing; displaying fallback results (15 newest)", "error")
82 return fallback_route(channel_id, subpage)
83
84 # set pin/hide stati of retrieved videos:
85 video_ids = [card['content']['video_id'] for card in rows]
86 pinned, hidden = fetch_video_flags(token, video_ids)
87 rows = sorted([
88 {'type':v['type'], 'content':{**v['content'], 'pinned': v['content']['video_id'] in pinned}}
89 for v in rows
90 if v['content']['video_id'] not in hidden
91 ], key=lambda v:v['content']['pinned'], reverse=True)
92
93 with sqlite3.connect(cf['global']['database']) as conn:
94 c = conn.cursor()
95 c.execute("""
96 SELECT COUNT(*)
97 FROM subscriptions
98 WHERE channel_id = ? AND user = ?
99 """, (channel_id, token))
100 (is_subscribed,) = c.fetchone()
101
102 return render_template('channel.html.j2',
103 title=title,
104 subpage=subpage,
105 rows=rows,
106 channel_id=channel_id,
107 channel_img=thumb,
108 channel_desc=descr,
109 is_subscribed=is_subscribed,
110 page=page,
111 has_more=more)
112
113 @frontend.route('/user/<user>/')
114 @frontend.route('/user/<user>/<subpage>')
115 @frontend.route('/c/<user>/')
116 @frontend.route('/c/<user>/<subpage>')
117 def channel_redirect(user, subpage=None):
118 """
119 The browse_ajax 'API' needs the UCID.
120 """
121
122 # inverse of the test in /channel/:
123 if re.match(r"(UC[A-Za-z0-9_-]{22})", user):
124 return redirect(url_for('.channel', channel_id=user))
125
126 channel_id = canonicalize_channel(user)
127 if not channel_id:
128 raise NotFound("channel appears to not exist")
129 return redirect(
130 url_for('.channel', channel_id=channel_id, subpage=subpage), 308
131 )
132
133 @frontend.route('/playlist')
134 def playlist():
135 playlist_id = request.args.get('list')
136 if not playlist_id:
137 raise BadRequest("No playlist ID")
138 page = request.args.get('page', 1, type=int)
139
140 xmlfeed = fetch_xml("playlist_id", playlist_id)
141 if not xmlfeed:
142 raise NotFound("Unable to fetch playlist")
143 title, author, _, channel_id, _ = parse_xml(xmlfeed)
144
145 offset = (page-1)*100 # each call returns 100 items
146 result = fetch_ajax(make_playlist_params(playlist_id, offset))
147 error = find_and_parse_error(result)
148
149 if result is None:
150 flash(f"1 {error}. Loading fallback.", 'error')
151 return fallback_route()
152
153 if not 'continuationContents' in result:
154 flash(f"2 {error}. Loading fallback.", 'error')
155 return fallback_route()
156
157 rows, more = prepare_playlist(result)
158
159 return render_template('playlist.html.j2',
160 title=title,
161 author=author,
162 channel_id=channel_id,
163 rows=rows,
164 page=page,
165 has_more=more)
166
167 @frontend.route('/<something>', strict_slashes=False)
168 def plain_user_or_video(something):
169 # this is a near-copy of the same route in app/youtube, but using a
170 # different, more reliable endpoint to determine whether a channel exists.
171 if '.' in something:
172 # prevent a lot of false-positives (and reduce youtube api calls)
173 raise NotFound
174
175 channel_id = canonicalize_channel(something)
176 if channel_id:
177 return redirect(url_for('.channel', channel_id=channel_id))
178 elif re.match(r"^[-_0-9A-Za-z]{11}$", something): # looks like a video id
179 return redirect(url_for('youtube.watch', v=something, t=request.args.get('t')))
180 else: # ¯\_(ツ)_/¯
181 raise NotFound("Note: some usernames not recognized; try searching it")
182
183 @frontend.before_app_request
184 def inject_button():
185 if not 'header_items' in g:
186 g.header_items = []
187 g.header_items.append({
188 'name': 'search',
189 'url': url_for('browse.search'),
190 'parent': frontend.name,
191 'priority': 15,
192 })
Imprint / Impressum