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.

413 lines
8.5KB

  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <sys/param.h> // for MAXPATHLEN
  8. #include <fcntl.h>
  9. #include <zip.h>
  10. #include <jansson.h>
  11. #if ARCH_WIN
  12. #include <windows.h>
  13. #include <direct.h>
  14. #define mkdir(_dir, _perms) _mkdir(_dir)
  15. #else
  16. #include <dlfcn.h>
  17. #endif
  18. #include <dirent.h>
  19. #include "plugin.hpp"
  20. #include "app.hpp"
  21. #include "asset.hpp"
  22. #include "util/request.hpp"
  23. namespace rack {
  24. std::list<Plugin*> gPlugins;
  25. std::string gToken;
  26. std::string gTagNames[NUM_TAGS] = {
  27. "Amplifier/VCA",
  28. "Attenuator",
  29. "Blank",
  30. "Clock",
  31. "Controller",
  32. "Delay",
  33. "Digital",
  34. "Distortion",
  35. "Drum",
  36. "Dual/Stereo",
  37. "Dynamics",
  38. "Effect",
  39. "Envelope Follower",
  40. "Envelope Generator",
  41. "Equalizer",
  42. "External",
  43. "Filter/VCF",
  44. "Function Generator",
  45. "Granular",
  46. "LFO",
  47. "Logic",
  48. "Low Pass Gate",
  49. "MIDI",
  50. "Mixer",
  51. "Multiple",
  52. "Noise",
  53. "Oscillator/VCO",
  54. "Panning",
  55. "Quad",
  56. "Quantizer",
  57. "Random",
  58. "Reverb",
  59. "Ring Modulator",
  60. "Sample and Hold",
  61. "Sampler",
  62. "Sequencer",
  63. "Slew Limiter",
  64. "Switch",
  65. "Synth Voice",
  66. "Tuner",
  67. "Utility",
  68. "Visual",
  69. "Waveshaper",
  70. };
  71. static bool isDownloading = false;
  72. static float downloadProgress = 0.0;
  73. static std::string downloadName;
  74. static std::string loginStatus;
  75. Plugin::~Plugin() {
  76. for (Model *model : models) {
  77. delete model;
  78. }
  79. }
  80. void Plugin::addModel(Model *model) {
  81. assert(!model->plugin);
  82. model->plugin = this;
  83. models.push_back(model);
  84. }
  85. static int loadPlugin(std::string path) {
  86. std::string libraryFilename;
  87. #if ARCH_LIN
  88. libraryFilename = path + "/" + "plugin.so";
  89. #elif ARCH_WIN
  90. libraryFilename = path + "/" + "plugin.dll";
  91. #elif ARCH_MAC
  92. libraryFilename = path + "/" + "plugin.dylib";
  93. #endif
  94. // Load dynamic/shared library
  95. #if ARCH_WIN
  96. SetErrorMode(SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS);
  97. HINSTANCE handle = LoadLibrary(libraryFilename.c_str());
  98. SetErrorMode(0);
  99. if (!handle) {
  100. int error = GetLastError();
  101. warn("Failed to load library %s: %d", libraryFilename.c_str(), error);
  102. return -1;
  103. }
  104. #elif ARCH_LIN || ARCH_MAC
  105. void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW);
  106. if (!handle) {
  107. warn("Failed to load library %s: %s", libraryFilename.c_str(), dlerror());
  108. return -1;
  109. }
  110. #endif
  111. // Call plugin's init() function
  112. typedef void (*InitCallback)(Plugin *);
  113. InitCallback initCallback;
  114. #if ARCH_WIN
  115. initCallback = (InitCallback) GetProcAddress(handle, "init");
  116. #elif ARCH_LIN || ARCH_MAC
  117. initCallback = (InitCallback) dlsym(handle, "init");
  118. #endif
  119. if (!initCallback) {
  120. warn("Failed to read init() symbol in %s", libraryFilename.c_str());
  121. return -2;
  122. }
  123. // Construct and initialize Plugin instance
  124. Plugin *plugin = new Plugin();
  125. plugin->path = path;
  126. plugin->handle = handle;
  127. initCallback(plugin);
  128. // Add plugin to list
  129. gPlugins.push_back(plugin);
  130. info("Loaded plugin %s", libraryFilename.c_str());
  131. return 0;
  132. }
  133. static void loadPlugins(std::string path) {
  134. DIR *dir = opendir(path.c_str());
  135. if (dir) {
  136. struct dirent *d;
  137. while ((d = readdir(dir))) {
  138. if (d->d_name[0] == '.')
  139. continue;
  140. loadPlugin(path + "/" + d->d_name);
  141. }
  142. closedir(dir);
  143. }
  144. }
  145. ////////////////////
  146. // plugin helpers
  147. ////////////////////
  148. static int extractZipHandle(zip_t *za, const char *dir) {
  149. int err = 0;
  150. for (int i = 0; i < zip_get_num_entries(za, 0); i++) {
  151. zip_stat_t zs;
  152. err = zip_stat_index(za, i, 0, &zs);
  153. if (err)
  154. return err;
  155. int nameLen = strlen(zs.name);
  156. char path[MAXPATHLEN];
  157. snprintf(path, sizeof(path), "%s/%s", dir, zs.name);
  158. if (zs.name[nameLen - 1] == '/') {
  159. err = mkdir(path, 0755);
  160. if (err && errno != EEXIST)
  161. return err;
  162. }
  163. else {
  164. zip_file_t *zf = zip_fopen_index(za, i, 0);
  165. if (!zf)
  166. return 1;
  167. FILE *outFile = fopen(path, "wb");
  168. if (!outFile)
  169. continue;
  170. while (1) {
  171. char buffer[4096];
  172. int len = zip_fread(zf, buffer, sizeof(buffer));
  173. if (len <= 0)
  174. break;
  175. fwrite(buffer, 1, len, outFile);
  176. }
  177. err = zip_fclose(zf);
  178. if (err)
  179. return err;
  180. fclose(outFile);
  181. }
  182. }
  183. return 0;
  184. }
  185. static int extractZip(const char *filename, const char *dir) {
  186. int err = 0;
  187. zip_t *za = zip_open(filename, 0, &err);
  188. if (!za)
  189. return 1;
  190. if (!err) {
  191. err = extractZipHandle(za, dir);
  192. }
  193. zip_close(za);
  194. return err;
  195. }
  196. static void refreshPurchase(json_t *pluginJ) {
  197. json_t *slugJ = json_object_get(pluginJ, "slug");
  198. if (!slugJ) return;
  199. std::string slug = json_string_value(slugJ);
  200. json_t *nameJ = json_object_get(pluginJ, "name");
  201. if (!nameJ) return;
  202. std::string name = json_string_value(nameJ);
  203. json_t *versionJ = json_object_get(pluginJ, "version");
  204. if (!versionJ) return;
  205. std::string version = json_string_value(versionJ);
  206. // Check whether the plugin is already loaded
  207. for (Plugin *plugin : gPlugins) {
  208. if (plugin->slug == slug && plugin->version == version) {
  209. return;
  210. }
  211. }
  212. // Append token and version to download URL
  213. std::string url = gApiHost;
  214. url += "/download";
  215. url += "?product=";
  216. url += slug;
  217. url += "&version=";
  218. url += requestEscape(gApplicationVersion);
  219. url += "&token=";
  220. url += requestEscape(gToken);
  221. // If plugin is not loaded, download the zip file to /plugins
  222. downloadName = name;
  223. downloadProgress = 0.0;
  224. // Download zip
  225. std::string pluginsDir = assetLocal("plugins");
  226. std::string pluginPath = pluginsDir + "/" + slug;
  227. std::string zipPath = pluginPath + ".zip";
  228. bool success = requestDownload(url, zipPath, &downloadProgress);
  229. if (success) {
  230. // Unzip file
  231. int err = extractZip(zipPath.c_str(), pluginsDir.c_str());
  232. if (!err) {
  233. // Delete zip
  234. remove(zipPath.c_str());
  235. // Load plugin
  236. loadPlugin(pluginPath);
  237. }
  238. }
  239. downloadName = "";
  240. }
  241. ////////////////////
  242. // plugin API
  243. ////////////////////
  244. void pluginInit() {
  245. // Load core
  246. // This function is defined in core.cpp
  247. Plugin *coreManufacturer = new Plugin();
  248. init(coreManufacturer);
  249. gPlugins.push_back(coreManufacturer);
  250. // Load plugins from global directory
  251. std::string globalPlugins = assetGlobal("plugins");
  252. info("Loading plugins from %s", globalPlugins.c_str());
  253. loadPlugins(globalPlugins);
  254. // Load plugins from local directory
  255. std::string localPlugins = assetLocal("plugins");
  256. if (globalPlugins != localPlugins) {
  257. mkdir(localPlugins.c_str(), 0755);
  258. info("Loading plugins from %s", localPlugins.c_str());
  259. loadPlugins(localPlugins);
  260. }
  261. }
  262. void pluginDestroy() {
  263. for (Plugin *plugin : gPlugins) {
  264. // Free library handle
  265. #if ARCH_WIN
  266. if (plugin->handle)
  267. FreeLibrary((HINSTANCE)plugin->handle);
  268. #elif ARCH_LIN || ARCH_MAC
  269. if (plugin->handle)
  270. dlclose(plugin->handle);
  271. #endif
  272. // For some reason this segfaults.
  273. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins.
  274. // delete plugin;
  275. }
  276. gPlugins.clear();
  277. }
  278. void pluginLogIn(std::string email, std::string password) {
  279. json_t *reqJ = json_object();
  280. json_object_set(reqJ, "email", json_string(email.c_str()));
  281. json_object_set(reqJ, "password", json_string(password.c_str()));
  282. json_t *resJ = requestJson(METHOD_POST, gApiHost + "/token", reqJ);
  283. json_decref(reqJ);
  284. if (resJ) {
  285. json_t *errorJ = json_object_get(resJ, "error");
  286. if (errorJ) {
  287. const char *errorStr = json_string_value(errorJ);
  288. loginStatus = errorStr;
  289. }
  290. else {
  291. json_t *tokenJ = json_object_get(resJ, "token");
  292. if (tokenJ) {
  293. const char *tokenStr = json_string_value(tokenJ);
  294. gToken = tokenStr;
  295. loginStatus = "";
  296. }
  297. }
  298. json_decref(resJ);
  299. }
  300. }
  301. void pluginLogOut() {
  302. gToken = "";
  303. }
  304. void pluginRefresh() {
  305. if (gToken.empty())
  306. return;
  307. isDownloading = true;
  308. downloadProgress = 0.0;
  309. downloadName = "";
  310. json_t *reqJ = json_object();
  311. json_object_set(reqJ, "version", json_string(gApplicationVersion.c_str()));
  312. json_object_set(reqJ, "token", json_string(gToken.c_str()));
  313. json_t *resJ = requestJson(METHOD_GET, gApiHost + "/purchases", reqJ);
  314. json_decref(reqJ);
  315. if (resJ) {
  316. json_t *errorJ = json_object_get(resJ, "error");
  317. if (errorJ) {
  318. const char *errorStr = json_string_value(errorJ);
  319. warn("Plugin refresh error: %s", errorStr);
  320. }
  321. else {
  322. json_t *purchasesJ = json_object_get(resJ, "purchases");
  323. size_t index;
  324. json_t *purchaseJ;
  325. json_array_foreach(purchasesJ, index, purchaseJ) {
  326. refreshPurchase(purchaseJ);
  327. }
  328. }
  329. json_decref(resJ);
  330. }
  331. isDownloading = false;
  332. }
  333. void pluginCancelDownload() {
  334. // TODO
  335. }
  336. bool pluginIsLoggedIn() {
  337. return gToken != "";
  338. }
  339. bool pluginIsDownloading() {
  340. return isDownloading;
  341. }
  342. float pluginGetDownloadProgress() {
  343. return downloadProgress;
  344. }
  345. std::string pluginGetDownloadName() {
  346. return downloadName;
  347. }
  348. std::string pluginGetLoginStatus() {
  349. return loginStatus;
  350. }
  351. } // namespace rack