Repository navigation
Expand file tree
/
Copy pathlr2folder.py
More file actions
209 lines (177 loc) · 8.37 KB
/
Copy pathlr2folder.py
File metadata and controls
209 lines (177 loc) · 8.37 KB
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
"""Write generated BMSTABLE folders into LR2's song.db folder table and register
the path in the jukebox section of LR2's config.xml, so users no longer have to
manually delete/re-add the folder in the LR2 jukebox after every update.
Field semantics verified against a song.db dump produced by LR2 itself:
- path : path relative to the LR2 root, backslashes; directories end with '\\'
- parent : lowercase hex crc32 (including trailing NUL) of the parent's path;
top-level folders use the crc32 of "ROOT" -> 'e2977170'
- type : 1 = plain folder, 2 = table folder / .lr2folder
- date : LR2 timestamp of the file/folder's last write time
- adddate : LR2 timestamp of when the rows were added (now)
"""
import os
import sqlite3
import zlib
import datetime
ROOT_PARENT = "e2977170" # crc32("ROOT\0"), lowercase
FOLDER_SCHEMA_COLS = ["title", "subtitle", "category", "info_a", "info_b",
"command", "path", "type", "banner", "parent",
"date", "max", "adddate"]
def folderCrc32(path: str) -> str:
"""crc32 of path (incl. trailing NUL), lowercase hex — LR2 folder parent id."""
return "%08x" % (zlib.crc32(path.encode("utf-8") + b"\x00") & 0xFFFFFFFF)
def makeLR2Date(filepath=None) -> int:
"""Re-implementation of LR2's makeLR2Date (reverse-engineered).
filepath: file/folder whose last-write time is used; None -> current time.
Returns the LR2 internal timestamp (NOT unix time)."""
if filepath and os.path.exists(filepath):
mtime = os.path.getmtime(filepath)
ft = int((mtime + 11644473600) * 1e7)
else:
ft = int((datetime.datetime.now().timestamp() + 11644473600) * 1e7)
# FILETIME (100ns ticks since 1601-01-01 UTC) -> SYSTEMTIME (UTC)
secs = ft // 10_000_000
micro = (ft % 10_000_000) // 10
dt = datetime.datetime(1601, 1, 1) + datetime.timedelta(seconds=secs, microseconds=micro)
# st.wYear += 0xFE8F (16-bit wrap, like the C++ WORD)
year2 = (dt.year + 0xFE8F) & 0xFFFF
try:
dt2 = dt.replace(year=year2)
ft2 = int((dt2 - datetime.datetime(1601, 1, 1)).total_seconds() * 1e7)
except ValueError:
ft2 = ft # SystemTimeToFileTime can fail per the original comments
dw_low = ft2 & 0xFFFFFFFF
dw_high = (ft2 >> 32) & 0xFFFFFFFF
return int(dw_low / 1.0e7) - int(dw_high * -429.4836225)
def parseFolderFile(filepath: str) -> dict:
"""Parse #TITLE/#CATEGORY/#INFORMATION_A/#INFORMATION_B/#COMMAND/#MAXTRACKS
from a folderinfo.txt or .lr2folder file."""
result = {"title": "", "category": "", "info_a": "", "info_b": "",
"command": "", "max": 0}
try:
with open(filepath, encoding="shift-jis", errors="ignore") as f:
for raw in f:
line = raw.strip()
for key, field in (("#TITLE", "title"), ("#CATEGORY", "category"),
("#INFORMATION_A", "info_a"), ("#INFORMATION_B", "info_b"),
("#COMMAND", "command")):
if line.startswith(key):
result[field] = line[len(key):].strip()
break
else:
if line.startswith("#MAXTRACKS"):
try:
result["max"] = int(line[len("#MAXTRACKS"):].strip())
except ValueError:
pass
except Exception:
pass
return result
def relPath(bmstableDir: str, lr2Root: str) -> str:
"""Absolute bmstableDir -> LR2-relative path with backslashes and trailing '\\'."""
rel = os.path.relpath(bmstableDir, lr2Root).replace("/", "\\")
if not rel.endswith("\\"):
rel += "\\"
return rel
def buildFolderRows(bmstableDir: str, lr2Root: str):
"""Scan the generated BMSTABLE tree and build folder rows (list of tuples)."""
rel_bms = relPath(bmstableDir, lr2Root)
parent_bms = folderCrc32(rel_bms)
now = makeLR2Date(None)
rows = []
# the BMSTABLE root folder itself (type=1, parent = ROOT)
rows.append(("BMSTABLE", None, None, None, None, None, rel_bms, 1, None,
ROOT_PARENT, makeLR2Date(bmstableDir), None, now))
if not os.path.isdir(bmstableDir):
return rows
for name in sorted(os.listdir(bmstableDir)):
d = os.path.join(bmstableDir, name)
if not os.path.isdir(d):
continue
info = parseFolderFile(os.path.join(d, "folderinfo.txt"))
rel_d = rel_bms + name + "\\"
date_d = makeLR2Date(d)
# table folder row (type=2)
rows.append((info["title"], None, info["category"], info["info_a"], info["info_b"],
"", rel_d, 2, "", parent_bms, date_d, info["max"], now))
# .lr2folder rows (type=2, one per level)
for fname in sorted(os.listdir(d)):
if not fname.endswith(".lr2folder"):
continue
fp = os.path.join(d, fname)
fi = parseFolderFile(fp)
rows.append((fi["title"], None, fi["category"], fi["info_a"], fi["info_b"],
fi["command"], rel_d + fname, 2, "",
folderCrc32(rel_d), makeLR2Date(fp), fi["max"], now))
return rows
def writeFolderRecords(databasePath: str, bmstableDir: str, lr2Root: str, onProgress=None) -> int:
"""Delete old BMSTABLE rows from song.db's folder table and insert fresh ones.
Returns number of rows written."""
if not os.path.exists(databasePath) or not os.path.isdir(bmstableDir):
return 0
rows = buildFolderRows(bmstableDir, lr2Root)
if len(rows) == 0:
return 0
rel_bms = relPath(bmstableDir, lr2Root)
if onProgress: onProgress("Writing jukebox folder table...")
db = sqlite3.connect(databasePath)
db.execute("DELETE FROM folder WHERE path LIKE ?", (rel_bms + "%",))
db.executemany(
"INSERT INTO folder(%s) VALUES (%s)" %
(",".join(FOLDER_SCHEMA_COLS), ",".join("?" * len(FOLDER_SCHEMA_COLS))),
rows)
db.commit()
db.close()
if onProgress: onProgress("Jukebox folder table updated: %d row(s)" % len(rows))
return len(rows)
def removeTableFolderRows(databasePath: str, bmstableRelPath: str, tableHash: str) -> int:
"""Delete folder rows belonging to one table (matched by its hash, which is
part of the generated folder name like 01_<hash>). Returns rows deleted."""
if not os.path.exists(databasePath) or not tableHash:
return 0
db = sqlite3.connect(databasePath)
cur = db.execute("DELETE FROM folder WHERE path LIKE ?",
(bmstableRelPath + "%" + tableHash + "%",))
db.commit()
n = cur.rowcount
db.close()
return n
def removeAllFolderRows(databasePath: str, bmstableRelPath: str) -> int:
"""Delete every BMSTABLE row from the folder table. Returns rows deleted."""
if not os.path.exists(databasePath):
return 0
db = sqlite3.connect(databasePath)
cur = db.execute("DELETE FROM folder WHERE path LIKE ?", (bmstableRelPath + "%",))
db.commit()
n = cur.rowcount
db.close()
return n
def updateJukeboxXml(configXmlPath: str, bmstableRelPath: str) -> bool:
"""Make sure <path>bmstableRelPath</path> exists under <jukebox> in LR2's
config.xml (shift_jis). Minimal string surgery keeps the rest of the file
byte-identical. Returns True if the file was modified."""
if not os.path.exists(configXmlPath):
return False
if not bmstableRelPath.endswith("\\"):
bmstableRelPath += "\\"
entry = "<path>%s</path>" % bmstableRelPath
with open(configXmlPath, encoding="shift-jis") as f:
content = f.read()
if entry in content:
return False
if "<jukebox>" in content and "</jukebox>" in content:
idx = content.rindex("</jukebox>")
# insert a new indented line right after the opening of that line,
# so the existing "\t" indentation of </jukebox> is not doubled
line_start = content.rindex("\n", 0, idx) + 1
insert = "\t\t" + entry + "\n"
new = content[:line_start] + insert + content[line_start:]
elif "</config>" in content:
block = "\t<jukebox>\n\t\t" + entry + "\n\t</jukebox>\n"
idx = content.rindex("</config>")
new = content[:idx] + block + content[idx:]
else:
return False # unknown format, leave it alone
with open(configXmlPath, "w", encoding="shift-jis") as f:
f.write(new)
return True