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.

409 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. json_t* downloadUrlJ = json_object_get(downloadUrlsJ, APP_ARCH.c_str());
  76. if (downloadUrlJ)
  77. appDownloadUrl = json_string_value(downloadUrlJ);
  78. }
  79. }
  80. bool isAppUpdateAvailable() {
  81. return (appVersion != "");
  82. }
  83. bool isLoggedIn() {
  84. return settings::token != "";
  85. }
  86. void logIn(std::string email, std::string password) {
  87. if (!updateMutex.try_lock())
  88. return;
  89. DEFER({updateMutex.unlock();});
  90. loginStatus = "Logging in...";
  91. json_t* reqJ = json_object();
  92. json_object_set(reqJ, "email", json_string(email.c_str()));
  93. json_object_set(reqJ, "password", json_string(password.c_str()));
  94. std::string url = API_URL + "/token";
  95. json_t* resJ = network::requestJson(network::METHOD_POST, url, reqJ);
  96. json_decref(reqJ);
  97. if (!resJ) {
  98. loginStatus = "No response from server";
  99. return;
  100. }
  101. DEFER({json_decref(resJ);});
  102. json_t* errorJ = json_object_get(resJ, "error");
  103. if (errorJ) {
  104. const char* errorStr = json_string_value(errorJ);
  105. loginStatus = errorStr;
  106. return;
  107. }
  108. json_t* tokenJ = json_object_get(resJ, "token");
  109. if (!tokenJ) {
  110. loginStatus = "No token in response";
  111. return;
  112. }
  113. const char* tokenStr = json_string_value(tokenJ);
  114. settings::token = tokenStr;
  115. loginStatus = "";
  116. refreshRequested = true;
  117. }
  118. void logOut() {
  119. settings::token = "";
  120. updateInfos.clear();
  121. }
  122. static network::CookieMap getTokenCookies() {
  123. network::CookieMap cookies;
  124. cookies["token"] = settings::token;
  125. return cookies;
  126. }
  127. void checkUpdates() {
  128. if (!updateMutex.try_lock())
  129. return;
  130. DEFER({updateMutex.unlock();});
  131. if (settings::token.empty())
  132. return;
  133. // Refuse to check for updates while updating plugins
  134. if (isSyncing)
  135. return;
  136. updateStatus = "Querying for updates...";
  137. // Check user token
  138. std::string userUrl = API_URL + "/user";
  139. json_t* userResJ = network::requestJson(network::METHOD_GET, userUrl, NULL, getTokenCookies());
  140. if (!userResJ) {
  141. WARN("Request for user account failed");
  142. updateStatus = "Could not query user account";
  143. return;
  144. }
  145. DEFER({json_decref(userResJ);});
  146. json_t* userErrorJ = json_object_get(userResJ, "error");
  147. if (userErrorJ) {
  148. std::string userError = json_string_value(userErrorJ);
  149. WARN("Request for user account error: %s", userError.c_str());
  150. // Unset token
  151. settings::token = "";
  152. refreshRequested = true;
  153. return;
  154. }
  155. // Get library manifests
  156. std::string manifestsUrl = API_URL + "/library/manifests";
  157. json_t* manifestsReq = json_object();
  158. json_object_set(manifestsReq, "version", json_string(APP_VERSION_MAJOR.c_str()));
  159. json_t* manifestsResJ = network::requestJson(network::METHOD_GET, manifestsUrl, manifestsReq);
  160. json_decref(manifestsReq);
  161. if (!manifestsResJ) {
  162. WARN("Request for library manifests failed");
  163. updateStatus = "Could not query plugin manifests";
  164. return;
  165. }
  166. DEFER({json_decref(manifestsResJ);});
  167. // Get user's modules
  168. std::string modulesUrl = API_URL + "/modules";
  169. json_t* modulesResJ = network::requestJson(network::METHOD_GET, modulesUrl, NULL, getTokenCookies());
  170. if (!modulesResJ) {
  171. WARN("Request for user's modules failed");
  172. updateStatus = "Could not query user's modules";
  173. return;
  174. }
  175. DEFER({json_decref(modulesResJ);});
  176. json_t* manifestsJ = json_object_get(manifestsResJ, "manifests");
  177. json_t* pluginsJ = json_object_get(modulesResJ, "modules");
  178. const char* modulesKey;
  179. json_t* modulesJ;
  180. json_object_foreach(pluginsJ, modulesKey, modulesJ) {
  181. std::string pluginSlug = modulesKey;
  182. // Get plugin manifest
  183. json_t* manifestJ = json_object_get(manifestsJ, pluginSlug.c_str());
  184. if (!manifestJ) {
  185. WARN("VCV account has plugin %s but no manifest was found", pluginSlug.c_str());
  186. continue;
  187. }
  188. // Don't replace existing UpdateInfo, even if version is newer.
  189. // This keeps things sane and ensures that only one version of each plugin is downloaded to `plugins/` at a time.
  190. auto it = updateInfos.find(pluginSlug);
  191. if (it != updateInfos.end()) {
  192. continue;
  193. }
  194. UpdateInfo update;
  195. // Get plugin name
  196. json_t* nameJ = json_object_get(manifestJ, "name");
  197. if (nameJ)
  198. update.name = json_string_value(nameJ);
  199. // Get version
  200. json_t* versionJ = json_object_get(manifestJ, "version");
  201. if (!versionJ) {
  202. // WARN("Plugin %s has no version in manifest", pluginSlug.c_str());
  203. continue;
  204. }
  205. update.version = json_string_value(versionJ);
  206. // Reject plugins with ABI mismatch
  207. if (!string::startsWith(update.version, APP_VERSION_MAJOR + ".")) {
  208. continue;
  209. }
  210. // Check if update is needed
  211. plugin::Plugin* p = plugin::getPlugin(pluginSlug);
  212. if (p) {
  213. if (update.version == p->version)
  214. continue;
  215. if (string::Version(update.version) < string::Version(p->version))
  216. continue;
  217. }
  218. // Require that plugin is available
  219. json_t* availableJ = json_object_get(manifestJ, "available");
  220. if (!json_boolean_value(availableJ))
  221. continue;
  222. // Get changelog URL
  223. json_t* changelogUrlJ = json_object_get(manifestJ, "changelogUrl");
  224. if (changelogUrlJ)
  225. update.changelogUrl = json_string_value(changelogUrlJ);
  226. // Add update to updates map
  227. updateInfos[pluginSlug] = update;
  228. }
  229. // Merge module whitelist
  230. {
  231. // Clone plugin slugs from settings to temporary whitelist.
  232. // This makes existing plugins entirely hidden if removed from user's VCV account.
  233. std::map<std::string, settings::PluginWhitelist> moduleWhitelist;
  234. for (const auto& pluginPair : settings::moduleWhitelist) {
  235. std::string pluginSlug = pluginPair.first;
  236. moduleWhitelist[pluginSlug] = settings::PluginWhitelist();
  237. }
  238. // Iterate plugins
  239. const char* modulesKey;
  240. json_t* modulesJ;
  241. json_object_foreach(pluginsJ, modulesKey, modulesJ) {
  242. std::string pluginSlug = modulesKey;
  243. settings::PluginWhitelist& pw = moduleWhitelist[pluginSlug];
  244. // If value is "true", plugin is subscribed
  245. if (json_is_true(modulesJ)) {
  246. pw.subscribed = true;
  247. continue;
  248. }
  249. // Iterate modules in plugin
  250. size_t moduleIndex;
  251. json_t* moduleSlugJ;
  252. json_array_foreach(modulesJ, moduleIndex, moduleSlugJ) {
  253. std::string moduleSlug = json_string_value(moduleSlugJ);
  254. // Insert module in whitelist
  255. pw.moduleSlugs.insert(moduleSlug);
  256. }
  257. }
  258. settings::moduleWhitelist = moduleWhitelist;
  259. }
  260. updateStatus = "";
  261. refreshRequested = true;
  262. }
  263. bool hasUpdates() {
  264. for (auto& pair : updateInfos) {
  265. if (!pair.second.downloaded)
  266. return true;
  267. }
  268. return false;
  269. }
  270. void syncUpdate(std::string slug) {
  271. if (!updateMutex.try_lock())
  272. return;
  273. DEFER({updateMutex.unlock();});
  274. if (settings::token.empty())
  275. return;
  276. isSyncing = true;
  277. DEFER({isSyncing = false;});
  278. // Get the UpdateInfo object
  279. auto it = updateInfos.find(slug);
  280. if (it == updateInfos.end())
  281. return;
  282. UpdateInfo update = it->second;
  283. updateSlug = slug;
  284. DEFER({updateSlug = "";});
  285. // Set progress to 0%
  286. updateProgress = 0.f;
  287. DEFER({updateProgress = 0.f;});
  288. INFO("Downloading plugin %s v%s for %s", slug.c_str(), update.version.c_str(), APP_ARCH.c_str());
  289. // Get download URL
  290. std::string downloadUrl = API_URL + "/download";
  291. downloadUrl += "?slug=" + network::encodeUrl(slug);
  292. downloadUrl += "&version=" + network::encodeUrl(update.version);
  293. downloadUrl += "&os=" + network::encodeUrl(APP_ARCH);
  294. // Get file path
  295. std::string packageFilename = slug + "-" + update.version + "-" + APP_ARCH + ".vcvplugin";
  296. std::string packagePath = system::join(plugin::pluginsPath, packageFilename);
  297. // Download plugin package
  298. if (!network::requestDownload(downloadUrl, packagePath, &updateProgress, getTokenCookies())) {
  299. WARN("Plugin %s download was unsuccessful", slug.c_str());
  300. return;
  301. }
  302. // updateInfos could possibly change in the checkUpdates() thread, so re-get the UpdateInfo to modify it.
  303. it = updateInfos.find(slug);
  304. if (it == updateInfos.end())
  305. return;
  306. it->second.downloaded = true;
  307. }
  308. void syncUpdates() {
  309. if (settings::token.empty())
  310. return;
  311. // 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.
  312. auto updateInfosClone = updateInfos;
  313. for (auto& pair : updateInfosClone) {
  314. syncUpdate(pair.first);
  315. }
  316. restartRequested = true;
  317. }
  318. std::string appVersion;
  319. std::string appDownloadUrl;
  320. std::string appChangelogUrl;
  321. std::string loginStatus;
  322. std::map<std::string, UpdateInfo> updateInfos;
  323. std::string updateStatus;
  324. std::string updateSlug;
  325. float updateProgress = 0.f;
  326. bool isSyncing = false;
  327. bool restartRequested = false;
  328. bool refreshRequested = false;
  329. } // namespace library
  330. } // namespace rack