Last active
December 20, 2021 21:12
-
-
Save scotchi/fd3198a2b13fd41db4fe2502670229bd to your computer and use it in GitHub Desktop.
Tool to read the 10 oldest, downloaded episodes of all podcasts from Podcasts.app and copy them to a specified folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import os | |
import sys | |
import glob | |
import sqlite3 | |
import datetime | |
import urllib.parse | |
import re | |
import shutil | |
MAX_EPISODES_FROM_ONE_PODCAST = 10 | |
def sanitize_filename(name): | |
return re.sub("[^\w\-_\. ]", "", name) | |
if len(sys.argv) < 2: | |
print("You must specify a destination for the files.") | |
exit(1) | |
destination = sys.argv[1] | |
if not os.path.isdir(destination): | |
print("Destination does not exist.") | |
exit(2) | |
apple_epoch = datetime.datetime.strptime("01-01-2001", "%m-%d-%Y") | |
database = glob.glob( | |
os.environ.get("HOME") + | |
"/Library/Group Containers/*.groups.com.apple.podcasts/Documents/" + | |
"MTLibrary.sqlite")[0] | |
connection = sqlite3.connect(database) | |
connection.row_factory = sqlite3.Row | |
cursor = connection.cursor() | |
subquery = ("(select Z_PK from ZMTEPISODE " + | |
"where ZPODCAST = podcast_id and ZASSETURL not null " + | |
"order by ZPUBDATE limit {})".format(MAX_EPISODES_FROM_ONE_PODCAST)) | |
for row in cursor.execute( | |
"select ZMTEPISODE.ZPODCAST as podcast_id, " + | |
"ZMTPODCAST.ZTITLE as podcast_title, " + | |
"ZMTEPISODE.ZTITLE as episode_title, " + | |
"ZMTEPISODE.ZPUBDATE, ZMTEPISODE.ZASSETURL " + | |
"from ZMTPODCAST, ZMTEPISODE " + | |
"where ZMTEPISODE.ZPODCAST = ZMTPODCAST.Z_PK " + | |
"and ZMTEPISODE.Z_PK in " + subquery + | |
"order by podcast_title, ZPUBDATE"): | |
source = urllib.parse.unquote(urllib.parse.urlparse(row["ZASSETURL"]).path) | |
date = (apple_epoch + | |
datetime.timedelta(seconds=row["ZPUBDATE"])).strftime("%Y-%m-%d") | |
podcast_title = row["podcast_title"] | |
episode_title = row["episode_title"] | |
target_dir = destination + '/' + sanitize_filename(podcast_title) | |
target = u"{}/{} - {}.mp3".format(target_dir, date, sanitize_filename(episode_title)) | |
if not os.path.isfile(target): | |
if not os.path.isdir(target_dir): | |
os.mkdir(target_dir) | |
print(u"Copying: " + target) | |
shutil.copyfile(source, target) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment