forked from Skype-GitHub/YUKI-2
-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.py
376 lines (322 loc) · 16.6 KB
/
main.py
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
import json
import requests
import urllib.parse
import time
import datetime
import random
import os
import subprocess
from cache import cache
ver = "2.6.0" # バージョン
update = "APIサーバーの設定変更" # アップデート内容
token = "e4f5c13f-4f31-4ae1-ac5c-b3f1df232073" # hcaptchaのサイトキー
max_api_wait_time = 3
max_time = 10
apis = [r"https://invidious.jing.rocks/",r"https://inv.nadeko.net/",r"https://invidious.nerdvpn.de/",r"https://invidious.privacyredirect.com/",]
version = "1.0"
adminannounce = requests.get(r'https://ztttas1.github.io/yuki00000000000000000000000000000/AN.txt').text.rstrip()
os.system("chmod 777 ./yukiverify")
# フォーク元:https://github.com/mochidukiyukimi/yuki-youtube-slim-2
# このyuki:https://github.com/Skype-GitHub/YUKI-GOD
# フォークした場合hcaptchaのサイトキーを自分で作り直して使用してください
url = requests.get(r'https://raw.githubusercontent.com/mochidukiyukimi/yuki-youtube-instance/main/instance.txt').text.rstrip()
version = "1.0"
apichannels = []
apicomments = []
[[apichannels.append(i),apicomments.append(i)] for i in apis]
class APItimeoutError(Exception):
pass
def is_json(json_str):
result = False
try:
json.loads(json_str)
result = True
except json.JSONDecodeError as jde:
pass
return result
def apirequest(url):
global apis
global max_time
starttime = time.time()
for api in apis:
if time.time() - starttime >= max_time -1:
break
try:
res = requests.get(api+url,timeout=max_api_wait_time)
if res.status_code == 200 and is_json(res.text):
return res.text
else:
print(f"エラー:{api}")
apis.append(api)
apis.remove(api)
except:
print(f"タイムアウト:{api}")
apis.append(api)
apis.remove(api)
raise APItimeoutError("APIがタイムアウトしました")
def apichannelrequest(url):
global apichannels
global max_time
starttime = time.time()
for api in apichannels:
if time.time() - starttime >= max_time -1:
break
try:
res = requests.get(api+url,timeout=max_api_wait_time)
if res.status_code == 200 and is_json(res.text):
return res.text
else:
print(f"エラー:{api}")
apichannels.append(api)
apichannels.remove(api)
except:
print(f"タイムアウト:{api}")
apichannels.append(api)
apichannels.remove(api)
raise APItimeoutError("APIがタイムアウトしました")
def apicommentsrequest(url):
global apicomments
global max_time
starttime = time.time()
for api in apicomments:
if time.time() - starttime >= max_time -1:
break
try:
res = requests.get(api+url,timeout=max_api_wait_time)
if res.status_code == 200 and is_json(res.text):
return res.text
else:
print(f"エラー:{api}")
apicomments.append(api)
apicomments.remove(api)
except:
print(f"タイムアウト:{api}")
apicomments.append(api)
apicomments.remove(api)
raise APItimeoutError("APIがタイムアウトしました")
def get_info(request):
global version
return json.dumps([version,os.environ.get('RENDER_EXTERNAL_URL'),str(request.scope["headers"]),str(request.scope['router'])[39:-2]])
def get_data(videoid):
global logs
t = json.loads(apirequest(r"api/v1/videos/"+ urllib.parse.quote(videoid)))
return [{"id":i["videoId"],"title":i["title"],"authorId":i["authorId"],"author":i["author"],"viewCountText":i["viewCountText"]} for i in t["recommendedVideos"]],list(reversed([i["url"] for i in t["formatStreams"]]))[:2],t["descriptionHtml"].replace("\n","<br>"),t["title"],t["authorId"],t["author"],t["authorThumbnails"][-1]["url"]
def get_data2(videoid):
global logs
response = apirequest(r"api/v1/videos/" + urllib.parse.quote(videoid))
data = json.loads(response)
# "viewCountText" を抽出
view_count_text = data.get("viewCountText")
return view_count_text
def get_search(q,page):
global logs
t = json.loads(apirequest(fr"api/v1/search?q={urllib.parse.quote(q)}&page={page}&hl=jp"))
def load_search(i):
if i["type"] == "video":
return {"title":i["title"],"id":i["videoId"],"authorId":i["authorId"],"author":i["author"],"length":str(datetime.timedelta(seconds=i["lengthSeconds"])),"published":i["publishedText"],"type":"video"}
elif i["type"] == "playlist":
return {"title":i["title"],"id":i["playlistId"],"thumbnail":i["videos"][0]["videoId"],"count":i["videoCount"],"type":"playlist"}
else:
if i["authorThumbnails"][-1]["url"].startswith("https"):
return {"author":i["author"],"id":i["authorId"],"thumbnail":i["authorThumbnails"][-1]["url"],"type":"channel"}
else:
return {"author":i["author"],"id":i["authorId"],"thumbnail":r"https://"+i["authorThumbnails"][-1]["url"],"type":"channel"}
return [load_search(i) for i in t]
def get_channel(channelid):
global apichannels
t = json.loads(apichannelrequest(r"api/v1/channels/"+ urllib.parse.quote(channelid)))
if t["latestVideos"] == []:
print("APIがチャンネルを返しませんでした")
apichannels.append(apichannels[0])
apichannels.remove(apichannels[0])
raise APItimeoutError("APIがチャンネルを返しませんでした")
return [[{"title":i["title"],"id":i["videoId"],"authorId":t["authorId"],"author":t["author"],"published":i["publishedText"],"type":"video"} for i in t["latestVideos"]],{"channelname":t["author"],"channelicon":t["authorThumbnails"][-1]["url"],"channelprofile":t["descriptionHtml"]}]
def get_playlist(listid,page):
t = json.loads(apirequest(r"/api/v1/playlists/"+ urllib.parse.quote(listid)+"?page="+urllib.parse.quote(page)))["videos"]
return [{"title":i["title"],"id":i["videoId"],"authorId":i["authorId"],"author":i["author"],"type":"video"} for i in t]
def get_comments(videoid):
t = json.loads(apicommentsrequest(r"api/v1/comments/"+ urllib.parse.quote(videoid)+"?hl=jp"))["comments"]
return [{"author":i["author"],"authoricon":i["authorThumbnails"][-1]["url"],"authorid":i["authorId"],"body":i["contentHtml"].replace("\n","<br>")} for i in t]
def get_replies(videoid,key):
t = json.loads(apicommentsrequest(fr"api/v1/comments/{videoid}?hmac_key={key}&hl=jp&format=html"))["contentHtml"]
def get_level(word):
for i1 in range(1,13):
with open(f'Level{i1}.txt', 'r', encoding='UTF-8', newline='\n') as f:
if word in [i2.rstrip("\r\n") for i2 in f.readlines()]:
return i1
return 0
def check_cokie(cookie):
print(cookie)
if cookie == "True":
return True
return False
def get_verifycode():
try:
result = subprocess.run(["./yukiverify"], encoding='utf-8', stdout=subprocess.PIPE)
hashed_password = result.stdout.strip()
return hashed_password
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
return None
from fastapi import FastAPI, Depends
from fastapi import Response,Cookie,Request
from fastapi.responses import HTMLResponse,PlainTextResponse
from fastapi.responses import RedirectResponse as redirect
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import Union
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
app.mount("/css", StaticFiles(directory="./css"), name="static")
app.mount("/js", StaticFiles(directory="./js"), name="static")
app.add_middleware(GZipMiddleware, minimum_size=1000)
from fastapi.templating import Jinja2Templates
template = Jinja2Templates(directory='templates').TemplateResponse
@app.get("/", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
adminannounce = requests.get(r'https://ztttas1.github.io/yuki00000000000000000000000000000/AN.txt').text.rstrip()
if check_cokie(yuki):
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("home.html",{"request": request,"ver":ver, "adminannounce": adminannounce,})
print(check_cokie(yuki))
return redirect("/hcaptcha")
@app.get('/watch', response_class=HTMLResponse)
def video(v:str,response: Response,request: Request,yuki: Union[str] = Cookie(None),proxy: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
response.set_cookie(key="yuki", value="True",max_age=7*24*60*60)
videoid = v
t = get_data(videoid)
t2 = get_data2(videoid)
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template('video.html', {"request": request,"videoid":videoid,"videourls":t[1],"res":t[0],"description":t[2],"videotitle":t[3],"authorid":t[4],"authoricon":t[6],"author":t[5],"viewCountText":t2,"proxy":proxy})
@app.get("/search", response_class=HTMLResponse,)
def search(q:str,response: Response,request: Request,page:Union[int,None]=1,yuki: Union[str] = Cookie(None),proxy: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("search.html", {"request": request,"results":get_search(q,page),"word":q,"next":f"/search?q={q}&page={page + 1}","proxy":proxy})
@app.get("/hashtag/{tag}")
def search(tag:str,response: Response,request: Request,page:Union[int,None]=1,yuki: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
return redirect(f"/search?q={tag}")
@app.get("/channel/{channelid}", response_class=HTMLResponse)
def channel(channelid:str,response: Response,request: Request,yuki: Union[str] = Cookie(None),proxy: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
t = get_channel(channelid)
return template("channel.html", {"request": request,"results":t[0],"channelname":t[1]["channelname"],"channelicon":t[1]["channelicon"],"channelprofile":t[1]["channelprofile"],"proxy":proxy})
@app.get("/answer", response_class=HTMLResponse)
def set_cokie(q:str):
t = get_level(q)
if t > 5:
return f"level{t}\n推測を推奨する"
elif t == 0:
return "level12以上\nほぼ推測必須"
return f"level{t}\n覚えておきたいレベル"
@app.get("/playlist", response_class=HTMLResponse)
def playlist(list:str,response: Response,request: Request,page:Union[int,None]=1,yuki: Union[str] = Cookie(None),proxy: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("search.html", {"request": request,"results":get_playlist(list,str(page)),"word":"","next":f"/playlist?list={list}","proxy":proxy})
@app.get("/info", response_class=HTMLResponse)
def viewlist(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
global apis,apichannels,apicomments
if not(check_cokie(yuki)):
return redirect("/")
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("info.html",{"request": request,"Youtube_API":apis[0],"Channel_API":apichannels[0],"Comments_API":apicomments[0]})
@app.get("/suggest")
def suggest(keyword:str):
return [i[0] for i in json.loads(requests.get(r"http://www.google.com/complete/search?client=youtube&hl=ja&ds=yt&q="+urllib.parse.quote(keyword)).text[19:-1])[1]]
@app.get("/comments")
def comments(request: Request,v:str):
return template("comments.html",{"request": request,"comments":get_comments(v)})
@app.get("/thumbnail")
def thumbnail(v:str):
return Response(content = requests.get(fr"https://img.youtube.com/vi/{v}/0.jpg").content,media_type=r"image/jpeg")
@app.get("/bbs",response_class=HTMLResponse)
def view_bbs(request: Request,name: Union[str, None] = "",seed:Union[str,None]="",channel:Union[str,None]="main",verify:Union[str,None]="false",yuki: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
res = HTMLResponse(requests.get(fr"{url}bbs?name={urllib.parse.quote(name)}&seed={urllib.parse.quote(seed)}&channel={urllib.parse.quote(channel)}&verify={urllib.parse.quote(verify)}",cookies={"yuki":"True"}).text)
return res
@cache(seconds=5)
def bbsapi_cached(verify,channel):
return requests.get(fr"{url}bbs/api?t={urllib.parse.quote(str(int(time.time()*1000)))}&verify={urllib.parse.quote(verify)}&channel={urllib.parse.quote(channel)}",cookies={"yuki":"True"}).text
@app.get("/bbs/api",response_class=HTMLResponse)
def view_bbs(request: Request,t: str,channel:Union[str,None]="main",verify: Union[str,None] = "false"):
print(fr"{url}bbs/api?t={urllib.parse.quote(t)}&verify={urllib.parse.quote(verify)}&channel={urllib.parse.quote(channel)}")
return bbsapi_cached(verify,channel)
@app.get("/bbs/result")
def write_bbs(request: Request,name: str = "",message: str = "",seed:Union[str,None] = "",channel:Union[str,None]="main",verify:Union[str,None]="false",yuki: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
t = requests.get(fr"{url}bbs/result?name={urllib.parse.quote(name)}&message={urllib.parse.quote(message)}&seed={urllib.parse.quote(seed)}&channel={urllib.parse.quote(channel)}&verify={urllib.parse.quote(verify)}&info={urllib.parse.quote(get_info(request))}&serververify={get_verifycode()}",cookies={"yuki":"True"}, allow_redirects=False)
if t.status_code != 307:
return HTMLResponse(t.text)
return redirect(f"/bbs?name={urllib.parse.quote(name)}&seed={urllib.parse.quote(seed)}&channel={urllib.parse.quote(channel)}&verify={urllib.parse.quote(verify)}")
@cache(seconds=30)
def how_cached():
return requests.get(fr"{url}bbs/how").text
@app.get("/bbs/how",response_class=PlainTextResponse)
def view_commonds(request: Request,yuki: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
return how_cached()
@app.get("/load_instance")
def home():
global url
url = requests.get(r'https://raw.githubusercontent.com/mochidukiyukimi/yuki-youtube-instance/main/instance.txt').text.rstrip()
@app.exception_handler(500)
def page(request: Request,__):
return template("APIwait.html",{"request": request},status_code=500)
@app.exception_handler(APItimeoutError)
def APIwait(request: Request,exception: APItimeoutError):
return template("APIwait.html",{"request": request},status_code=500)
@app.get("/updateinfo", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if check_cokie(yuki):
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("apd1.html",{"request": request,"ver":ver,"update":update})
print(check_cokie(yuki))
return redirect("/")
@app.get("/instance", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if check_cokie(yuki):
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("ins.html",{"request": request})
print(check_cokie(yuki))
return redirect("/")
@app.get("/build", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if check_cokie(yuki):
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("build.html",{"request": request})
print(check_cokie(yuki))
return redirect("/")
@app.get("/qa", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if check_cokie(yuki):
response.set_cookie("yuki","True",max_age=60 * 60 * 24 * 7)
return template("qanda.html",{"request": request})
print(check_cokie(yuki))
return redirect("/")
@app.get("/hcaptcha", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if (check_cokie(yuki)):
return redirect("/")
return template("hcaptcha.html",{"request": request,"token": token})
@app.get("/word", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if (check_cokie(yuki)):
return redirect("/")
return template("word2.html",{"request": request})
@app.get("/like", response_class=HTMLResponse)
def home(response: Response,request: Request,yuki: Union[str] = Cookie(None)):
if not(check_cokie(yuki)):
return redirect("/")
return template("okini.html",{"request": request})