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
11KB

  1. #include <thread>
  2. #include <mutex>
  3. #include <condition_variable>
  4. #include <library.hpp>
  5. #include <settings.hpp>
  6. #include <app/common.hpp>
  7. #include <network.hpp>
  8. #include <system.hpp>
  9. #include <context.hpp>
  10. #include <window/Window.hpp>
  11. #include <asset.hpp>
  12. #include <settings.hpp>
  13. #include <plugin.hpp>
  14. namespace rack {
  15. namespace library {
  16. static std::mutex appUpdateMutex;
  17. static std::mutex updateMutex;
  18. static std::mutex timeoutMutex;
  19. static std::condition_variable updateCv;
  20. void init() {
  21. if (!settings::autoCheckUpdates)
  22. return;
  23. // Dev mode is typically used when Rack or plugins are compiled from source, so updating might overwrite assets.
  24. if (settings::devMode)
  25. return;
  26. // Safe mode disables plugin loading, so Rack will unnecessarily try to sync all plugins.
  27. if (settings::safeMode)
  28. return;
  29. std::thread t([&]() {
  30. system::setThreadName("Library");
  31. // Wait a few seconds before updating in case library is destroyed immediately afterwards
  32. {
  33. std::unique_lock<std::mutex> lock(timeoutMutex);
  34. if (updateCv.wait_for(lock, std::chrono::duration<double>(4.0)) != std::cv_status::timeout)
  35. return;
  36. }
  37. checkAppUpdate();
  38. checkUpdates();
  39. });
  40. t.detach();
  41. }
  42. void destroy() {
  43. // Wait until all library threads are finished
  44. updateCv.notify_all();
  45. std::lock_guard<std::mutex> timeoutLock(timeoutMutex);
  46. std::lock_guard<std::mutex> appUpdateLock(appUpdateMutex);
  47. std::lock_guard<std::mutex> updateLock(updateMutex);
  48. }
  49. void checkAppUpdate() {
  50. if (!appUpdateMutex.try_lock())
  51. return;
  52. DEFER({appUpdateMutex.unlock();});
  53. std::string versionUrl = API_URL + "/version";
  54. json_t* reqJ = json_object();
  55. json_object_set(reqJ, "edition", json_string(APP_EDITION.c_str()));
  56. DEFER({json_decref(reqJ);});
  57. json_t* resJ = network::requestJson(network::METHOD_GET, versionUrl, reqJ);
  58. if (!resJ) {
  59. WARN("Request for version failed");
  60. return;
  61. }
  62. DEFER({json_decref(resJ);});
  63. json_t* versionJ = json_object_get(resJ, "version");
  64. if (versionJ) {
  65. std::string appVersion = json_string_value(versionJ);
  66. // Check if app version is more recent than current version
  67. if (string::Version(APP_VERSION) < string::Version(appVersion))
  68. library::appVersion = appVersion;
  69. }
  70. json_t* changelogUrlJ = json_object_get(resJ, "changelogUrl");
  71. if (changelogUrlJ)
  72. appChangelogUrl = json_string_value(changelogUrlJ);
  73. json_t* downloadUrlsJ = json_object_get(resJ, "downloadUrls");
  74. if (downloadUrlsJ) {
  75. std::string arch = APP_OS + "-" + APP_CPU;
  76. json_t* downloadUrlJ = json_object_get(downloadUrlsJ, arch.c_str());
  77. if (downloadUrlJ)
  78. appDownloadUrl = json_string_value(downloadUrlJ);
  79. }
  80. }
  81. bool isAppUpdateAvailable() {
  82. return (appVersion != "");
  83. }
  84. bool isLoggedIn() {
  85. return settings::token != "";
  86. }
  87. void logIn(std::string email, std::string password) {
  88. if (!updateMutex.try_lock())
  89. return;
  90. DEFER({updateMutex.unlock();});
  91. loginStatus = "Logging in...";
  92. json_t* reqJ = json_object();
  93. json_object_set(reqJ, "email", json_string(email.c_str()));
  94. json_object_set(reqJ, "password", json_string(password.c_str()));
  95. std::string url = API_URL + "/token";
  96. json_t* resJ = network::requestJson(network::METHOD_POST, url, reqJ);
  97. json_decref(reqJ);
  98. if (!resJ) {
  99. loginStatus = "No response from server";
  100. return;
  101. }
  102. DEFER({json_decref(resJ);});
  103. json_t* errorJ = json_object_get(resJ, "error");
  104. if (errorJ) {
  105. const char* errorStr = json_string_value(errorJ);
  106. loginStatus = errorStr;
  107. return;
  108. }
  109. json_t* tokenJ = json_object_get(resJ, "token");
  110. if (!tokenJ) {
  111. loginStatus = "No token in response";
  112. return;
  113. }
  114. const char* tokenStr = json_string_value(tokenJ);
  115. settings::token = tokenStr;
  116. loginStatus = "";
  117. refreshRequested = true;
  118. }
  119. void logOut() {
  120. settings::token = "";
  121. updateInfos.clear();
  122. }
  123. static network::CookieMap getTokenCookies() {
  124. network::CookieMap cookies;
  125. cookies["token"] = settings::token;
  126. return cookies;
  127. }
  128. void checkUpdates() {
  129. if (!updateMutex.try_lock())
  130. return;
  131. DEFER({updateMutex.unlock();});
  132. if (settings::token.empty())
  133. return;
  134. // Refuse to check for updates while updating plugins
  135. if (isSyncing)
  136. return;
  137. updateStatus = "Querying for updates...";
  138. // Check user token
  139. std::string userUrl = API_URL + "/user";
  140. json_t* userResJ = network::requestJson(network::METHOD_GET, userUrl, NULL, getTokenCookies());
  141. if (!userResJ) {
  142. WARN("Request for user account failed");
  143. updateStatus = "Could not query user account";
  144. return;
  145. }
  146. DEFER({json_decref(userResJ);});
  147. json_t* userErrorJ = json_object_get(userResJ, "error");
  148. if (userErrorJ) {
  149. std::string userError = json_string_value(userErrorJ);
  150. WARN("Request for user account error: %s", userError.c_str());
  151. // Unset token
  152. settings::token = "";
  153. refreshRequested = true;
  154. return;
  155. }
  156. // Get library manifests
  157. std::string manifestsUrl = API_URL + "/library/manifests";
  158. json_t* manifestsReq = json_object();
  159. json_object_set(manifestsReq, "version", json_string(APP_VERSION_MAJOR.c_str()));
  160. json_t* manifestsResJ = network::requestJson(network::METHOD_GET, manifestsUrl, manifestsReq);
  161. json_decref(manifestsReq);
  162. if (!manifestsResJ) {
  163. WARN("Request for library manifests failed");
  164. updateStatus = "Could not query plugin manifests";
  165. return;
  166. }
  167. DEFER({json_decref(manifestsResJ);});
  168. // Get user's modules
  169. std::string modulesUrl = API_URL + "/modules";
  170. json_t* modulesResJ = network::requestJson(network::METHOD_GET, modulesUrl, NULL, getTokenCookies());
  171. if (!modulesResJ) {
  172. WARN("Request for user's modules failed");
  173. updateStatus = "Could not query user's modules";
  174. return;
  175. }
  176. DEFER({json_decref(modulesResJ);});
  177. json_t* manifestsJ = json_object_get(manifestsResJ, "manifests");
  178. json_t* pluginsJ = json_object_get(modulesResJ, "modules");
  179. const char* modulesKey;
  180. json_t* modulesJ;
  181. json_object_foreach(pluginsJ, modulesKey, modulesJ) {
  182. std::string pluginSlug = modulesKey;
  183. // Get plugin manifest
  184. json_t* manifestJ = json_object_get(manifestsJ, pluginSlug.c_str());
  185. if (!manifestJ) {
  186. WARN("VCV account has plugin %s but no manifest was found", pluginSlug.c_str());
  187. continue;
  188. }
  189. // Don't replace existing UpdateInfo, even if version is newer.
  190. // This keeps things sane and ensures that only one version of each plugin is downloaded to `plugins/` at a time.
  191. auto it = updateInfos.find(pluginSlug);
  192. if (it != updateInfos.end()) {
  193. continue;
  194. }
  195. UpdateInfo update;
  196. // Get plugin name
  197. json_t* nameJ = json_object_get(manifestJ, "name");
  198. if (nameJ)
  199. update.name = json_string_value(nameJ);
  200. // Get version
  201. json_t* versionJ = json_object_get(manifestJ, "version");
  202. if (!versionJ) {
  203. // WARN("Plugin %s has no version in manifest", pluginSlug.c_str());
  204. continue;
  205. }
  206. update.version = json_string_value(versionJ);
  207. // Reject plugins with ABI mismatch
  208. if (!string::startsWith(update.version, APP_VERSION_MAJOR + ".")) {
  209. continue;
  210. }
  211. // Check if update is needed
  212. plugin::Plugin* p = plugin::getPlugin(pluginSlug);
  213. if (p) {
  214. if (update.version == p->version)
  215. continue;
  216. if (string::Version(update.version) < string::Version(p->version))
  217. continue;
  218. }
  219. // Require that plugin is available
  220. json_t* availableJ = json_object_get(manifestJ, "available");
  221. if (!json_boolean_value(availableJ))
  222. continue;
  223. // Get changelog URL
  224. json_t* changelogUrlJ = json_object_get(manifestJ, "changelogUrl");
  225. if (changelogUrlJ)
  226. update.changelogUrl = json_string_value(changelogUrlJ);
  227. // Add update to updates map
  228. updateInfos[pluginSlug] = update;
  229. }
  230. // Merge module whitelist
  231. {
  232. // Clone plugin slugs from settings to temporary whitelist.
  233. // This makes existing plugins entirely hidden if removed from user's VCV account.
  234. std::map<std::string, settings::PluginWhitelist> moduleWhitelist;
  235. for (const auto& pluginPair : settings::moduleWhitelist) {
  236. std::string pluginSlug = pluginPair.first;
  237. moduleWhitelist[pluginSlug] = settings::PluginWhitelist();
  238. }
  239. // Iterate plugins
  240. const char* modulesKey;
  241. json_t* modulesJ;
  242. json_object_foreach(pluginsJ, modulesKey, modulesJ) {
  243. std::string pluginSlug = modulesKey;
  244. settings::PluginWhitelist& pw = moduleWhitelist[pluginSlug];
  245. // If value is "true", plugin is subscribed
  246. if (json_is_true(modulesJ)) {
  247. pw.subscribed = true;
  248. continue;
  249. }
  250. // Iterate modules in plugin
  251. size_t moduleIndex;
  252. json_t* moduleSlugJ;
  253. json_array_foreach(modulesJ, moduleIndex, moduleSlugJ) {
  254. std::string moduleSlug = json_string_value(moduleSlugJ);
  255. // Insert module in whitelist
  256. pw.moduleSlugs.insert(moduleSlug);
  257. }
  258. }
  259. settings::moduleWhitelist = moduleWhitelist;
  260. }
  261. updateStatus = "";
  262. refreshRequested = true;
  263. }
  264. bool hasUpdates() {
  265. for (auto& pair : updateInfos) {
  266. if (!pair.second.downloaded)
  267. return true;
  268. }
  269. return false;
  270. }
  271. void syncUpdate(std::string slug) {
  272. if (!updateMutex.try_lock())
  273. return;
  274. DEFER({updateMutex.unlock();});
  275. if (settings::token.empty())
  276. return;
  277. isSyncing = true;
  278. DEFER({isSyncing = false;});
  279. // Get the UpdateInfo object
  280. auto it = updateInfos.find(slug);
  281. if (it == updateInfos.end())
  282. return;
  283. UpdateInfo update = it->second;
  284. updateSlug = slug;
  285. DEFER({updateSlug = "";});
  286. // Set progress to 0%
  287. updateProgress = 0.f;
  288. DEFER({updateProgress = 0.f;});
  289. INFO("Downloading plugin %s v%s for %s-%s", slug.c_str(), update.version.c_str(), APP_OS.c_str(), APP_CPU.c_str());
  290. // Get download URL
  291. std::string downloadUrl = API_URL + "/download";
  292. downloadUrl += "?slug=" + network::encodeUrl(slug);
  293. downloadUrl += "&version=" + network::encodeUrl(update.version);
  294. downloadUrl += "&arch=" + network::encodeUrl(APP_OS + "-" + APP_CPU);
  295. // Get file path
  296. std::string packageFilename = slug + "-" + update.version + "-" + APP_OS + "-" + APP_CPU + ".vcvplugin";
  297. std::string packagePath = system::join(plugin::pluginsPath, packageFilename);
  298. // Download plugin package
  299. if (!network::requestDownload(downloadUrl, packagePath, &updateProgress, getTokenCookies())) {
  300. WARN("Plugin %s download was unsuccessful", slug.c_str());
  301. return;
  302. }
  303. // updateInfos could possibly change in the checkUpdates() thread, so re-get the UpdateInfo to modify it.
  304. it = updateInfos.find(slug);
  305. if (it == updateInfos.end())
  306. return;
  307. it->second.downloaded = true;
  308. }
  309. void syncUpdates() {
  310. if (settings::token.empty())
  311. return;
  312. // updateInfos could possibly change in the checkUpdates() thread, but checkUpdates() will not execute if syncUpdate() is running, so the chance of the updateInfos map being modified while iterating is rare.
  313. auto updateInfosClone = updateInfos;
  314. for (auto& pair : updateInfosClone) {
  315. syncUpdate(pair.first);
  316. }
  317. restartRequested = true;
  318. }
  319. std::string appVersion;
  320. std::string appDownloadUrl;
  321. std::string appChangelogUrl;
  322. std::string loginStatus;
  323. std::map<std::string, UpdateInfo> updateInfos;
  324. std::string updateStatus;
  325. std::string updateSlug;
  326. float updateProgress = 0.f;
  327. bool isSyncing = false;
  328. bool restartRequested = false;
  329. bool refreshRequested = false;
  330. } // namespace library
  331. } // namespace rack