pedalboard_share.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2026 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. # Pedalboard files (.modpedalboard) for Export / Import in the Pedalboards Library.
  5. #
  6. # A .modpedalboard is a tar.gz with:
  7. # modpedalboard.json what the pedalboard is (title, plugins, OS version, files it uses)
  8. # <name>.pedalboard/... the pedalboard bundle as saved on the unit (ttl files, addressings,
  9. # snapshots, plugin state folders, screenshot, thumbnail)
  10. #
  11. # User files the pedalboard uses (NAM models, IRs, samples) are not included; their names are
  12. # listed in the header. Packed and unpacked in Python (no shell tools: also runs on Windows).
  13. # Must stay Python 3.4 compatible (device image).
  14. import io
  15. import json
  16. import os
  17. import posixpath
  18. import re
  19. import tarfile
  20. import time
  21. import zlib
  22. FORMAT_VERSION = 1
  23. EXTENSION = ".modpedalboard"
  24. HEADER_NAME = "modpedalboard.json"
  25. # a pedalboard bundle is usually well under 1 MB; plugin state folders can add some
  26. MAX_PACKED_SIZE = 32 * 1024 * 1024
  27. MAX_UNPACKED_SIZE = 128 * 1024 * 1024
  28. MAX_MEMBERS = 2000
  29. class PedalboardFileError(Exception):
  30. pass
  31. def make_header(title, plugins, files, os_version, platform):
  32. return {
  33. 'format': FORMAT_VERSION,
  34. 'title': title,
  35. 'plugins': plugins,
  36. 'files': files,
  37. 'os_version': os_version,
  38. 'platform': platform,
  39. 'created': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
  40. }
  41. def _bundle_files(bundlepath):
  42. "Regular files of a bundle, relative paths with '/', symlinks skipped."
  43. result = []
  44. for root, dirs, files in os.walk(bundlepath):
  45. dirs[:] = sorted(d for d in dirs if not os.path.islink(os.path.join(root, d)))
  46. for name in sorted(files):
  47. path = os.path.join(root, name)
  48. if os.path.islink(path) or not os.path.isfile(path):
  49. continue
  50. result.append(os.path.relpath(path, bundlepath).replace(os.sep, "/"))
  51. return result
  52. def find_user_files(bundlepath, user_files_dir):
  53. """
  54. Names of user files a pedalboard points to, relative to the user files folder
  55. (e.g. "NAM Models/amp.nam"), read from the paths in its ttl files.
  56. """
  57. found = set()
  58. prefixes = set([user_files_dir.rstrip("/\\")])
  59. if os.sep != "/":
  60. prefixes.add(user_files_dir.rstrip("/\\").replace(os.sep, "/"))
  61. for relpath in _bundle_files(bundlepath):
  62. if not relpath.endswith(".ttl"):
  63. continue
  64. try:
  65. with open(os.path.join(bundlepath, relpath), 'r', encoding="utf-8", errors="ignore") as fh:
  66. text = fh.read()
  67. except (IOError, OSError):
  68. continue
  69. for prefix in prefixes:
  70. for match in re.finditer(re.escape(prefix) + r'[/\\]([^"<>\n]+)', text):
  71. name = match.group(1).replace("\\", "/").strip()
  72. if name:
  73. found.add(name)
  74. return sorted(found)
  75. def _add_bytes(tar, name, data, mtime=None):
  76. info = tarfile.TarInfo(name)
  77. info.size = len(data)
  78. info.mtime = int(mtime if mtime is not None else time.time())
  79. info.mode = 0o644
  80. tar.addfile(info, io.BytesIO(data))
  81. def pack(bundlepath, header):
  82. "Pack a saved pedalboard bundle. Returns the file contents."
  83. bundlename = os.path.basename(bundlepath.rstrip("/\\"))
  84. relpaths = _bundle_files(bundlepath)
  85. if "manifest.ttl" not in relpaths:
  86. raise PedalboardFileError("The saved pedalboard is incomplete")
  87. total = sum(os.path.getsize(os.path.join(bundlepath, p)) for p in relpaths)
  88. if total > MAX_UNPACKED_SIZE or len(relpaths) + 1 > MAX_MEMBERS:
  89. raise PedalboardFileError("This pedalboard is too big to export")
  90. buf = io.BytesIO()
  91. with tarfile.open(fileobj=buf, mode="w:gz") as tar:
  92. _add_bytes(tar, HEADER_NAME, json.dumps(header, indent=2, sort_keys=True).encode("utf-8"))
  93. for relpath in relpaths:
  94. path = os.path.join(bundlepath, relpath)
  95. with open(path, 'rb') as fh:
  96. _add_bytes(tar, "%s/%s" % (bundlename, relpath), fh.read(), os.path.getmtime(path))
  97. data = buf.getvalue()
  98. if len(data) > MAX_PACKED_SIZE:
  99. raise PedalboardFileError("This pedalboard is too big to export")
  100. return data
  101. def _check_name(name):
  102. if not name or "\\" in name or name.startswith("/") or posixpath.normpath(name) != name.rstrip("/"):
  103. raise PedalboardFileError("This file contains an invalid path")
  104. for part in name.rstrip("/").split("/"):
  105. if part in ("", ".", "..") or part.startswith("."):
  106. raise PedalboardFileError("This file contains an invalid path")
  107. def unpack(data, destdir):
  108. """
  109. Read and check a .modpedalboard (untrusted: it comes from another unit or someone else) and
  110. write its bundle into destdir, which must exist and be empty.
  111. Returns (header, bundlepath). Raises PedalboardFileError with a message for the user.
  112. """
  113. if len(data) > MAX_PACKED_SIZE:
  114. raise PedalboardFileError("This file is too big to be a pedalboard")
  115. try:
  116. tar = tarfile.open(fileobj=io.BytesIO(data), mode="r:gz")
  117. except (tarfile.TarError, OSError, EOFError, zlib.error):
  118. raise PedalboardFileError("This is not a %s file" % EXTENSION)
  119. header = None
  120. bundlename = None
  121. contents = []
  122. total = 0
  123. try:
  124. count = 0
  125. for member in tar:
  126. count += 1
  127. if count > MAX_MEMBERS:
  128. raise PedalboardFileError("This file has too many entries to be a pedalboard")
  129. name = member.name
  130. _check_name(name)
  131. if member.isdir():
  132. continue
  133. if not member.isfile():
  134. raise PedalboardFileError("This file contains something other than a pedalboard")
  135. total += member.size
  136. if total > MAX_UNPACKED_SIZE:
  137. raise PedalboardFileError("This file is too big to be a pedalboard")
  138. content = tar.extractfile(member).read(member.size + 1)
  139. if len(content) != member.size:
  140. raise PedalboardFileError("This pedalboard file is damaged")
  141. if name == HEADER_NAME:
  142. try:
  143. header = json.loads(content.decode("utf-8"))
  144. except ValueError:
  145. raise PedalboardFileError("This pedalboard file is damaged")
  146. continue
  147. parts = name.split("/")
  148. if len(parts) < 2 or not parts[0].endswith(".pedalboard"):
  149. raise PedalboardFileError("This file contains something other than a pedalboard")
  150. if bundlename is None:
  151. bundlename = parts[0]
  152. elif bundlename != parts[0]:
  153. raise PedalboardFileError("This file contains more than one pedalboard")
  154. contents.append((parts[1:], content))
  155. except (tarfile.TarError, OSError, EOFError, zlib.error):
  156. raise PedalboardFileError("This pedalboard file is damaged")
  157. finally:
  158. tar.close()
  159. if not isinstance(header, dict):
  160. raise PedalboardFileError("This is not a %s file" % EXTENSION)
  161. fmt = header.get('format')
  162. if not isinstance(fmt, int):
  163. raise PedalboardFileError("This pedalboard file is damaged")
  164. if fmt > FORMAT_VERSION:
  165. raise PedalboardFileError("This pedalboard was made by a newer MOD OS, please update")
  166. if bundlename is None or ["manifest.ttl"] not in [parts for parts, _ in contents]:
  167. raise PedalboardFileError("This pedalboard file is damaged")
  168. if not isinstance(header.get('title'), str) or not header['title'].strip():
  169. header['title'] = bundlename[:-len(".pedalboard")]
  170. for key in ('plugins', 'files'):
  171. if not isinstance(header.get(key), list):
  172. header[key] = []
  173. bundlepath = os.path.join(destdir, bundlename)
  174. for parts, content in contents:
  175. path = os.path.join(bundlepath, *parts)
  176. folder = os.path.dirname(path)
  177. if not os.path.isdir(folder):
  178. os.makedirs(folder)
  179. with open(path, 'wb') as fh:
  180. fh.write(content)
  181. return header, bundlepath
  182. def relocate_user_files(bundlepath, source_dir, local_dir):
  183. """
  184. Point the user-file paths of an imported pedalboard at this unit's user files folder
  185. (a Dwarf keeps them in /data/user-files, MOD Desktop in the user's documents).
  186. Only the ttl files of the bundle are touched.
  187. """
  188. if not isinstance(source_dir, str) or not source_dir:
  189. return
  190. source = source_dir.rstrip("/\\")
  191. local = local_dir.rstrip("/\\")
  192. if source == local:
  193. return
  194. for relpath in _bundle_files(bundlepath):
  195. if not relpath.endswith(".ttl"):
  196. continue
  197. path = os.path.join(bundlepath, *relpath.split("/"))
  198. with open(path, 'r', encoding="utf-8", errors="surrogateescape") as fh:
  199. text = fh.read()
  200. if source not in text:
  201. continue
  202. def repl(match):
  203. return local + os.sep + match.group(1).replace("\\", "/").replace("/", os.sep)
  204. text = re.sub(re.escape(source) + r'[/\\]([^"<>\n]+)', repl, text)
  205. with open(path, 'w', encoding="utf-8", errors="surrogateescape") as fh:
  206. fh.write(text)