| 1 |
"""Exports data from beets""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import codecs |
| 6 |
import csv |
| 7 |
import json |
| 8 |
import os |
| 9 |
import sys |
| 10 |
from datetime import date, datetime |
| 11 |
from typing import TYPE_CHECKING, Any, Literal, Protocol, get_args |
| 12 |
from xml.etree import ElementTree |
| 13 |
|
| 14 |
import mediafile |
| 15 |
|
| 16 |
from beets import ui |
| 17 |
from beets.dbcore.types import BasePathType |
| 18 |
from beets.library.fields import TYPE_BY_FIELD |
| 19 |
from beets.plugins import BeetsPlugin |
| 20 |
from beetsplug.info import library_data, tag_data |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from collections.abc import Iterable, Iterator, Sequence |
| 24 |
|
| 25 |
from beets.library import Library |
| 26 |
|
| 27 |
from ._typing import JSONDict |
| 28 |
|
| 29 |
Format = Literal["json", "jsonlines", "csv", "xml"] |
| 30 |
VALID_FORMATS = get_args(Format) |
| 31 |
|
| 32 |
|
| 33 |
class ExportCLIOpts(Protocol): |
| 34 |
library: bool | None |
| 35 |
album: bool |
| 36 |
append: bool |
| 37 |
included_keys: Sequence[str] |
| 38 |
output: str | None |
| 39 |
format: Format | None |
| 40 |
|
| 41 |
|
| 42 |
class ExportEncoder(json.JSONEncoder): |
| 43 |
"""Deals with dates because JSON doesn't have a standard""" |
| 44 |
|
| 45 |
def default(self, o: object) -> Any: |
| 46 |
if isinstance(o, (datetime, date)): |
| 47 |
return o.isoformat() |
| 48 |
return json.JSONEncoder.default(self, o) |
| 49 |
|
| 50 |
|
| 51 |
class ExportPlugin(BeetsPlugin): |
| 52 |
default_format: Format |
| 53 |
|
| 54 |
def __init__(self) -> None: |
| 55 |
super().__init__() |
| 56 |
|
| 57 |
self.config.add( |
| 58 |
{ |
| 59 |
"default_format": "json", |
| 60 |
"json": { |
| 61 |
# JSON module formatting options. |
| 62 |
"formatting": { |
| 63 |
"ensure_ascii": False, |
| 64 |
"indent": 4, |
| 65 |
"separators": (",", ": "), |
| 66 |
"sort_keys": True, |
| 67 |
} |
| 68 |
}, |
| 69 |
"jsonlines": { |
| 70 |
# JSON Lines formatting options. |
| 71 |
"formatting": { |
| 72 |
"ensure_ascii": False, |
| 73 |
"separators": (",", ": "), |
| 74 |
"sort_keys": True, |
| 75 |
} |
| 76 |
}, |
| 77 |
"csv": { |
| 78 |
# CSV module formatting options. |
| 79 |
"formatting": { |
| 80 |
# The delimiter used to separate columns. |
| 81 |
"delimiter": ",", |
| 82 |
# The dialect to use when formatting the file output. |
| 83 |
"dialect": "excel", |
| 84 |
} |
| 85 |
}, |
| 86 |
"xml": { |
| 87 |
# XML module formatting options. |
| 88 |
"formatting": {} |
| 89 |
}, |
| 90 |
# TODO: Use something like the edit plugin |
| 91 |
# 'item_fields': [] |
| 92 |
} |
| 93 |
) |
| 94 |
self.default_format = self.config["default_format"].as_choice( |
| 95 |
VALID_FORMATS |
| 96 |
) |
| 97 |
|
| 98 |
def commands(self) -> list[ui.Subcommand]: |
| 99 |
cmd = ui.Subcommand("export", help="export data from beets") |
| 100 |
cmd.func = self.run |
| 101 |
cmd.parser.add_album_option() |
| 102 |
cmd.parser.add_option( |
| 103 |
"-l", |
| 104 |
"--library", |
| 105 |
action="store_true", |
| 106 |
help="show library fields instead of tags", |
| 107 |
) |
| 108 |
cmd.parser.add_option( |
| 109 |
"--append", |
| 110 |
action="store_true", |
| 111 |
default=False, |
| 112 |
help="if should append data to the file", |
| 113 |
) |
| 114 |
cmd.parser.add_option( |
| 115 |
"-i", |
| 116 |
"--include-keys", |
| 117 |
default=[], |
| 118 |
action="append", |
| 119 |
dest="included_keys", |
| 120 |
help="comma separated list of keys to show", |
| 121 |
) |
| 122 |
cmd.parser.add_option( |
| 123 |
"-o", |
| 124 |
"--output", |
| 125 |
help="path for the output file. If not given, will print the data", |
| 126 |
) |
| 127 |
cmd.parser.add_option( |
| 128 |
"-f", |
| 129 |
"--format", |
| 130 |
type="choice", |
| 131 |
choices=VALID_FORMATS, |
| 132 |
default=self.config["default_format"].get(), |
| 133 |
help="the output format: json|jsonlines|csv|xml", |
| 134 |
) |
| 135 |
return [cmd] |
| 136 |
|
| 137 |
def run( |
| 138 |
self, lib: Library, opts: ExportCLIOpts, args: Sequence[str] |
| 139 |
) -> None: |
| 140 |
file_path = opts.output |
| 141 |
file_mode = "a" if opts.append else "w" |
| 142 |
file_format = opts.format or self.default_format |
| 143 |
format_options = self.config[file_format]["formatting"].get(dict) |
| 144 |
|
| 145 |
_format = ( |
| 146 |
CSVFormat |
| 147 |
if file_format == "csv" |
| 148 |
else XMLFormat |
| 149 |
if file_format == "xml" |
| 150 |
else JsonFormat |
| 151 |
) |
| 152 |
export_format = _format( |
| 153 |
file_format=file_format, file_path=file_path, file_mode=file_mode |
| 154 |
) |
| 155 |
|
| 156 |
if opts.library or opts.album: |
| 157 |
data_collector = library_data |
| 158 |
else: |
| 159 |
data_collector = tag_data |
| 160 |
|
| 161 |
included_keys = [] |
| 162 |
for keys in opts.included_keys: |
| 163 |
included_keys.extend(keys.split(",")) |
| 164 |
|
| 165 |
byte_fields = [ |
| 166 |
k for k, v in TYPE_BY_FIELD.items() if isinstance(v, BasePathType) |
| 167 |
] |
| 168 |
|
| 169 |
def collect_data() -> Iterator[JSONDict]: |
| 170 |
for data_emitter in data_collector(lib, args, album=opts.album): |
| 171 |
try: |
| 172 |
data, _ = data_emitter(included_keys or "*") |
| 173 |
except (mediafile.UnreadableFileError, OSError) as ex: |
| 174 |
self._log.error("cannot read file: {}", ex) |
| 175 |
continue |
| 176 |
else: |
| 177 |
yield data |
| 178 |
|
| 179 |
def stringify_bytes(data: JSONDict) -> JSONDict: |
| 180 |
for field in byte_fields: |
| 181 |
if (value := data.get(field)) is not None: |
| 182 |
data[field] = os.fsdecode(value) |
| 183 |
|
| 184 |
return data |
| 185 |
|
| 186 |
export_format.export( |
| 187 |
map(stringify_bytes, collect_data()), **format_options |
| 188 |
) |
| 189 |
|
| 190 |
|
| 191 |
class ExportFormat: |
| 192 |
"""The output format type""" |
| 193 |
|
| 194 |
def __init__( |
| 195 |
self, |
| 196 |
file_format: str, |
| 197 |
file_path: str | None, |
| 198 |
file_mode: str = "w", |
| 199 |
encoding: str = "utf-8", |
| 200 |
) -> None: |
| 201 |
self.file_format = file_format |
| 202 |
self.path = file_path |
| 203 |
self.mode = file_mode |
| 204 |
self.encoding = encoding |
| 205 |
# creates a file object to write/append or sets to stdout |
| 206 |
self.out_stream = ( |
| 207 |
codecs.open(self.path, self.mode, self.encoding) |
| 208 |
if self.path |
| 209 |
else sys.stdout |
| 210 |
) |
| 211 |
|
| 212 |
def export(self, data_iter: Iterable[JSONDict], **kwargs) -> None: |
| 213 |
raise NotImplementedError() |
| 214 |
|
| 215 |
|
| 216 |
class JsonFormat(ExportFormat): |
| 217 |
"""Saves in a json file""" |
| 218 |
|
| 219 |
def _print_json(self, data: Any, **kwargs) -> None: |
| 220 |
json.dump(data, self.out_stream, cls=ExportEncoder, **kwargs) |
| 221 |
self.out_stream.write("\n") |
| 222 |
|
| 223 |
def export(self, data_iter: Iterable[JSONDict], **kwargs) -> None: |
| 224 |
if self.file_format == "json": |
| 225 |
self._print_json(list(data_iter), **kwargs) |
| 226 |
else: |
| 227 |
for item in data_iter: |
| 228 |
self._print_json(item, **kwargs) |
| 229 |
|
| 230 |
|
| 231 |
class CSVFormat(ExportFormat): |
| 232 |
"""Saves in a csv file""" |
| 233 |
|
| 234 |
def export(self, data_iter: Iterable[JSONDict], **kwargs) -> None: |
| 235 |
data = list(data_iter) |
| 236 |
header = list(data[0].keys()) if data else [] |
| 237 |
writer = csv.DictWriter(self.out_stream, fieldnames=header, **kwargs) |
| 238 |
writer.writeheader() |
| 239 |
writer.writerows(data) |
| 240 |
|
| 241 |
|
| 242 |
class XMLFormat(ExportFormat): |
| 243 |
"""Saves in a xml file""" |
| 244 |
|
| 245 |
def export(self, data_iter: Iterable[JSONDict], **kwargs) -> None: |
| 246 |
# Creates the XML file structure. |
| 247 |
data = list(data_iter) |
| 248 |
library = ElementTree.Element("library") |
| 249 |
tracks = ElementTree.SubElement(library, "tracks") |
| 250 |
if data and isinstance(data[0], dict): |
| 251 |
for index, item in enumerate(data): |
| 252 |
track = ElementTree.SubElement(tracks, "track") |
| 253 |
for key, value in item.items(): |
| 254 |
track_details = ElementTree.SubElement(track, key) |
| 255 |
track_details.text = value |
| 256 |
# Depending on the version of python the encoding needs to change |
| 257 |
try: |
| 258 |
string = ElementTree.tostring(library, encoding="unicode", **kwargs) |
| 259 |
except LookupError: |
| 260 |
string = ElementTree.tostring(library, encoding="utf-8", **kwargs) |
| 261 |
|
| 262 |
self.out_stream.write(string) |