__init__.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. import os
  5. import sys
  6. import re
  7. import json
  8. import shutil
  9. from datetime import datetime
  10. from functools import wraps
  11. from unicodedata import normalize
  12. from mod.settings import HARDWARE_DESC_FILE
  13. WINDOWS = sys.platform == 'win32'
  14. def jsoncall(method):
  15. @wraps(method)
  16. def wrapper(self, *args, **kwargs):
  17. body = self.request.body
  18. self.request.jsoncall = True
  19. if body is not None:
  20. decoded = body.decode()
  21. if decoded:
  22. self.request.body = json.loads(decoded)
  23. result = method(self, *args, **kwargs)
  24. if result is not None:
  25. self.set_header('Content-Type', 'application/json; charset=UTF-8')
  26. self.write(json.dumps(result, default=json_handler))
  27. else:
  28. self.set_header('Content-Type', 'text/plain; charset=UTF-8')
  29. self.set_status(204)
  30. return wrapper
  31. def json_handler(obj):
  32. if isinstance(obj, datetime):
  33. return obj.isoformat()
  34. return None
  35. def os_sync():
  36. if not WINDOWS:
  37. os.sync()
  38. def check_environment():
  39. from mod.settings import (LV2_PEDALBOARDS_DIR,
  40. DEFAULT_PEDALBOARD, DEFAULT_PEDALBOARD_COPY,
  41. DATA_DIR, DOWNLOAD_TMP_DIR, PEDALBOARD_TMP_DIR,
  42. KEYS_PATH, USER_BANKS_JSON_FILE, FAVORITES_JSON_FILE,
  43. UPDATE_CC_FIRMWARE_FILE, UPDATE_MOD_OS_FILE, UPDATE_MOD_OS_HERLPER_FILE,
  44. CAPTURE_PATH, PLAYBACK_PATH)
  45. # create temp dirs
  46. if not os.path.exists(DOWNLOAD_TMP_DIR):
  47. os.makedirs(DOWNLOAD_TMP_DIR)
  48. if os.path.exists(PEDALBOARD_TMP_DIR):
  49. try:
  50. shutil.rmtree(PEDALBOARD_TMP_DIR)
  51. except OSError:
  52. pass
  53. else:
  54. os.makedirs(PEDALBOARD_TMP_DIR)
  55. else:
  56. os.makedirs(PEDALBOARD_TMP_DIR)
  57. # remove temp files
  58. for path in (CAPTURE_PATH, PLAYBACK_PATH, UPDATE_CC_FIRMWARE_FILE):
  59. if os.path.exists(path):
  60. os.remove(path)
  61. # check RW access
  62. if os.path.exists(DATA_DIR):
  63. if not os.access(DATA_DIR, os.W_OK):
  64. print("ERROR: No write access to data dir '%s'" % DATA_DIR)
  65. return False
  66. else:
  67. try:
  68. os.makedirs(DATA_DIR)
  69. except OSError:
  70. print("ERROR: Cannot create data dir '%s'" % DATA_DIR)
  71. return False
  72. # create needed dirs and files
  73. if not os.path.exists(KEYS_PATH):
  74. os.makedirs(KEYS_PATH)
  75. if not os.path.exists(LV2_PEDALBOARDS_DIR):
  76. os.makedirs(LV2_PEDALBOARDS_DIR)
  77. if os.path.exists(DEFAULT_PEDALBOARD_COPY) and not os.path.exists(DEFAULT_PEDALBOARD):
  78. shutil.copytree(DEFAULT_PEDALBOARD_COPY, DEFAULT_PEDALBOARD)
  79. if not os.path.exists(USER_BANKS_JSON_FILE):
  80. with open(USER_BANKS_JSON_FILE, 'w') as fh:
  81. fh.write("[]")
  82. if not os.path.exists(FAVORITES_JSON_FILE):
  83. with open(FAVORITES_JSON_FILE, 'w') as fh:
  84. fh.write("[]")
  85. # remove previous update file
  86. if os.path.exists(UPDATE_MOD_OS_FILE) and not os.path.exists("/root/check-upgrade-system"):
  87. os.remove(UPDATE_MOD_OS_FILE)
  88. os_sync()
  89. if os.path.exists(UPDATE_MOD_OS_HERLPER_FILE):
  90. os.remove(UPDATE_MOD_OS_HERLPER_FILE)
  91. os_sync()
  92. return True
  93. def get_nearest_valid_scalepoint_value(value, options):
  94. if not options:
  95. return value
  96. # find a value that matches
  97. for i, (ovalue, _) in enumerate(options):
  98. if ovalue == value:
  99. ivalue = i
  100. return (i, ovalue)
  101. # find a value within a small range
  102. for i, (ovalue, _) in enumerate(options):
  103. if abs(ovalue - value) <= 0.0001:
  104. ivalue = i
  105. return (i, ovalue)
  106. # find closest match
  107. smallestdiff = None
  108. smallestpos = 0
  109. for i, (ovalue, _) in enumerate(options):
  110. diff = abs(ovalue - value)
  111. if smallestdiff is None or diff < smallestdiff:
  112. smallestdiff = diff
  113. smallestpos = i
  114. return (smallestpos, options[smallestpos][0])
  115. def get_unique_name(name, names):
  116. if name not in names:
  117. return None
  118. regex = r'^.* \(([0-9]*)\)$'
  119. match = re.match(regex, name)
  120. if match is None:
  121. name += ' (2)'
  122. if name in names:
  123. match = re.match(regex, name)
  124. while match is not None:
  125. num = int(match.groups()[0])
  126. name = name[:name.rfind('(')] + '({})'.format(num + 1)
  127. if name not in names:
  128. return name
  129. match = re.match(regex, name)
  130. return name
  131. def normalize_for_hw(string, limit = 31):
  132. return '"%s"' % (
  133. normalize('NFKD',string).encode('ascii','ignore').decode('ascii','ignore').replace('"','')[:limit].upper()
  134. )
  135. def safe_json_load(path, objtype):
  136. if not os.path.exists(path):
  137. return objtype()
  138. try:
  139. with open(path, 'r') as fh:
  140. data = json.load(fh)
  141. except:
  142. return objtype()
  143. if not isinstance(data, objtype):
  144. return objtype()
  145. return data
  146. def symbolify(name):
  147. if len(name) == 0:
  148. return "_"
  149. name = normalize('NFKD', name).encode('ascii', 'ignore').decode('ascii', 'ignore')
  150. name = re.sub("[^_a-zA-Z0-9]+", "_", name)
  151. if name[0].isdigit():
  152. name = "_" + name
  153. return name
  154. def get_hardware_descriptor():
  155. return safe_json_load(HARDWARE_DESC_FILE, dict)
  156. def get_hardware_actuators():
  157. return get_hardware_descriptor().get('actuators', [])
  158. def read_file_contents(fh, fallback):
  159. if fh is None:
  160. return fallback
  161. fh.seek(0)
  162. return fh.read().strip() or fallback
  163. class DummyFile(object):
  164. def write(self, _):
  165. return
  166. def flush(self):
  167. return
  168. def close(self):
  169. return
  170. class TextFileFlusher(object):
  171. def __init__(self, filename):
  172. self.filename = filename
  173. self.filehandle = None
  174. def __enter__(self):
  175. try:
  176. self.filehandle = open(self.filename+".tmp", 'w', 1)
  177. except OSError:
  178. print("ERROR: failed to open", self.filename)
  179. self.filehandle = DummyFile()
  180. return self.filehandle
  181. def __exit__(self, typ, val, tb):
  182. if self.filehandle is None or isinstance(self.filehandle, DummyFile):
  183. return
  184. self.filehandle.flush()
  185. os.fsync(self.filehandle)
  186. self.filehandle.close()
  187. if WINDOWS and os.path.exists(self.filename):
  188. os.remove(self.filename)
  189. os.rename(self.filename+".tmp", self.filename)