yt-unlist-saver/yt-unlist-saver.py

92 lines
2.5 KiB
Python

#!/usr/bin/env python3
from youtube_api import YouTubeAPI
import sys, os
import youtube_dl
# Read YouTube API Key.
def getYouTubeAPIKey():
return open('youtube.key', 'r').read()
def getTitle(info):
return info[0]
def getUploadTime(info):
return info[1]
def getYear(info):
return int(getUploadTime(info)[:4])
def getChannel(info):
return info[2]
def getChannelId(info):
return info[3]
def getDescription(info):
return info[4]
def getTags(info):
if isinstance(info[5], list):
return '[' + ','.join(info[5]) + ']'
return info[5]
def getPrivacy(info):
return info[6]
def getId(info):
return info[7]
# Print out information about a video.
def printVideoInfo(info):
title, date, channel, channelId, description, tags, privacy = info
print('Title: ' + title)
print('Date: ' + date)
print('Channel: {} ({})'.format(channel, channelId) )
print('Description: ' + description)
print('Tags: ', tags)
print('Privacy: ' + privacy)
playlistId = sys.argv[1]
# Create download directory
downloadDir = 'playlists'
playlistDir = downloadDir+'/'+playlistId
if not os.path.exists(downloadDir):
os.mkdir(downloadDir)
if not os.path.exists(playlistDir):
os.mkdir(playlistDir)
api = YouTubeAPI(getYouTubeAPIKey())
videos = api.getPlaylistVideos(playlistId)
videoInfo = [api.getVideoInfo(video['snippet']['resourceId']['videoId']) for video in videos]
filteredVideos = [video for video in videoInfo if getPrivacy(video) == 'unlisted' and getYear(video) <= 2017]
ydl_opts = {
'outtmpl': '{}/%(uploader)s-%(title)s-%(id)s.%(ext)s'.format(playlistDir)
}
for v in filteredVideos:
# Save metadata to file
descriptionFile = '{}/{}-{}-{}.txt'.format(playlistDir,
getChannel(v),
getTitle(v).replace('/', ''),
getId(v))
if not os.path.exists(descriptionFile):
description = open(descriptionFile, 'w')
description.write('Title: ' + getTitle(v) + '\n')
description.write('Uploaded: ' + getUploadTime(v) + '\n')
description.write('Channel: ' + getChannel(v) + '\n')
description.write('Channel ID: ' + getChannelId(v) + '\n')
description.write('Description: ' + getDescription(v) + '\n')
description.write('Tags: ' + getTags(v) + '\n')
description.write('Video ID: ' + getId(v) + '\n')
description.close()
videoURL = 'https://www.youtube.com/watch?v='+getId(v)
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([videoURL])