]>
git.gir.st - subscriptionfeed.git/blob - app/youtube/__init__.py
5 #from flask_login import current_user, login_required
6 from flask_login
import LoginManager
, UserMixin
, current_user
, login_user
, logout_user
, login_required
7 from flask
import Blueprint
, render_template
, request
, redirect
, flash
, url_for
, jsonify
, g
9 from ..common
.common
import *
11 frontend
= Blueprint('youtube', __name__
,
12 template_folder
='templates',
13 static_folder
='static',
14 static_url_path
='/static/yt')
18 return redirect(url_for('.feed'), code
=302)
20 @frontend.route('/feed/subscriptions')
21 # disabled for guest user: @login_required
23 if current_user
.is_anonymous
:
26 token
= current_user
.token
27 page
= int(request
.args
.get('page', 0))
28 with sqlite3
.connect(cf
['global']['database']) as conn
:
31 SELECT videos.id, channel_id, name, title, published, flags.display
33 JOIN channels ON videos.channel_id = channels.id
34 LEFT JOIN flags ON (videos.id = flags.video_id) AND (flags.user = ?)
36 (SELECT channel_id FROM subscriptions WHERE user = ?)
37 AND flags.display IS NOT 'hidden'
38 ORDER BY (display = 'pinned') DESC, crawled DESC
40 OFFSET 36*?""", (token
, token
, page
))
43 'channel_id': channel_id
,
46 'published': published
,
47 'pinned': display
== 'pinned',
48 } for (video_id
, channel_id
, author
, title
, published
, display
) in c
.fetchall()]
49 return render_template('index.html.j2', rows
=rows
, page
=page
)
51 @frontend.route('/watch')
53 if not 'v' in request
.args
:
54 return "missing video id", 400
57 'content-type': 'text/plain',
58 'Link': "<data:text/css,body%7Bcolor:%23eee;background:%23333%7D>; rel=stylesheet;"
61 video_id
= request
.args
.get('v')
62 sts
, algo
= get_cipher()
63 video_url
, metadata
, error
, errdetails
= get_video_info(video_id
, sts
, algo
)
65 extra
= {'geolocked':'local=1', 'livestream':'raw=0'}.get(error
,'')
66 invidious_url
= f
"https://invidio.us/watch?v={video_id}&{extra}&raw=1"
68 'malformed': "Video ID is invalid.",
69 'geolocked': "This video is geolocked.",
70 'livestream': "Livestreams not yet supported.",
71 'exhausted': errdetails
or "Couldn't extract video URLs.",
75 show
= request
.args
.get("show")
78 msg
= errdetails
if error
=='player' else f
"{error.upper()}: {errdetails}"
79 return f
"{msg}\n\nRedirecting to Invidious.", 502, {
80 'Refresh': f
'2; URL={invidious_url}',
82 return redirect(video_url
, code
=307)
84 if error
and not metadata
:
85 return {'error': True, error
: errdetails
}, 400 # TODO: better (test _CpR4o81XQc)
86 return jsonify(metadata
)
88 if error
and not metadata
: # e.g. malformed, private/deleted video, ...
89 return errdetails
,400 # TODO: nicer
90 return render_template('watch.html.j2',
91 video_id
=video_id
, video_url
=video_url
,
92 video_error
=error
, errdetails
=errdetails
, invidious_url
=invidious_url
,
93 **prepare_metadata(metadata
))
95 @frontend.route('/channel/<channel_id>')
96 def channel(channel_id
):
97 if not re
.match(r
"(UC[A-Za-z0-9_-]{22})", channel_id
):
98 return "bad channel id", 400 # todo
100 xmlfeed
= fetch_xml("channel_id", channel_id
)
102 return "not found or something", 404 # XXX
103 title
, author
, videos
= parse_xml(xmlfeed
)
104 return render_template('xmlfeed.html.j2', title
=author
, rows
=videos
)
106 @frontend.route('/playlist')
108 playlist_id
= request
.args
.get('list')
110 return "bad list id", 400 # todo
112 xmlfeed
= fetch_xml("playlist_id", playlist_id
)
114 return "not found or something", 404 # XXX
115 title
, author
, videos
= parse_xml(xmlfeed
)
116 return render_template('xmlfeed.html.j2', title
=f
"{title} by {author}", rows
=videos
)
118 @frontend.route('/manage/subscriptions')
119 # disabled for guest user: @login_required
120 def subscription_manager():
121 if current_user
.is_anonymous
:
124 token
= current_user
.token
125 with sqlite3
.connect(cf
['global']['database']) as conn
:
126 #with conn.cursor() as c:
129 SELECT subscriptions.channel_id, name,
130 (subscribed_until < datetime('now')) AS obsolete
132 left JOIN channels ON channels.id = subscriptions.channel_id
133 left JOIN websub ON channels.id = websub.channel_id
135 AND subscriptions.type IN ('channel', 'playlist')
136 ORDER BY obsolete=0, name COLLATE NOCASE ASC""", (token
,))
138 'channel_id': channel_id
,
139 'author': author
or channel_id
,
140 'subscribed_until': subscribed_until
141 } for (channel_id
, author
, subscribed_until
) in c
.fetchall()]
142 return render_template('subscription_manager.html.j2', rows
=rows
)
144 @frontend.route('/feed/subscriptions', methods
=['POST'])
147 token
= current_user
.token
148 action
= next(request
.form
.keys(), None)
149 if action
in ['pin', 'unpin', 'hide']:
150 video_id
= request
.form
.get(action
)
156 with sqlite3
.connect(cf
['global']['database']) as conn
:
157 #with conn.cursor() as c:
160 INSERT OR REPLACE INTO flags (user, video_id, display)
162 """, (token
, video_id
, display
))
164 flash("unsupported action", "error")
165 return redirect(request
.url
, code
=303)
167 @frontend.route('/manage/subscriptions', methods
=['POST'])
169 def manage_subscriptions():
170 token
= current_user
.token
171 if 'subscribe' in request
.form
:
172 channel_id
= request
.form
.get("subscribe")
173 match
= re
.search(r
"(UC[A-Za-z0-9_-]{22})", channel_id
)
175 channel_id
= match
.group(1)
177 match
= re
.search(r
"((?:PL|LL|EC|UU|FL|UL|OL)[A-Za-z0-9_-]{10,})", channel_id
)
178 if match
: # NOTE: PL-playlists are 32chars, others differ in length.
179 flash("playlists not (yet?) supported.", "error")
180 return redirect(request
.url
, code
=303) # TODO: dedup redirection
182 flash("not a valid/subscribable URI", "error")
183 return redirect(request
.url
, code
=303) # TODO: dedup redirection
184 with sqlite3
.connect(cf
['global']['database']) as conn
:
185 #with conn.cursor() as c:
188 INSERT OR IGNORE INTO subscriptions (user, channel_id)
190 """, (token
, channel_id
))
191 # TODO: sql-error-handling, asynchronically calling update-subs.pl
193 elif 'unsubscribe' in request
.form
:
194 channel_id
= request
.form
.get("unsubscribe")
195 with sqlite3
.connect(cf
['global']['database']) as conn
:
196 #with conn.cursor() as c:
199 DELETE FROM subscriptions
200 WHERE user = ? AND channel_id = ?
201 """, (token
, channel_id
))
202 # TODO: sql-error-handling, report success
205 flash("unsupported action", "error")
207 return redirect(request
.url
, code
=303)
209 @frontend.route('/r/')
212 @frontend.route('/r/<subreddit>')
213 def reddit(subreddit
="videos"):
214 count
= int(request
.args
.get('count', 0))
215 before
= request
.args
.get('before')
216 after
= request
.args
.get('after')
217 query
= '&'.join([f
"{k}={v}" for k
,v
in [('count',count
), ('before',before
), ('after',after
)] if v
])
218 r
= requests
.get(f
"https://old.reddit.com/r/{subreddit}.json?{query}", headers
={'User-Agent':'Mozilla/5.0'})
219 if not r
.ok
or not 'data' in r
.json():
220 return r
.text
+"error retrieving reddit data", 502
222 good
= [e
for e
in r
.json()['data']['children'] if e
['data']['score'] > 1]
223 bad
= [e
for e
in r
.json()['data']['children'] if e
['data']['score'] <=1]
225 for entry
in (good
+bad
):
227 if e
['domain'] not in ['youtube.com', 'youtu.be', 'invidio.us']:
229 video_id
= re
.match(r
'^https?://(?:www.|m.)?(?:youtube.com/watch\?(?:.*&)?v=|youtu.be/|youtube.com/embed/)([-_0-9A-Za-z]+)', e
['url']).group(1)
230 if not video_id
: continue
232 'video_id': video_id
,
234 'url': e
['permalink'],
235 'n_comments': e
['num_comments'],
236 'n_karma': e
['score'],
238 before
= r
.json()['data']['before']
239 after
= r
.json()['data']['after']
240 return render_template('reddit.html.j2', subreddit
=subreddit
, rows
=videos
, before
=before
, after
=after
, count
=count
)
243 # reload cipher from database every 1 hour
244 if 'cipher' not in g
or time
.time() - g
.get('cipher_updated', 0) > 1 * 60 * 60:
245 with sqlite3
.connect(cf
['global']['database']) as conn
:
247 c
.execute("SELECT sts, algorithm FROM cipher")
248 g
.cipher
= c
.fetchone()
249 g
.cipher_updated
= time
.time()
253 #@frontend.teardown_appcontext
255 # db = g.pop('db', None)
261 @frontend.app_template_filter('format_date')
263 (y
,m
,d
) = (int(n
) for n
in s
.split('T')[0].split(' ')[0].split('-')) # iso-dates can seperate date from time with space or 'T'
264 M
= '_ Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()