45 lines
1.5 KiB
Python
45 lines
1.5 KiB
Python
import requests
|
|
import httplib2
|
|
from googleapiclient.discovery import build
|
|
from googleapiclient.http import MediaFileUpload
|
|
from oauth2client.client import AccessTokenCredentials
|
|
|
|
from settings import *
|
|
from downloader import resumable_upload
|
|
|
|
|
|
def get_auth_code():
|
|
""" Get access token for connect to youtube api """
|
|
oauth_url = 'https://accounts.google.com/o/oauth2/token'
|
|
data = {
|
|
"refresh_token": YOUTUBE_REFRESH_TOKEN,
|
|
"client_id": YOUTUBE_CLIENT_ID,
|
|
"client_secret": YOUTUBE_CLIENT_SECRET,
|
|
"grant_type": "refresh_token",
|
|
}
|
|
headers = {
|
|
'Content-Type': 'application/x-www-form-urlencoded',
|
|
'Accept': 'application/json'
|
|
}
|
|
|
|
response = requests.post(oauth_url, data=data, headers=headers)
|
|
return response.json()['access_token']
|
|
|
|
|
|
def get_authenticated_service():
|
|
""" Create youtube oauth2 connection """
|
|
credentials = AccessTokenCredentials(
|
|
access_token=get_auth_code(), user_agent='my-awesome-project/1.0'
|
|
)
|
|
return build('youtube', 'v3', http=credentials.authorize(httplib2.Http()))
|
|
|
|
|
|
def initialize_upload(youtube, metadata: dict, video_path: str):
|
|
""" Create youtube upload data """
|
|
# create video meta data
|
|
# Call the API's videos.insert method to create and upload the video
|
|
insert_request = youtube.videos().insert(
|
|
part=",".join(metadata.keys()), body=metadata,
|
|
media_body=MediaFileUpload(video_path, chunksize=-1, resumable=True))
|
|
# wait for file uploading
|
|
return resumable_upload(insert_request)
|