How to delete all recording rules

Have a MythTV related problem? Ask for help from other MythTV users here.

Moderator: Forum Moderators

Post Reply
bklein
Junior
Posts: 24
Joined: Sat Sep 19, 2020 6:09 am
Australia

How to delete all recording rules

Post by bklein » Sat Sep 19, 2020 2:01 pm

I have been using MythTV since 2008 and have hundreds of recording rules. I often have upcoming recordings that I am not interested in. I would like to delete all my recording rules and start with a clean slate. How can I mass delete all my recording rules without having to individually delete each one?

User avatar
heyted
Senior
Posts: 157
Joined: Sun Jun 08, 2014 2:14 am
Location: South Florida
Contact:
United States of America

Re: How to delete all recording rules

Post by heyted » Sun Sep 20, 2020 11:49 pm

Maybe not the option you're looking for, but you could do a fresh install of MythTV v31 without keeping the database. It is possible to do a fresh install of MythTV and keep the existing recordings.
Ted | My blog

bklein
Junior
Posts: 24
Joined: Sat Sep 19, 2020 6:09 am
Australia

Re: How to delete all recording rules

Post by bklein » Tue Sep 22, 2020 9:26 am

Thanks. How do you drop the database without losing the names, details and file locations of the existing recordings?

User avatar
bill6502
Developer
Posts: 1722
Joined: Fri Feb 07, 2014 5:28 pm
United States of America

Re: How to delete all recording rules

Post by bill6502 » Tue Sep 22, 2020 2:27 pm

Here's a tool, based on other ones I use. Read the comments at the top
for instructions. It only deletes rules using the Services API. It's written
and tested for Python 3, but probably works on version 2. Change the
1st line accordingly.

Code: Select all

#!/usr/bin/python3
# -*- coding: utf-8 -*-

'''
Delete ALL or selected recording rules

Try: delete_selected_recording_rules.py --help

For --title, regular expressions work, e.g. --title "News.*6" would
get any rule that had  News in it, e.g "XYZ News on 6" or "News At 6"
etc. Just "News" would get all rules with "News" in the title.

--wrmi is key! Run this any way you like without --wrmi and no rules
will be deleted, only what COULD have been removed will be printed.
'''

from __future__ import print_function
import argparse
import logging
import re
import sys
from MythTV.services_api import send as api

try:
    INPUT = raw_input
except NameError:
    INPUT = input


def process_switches():
    ''' Handle the command line...'''
    parser = argparse.ArgumentParser(description='Delete Recording Rules',
                                     epilog='Default values in ()s. "Default '
                                            '(Template)" isn\'t removed.')

    parser.add_argument('--chanid', type=int, required=False,
                        metavar='<chanid>',
                        help='filter on MythTV chanid (%(default)s)')

    parser.add_argument('--debug', action='store_true',
                        help='turn on debug messages (%(default)s)')

    parser.add_argument('--digest', type=str, metavar='<user:pass>',
                        help='digest username:password (%(default)s)')

    parser.add_argument('--host', type=str, required=False,
                        default='localhost', metavar='<hostname>',
                        help='backend hostname (%(default)s)')

    parser.add_argument('--port', type=int, default=6544, metavar='<port>',
                        help='port number of the Services API (%(default)s)')

    parser.add_argument('--title', type=str, default='', required=False,
                        metavar='<title>',
                        help='filter by RE case insensitive title (ALL Rules)')

    parser.add_argument('--version', action='version', version='%(prog)s 0.1')

    parser.add_argument('--wrmi', action='store_true',
                        help='REALLY delete selected rules (%(default)s)')

    return parser.parse_args()


def prompt_for_string(answer):
    '''
    Prompt for a string and match it against the input.

    Input:  answer - the text to prompt with

    Return: None, or just exit
    '''

    good_prompt = 'Type {} to proceed/Control-D to abort: '.format(answer)

    while True:
        try:
            response = INPUT(good_prompt)
        except (EOFError, KeyboardInterrupt):
            sys.exit('\n\nControl-D/Control-C pressed, aborting')

        if response == answer:
            break

    print()


def main():
    '''
    Get the list of recording rules, optionally filter only chanid/title
    rules. Give the user a chance to abort. If ready, delete them.

    Uses the --wrmi switch as an additional precaution. If not set, then
    just print what would have been done.
    '''

    args = process_switches()

    opts = {'noetag': False, 'nogzip': False, 'usexml': False, 'timeout': 2,
            'wsdl': False, 'wrmi': args.wrmi}

    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)

    if args.title:
        title_reg_exp = re.compile(args.title, flags=re.IGNORECASE)

    try:
        opts['user'], opts['pass'] = args.digest.split(':')
    except (AttributeError, ValueError):
        pass

    backend = api.Send(host=args.host, port=args.port)

    try:
        resp_dict = backend.send(endpoint='Dvr/GetRecordScheduleList',
                                 opts=opts)
    except RuntimeError as error:
        sys.exit('\nFatal error: "{}"'.format(error))

    count = int(resp_dict['RecRuleList']['Count'])

    if count < 1:
        sys.exit('\nNo rules found.\n')

    rule_filter = ''

    if not args.chanid and not args.title:
        rule_filter = 'ALL'

    if args.chanid:
        rule_filter = 'Channel ID: {}'.format(args.chanid)

    if args.title:
        rule_filter += ' Title: {}'.format(args.title)

    print('\n{} delete {} recording rules. '.
          format('Will' if args.wrmi else 'Could', rule_filter), end='')

    if args.wrmi:
        prompt_for_string('YES')
    else:
        print()

    for rule_index in range(count):

        rule = resp_dict['RecRuleList']['RecRules'][rule_index]
        recordid = rule['Id']
        chanid = int(rule['ChanId'])
        title = rule['Title']

        if args.chanid and args.chanid != chanid:
            continue
        if title == 'Default (Template)':
            continue
        if args.title and not title_reg_exp.search(title):
            continue

        postdata = {'RecordId': recordid}

        try:
            backend.send(endpoint='Dvr/RemoveRecordSchedule',
                         postdata=postdata, opts=opts)
        except RuntimeWarning:
            print('No --wrmi, would have deleted: RecordId: {:>5.5}, Title: {}'
                  .format(recordid, title))
            continue
        except RuntimeError as error:
            sys.exit('\nFatal error: "{}"'.format(error))

        print('Deleted: RecordId: {:>5.5}, Title: {}'.format(recordid, title))


if __name__ == '__main__':
    main()

# vim: set expandtab tabstop=4 shiftwidth=4 colorcolumn=80:

wesnewell
Senior
Posts: 669
Joined: Mon Jun 23, 2014 6:54 pm
Location: Wylie TX, USA
United States of America

Re: How to delete all recording rules

Post by wesnewell » Tue Sep 22, 2020 2:44 pm

It takes all of 1 second to delete a recording rule. I've got about 100 and could delete all of them in about 90 seconds. press d, press arrow down, press enter, repeat.
BE/FE-Asrock AB350 Pro Ryzen 3 3200G, 6 atsc tuners. FE's-GF8200's Athlon II, Ryzen 3 2200G. Mythtv user since 2005.

User avatar
heyted
Senior
Posts: 157
Joined: Sun Jun 08, 2014 2:14 am
Location: South Florida
Contact:
United States of America

Re: How to delete all recording rules

Post by heyted » Tue Sep 22, 2020 10:43 pm

Thanks. How do you drop the database without losing the names, details and file locations of the existing recordings?
The other options are more convenient than doing a fresh install, but Mytharchive can be used to export and import the recordings and keep the metadata if you were going to install a more recent version for other reasons. Mytharchive can be cumbersome if there are a large number of recordings. I think there is a faster method if there is a large number of recordings.

https://www.mythtv.org/wiki/MythArchive:
Main features of the raw archive format:
Can create backups of both MythTV recordings and MythVideo files.
Saves not only the file but also all metadata belonging to the file like its title, description, cut list and markup map etc and any preview or coverart files.
Creates an easily parseable xml file containing all the metadata.
Can archive to any directory on a machine's file system...
Ted | My blog

bklein
Junior
Posts: 24
Joined: Sat Sep 19, 2020 6:09 am
Australia

Re: How to delete all recording rules

Post by bklein » Sun Sep 27, 2020 1:35 am

bill6502 wrote:
Tue Sep 22, 2020 2:27 pm
Here's a tool, based on other ones I use. Read the comments at the top
for instructions. It only deletes rules using the Services API. It's written
and tested for Python 3, but probably works on version 2. Change the
1st line accordingly.
Thanks for this script. I gave it a go but there is a small issue. When run without --wrmi it lists all matches. However, when run with --wrmi it only deletes the first matching rule.

User avatar
bill6502
Developer
Posts: 1722
Joined: Fri Feb 07, 2014 5:28 pm
United States of America

Re: How to delete all recording rules

Post by bill6502 » Sun Sep 27, 2020 2:30 am

Found it, fixed above. Or, you can just remove the resp_dict from the
2nd try/except block. I was stomping on my own variable.

bklein
Junior
Posts: 24
Joined: Sat Sep 19, 2020 6:09 am
Australia

Re: How to delete all recording rules

Post by bklein » Sun Sep 27, 2020 2:37 am

bill6502 wrote:
Sun Sep 27, 2020 2:30 am
Found it, fixed above. Or, you can just remove the resp_dict from the
2nd try/except block. I was stomping on my own variable.
Thanks

Post Reply