-
Notifications
You must be signed in to change notification settings - Fork 2
/
mythdb_access
executable file
·364 lines (322 loc) · 14 KB
/
mythdb_access
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
mythdb_access can be used to access data from a MythTV-DB or to request
the mythbackend to delete a recording.
mythdb_access uses the MythTV python bindings to access a MythTV-DB.
It currently supports: obtaining information about a recording, which
can be written to a file or stdout; obtaining StorageGroup information
which is written to stdout; and requesting the mythbackend to delete a
specified recording. It is part of the myth2kodi project.
https://github.com/stuart-knock/myth2kodi
http://forum.kodi.tv/showthread.php?tid=301925
mythdb_access is a derivative of MythDataGrabber.
MythDataGrabber -- Written by Mike Szczys and Adam Outler.
https://github.com/adamoutler/mythicallibrarian
http://forum.xbmc.org/showthread.php?t=65644
MythDataGrabber was written for the mythicalLibrarian project, and is
licensed under the Apache License, which requires a notification to
adamoutler (at) gmail.com as a formality before any derivative work.
We just want to hear about your project.
USAGE:
mythdb_access [options]
See,
mythdb_access --help
OPTIONS:
--filename=file.ext : recording to be accessed
--DBHostName : sets the DB Host, default: localhost
--DBName : sets the DB Name, default: mythconverg
--DBUserName : sets the User Name, default: mythtv
--DBPassword : sets the Password, default: mythtv
--SecurityPin : sets the Pin, default: 0
--writeFile : don't display output, write to output file.
--output=file.txt : sets the output, default: ~/showdata.txt
--version : displays version information
--verbosity : Sets the logging level.
--Diagnostic : perform some basic diagnostic checks.
--storagegroups : write the MythTV-DB StorageGroup info to stdout.
--delete : request the mythbackend to delete a recording.
--rerecord : like delete, but, requests rerecord of recording.
--force : force deletion of DB-entry for recording.
--help : print a help message (autogenerated by argparse).
EXAMPLES:
#Write the information for a recording to stdout
mythdb_access --filename=1000_20101010101010.mpg
#Perform diagnostics
mythdb_access --Diagnostic --verbosity=3
#Write the information for a recording to a file.
mythdb_access --filename=1000_20101010101010.mpg
--DBHostName=192.168.1.42
--DBName=mythconverg
--DBUserName=mythtv
--DBPassword=mysupersecurenonstandardpassword
--writeFile
--output=/home/myfile.txt
#Delete a specific recording.
mythdb_access --filename=1000_20101010101010.mpg
--writeFile
--output=/tmp/deleted_recording_info.txt
--delete
REQUIRES:
libmyth-python
python-lxml
.. moduleauthor:: Stuart Knock <>
.. moduleauthor:: Mike Szczys <>
.. moduleauthor:: Adam Outler <adamoutler (at) gmail.com>
"""
__version__ = '0.6.0'
# First, import from python standard library
import logging
logging.basicConfig(level=logging.DEBUG)
LOG = logging.getLogger(__name__)
import sys
import os
# Then, try importing less reliable packages
try:
from MythTV import MythDB
except ImportError:
LOG.error("Failed to import MythTV.MythDB...")
raise
###########################################################################
def read_mysql_text():
"""Read database settings from ~/.mythtv/mysql.txt
Function: read_mysql_text
Arguments: None
Returns: extracted login information
"""
LOG.debug("Calling read_mysql_text()")
mysql_text = os.path.expanduser('~') + "/.mythtv/mysql.txt"
dbdata = {}
for line in open(mysql_text, 'r'):
if line.startswith('#'):
continue
if '=' in line:
setting_name, setting_value = line.strip().split('=')
dbdata[setting_name.strip()] = setting_value.strip()
return dbdata
###########################################################################
def write_data():
"""
Function: write_data
Arguments: None
Returns: database information for the recording.
"""
LOG.debug("Calling write_data()")
# loop through recording information
for field, value in REC.items():
#write recording information as unicode strings:
if isinstance(value, str):
OUTPUT.write('%s = "%s"\n' % (field, value.encode('utf-8')))
else:
OUTPUT.write('%s = "%s"\n' % (field, value))
# loop through comm-start points
for i, data in enumerate(MARKUPSTART):
OUTPUT.write('startdata[%s] = "%s"\n' % (i, data))
# loop through comm-end points
for i, data in enumerate(MARKUPSTOP):
OUTPUT.write('stopdata[%s] = "%s"\n' % (i, data))
# grab guide data provider
with DB as cursor:
# set cursor on xmltvgrabber
cursor.execute("SELECT xmltvgrabber FROM videosource")
# pull the data
res = cursor.fetchone()
# write the data if any
if res is not None:
OUTPUT.write('xmltvgrabber = "%s"\n' % res[0].strip())
# verify valid data was written
if REC.chanid != '': #TODO: this is strange to do at the end, and also doesn't test writing but rather that a valid recording was found in the first place.
LOG.debug("Operation complete.")
###########################################################################
def closefile():
"""If we have an open file, close it."""
LOG.debug("Closing out the file/stdout")
if OUTPUT is not None:
if OUTPUT.fileno() != 1:
OUTPUT.close()
###########################################################################
if __name__ == "__main__":
import argparse
PARSER = argparse.ArgumentParser(
description="Pull data from MythTV-DB via python bindings.")
#Select mode of operation: diagnostics; storage-group info; recording-specific.
MODE_GROUP = PARSER.add_mutually_exclusive_group(required=True)
#Diagnostic arg
MODE_GROUP.add_argument('--Diagnostic',
action='store_true',
default='False',
help="Displays diagnostic information.")
#Storage group arg
MODE_GROUP.add_argument('--storagegroups',
action='store_true',
default='False',
help="Write MythTV-DB storage-group information to stdout.")
#File arg
MODE_GROUP.add_argument('-f', '--filename',
help="""Name of the recording file you want to process.
Information on this recording will be printed
to stdout (DEFAULT) or a file (--writeFile).""")
#writeFile arg
PARSER.add_argument('--writeFile',
action='store_true',
default='False',
help="""Use this flag to write data to the file
specified by --output.""")
#Output file arg
PARSER.add_argument('-o', '--output',
type=argparse.FileType('w'),
default=os.path.expanduser('~') + "/showdata.txt",
help="""Use this argument to override default output file.
NB. You must also set --writeFile.""")
#Block setting both --delete and --rerecord.
DELETE_GROUP = PARSER.add_mutually_exclusive_group(required=False)
#delete arg
DELETE_GROUP.add_argument('--delete',
action='store_true',
default='False',
help="""Use this flag to delete the recording
specified by --filename.""")
#rerecord arg
DELETE_GROUP.add_argument('--rerecord',
action='store_true',
default='False',
help="""Use this flag to rerecord the recording
specified by --filename. It works by deleting
the recording and setting 'rerecord' on the
associated oldrecorded entry.""")
#force arg
PARSER.add_argument('--force',
action='store_true',
default='False',
help="""Use this flag to force the deletion the DB-entry
for the recording even if the associated
recording file cannot be found.""")
#DBHostName arg
PARSER.add_argument('--DBHostName',
default="localhost",
help="Sets the DB Host")
#DBName arg
PARSER.add_argument('--DBName',
default="mythconverg",
help="Sets the MythTV-DB Name, default: mythconverg")
#DBUserName arg
PARSER.add_argument('--DBUserName',
default="mythtv",
help="Sets the MythTV-DB User Name")
#DBPassword arg
PARSER.add_argument('--DBPassword',
default="mythtv",
help="Sets the MythTV-DB Password")
#SecurityPin arg
PARSER.add_argument('--SecurityPin',
type=int,
default=0,
help="Sets the MythTV-DB SecurityPin")
#version arg
PARSER.add_argument('--version',
action='version',
version=__version__,
help="Displays version information")
#Logging arg
PARSER.add_argument("--verbosity",
type=int,
choices=[0, 1, 2, 3],
default=2,
help="""Set the logging verbosity: 0=ERROR; 1=WARNING;
2=INFO; 3=DEBUG.""")
ARGS = PARSER.parse_args()
#######################################################################
#import pdb; pdb.set_trace()
#Set the logging level
LOGLEVELMAPPING = ["ERROR", "WARNING", "INFO", "DEBUG"]
LOG.setLevel(LOGLEVELMAPPING[ARGS.verbosity])
#Get a connection to the database
LOG.debug("Establishing database connection")
try:
# Defaults or ARGS
DB = MythDB(**vars(ARGS))
except Exception:
try:
# mythtv preconfigured options
LOG.error('Failed: attempting to use system default configuration')
DB = MythDB(SecurityPin=ARGS.SecurityPin)
except Exception:
try:
# read from the mysql.txt
LOG.error('Failed: attempting to read from default mythtv file')
DB = MythDB(read_mysql_text(), SecurityPin=ARGS.SecurityPin)
except Exception:
LOG.error('Failed: Please specify database information manually')
LOG.error('See --help for more information.')
raise
#######################################################################
#If requested, run some diagnostics.
if ARGS.Diagnostic is True:
try:
LOG.info("Connected to: " + DB.gethostname())
LOG.info("Identified StorageGroups:")
for sg in DB.getStorageGroup():
LOG.info(" %s: %s" % (sg.groupname, sg.dirname))
LOG.info("Diagnostics passed...")
except Exception:
LOG.error("Diagnostics failed.")
raise
sys.exit(0)
#######################################################################
#If requested, return storage group information.
if ARGS.storagegroups is True:
try:
STORAGE_GROUPS = DB.getStorageGroup()
OUTPUT = sys.stdout
for sg in STORAGE_GROUPS:
sg_dirname = sg.dirname.encode('utf-8')
LOG.debug("Found StorageGroup: " + sg_dirname.strip())
OUTPUT.write("%s " % sg_dirname.strip())
except Exception:
LOG.error("StorageGroup access failed.")
raise
sys.exit(0)
#######################################################################
#Gather information from the database for the recording
try:
REC = DB.searchRecorded(basename=ARGS.filename).next()
except StopIteration:
LOG.error("Failed to find DB record for: " + ARGS.filename)
raise
#Set comskip data
try:
MARKUPSTART, MARKUPSTOP = zip(*REC.markup.getskiplist())
except Exception:
LOG.warning("No comskip information found.")
MARKUPSTART, MARKUPSTOP = '', ''
#######################################################################
# Return the data, either to a file or to stdout
OUTPUT = None
if ARGS.writeFile is True:
LOG.debug("Attempting to write data to file: " + ARGS.output.name)
try:
# Write data to file defined by "output" keyword arg.
OUTPUT = ARGS.output
write_data()
except IOError: #the file failed to write
LOG.error("Write Failed: " + ARGS.output.name)
raise
else:
LOG.debug("Writing data to standard out (terminal).")
OUTPUT = sys.stdout
write_data()
closefile()
#######################################################################
# Ask mythbackend to delete the recording, if the --force flag is also
# set then ask for the DB-entry to be deleted even if the recording file
# cannot be found. Sets the file as recordable in oldrecorded.
if ARGS.rerecord is True:
LOG.debug("Deleting and setting 'rerecord': " + ARGS.filename)
REC.delete(force=ARGS.force, rerecord=ARGS.rerecord)
sys.exit(0) #Prevent fall through to delete.
# Ask mythbackend to delete the recording, if the --force flag is also
# set then ask for the DB-entry to be deleted even if the recording file
# cannot be found.
if ARGS.delete is True:
LOG.debug("Deleting recording: " + ARGS.filename)
REC.delete(force=ARGS.force)