radiorec/radiorec.py

102 lines
3.4 KiB
Python
Raw Normal View History

2013-09-11 10:46:47 +02:00
#!/usr/bin/env python3
2013-09-11 16:10:16 +02:00
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
2013-09-11 10:46:47 +02:00
2013-09-11 11:06:13 +02:00
"""
This script records internet radio streams. It can be used in conjunction
with "at" or "crontab".
"""
2013-09-11 10:46:47 +02:00
import argparse
import configparser
2013-09-16 13:51:20 +02:00
import datetime
2013-09-13 21:34:41 +02:00
import os
import sys
2013-09-13 12:54:59 +02:00
import threading
2013-09-11 10:46:47 +02:00
import urllib.request
2013-09-13 21:34:41 +02:00
def check_duration(value):
2013-09-13 12:54:59 +02:00
try:
value = int(value)
except ValueError:
raise argparse.ArgumentTypeError('Duration must be a positive integer.')
if value < 1:
raise argparse.ArgumentTypeError('Duration must be a positive integer.')
else:
return value
2013-09-13 21:34:41 +02:00
def read_settings():
settings_base_dir = ''
if sys.platform == 'linux':
settings_base_dir = os.getenv('HOME') + os.sep + '.config' + os.sep + 'radiorec'
elif sys.platform == 'win32':
settings_base_dir = os.getenv('APPDATA') + os.sep + 'radiorec'
settings_base_dir += os.sep
config = configparser.ConfigParser()
config.read(settings_base_dir + 'settings.ini')
return dict(config.items())
2013-09-16 15:43:29 +02:00
def record_worker(stoprec, streamurl, target_dir, name=None):
2013-09-13 21:34:41 +02:00
conn = urllib.request.urlopen(streamurl)
2013-09-16 13:51:20 +02:00
filename = target_dir + os.sep + datetime.datetime.now().isoformat()
if name:
filename += '_' + name
2013-09-16 15:49:35 +02:00
content_type = conn.getheader('Content-Type')
if(content_type == 'audio/mpeg'):
2013-09-16 13:51:20 +02:00
filename += '.mp3'
2013-09-16 15:49:35 +02:00
elif(content_type == 'application/ogg' or content_type == 'audio/ogg'):
filename += '.ogg'
else:
print('Unknown content type. Assuming mp3.')
filename += 'mp3'
2013-09-16 13:51:20 +02:00
target = open(filename, "wb")
2013-09-13 13:51:01 +02:00
while(not stoprec.is_set() and not conn.closed):
target.write(conn.read(1024))
2013-09-13 12:54:59 +02:00
2013-09-16 15:43:29 +02:00
def record(args):
2013-09-13 21:34:41 +02:00
settings = read_settings()
streamurl = ''
try:
2013-09-13 21:55:38 +02:00
streamurl = settings['STATIONS'][args.station]
2013-09-13 21:34:41 +02:00
except KeyError:
print('Unkown station name: ' + args.station)
return
2013-09-13 21:55:38 +02:00
target_dir = os.path.expandvars(settings['GLOBAL']['target_dir'])
2013-09-13 12:54:59 +02:00
stoprec = threading.Event()
2013-09-13 21:34:41 +02:00
2013-09-16 15:43:29 +02:00
print('Recording ' + args.station + '')
recthread = threading.Thread(target = record_worker,
2013-09-16 13:51:20 +02:00
args = (stoprec, streamurl, target_dir, args.name), daemon = True)
2013-09-13 12:54:59 +02:00
recthread.start()
recthread.join(args.duration * 60)
2013-09-13 21:34:41 +02:00
2013-09-13 12:54:59 +02:00
if(recthread.is_alive):
stoprec.set()
2013-09-11 16:10:16 +02:00
2013-09-16 15:43:29 +02:00
def list(args):
settings = read_settings()
print('Known stations:')
for key in settings['STATIONS']:
print(key)
def main():
parser = argparse.ArgumentParser(prog='radiorec', description='This program records internet radio streams')
subparsers = parser.add_subparsers(help='sub-command help')
parser_record = subparsers.add_parser('record', help='Record a station')
parser_record.add_argument('station', type=str, help='Name of the radio station '
'(see config file for a list)')
parser_record.add_argument('duration', type=check_duration,
help='Recording time in minutes')
parser_record.add_argument('name', nargs='?', type=str,
help='A name for the recording')
parser_record.set_defaults(func=record)
parser_list = subparsers.add_parser('list', help='List all known stations')
parser_list.set_defaults(func=list)
#parser_list.add_argument('-l', '--list', action='store_true',
# help='Get a list of all known radio stations')
args = parser.parse_args()
args.func(args)
2013-09-11 16:10:16 +02:00
if __name__ == '__main__':
main()