-
Notifications
You must be signed in to change notification settings - Fork 81
/
db_explorer.py
executable file
·233 lines (189 loc) · 5.49 KB
/
db_explorer.py
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
#!/usr/bin/env python3
#
# Copyright (C) 2016 Dustin Spicuzza
#
# 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 2, 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
#
# This requires click to be installed, which is not an Exaile dependency
#
import copy
import datetime
from dbm import whichdb
import json
import os.path
import pickle
import pprint
import shelve
import bsddb3 as bsddb
import click
class Utf8Unpickler(pickle.Unpickler):
def __init__(self, *args, **kwargs):
kwargs['encoding'] = 'utf-8'
super().__init__(*args, **kwargs)
# For compatibility with Python 2 shelves
shelve.Unpickler = Utf8Unpickler
exaile_db = os.path.join(os.path.expanduser('~'), '.local', 'share', 'exaile',
'music.db')
exaile_pickle_protocol = 2
def tracks(data):
for k, v in data.items():
if not k.startswith('tracks-'):
continue
yield k, v
@click.group()
@click.option('--db', default=exaile_db)
@click.pass_context
def cli(ctx, db):
'''
Tool that allows low-level exploration of an Exaile music database
'''
# simpler version of trackdb.py
try:
d = bsddb.hashopen(db, 'r')
contents = shelve.Shelf(d, protocol=exaile_pickle_protocol)
except Exception:
try:
contents = shelve.open(db, flag='r', protocol=exaile_pickle_protocol)
except Exception:
if os.path.exists(db):
raise
else:
raise click.ClickException("%s does not exist" % db)
ctx.obj = contents
def _on_close():
ctx.obj.close()
ctx.call_on_close(_on_close)
@cli.command()
@click.pass_obj
@click.pass_context
@click.argument('dbtype')
def cvtdb(ctx, data, dbtype):
'''
Only used for testing purposes
'''
db = ctx.parent.params['db']
newdb = db + '.new'
if dbtype == 'gdbm':
import dbm.gnu
new_d = dbm.gnu.open(newdb, 'n')
elif dbtype == 'dbm':
import dbm.ndbm
new_d = dbm.ndbm.open(newdb, 'n')
elif dbtype == 'dbhash':
import dbm.bsd
new_d = dbm.bsd.open(newdb, 'n')
elif dbtype == 'bsddb':
new_d = bsddb.hashopen(newdb, 'n')
elif dbtype == 'dumbdbm':
import dbm.dumb
new_d = dbm.dumb.open(newdb, 'n')
else:
raise click.ClickException("Invalid type %s" % dbtype)
new_data = shelve.Shelf(new_d, protocol=exaile_pickle_protocol)
for k, v in data.items():
new_data[k] = v
new_data.sync()
new_data.close()
@cli.command()
@click.pass_obj
@click.argument('output')
def tojson(data, output):
'''
Export Exaile's database to JSON
'''
# not really a db type, but useful?
d = {}
for k, v in data.items():
d[k] = v
with open(output, 'w') as fp:
json.dump(d, fp, sort_keys=True, indent=4, separators=(',', ': '))
@cli.command()
@click.pass_obj
@click.pass_context
def info(ctx, data):
'''
Display summary information about the DB
'''
print('DB Type:', whichdb(ctx.parent.params['db']))
print('Version:', data.get('_dbversion'))
print('Name :', data.get('name'))
print('Key :', data.get('_key'))
print("Count :", len(data))
print()
print('Location(s):')
pprint.pprint(data.get('_serial_libraries'))
@cli.command()
@click.argument('search')
@click.option('-t', '--tag', default='title')
@click.pass_obj
def search(data, tag, search):
'''
Search for tracks via the contents of particular tags
'''
tag = str(tag)
for k, tr in tracks(data):
tr = tr[0]
val = tr.get(tag)
if val:
if isinstance(val, list):
val = val[0]
if search in val:
print('%10s: %s' % (k, val))
def _date_fix(tags):
tags = copy.deepcopy(tags)
for t in ['__date_added', '__last_played', '__modified']:
if t in tags:
try:
dt = datetime.datetime.fromtimestamp(tags[t])
tags[t] = dt.strftime("%Y-%m-%d %H:%M:%S")
except:
pass
return tags
def _print_tr(tr, raw):
if tr is not None:
tags, key, attrs = tr
print("Track key", key)
print("Tags:")
if not raw:
tags = _date_fix(tags)
pprint.pprint(tags)
print("Attrs:")
pprint.pprint(attrs)
@cli.command('track-by-idx')
@click.argument('idx')
@click.option('--raw/--no-raw', default=False)
@click.pass_obj
def track_by_idx(data, idx, raw):
'''
pprint a track by its index in the database
'''
key = str('tracks-%s' % idx)
tr = data.get(key)
_print_tr(tr, raw)
@cli.command()
@click.pass_obj
def tags(data):
'''
Display summary information about tags present
'''
tags = set()
for k, v in tracks(data):
# print(v[0].keys())
tags.update(set(v[0].keys()))
print("All tags:")
pprint.pprint(tags)
if __name__ == '__main__':
cli()