tubearchivist/tubearchivist/home/src/download/yt_cookie.py

89 lines
2.4 KiB
Python
Raw Normal View History

2022-04-30 05:05:41 +00:00
"""
functionality:
- import yt cookie from filesystem
- make cookie available for yt-dlp
"""
import os
2022-04-30 06:05:01 +00:00
import yt_dlp
2022-04-30 05:05:41 +00:00
from home.src.ta.config import AppConfig
from home.src.ta.ta_redis import RedisArchivist
class CookieHandler:
"""handle youtube cookie for yt-dlp"""
CONFIG = AppConfig().config
CACHE_PATH = CONFIG["application"]["cache_dir"]
COOKIE_FILE_NAME = "cookies.google.txt"
2022-04-30 09:38:23 +00:00
COOKIE_KEY = "cookie"
COOKIE_PATH = "cookie.txt"
2022-04-30 05:05:41 +00:00
def import_cookie(self):
"""import cookie from file"""
import_path = os.path.join(
self.CACHE_PATH, "import", self.COOKIE_FILE_NAME
)
with open(import_path, encoding="utf-8") as cookie_file:
cookie = cookie_file.read()
2022-04-30 09:38:23 +00:00
RedisArchivist().set_message(self.COOKIE_KEY, cookie, expire=False)
2022-04-30 05:05:41 +00:00
os.remove(import_path)
print("cookie: import successfully")
def use(self):
"""make cookie available in FS"""
2022-04-30 09:38:23 +00:00
cookie = RedisArchivist().get_message(self.COOKIE_KEY)
if isinstance(cookie, dict):
print("no cookie imported")
raise FileNotFoundError
2022-05-07 02:34:33 +00:00
if os.path.exists(self.COOKIE_PATH):
return self.COOKIE_PATH
2022-04-30 09:38:23 +00:00
with open(self.COOKIE_PATH, "w", encoding="utf-8") as cookie_file:
2022-04-30 05:05:41 +00:00
cookie_file.write(cookie)
print("cookie: made available")
2022-04-30 09:38:23 +00:00
return self.COOKIE_PATH
2022-04-30 05:05:41 +00:00
def hide(self):
"""hide cookie file if not in use"""
try:
2022-04-30 09:38:23 +00:00
os.remove(self.COOKIE_PATH)
2022-04-30 11:34:28 +00:00
except FileNotFoundError:
2022-04-30 05:05:41 +00:00
print("cookie: not available")
return
print("cookie: hidden")
def revoke(self):
"""revoke cookie"""
self.hide()
2022-04-30 09:38:23 +00:00
RedisArchivist().del_message(self.COOKIE_KEY)
2022-04-30 05:05:41 +00:00
print("cookie: revoked")
2022-04-30 06:05:01 +00:00
def validate(self):
"""validate cookie using the liked videos playlist"""
try:
_ = self.use()
except FileNotFoundError:
return False
2022-04-30 06:05:01 +00:00
url = "https://www.youtube.com/playlist?list=LL"
yt_obs = {
"quiet": True,
"skip_download": True,
"extract_flat": True,
2022-04-30 09:38:23 +00:00
"cookiefile": self.COOKIE_PATH,
2022-04-30 06:05:01 +00:00
}
try:
response = yt_dlp.YoutubeDL(yt_obs).extract_info(url)
except yt_dlp.utils.DownloadError:
print("failed to validate cookie")
response = False
return bool(response)