Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- # -*- coding: utf-8 -*-
- '''
- Create a new recorded entry for the recordedid passed on the command line.
- Use: add_recorded_program.py --help to get started.
- Install as: add_recorded_program.py; chmod a+rx add_recorded_program.py
- '''
- import argparse
- import json
- import logging
- import sys
- try:
- from MythTV.services_api import (send as api, utilities as util)
- except ImportError:
- sys.exit("Missing python bindings?")
- # pylint: disable=consider-using-f-string
- def process_command_line():
- '''All command line processing is done here.'''
- parser = argparse.ArgumentParser(description='Add Guide data',
- epilog='Default values are in ()s')
- mandatory = parser.add_argument_group('required arguments')
- parser.add_argument('--digest', type=str, metavar='<user:pass>',
- help='digest username:password')
- parser.add_argument('--debug', action='store_true',
- help='turn on debug messages (%(default)s)')
- parser.add_argument('--jdump', action='store_true',
- help='turn on json debug messages (%(default)s)')
- mandatory.add_argument('--host', type=str, required=True,
- metavar='<hostname>', help='backend hostname')
- mandatory.add_argument('--recordedid', type=int, required=True,
- metavar='<recid>',
- help='recorded id for the program of interest')
- parser.add_argument('--port', type=int, default=6544, metavar='<port>',
- help='port number of the Services API (%(default)s)')
- parser.add_argument('--quiet', action='store_true',
- help='suppress progress messages (%(default)s)')
- parser.add_argument('--starttime', type=str, metavar='<start>',
- help='format: yyyy-mm-ddThh:mm:ssZ')
- parser.add_argument('--title', type=str, metavar='<title>',
- help='Replacement title')
- parser.add_argument('--version', action='version', version='%(prog)s 0.1')
- parser.add_argument('--wrmi', action='store_true',
- help='allow data to be changed (%(default)s)')
- return vars(parser.parse_args())
- def setup(backend, opts):
- '''
- Make sure the backend is up (GetHostName) and then set the backend's UTC
- offset for other methods to use.
- '''
- try:
- backend.send(endpoint='Myth/GetHostName', opts=opts)
- int(util.get_utc_offset(backend=backend, opts=opts))
- except ValueError:
- sys.exit('\nExit, non integer response from get_utc_offset.')
- except RuntimeError as error:
- sys.exit('\nExit on fatal API error: "{}"'.format(error))
- def get_recorded_data(backend, args, opts):
- ''' Find existing recordedid entry. '''
- endpoint = 'Dvr/GetRecorded'
- rest = 'RecordedId={}'.format(args['recordedid'])
- try:
- resp_dict = backend.send(endpoint=endpoint, rest=rest, opts=opts)
- except RuntimeError as error:
- sys.exit('\nExit, GetRecorded: Fatal error; "{}"'.format(error))
- if not resp_dict['Program']['Title']:
- sys.exit('\nExit, No recorded program matched RecordedId: {}.\n'
- .format(args['recordedid']))
- if args['jdump']:
- print(json.dumps(resp_dict, sort_keys=True, indent=4,
- separators=(',', ': ')))
- return resp_dict
- def update_recorded_data(recorded_data, args):
- ''' We're here to make any changes in the Recorded Data. '''
- try:
- # On 33-Pre, port 6544, the following results in the chanid 0
- # error message, ChanId must be a string
- # recorded_data['Program']['Channel']['ChanId'] = \
- # int(recorded_data['Program']['Channel']['ChanId'])
- recorded_data['Program']['StartTime'] = args['starttime']
- recorded_data['Program']['Recording']['StartTs'] = args['starttime']
- if args['title']:
- recorded_data['Program']['Title'] = args['title']
- except KeyError:
- print('++++++++ KeyError THIS SHOULD PRINT A BETTER ERROR!!!')
- return False
- return True
- def add_record_schedule(backend, recorded_data, args, opts):
- ''' Use the changed data to create a new recorded entry. '''
- endpoint = 'Dvr/AddRecordedProgram'
- params_not_sent = ('Cast', 'Artwork')
- for param in params_not_sent:
- try:
- del recorded_data['Program'][param]
- except KeyError:
- pass
- # This isn't honored by jsondata.
- opts['wrmi'] = args['wrmi']
- if args['jdump']:
- print(json.dumps(recorded_data, sort_keys=True, indent=4,
- separators=(',', ': ')))
- try:
- resp_dict = backend.send(endpoint=endpoint, jsondata=recorded_data,
- opts=opts)
- except RuntimeWarning as error:
- sys.exit('Exit, Unable to add rule: {}. Warning was: {}.'
- .format(recorded_data['Program']['Title'], error))
- except RuntimeError as error:
- sys.exit('\nExit, Fatal API Error response: {}\n'.format(error))
- opts['wrmi'] = False
- if isinstance(resp_dict, dict) and \
- isinstance(resp_dict['int'], (int, str)):
- recording_rule = int(resp_dict['int'])
- if recording_rule < 4294967295:
- vprint('\nAdded: "{}" (RecordId {}).'
- .format(recorded_data['Program']['Title'],
- recording_rule), args)
- else:
- recording_rule = -1
- vprint('Backend failed to add: "{}" (RecordId {}).'
- .format(recorded_data['Program']['Title'],
- recording_rule), args)
- else:
- vprint('Expected a "int: int" dictionary response, but got {}'
- .format(resp_dict), args)
- def vprint(message, args):
- '''
- Verbose Print: print recording rule information unless --quiet
- was used. Not fully implemented, as there are still lots of
- print()s here.
- The intention is that if run out of some other program, this
- will can remain quiet. sys.exit()s will return 1 for failures.
- This may get expanded to put messages in a log...
- '''
- if not args['quiet']:
- print(message)
- def main():
- '''
- The primary job of main is to get the arguments from the command line,
- setup logging (and possibly) handle the digest user/password then:
- '''
- args = process_command_line()
- opts = {}
- logging.basicConfig(level=logging.DEBUG if args['debug'] else logging.INFO)
- logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING)
- logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING)
- try:
- opts['user'], opts['pass'] = args['digest'].split(':', 1)
- except (AttributeError, ValueError):
- pass
- backend = api.Send(host=args['host'], port=args['port'])
- setup(backend, opts)
- recorded_data = get_recorded_data(backend, args, opts)
- if not recorded_data['Program']['Title']:
- sys.exit('\nExit, no recording for RecordedId: {}'.
- format(args['recordedid']))
- if update_recorded_data(recorded_data, args):
- add_record_schedule(backend, recorded_data, args, opts)
- else:
- print('++++++++ update_recorded_data failed NEEDS TO BE A BETTER MSG')
- if __name__ == '__main__':
- main()
- # vim: set expandtab tabstop=4 shiftwidth=4 smartindent noai colorcolumn=80:
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement