radiorec/radiorec.py

143 lines
5.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
"""
2013-09-18 15:19:04 +02:00
radiorec.py Recording internet radio streams
Copyright (C) 2013 Martin Brodbeck <martin@brodbeck-online.de>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
2013-09-11 11:06:13 +02:00
"""
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 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':
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()
2013-09-18 15:20:47 +02:00
try:
config.read_file(open(settings_base_dir + 'settings.ini'))
except FileNotFoundError as err:
print(str(err))
print('Please copy/create the settings file to/in the appropriate location.')
sys.exit()
2013-09-13 21:34:41 +02:00
return dict(config.items())
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')
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'
with open(filename, "wb") as target:
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 + '...')
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 = ''
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)
sys.exit()
if streamurl.endswith('.m3u'):
2013-09-17 13:44:57 +02:00
verboseprint('Seems to be an M3U playlist. Trying to parse...')
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,
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()
2013-09-18 15:19:04 +02:00
for key in sorted(settings['STATIONS']):
2013-09-16 15:43:29 +02:00
print(key)
def main():
2013-09-18 15:19:04 +02:00
parser = argparse.ArgumentParser(description='This program records internet radio streams. '
'It is free software and comes with ABSOLUTELY NO WARRANTY.')
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 '
2013-09-24 15:46:00 +02:00
'(see `radiorec.py list`)')
2013-09-16 15:43:29 +02:00
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.add_argument('-p', '--public', action='store_true', help="Public write permissions (Linux only)")
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-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()