You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

628 lines
16KB

  1. #include "plugin.hpp"
  2. #include "system.hpp"
  3. #include "network.hpp"
  4. #include "asset.hpp"
  5. #include "string.hpp"
  6. #include "app.hpp"
  7. #include "app/common.hpp"
  8. #include "plugin/callbacks.hpp"
  9. #include "settings.hpp"
  10. #include <unistd.h>
  11. #include <sys/types.h>
  12. #include <sys/stat.h>
  13. #include <sys/param.h> // for MAXPATHLEN
  14. #include <fcntl.h>
  15. #include <thread>
  16. #include <map>
  17. #include <stdexcept>
  18. #define ZIP_STATIC
  19. #include <zip.h>
  20. #include <jansson.h>
  21. #if defined ARCH_WIN
  22. #include <windows.h>
  23. #include <direct.h>
  24. #define mkdir(_dir, _perms) _mkdir(_dir)
  25. #else
  26. #include <dlfcn.h>
  27. #endif
  28. #include <dirent.h>
  29. #include <osdialog.h>
  30. namespace rack {
  31. namespace plugin {
  32. ////////////////////
  33. // private API
  34. ////////////////////
  35. static bool loadPlugin(std::string path) {
  36. // Load plugin.json
  37. std::string metadataFilename = path + "/plugin.json";
  38. FILE *file = fopen(metadataFilename.c_str(), "r");
  39. if (!file) {
  40. WARN("Plugin metadata file %s does not exist", metadataFilename.c_str());
  41. return false;
  42. }
  43. DEFER({
  44. fclose(file);
  45. });
  46. json_error_t error;
  47. json_t *rootJ = json_loadf(file, 0, &error);
  48. if (!rootJ) {
  49. WARN("JSON parsing error at %s %d:%d %s", error.source, error.line, error.column, error.text);
  50. return false;
  51. }
  52. DEFER({
  53. json_decref(rootJ);
  54. });
  55. // Load plugin library
  56. std::string libraryFilename;
  57. #if defined ARCH_LIN
  58. libraryFilename = path + "/" + "plugin.so";
  59. #elif defined ARCH_WIN
  60. libraryFilename = path + "/" + "plugin.dll";
  61. #elif ARCH_MAC
  62. libraryFilename = path + "/" + "plugin.dylib";
  63. #endif
  64. // Check file existence
  65. if (!system::isFile(libraryFilename)) {
  66. WARN("Plugin file %s does not exist", libraryFilename.c_str());
  67. return false;
  68. }
  69. // Load dynamic/shared library
  70. #if defined ARCH_WIN
  71. SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  72. HINSTANCE handle = LoadLibrary(libraryFilename.c_str());
  73. SetErrorMode(0);
  74. if (!handle) {
  75. int error = GetLastError();
  76. WARN("Failed to load library %s: code %d", libraryFilename.c_str(), error);
  77. return false;
  78. }
  79. #else
  80. void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW);
  81. if (!handle) {
  82. WARN("Failed to load library %s: %s", libraryFilename.c_str(), dlerror());
  83. return false;
  84. }
  85. #endif
  86. // Call plugin's init() function
  87. typedef void (*InitCallback)(Plugin *);
  88. InitCallback initCallback;
  89. #if defined ARCH_WIN
  90. initCallback = (InitCallback) GetProcAddress(handle, "init");
  91. #else
  92. initCallback = (InitCallback) dlsym(handle, "init");
  93. #endif
  94. if (!initCallback) {
  95. WARN("Failed to read init() symbol in %s", libraryFilename.c_str());
  96. return false;
  97. }
  98. // Construct and initialize Plugin instance
  99. Plugin *plugin = new Plugin;
  100. plugin->path = path;
  101. plugin->handle = handle;
  102. initCallback(plugin);
  103. plugin->fromJson(rootJ);
  104. // Check slug
  105. if (!isSlugValid(plugin->slug)) {
  106. WARN("Plugin slug \"%s\" is invalid", plugin->slug.c_str());
  107. // TODO Fix memory leak with `plugin`
  108. return false;
  109. }
  110. // Reject plugin if slug already exists
  111. Plugin *oldPlugin = getPlugin(plugin->slug);
  112. if (oldPlugin) {
  113. WARN("Plugin \"%s\" is already loaded, not attempting to load it again", plugin->slug.c_str());
  114. // TODO Fix memory leak with `plugin`
  115. return false;
  116. }
  117. // Add plugin to list
  118. plugins.push_back(plugin);
  119. INFO("Loaded plugin %s v%s from %s", plugin->slug.c_str(), plugin->version.c_str(), libraryFilename.c_str());
  120. // Normalize tags
  121. for (Model *model : plugin->models) {
  122. std::vector<std::string> normalizedTags;
  123. for (const std::string &tag : model->tags) {
  124. std::string normalizedTag = normalizeTag(tag);
  125. if (!normalizedTag.empty())
  126. normalizedTags.push_back(normalizedTag);
  127. }
  128. model->tags = normalizedTags;
  129. }
  130. // Search for presets
  131. for (Model *model : plugin->models) {
  132. std::string presetDir = asset::plugin(plugin, "presets/" + model->slug);
  133. for (const std::string &presetPath : system::getEntries(presetDir)) {
  134. model->presetPaths.push_back(presetPath);
  135. }
  136. }
  137. return true;
  138. }
  139. static bool syncUpdate(const Update &update) {
  140. #if defined ARCH_WIN
  141. std::string arch = "win";
  142. #elif ARCH_MAC
  143. std::string arch = "mac";
  144. #elif defined ARCH_LIN
  145. std::string arch = "lin";
  146. #endif
  147. std::string downloadUrl = app::API_URL;
  148. downloadUrl += "/download";
  149. downloadUrl += "?token=" + network::encodeUrl(settings::token);
  150. downloadUrl += "&slug=" + network::encodeUrl(update.pluginSlug);
  151. downloadUrl += "&version=" + network::encodeUrl(update.version);
  152. downloadUrl += "&arch=" + network::encodeUrl(arch);
  153. // downloadName = name;
  154. downloadProgress = 0.0;
  155. INFO("Downloading plugin %s %s %s", update.pluginSlug.c_str(), update.version.c_str(), arch.c_str());
  156. // Download zip
  157. std::string pluginDest = asset::user("plugins/" + update.pluginSlug + ".zip");
  158. if (!network::requestDownload(downloadUrl, pluginDest, &downloadProgress)) {
  159. WARN("Plugin %s download was unsuccessful", update.pluginSlug.c_str());
  160. return false;
  161. }
  162. // downloadName = "";
  163. return true;
  164. }
  165. static void loadPlugins(std::string path) {
  166. std::string message;
  167. for (std::string pluginPath : system::getEntries(path)) {
  168. if (!system::isDirectory(pluginPath))
  169. continue;
  170. if (!loadPlugin(pluginPath)) {
  171. // Ignore bad plugins. They are reported in log.txt.
  172. }
  173. }
  174. }
  175. /** Returns 0 if successful */
  176. static int extractZipHandle(zip_t *za, const char *dir) {
  177. int err;
  178. for (int i = 0; i < zip_get_num_entries(za, 0); i++) {
  179. zip_stat_t zs;
  180. err = zip_stat_index(za, i, 0, &zs);
  181. if (err) {
  182. WARN("zip_stat_index() failed: error %d", err);
  183. return err;
  184. }
  185. int nameLen = strlen(zs.name);
  186. char path[MAXPATHLEN];
  187. snprintf(path, sizeof(path), "%s/%s", dir, zs.name);
  188. if (zs.name[nameLen - 1] == '/') {
  189. if (mkdir(path, 0755)) {
  190. if (errno != EEXIST) {
  191. WARN("mkdir(%s) failed: error %d", path, errno);
  192. return errno;
  193. }
  194. }
  195. }
  196. else {
  197. zip_file_t *zf = zip_fopen_index(za, i, 0);
  198. if (!zf) {
  199. WARN("zip_fopen_index() failed");
  200. return -1;
  201. }
  202. FILE *outFile = fopen(path, "wb");
  203. if (!outFile)
  204. continue;
  205. while (1) {
  206. char buffer[1<<15];
  207. int len = zip_fread(zf, buffer, sizeof(buffer));
  208. if (len <= 0)
  209. break;
  210. fwrite(buffer, 1, len, outFile);
  211. }
  212. err = zip_fclose(zf);
  213. if (err) {
  214. WARN("zip_fclose() failed: error %d", err);
  215. return err;
  216. }
  217. fclose(outFile);
  218. }
  219. }
  220. return 0;
  221. }
  222. /** Returns 0 if successful */
  223. static int extractZip(const char *filename, const char *path) {
  224. int err;
  225. zip_t *za = zip_open(filename, 0, &err);
  226. if (!za) {
  227. WARN("Could not open zip %s: error %d", filename, err);
  228. return err;
  229. }
  230. DEFER({
  231. zip_close(za);
  232. });
  233. err = extractZipHandle(za, path);
  234. return err;
  235. }
  236. static void extractPackages(const std::string &path) {
  237. std::string message;
  238. for (std::string packagePath : system::getEntries(path)) {
  239. if (string::filenameExtension(packagePath) != "zip")
  240. continue;
  241. INFO("Extracting package %s", packagePath.c_str());
  242. // Extract package
  243. if (extractZip(packagePath.c_str(), path.c_str())) {
  244. WARN("Package %s failed to extract", packagePath.c_str());
  245. message += string::f("Could not extract package %s\n", packagePath.c_str());
  246. continue;
  247. }
  248. // Remove package
  249. if (remove(packagePath.c_str())) {
  250. WARN("Could not delete file %s: error %d", packagePath.c_str(), errno);
  251. }
  252. }
  253. if (!message.empty()) {
  254. osdialog_message(OSDIALOG_WARNING, OSDIALOG_OK, message.c_str());
  255. }
  256. }
  257. ////////////////////
  258. // public API
  259. ////////////////////
  260. void init() {
  261. // Load Core
  262. Plugin *corePlugin = new Plugin;
  263. // This function is defined in Core/plugin.cpp
  264. ::init(corePlugin);
  265. plugins.push_back(corePlugin);
  266. // Get user plugins directory
  267. std::string pluginsDir = asset::user("plugins");
  268. mkdir(pluginsDir.c_str(), 0755);
  269. // Extract packages and load plugins
  270. extractPackages(pluginsDir);
  271. loadPlugins(pluginsDir);
  272. // Copy Fundamental package to plugins directory if Fundamental is not loaded
  273. std::string fundamentalSrc = asset::system("Fundamental.zip");
  274. std::string fundamentalDir = asset::user("plugins/Fundamental");
  275. if (!settings::devMode && !getPlugin("Fundamental") && system::isFile(fundamentalSrc)) {
  276. INFO("Extracting bundled Fundamental package");
  277. extractZip(fundamentalSrc.c_str(), pluginsDir.c_str());
  278. loadPlugin(fundamentalDir);
  279. }
  280. // TEMP
  281. // Sync in a detached thread
  282. std::thread t([]{
  283. queryUpdates();
  284. });
  285. t.detach();
  286. }
  287. void destroy() {
  288. for (Plugin *plugin : plugins) {
  289. // Free library handle
  290. #if defined ARCH_WIN
  291. if (plugin->handle)
  292. FreeLibrary((HINSTANCE) plugin->handle);
  293. #else
  294. if (plugin->handle)
  295. dlclose(plugin->handle);
  296. #endif
  297. // For some reason this segfaults.
  298. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins.
  299. // delete plugin;
  300. }
  301. plugins.clear();
  302. }
  303. void logIn(const std::string &email, const std::string &password) {
  304. loginStatus = "Logging in...";
  305. json_t *reqJ = json_object();
  306. json_object_set(reqJ, "email", json_string(email.c_str()));
  307. json_object_set(reqJ, "password", json_string(password.c_str()));
  308. std::string url = app::API_URL;
  309. url += "/token";
  310. json_t *resJ = network::requestJson(network::METHOD_POST, url, reqJ);
  311. json_decref(reqJ);
  312. if (!resJ) {
  313. loginStatus = "No response from server";
  314. return;
  315. }
  316. json_t *errorJ = json_object_get(resJ, "error");
  317. if (errorJ) {
  318. const char *errorStr = json_string_value(errorJ);
  319. loginStatus = errorStr;
  320. }
  321. else {
  322. json_t *tokenJ = json_object_get(resJ, "token");
  323. if (tokenJ) {
  324. const char *tokenStr = json_string_value(tokenJ);
  325. settings::token = tokenStr;
  326. loginStatus = "";
  327. }
  328. else {
  329. loginStatus = "No token in response";
  330. }
  331. }
  332. json_decref(resJ);
  333. }
  334. void logOut() {
  335. settings::token = "";
  336. }
  337. void queryUpdates() {
  338. if (settings::token.empty())
  339. return;
  340. updates.clear();
  341. // Get user's plugins list
  342. json_t *pluginsReqJ = json_object();
  343. json_object_set(pluginsReqJ, "token", json_string(settings::token.c_str()));
  344. std::string pluginsUrl = app::API_URL;
  345. pluginsUrl += "/plugins";
  346. json_t *pluginsResJ = network::requestJson(network::METHOD_GET, pluginsUrl, pluginsReqJ);
  347. json_decref(pluginsReqJ);
  348. if (!pluginsResJ) {
  349. WARN("Request for user's plugins failed");
  350. return;
  351. }
  352. DEFER({
  353. json_decref(pluginsResJ);
  354. });
  355. json_t *errorJ = json_object_get(pluginsResJ, "error");
  356. if (errorJ) {
  357. WARN("Request for user's plugins returned an error: %s", json_string_value(errorJ));
  358. return;
  359. }
  360. // Get community manifests
  361. std::string manifestsUrl = app::API_URL;
  362. manifestsUrl += "/community/manifests";
  363. json_t *manifestsResJ = network::requestJson(network::METHOD_GET, manifestsUrl, NULL);
  364. if (!manifestsResJ) {
  365. WARN("Request for community manifests failed");
  366. return;
  367. }
  368. DEFER({
  369. json_decref(manifestsResJ);
  370. });
  371. json_t *manifestsJ = json_object_get(manifestsResJ, "manifests");
  372. json_t *pluginsJ = json_object_get(pluginsResJ, "plugins");
  373. size_t pluginIndex;
  374. json_t *pluginJ;
  375. json_array_foreach(pluginsJ, pluginIndex, pluginJ) {
  376. Update update;
  377. // Get plugin manifest
  378. update.pluginSlug = json_string_value(pluginJ);
  379. json_t *manifestJ = json_object_get(manifestsJ, update.pluginSlug.c_str());
  380. if (!manifestJ) {
  381. WARN("VCV account has plugin %s but no manifest was found", update.pluginSlug.c_str());
  382. continue;
  383. }
  384. // Get version
  385. // TODO Change this to "version" when API changes
  386. json_t *versionJ = json_object_get(manifestJ, "latestVersion");
  387. if (!versionJ) {
  388. WARN("Plugin %s has no version in manifest", update.pluginSlug.c_str());
  389. continue;
  390. }
  391. update.version = json_string_value(versionJ);
  392. // Check if update is needed
  393. Plugin *p = getPlugin(update.pluginSlug);
  394. if (p && p->version == update.version)
  395. continue;
  396. // Check status
  397. json_t *statusJ = json_object_get(manifestJ, "status");
  398. if (!statusJ)
  399. continue;
  400. std::string status = json_string_value(statusJ);
  401. if (status != "available")
  402. continue;
  403. // Get changelog URL
  404. json_t *changelogUrlJ = json_object_get(manifestJ, "changelogUrl");
  405. if (changelogUrlJ) {
  406. update.changelogUrl = json_string_value(changelogUrlJ);
  407. }
  408. updates.push_back(update);
  409. }
  410. }
  411. void syncUpdates() {
  412. if (settings::token.empty())
  413. return;
  414. downloadProgress = 0.0;
  415. downloadName = "Updating plugins...";
  416. for (const Update &update : updates) {
  417. syncUpdate(update);
  418. }
  419. }
  420. void cancelDownload() {
  421. // TODO
  422. }
  423. bool isLoggedIn() {
  424. return settings::token != "";
  425. }
  426. Plugin *getPlugin(const std::string &pluginSlug) {
  427. for (Plugin *plugin : plugins) {
  428. if (plugin->slug == pluginSlug) {
  429. return plugin;
  430. }
  431. }
  432. return NULL;
  433. }
  434. Model *getModel(const std::string &pluginSlug, const std::string &modelSlug) {
  435. Plugin *plugin = getPlugin(pluginSlug);
  436. if (!plugin)
  437. return NULL;
  438. Model *model = plugin->getModel(modelSlug);
  439. if (!model)
  440. return NULL;
  441. return model;
  442. }
  443. /** List of allowed tags in human display form, alphabetized.
  444. All tags here should be in sentence caps for display consistency.
  445. However, tags are case-insensitive in plugin metadata.
  446. */
  447. const std::set<std::string> allowedTags = {
  448. "Arpeggiator",
  449. "Attenuator", // With a level knob and not much else.
  450. "Blank", // No parameters or ports. Serves no purpose except visual.
  451. "Chorus",
  452. "Clock generator",
  453. "Clock modulator", // Clock dividers, multipliers, etc.
  454. "Compressor", // With threshold, ratio, knee, etc parameters.
  455. "Controller", // Use only if the artist "performs" with this module. Simply having knobs is not enough. Examples: on-screen keyboard, XY pad.
  456. "Delay",
  457. "Digital",
  458. "Distortion",
  459. "Drum",
  460. "Dual", // The core functionality times two. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Dual module.
  461. "Dynamics",
  462. "Effect",
  463. "Envelope follower",
  464. "Envelope generator",
  465. "Equalizer",
  466. "Expander", // Expands the functionality of a "mother" module when placed next to it. Expanders should inherit the tags of its mother module.
  467. "External",
  468. "Flanger",
  469. "Function generator",
  470. "Granular",
  471. "LFO",
  472. "Limiter",
  473. "Logic",
  474. "Low pass gate",
  475. "MIDI",
  476. "Mixer",
  477. "Multiple",
  478. "Noise",
  479. "Panning",
  480. "Phaser",
  481. "Physical modeling",
  482. "Polyphonic",
  483. "Quad", // The core functionality times four. If multiple channels are a requirement for the module to exist (ring modulator, mixer, etc), it is not a Quad module.
  484. "Quantizer",
  485. "Random",
  486. "Recording",
  487. "Reverb",
  488. "Ring modulator",
  489. "Sample and hold",
  490. "Sampler",
  491. "Sequencer",
  492. "Slew limiter",
  493. "Switch",
  494. "Synth voice", // A synth voice must have, at the minimum, a built-in oscillator and envelope.
  495. "Tuner",
  496. "Utility", // Serves only extremely basic functions, like inverting, max, min, multiplying by 2, etc.
  497. "VCA",
  498. "VCF",
  499. "VCO",
  500. "Visual",
  501. "Vocoder",
  502. "Waveshaper",
  503. };
  504. /** List of common synonyms for allowed tags.
  505. Aliases and tags must be lowercase.
  506. */
  507. const std::map<std::string, std::string> tagAliases = {
  508. {"amplifier", "vca"},
  509. {"clock", "clock generator"},
  510. {"drums", "drum"},
  511. {"eq", "equalizer"},
  512. {"filter", "vcf"},
  513. {"low frequency oscillator", "lfo"},
  514. {"lowpass gate", "low pass gate"},
  515. {"oscillator", "vco"},
  516. {"percussion", "drum"},
  517. {"poly", "polyphonic"},
  518. {"s&h", "sample and hold"},
  519. {"voltage controlled amplifier", "vca"},
  520. {"voltage controlled filter", "vcf"},
  521. {"voltage controlled oscillator", "vco"},
  522. };
  523. std::string normalizeTag(const std::string &tag) {
  524. std::string lowercaseTag = string::lowercase(tag);
  525. // Transform aliases
  526. auto it = tagAliases.find(lowercaseTag);
  527. if (it != tagAliases.end())
  528. lowercaseTag = it->second;
  529. // Find allowed tag
  530. for (const std::string &allowedTag : allowedTags) {
  531. if (lowercaseTag == string::lowercase(allowedTag))
  532. return allowedTag;
  533. }
  534. return "";
  535. }
  536. bool isSlugValid(const std::string &slug) {
  537. for (char c : slug) {
  538. if (!(std::isalnum(c) || c == '-' || c == '_'))
  539. return false;
  540. }
  541. return true;
  542. }
  543. std::vector<Plugin*> plugins;
  544. std::string loginStatus;
  545. std::vector<Update> updates;
  546. float downloadProgress = 0.f;
  547. std::string downloadName;
  548. } // namespace plugin
  549. } // namespace rack