Skip to content

Instantly share code, notes, and snippets.

@asakasinsky
Last active December 15, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asakasinsky/5317811 to your computer and use it in GitHub Desktop.
Save asakasinsky/5317811 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
import os
import argparse
import urllib2
from mutagen.id3 import ID3, TIT2, TALB, TPE2, TCOM, TCON, TRCK, APIC
class get_my_radiot(object):
def __init__(self, path, frm=0, to=299, overwrite=False):
""" Initialize radiot dowloader"""
self.path = path
self.overwrite = overwrite
self.cover_name = False
self.frm = frm
self.to = to+1
self.cover_url = 'http://cdn.webstatics.net/podcast/podcastimage_133409.gif'
def doit_man(self):
cover_exists = self.check_cover_image_existence(self.path)
if not cover_exists:
self.download_image(self.path, self.cover_url)
for i in range(self.frm, self.to):
url = 'http://cdn.radio-t.com/rt_podcast%d.mp3' % (i,)
file_name = self.path+'/'+url.split('/')[-1]
try:
with open(file_name):
if self.overwrite:
self.download_file(url, file_name)
self.write_tags(file_name, i)
except IOError:
self.download_file(url, file_name)
self.write_tags(file_name, i)
def download_file(self, url, file_name):
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
def write_tags(self, filename, i):
media = ID3(filename)
# title
media["TIT2"] = TIT2(encoding=3, text=u'Радио-Т %d ' % (i,))
# album
media["TALB"] = TALB(encoding=3, text=u'Радио-Т')
# album artists (perfomer)
media["TPE2"] = TPE2(encoding=3, text=u'Various Artists')
# composer
media["TCOM"] = TCOM(encoding=3, text=u'Umputun')
# genre
media["TCON"] = TCON(encoding=3, text=u'Podcast')
# tracknumber
media["TRCK"] = TRCK(encoding=3, text=u'%d' % (i+1,))
# cover
media.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/jpeg', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=open(self.cover_name).read()
)
)
try:
media.save()
except:
raise IOError('ExporterError: cannot write tags')
def check_cover_image_existence(self, dirname):
""" Check if cover image already exists in the specified directory """
possible_covers = ["cover.png", "cover.jpg", "cover.gif", "cover.tiff", "cover.svg"]
for cover_name in possible_covers:
if os.path.exists(os.path.join(dirname, cover_name)):
self.cover_name = os.path.join(dirname, cover_name)
return True
return False
def download_image(self, dirname, image_url):
""" Check if overwrite is enabled. Check if album cover already exists
Call method to download album cover art image to specified directory"""
# Set name of image file based on extension from image URL
if ".png" in image_url.lower():
self.cover_name = "cover.png"
elif ".jpg" in image_url.lower():
self.cover_name = "cover.jpg"
elif ".jpeg" in image_url.lower():
self.cover_name = "cover.jpg"
elif ".gif" in image_url.lower():
self.cover_name = "cover.gif"
elif ".tif" in image_url.lower():
self.cover_name = "cover.tiff"
elif ".tiff" in image_url.lower():
self.cover_name = "cover.tiff"
elif ".svg" in image_url.lower():
self.cover_name = "cover.svg"
else:
return
# Does cover.(png|jpg|gif|tiff|svg) already exist?
if os.path.exists(os.path.join(dirname, self.cover_name)):
# If overwrite is set to True, then go ahead and re-download album cover
if self.overwrite:
self.do_download(dirname, image_url, self.cover_name)
else:
print (u'Cover ({covername}) already exists in {dir_name}'.format(covername=self.cover_name, dir_name=dirname))
else:
# If cover doesn't exist, go ahead and download
self.do_download(dirname, image_url, self.cover_name)
def do_download(self, dirname, image_url, cover_name):
""" Download album cover art and save as cover.(png|jpg|gif|tiff|svg)"""
image_data = urllib2.urlopen(image_url).read()
f = open(os.path.join(dirname, cover_name), 'w')
f.write(image_data)
f.close()
self.cover_name = os.path.join(dirname, cover_name)
def main(path, frm=0, to=299, overwrite=False):
radiot = get_my_radiot(path, frm, to, overwrite)
radiot.doit_man()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("path", type=str, help="path to downloads")
parser.add_argument("--frm", type=int, default=0, help="i will download from")
parser.add_argument("--to", type=int, default=299, help="i will download to")
parser.add_argument("--overwrite", type=bool, default=False, help="Can I overwrite all?")
args = parser.parse_args()
if os.path.exists(args.path):
main(args.path, args.frm, args.to, args.overwrite)
else:
print ('Path to downloads is not exists')
@asakasinsky
Copy link
Author

Script for downloading all «Radio-T» podcasts

Features:

  1. Specify a range of downloads (from 12 to 102 podcast numbers, for example)
  2. ID3 tag fix (iTunes loved it)
  3. Set current version of cover art

Dependencies:
mutagen

pip install mutagen

Usage:

./radiot.py [--frm int] [--to int] <Path to downloads>
./radiot.py --frm 0 --to 199 ~/Downloads/radiot
or
./radiot.py  ~/Downloads/radiot

Special thanks:

  • to Umputun and Bobuk for great podcast
  • to Joel for the StackOverflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment