-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
775 lines (632 loc) · 28 KB
/
Copy pathbackend.py
File metadata and controls
775 lines (632 loc) · 28 KB
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# backend.py
# Cleaned and merged backend for your revival + yt2009 playback
import html
import random
import string
import requests
from datetime import datetime, timezone
from flask import Flask, request, Response, redirect
from yt_dlp import YoutubeDL
from innertube import InnerTube
from xml.etree.ElementTree import Element, SubElement, tostring
import os
app = Flask(__name__)
# --- Innertube clients ---
yt_client = InnerTube("WEB")
yt_android = InnerTube("ANDROID")
# ------------------------------------------------------------
# Helper: dynamic base URL for feeds/static
# ------------------------------------------------------------
def base_url():
return f"https://{request.host}"
# ------------------------------------------------------------
# Comments via yt-dlp (legacy /feeds/api/videos/<id>/comments)
# ------------------------------------------------------------
def comments_to_atom(video_id, limit=15, start=0):
url = f"https://www.youtube.com/watch?v={video_id}"
ydl_opts = {
"skip_download": True,
"getcomments": True,
"quiet": True,
"max_comments": 200,
"format": "bestvideo+bestaudio/best",
}
with YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
comments = info.get("comments", [])[start:start + limit]
feed = Element("feed", xmlns="http://www.w3.org/2005/Atom")
title = SubElement(feed, "title")
title.text = f"Comments for {info.get('title', 'Unknown Video')}"
for c in comments:
entry = SubElement(feed, "entry")
author = SubElement(entry, "author")
name = SubElement(author, "name")
name.text = c.get("author", "Unknown")
content = SubElement(entry, "content")
content.text = c.get("text", "")
updated = SubElement(entry, "updated")
updated.text = c.get("_time_text", "Unknown")
SubElement(entry, "category", term="likes").text = str(c.get("like_count", 0))
return tostring(feed, encoding="unicode")
# ------------------------------------------------------------
# Innertube comment helpers (newer comments feed)
# ------------------------------------------------------------
def find_comment_token(next_data):
token = None
def walk(obj):
nonlocal token
if isinstance(obj, dict):
if "continuationCommand" in obj:
token = obj["continuationCommand"].get("token")
for v in obj.values():
walk(v)
elif isinstance(obj, list):
for item in obj:
walk(item)
walk(next_data)
return token
def extract_comments(next_data):
comments = []
def walk(obj):
if isinstance(obj, dict):
if "commentThreadRenderer" in obj:
cr = obj["commentThreadRenderer"].get("comment", {}).get("commentRenderer")
if cr:
comments.append(cr)
for v in obj.values():
walk(v)
elif isinstance(obj, list):
for item in obj:
walk(item)
walk(next_data)
return comments
def build_comment_entry(cr):
cid = cr.get("commentId")
author = cr.get("authorText", {}).get("simpleText", "")
content = cr.get("contentText", {}).get("simpleText", "")
published = cr.get("publishedTimeText", {}).get("simpleText", "")
return f"""
<entry>
<id>tag:youtube.com,2008:comment:{cid}</id>
<author><name>{author}</name></author>
<published>{published}</published>
<content type="text">{content}</content>
</entry>
"""
def build_comments_feed(video_id):
try:
first = yt_android.next(video_id)
token = find_comment_token(first)
comment_items = []
if token:
second = yt_android.next(continuation=token)
comment_items = extract_comments(second)
except Exception as e:
print("DEBUG comments fetch failed:", e)
comment_items = []
entries = [build_comment_entry(cr) for cr in comment_items]
now = datetime.now(timezone.utc).isoformat()
return f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:gd="http://schemas.google.com/g/2005">
<id>{base_url()}/feeds/api/videos/{video_id}/comments</id>
<updated>{now}</updated>
<title type="text">Comments for {video_id}</title>
{''.join(entries)}
</feed>
"""
# ------------------------------------------------------------
# Video extraction helpers
# ------------------------------------------------------------
def extract_videos(search_data):
videos = []
def walk(obj):
if isinstance(obj, dict):
for k, v in obj.items():
if k == "videoRenderer":
videos.append(v)
else:
walk(v)
elif isinstance(obj, list):
for item in obj:
walk(item)
walk(search_data)
return videos
# ------------------------------------------------------------
# Playback (yt2009)
# ------------------------------------------------------------
def playback_link(video_id, mode="rtsp_mp4"):
lookup = {
"rtsp_mp4": f"https://yt2009.truehosting.net/mobile/create_rtsp?v={video_id}",
"rtsp_3gp": f"https://yt2009.truehosting.net/mobile/create_rtsp?v={video_id}&3gp=1",
"http_mp4": f"https://yt2009.truehosting.net/get_video?video_id={video_id}/mp4",
"http_3gp": f"https://yt2009.truehosting.net/http_3gp?v={video_id}",
"http_wmv": f"https://yt2009.truehosting.net/http_wmv?v={video_id}",
"http_xvid": f"https://yt2009.truehosting.net/http_xvid?v={video_id}",
"http_flash": f"https://yt2009.truehosting.net/mobile/watch?v={video_id}",
}
return lookup.get(mode, lookup["rtsp_mp4"])
# ------------------------------------------------------------
# RYD stats
# ------------------------------------------------------------
def get_ryd_stats(video_id):
try:
resp = requests.get(
f"https://returnyoutubedislikeapi.com/votes?videoId={video_id}",
timeout=5,
)
if resp.status_code == 200:
data = resp.json()
return str(data.get("likes", 0)), str(data.get("dislikes", 0))
except Exception as e:
print("RYD fetch failed:", e)
return "0", "0"
# ------------------------------------------------------------
# Build feed entry
# ------------------------------------------------------------
def parse_duration(text):
try:
parts = text.split(":")
if len(parts) == 2:
return int(parts[0]) * 60 + int(parts[1])
if len(parts) == 3:
return int(parts[0]) * 3600 + int(parts[1]) * 60 + int(parts[2])
except:
pass
return 0
def build_entry(video):
vid = video.get("videoId", "dummy123")
title = video.get("title", {}).get("runs", [{}])[0].get("text", "Untitled")
desc = video.get("descriptionSnippet", {}).get("runs", [{}])[0].get("text", "")
author = (
video.get("ownerText", {}).get("runs", [{}])[0].get("text")
or video.get("shortBylineText", {}).get("runs", [{}])[0].get("text")
or "Unknown"
)
thumb_list = video.get("thumbnail", {}).get("thumbnails", [])
thumb = thumb_list[-1]["url"] if thumb_list else f"https://i.ytimg.com/vi/{vid}/hqdefault.jpg"
thumb = html.escape(thumb)
length_text = video.get("lengthText", {}).get("simpleText", "0:00")
duration_seconds = parse_duration(length_text)
view_count = "0"
keywords = title
published = datetime.now(timezone.utc).isoformat()
try:
player_data = yt_client.player(vid)
details = player_data.get("videoDetails", {})
micro = player_data.get("microformat", {}).get("playerMicroformatRenderer", {})
desc = details.get("shortDescription", desc)
view_count = details.get("viewCount", view_count)
keywords = ",".join(details.get("keywords", [title]))
published = micro.get("publishDate", published)
except Exception as e:
print("DEBUG player enrichment failed:", e)
like_count, dislike_count = get_ryd_stats(vid)
now = datetime.now(timezone.utc).isoformat()
b = base_url()
return f"""
<entry>
<id>{b}/feeds/api/videos/{vid}</id>
<youTubeId id="{vid}">{vid}</youTubeId>
<published>{published}</published>
<updated>{now}</updated>
<title type="text">{html.escape(title)}</title>
<content type="text">{html.escape(desc)}</content>
<link rel="http://gdata.youtube.com/schemas/2007#video.related"
href="{b}/feeds/api/videos/{vid}/related"/>
<author><name>{html.escape(author)}</name></author>
<gd:comments>
<gd:feedLink href="{b}/feeds/api/videos/{vid}/comments" countHint="0"/>
</gd:comments>
<media:group>
<media:content url="{playback_link(vid)}"
type="video/mp4"
medium="video"
expression="full"
duration="{duration_seconds}"/>
<media:description type="plain">{html.escape(desc)}</media:description>
<media:keywords>{html.escape(keywords)}</media:keywords>
<media:player url="{b}/watch?v={vid}"/>
<media:thumbnail url="{thumb}" height="240" width="320"/>
<yt:duration seconds="{duration_seconds}"/>
<yt:videoid id="{vid}">{vid}</yt:videoid>
<media:credit role="uploader" name="{html.escape(author)}">{html.escape(author)}</media:credit>
</media:group>
<yt:statistics viewCount="{view_count}"/>
<yt:rating numLikes="{like_count}" numDislikes="{dislike_count}"/>
</entry>
"""
# ------------------------------------------------------------
# Build entire feed
# ------------------------------------------------------------
def build_feed(feed_id, feed_title, data):
entries = []
if data:
search_results = data.get("contents", {}).get("twoColumnSearchResultsRenderer", {})
primary = search_results.get("primaryContents", {}).get("sectionListRenderer", {})
for section in primary.get("contents", []):
item_section = section.get("itemSectionRenderer", {})
for item in item_section.get("contents", []):
video = item.get("videoRenderer")
if video:
entries.append(build_entry(video))
if not entries:
entries.append(build_entry({
"videoId": "dummy123",
"title": {"runs": [{"text": "Shrek Saxophone"}]},
"descriptionSnippet": {"runs": [{"text": "Shrek playing saxophone"}]},
"ownerText": {"runs": [{"text": "get out of my SWAP"}]},
"thumbnail": {"thumbnails": [{"url": "https://i.ytimg.com/vi/dummy123/hqdefault.jpg"}]},
"lengthText": {"simpleText": "2:00"},
}))
return f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:standardfeed:{feed_id}</id>
<title type="text">{feed_title}</title>
<openSearch:totalResults>{len(entries)}</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
{''.join(entries)}
</feed>
"""
# ------------------------------------------------------------
# Core routes (feeds, search, playback)
# ------------------------------------------------------------
@app.route("/get_video_info")
def get_video_info():
video_id = request.args.get("video_id")
if not video_id:
return "status=fail", 400
stream_url = playback_link(video_id)
response = f"url={stream_url}&title=Unknown&length_seconds=0&status=ok"
return Response(response, mimetype="text/plain")
@app.route("/videoplayback")
def videoplayback():
video_id = request.args.get("id")
if not video_id:
return redirect(f"{base_url()}/static/shrek.mp4")
return redirect(playback_link(video_id))
@app.route("/feeds/api/standardfeeds/<region>/most_popular")
@app.route("/feeds/api/standardfeeds/most_popular")
def most_popular(region=None):
try:
data = yt_client.search("trending")
except Exception as e:
print("DEBUG most_popular error:", e)
data = None
return Response(build_feed("most_popular", "Most Popular", data),
mimetype="application/atom+xml")
@app.route("/feeds/api/standardfeeds/<region>/recently_featured")
@app.route("/feeds/api/standardfeeds/recently_featured")
def recently_featured(region=None):
try:
data = yt_client.search("featured")
except Exception as e:
print("DEBUG recently_featured error:", e)
data = None
return Response(build_feed("recently_featured", "Recently Featured", data),
mimetype="application/atom+xml")
@app.route("/feeds/api/standardfeeds/<region>/most_discussed")
@app.route("/feeds/api/standardfeeds/most_discussed")
def most_discussed(region=None):
try:
data = yt_client.search("most discussed")
except Exception as e:
print("DEBUG most_discussed error:", e)
data = None
return Response(build_feed("most_discussed", "Most Discussed", data),
mimetype="application/atom+xml")
@app.route("/feeds/api/standardfeeds/<region>/top_rated")
@app.route("/feeds/api/standardfeeds/top_rated")
def top_rated(region=None):
try:
data = yt_client.search("top rated videos")
except Exception as e:
print("DEBUG top_rated error:", e)
data = None
return Response(build_feed("top_rated", "Top Rated", data),
mimetype="application/atom+xml")
@app.route("/feeds/api/standardfeeds/<region>/top_favorites")
@app.route("/feeds/api/standardfeeds/top_favorites")
def top_favorites(region=None):
try:
data = yt_client.search("favorite videos")
except Exception as e:
print("DEBUG top_favorites error:", e)
data = None
return Response(build_feed("top_favorites", "Top Favorites", data),
mimetype="application/atom+xml")
@app.route("/feeds/api/videos/<video_id>/comments")
def legacy_comments_feed(video_id):
start = int(request.args.get("start-index", 1)) - 1
limit = int(request.args.get("max-results", 15))
xml_output = comments_to_atom(video_id, limit=limit, start=start)
return Response(xml_output, mimetype="text/xml")
@app.route("/feeds/api/videos")
def search_videos():
query = request.args.get("q", "")
print(f"🔍 Search requested: {query}")
try:
data = yt_client.search(query)
except Exception as e:
print("DEBUG search error:", e)
data = None
feed_xml = build_feed("search", f"Search results for {query}", data)
return Response(feed_xml, mimetype="application/atom+xml")
@app.route("/feeds/api/videos/<video_id>/related")
def related_feed(video_id):
try:
player_data = yt_client.player(video_id)
title = player_data.get("videoDetails", {}).get("title", "")
keywords = player_data.get("videoDetails", {}).get("keywords", [])
query = keywords[0] if keywords else title
search_data = yt_client.search(query)
related_items = extract_videos(search_data)
related_items = [rv for rv in related_items if rv.get("videoId") != video_id]
entries = [build_entry(rv) for rv in related_items]
except Exception as e:
print("DEBUG related fetch failed:", e)
entries = []
now = datetime.now(timezone.utc).isoformat()
b = base_url()
return Response(f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:gd="http://schemas.google.com/g/2005">
<id>{b}/feeds/api/videos/{video_id}/related</id>
<updated>{now}</updated>
<title type="text">Related videos for {video_id}</title>
{''.join(entries)}
</feed>
""", mimetype="application/atom+xml")
# ------------------------------------------------------------
# Debug + user feeds (uploads, playlists, activity, etc.)
# ------------------------------------------------------------
@app.route("/debug_search/<query>")
def debug_search(query):
try:
data = yt_client.search(query)
return data
except Exception as e:
return {"error": str(e)}
@app.route("/feeds/api/users/<username>/uploads")
def user_uploads(username):
try:
data = yt_client.search(username)
entries = []
for section in data.get("contents", []):
if isinstance(section, dict):
sec_contents = section.get("itemSectionRenderer", {}).get("contents", [])
for item in sec_contents:
video = item.get("videoRenderer")
if video:
entries.append(build_entry(video))
b = base_url()
uploads_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:user:{username}:uploads</id>
<title>Uploads by {username}</title>
<generator version="2.0" uri="http://gdata.youtube.com/">YouTube data API</generator>
<author>
<name>{username}</name>
<uri>http://www.youtube.com/profile?user={username}</uri>
<yt:userId>UCswamp123</yt:userId>
</author>
<media:thumbnail url="{b}/static/shrekpfp.jpg" width="88" height="88"/>
<yt:statistics subscriberCount="42" viewCount="1337"/>
<openSearch:totalResults>{len(entries)}</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
{''.join(entries)}
</feed>"""
return Response(uploads_feed, mimetype="application/atom+xml")
except Exception as e:
return Response(
f"<feed><title>Error</title><entry><title>{html.escape(str(e))}</title></entry></feed>",
mimetype="application/atom+xml",
)
# Simple dummy favorites feed
dummy_feed = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Favorites</title>
<entry><title>Shrek Saxophone (Favorite)</title></entry>
</feed>"""
@app.route("/feeds/api/users/<username>/favorites")
def user_favorites(username):
return Response(dummy_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/users/<username>/playlists")
def user_playlists(username):
b = base_url()
playlists_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:user:{username}:playlists</id>
<title>Playlists of {username}</title>
<generator version="2.0" uri="http://gdata.youtube.com/">YouTube data API</generator>
<author><name>{username}</name></author>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
<entry>
<id>tag:youtube.com,2008:playlist:swampjams</id>
<published>{datetime.utcnow().isoformat()}Z</published>
<updated>{datetime.utcnow().isoformat()}Z</updated>
<title>Swamp Jams</title>
<summary>A playlist of Shrek and friends music videos</summary>
<link rel="alternate" type="text/html"
href="http://www.youtube.com/view_play_list?p=swampjams"/>
<gd:feedLink rel="http://gdata.youtube.com/schemas/2007#playlist"
href="{b}/feeds/api/playlists/swampjams"
countHint="1"/>
<yt:playlistId>swampjams</yt:playlistId>
<yt:countHint>1</yt:countHint>
<media:group>
<media:title type="plain">Swamp Jams</media:title>
<media:description type="plain">A playlist of Shrek and friends music videos</media:description>
<media:thumbnail url="{b}/static/shrekthumb.jpg" width="120" height="90"/>
</media:group>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://gdata.youtube.com/schemas/2007#playlist"/>
</entry>
</feed>"""
return Response(playlists_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/playlists/<path:subpath>")
def debug_playlists(subpath):
print("DEBUG: client requested /feeds/api/playlists/" + subpath)
return Response(
f"<feed><title>Debug placeholder for {subpath}</title></feed>",
mimetype="application/atom+xml",
)
@app.route("/feeds/api/playlists/<playlist_id>")
def playlist_contents(playlist_id):
print("DEBUG playlist contents request:", playlist_id)
return playlist_feed_response(playlist_id)
@app.route("/feeds/api/playlists/<playlist_id>/videos")
def playlist_contents_videos(playlist_id):
return playlist_feed_response(playlist_id)
def playlist_feed_response(playlist_id):
b = base_url()
playlist_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:gd="http://schemas.google.com/g/2005"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:playlist:{playlist_id}</id>
<title>Playlist {playlist_id}</title>
<generator version="2.0" uri="http://gdata.youtube.com/">YouTube data API</generator>
<author><name>get out of my SWAP</name></author>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
<entry>
<id>tag:youtube.com,2008:video:dummy123</id>
<published>2026-02-24T18:00:00Z</published>
<updated>2026-02-24T18:00:00Z</updated>
<title>Shrek Saxophone</title>
<author><name>get out of my SWAP</name></author>
<link rel="alternate" type="text/html"
href="http://www.youtube.com/watch?v=dummy123"/>
<link rel="http://gdata.youtube.com/schemas/2007#video"
href="{b}/feeds/api/videos/dummy123"/>
<media:group>
<media:title type="plain">Shrek Saxophone</media:title>
<media:content url="{b}/static/shrek.mp4" type="video/mp4" duration="120"/>
<media:thumbnail url="{b}/static/shrekthumb.jpg" width="120" height="90"/>
<yt:duration seconds="120"/>
<yt:videoid>dummy123</yt:videoid>
</media:group>
<category scheme="http://schemas.google.com/g/2005#kind"
term="http://gdata.youtube.com/schemas/2007#video"/>
</entry>
</feed>"""
print("DEBUG playlist contents feed:\n", playlist_feed)
return Response(playlist_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/users/<username>/subscriptions")
def user_subscriptions(username):
subs_feed = """<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title>Subscriptions</title>
<entry><title>Donkey Channel</title></entry>
</feed>"""
return Response(subs_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/users/<username>/activity")
def user_activity(username):
activity_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:user:{username}:activity</id>
<title>Activity of {username}</title>
<generator version="2.0" uri="http://gdata.youtube.com/">YouTube data API</generator>
<author><name>{username}</name></author>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
<entry>
<id>tag:youtube.com,2008:activity:1</id>
<title>{username} uploaded Shrek Saxophone</title>
<author><name>{username}</name></author>
<published>2026-02-24T18:00:00Z</published>
<updated>2026-02-24T18:00:00Z</updated>
<content>Uploaded a new video: Shrek Saxophone</content>
</entry>
</feed>"""
return Response(activity_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/events")
def events_feed():
author = request.args.get("author", "unknown")
events_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">
<id>tag:youtube.com,2008:events:{author}</id>
<title>Events for {author}</title>
<generator version="2.0" uri="http://gdata.youtube.com/">YouTube data API</generator>
<author><name>{author}</name></author>
<openSearch:totalResults>1</openSearch:totalResults>
<openSearch:startIndex>1</openSearch:startIndex>
<openSearch:itemsPerPage>15</openSearch:itemsPerPage>
<entry>
<id>tag:youtube.com,2008:event:1</id>
<title>{author} uploaded Shrek Saxophone</title>
<author><name>{author}</name></author>
<published>2026-02-24T18:00:00Z</published>
<updated>2026-02-24T18:00:00Z</updated>
<content>Uploaded a new video: Shrek Saxophone</content>
</entry>
</feed>"""
return Response(events_feed, mimetype="application/atom+xml")
@app.route("/feeds/api/users/<username>")
def user_info(username):
b = base_url()
user_feed = f"""<?xml version="1.0" encoding="UTF-8"?>
<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:yt="http://gdata.youtube.com/schemas/2007"
xmlns:media="http://search.yahoo.com/mrss/"
xmlns:gd="http://schemas.google.com/g/2005">
<id>tag:youtube.com,2008:user:{username}</id>
<published>2026-02-24T18:00:00Z</published>
<updated>2026-02-24T18:00:00Z</updated>
<title>{username}</title>
<summary>Welcome to the swamp — Shrek’s official channel revival.</summary>
<author><name>{username}</name></author>
<yt:username>{username}</yt:username>
<yt:channelId>UCswamp123</yt:channelId>
<media:thumbnail url="{b}/static/shrekpfp.jpg" width="88" height="88"/>
<yt:statistics subscriberCount="42" viewCount="1337"/>
</entry>"""
print("DEBUG user info feed:\n", user_feed)
return Response(user_feed, mimetype="application/atom+xml")
# ------------------------------------------------------------
# Auth-ish endpoints (registerDevice, ClientLogin)
# ------------------------------------------------------------
@app.route("/youtube/accounts/registerDevice", methods=["POST"])
def register_device():
chars = string.ascii_lowercase + string.digits
device_id = "".join(random.choice(chars) for _ in range(5))
device_key = "ULxlVAAVMhZ2GeqZA/X1GgqEEIP1ibcd3S+42pkWfmk="
response = f"DeviceId={device_id}\nDeviceKey={device_key}"
return Response(response, mimetype="text/plain")
@app.route("/accounts/ClientLogin", methods=["POST"])
def client_login():
username = request.form.get("username", "dummyUser")
token = f"{username}_token"
response = f"SID=dummySID\nLSID=dummyLSID\nAuth={token}\n"
return Response(response, mimetype="text/plain")
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8000))
app.run(host="0.0.0.0", port=port)