├── docs ├── _config.yml ├── index.html └── templates.html ├── run_dev.sh ├── requirements-dev.txt ├── requirements.txt ├── ytstudio ├── __main__.py ├── __init__.py └── templates.py ├── examples ├── login.json ├── upload_video.py ├── schedule_upload_video.py ├── get_videos.py └── edit_video.py ├── tests └── test_upload_video.py ├── setup.py ├── README.md ├── .gitignore └── LICENSE /docs/_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /run_dev.sh: -------------------------------------------------------------------------------- 1 | pdoc --html ytstudio 2 | pytest 3 | -------------------------------------------------------------------------------- /requirements-dev.txt: -------------------------------------------------------------------------------- 1 | pytest 2 | pytest-asyncio 3 | pdoc3 -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | js2py 2 | aiohttp 3 | pyquery 4 | aiofiles -------------------------------------------------------------------------------- /ytstudio/__main__.py: -------------------------------------------------------------------------------- 1 | if __name__ == "__main__": 2 | pass -------------------------------------------------------------------------------- /examples/login.json: -------------------------------------------------------------------------------- 1 | { 2 | "SESSION_TOKEN": "", 3 | "VISITOR_INFO1_LIVE": "", 4 | "PREF": "", 5 | "LOGIN_INFO": "", 6 | "SID": "", 7 | "__Secure-3PSID": "", 8 | "HSID": "", 9 | "SSID": "", 10 | "APISID": "", 11 | "SAPISID": "", 12 | "__Secure-3PAPISID": "", 13 | "YSC": "", 14 | "SIDCC": "" 15 | } -------------------------------------------------------------------------------- /tests/test_upload_video.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import ytstudio 3 | import json 4 | import os 5 | 6 | if os.path.exists("./login.json"): 7 | LOGIN_FILE = json.loads(open("./login.json", "r")) 8 | else: 9 | exit("can't run test without login json") 10 | 11 | studio = ytstudio.Studio(LOGIN_FILE) 12 | 13 | 14 | @pytest.mark.asyncio 15 | async def test_upload_video(): 16 | await studio.login() 17 | assert 'videoId' in (await studio.uploadVideo(os.path.join( 18 | os.getcwd(), "test.mp4"))) 19 | -------------------------------------------------------------------------------- /examples/upload_video.py: -------------------------------------------------------------------------------- 1 | from ytstudio import Studio 2 | import asyncio 3 | import os 4 | import json 5 | 6 | 7 | def progress(yuklenen, toplam): 8 | print(f"{round(yuklenen / toplam) * 100}% upload", end="\r") 9 | pass 10 | 11 | 12 | if os.path.exists("./login.json"): 13 | LOGIN_FILE = json.loads(open("./login.json", "r").read()) 14 | else: 15 | exit("can't run example without login json") 16 | 17 | yt = Studio(LOGIN_FILE) 18 | 19 | 20 | async def main(): 21 | await yt.login() 22 | sonuc = await yt.uploadVideo(os.path.join(os.getcwd(), "test_video.mp4"), progress=progress) 23 | print(f"successfully uploaded! videoId: {sonuc['videoId']}") 24 | 25 | loop = asyncio.get_event_loop() 26 | loop.run_until_complete(main()) 27 | -------------------------------------------------------------------------------- /examples/schedule_upload_video.py: -------------------------------------------------------------------------------- 1 | from ytstudio import Studio 2 | import asyncio 3 | import os 4 | import json 5 | import datetime 6 | 7 | 8 | def progress(yuklenen, toplam): 9 | print(f"{round(yuklenen / toplam) * 100}% upload", end="\r") 10 | pass 11 | 12 | 13 | if os.path.exists("./login.json"): 14 | LOGIN_FILE = json.loads(open("./login.json", "r").read()) 15 | else: 16 | exit("can't run example without login json") 17 | 18 | yt = Studio(LOGIN_FILE) 19 | 20 | 21 | async def main(): 22 | await yt.login() 23 | up_result, edit_result = await yt.scheduledUploadVideo(os.path.join(os.getcwd(), "test_video.mp4"), progress=progress, schedule_time=datetime.datetime.now() + datetime.timedelta(minutes=30), scheduled_privacy="PUBLIC", ) 24 | print(f"successfully uploaded! videoId: {up_result['videoId']}") 25 | 26 | loop = asyncio.get_event_loop() 27 | loop.run_until_complete(main()) 28 | -------------------------------------------------------------------------------- /examples/get_videos.py: -------------------------------------------------------------------------------- 1 | from ytstudio import Studio 2 | import asyncio 3 | import json 4 | import os 5 | 6 | 7 | async def get_video_list(): 8 | if os.path.exists("./login.json"): 9 | LOGIN_FILE = json.loads(open("./login.json", "r").read()) 10 | else: 11 | exit("can't run example without login json") 12 | 13 | yt = Studio(LOGIN_FILE) 14 | 15 | await yt.login() 16 | sonuc = await yt.listVideos() 17 | print(sonuc) 18 | 19 | 20 | async def get_video(): 21 | if os.path.exists("./login.json"): 22 | LOGIN_FILE = json.loads(open("./login.json", "r")) 23 | else: 24 | exit("can't run example without login json") 25 | 26 | yt = Studio(LOGIN_FILE) 27 | 28 | await yt.login() 29 | sonuc = await yt.getVideo("aaaaaaa") 30 | print(sonuc) 31 | 32 | loop = asyncio.get_event_loop() 33 | loop.run_until_complete(get_video()) 34 | loop.run_until_complete(get_video_list()) 35 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | 2 | import setuptools 3 | 4 | required = ["js2py", "aiohttp", "pyquery", "aiofiles"] 5 | long_description = open('README.md').read() 6 | 7 | setuptools.setup( 8 | name='ytstudio', 9 | version='1.5.2', 10 | description='Unofficial API for Youtube Studio.', 11 | long_description=long_description, 12 | author='Yusuf Usta', 13 | author_email='yusuf@usta.email', 14 | maintainer='Yusuf Usta', 15 | maintainer_email='yusuf@usta.email', 16 | url='https://github.com/yusufusta/ytstudio', 17 | license='GPL3', 18 | packages=['ytstudio'], 19 | install_requires=required, 20 | keywords=['youtube', 'youtube-studio', 'ytstudio', 'studio'], 21 | long_description_content_type="text/markdown", 22 | classifiers=[ 23 | 'Intended Audience :: Developers', 24 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 25 | 'Programming Language :: Python :: 3.7', 26 | 'Programming Language :: Python :: 3.8', 27 | 'Programming Language :: Python :: 3.9', 28 | 'Programming Language :: Python :: 3.10' 29 | ], 30 | ) 31 | -------------------------------------------------------------------------------- /examples/edit_video.py: -------------------------------------------------------------------------------- 1 | from ytstudio import Studio 2 | import asyncio 3 | import json 4 | import os 5 | 6 | if os.path.exists("./login.json"): 7 | LOGIN_FILE = json.loads(open("./login.json", "r")) 8 | else: 9 | exit("can't run example without login json") 10 | yt = Studio(LOGIN_FILE) 11 | 12 | 13 | async def edit_video(): 14 | await yt.login() 15 | sonuc = await yt.editVideo( 16 | video_id="aaaaaaaa", 17 | title="test", # new title 18 | description="test", # new description 19 | privacy="PUBLIC", # new privacy status (PUBLIC, PRIVATE, UNLISTER) 20 | tags=["test", "test2"], # new tags 21 | category=22, # new category 22 | thumb="./test.png", # new thumbnail (png, jpg, jpeg, <2MB) 23 | playlist=["aaaaa", "bbbbbb"], # new playlist 24 | monetization=True, # new monetization status (True, False) 25 | ) 26 | print(f"successfully edited! videoId: {sonuc['videoId']}") 27 | 28 | 29 | async def delete_video(): 30 | await yt.login() 31 | sonuc = await yt.deleteVideo( 32 | video_id="aaaaaaaa", 33 | ) 34 | print(f"successfully deleted! videoId: {sonuc['videoId']}") 35 | 36 | loop = asyncio.get_event_loop() 37 | loop.run_until_complete(edit_video()) 38 | loop.run_until_complete(delete_video()) 39 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Youtube Studio 2 | 3 | Unofficial Async YouTube Studio API. Set of features limited or not provided by official YouTube API! 4 | 5 | > This is the Python version of [this project](https://github.com/adasq/youtube-studio). All thanks going to [@adasq](https://github.com/adasq) :) 6 | 7 | ## Installation 8 | 9 | You can install with [PIP](https://pypi.org/project/ytstudio/). 10 | 11 | `pip install ytstudio` 12 | 13 | ## Features 14 | 15 | Look at the documentation: [Click here](https://yusufusta.github.io/ytstudio/) 16 | 17 | - Fully Async 18 | - [Uploading Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.uploadVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/upload_video.py) (**NOT LIMITED** - official API's videos.insert charges you 1600 quota units) 19 | - [Deleting Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.deleteVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/edit_video.py#L29) 20 | - [Edit Video](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.editVideo) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/edit_video.py#L13) 21 | - [Get Video(s)](https://yusufusta.github.io/ytstudio/#ytstudio.Studio.listVideos) - [Example](https://github.com/yusufusta/ytstudio/blob/master/examples/get_videos.py#L7) 22 | 23 | ## Login 24 | 25 | You need cookies for login. Use an cookie manager([EditThisCookie](https://chrome.google.com/webstore/detail/editthiscookie/fngmhnnpilhplaeedifhccceomclgfbg?hl=tr)) for [needed cookies.](https://github.com/yusufusta/ytstudio/blob/master/examples/login.json) 26 | 27 | Also you need SESSION_TOKEN for (upload/edit/delete) video. [How to get Session Token?](https://github.com/adasq/youtube-studio#preparing-authentication) 28 | 29 | ## TO-DO 30 | 31 | - [ ] Better Documentation 32 | - [ ] Better Tests 33 | - [ ] More Functions 34 | 35 | ## Author 36 | 37 | Yusuf Usta, me@yusufusta.dev 38 | 39 | ## Note 40 | 41 | This library is in no way affiliated with YouTube or Google. Use at your own discretion. Do not spam with this. 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 98 | __pypackages__/ 99 | 100 | # Celery stuff 101 | celerybeat-schedule 102 | celerybeat.pid 103 | 104 | # SageMath parsed files 105 | *.sage.py 106 | 107 | # Environments 108 | .env 109 | .venv 110 | env/ 111 | venv/ 112 | ENV/ 113 | env.bak/ 114 | venv.bak/ 115 | 116 | # Spyder project settings 117 | .spyderproject 118 | .spyproject 119 | 120 | # Rope project settings 121 | .ropeproject 122 | 123 | # mkdocs documentation 124 | /site 125 | 126 | # mypy 127 | .mypy_cache/ 128 | .dmypy.json 129 | dmypy.json 130 | 131 | # Pyre type checker 132 | .pyre/ 133 | 134 | # pytype static type analyzer 135 | .pytype/ 136 | 137 | # Cython debug symbols 138 | cython_debug/ 139 | .DS_store 140 | dist/ 141 | -------------------------------------------------------------------------------- /ytstudio/__init__.py: -------------------------------------------------------------------------------- 1 | from hashlib import sha1 2 | import time 3 | import aiohttp 4 | import asyncio 5 | import aiofiles 6 | from pyquery import PyQuery as pq 7 | import js2py 8 | import js2py.pyjs 9 | import random 10 | import os 11 | import json 12 | from .templates import Templates 13 | import typing 14 | import pathlib 15 | import base64 16 | import datetime 17 | 18 | 19 | class Studio: 20 | YT_STUDIO_URL = "https://studio.youtube.com" 21 | USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36" 22 | TRANSFERRED_BYTES = 0 23 | CHUNK_SIZE = 64*1024 24 | 25 | def __init__(self, cookies: dict = {'SESSION_TOKEN': '', 'VISITOR_INFO1_LIVE': '', 'PREF': '', 'LOGIN_INFO': '', 'SID': '', '__Secure-3PSID': '.', 'HSID': '', 26 | 'SSID': '', 'APISID': '', 'SAPISID': '', '__Secure-3PAPISID': '', 'YSC': '', 'SIDCC': ''}): 27 | self.SAPISIDHASH = self.generateSAPISIDHASH(cookies['SAPISID']) 28 | self.cookies = cookies 29 | self.Cookie = " ".join( 30 | [f"{c}={cookies[c]};" if not c in ["SESSION_TOKEN", "BOTGUARD_RESPONSE"] else "" for c in cookies.keys()]) 31 | self.HEADERS = { 32 | 'Authorization': f'SAPISIDHASH {self.SAPISIDHASH}', 33 | 'Content-Type': 'application/json', 34 | 'Cookie': self.Cookie, 35 | 'X-Origin': self.YT_STUDIO_URL, 36 | 'User-Agent': self.USER_AGENT 37 | } 38 | self.session = aiohttp.ClientSession(headers=self.HEADERS) 39 | self.loop = asyncio.get_event_loop() 40 | self.config = {} 41 | self.js = js2py.EvalJs() 42 | self.js.execute("var window = {ytcfg: {}};") 43 | 44 | def __del__(self): 45 | asyncio.run(self.session.close()) 46 | 47 | def generateSAPISIDHASH(self, SAPISID) -> str: 48 | hash = f"{round(time.time())} {SAPISID} {self.YT_STUDIO_URL}" 49 | sifrelenmis = sha1(hash.encode('utf-8')).hexdigest() 50 | return f"{round(time.time())}_{sifrelenmis}" 51 | 52 | async def getMainPage(self) -> str: 53 | page = await self.session.get(self.YT_STUDIO_URL) 54 | return await page.text("utf-8") 55 | 56 | async def login(self) -> bool: 57 | """ 58 | Login to your youtube account 59 | """ 60 | page = await self.getMainPage() 61 | _ = pq(page) 62 | script = _("script") 63 | if len(script) < 1: 64 | raise Exception("Didn't find script. Can you check your cookies?") 65 | script = script[0].text 66 | self.js.execute( 67 | f"{script} window.ytcfg = ytcfg;") 68 | 69 | INNERTUBE_API_KEY = self.js.window.ytcfg.data_.INNERTUBE_API_KEY 70 | CHANNEL_ID = self.js.window.ytcfg.data_.CHANNEL_ID 71 | DELEGATED_SESSION_ID = self.js.window.ytcfg.data_.DELEGATED_SESSION_ID 72 | 73 | if INNERTUBE_API_KEY == None or CHANNEL_ID == None: 74 | raise Exception( 75 | "Didn't find INNERTUBE_API_KEY or CHANNEL_ID. Can you check your cookies?") 76 | self.config = {'INNERTUBE_API_KEY': INNERTUBE_API_KEY, 77 | 'CHANNEL_ID': CHANNEL_ID, 'data_': self.js.window.ytcfg.data_} 78 | self.templates = Templates({ 79 | 'channelId': CHANNEL_ID, 80 | 'sessionToken': self.cookies['SESSION_TOKEN'], 81 | 'botguardResponse': self.cookies['BOTGUARD_RESPONSE'] if 'BOTGUARD_RESPONSE' in self.cookies else '', 82 | 'delegatedSessionId': DELEGATED_SESSION_ID 83 | }) 84 | 85 | return True 86 | 87 | def generateHash(self) -> str: 88 | harfler = list( 89 | '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') 90 | keys = ['' for i in range(0, 36)] 91 | b = 0 92 | c = "" 93 | e = 0 94 | 95 | while e < 36: 96 | if 8 == e or 13 == e or 18 == e or 23 == e: 97 | keys[e] = "-" 98 | else: 99 | if 14 == e: 100 | keys[e] = "4" 101 | elif 2 >= b: 102 | b = round(33554432 + 16777216 * random.uniform(0, 0.9)) 103 | c = b & 15 104 | b = b >> 4 105 | keys[e] = harfler[c & 3 | 8 if 19 == e else c] 106 | e += 1 107 | 108 | return "".join(keys) 109 | 110 | async def fileSender(self, file_name): 111 | async with aiofiles.open(file_name, 'rb') as f: 112 | chunk = await f.read(self.CHUNK_SIZE) 113 | while chunk: 114 | if self.progress != None: 115 | self.TRANSFERRED_BYTES += len(chunk) 116 | self.progress(self.TRANSFERRED_BYTES, 117 | os.path.getsize(file_name)) 118 | 119 | self.TRANSFERRED_BYTES += len(chunk) 120 | yield chunk 121 | chunk = await f.read(self.CHUNK_SIZE) 122 | if not chunk: 123 | break 124 | 125 | async def uploadFileToYoutube(self, upload_url, file_path): 126 | self.TRANSFERRED_BYTES = 0 127 | 128 | uploaded = await self.session.post(upload_url, headers={ 129 | "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'", 130 | "x-goog-upload-command": "upload, finalize", 131 | "x-goog-upload-file-name": f"file-{round(time.time())}", 132 | "x-goog-upload-offset": "0", 133 | "Referer": self.YT_STUDIO_URL, 134 | }, data=self.fileSender(file_path), timeout=None) 135 | _ = await uploaded.text("utf-8") 136 | _ = json.loads(_) 137 | return _['scottyResourceId'] 138 | 139 | async def uploadVideo(self, file_name, title=f"New Video {round(time.time())}", description='This video uploaded by github.com/yusufusta/ytstudio', privacy='PRIVATE', draft=False, progress=None, extra_fields={}): 140 | """ 141 | Uploads a video to youtube. 142 | """ 143 | self.progress = progress 144 | frontEndUID = f"innertube_studio:{self.generateHash()}:0" 145 | 146 | uploadRequest = await self.session.post("https://upload.youtube.com/upload/studio", 147 | headers={ 148 | "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'", 149 | "x-goog-upload-command": "start", 150 | "x-goog-upload-file-name": f"file-{round(time.time())}", 151 | "x-goog-upload-protocol": "resumable", 152 | "Referer": self.YT_STUDIO_URL, 153 | }, 154 | json={'frontendUploadId': frontEndUID}) 155 | 156 | uploadUrl = uploadRequest.headers.get("x-goog-upload-url") 157 | scottyResourceId = await self.uploadFileToYoutube(uploadUrl, file_name) 158 | _data = self.templates.UPLOAD_VIDEO 159 | _data["resourceId"]["scottyResourceId"]["id"] = scottyResourceId 160 | _data["frontendUploadId"] = frontEndUID 161 | _data["initialMetadata"] = { 162 | "title": { 163 | "newTitle": title 164 | }, 165 | "description": { 166 | "newDescription": description, 167 | "shouldSegment": True 168 | }, 169 | "privacy": { 170 | "newPrivacy": privacy 171 | }, 172 | "draftState": { 173 | "isDraft": draft 174 | }, 175 | } 176 | _data["initialMetadata"].update(extra_fields) 177 | 178 | upload = await self.session.post( 179 | f"https://studio.youtube.com/youtubei/v1/upload/createvideo?alt=json&key={self.config['INNERTUBE_API_KEY']}", 180 | json=_data 181 | ) 182 | 183 | return await upload.json() 184 | 185 | async def deleteVideo(self, video_id): 186 | """ 187 | Delete video from your channel 188 | """ 189 | self.templates.setVideoId(video_id) 190 | delete = await self.session.post( 191 | f"https://studio.youtube.com/youtubei/v1/video/delete?alt=json&key={self.config['INNERTUBE_API_KEY']}", 192 | json=self.templates.DELETE_VIDEO 193 | ) 194 | return await delete.json() 195 | 196 | async def listVideos(self): 197 | """ 198 | Returns a list of videos in your channel 199 | """ 200 | list = await self.session.post( 201 | f"https://studio.youtube.com/youtubei/v1/creator/list_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}", 202 | json=self.templates.LIST_VIDEOS 203 | ) 204 | return await list.json() 205 | 206 | async def getVideo(self, video_id): 207 | """ 208 | Get video data. 209 | """ 210 | self.templates.setVideoId(video_id) 211 | video = await self.session.post( 212 | f"https://studio.youtube.com/youtubei/v1/creator/get_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}", 213 | json=self.templates.GET_VIDEO 214 | ) 215 | return await video.json() 216 | 217 | async def createPlaylist(self, title, privacy="PUBLIC") -> dict: 218 | """ 219 | Create a new playlist. 220 | """ 221 | _data = self.templates.CREATE_PLAYLIST 222 | _data["title"] = title 223 | _data["privacyStatus"] = privacy 224 | 225 | create = await self.session.post( 226 | f"https://studio.youtube.com/youtubei/v1/playlist/create?alt=json&key={self.config['INNERTUBE_API_KEY']}", 227 | json=_data 228 | ) 229 | return await create.json() 230 | 231 | async def editVideo(self, video_id, title: str = "", description: str = "", privacy: str = "", thumb: typing.Union[str, pathlib.Path, os.PathLike] = "", tags: typing.List[str] = [], category: int = -1, monetization: bool = True, playlist: typing.List[str] = [], removeFromPlaylist: typing.List[str] = []): 232 | """ 233 | Edit video metadata. 234 | """ 235 | self.templates.setVideoId(video_id) 236 | _data = self.templates.METADATA_UPDATE 237 | if title != "": 238 | _title = self.templates.METADATA_UPDATE_TITLE 239 | _title["title"]["newTitle"] = title 240 | _data.update(_title) 241 | 242 | if description != "": 243 | _description = self.templates.METADATA_UPDATE_DESCRIPTION 244 | _description["description"]["newDescription"] = description 245 | _data.update(_description) 246 | 247 | if privacy != "": 248 | _privacy = self.templates.METADATA_UPDATE_PRIVACY 249 | _privacy["privacy"]["newPrivacy"] = privacy 250 | _data.update(_privacy) 251 | 252 | if thumb != "": 253 | _thumb = self.templates.METADATA_UPDATE_THUMB 254 | image = open(thumb, 'rb') 255 | image_64_encode = base64.b64encode(image.read()).decode('utf-8') 256 | 257 | _thumb["videoStill"]["image"][ 258 | "dataUri"] = f"data:image/png;base64,{image_64_encode}" 259 | _data.update(_thumb) 260 | 261 | if len(tags) > 0: 262 | _tags = self.templates.METADATA_UPDATE_TAGS 263 | _tags["tags"]["newTags"] = tags 264 | _data.update(_tags) 265 | 266 | if category != -1: 267 | _category = self.templates.METADATA_UPDATE_CATEGORY 268 | _category["category"]["newCategoryId"] = category 269 | _data.update(_category) 270 | 271 | if len(playlist) > 0: 272 | _playlist = self.templates.METADATA_UPDATE_PLAYLIST 273 | _playlist["addToPlaylist"]["addToPlaylistIds"] = playlist 274 | if len(removeFromPlaylist) > 0: 275 | _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist 276 | _data.update(_playlist) 277 | 278 | if len(removeFromPlaylist) > 0: 279 | _playlist = self.templates.METADATA_UPDATE_PLAYLIST 280 | _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist 281 | _data.update(_playlist) 282 | 283 | _monetization = self.templates.METADATA_UPDATE_MONETIZATION 284 | _monetization["monetizationSettings"]["newMonetization"] = monetization 285 | _data.update(_monetization) 286 | 287 | update = await self.session.post( 288 | f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}", 289 | json=_data 290 | ) 291 | return await update.json() 292 | 293 | async def scheduledUploadVideo(self, file_name, title="New Video", description='This video uploaded by github.com/yusufusta/ytstudio', now_privacy='PRIVATE', schedule_time: datetime.datetime | int = 0, scheduled_privacy="PUBLIC", progress=None, extra_fields={}): 294 | """ 295 | Scheduled uploads a video to youtube. 296 | """ 297 | upload = await self.uploadVideo(file_name, title, description, now_privacy, draft=True, progress=progress, extra_fields=extra_fields) 298 | if not "videoId" in upload: 299 | raise Exception( 300 | "Video upload failed. Please check your cookies (specially SESSION_TOKEN)", upload) 301 | 302 | self.templates.setVideoId(upload["videoId"]) 303 | 304 | _data = self.templates.METADATA_UPDATE 305 | _schedule = self.templates.METADATA_UPDATE_SCHEDULE 306 | 307 | if isinstance(schedule_time, datetime.datetime): 308 | schedule_time = int(schedule_time.timestamp()) 309 | elif schedule_time == 0: 310 | schedule_time = int(datetime.datetime.now().timestamp()) + 60 311 | 312 | _schedule["scheduledPublishing"]["set"]["timeSec"] = schedule_time 313 | _schedule["scheduledPublishing"]["set"]["privacy"] = scheduled_privacy 314 | _schedule["privacyState"]["newPrivacy"] = now_privacy 315 | _data.update(_schedule) 316 | 317 | update = await self.session.post( 318 | f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}", 319 | json=_data 320 | ) 321 | up = await update.json() 322 | return upload, up 323 | -------------------------------------------------------------------------------- /ytstudio/templates.py: -------------------------------------------------------------------------------- 1 | class Templates: 2 | channelId = "" 3 | videoId = "" 4 | sessionToken = "" 5 | botguardResponse = "" 6 | delegatedSessionId = "" 7 | 8 | CLIENT = { 9 | "clientName": 62, 10 | "clientVersion": "1.20201130.03.00", 11 | "hl": "en-GB", 12 | "gl": "PL", 13 | "experimentsToken": "", 14 | "utcOffsetMinutes": 60 15 | } 16 | 17 | def __init__(self, config) -> None: 18 | self.config = config 19 | self.channelId = self.config["channelId"] 20 | self.sessionToken = self.config["sessionToken"] 21 | self.botguardResponse = self.config["botguardResponse"] if "botguardResponse" in self.config else "" 22 | self.delegatedSessionId = self.config["delegatedSessionId"] if "delegatedSessionId" in self.config else "" 23 | self._() 24 | 25 | def setVideoId(self, videoId): 26 | self.videoId = videoId 27 | self._() 28 | 29 | def _(self): 30 | self.DELETE_VIDEO = { 31 | "videoId": self.videoId, 32 | "context": { 33 | "client": self.CLIENT, 34 | "request": { 35 | "returnLogEntry": True, 36 | "internalExperimentFlags": [], 37 | "sessionInfo": { 38 | "token": self.sessionToken 39 | } 40 | }, 41 | "user": { 42 | "delegationContext": { 43 | "roleType": { 44 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 45 | }, 46 | "externalChannelId": self.channelId 47 | }, 48 | "serializedDelegationContext": "" 49 | }, 50 | "clientScreenNonce": "" 51 | }, 52 | "delegationContext": { 53 | "roleType": { 54 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 55 | }, 56 | "externalChannelId": self.channelId 57 | } 58 | } 59 | 60 | self.UPLOAD_VIDEO = { 61 | "channelId": self.channelId, 62 | "resourceId": { 63 | "scottyResourceId": { 64 | "id": "" 65 | } 66 | }, 67 | "frontendUploadId": "", 68 | "initialMetadata": { 69 | "title": { 70 | "newTitle": "" 71 | }, 72 | "description": { 73 | "newDescription": "", 74 | "shouldSegment": True 75 | }, 76 | "privacy": { 77 | "newPrivacy": "" 78 | }, 79 | "draftState": { 80 | "isDraft": "" 81 | } 82 | }, 83 | "context": { 84 | "client": self.CLIENT, 85 | "request": { 86 | "returnLogEntry": True, 87 | "internalExperimentFlags": [], 88 | "sessionInfo": { 89 | "token": self.sessionToken 90 | } 91 | }, 92 | "user": { 93 | "onBehalfOfUser": self.delegatedSessionId, 94 | "delegationContext": { 95 | "externalChannelId": self.channelId, 96 | "roleType": { 97 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 98 | } 99 | }, 100 | "serializedDelegationContext": "" 101 | }, 102 | "clientScreenNonce": "" 103 | }, 104 | "delegationContext": { 105 | "roleType": { 106 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 107 | }, 108 | "externalChannelId": self.channelId 109 | } 110 | } 111 | 112 | if self.botguardResponse and self.botguardResponse != "": 113 | self.UPLOAD_VIDEO["botguardClientResponse"] = self.botguardResponse 114 | 115 | self.METADATA_UPDATE = { 116 | "encryptedVideoId": self.videoId, 117 | "videoReadMask": { 118 | "channelId": True, 119 | "videoId": True, 120 | "lengthSeconds": True, 121 | "premiere": { 122 | "all": True 123 | }, 124 | "status": True, 125 | "thumbnailDetails": { 126 | "all": True 127 | }, 128 | "title": True, 129 | "draftStatus": True, 130 | "downloadUrl": True, 131 | "watchUrl": True, 132 | "permissions": { 133 | "all": True 134 | }, 135 | "timeCreatedSeconds": True, 136 | "timePublishedSeconds": True, 137 | "origin": True, 138 | "livestream": { 139 | "all": True 140 | }, 141 | "privacy": True, 142 | "contentOwnershipModelSettings": { 143 | "all": True 144 | }, 145 | "features": { 146 | "all": True 147 | }, 148 | "responseStatus": { 149 | "all": True 150 | }, 151 | "statusDetails": { 152 | "all": True 153 | }, 154 | "description": True, 155 | "metrics": { 156 | "all": True 157 | }, 158 | "publicLivestream": { 159 | "all": True 160 | }, 161 | "publicPremiere": { 162 | "all": True 163 | }, 164 | "titleFormattedString": { 165 | "all": True 166 | }, 167 | "descriptionFormattedString": { 168 | "all": True 169 | }, 170 | "audienceRestriction": { 171 | "all": True 172 | }, 173 | "monetization": { 174 | "all": True 175 | }, 176 | "selfCertification": { 177 | "all": True 178 | }, 179 | "allRestrictions": { 180 | "all": True 181 | }, 182 | "inlineEditProcessingStatus": True, 183 | "videoPrechecks": { 184 | "all": True 185 | }, 186 | "videoResolutions": { 187 | "all": True 188 | }, 189 | "scheduledPublishingDetails": { 190 | "all": True 191 | }, 192 | "visibility": { 193 | "all": True 194 | }, 195 | "privateShare": { 196 | "all": True 197 | }, 198 | "sponsorsOnly": { 199 | "all": True 200 | }, 201 | "unlistedExpired": True, 202 | "videoTrailers": { 203 | "all": True 204 | } 205 | }, 206 | "context": { 207 | "client": self.CLIENT, 208 | "request": { 209 | "returnLogEntry": True, 210 | "internalExperimentFlags": [], 211 | "sessionInfo": { 212 | "token": self.sessionToken 213 | } 214 | }, 215 | "user": { 216 | "delegationContext": { 217 | "externalChannelId": self.channelId, 218 | "roleType": { 219 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 220 | } 221 | }, 222 | "serializedDelegationContext": "" 223 | }, 224 | "clientScreenNonce": "" 225 | }, 226 | "delegationContext": { 227 | "externalChannelId": self.channelId, 228 | "roleType": { 229 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 230 | } 231 | } 232 | } 233 | 234 | self.METADATA_UPDATE_MONETIZATION = { 235 | "monetizationSettings": { 236 | "newMonetizeWithAds": True 237 | } 238 | } 239 | 240 | self.METADATA_UPDATE_SCHEDULE = { 241 | "flowType": "MDE_FLOW_TYPE_UPLOAD", 242 | "privacyState": { 243 | "newPrivacy": "PRIVATE" 244 | }, 245 | "scheduledPublishing": { 246 | "set": { 247 | "timeSec": 0, 248 | "privacy": "PUBLIC" 249 | } 250 | }, 251 | "draftState": { 252 | "operation": "MDE_DRAFT_STATE_UPDATE_OPERATION_REMOVE_DRAFT_STATE" 253 | } 254 | } 255 | 256 | self.LIST_VIDEOS = { 257 | "filter": { 258 | "and": { 259 | "operands": [ 260 | { 261 | "channelIdIs": { 262 | "value": self.channelId 263 | } 264 | }, { 265 | "videoOriginIs": { 266 | "value": "VIDEO_ORIGIN_UPLOAD" 267 | } 268 | } 269 | ] 270 | } 271 | }, 272 | "order": "VIDEO_ORDER_DISPLAY_TIME_DESC", 273 | "pageSize": 30, 274 | "mask": { 275 | "channelId": True, 276 | "videoId": True, 277 | "lengthSeconds": True, 278 | "premiere": { 279 | "all": True 280 | }, 281 | "status": True, 282 | "thumbnailDetails": { 283 | "all": True 284 | }, 285 | "title": True, 286 | "draftStatus": True, 287 | "downloadUrl": True, 288 | "watchUrl": True, 289 | "permissions": { 290 | "all": True 291 | }, 292 | "timeCreatedSeconds": True, 293 | "timePublishedSeconds": True, 294 | "origin": True, 295 | "livestream": { 296 | "all": True 297 | }, 298 | "privacy": True, 299 | "contentOwnershipModelSettings": { 300 | "all": True 301 | }, 302 | "features": { 303 | "all": True 304 | }, 305 | "responseStatus": { 306 | "all": True 307 | }, 308 | "statusDetails": { 309 | "all": True 310 | }, 311 | "description": True, 312 | "metrics": { 313 | "all": True 314 | }, 315 | "publicLivestream": { 316 | "all": True 317 | }, 318 | "publicPremiere": { 319 | "all": True 320 | }, 321 | "titleFormattedString": { 322 | "all": True 323 | }, 324 | "descriptionFormattedString": { 325 | "all": True 326 | }, 327 | "audienceRestriction": { 328 | "all": True 329 | }, 330 | "monetization": { 331 | "all": True 332 | }, 333 | "selfCertification": { 334 | "all": True 335 | }, 336 | "allRestrictions": { 337 | "all": True 338 | }, 339 | "inlineEditProcessingStatus": True, 340 | "videoPrechecks": { 341 | "all": True 342 | }, 343 | "videoResolutions": { 344 | "all": True 345 | }, 346 | "scheduledPublishingDetails": { 347 | "all": True 348 | }, 349 | "visibility": { 350 | "all": True 351 | }, 352 | "privateShare": { 353 | "all": True 354 | }, 355 | "sponsorsOnly": { 356 | "all": True 357 | }, 358 | "unlistedExpired": True, 359 | "videoTrailers": { 360 | "all": True 361 | } 362 | }, 363 | "context": { 364 | "client": self.CLIENT, 365 | "request": { 366 | "returnLogEntry": True, 367 | "internalExperimentFlags": [] 368 | }, 369 | "user": { 370 | "delegationContext": { 371 | "externalChannelId": self.channelId, 372 | "roleType": { 373 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 374 | } 375 | }, 376 | "serializedDelegationContext": "" 377 | }, 378 | "clientScreenNonce": "" 379 | } 380 | } 381 | 382 | self.GET_VIDEO = { 383 | "context": { 384 | "client": self.CLIENT, 385 | "request": { 386 | "returnLogEntry": True, 387 | "internalExperimentFlags": [] 388 | }, 389 | "user": { 390 | "delegationContext": { 391 | "externalChannelId": self.channelId, 392 | "roleType": { 393 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 394 | } 395 | }, 396 | "serializedDelegationContext": "" 397 | }, 398 | "clientScreenNonce": "" 399 | }, 400 | "failOnError": True, 401 | "videoIds": [self.videoId], 402 | "mask": { 403 | "downloadUrl": True, 404 | "origin": True, 405 | "premiere": { 406 | "all": True 407 | }, 408 | "privacy": True, 409 | "videoId": True, 410 | "status": True, 411 | "permissions": { 412 | "all": True 413 | }, 414 | "draftStatus": True, 415 | "statusDetails": { 416 | "all": True 417 | }, 418 | "inlineEditProcessingStatus": True, 419 | "selfCertification": { 420 | "all": True 421 | }, 422 | "monetization": { 423 | "all": True 424 | }, 425 | "allRestrictions": { 426 | "all": True 427 | }, 428 | "videoPrechecks": { 429 | "all": True 430 | }, 431 | "audienceRestriction": { 432 | "all": True 433 | }, 434 | "responseStatus": { 435 | "all": True 436 | }, 437 | "features": { 438 | "all": True 439 | }, 440 | "videoAdvertiserSpecificAgeGates": { 441 | "all": True 442 | }, 443 | "claimDetails": { 444 | "all": True 445 | }, 446 | "commentsDisabledInternally": True, 447 | "livestream": { 448 | "all": True 449 | }, 450 | "music": { 451 | "all": True 452 | }, 453 | "ownedClaimDetails": { 454 | "all": True 455 | }, 456 | "timePublishedSeconds": True, 457 | "uncaptionedReason": True, 458 | "remix": { 459 | "all": True 460 | }, 461 | "contentOwnershipModelSettings": { 462 | "all": True 463 | }, 464 | "channelId": True, 465 | "mfkSettings": { 466 | "all": True 467 | }, 468 | "thumbnailEditorState": { 469 | "all": True 470 | }, 471 | "thumbnailDetails": { 472 | "all": True 473 | }, 474 | "scheduledPublishingDetails": { 475 | "all": True 476 | }, 477 | "visibility": { 478 | "all": True 479 | }, 480 | "privateShare": { 481 | "all": True 482 | }, 483 | "sponsorsOnly": { 484 | "all": True 485 | }, 486 | "unlistedExpired": True, 487 | "videoTrailers": { 488 | "all": True 489 | }, 490 | "allowComments": True, 491 | "allowEmbed": True, 492 | "allowRatings": True, 493 | "ageRestriction": True, 494 | "audioLanguage": { 495 | "all": True 496 | }, 497 | "category": True, 498 | "commentFilter": True, 499 | "crowdsourcingEnabled": True, 500 | "dateRecorded": { 501 | "all": True 502 | }, 503 | "defaultCommentSortOrder": True, 504 | "description": True, 505 | "descriptionFormattedString": { 506 | "all": True 507 | }, 508 | "gameTitle": { 509 | "all": True 510 | }, 511 | "license": True, 512 | "liveChat": { 513 | "all": True 514 | }, 515 | "location": { 516 | "all": True 517 | }, 518 | "metadataLanguage": { 519 | "all": True 520 | }, 521 | "paidProductPlacement": True, 522 | "publishing": { 523 | "all": True 524 | }, 525 | "tags": { 526 | "all": True 527 | }, 528 | "title": True, 529 | "titleFormattedString": { 530 | "all": True 531 | }, 532 | "viewCountIsHidden": True, 533 | "autoChapterSettings": { 534 | "all": True 535 | }, 536 | "videoStreamUrl": True, 537 | "videoDurationMs": True, 538 | "videoEditorProject": { 539 | "videoDimensions": { 540 | "all": True 541 | } 542 | }, 543 | "originalFilename": True, 544 | "videoResolutions": { 545 | "all": True 546 | } 547 | }, 548 | "criticalRead": False 549 | } 550 | 551 | self.CREATE_PLAYLIST = { 552 | "title": "", 553 | "privacyStatus": "", 554 | "context": { 555 | "client": self.CLIENT, 556 | "request": { 557 | "returnLogEntry": True, 558 | "internalExperimentFlags": [], 559 | "sessionInfo": { 560 | "token": self.sessionToken 561 | } 562 | }, 563 | "user": { 564 | "delegationContext": { 565 | "externalChannelId": self.channelId, 566 | "roleType": { 567 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 568 | } 569 | }, 570 | "serializedDelegationContext": "" 571 | }, 572 | "clientScreenNonce": "" 573 | }, 574 | "delegationContext": { 575 | "externalChannelId": self.channelId, 576 | "roleType": { 577 | "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER" 578 | } 579 | } 580 | } 581 | 582 | self.METADATA_UPDATE_PLAYLIST = { 583 | "addToPlaylist": { 584 | "addToPlaylistIds": [], 585 | "deleteFromPlaylistIds": [] 586 | } 587 | } 588 | 589 | self.METADATA_UPDATE_TITLE = { 590 | "title": { 591 | "newTitle": "", 592 | "shouldSegment": True 593 | } 594 | } 595 | 596 | self.METADATA_UPDATE_DESCRIPTION = { 597 | "description": { 598 | "newDescription": "", 599 | "shouldSegment": True 600 | } 601 | } 602 | 603 | self.METADATA_UPDATE_TAGS = { 604 | "tags": { 605 | "newTags": [], 606 | "shouldSegment": True 607 | } 608 | } 609 | 610 | self.METADATA_UPDATE_CATEGORY = { 611 | "category": { 612 | "newCategoryId": 0 613 | } 614 | } 615 | 616 | self.METADATA_UPDATE_COMMENTS = { 617 | "commentOptions": { 618 | "newAllowComments": True, 619 | "newAllowCommentsMode": "ALL_COMMENTS", 620 | "newCanViewRatings": True, 621 | "newDefaultSortOrder": "MDE_COMMENT_SORT_ORDER_TOP" 622 | } 623 | } 624 | 625 | self.METADATA_UPDATE_PRIVACY = { 626 | "privacyState": {"newPrivacy": "PUBLIC"} 627 | } 628 | 629 | self.METADATA_UPDATE_THUMB = { 630 | "videoStill": {"operation": "UPLOAD_CUSTOM_THUMBNAIL", "image": { 631 | "dataUri": "" 632 | }} 633 | } 634 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ytstudio API documentation 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 |
21 |
22 |

Package ytstudio

23 |
24 |
25 |
26 | 27 | Expand source code 28 | 29 |
from hashlib import sha1
  30 | import time
  31 | import aiohttp
  32 | import asyncio
  33 | import aiofiles
  34 | from pyquery import PyQuery as pq
  35 | import js2py
  36 | import js2py.pyjs
  37 | import random
  38 | import os
  39 | import json
  40 | from .templates import Templates
  41 | import typing
  42 | import pathlib
  43 | import base64
  44 | import datetime
  45 | 
  46 | 
  47 | class Studio:
  48 |     YT_STUDIO_URL = "https://studio.youtube.com"
  49 |     USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
  50 |     TRANSFERRED_BYTES = 0
  51 |     CHUNK_SIZE = 64*1024
  52 | 
  53 |     def __init__(self, cookies: dict = {'SESSION_TOKEN': '', 'VISITOR_INFO1_LIVE': '', 'PREF': '', 'LOGIN_INFO': '', 'SID': '', '__Secure-3PSID': '.', 'HSID': '',
  54 |                  'SSID': '', 'APISID': '', 'SAPISID': '', '__Secure-3PAPISID': '', 'YSC': '', 'SIDCC': ''}):
  55 |         self.SAPISIDHASH = self.generateSAPISIDHASH(cookies['SAPISID'])
  56 |         self.cookies = cookies
  57 |         self.Cookie = " ".join(
  58 |             [f"{c}={cookies[c]};" if not c in ["SESSION_TOKEN", "BOTGUARD_RESPONSE"] else "" for c in cookies.keys()])
  59 |         self.HEADERS = {
  60 |             'Authorization': f'SAPISIDHASH {self.SAPISIDHASH}',
  61 |             'Content-Type': 'application/json',
  62 |             'Cookie': self.Cookie,
  63 |             'X-Origin': self.YT_STUDIO_URL,
  64 |             'User-Agent': self.USER_AGENT
  65 |         }
  66 |         self.session = aiohttp.ClientSession(headers=self.HEADERS)
  67 |         self.loop = asyncio.get_event_loop()
  68 |         self.config = {}
  69 |         self.js = js2py.EvalJs()
  70 |         self.js.execute("var window = {ytcfg: {}};")
  71 | 
  72 |     def __del__(self):
  73 |         asyncio.run(self.session.close())
  74 | 
  75 |     def generateSAPISIDHASH(self, SAPISID) -> str:
  76 |         hash = f"{round(time.time())} {SAPISID} {self.YT_STUDIO_URL}"
  77 |         sifrelenmis = sha1(hash.encode('utf-8')).hexdigest()
  78 |         return f"{round(time.time())}_{sifrelenmis}"
  79 | 
  80 |     async def getMainPage(self) -> str:
  81 |         page = await self.session.get(self.YT_STUDIO_URL)
  82 |         return await page.text("utf-8")
  83 | 
  84 |     async def login(self) -> bool:
  85 |         """
  86 |         Login to your youtube account
  87 |         """
  88 |         page = await self.getMainPage()
  89 |         _ = pq(page)
  90 |         script = _("script")
  91 |         if len(script) < 1:
  92 |             raise Exception("Didn't find script. Can you check your cookies?")
  93 |         script = script[0].text
  94 |         self.js.execute(
  95 |             f"{script} window.ytcfg = ytcfg;")
  96 | 
  97 |         INNERTUBE_API_KEY = self.js.window.ytcfg.data_.INNERTUBE_API_KEY
  98 |         CHANNEL_ID = self.js.window.ytcfg.data_.CHANNEL_ID
  99 |         DELEGATED_SESSION_ID = self.js.window.ytcfg.data_.DELEGATED_SESSION_ID
 100 | 
 101 |         if INNERTUBE_API_KEY == None or CHANNEL_ID == None:
 102 |             raise Exception(
 103 |                 "Didn't find INNERTUBE_API_KEY or CHANNEL_ID. Can you check your cookies?")
 104 |         self.config = {'INNERTUBE_API_KEY': INNERTUBE_API_KEY,
 105 |                        'CHANNEL_ID': CHANNEL_ID, 'data_': self.js.window.ytcfg.data_}
 106 |         self.templates = Templates({
 107 |             'channelId': CHANNEL_ID,
 108 |             'sessionToken': self.cookies['SESSION_TOKEN'],
 109 |             'botguardResponse': self.cookies['BOTGUARD_RESPONSE'] if 'BOTGUARD_RESPONSE' in self.cookies else '',
 110 |             'delegatedSessionId': DELEGATED_SESSION_ID
 111 |         })
 112 | 
 113 |         return True
 114 | 
 115 |     def generateHash(self) -> str:
 116 |         harfler = list(
 117 |             '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
 118 |         keys = ['' for i in range(0, 36)]
 119 |         b = 0
 120 |         c = ""
 121 |         e = 0
 122 | 
 123 |         while e < 36:
 124 |             if 8 == e or 13 == e or 18 == e or 23 == e:
 125 |                 keys[e] = "-"
 126 |             else:
 127 |                 if 14 == e:
 128 |                     keys[e] = "4"
 129 |                 elif 2 >= b:
 130 |                     b = round(33554432 + 16777216 * random.uniform(0, 0.9))
 131 |                 c = b & 15
 132 |                 b = b >> 4
 133 |                 keys[e] = harfler[c & 3 | 8 if 19 == e else c]
 134 |             e += 1
 135 | 
 136 |         return "".join(keys)
 137 | 
 138 |     async def fileSender(self, file_name):
 139 |         async with aiofiles.open(file_name, 'rb') as f:
 140 |             chunk = await f.read(self.CHUNK_SIZE)
 141 |             while chunk:
 142 |                 if self.progress != None:
 143 |                     self.TRANSFERRED_BYTES += len(chunk)
 144 |                     self.progress(self.TRANSFERRED_BYTES,
 145 |                                   os.path.getsize(file_name))
 146 | 
 147 |                 self.TRANSFERRED_BYTES += len(chunk)
 148 |                 yield chunk
 149 |                 chunk = await f.read(self.CHUNK_SIZE)
 150 |                 if not chunk:
 151 |                     break
 152 | 
 153 |     async def uploadFileToYoutube(self, upload_url, file_path):
 154 |         self.TRANSFERRED_BYTES = 0
 155 | 
 156 |         uploaded = await self.session.post(upload_url,  headers={
 157 |             "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
 158 |             "x-goog-upload-command": "upload, finalize",
 159 |             "x-goog-upload-file-name": f"file-{round(time.time())}",
 160 |             "x-goog-upload-offset": "0",
 161 |             "Referer": self.YT_STUDIO_URL,
 162 |         }, data=self.fileSender(file_path), timeout=None)
 163 |         _ = await uploaded.text("utf-8")
 164 |         _ = json.loads(_)
 165 |         return _['scottyResourceId']
 166 | 
 167 |     async def uploadVideo(self, file_name, title=f"New Video {round(time.time())}", description='This video uploaded by github.com/yusufusta/ytstudio', privacy='PRIVATE', draft=False, progress=None, extra_fields={}):
 168 |         """
 169 |         Uploads a video to youtube.
 170 |         """
 171 |         self.progress = progress
 172 |         frontEndUID = f"innertube_studio:{self.generateHash()}:0"
 173 | 
 174 |         uploadRequest = await self.session.post("https://upload.youtube.com/upload/studio",
 175 |                                                 headers={
 176 |                                                     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
 177 |                                                     "x-goog-upload-command": "start",
 178 |                                                     "x-goog-upload-file-name": f"file-{round(time.time())}",
 179 |                                                     "x-goog-upload-protocol": "resumable",
 180 |                                                     "Referer": self.YT_STUDIO_URL,
 181 |                                                 },
 182 |                                                 json={'frontendUploadId': frontEndUID})
 183 | 
 184 |         uploadUrl = uploadRequest.headers.get("x-goog-upload-url")
 185 |         scottyResourceId = await self.uploadFileToYoutube(uploadUrl, file_name)
 186 | 
 187 |         _data = self.templates.UPLOAD_VIDEO
 188 |         _data["resourceId"]["scottyResourceId"]["id"] = scottyResourceId
 189 |         _data["frontendUploadId"] = frontEndUID
 190 |         _data["initialMetadata"] = {
 191 |             "title": {
 192 |                 "newTitle": title
 193 |             },
 194 |             "description": {
 195 |                 "newDescription": description,
 196 |                 "shouldSegment": True
 197 |             },
 198 |             "privacy": {
 199 |                 "newPrivacy": privacy
 200 |             },
 201 |             "draftState": {
 202 |                 "isDraft": draft
 203 |             },
 204 |         }
 205 |         _data["initialMetadata"].update(extra_fields)
 206 | 
 207 |         upload = await self.session.post(
 208 |             f"https://studio.youtube.com/youtubei/v1/upload/createvideo?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 209 |             json=_data
 210 |         )
 211 | 
 212 |         return await upload.json()
 213 | 
 214 |     async def deleteVideo(self, video_id):
 215 |         """
 216 |         Delete video from your channel
 217 |         """
 218 |         self.templates.setVideoId(video_id)
 219 |         delete = await self.session.post(
 220 |             f"https://studio.youtube.com/youtubei/v1/video/delete?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 221 |             json=self.templates.DELETE_VIDEO
 222 |         )
 223 |         return await delete.json()
 224 | 
 225 |     async def listVideos(self):
 226 |         """
 227 |         Returns a list of videos in your channel
 228 |         """
 229 |         list = await self.session.post(
 230 |             f"https://studio.youtube.com/youtubei/v1/creator/list_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 231 |             json=self.templates.LIST_VIDEOS
 232 |         )
 233 |         return await list.json()
 234 | 
 235 |     async def getVideo(self, video_id):
 236 |         """
 237 |         Get video data.
 238 |         """
 239 |         self.templates.setVideoId(video_id)
 240 |         video = await self.session.post(
 241 |             f"https://studio.youtube.com/youtubei/v1/creator/get_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 242 |             json=self.templates.GET_VIDEO
 243 |         )
 244 |         return await video.json()
 245 | 
 246 |     async def createPlaylist(self, title, privacy="PUBLIC") -> dict:
 247 |         """
 248 |         Create a new playlist.
 249 |         """
 250 |         _data = self.templates.CREATE_PLAYLIST
 251 |         _data["title"] = title
 252 |         _data["privacyStatus"] = privacy
 253 | 
 254 |         create = await self.session.post(
 255 |             f"https://studio.youtube.com/youtubei/v1/playlist/create?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 256 |             json=_data
 257 |         )
 258 |         return await create.json()
 259 | 
 260 |     async def editVideo(self, video_id, title: str = "", description: str = "", privacy: str = "", thumb: typing.Union[str, pathlib.Path, os.PathLike] = "", tags: typing.List[str] = [], category: int = -1, monetization: bool = True, playlist: typing.List[str] = [], removeFromPlaylist: typing.List[str] = []):
 261 |         """
 262 |         Edit video metadata.
 263 |         """
 264 |         self.templates.setVideoId(video_id)
 265 |         _data = self.templates.METADATA_UPDATE
 266 |         if title != "":
 267 |             _title = self.templates.METADATA_UPDATE_TITLE
 268 |             _title["title"]["newTitle"] = title
 269 |             _data.update(_title)
 270 | 
 271 |         if description != "":
 272 |             _description = self.templates.METADATA_UPDATE_DESCRIPTION
 273 |             _description["description"]["newDescription"] = description
 274 |             _data.update(_description)
 275 | 
 276 |         if privacy != "":
 277 |             _privacy = self.templates.METADATA_UPDATE_PRIVACY
 278 |             _privacy["privacy"]["newPrivacy"] = privacy
 279 |             _data.update(_privacy)
 280 | 
 281 |         if thumb != "":
 282 |             _thumb = self.templates.METADATA_UPDATE_THUMB
 283 |             image = open(thumb, 'rb')
 284 |             image_64_encode = base64.b64encode(image.read()).decode('utf-8')
 285 | 
 286 |             _thumb["videoStill"]["image"][
 287 |                 "dataUri"] = f"data:image/png;base64,{image_64_encode}"
 288 |             _data.update(_thumb)
 289 | 
 290 |         if len(tags) > 0:
 291 |             _tags = self.templates.METADATA_UPDATE_TAGS
 292 |             _tags["tags"]["newTags"] = tags
 293 |             _data.update(_tags)
 294 | 
 295 |         if category != -1:
 296 |             _category = self.templates.METADATA_UPDATE_CATEGORY
 297 |             _category["category"]["newCategoryId"] = category
 298 |             _data.update(_category)
 299 | 
 300 |         if len(playlist) > 0:
 301 |             _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 302 |             _playlist["addToPlaylist"]["addToPlaylistIds"] = playlist
 303 |             if len(removeFromPlaylist) > 0:
 304 |                 _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 305 |             _data.update(_playlist)
 306 | 
 307 |         if len(removeFromPlaylist) > 0:
 308 |             _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 309 |             _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 310 |             _data.update(_playlist)
 311 | 
 312 |         _monetization = self.templates.METADATA_UPDATE_MONETIZATION
 313 |         _monetization["monetizationSettings"]["newMonetization"] = monetization
 314 |         _data.update(_monetization)
 315 | 
 316 |         update = await self.session.post(
 317 |             f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 318 |             json=_data
 319 |         )
 320 |         return await update.json()
 321 | 
 322 |     async def scheduledUploadVideo(self, file_name, title="New Video", description='This video uploaded by github.com/yusufusta/ytstudio', now_privacy='PRIVATE', schedule_time: datetime.datetime | int = 0, scheduled_privacy="PUBLIC", progress=None, extra_fields={}):
 323 |         """
 324 |         Scheduled uploads a video to youtube.
 325 |         """
 326 |         upload = await self.uploadVideo(file_name, title, description, now_privacy, draft=True, progress=progress, extra_fields=extra_fields)
 327 |         if not "videoId" in upload:
 328 |             return upload
 329 | 
 330 |         self.templates.setVideoId(upload["videoId"])
 331 | 
 332 |         _data = self.templates.METADATA_UPDATE
 333 |         _schedule = self.templates.METADATA_UPDATE_SCHEDULE
 334 | 
 335 |         if isinstance(schedule_time, datetime.datetime):
 336 |             schedule_time = int(schedule_time.timestamp())
 337 |         elif schedule_time == 0:
 338 |             schedule_time = int(datetime.datetime.now().timestamp()) + 60
 339 | 
 340 |         _schedule["scheduledPublishing"]["set"]["timeSec"] = schedule_time
 341 |         _schedule["scheduledPublishing"]["set"]["privacy"] = scheduled_privacy
 342 |         _schedule["privacyState"]["newPrivacy"] = now_privacy
 343 | 
 344 |         _data.update(self.templates.METADATA_UPDATE_SCHEDULE)
 345 | 
 346 |         update = await self.session.post(
 347 |             f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 348 |             json=_data
 349 |         )
 350 |         return upload, await update.json()
351 |
352 |
353 |
354 |

Sub-modules

355 |
356 |
ytstudio.templates
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |

Classes

368 |
369 |
370 | class Studio 371 | (cookies: dict = {'SESSION_TOKEN': '', 'VISITOR_INFO1_LIVE': '', 'PREF': '', 'LOGIN_INFO': '', 'SID': '', '__Secure-3PSID': '.', 'HSID': '', 'SSID': '', 'APISID': '', 'SAPISID': '', '__Secure-3PAPISID': '', 'YSC': '', 'SIDCC': ''}) 372 |
373 |
374 |
375 |
376 | 377 | Expand source code 378 | 379 |
class Studio:
 380 |     YT_STUDIO_URL = "https://studio.youtube.com"
 381 |     USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"
 382 |     TRANSFERRED_BYTES = 0
 383 |     CHUNK_SIZE = 64*1024
 384 | 
 385 |     def __init__(self, cookies: dict = {'SESSION_TOKEN': '', 'VISITOR_INFO1_LIVE': '', 'PREF': '', 'LOGIN_INFO': '', 'SID': '', '__Secure-3PSID': '.', 'HSID': '',
 386 |                  'SSID': '', 'APISID': '', 'SAPISID': '', '__Secure-3PAPISID': '', 'YSC': '', 'SIDCC': ''}):
 387 |         self.SAPISIDHASH = self.generateSAPISIDHASH(cookies['SAPISID'])
 388 |         self.cookies = cookies
 389 |         self.Cookie = " ".join(
 390 |             [f"{c}={cookies[c]};" if not c in ["SESSION_TOKEN", "BOTGUARD_RESPONSE"] else "" for c in cookies.keys()])
 391 |         self.HEADERS = {
 392 |             'Authorization': f'SAPISIDHASH {self.SAPISIDHASH}',
 393 |             'Content-Type': 'application/json',
 394 |             'Cookie': self.Cookie,
 395 |             'X-Origin': self.YT_STUDIO_URL,
 396 |             'User-Agent': self.USER_AGENT
 397 |         }
 398 |         self.session = aiohttp.ClientSession(headers=self.HEADERS)
 399 |         self.loop = asyncio.get_event_loop()
 400 |         self.config = {}
 401 |         self.js = js2py.EvalJs()
 402 |         self.js.execute("var window = {ytcfg: {}};")
 403 | 
 404 |     def __del__(self):
 405 |         asyncio.run(self.session.close())
 406 | 
 407 |     def generateSAPISIDHASH(self, SAPISID) -> str:
 408 |         hash = f"{round(time.time())} {SAPISID} {self.YT_STUDIO_URL}"
 409 |         sifrelenmis = sha1(hash.encode('utf-8')).hexdigest()
 410 |         return f"{round(time.time())}_{sifrelenmis}"
 411 | 
 412 |     async def getMainPage(self) -> str:
 413 |         page = await self.session.get(self.YT_STUDIO_URL)
 414 |         return await page.text("utf-8")
 415 | 
 416 |     async def login(self) -> bool:
 417 |         """
 418 |         Login to your youtube account
 419 |         """
 420 |         page = await self.getMainPage()
 421 |         _ = pq(page)
 422 |         script = _("script")
 423 |         if len(script) < 1:
 424 |             raise Exception("Didn't find script. Can you check your cookies?")
 425 |         script = script[0].text
 426 |         self.js.execute(
 427 |             f"{script} window.ytcfg = ytcfg;")
 428 | 
 429 |         INNERTUBE_API_KEY = self.js.window.ytcfg.data_.INNERTUBE_API_KEY
 430 |         CHANNEL_ID = self.js.window.ytcfg.data_.CHANNEL_ID
 431 |         DELEGATED_SESSION_ID = self.js.window.ytcfg.data_.DELEGATED_SESSION_ID
 432 | 
 433 |         if INNERTUBE_API_KEY == None or CHANNEL_ID == None:
 434 |             raise Exception(
 435 |                 "Didn't find INNERTUBE_API_KEY or CHANNEL_ID. Can you check your cookies?")
 436 |         self.config = {'INNERTUBE_API_KEY': INNERTUBE_API_KEY,
 437 |                        'CHANNEL_ID': CHANNEL_ID, 'data_': self.js.window.ytcfg.data_}
 438 |         self.templates = Templates({
 439 |             'channelId': CHANNEL_ID,
 440 |             'sessionToken': self.cookies['SESSION_TOKEN'],
 441 |             'botguardResponse': self.cookies['BOTGUARD_RESPONSE'] if 'BOTGUARD_RESPONSE' in self.cookies else '',
 442 |             'delegatedSessionId': DELEGATED_SESSION_ID
 443 |         })
 444 | 
 445 |         return True
 446 | 
 447 |     def generateHash(self) -> str:
 448 |         harfler = list(
 449 |             '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
 450 |         keys = ['' for i in range(0, 36)]
 451 |         b = 0
 452 |         c = ""
 453 |         e = 0
 454 | 
 455 |         while e < 36:
 456 |             if 8 == e or 13 == e or 18 == e or 23 == e:
 457 |                 keys[e] = "-"
 458 |             else:
 459 |                 if 14 == e:
 460 |                     keys[e] = "4"
 461 |                 elif 2 >= b:
 462 |                     b = round(33554432 + 16777216 * random.uniform(0, 0.9))
 463 |                 c = b & 15
 464 |                 b = b >> 4
 465 |                 keys[e] = harfler[c & 3 | 8 if 19 == e else c]
 466 |             e += 1
 467 | 
 468 |         return "".join(keys)
 469 | 
 470 |     async def fileSender(self, file_name):
 471 |         async with aiofiles.open(file_name, 'rb') as f:
 472 |             chunk = await f.read(self.CHUNK_SIZE)
 473 |             while chunk:
 474 |                 if self.progress != None:
 475 |                     self.TRANSFERRED_BYTES += len(chunk)
 476 |                     self.progress(self.TRANSFERRED_BYTES,
 477 |                                   os.path.getsize(file_name))
 478 | 
 479 |                 self.TRANSFERRED_BYTES += len(chunk)
 480 |                 yield chunk
 481 |                 chunk = await f.read(self.CHUNK_SIZE)
 482 |                 if not chunk:
 483 |                     break
 484 | 
 485 |     async def uploadFileToYoutube(self, upload_url, file_path):
 486 |         self.TRANSFERRED_BYTES = 0
 487 | 
 488 |         uploaded = await self.session.post(upload_url,  headers={
 489 |             "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
 490 |             "x-goog-upload-command": "upload, finalize",
 491 |             "x-goog-upload-file-name": f"file-{round(time.time())}",
 492 |             "x-goog-upload-offset": "0",
 493 |             "Referer": self.YT_STUDIO_URL,
 494 |         }, data=self.fileSender(file_path), timeout=None)
 495 |         _ = await uploaded.text("utf-8")
 496 |         _ = json.loads(_)
 497 |         return _['scottyResourceId']
 498 | 
 499 |     async def uploadVideo(self, file_name, title=f"New Video {round(time.time())}", description='This video uploaded by github.com/yusufusta/ytstudio', privacy='PRIVATE', draft=False, progress=None, extra_fields={}):
 500 |         """
 501 |         Uploads a video to youtube.
 502 |         """
 503 |         self.progress = progress
 504 |         frontEndUID = f"innertube_studio:{self.generateHash()}:0"
 505 | 
 506 |         uploadRequest = await self.session.post("https://upload.youtube.com/upload/studio",
 507 |                                                 headers={
 508 |                                                     "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
 509 |                                                     "x-goog-upload-command": "start",
 510 |                                                     "x-goog-upload-file-name": f"file-{round(time.time())}",
 511 |                                                     "x-goog-upload-protocol": "resumable",
 512 |                                                     "Referer": self.YT_STUDIO_URL,
 513 |                                                 },
 514 |                                                 json={'frontendUploadId': frontEndUID})
 515 | 
 516 |         uploadUrl = uploadRequest.headers.get("x-goog-upload-url")
 517 |         scottyResourceId = await self.uploadFileToYoutube(uploadUrl, file_name)
 518 | 
 519 |         _data = self.templates.UPLOAD_VIDEO
 520 |         _data["resourceId"]["scottyResourceId"]["id"] = scottyResourceId
 521 |         _data["frontendUploadId"] = frontEndUID
 522 |         _data["initialMetadata"] = {
 523 |             "title": {
 524 |                 "newTitle": title
 525 |             },
 526 |             "description": {
 527 |                 "newDescription": description,
 528 |                 "shouldSegment": True
 529 |             },
 530 |             "privacy": {
 531 |                 "newPrivacy": privacy
 532 |             },
 533 |             "draftState": {
 534 |                 "isDraft": draft
 535 |             },
 536 |         }
 537 |         _data["initialMetadata"].update(extra_fields)
 538 | 
 539 |         upload = await self.session.post(
 540 |             f"https://studio.youtube.com/youtubei/v1/upload/createvideo?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 541 |             json=_data
 542 |         )
 543 | 
 544 |         return await upload.json()
 545 | 
 546 |     async def deleteVideo(self, video_id):
 547 |         """
 548 |         Delete video from your channel
 549 |         """
 550 |         self.templates.setVideoId(video_id)
 551 |         delete = await self.session.post(
 552 |             f"https://studio.youtube.com/youtubei/v1/video/delete?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 553 |             json=self.templates.DELETE_VIDEO
 554 |         )
 555 |         return await delete.json()
 556 | 
 557 |     async def listVideos(self):
 558 |         """
 559 |         Returns a list of videos in your channel
 560 |         """
 561 |         list = await self.session.post(
 562 |             f"https://studio.youtube.com/youtubei/v1/creator/list_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 563 |             json=self.templates.LIST_VIDEOS
 564 |         )
 565 |         return await list.json()
 566 | 
 567 |     async def getVideo(self, video_id):
 568 |         """
 569 |         Get video data.
 570 |         """
 571 |         self.templates.setVideoId(video_id)
 572 |         video = await self.session.post(
 573 |             f"https://studio.youtube.com/youtubei/v1/creator/get_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 574 |             json=self.templates.GET_VIDEO
 575 |         )
 576 |         return await video.json()
 577 | 
 578 |     async def createPlaylist(self, title, privacy="PUBLIC") -> dict:
 579 |         """
 580 |         Create a new playlist.
 581 |         """
 582 |         _data = self.templates.CREATE_PLAYLIST
 583 |         _data["title"] = title
 584 |         _data["privacyStatus"] = privacy
 585 | 
 586 |         create = await self.session.post(
 587 |             f"https://studio.youtube.com/youtubei/v1/playlist/create?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 588 |             json=_data
 589 |         )
 590 |         return await create.json()
 591 | 
 592 |     async def editVideo(self, video_id, title: str = "", description: str = "", privacy: str = "", thumb: typing.Union[str, pathlib.Path, os.PathLike] = "", tags: typing.List[str] = [], category: int = -1, monetization: bool = True, playlist: typing.List[str] = [], removeFromPlaylist: typing.List[str] = []):
 593 |         """
 594 |         Edit video metadata.
 595 |         """
 596 |         self.templates.setVideoId(video_id)
 597 |         _data = self.templates.METADATA_UPDATE
 598 |         if title != "":
 599 |             _title = self.templates.METADATA_UPDATE_TITLE
 600 |             _title["title"]["newTitle"] = title
 601 |             _data.update(_title)
 602 | 
 603 |         if description != "":
 604 |             _description = self.templates.METADATA_UPDATE_DESCRIPTION
 605 |             _description["description"]["newDescription"] = description
 606 |             _data.update(_description)
 607 | 
 608 |         if privacy != "":
 609 |             _privacy = self.templates.METADATA_UPDATE_PRIVACY
 610 |             _privacy["privacy"]["newPrivacy"] = privacy
 611 |             _data.update(_privacy)
 612 | 
 613 |         if thumb != "":
 614 |             _thumb = self.templates.METADATA_UPDATE_THUMB
 615 |             image = open(thumb, 'rb')
 616 |             image_64_encode = base64.b64encode(image.read()).decode('utf-8')
 617 | 
 618 |             _thumb["videoStill"]["image"][
 619 |                 "dataUri"] = f"data:image/png;base64,{image_64_encode}"
 620 |             _data.update(_thumb)
 621 | 
 622 |         if len(tags) > 0:
 623 |             _tags = self.templates.METADATA_UPDATE_TAGS
 624 |             _tags["tags"]["newTags"] = tags
 625 |             _data.update(_tags)
 626 | 
 627 |         if category != -1:
 628 |             _category = self.templates.METADATA_UPDATE_CATEGORY
 629 |             _category["category"]["newCategoryId"] = category
 630 |             _data.update(_category)
 631 | 
 632 |         if len(playlist) > 0:
 633 |             _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 634 |             _playlist["addToPlaylist"]["addToPlaylistIds"] = playlist
 635 |             if len(removeFromPlaylist) > 0:
 636 |                 _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 637 |             _data.update(_playlist)
 638 | 
 639 |         if len(removeFromPlaylist) > 0:
 640 |             _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 641 |             _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 642 |             _data.update(_playlist)
 643 | 
 644 |         _monetization = self.templates.METADATA_UPDATE_MONETIZATION
 645 |         _monetization["monetizationSettings"]["newMonetization"] = monetization
 646 |         _data.update(_monetization)
 647 | 
 648 |         update = await self.session.post(
 649 |             f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 650 |             json=_data
 651 |         )
 652 |         return await update.json()
 653 | 
 654 |     async def scheduledUploadVideo(self, file_name, title="New Video", description='This video uploaded by github.com/yusufusta/ytstudio', now_privacy='PRIVATE', schedule_time: datetime.datetime | int = 0, scheduled_privacy="PUBLIC", progress=None, extra_fields={}):
 655 |         """
 656 |         Scheduled uploads a video to youtube.
 657 |         """
 658 |         upload = await self.uploadVideo(file_name, title, description, now_privacy, draft=True, progress=progress, extra_fields=extra_fields)
 659 |         if not "videoId" in upload:
 660 |             return upload
 661 | 
 662 |         self.templates.setVideoId(upload["videoId"])
 663 | 
 664 |         _data = self.templates.METADATA_UPDATE
 665 |         _schedule = self.templates.METADATA_UPDATE_SCHEDULE
 666 | 
 667 |         if isinstance(schedule_time, datetime.datetime):
 668 |             schedule_time = int(schedule_time.timestamp())
 669 |         elif schedule_time == 0:
 670 |             schedule_time = int(datetime.datetime.now().timestamp()) + 60
 671 | 
 672 |         _schedule["scheduledPublishing"]["set"]["timeSec"] = schedule_time
 673 |         _schedule["scheduledPublishing"]["set"]["privacy"] = scheduled_privacy
 674 |         _schedule["privacyState"]["newPrivacy"] = now_privacy
 675 | 
 676 |         _data.update(self.templates.METADATA_UPDATE_SCHEDULE)
 677 | 
 678 |         update = await self.session.post(
 679 |             f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 680 |             json=_data
 681 |         )
 682 |         return upload, await update.json()
683 |
684 |

Class variables

685 |
686 |
var CHUNK_SIZE
687 |
688 |
689 |
690 |
var TRANSFERRED_BYTES
691 |
692 |
693 |
694 |
var USER_AGENT
695 |
696 |
697 |
698 |
var YT_STUDIO_URL
699 |
700 |
701 |
702 |
703 |

Methods

704 |
705 |
706 | async def createPlaylist(self, title, privacy='PUBLIC') ‑> dict 707 |
708 |
709 |

Create a new playlist.

710 |
711 | 712 | Expand source code 713 | 714 |
async def createPlaylist(self, title, privacy="PUBLIC") -> dict:
 715 |     """
 716 |     Create a new playlist.
 717 |     """
 718 |     _data = self.templates.CREATE_PLAYLIST
 719 |     _data["title"] = title
 720 |     _data["privacyStatus"] = privacy
 721 | 
 722 |     create = await self.session.post(
 723 |         f"https://studio.youtube.com/youtubei/v1/playlist/create?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 724 |         json=_data
 725 |     )
 726 |     return await create.json()
727 |
728 |
729 |
730 | async def deleteVideo(self, video_id) 731 |
732 |
733 |

Delete video from your channel

734 |
735 | 736 | Expand source code 737 | 738 |
async def deleteVideo(self, video_id):
 739 |     """
 740 |     Delete video from your channel
 741 |     """
 742 |     self.templates.setVideoId(video_id)
 743 |     delete = await self.session.post(
 744 |         f"https://studio.youtube.com/youtubei/v1/video/delete?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 745 |         json=self.templates.DELETE_VIDEO
 746 |     )
 747 |     return await delete.json()
748 |
749 |
750 |
751 | async def editVideo(self, video_id, title: str = '', description: str = '', privacy: str = '', thumb: Union[str, pathlib.Path, os.PathLike] = '', tags: List[str] = [], category: int = -1, monetization: bool = True, playlist: List[str] = [], removeFromPlaylist: List[str] = []) 752 |
753 |
754 |

Edit video metadata.

755 |
756 | 757 | Expand source code 758 | 759 |
async def editVideo(self, video_id, title: str = "", description: str = "", privacy: str = "", thumb: typing.Union[str, pathlib.Path, os.PathLike] = "", tags: typing.List[str] = [], category: int = -1, monetization: bool = True, playlist: typing.List[str] = [], removeFromPlaylist: typing.List[str] = []):
 760 |     """
 761 |     Edit video metadata.
 762 |     """
 763 |     self.templates.setVideoId(video_id)
 764 |     _data = self.templates.METADATA_UPDATE
 765 |     if title != "":
 766 |         _title = self.templates.METADATA_UPDATE_TITLE
 767 |         _title["title"]["newTitle"] = title
 768 |         _data.update(_title)
 769 | 
 770 |     if description != "":
 771 |         _description = self.templates.METADATA_UPDATE_DESCRIPTION
 772 |         _description["description"]["newDescription"] = description
 773 |         _data.update(_description)
 774 | 
 775 |     if privacy != "":
 776 |         _privacy = self.templates.METADATA_UPDATE_PRIVACY
 777 |         _privacy["privacy"]["newPrivacy"] = privacy
 778 |         _data.update(_privacy)
 779 | 
 780 |     if thumb != "":
 781 |         _thumb = self.templates.METADATA_UPDATE_THUMB
 782 |         image = open(thumb, 'rb')
 783 |         image_64_encode = base64.b64encode(image.read()).decode('utf-8')
 784 | 
 785 |         _thumb["videoStill"]["image"][
 786 |             "dataUri"] = f"data:image/png;base64,{image_64_encode}"
 787 |         _data.update(_thumb)
 788 | 
 789 |     if len(tags) > 0:
 790 |         _tags = self.templates.METADATA_UPDATE_TAGS
 791 |         _tags["tags"]["newTags"] = tags
 792 |         _data.update(_tags)
 793 | 
 794 |     if category != -1:
 795 |         _category = self.templates.METADATA_UPDATE_CATEGORY
 796 |         _category["category"]["newCategoryId"] = category
 797 |         _data.update(_category)
 798 | 
 799 |     if len(playlist) > 0:
 800 |         _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 801 |         _playlist["addToPlaylist"]["addToPlaylistIds"] = playlist
 802 |         if len(removeFromPlaylist) > 0:
 803 |             _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 804 |         _data.update(_playlist)
 805 | 
 806 |     if len(removeFromPlaylist) > 0:
 807 |         _playlist = self.templates.METADATA_UPDATE_PLAYLIST
 808 |         _playlist["addToPlaylist"]["deleteFromPlaylistIds"] = removeFromPlaylist
 809 |         _data.update(_playlist)
 810 | 
 811 |     _monetization = self.templates.METADATA_UPDATE_MONETIZATION
 812 |     _monetization["monetizationSettings"]["newMonetization"] = monetization
 813 |     _data.update(_monetization)
 814 | 
 815 |     update = await self.session.post(
 816 |         f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 817 |         json=_data
 818 |     )
 819 |     return await update.json()
820 |
821 |
822 |
823 | async def fileSender(self, file_name) 824 |
825 |
826 |
827 |
828 | 829 | Expand source code 830 | 831 |
async def fileSender(self, file_name):
 832 |     async with aiofiles.open(file_name, 'rb') as f:
 833 |         chunk = await f.read(self.CHUNK_SIZE)
 834 |         while chunk:
 835 |             if self.progress != None:
 836 |                 self.TRANSFERRED_BYTES += len(chunk)
 837 |                 self.progress(self.TRANSFERRED_BYTES,
 838 |                               os.path.getsize(file_name))
 839 | 
 840 |             self.TRANSFERRED_BYTES += len(chunk)
 841 |             yield chunk
 842 |             chunk = await f.read(self.CHUNK_SIZE)
 843 |             if not chunk:
 844 |                 break
845 |
846 |
847 |
848 | def generateHash(self) ‑> str 849 |
850 |
851 |
852 |
853 | 854 | Expand source code 855 | 856 |
def generateHash(self) -> str:
 857 |     harfler = list(
 858 |         '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
 859 |     keys = ['' for i in range(0, 36)]
 860 |     b = 0
 861 |     c = ""
 862 |     e = 0
 863 | 
 864 |     while e < 36:
 865 |         if 8 == e or 13 == e or 18 == e or 23 == e:
 866 |             keys[e] = "-"
 867 |         else:
 868 |             if 14 == e:
 869 |                 keys[e] = "4"
 870 |             elif 2 >= b:
 871 |                 b = round(33554432 + 16777216 * random.uniform(0, 0.9))
 872 |             c = b & 15
 873 |             b = b >> 4
 874 |             keys[e] = harfler[c & 3 | 8 if 19 == e else c]
 875 |         e += 1
 876 | 
 877 |     return "".join(keys)
878 |
879 |
880 |
881 | def generateSAPISIDHASH(self, SAPISID) ‑> str 882 |
883 |
884 |
885 |
886 | 887 | Expand source code 888 | 889 |
def generateSAPISIDHASH(self, SAPISID) -> str:
 890 |     hash = f"{round(time.time())} {SAPISID} {self.YT_STUDIO_URL}"
 891 |     sifrelenmis = sha1(hash.encode('utf-8')).hexdigest()
 892 |     return f"{round(time.time())}_{sifrelenmis}"
893 |
894 |
895 |
896 | async def getMainPage(self) ‑> str 897 |
898 |
899 |
900 |
901 | 902 | Expand source code 903 | 904 |
async def getMainPage(self) -> str:
 905 |     page = await self.session.get(self.YT_STUDIO_URL)
 906 |     return await page.text("utf-8")
907 |
908 |
909 |
910 | async def getVideo(self, video_id) 911 |
912 |
913 |

Get video data.

914 |
915 | 916 | Expand source code 917 | 918 |
async def getVideo(self, video_id):
 919 |     """
 920 |     Get video data.
 921 |     """
 922 |     self.templates.setVideoId(video_id)
 923 |     video = await self.session.post(
 924 |         f"https://studio.youtube.com/youtubei/v1/creator/get_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 925 |         json=self.templates.GET_VIDEO
 926 |     )
 927 |     return await video.json()
928 |
929 |
930 |
931 | async def listVideos(self) 932 |
933 |
934 |

Returns a list of videos in your channel

935 |
936 | 937 | Expand source code 938 | 939 |
async def listVideos(self):
 940 |     """
 941 |     Returns a list of videos in your channel
 942 |     """
 943 |     list = await self.session.post(
 944 |         f"https://studio.youtube.com/youtubei/v1/creator/list_creator_videos?alt=json&key={self.config['INNERTUBE_API_KEY']}",
 945 |         json=self.templates.LIST_VIDEOS
 946 |     )
 947 |     return await list.json()
948 |
949 |
950 |
951 | async def login(self) ‑> bool 952 |
953 |
954 |

Login to your youtube account

955 |
956 | 957 | Expand source code 958 | 959 |
async def login(self) -> bool:
 960 |     """
 961 |     Login to your youtube account
 962 |     """
 963 |     page = await self.getMainPage()
 964 |     _ = pq(page)
 965 |     script = _("script")
 966 |     if len(script) < 1:
 967 |         raise Exception("Didn't find script. Can you check your cookies?")
 968 |     script = script[0].text
 969 |     self.js.execute(
 970 |         f"{script} window.ytcfg = ytcfg;")
 971 | 
 972 |     INNERTUBE_API_KEY = self.js.window.ytcfg.data_.INNERTUBE_API_KEY
 973 |     CHANNEL_ID = self.js.window.ytcfg.data_.CHANNEL_ID
 974 |     DELEGATED_SESSION_ID = self.js.window.ytcfg.data_.DELEGATED_SESSION_ID
 975 | 
 976 |     if INNERTUBE_API_KEY == None or CHANNEL_ID == None:
 977 |         raise Exception(
 978 |             "Didn't find INNERTUBE_API_KEY or CHANNEL_ID. Can you check your cookies?")
 979 |     self.config = {'INNERTUBE_API_KEY': INNERTUBE_API_KEY,
 980 |                    'CHANNEL_ID': CHANNEL_ID, 'data_': self.js.window.ytcfg.data_}
 981 |     self.templates = Templates({
 982 |         'channelId': CHANNEL_ID,
 983 |         'sessionToken': self.cookies['SESSION_TOKEN'],
 984 |         'botguardResponse': self.cookies['BOTGUARD_RESPONSE'] if 'BOTGUARD_RESPONSE' in self.cookies else '',
 985 |         'delegatedSessionId': DELEGATED_SESSION_ID
 986 |     })
 987 | 
 988 |     return True
989 |
990 |
991 |
992 | async def scheduledUploadVideo(self, file_name, title='New Video', description='This video uploaded by github.com/yusufusta/ytstudio', now_privacy='PRIVATE', schedule_time: datetime.datetime | int = 0, scheduled_privacy='PUBLIC', progress=None, extra_fields={}) 993 |
994 |
995 |

Scheduled uploads a video to youtube.

996 |
997 | 998 | Expand source code 999 | 1000 |
async def scheduledUploadVideo(self, file_name, title="New Video", description='This video uploaded by github.com/yusufusta/ytstudio', now_privacy='PRIVATE', schedule_time: datetime.datetime | int = 0, scheduled_privacy="PUBLIC", progress=None, extra_fields={}):
1001 |     """
1002 |     Scheduled uploads a video to youtube.
1003 |     """
1004 |     upload = await self.uploadVideo(file_name, title, description, now_privacy, draft=True, progress=progress, extra_fields=extra_fields)
1005 |     if not "videoId" in upload:
1006 |         return upload
1007 | 
1008 |     self.templates.setVideoId(upload["videoId"])
1009 | 
1010 |     _data = self.templates.METADATA_UPDATE
1011 |     _schedule = self.templates.METADATA_UPDATE_SCHEDULE
1012 | 
1013 |     if isinstance(schedule_time, datetime.datetime):
1014 |         schedule_time = int(schedule_time.timestamp())
1015 |     elif schedule_time == 0:
1016 |         schedule_time = int(datetime.datetime.now().timestamp()) + 60
1017 | 
1018 |     _schedule["scheduledPublishing"]["set"]["timeSec"] = schedule_time
1019 |     _schedule["scheduledPublishing"]["set"]["privacy"] = scheduled_privacy
1020 |     _schedule["privacyState"]["newPrivacy"] = now_privacy
1021 | 
1022 |     _data.update(self.templates.METADATA_UPDATE_SCHEDULE)
1023 | 
1024 |     update = await self.session.post(
1025 |         f"https://studio.youtube.com/youtubei/v1/video_manager/metadata_update?alt=json&key={self.config['INNERTUBE_API_KEY']}",
1026 |         json=_data
1027 |     )
1028 |     return upload, await update.json()
1029 |
1030 |
1031 |
1032 | async def uploadFileToYoutube(self, upload_url, file_path) 1033 |
1034 |
1035 |
1036 |
1037 | 1038 | Expand source code 1039 | 1040 |
async def uploadFileToYoutube(self, upload_url, file_path):
1041 |     self.TRANSFERRED_BYTES = 0
1042 | 
1043 |     uploaded = await self.session.post(upload_url,  headers={
1044 |         "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
1045 |         "x-goog-upload-command": "upload, finalize",
1046 |         "x-goog-upload-file-name": f"file-{round(time.time())}",
1047 |         "x-goog-upload-offset": "0",
1048 |         "Referer": self.YT_STUDIO_URL,
1049 |     }, data=self.fileSender(file_path), timeout=None)
1050 |     _ = await uploaded.text("utf-8")
1051 |     _ = json.loads(_)
1052 |     return _['scottyResourceId']
1053 |
1054 |
1055 |
1056 | async def uploadVideo(self, file_name, title='New Video 1675980145', description='This video uploaded by github.com/yusufusta/ytstudio', privacy='PRIVATE', draft=False, progress=None, extra_fields={}) 1057 |
1058 |
1059 |

Uploads a video to youtube.

1060 |
1061 | 1062 | Expand source code 1063 | 1064 |
async def uploadVideo(self, file_name, title=f"New Video {round(time.time())}", description='This video uploaded by github.com/yusufusta/ytstudio', privacy='PRIVATE', draft=False, progress=None, extra_fields={}):
1065 |     """
1066 |     Uploads a video to youtube.
1067 |     """
1068 |     self.progress = progress
1069 |     frontEndUID = f"innertube_studio:{self.generateHash()}:0"
1070 | 
1071 |     uploadRequest = await self.session.post("https://upload.youtube.com/upload/studio",
1072 |                                             headers={
1073 |                                                 "Content-Type": "application/x-www-form-urlencoded;charset=utf-8'",
1074 |                                                 "x-goog-upload-command": "start",
1075 |                                                 "x-goog-upload-file-name": f"file-{round(time.time())}",
1076 |                                                 "x-goog-upload-protocol": "resumable",
1077 |                                                 "Referer": self.YT_STUDIO_URL,
1078 |                                             },
1079 |                                             json={'frontendUploadId': frontEndUID})
1080 | 
1081 |     uploadUrl = uploadRequest.headers.get("x-goog-upload-url")
1082 |     scottyResourceId = await self.uploadFileToYoutube(uploadUrl, file_name)
1083 | 
1084 |     _data = self.templates.UPLOAD_VIDEO
1085 |     _data["resourceId"]["scottyResourceId"]["id"] = scottyResourceId
1086 |     _data["frontendUploadId"] = frontEndUID
1087 |     _data["initialMetadata"] = {
1088 |         "title": {
1089 |             "newTitle": title
1090 |         },
1091 |         "description": {
1092 |             "newDescription": description,
1093 |             "shouldSegment": True
1094 |         },
1095 |         "privacy": {
1096 |             "newPrivacy": privacy
1097 |         },
1098 |         "draftState": {
1099 |             "isDraft": draft
1100 |         },
1101 |     }
1102 |     _data["initialMetadata"].update(extra_fields)
1103 | 
1104 |     upload = await self.session.post(
1105 |         f"https://studio.youtube.com/youtubei/v1/upload/createvideo?alt=json&key={self.config['INNERTUBE_API_KEY']}",
1106 |         json=_data
1107 |     )
1108 | 
1109 |     return await upload.json()
1110 |
1111 |
1112 |
1113 |
1114 |
1115 |
1116 |
1117 | 1156 |
1157 | 1160 | 1161 | -------------------------------------------------------------------------------- /docs/templates.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | ytstudio.templates API documentation 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 |
21 |
22 |

Module ytstudio.templates

23 |
24 |
25 |
26 | 27 | Expand source code 28 | 29 |
class Templates:
  30 |     channelId = ""
  31 |     videoId = ""
  32 |     sessionToken = ""
  33 |     botguardResponse = ""
  34 |     delegatedSessionId = ""
  35 | 
  36 |     CLIENT = {
  37 |         "clientName": 62,
  38 |         "clientVersion": "1.20201130.03.00",
  39 |         "hl": "en-GB",
  40 |         "gl": "PL",
  41 |         "experimentsToken": "",
  42 |         "utcOffsetMinutes": 60
  43 |     }
  44 | 
  45 |     def __init__(self, config) -> None:
  46 |         self.config = config
  47 |         self.channelId = self.config["channelId"]
  48 |         self.sessionToken = self.config["sessionToken"]
  49 |         self.botguardResponse = self.config["botguardResponse"] if "botguardResponse" in self.config else ""
  50 |         self.delegatedSessionId = self.config["delegatedSessionId"] if "delegatedSessionId" in self.config else ""
  51 |         self._()
  52 | 
  53 |     def setVideoId(self, videoId):
  54 |         self.videoId = videoId
  55 |         self._()
  56 | 
  57 |     def _(self):
  58 |         self.DELETE_VIDEO = {
  59 |             "videoId": self.videoId,
  60 |             "context": {
  61 |                 "client": self.CLIENT,
  62 |                 "request": {
  63 |                     "returnLogEntry": True,
  64 |                     "internalExperimentFlags": [],
  65 |                     "sessionInfo": {
  66 |                         "token": self.sessionToken
  67 |                     }
  68 |                 },
  69 |                 "user": {
  70 |                     "delegationContext": {
  71 |                         "roleType": {
  72 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
  73 |                         },
  74 |                         "externalChannelId": self.channelId
  75 |                     },
  76 |                     "serializedDelegationContext": ""
  77 |                 },
  78 |                 "clientScreenNonce": ""
  79 |             },
  80 |             "delegationContext": {
  81 |                 "roleType": {
  82 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
  83 |                 },
  84 |                 "externalChannelId": self.channelId
  85 |             }
  86 |         }
  87 | 
  88 |         self.UPLOAD_VIDEO = {
  89 |             "channelId": self.channelId,
  90 |             "resourceId": {
  91 |                 "scottyResourceId": {
  92 |                     "id": ""
  93 |                 }
  94 |             },
  95 |             "frontendUploadId": "",
  96 |             "initialMetadata": {
  97 |                 "title": {
  98 |                     "newTitle": ""
  99 |                 },
 100 |                 "description": {
 101 |                     "newDescription": "",
 102 |                     "shouldSegment": True
 103 |                 },
 104 |                 "privacy": {
 105 |                     "newPrivacy": ""
 106 |                 },
 107 |                 "draftState": {
 108 |                     "isDraft": ""
 109 |                 }
 110 |             },
 111 |             "context": {
 112 |                 "client": self.CLIENT,
 113 |                 "request": {
 114 |                     "returnLogEntry": True,
 115 |                     "internalExperimentFlags": [],
 116 |                     "sessionInfo": {
 117 |                         "token": self.sessionToken
 118 |                     }
 119 |                 },
 120 |                 "user": {
 121 |                     "onBehalfOfUser": self.delegatedSessionId,
 122 |                     "delegationContext": {
 123 |                         "externalChannelId": self.channelId,
 124 |                         "roleType": {
 125 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 126 |                         }
 127 |                     },
 128 |                     "serializedDelegationContext": ""
 129 |                 },
 130 |                 "clientScreenNonce": ""
 131 |             },
 132 |             "delegationContext": {
 133 |                 "roleType": {
 134 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 135 |                 },
 136 |                 "externalChannelId": self.channelId
 137 |             }
 138 |         }
 139 | 
 140 |         if self.botguardResponse and self.botguardResponse != "":
 141 |             self.UPLOAD_VIDEO["botguardClientResponse"] = self.botguardResponse
 142 | 
 143 |         self.METADATA_UPDATE = {
 144 |             "encryptedVideoId": self.videoId,
 145 |             "videoReadMask": {
 146 |                 "channelId": True,
 147 |                 "videoId": True,
 148 |                 "lengthSeconds": True,
 149 |                 "premiere": {
 150 |                     "all": True
 151 |                 },
 152 |                 "status": True,
 153 |                 "thumbnailDetails": {
 154 |                     "all": True
 155 |                 },
 156 |                 "title": True,
 157 |                 "draftStatus": True,
 158 |                 "downloadUrl": True,
 159 |                 "watchUrl": True,
 160 |                 "permissions": {
 161 |                     "all": True
 162 |                 },
 163 |                 "timeCreatedSeconds": True,
 164 |                 "timePublishedSeconds": True,
 165 |                 "origin": True,
 166 |                 "livestream": {
 167 |                     "all": True
 168 |                 },
 169 |                 "privacy": True,
 170 |                 "contentOwnershipModelSettings": {
 171 |                     "all": True
 172 |                 },
 173 |                 "features": {
 174 |                     "all": True
 175 |                 },
 176 |                 "responseStatus": {
 177 |                     "all": True
 178 |                 },
 179 |                 "statusDetails": {
 180 |                     "all": True
 181 |                 },
 182 |                 "description": True,
 183 |                 "metrics": {
 184 |                     "all": True
 185 |                 },
 186 |                 "publicLivestream": {
 187 |                     "all": True
 188 |                 },
 189 |                 "publicPremiere": {
 190 |                     "all": True
 191 |                 },
 192 |                 "titleFormattedString": {
 193 |                     "all": True
 194 |                 },
 195 |                 "descriptionFormattedString": {
 196 |                     "all": True
 197 |                 },
 198 |                 "audienceRestriction": {
 199 |                     "all": True
 200 |                 },
 201 |                 "monetization": {
 202 |                     "all": True
 203 |                 },
 204 |                 "selfCertification": {
 205 |                     "all": True
 206 |                 },
 207 |                 "allRestrictions": {
 208 |                     "all": True
 209 |                 },
 210 |                 "inlineEditProcessingStatus": True,
 211 |                 "videoPrechecks": {
 212 |                     "all": True
 213 |                 },
 214 |                 "videoResolutions": {
 215 |                     "all": True
 216 |                 },
 217 |                 "scheduledPublishingDetails": {
 218 |                     "all": True
 219 |                 },
 220 |                 "visibility": {
 221 |                     "all": True
 222 |                 },
 223 |                 "privateShare": {
 224 |                     "all": True
 225 |                 },
 226 |                 "sponsorsOnly": {
 227 |                     "all": True
 228 |                 },
 229 |                 "unlistedExpired": True,
 230 |                 "videoTrailers": {
 231 |                     "all": True
 232 |                 }
 233 |             },
 234 |             "context": {
 235 |                 "client": self.CLIENT,
 236 |                 "request": {
 237 |                     "returnLogEntry": True,
 238 |                     "internalExperimentFlags": [],
 239 |                     "sessionInfo": {
 240 |                         "token": self.sessionToken
 241 |                     }
 242 |                 },
 243 |                 "user": {
 244 |                     "delegationContext": {
 245 |                         "externalChannelId": self.channelId,
 246 |                         "roleType": {
 247 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 248 |                         }
 249 |                     },
 250 |                     "serializedDelegationContext": ""
 251 |                 },
 252 |                 "clientScreenNonce": ""
 253 |             },
 254 |             "delegationContext": {
 255 |                 "externalChannelId": self.channelId,
 256 |                 "roleType": {
 257 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 258 |                 }
 259 |             }
 260 |         }
 261 | 
 262 |         self.METADATA_UPDATE_MONETIZATION = {
 263 |             "monetizationSettings": {
 264 |                 "newMonetizeWithAds": True
 265 |             }
 266 |         }
 267 | 
 268 |         self.METADATA_UPDATE_SCHEDULE = {
 269 |             "flowType": "MDE_FLOW_TYPE_UPLOAD",
 270 |             "privacyState": {
 271 |                 "newPrivacy": "PRIVATE"
 272 |             },
 273 |             "scheduledPublishing": {
 274 |                 "set": {
 275 |                     "timeSec": 0,
 276 |                     "privacy": "PUBLIC"
 277 |                 }
 278 |             },
 279 |             "draftState": {
 280 |                 "operation": "MDE_DRAFT_STATE_UPDATE_OPERATION_REMOVE_DRAFT_STATE"
 281 |             }
 282 |         }
 283 | 
 284 |         self.LIST_VIDEOS = {
 285 |             "filter": {
 286 |                 "and": {
 287 |                     "operands": [
 288 |                         {
 289 |                             "channelIdIs": {
 290 |                                 "value": self.channelId
 291 |                             }
 292 |                         }, {
 293 |                             "videoOriginIs": {
 294 |                                 "value": "VIDEO_ORIGIN_UPLOAD"
 295 |                             }
 296 |                         }
 297 |                     ]
 298 |                 }
 299 |             },
 300 |             "order": "VIDEO_ORDER_DISPLAY_TIME_DESC",
 301 |             "pageSize": 30,
 302 |             "mask": {
 303 |                 "channelId": True,
 304 |                 "videoId": True,
 305 |                 "lengthSeconds": True,
 306 |                 "premiere": {
 307 |                     "all": True
 308 |                 },
 309 |                 "status": True,
 310 |                 "thumbnailDetails": {
 311 |                     "all": True
 312 |                 },
 313 |                 "title": True,
 314 |                 "draftStatus": True,
 315 |                 "downloadUrl": True,
 316 |                 "watchUrl": True,
 317 |                 "permissions": {
 318 |                     "all": True
 319 |                 },
 320 |                 "timeCreatedSeconds": True,
 321 |                 "timePublishedSeconds": True,
 322 |                 "origin": True,
 323 |                 "livestream": {
 324 |                     "all": True
 325 |                 },
 326 |                 "privacy": True,
 327 |                 "contentOwnershipModelSettings": {
 328 |                     "all": True
 329 |                 },
 330 |                 "features": {
 331 |                     "all": True
 332 |                 },
 333 |                 "responseStatus": {
 334 |                     "all": True
 335 |                 },
 336 |                 "statusDetails": {
 337 |                     "all": True
 338 |                 },
 339 |                 "description": True,
 340 |                 "metrics": {
 341 |                     "all": True
 342 |                 },
 343 |                 "publicLivestream": {
 344 |                     "all": True
 345 |                 },
 346 |                 "publicPremiere": {
 347 |                     "all": True
 348 |                 },
 349 |                 "titleFormattedString": {
 350 |                     "all": True
 351 |                 },
 352 |                 "descriptionFormattedString": {
 353 |                     "all": True
 354 |                 },
 355 |                 "audienceRestriction": {
 356 |                     "all": True
 357 |                 },
 358 |                 "monetization": {
 359 |                     "all": True
 360 |                 },
 361 |                 "selfCertification": {
 362 |                     "all": True
 363 |                 },
 364 |                 "allRestrictions": {
 365 |                     "all": True
 366 |                 },
 367 |                 "inlineEditProcessingStatus": True,
 368 |                 "videoPrechecks": {
 369 |                     "all": True
 370 |                 },
 371 |                 "videoResolutions": {
 372 |                     "all": True
 373 |                 },
 374 |                 "scheduledPublishingDetails": {
 375 |                     "all": True
 376 |                 },
 377 |                 "visibility": {
 378 |                     "all": True
 379 |                 },
 380 |                 "privateShare": {
 381 |                     "all": True
 382 |                 },
 383 |                 "sponsorsOnly": {
 384 |                     "all": True
 385 |                 },
 386 |                 "unlistedExpired": True,
 387 |                 "videoTrailers": {
 388 |                     "all": True
 389 |                 }
 390 |             },
 391 |             "context": {
 392 |                 "client": self.CLIENT,
 393 |                 "request": {
 394 |                     "returnLogEntry": True,
 395 |                     "internalExperimentFlags": []
 396 |                 },
 397 |                 "user": {
 398 |                     "delegationContext": {
 399 |                         "externalChannelId": self.channelId,
 400 |                         "roleType": {
 401 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 402 |                         }
 403 |                     },
 404 |                     "serializedDelegationContext": ""
 405 |                 },
 406 |                 "clientScreenNonce": ""
 407 |             }
 408 |         }
 409 | 
 410 |         self.GET_VIDEO = {
 411 |             "context": {
 412 |                 "client": self.CLIENT,
 413 |                 "request": {
 414 |                     "returnLogEntry": True,
 415 |                     "internalExperimentFlags": []
 416 |                 },
 417 |                 "user": {
 418 |                     "delegationContext": {
 419 |                         "externalChannelId": self.channelId,
 420 |                         "roleType": {
 421 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 422 |                         }
 423 |                     },
 424 |                     "serializedDelegationContext": ""
 425 |                 },
 426 |                 "clientScreenNonce": ""
 427 |             },
 428 |             "failOnError": True,
 429 |             "videoIds": [self.videoId],
 430 |             "mask": {
 431 |                 "downloadUrl": True,
 432 |                 "origin": True,
 433 |                 "premiere": {
 434 |                     "all": True
 435 |                 },
 436 |                 "privacy": True,
 437 |                 "videoId": True,
 438 |                 "status": True,
 439 |                 "permissions": {
 440 |                     "all": True
 441 |                 },
 442 |                 "draftStatus": True,
 443 |                 "statusDetails": {
 444 |                     "all": True
 445 |                 },
 446 |                 "inlineEditProcessingStatus": True,
 447 |                 "selfCertification": {
 448 |                     "all": True
 449 |                 },
 450 |                 "monetization": {
 451 |                     "all": True
 452 |                 },
 453 |                 "allRestrictions": {
 454 |                     "all": True
 455 |                 },
 456 |                 "videoPrechecks": {
 457 |                     "all": True
 458 |                 },
 459 |                 "audienceRestriction": {
 460 |                     "all": True
 461 |                 },
 462 |                 "responseStatus": {
 463 |                     "all": True
 464 |                 },
 465 |                 "features": {
 466 |                     "all": True
 467 |                 },
 468 |                 "videoAdvertiserSpecificAgeGates": {
 469 |                     "all": True
 470 |                 },
 471 |                 "claimDetails": {
 472 |                     "all": True
 473 |                 },
 474 |                 "commentsDisabledInternally": True,
 475 |                 "livestream": {
 476 |                     "all": True
 477 |                 },
 478 |                 "music": {
 479 |                     "all": True
 480 |                 },
 481 |                 "ownedClaimDetails": {
 482 |                     "all": True
 483 |                 },
 484 |                 "timePublishedSeconds": True,
 485 |                 "uncaptionedReason": True,
 486 |                 "remix": {
 487 |                     "all": True
 488 |                 },
 489 |                 "contentOwnershipModelSettings": {
 490 |                     "all": True
 491 |                 },
 492 |                 "channelId": True,
 493 |                 "mfkSettings": {
 494 |                     "all": True
 495 |                 },
 496 |                 "thumbnailEditorState": {
 497 |                     "all": True
 498 |                 },
 499 |                 "thumbnailDetails": {
 500 |                     "all": True
 501 |                 },
 502 |                 "scheduledPublishingDetails": {
 503 |                     "all": True
 504 |                 },
 505 |                 "visibility": {
 506 |                     "all": True
 507 |                 },
 508 |                 "privateShare": {
 509 |                     "all": True
 510 |                 },
 511 |                 "sponsorsOnly": {
 512 |                     "all": True
 513 |                 },
 514 |                 "unlistedExpired": True,
 515 |                 "videoTrailers": {
 516 |                     "all": True
 517 |                 },
 518 |                 "allowComments": True,
 519 |                 "allowEmbed": True,
 520 |                 "allowRatings": True,
 521 |                 "ageRestriction": True,
 522 |                 "audioLanguage": {
 523 |                     "all": True
 524 |                 },
 525 |                 "category": True,
 526 |                 "commentFilter": True,
 527 |                 "crowdsourcingEnabled": True,
 528 |                 "dateRecorded": {
 529 |                     "all": True
 530 |                 },
 531 |                 "defaultCommentSortOrder": True,
 532 |                 "description": True,
 533 |                 "descriptionFormattedString": {
 534 |                     "all": True
 535 |                 },
 536 |                 "gameTitle": {
 537 |                     "all": True
 538 |                 },
 539 |                 "license": True,
 540 |                 "liveChat": {
 541 |                     "all": True
 542 |                 },
 543 |                 "location": {
 544 |                     "all": True
 545 |                 },
 546 |                 "metadataLanguage": {
 547 |                     "all": True
 548 |                 },
 549 |                 "paidProductPlacement": True,
 550 |                 "publishing": {
 551 |                     "all": True
 552 |                 },
 553 |                 "tags": {
 554 |                     "all": True
 555 |                 },
 556 |                 "title": True,
 557 |                 "titleFormattedString": {
 558 |                     "all": True
 559 |                 },
 560 |                 "viewCountIsHidden": True,
 561 |                 "autoChapterSettings": {
 562 |                     "all": True
 563 |                 },
 564 |                 "videoStreamUrl": True,
 565 |                 "videoDurationMs": True,
 566 |                 "videoEditorProject": {
 567 |                     "videoDimensions": {
 568 |                         "all": True
 569 |                     }
 570 |                 },
 571 |                 "originalFilename": True,
 572 |                 "videoResolutions": {
 573 |                     "all": True
 574 |                 }
 575 |             },
 576 |             "criticalRead": False
 577 |         }
 578 | 
 579 |         self.CREATE_PLAYLIST = {
 580 |             "title": "",
 581 |             "privacyStatus": "",
 582 |             "context": {
 583 |                 "client": self.CLIENT,
 584 |                 "request": {
 585 |                     "returnLogEntry": True,
 586 |                     "internalExperimentFlags": [],
 587 |                     "sessionInfo": {
 588 |                         "token": self.sessionToken
 589 |                     }
 590 |                 },
 591 |                 "user": {
 592 |                     "delegationContext": {
 593 |                         "externalChannelId": self.channelId,
 594 |                         "roleType": {
 595 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 596 |                         }
 597 |                     },
 598 |                     "serializedDelegationContext": ""
 599 |                 },
 600 |                 "clientScreenNonce": ""
 601 |             },
 602 |             "delegationContext": {
 603 |                 "externalChannelId": self.channelId,
 604 |                 "roleType": {
 605 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 606 |                 }
 607 |             }
 608 |         }
 609 | 
 610 |         self.METADATA_UPDATE_PLAYLIST = {
 611 |             "addToPlaylist": {
 612 |                 "addToPlaylistIds": [],
 613 |                 "deleteFromPlaylistIds": []
 614 |             }
 615 |         }
 616 | 
 617 |         self.METADATA_UPDATE_TITLE = {
 618 |             "title": {
 619 |                 "newTitle": "",
 620 |                 "shouldSegment": True
 621 |             }
 622 |         }
 623 | 
 624 |         self.METADATA_UPDATE_DESCRIPTION = {
 625 |             "description": {
 626 |                 "newDescription": "",
 627 |                 "shouldSegment": True
 628 |             }
 629 |         }
 630 | 
 631 |         self.METADATA_UPDATE_TAGS = {
 632 |             "tags": {
 633 |                 "newTags": [],
 634 |                 "shouldSegment": True
 635 |             }
 636 |         }
 637 | 
 638 |         self.METADATA_UPDATE_CATEGORY = {
 639 |             "category": {
 640 |                 "newCategoryId": 0
 641 |             }
 642 |         }
 643 | 
 644 |         self.METADATA_UPDATE_COMMENTS = {
 645 |             "commentOptions": {
 646 |                 "newAllowComments": True,
 647 |                 "newAllowCommentsMode": "ALL_COMMENTS",
 648 |                 "newCanViewRatings": True,
 649 |                 "newDefaultSortOrder": "MDE_COMMENT_SORT_ORDER_TOP"
 650 |             }
 651 |         }
 652 | 
 653 |         self.METADATA_UPDATE_PRIVACY = {
 654 |             "privacyState": {"newPrivacy": "PUBLIC"}
 655 |         }
 656 | 
 657 |         self.METADATA_UPDATE_THUMB = {
 658 |             "videoStill": {"operation": "UPLOAD_CUSTOM_THUMBNAIL", "image": {
 659 |                 "dataUri": ""
 660 |             }}
 661 |         }
662 |
663 |
664 |
665 |
666 |
667 |
668 |
669 |
670 |
671 |

Classes

672 |
673 |
674 | class Templates 675 | (config) 676 |
677 |
678 |
679 |
680 | 681 | Expand source code 682 | 683 |
class Templates:
 684 |     channelId = ""
 685 |     videoId = ""
 686 |     sessionToken = ""
 687 |     botguardResponse = ""
 688 |     delegatedSessionId = ""
 689 | 
 690 |     CLIENT = {
 691 |         "clientName": 62,
 692 |         "clientVersion": "1.20201130.03.00",
 693 |         "hl": "en-GB",
 694 |         "gl": "PL",
 695 |         "experimentsToken": "",
 696 |         "utcOffsetMinutes": 60
 697 |     }
 698 | 
 699 |     def __init__(self, config) -> None:
 700 |         self.config = config
 701 |         self.channelId = self.config["channelId"]
 702 |         self.sessionToken = self.config["sessionToken"]
 703 |         self.botguardResponse = self.config["botguardResponse"] if "botguardResponse" in self.config else ""
 704 |         self.delegatedSessionId = self.config["delegatedSessionId"] if "delegatedSessionId" in self.config else ""
 705 |         self._()
 706 | 
 707 |     def setVideoId(self, videoId):
 708 |         self.videoId = videoId
 709 |         self._()
 710 | 
 711 |     def _(self):
 712 |         self.DELETE_VIDEO = {
 713 |             "videoId": self.videoId,
 714 |             "context": {
 715 |                 "client": self.CLIENT,
 716 |                 "request": {
 717 |                     "returnLogEntry": True,
 718 |                     "internalExperimentFlags": [],
 719 |                     "sessionInfo": {
 720 |                         "token": self.sessionToken
 721 |                     }
 722 |                 },
 723 |                 "user": {
 724 |                     "delegationContext": {
 725 |                         "roleType": {
 726 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 727 |                         },
 728 |                         "externalChannelId": self.channelId
 729 |                     },
 730 |                     "serializedDelegationContext": ""
 731 |                 },
 732 |                 "clientScreenNonce": ""
 733 |             },
 734 |             "delegationContext": {
 735 |                 "roleType": {
 736 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 737 |                 },
 738 |                 "externalChannelId": self.channelId
 739 |             }
 740 |         }
 741 | 
 742 |         self.UPLOAD_VIDEO = {
 743 |             "channelId": self.channelId,
 744 |             "resourceId": {
 745 |                 "scottyResourceId": {
 746 |                     "id": ""
 747 |                 }
 748 |             },
 749 |             "frontendUploadId": "",
 750 |             "initialMetadata": {
 751 |                 "title": {
 752 |                     "newTitle": ""
 753 |                 },
 754 |                 "description": {
 755 |                     "newDescription": "",
 756 |                     "shouldSegment": True
 757 |                 },
 758 |                 "privacy": {
 759 |                     "newPrivacy": ""
 760 |                 },
 761 |                 "draftState": {
 762 |                     "isDraft": ""
 763 |                 }
 764 |             },
 765 |             "context": {
 766 |                 "client": self.CLIENT,
 767 |                 "request": {
 768 |                     "returnLogEntry": True,
 769 |                     "internalExperimentFlags": [],
 770 |                     "sessionInfo": {
 771 |                         "token": self.sessionToken
 772 |                     }
 773 |                 },
 774 |                 "user": {
 775 |                     "onBehalfOfUser": self.delegatedSessionId,
 776 |                     "delegationContext": {
 777 |                         "externalChannelId": self.channelId,
 778 |                         "roleType": {
 779 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 780 |                         }
 781 |                     },
 782 |                     "serializedDelegationContext": ""
 783 |                 },
 784 |                 "clientScreenNonce": ""
 785 |             },
 786 |             "delegationContext": {
 787 |                 "roleType": {
 788 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 789 |                 },
 790 |                 "externalChannelId": self.channelId
 791 |             }
 792 |         }
 793 | 
 794 |         if self.botguardResponse and self.botguardResponse != "":
 795 |             self.UPLOAD_VIDEO["botguardClientResponse"] = self.botguardResponse
 796 | 
 797 |         self.METADATA_UPDATE = {
 798 |             "encryptedVideoId": self.videoId,
 799 |             "videoReadMask": {
 800 |                 "channelId": True,
 801 |                 "videoId": True,
 802 |                 "lengthSeconds": True,
 803 |                 "premiere": {
 804 |                     "all": True
 805 |                 },
 806 |                 "status": True,
 807 |                 "thumbnailDetails": {
 808 |                     "all": True
 809 |                 },
 810 |                 "title": True,
 811 |                 "draftStatus": True,
 812 |                 "downloadUrl": True,
 813 |                 "watchUrl": True,
 814 |                 "permissions": {
 815 |                     "all": True
 816 |                 },
 817 |                 "timeCreatedSeconds": True,
 818 |                 "timePublishedSeconds": True,
 819 |                 "origin": True,
 820 |                 "livestream": {
 821 |                     "all": True
 822 |                 },
 823 |                 "privacy": True,
 824 |                 "contentOwnershipModelSettings": {
 825 |                     "all": True
 826 |                 },
 827 |                 "features": {
 828 |                     "all": True
 829 |                 },
 830 |                 "responseStatus": {
 831 |                     "all": True
 832 |                 },
 833 |                 "statusDetails": {
 834 |                     "all": True
 835 |                 },
 836 |                 "description": True,
 837 |                 "metrics": {
 838 |                     "all": True
 839 |                 },
 840 |                 "publicLivestream": {
 841 |                     "all": True
 842 |                 },
 843 |                 "publicPremiere": {
 844 |                     "all": True
 845 |                 },
 846 |                 "titleFormattedString": {
 847 |                     "all": True
 848 |                 },
 849 |                 "descriptionFormattedString": {
 850 |                     "all": True
 851 |                 },
 852 |                 "audienceRestriction": {
 853 |                     "all": True
 854 |                 },
 855 |                 "monetization": {
 856 |                     "all": True
 857 |                 },
 858 |                 "selfCertification": {
 859 |                     "all": True
 860 |                 },
 861 |                 "allRestrictions": {
 862 |                     "all": True
 863 |                 },
 864 |                 "inlineEditProcessingStatus": True,
 865 |                 "videoPrechecks": {
 866 |                     "all": True
 867 |                 },
 868 |                 "videoResolutions": {
 869 |                     "all": True
 870 |                 },
 871 |                 "scheduledPublishingDetails": {
 872 |                     "all": True
 873 |                 },
 874 |                 "visibility": {
 875 |                     "all": True
 876 |                 },
 877 |                 "privateShare": {
 878 |                     "all": True
 879 |                 },
 880 |                 "sponsorsOnly": {
 881 |                     "all": True
 882 |                 },
 883 |                 "unlistedExpired": True,
 884 |                 "videoTrailers": {
 885 |                     "all": True
 886 |                 }
 887 |             },
 888 |             "context": {
 889 |                 "client": self.CLIENT,
 890 |                 "request": {
 891 |                     "returnLogEntry": True,
 892 |                     "internalExperimentFlags": [],
 893 |                     "sessionInfo": {
 894 |                         "token": self.sessionToken
 895 |                     }
 896 |                 },
 897 |                 "user": {
 898 |                     "delegationContext": {
 899 |                         "externalChannelId": self.channelId,
 900 |                         "roleType": {
 901 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 902 |                         }
 903 |                     },
 904 |                     "serializedDelegationContext": ""
 905 |                 },
 906 |                 "clientScreenNonce": ""
 907 |             },
 908 |             "delegationContext": {
 909 |                 "externalChannelId": self.channelId,
 910 |                 "roleType": {
 911 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
 912 |                 }
 913 |             }
 914 |         }
 915 | 
 916 |         self.METADATA_UPDATE_MONETIZATION = {
 917 |             "monetizationSettings": {
 918 |                 "newMonetizeWithAds": True
 919 |             }
 920 |         }
 921 | 
 922 |         self.METADATA_UPDATE_SCHEDULE = {
 923 |             "flowType": "MDE_FLOW_TYPE_UPLOAD",
 924 |             "privacyState": {
 925 |                 "newPrivacy": "PRIVATE"
 926 |             },
 927 |             "scheduledPublishing": {
 928 |                 "set": {
 929 |                     "timeSec": 0,
 930 |                     "privacy": "PUBLIC"
 931 |                 }
 932 |             },
 933 |             "draftState": {
 934 |                 "operation": "MDE_DRAFT_STATE_UPDATE_OPERATION_REMOVE_DRAFT_STATE"
 935 |             }
 936 |         }
 937 | 
 938 |         self.LIST_VIDEOS = {
 939 |             "filter": {
 940 |                 "and": {
 941 |                     "operands": [
 942 |                         {
 943 |                             "channelIdIs": {
 944 |                                 "value": self.channelId
 945 |                             }
 946 |                         }, {
 947 |                             "videoOriginIs": {
 948 |                                 "value": "VIDEO_ORIGIN_UPLOAD"
 949 |                             }
 950 |                         }
 951 |                     ]
 952 |                 }
 953 |             },
 954 |             "order": "VIDEO_ORDER_DISPLAY_TIME_DESC",
 955 |             "pageSize": 30,
 956 |             "mask": {
 957 |                 "channelId": True,
 958 |                 "videoId": True,
 959 |                 "lengthSeconds": True,
 960 |                 "premiere": {
 961 |                     "all": True
 962 |                 },
 963 |                 "status": True,
 964 |                 "thumbnailDetails": {
 965 |                     "all": True
 966 |                 },
 967 |                 "title": True,
 968 |                 "draftStatus": True,
 969 |                 "downloadUrl": True,
 970 |                 "watchUrl": True,
 971 |                 "permissions": {
 972 |                     "all": True
 973 |                 },
 974 |                 "timeCreatedSeconds": True,
 975 |                 "timePublishedSeconds": True,
 976 |                 "origin": True,
 977 |                 "livestream": {
 978 |                     "all": True
 979 |                 },
 980 |                 "privacy": True,
 981 |                 "contentOwnershipModelSettings": {
 982 |                     "all": True
 983 |                 },
 984 |                 "features": {
 985 |                     "all": True
 986 |                 },
 987 |                 "responseStatus": {
 988 |                     "all": True
 989 |                 },
 990 |                 "statusDetails": {
 991 |                     "all": True
 992 |                 },
 993 |                 "description": True,
 994 |                 "metrics": {
 995 |                     "all": True
 996 |                 },
 997 |                 "publicLivestream": {
 998 |                     "all": True
 999 |                 },
1000 |                 "publicPremiere": {
1001 |                     "all": True
1002 |                 },
1003 |                 "titleFormattedString": {
1004 |                     "all": True
1005 |                 },
1006 |                 "descriptionFormattedString": {
1007 |                     "all": True
1008 |                 },
1009 |                 "audienceRestriction": {
1010 |                     "all": True
1011 |                 },
1012 |                 "monetization": {
1013 |                     "all": True
1014 |                 },
1015 |                 "selfCertification": {
1016 |                     "all": True
1017 |                 },
1018 |                 "allRestrictions": {
1019 |                     "all": True
1020 |                 },
1021 |                 "inlineEditProcessingStatus": True,
1022 |                 "videoPrechecks": {
1023 |                     "all": True
1024 |                 },
1025 |                 "videoResolutions": {
1026 |                     "all": True
1027 |                 },
1028 |                 "scheduledPublishingDetails": {
1029 |                     "all": True
1030 |                 },
1031 |                 "visibility": {
1032 |                     "all": True
1033 |                 },
1034 |                 "privateShare": {
1035 |                     "all": True
1036 |                 },
1037 |                 "sponsorsOnly": {
1038 |                     "all": True
1039 |                 },
1040 |                 "unlistedExpired": True,
1041 |                 "videoTrailers": {
1042 |                     "all": True
1043 |                 }
1044 |             },
1045 |             "context": {
1046 |                 "client": self.CLIENT,
1047 |                 "request": {
1048 |                     "returnLogEntry": True,
1049 |                     "internalExperimentFlags": []
1050 |                 },
1051 |                 "user": {
1052 |                     "delegationContext": {
1053 |                         "externalChannelId": self.channelId,
1054 |                         "roleType": {
1055 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
1056 |                         }
1057 |                     },
1058 |                     "serializedDelegationContext": ""
1059 |                 },
1060 |                 "clientScreenNonce": ""
1061 |             }
1062 |         }
1063 | 
1064 |         self.GET_VIDEO = {
1065 |             "context": {
1066 |                 "client": self.CLIENT,
1067 |                 "request": {
1068 |                     "returnLogEntry": True,
1069 |                     "internalExperimentFlags": []
1070 |                 },
1071 |                 "user": {
1072 |                     "delegationContext": {
1073 |                         "externalChannelId": self.channelId,
1074 |                         "roleType": {
1075 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
1076 |                         }
1077 |                     },
1078 |                     "serializedDelegationContext": ""
1079 |                 },
1080 |                 "clientScreenNonce": ""
1081 |             },
1082 |             "failOnError": True,
1083 |             "videoIds": [self.videoId],
1084 |             "mask": {
1085 |                 "downloadUrl": True,
1086 |                 "origin": True,
1087 |                 "premiere": {
1088 |                     "all": True
1089 |                 },
1090 |                 "privacy": True,
1091 |                 "videoId": True,
1092 |                 "status": True,
1093 |                 "permissions": {
1094 |                     "all": True
1095 |                 },
1096 |                 "draftStatus": True,
1097 |                 "statusDetails": {
1098 |                     "all": True
1099 |                 },
1100 |                 "inlineEditProcessingStatus": True,
1101 |                 "selfCertification": {
1102 |                     "all": True
1103 |                 },
1104 |                 "monetization": {
1105 |                     "all": True
1106 |                 },
1107 |                 "allRestrictions": {
1108 |                     "all": True
1109 |                 },
1110 |                 "videoPrechecks": {
1111 |                     "all": True
1112 |                 },
1113 |                 "audienceRestriction": {
1114 |                     "all": True
1115 |                 },
1116 |                 "responseStatus": {
1117 |                     "all": True
1118 |                 },
1119 |                 "features": {
1120 |                     "all": True
1121 |                 },
1122 |                 "videoAdvertiserSpecificAgeGates": {
1123 |                     "all": True
1124 |                 },
1125 |                 "claimDetails": {
1126 |                     "all": True
1127 |                 },
1128 |                 "commentsDisabledInternally": True,
1129 |                 "livestream": {
1130 |                     "all": True
1131 |                 },
1132 |                 "music": {
1133 |                     "all": True
1134 |                 },
1135 |                 "ownedClaimDetails": {
1136 |                     "all": True
1137 |                 },
1138 |                 "timePublishedSeconds": True,
1139 |                 "uncaptionedReason": True,
1140 |                 "remix": {
1141 |                     "all": True
1142 |                 },
1143 |                 "contentOwnershipModelSettings": {
1144 |                     "all": True
1145 |                 },
1146 |                 "channelId": True,
1147 |                 "mfkSettings": {
1148 |                     "all": True
1149 |                 },
1150 |                 "thumbnailEditorState": {
1151 |                     "all": True
1152 |                 },
1153 |                 "thumbnailDetails": {
1154 |                     "all": True
1155 |                 },
1156 |                 "scheduledPublishingDetails": {
1157 |                     "all": True
1158 |                 },
1159 |                 "visibility": {
1160 |                     "all": True
1161 |                 },
1162 |                 "privateShare": {
1163 |                     "all": True
1164 |                 },
1165 |                 "sponsorsOnly": {
1166 |                     "all": True
1167 |                 },
1168 |                 "unlistedExpired": True,
1169 |                 "videoTrailers": {
1170 |                     "all": True
1171 |                 },
1172 |                 "allowComments": True,
1173 |                 "allowEmbed": True,
1174 |                 "allowRatings": True,
1175 |                 "ageRestriction": True,
1176 |                 "audioLanguage": {
1177 |                     "all": True
1178 |                 },
1179 |                 "category": True,
1180 |                 "commentFilter": True,
1181 |                 "crowdsourcingEnabled": True,
1182 |                 "dateRecorded": {
1183 |                     "all": True
1184 |                 },
1185 |                 "defaultCommentSortOrder": True,
1186 |                 "description": True,
1187 |                 "descriptionFormattedString": {
1188 |                     "all": True
1189 |                 },
1190 |                 "gameTitle": {
1191 |                     "all": True
1192 |                 },
1193 |                 "license": True,
1194 |                 "liveChat": {
1195 |                     "all": True
1196 |                 },
1197 |                 "location": {
1198 |                     "all": True
1199 |                 },
1200 |                 "metadataLanguage": {
1201 |                     "all": True
1202 |                 },
1203 |                 "paidProductPlacement": True,
1204 |                 "publishing": {
1205 |                     "all": True
1206 |                 },
1207 |                 "tags": {
1208 |                     "all": True
1209 |                 },
1210 |                 "title": True,
1211 |                 "titleFormattedString": {
1212 |                     "all": True
1213 |                 },
1214 |                 "viewCountIsHidden": True,
1215 |                 "autoChapterSettings": {
1216 |                     "all": True
1217 |                 },
1218 |                 "videoStreamUrl": True,
1219 |                 "videoDurationMs": True,
1220 |                 "videoEditorProject": {
1221 |                     "videoDimensions": {
1222 |                         "all": True
1223 |                     }
1224 |                 },
1225 |                 "originalFilename": True,
1226 |                 "videoResolutions": {
1227 |                     "all": True
1228 |                 }
1229 |             },
1230 |             "criticalRead": False
1231 |         }
1232 | 
1233 |         self.CREATE_PLAYLIST = {
1234 |             "title": "",
1235 |             "privacyStatus": "",
1236 |             "context": {
1237 |                 "client": self.CLIENT,
1238 |                 "request": {
1239 |                     "returnLogEntry": True,
1240 |                     "internalExperimentFlags": [],
1241 |                     "sessionInfo": {
1242 |                         "token": self.sessionToken
1243 |                     }
1244 |                 },
1245 |                 "user": {
1246 |                     "delegationContext": {
1247 |                         "externalChannelId": self.channelId,
1248 |                         "roleType": {
1249 |                             "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
1250 |                         }
1251 |                     },
1252 |                     "serializedDelegationContext": ""
1253 |                 },
1254 |                 "clientScreenNonce": ""
1255 |             },
1256 |             "delegationContext": {
1257 |                 "externalChannelId": self.channelId,
1258 |                 "roleType": {
1259 |                     "channelRoleType": "CREATOR_CHANNEL_ROLE_TYPE_OWNER"
1260 |                 }
1261 |             }
1262 |         }
1263 | 
1264 |         self.METADATA_UPDATE_PLAYLIST = {
1265 |             "addToPlaylist": {
1266 |                 "addToPlaylistIds": [],
1267 |                 "deleteFromPlaylistIds": []
1268 |             }
1269 |         }
1270 | 
1271 |         self.METADATA_UPDATE_TITLE = {
1272 |             "title": {
1273 |                 "newTitle": "",
1274 |                 "shouldSegment": True
1275 |             }
1276 |         }
1277 | 
1278 |         self.METADATA_UPDATE_DESCRIPTION = {
1279 |             "description": {
1280 |                 "newDescription": "",
1281 |                 "shouldSegment": True
1282 |             }
1283 |         }
1284 | 
1285 |         self.METADATA_UPDATE_TAGS = {
1286 |             "tags": {
1287 |                 "newTags": [],
1288 |                 "shouldSegment": True
1289 |             }
1290 |         }
1291 | 
1292 |         self.METADATA_UPDATE_CATEGORY = {
1293 |             "category": {
1294 |                 "newCategoryId": 0
1295 |             }
1296 |         }
1297 | 
1298 |         self.METADATA_UPDATE_COMMENTS = {
1299 |             "commentOptions": {
1300 |                 "newAllowComments": True,
1301 |                 "newAllowCommentsMode": "ALL_COMMENTS",
1302 |                 "newCanViewRatings": True,
1303 |                 "newDefaultSortOrder": "MDE_COMMENT_SORT_ORDER_TOP"
1304 |             }
1305 |         }
1306 | 
1307 |         self.METADATA_UPDATE_PRIVACY = {
1308 |             "privacyState": {"newPrivacy": "PUBLIC"}
1309 |         }
1310 | 
1311 |         self.METADATA_UPDATE_THUMB = {
1312 |             "videoStill": {"operation": "UPLOAD_CUSTOM_THUMBNAIL", "image": {
1313 |                 "dataUri": ""
1314 |             }}
1315 |         }
1316 |
1317 |

Class variables

1318 |
1319 |
var CLIENT
1320 |
1321 |
1322 |
1323 |
var botguardResponse
1324 |
1325 |
1326 |
1327 |
var channelId
1328 |
1329 |
1330 |
1331 |
var delegatedSessionId
1332 |
1333 |
1334 |
1335 |
var sessionToken
1336 |
1337 |
1338 |
1339 |
var videoId
1340 |
1341 |
1342 |
1343 |
1344 |

Methods

1345 |
1346 |
1347 | def setVideoId(self, videoId) 1348 |
1349 |
1350 |
1351 |
1352 | 1353 | Expand source code 1354 | 1355 |
def setVideoId(self, videoId):
1356 |     self.videoId = videoId
1357 |     self._()
1358 |
1359 |
1360 |
1361 |
1362 |
1363 |
1364 |
1365 | 1394 |
1395 | 1398 | 1399 | --------------------------------------------------------------------------------