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.

410 lines
8.4KB

  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. HINSTANCE handle = LoadLibrary(libraryFilename.c_str());
  97. if (!handle) {
  98. int error = GetLastError();
  99. warn("Failed to load library %s: %d", libraryFilename.c_str(), error);
  100. return -1;
  101. }
  102. #elif ARCH_LIN || ARCH_MAC
  103. void *handle = dlopen(libraryFilename.c_str(), RTLD_NOW);
  104. if (!handle) {
  105. warn("Failed to load library %s: %s", libraryFilename.c_str(), dlerror());
  106. return -1;
  107. }
  108. #endif
  109. // Call plugin's init() function
  110. typedef void (*InitCallback)(Plugin *);
  111. InitCallback initCallback;
  112. #if ARCH_WIN
  113. initCallback = (InitCallback) GetProcAddress(handle, "init");
  114. #elif ARCH_LIN || ARCH_MAC
  115. initCallback = (InitCallback) dlsym(handle, "init");
  116. #endif
  117. if (!initCallback) {
  118. warn("Failed to read init() symbol in %s", libraryFilename.c_str());
  119. return -2;
  120. }
  121. // Construct and initialize Plugin instance
  122. Plugin *plugin = new Plugin();
  123. plugin->path = path;
  124. plugin->handle = handle;
  125. initCallback(plugin);
  126. // Add plugin to list
  127. gPlugins.push_back(plugin);
  128. info("Loaded plugin %s", libraryFilename.c_str());
  129. return 0;
  130. }
  131. static void loadPlugins(std::string path) {
  132. DIR *dir = opendir(path.c_str());
  133. if (dir) {
  134. struct dirent *d;
  135. while ((d = readdir(dir))) {
  136. if (d->d_name[0] == '.')
  137. continue;
  138. loadPlugin(path + "/" + d->d_name);
  139. }
  140. closedir(dir);
  141. }
  142. }
  143. ////////////////////
  144. // plugin helpers
  145. ////////////////////
  146. static int extractZipHandle(zip_t *za, const char *dir) {
  147. int err = 0;
  148. for (int i = 0; i < zip_get_num_entries(za, 0); i++) {
  149. zip_stat_t zs;
  150. err = zip_stat_index(za, i, 0, &zs);
  151. if (err)
  152. return err;
  153. int nameLen = strlen(zs.name);
  154. char path[MAXPATHLEN];
  155. snprintf(path, sizeof(path), "%s/%s", dir, zs.name);
  156. if (zs.name[nameLen - 1] == '/') {
  157. err = mkdir(path, 0755);
  158. if (err && errno != EEXIST)
  159. return err;
  160. }
  161. else {
  162. zip_file_t *zf = zip_fopen_index(za, i, 0);
  163. if (!zf)
  164. return 1;
  165. FILE *outFile = fopen(path, "wb");
  166. if (!outFile)
  167. continue;
  168. while (1) {
  169. char buffer[4096];
  170. int len = zip_fread(zf, buffer, sizeof(buffer));
  171. if (len <= 0)
  172. break;
  173. fwrite(buffer, 1, len, outFile);
  174. }
  175. err = zip_fclose(zf);
  176. if (err)
  177. return err;
  178. fclose(outFile);
  179. }
  180. }
  181. return 0;
  182. }
  183. static int extractZip(const char *filename, const char *dir) {
  184. int err = 0;
  185. zip_t *za = zip_open(filename, 0, &err);
  186. if (!za)
  187. return 1;
  188. if (!err) {
  189. err = extractZipHandle(za, dir);
  190. }
  191. zip_close(za);
  192. return err;
  193. }
  194. static void refreshPurchase(json_t *pluginJ) {
  195. json_t *slugJ = json_object_get(pluginJ, "slug");
  196. if (!slugJ) return;
  197. std::string slug = json_string_value(slugJ);
  198. json_t *nameJ = json_object_get(pluginJ, "name");
  199. if (!nameJ) return;
  200. std::string name = json_string_value(nameJ);
  201. json_t *versionJ = json_object_get(pluginJ, "version");
  202. if (!versionJ) return;
  203. std::string version = json_string_value(versionJ);
  204. // Check whether the plugin is already loaded
  205. for (Plugin *plugin : gPlugins) {
  206. if (plugin->slug == slug && plugin->version == version) {
  207. return;
  208. }
  209. }
  210. // Append token and version to download URL
  211. std::string url = gApiHost;
  212. url += "/download";
  213. url += "?product=";
  214. url += slug;
  215. url += "&version=";
  216. url += requestEscape(gApplicationVersion);
  217. url += "&token=";
  218. url += requestEscape(gToken);
  219. // If plugin is not loaded, download the zip file to /plugins
  220. downloadName = name;
  221. downloadProgress = 0.0;
  222. // Download zip
  223. std::string pluginsDir = assetLocal("plugins");
  224. std::string pluginPath = pluginsDir + "/" + slug;
  225. std::string zipPath = pluginPath + ".zip";
  226. bool success = requestDownload(url, zipPath, &downloadProgress);
  227. if (success) {
  228. // Unzip file
  229. int err = extractZip(zipPath.c_str(), pluginsDir.c_str());
  230. if (!err) {
  231. // Delete zip
  232. remove(zipPath.c_str());
  233. // Load plugin
  234. loadPlugin(pluginPath);
  235. }
  236. }
  237. downloadName = "";
  238. }
  239. ////////////////////
  240. // plugin API
  241. ////////////////////
  242. void pluginInit() {
  243. // Load core
  244. // This function is defined in core.cpp
  245. Plugin *coreManufacturer = new Plugin();
  246. init(coreManufacturer);
  247. gPlugins.push_back(coreManufacturer);
  248. // Load plugins from global directory
  249. std::string globalPlugins = assetGlobal("plugins");
  250. info("Loading plugins from %s", globalPlugins.c_str());
  251. loadPlugins(globalPlugins);
  252. // Load plugins from local directory
  253. std::string localPlugins = assetLocal("plugins");
  254. if (globalPlugins != localPlugins) {
  255. mkdir(localPlugins.c_str(), 0755);
  256. info("Loading plugins from %s", localPlugins.c_str());
  257. loadPlugins(localPlugins);
  258. }
  259. }
  260. void pluginDestroy() {
  261. for (Plugin *plugin : gPlugins) {
  262. // Free library handle
  263. #if ARCH_WIN
  264. if (plugin->handle)
  265. FreeLibrary((HINSTANCE)plugin->handle);
  266. #elif ARCH_LIN || ARCH_MAC
  267. if (plugin->handle)
  268. dlclose(plugin->handle);
  269. #endif
  270. // For some reason this segfaults.
  271. // It might be best to let them leak anyway, because "crash on exit" issues would occur with badly-written plugins.
  272. // delete plugin;
  273. }
  274. gPlugins.clear();
  275. }
  276. void pluginLogIn(std::string email, std::string password) {
  277. json_t *reqJ = json_object();
  278. json_object_set(reqJ, "email", json_string(email.c_str()));
  279. json_object_set(reqJ, "password", json_string(password.c_str()));
  280. json_t *resJ = requestJson(METHOD_POST, gApiHost + "/token", reqJ);
  281. json_decref(reqJ);
  282. if (resJ) {
  283. json_t *errorJ = json_object_get(resJ, "error");
  284. if (errorJ) {
  285. const char *errorStr = json_string_value(errorJ);
  286. loginStatus = errorStr;
  287. }
  288. else {
  289. json_t *tokenJ = json_object_get(resJ, "token");
  290. if (tokenJ) {
  291. const char *tokenStr = json_string_value(tokenJ);
  292. gToken = tokenStr;
  293. loginStatus = "";
  294. }
  295. }
  296. json_decref(resJ);
  297. }
  298. }
  299. void pluginLogOut() {
  300. gToken = "";
  301. }
  302. void pluginRefresh() {
  303. if (gToken.empty())
  304. return;
  305. isDownloading = true;
  306. downloadProgress = 0.0;
  307. downloadName = "";
  308. json_t *reqJ = json_object();
  309. json_object_set(reqJ, "token", json_string(gToken.c_str()));
  310. json_t *resJ = requestJson(METHOD_GET, gApiHost + "/purchases", reqJ);
  311. json_decref(reqJ);
  312. if (resJ) {
  313. json_t *errorJ = json_object_get(resJ, "error");
  314. if (errorJ) {
  315. const char *errorStr = json_string_value(errorJ);
  316. warn("Plugin refresh error: %s", errorStr);
  317. }
  318. else {
  319. json_t *purchasesJ = json_object_get(resJ, "purchases");
  320. size_t index;
  321. json_t *purchaseJ;
  322. json_array_foreach(purchasesJ, index, purchaseJ) {
  323. refreshPurchase(purchaseJ);
  324. }
  325. }
  326. json_decref(resJ);
  327. }
  328. isDownloading = false;
  329. }
  330. void pluginCancelDownload() {
  331. // TODO
  332. }
  333. bool pluginIsLoggedIn() {
  334. return gToken != "";
  335. }
  336. bool pluginIsDownloading() {
  337. return isDownloading;
  338. }
  339. float pluginGetDownloadProgress() {
  340. return downloadProgress;
  341. }
  342. std::string pluginGetDownloadName() {
  343. return downloadName;
  344. }
  345. std::string pluginGetLoginStatus() {
  346. return loginStatus;
  347. }
  348. } // namespace rack