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