preset_share.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. # Plugin preset files (.modpreset) for the Export / Import buttons of the preset bar.
  5. #
  6. # A .modpreset is a tar.gz with:
  7. # modpreset.json what the preset is for (plugin URI, versions, name)
  8. # <name>.lv2/manifest.ttl the LV2 preset bundle, as mod-host saves it
  9. # <name>.lv2/<name>.ttl
  10. #
  11. # Only .ttl files go in: files a preset points to (NAM models, IRs, samples) are left out.
  12. # Must stay Python 3.4 compatible (device image).
  13. import io
  14. import json
  15. import os
  16. import posixpath
  17. import tarfile
  18. import time
  19. import zlib
  20. FORMAT_VERSION = 1
  21. EXTENSION = ".modpreset"
  22. HEADER_NAME = "modpreset.json"
  23. MANIFEST_NAME = "manifest.ttl"
  24. # a preset is a few KB; anything near these limits is not a preset
  25. MAX_FILE_SIZE = 1024 * 1024
  26. MAX_MEMBERS = 8
  27. class PresetFileError(Exception):
  28. pass
  29. def make_header(plugin_uri, plugin_version, name, os_version, platform):
  30. return {
  31. 'format': FORMAT_VERSION,
  32. 'plugin_uri': plugin_uri,
  33. 'plugin_version': plugin_version,
  34. 'name': name,
  35. 'os_version': os_version,
  36. 'platform': platform,
  37. 'created': time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
  38. }
  39. def _add_bytes(tar, name, data):
  40. info = tarfile.TarInfo(name)
  41. info.size = len(data)
  42. info.mtime = int(time.time())
  43. info.mode = 0o644
  44. tar.addfile(info, io.BytesIO(data))
  45. def pack(bundlepath, header):
  46. """Pack a preset bundle. Returns (data, left_out), left_out = names that were not .ttl files."""
  47. bundlename = os.path.basename(bundlepath.rstrip("/"))
  48. ttlfiles = []
  49. left_out = []
  50. for name in sorted(os.listdir(bundlepath)):
  51. path = os.path.join(bundlepath, name)
  52. if name.endswith(".ttl") and os.path.isfile(path) and not os.path.islink(path):
  53. ttlfiles.append(name)
  54. else:
  55. left_out.append(name)
  56. if MANIFEST_NAME not in ttlfiles or len(ttlfiles) < 2:
  57. raise PresetFileError("The saved preset is incomplete")
  58. header = dict(header)
  59. header['files_left_out'] = left_out
  60. buf = io.BytesIO()
  61. with tarfile.open(fileobj=buf, mode="w:gz") as tar:
  62. _add_bytes(tar, HEADER_NAME, json.dumps(header, indent=2, sort_keys=True).encode("utf-8"))
  63. for name in ttlfiles:
  64. with open(os.path.join(bundlepath, name), 'rb') as fh:
  65. _add_bytes(tar, "%s/%s" % (bundlename, name), fh.read())
  66. return buf.getvalue(), left_out
  67. def unpack(data, plugin_uri):
  68. """
  69. Read and check a .modpreset (untrusted: it comes from someone else's unit).
  70. Nothing is written to disk here. Returns a dict with:
  71. header, preset_file (name of the preset .ttl), files ({name: bytes}, manifest included)
  72. Raises PresetFileError with a message for the user.
  73. """
  74. if len(data) > MAX_FILE_SIZE:
  75. raise PresetFileError("This file is too big to be a preset")
  76. header = None
  77. bundlename = None
  78. files = {}
  79. total = 0
  80. try:
  81. tar = tarfile.open(fileobj=io.BytesIO(data), mode="r:gz")
  82. except (tarfile.TarError, OSError, EOFError, zlib.error):
  83. raise PresetFileError("This is not a %s file" % EXTENSION)
  84. try:
  85. count = 0
  86. for member in tar:
  87. count += 1
  88. if count > MAX_MEMBERS:
  89. raise PresetFileError("This file has too many entries to be a preset")
  90. if not member.isfile():
  91. raise PresetFileError("This file contains something other than a preset")
  92. name = member.name
  93. if "\\" in name or name.startswith("/") or posixpath.normpath(name) != name:
  94. raise PresetFileError("This file contains an invalid path")
  95. total += member.size
  96. if total > MAX_FILE_SIZE:
  97. raise PresetFileError("This file is too big to be a preset")
  98. content = tar.extractfile(member).read(MAX_FILE_SIZE + 1)
  99. parts = name.split("/")
  100. if parts == [HEADER_NAME]:
  101. try:
  102. header = json.loads(content.decode("utf-8"))
  103. except ValueError:
  104. raise PresetFileError("This preset file is damaged")
  105. continue
  106. if len(parts) != 2 or not parts[0].endswith(".lv2") or not parts[1].endswith(".ttl"):
  107. raise PresetFileError("This file contains something other than a preset")
  108. if parts[1].startswith("."):
  109. raise PresetFileError("This file contains an invalid path")
  110. if bundlename is None:
  111. bundlename = parts[0]
  112. elif bundlename != parts[0]:
  113. raise PresetFileError("This file contains more than one preset")
  114. files[parts[1]] = content
  115. except (tarfile.TarError, OSError, EOFError, zlib.error):
  116. raise PresetFileError("This preset file is damaged")
  117. finally:
  118. tar.close()
  119. if not isinstance(header, dict):
  120. raise PresetFileError("This is not a %s file" % EXTENSION)
  121. fmt = header.get('format')
  122. if not isinstance(fmt, int):
  123. raise PresetFileError("This preset file is damaged")
  124. if fmt > FORMAT_VERSION:
  125. raise PresetFileError("This preset was made by a newer MOD OS, please update")
  126. if header.get('plugin_uri') != plugin_uri:
  127. raise PresetFileError("This preset is for another plugin (%s)" % header.get('plugin_uri'))
  128. presetfiles = [name for name in files if name != MANIFEST_NAME]
  129. if MANIFEST_NAME not in files or len(presetfiles) != 1:
  130. raise PresetFileError("This preset file is damaged")
  131. if not isinstance(header.get('name'), str) or not header['name'].strip():
  132. header['name'] = presetfiles[0][:-4]
  133. return {
  134. 'header': header,
  135. 'preset_file': presetfiles[0],
  136. 'files': files,
  137. }