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
|
2013-09-17 13:03:45 +02:00
|
|
|
import stat
|
2013-09-13 21:34:41 +02:00
|
|
|
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':
|
2013-09-17 10:38:29 +02:00
|
|
|
settings_base_dir = os.getenv('LOCALAPPDATA') + os.sep + 'radiorec'
|
2013-09-13 21:34:41 +02:00
|
|
|
settings_base_dir += os.sep
|
|
|
|
config = configparser.ConfigParser()
|
|
|
|
config.read(settings_base_dir + 'settings.ini')
|
|
|
|
return dict(config.items())
|
|
|
|
|
2013-09-17 13:03:45 +02:00
|
|
|
def record_worker(stoprec, streamurl, target_dir, args):
|
2013-09-13 21:34:41 +02:00
|
|
|
conn = urllib.request.urlopen(streamurl)
|
2013-09-17 11:23:22 +02:00
|
|
|
cur_dt_string = datetime.datetime.now().strftime('%Y-%m-%dT%H_%M_%S')
|
2013-09-17 13:03:45 +02:00
|
|
|
filename = target_dir + os.sep + cur_dt_string + "_" + args.station
|
|
|
|
if args.name:
|
|
|
|
filename += '_' + args.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'
|
2013-09-16 16:28:47 +02:00
|
|
|
elif(content_type == 'audio/x-mpegurl'):
|
|
|
|
print('Sorry, M3U playlists are currently not supported')
|
|
|
|
sys.exit()
|
2013-09-16 15:49:35 +02:00
|
|
|
else:
|
2013-09-16 16:28:47 +02:00
|
|
|
print('Unknown content type "' + content_type + '". Assuming mp3.')
|
2013-09-16 15:49:35 +02:00
|
|
|
filename += 'mp3'
|
2013-09-17 13:03:45 +02:00
|
|
|
|
2013-09-17 10:09:38 +02:00
|
|
|
with open(filename, "wb") as target:
|
2013-09-17 13:03:45 +02:00
|
|
|
if args.public:
|
|
|
|
verboseprint('Apply public write permissions (Linux only)')
|
|
|
|
os.chmod(filename, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP |
|
|
|
|
stat.S_IROTH | stat.S_IWOTH)
|
2013-09-17 13:44:57 +02:00
|
|
|
verboseprint('Recording ' + args.station + '...')
|
2013-09-17 10:09:38 +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 = ''
|
2013-09-17 10:09:38 +02:00
|
|
|
global verboseprint
|
|
|
|
verboseprint = print if args.verbose else lambda *a, **k: None
|
|
|
|
|
2013-09-13 21:34:41 +02:00
|
|
|
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)
|
2013-09-17 10:09:38 +02:00
|
|
|
sys.exit()
|
|
|
|
if streamurl.endswith('.m3u'):
|
2013-09-17 13:44:57 +02:00
|
|
|
verboseprint('Seems to be an M3U playlist. Trying to parse...')
|
2013-09-17 10:09:38 +02:00
|
|
|
with urllib.request.urlopen(streamurl) as remotefile:
|
|
|
|
for line in remotefile:
|
|
|
|
if not line.decode('utf-8').startswith('#'):
|
|
|
|
tmpstr = line.decode('utf-8')
|
|
|
|
break
|
|
|
|
streamurl = tmpstr
|
|
|
|
verboseprint('stream url: ' + streamurl)
|
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
|
|
|
recthread = threading.Thread(target = record_worker,
|
2013-09-17 13:03:45 +02:00
|
|
|
args = (stoprec, streamurl, target_dir, args), 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()
|
|
|
|
for key in settings['STATIONS']:
|
|
|
|
print(key)
|
|
|
|
|
|
|
|
def main():
|
2013-09-17 10:38:29 +02:00
|
|
|
parser = argparse.ArgumentParser(description='This program records internet radio streams')
|
2013-09-16 15:43:29 +02:00
|
|
|
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')
|
2013-09-17 13:03:45 +02:00
|
|
|
parser_record.add_argument('-p', '--public', action='store_true', help="Public write permissions (Linux only)")
|
2013-09-17 10:09:38 +02:00
|
|
|
parser_record.add_argument('-v', '--verbose', action='store_true', help="Verbose output")
|
2013-09-16 15:43:29 +02:00
|
|
|
parser_record.set_defaults(func=record)
|
|
|
|
parser_list = subparsers.add_parser('list', help='List all known stations')
|
|
|
|
parser_list.set_defaults(func=list)
|
2013-09-17 13:03:45 +02:00
|
|
|
|
2013-09-16 15:43:29 +02:00
|
|
|
args = parser.parse_args()
|
|
|
|
args.func(args)
|
|
|
|
|
2013-09-11 16:10:16 +02:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|