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.

364 lines
9.2KB

  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.hpp>
  11. #include <asset.hpp>
  12. #include <settings.hpp>
  13. #include <plugin.hpp>
  14. namespace rack {
  15. namespace library {
  16. static std::mutex updatesLoopMutex;
  17. static std::condition_variable updatesLoopCv;
  18. static bool updatesLoopRunning = false;
  19. static void checkUpdatesLoop() {
  20. updatesLoopRunning = true;
  21. while (updatesLoopRunning) {
  22. checkUpdates();
  23. // Sleep a few seconds, or wake up when destroy() is called
  24. std::unique_lock<std::mutex> lock(updatesLoopMutex);
  25. auto duration = std::chrono::seconds(15);
  26. if (!updatesLoopRunning)
  27. break;
  28. updatesLoopCv.wait_for(lock, duration, []() {return !updatesLoopRunning;});
  29. }
  30. }
  31. void init() {
  32. if (settings::autoCheckUpdates && !settings::devMode) {
  33. std::thread t([&]() {
  34. checkAppUpdate();
  35. });
  36. t.detach();
  37. std::thread t2([&] {
  38. checkUpdatesLoop();
  39. });
  40. t2.detach();
  41. }
  42. }
  43. void destroy() {
  44. // Stop checkUpdatesLoop thread if it's running
  45. {
  46. std::lock_guard<std::mutex> lock(updatesLoopMutex);
  47. updatesLoopRunning = false;
  48. updatesLoopCv.notify_all();
  49. }
  50. }
  51. void checkAppUpdate() {
  52. std::string versionUrl = API_URL + "/version";
  53. json_t* resJ = network::requestJson(network::METHOD_GET, versionUrl, NULL);
  54. if (!resJ) {
  55. WARN("Request for version failed");
  56. return;
  57. }
  58. DEFER({json_decref(resJ);});
  59. json_t* versionJ = json_object_get(resJ, "version");
  60. if (versionJ)
  61. appVersion = json_string_value(versionJ);
  62. json_t* changelogUrlJ = json_object_get(resJ, "changelogUrl");
  63. if (changelogUrlJ)
  64. appChangelogUrl = json_string_value(changelogUrlJ);
  65. json_t* downloadUrlsJ = json_object_get(resJ, "downloadUrls");
  66. if (downloadUrlsJ) {
  67. json_t* downloadUrlJ = json_object_get(downloadUrlsJ, APP_ARCH.c_str());
  68. if (downloadUrlJ)
  69. appDownloadUrl = json_string_value(downloadUrlJ);
  70. }
  71. }
  72. bool isAppUpdateAvailable() {
  73. return (appVersion != "") && (appVersion != APP_VERSION);
  74. }
  75. bool isLoggedIn() {
  76. return settings::token != "";
  77. }
  78. void logIn(const std::string& email, const std::string& password) {
  79. loginStatus = "Logging in...";
  80. json_t* reqJ = json_object();
  81. json_object_set(reqJ, "email", json_string(email.c_str()));
  82. json_object_set(reqJ, "password", json_string(password.c_str()));
  83. std::string url = API_URL + "/token";
  84. json_t* resJ = network::requestJson(network::METHOD_POST, url, reqJ);
  85. json_decref(reqJ);
  86. if (!resJ) {
  87. loginStatus = "No response from server";
  88. return;
  89. }
  90. DEFER({json_decref(resJ);});
  91. json_t* errorJ = json_object_get(resJ, "error");
  92. if (errorJ) {
  93. const char* errorStr = json_string_value(errorJ);
  94. loginStatus = errorStr;
  95. return;
  96. }
  97. json_t* tokenJ = json_object_get(resJ, "token");
  98. if (!tokenJ) {
  99. loginStatus = "No token in response";
  100. return;
  101. }
  102. const char* tokenStr = json_string_value(tokenJ);
  103. settings::token = tokenStr;
  104. loginStatus = "";
  105. checkUpdates();
  106. }
  107. void logOut() {
  108. settings::token = "";
  109. updateInfos.clear();
  110. }
  111. static network::CookieMap getTokenCookies() {
  112. network::CookieMap cookies;
  113. cookies["token"] = settings::token;
  114. return cookies;
  115. }
  116. void checkUpdates() {
  117. if (settings::token.empty())
  118. return;
  119. // Refuse to check for updates while updating plugins
  120. if (isSyncing)
  121. return;
  122. updateStatus = "Querying for updates...";
  123. // Get user's plugins list
  124. std::string pluginsUrl = API_URL + "/plugins";
  125. json_t* pluginsResJ = network::requestJson(network::METHOD_GET, pluginsUrl, NULL, getTokenCookies());
  126. if (!pluginsResJ) {
  127. WARN("Request for user's plugins failed");
  128. updateStatus = "Could not query plugins";
  129. return;
  130. }
  131. DEFER({json_decref(pluginsResJ);});
  132. json_t* errorJ = json_object_get(pluginsResJ, "error");
  133. if (errorJ) {
  134. WARN("Request for user's plugins returned an error: %s", json_string_value(errorJ));
  135. updateStatus = "Could not query plugins";
  136. return;
  137. }
  138. // Get library manifests
  139. std::string manifestsUrl = API_URL + "/library/manifests";
  140. json_t* manifestsReq = json_object();
  141. json_object_set(manifestsReq, "version", json_string(API_VERSION.c_str()));
  142. json_t* manifestsResJ = network::requestJson(network::METHOD_GET, manifestsUrl, manifestsReq);
  143. json_decref(manifestsReq);
  144. if (!manifestsResJ) {
  145. WARN("Request for library manifests failed");
  146. updateStatus = "Could not query updates";
  147. return;
  148. }
  149. DEFER({json_decref(manifestsResJ);});
  150. json_t* manifestsJ = json_object_get(manifestsResJ, "manifests");
  151. json_t* pluginsJ = json_object_get(pluginsResJ, "plugins");
  152. size_t pluginIndex;
  153. json_t* pluginJ;
  154. json_array_foreach(pluginsJ, pluginIndex, pluginJ) {
  155. // Get plugin manifest
  156. std::string slug = json_string_value(pluginJ);
  157. json_t* manifestJ = json_object_get(manifestsJ, slug.c_str());
  158. if (!manifestJ) {
  159. WARN("VCV account has plugin %s but no manifest was found", slug.c_str());
  160. continue;
  161. }
  162. // Don't replace existing UpdateInfo, even if version is newer.
  163. // This keeps things sane and ensures that only one version of each plugin is downloaded to `plugins/` at a time.
  164. auto it = updateInfos.find(slug);
  165. if (it != updateInfos.end()) {
  166. continue;
  167. }
  168. UpdateInfo update;
  169. // Get plugin name
  170. json_t* nameJ = json_object_get(manifestJ, "name");
  171. if (nameJ)
  172. update.name = json_string_value(nameJ);
  173. // Get version
  174. json_t* versionJ = json_object_get(manifestJ, "version");
  175. if (!versionJ) {
  176. WARN("Plugin %s has no version in manifest", slug.c_str());
  177. continue;
  178. }
  179. update.version = json_string_value(versionJ);
  180. // Check if update is needed
  181. plugin::Plugin* p = plugin::getPlugin(slug);
  182. if (p && p->version == update.version)
  183. continue;
  184. // Require that "status" is "available"
  185. json_t* statusJ = json_object_get(manifestJ, "status");
  186. if (!statusJ)
  187. continue;
  188. std::string status = json_string_value(statusJ);
  189. if (status != "available")
  190. continue;
  191. // Get changelog URL
  192. json_t* changelogUrlJ = json_object_get(manifestJ, "changelogUrl");
  193. if (changelogUrlJ)
  194. update.changelogUrl = json_string_value(changelogUrlJ);
  195. // Add update to updates map
  196. updateInfos[slug] = update;
  197. }
  198. // Get module whitelist
  199. {
  200. std::string whitelistUrl = API_URL + "/modules";
  201. json_t* whitelistResJ = network::requestJson(network::METHOD_GET, whitelistUrl, NULL, getTokenCookies());
  202. if (!whitelistResJ) {
  203. WARN("Request for module whitelist failed");
  204. updateStatus = "Could not query updates";
  205. return;
  206. }
  207. DEFER({json_decref(whitelistResJ);});
  208. std::map<std::string, std::set<std::string>> moduleWhitelist;
  209. json_t* pluginsJ = json_object_get(whitelistResJ, "plugins");
  210. // Iterate plugins
  211. const char* pluginSlug;
  212. json_t* modulesJ;
  213. json_object_foreach(pluginsJ, pluginSlug, modulesJ) {
  214. // Iterate modules in plugin
  215. size_t moduleIndex;
  216. json_t* moduleSlugJ;
  217. json_array_foreach(modulesJ, moduleIndex, moduleSlugJ) {
  218. std::string moduleSlug = json_string_value(moduleSlugJ);
  219. // Insert module in whitelist
  220. moduleWhitelist[pluginSlug].insert(moduleSlug);
  221. }
  222. }
  223. settings::moduleWhitelist = moduleWhitelist;
  224. }
  225. updateStatus = "";
  226. }
  227. bool hasUpdates() {
  228. for (auto& pair : updateInfos) {
  229. if (!pair.second.downloaded)
  230. return true;
  231. }
  232. return false;
  233. }
  234. void syncUpdate(const std::string& slug) {
  235. if (settings::token.empty())
  236. return;
  237. isSyncing = true;
  238. DEFER({isSyncing = false;});
  239. // Get the UpdateInfo object
  240. auto it = updateInfos.find(slug);
  241. if (it == updateInfos.end())
  242. return;
  243. UpdateInfo update = it->second;
  244. updateSlug = slug;
  245. DEFER({updateSlug = "";});
  246. // Set progress to 0%
  247. updateProgress = 0.f;
  248. DEFER({updateProgress = 0.f;});
  249. INFO("Downloading plugin %s v%s for %s", slug.c_str(), update.version.c_str(), APP_ARCH.c_str());
  250. // Get download URL
  251. std::string downloadUrl = API_URL + "/download";
  252. downloadUrl += "?slug=" + network::encodeUrl(slug);
  253. downloadUrl += "&version=" + network::encodeUrl(update.version);
  254. downloadUrl += "&arch=" + network::encodeUrl(APP_ARCH);
  255. // Get file path
  256. std::string packageFilename = slug + "-" + update.version + "-" + APP_ARCH + ".vcvplugin";
  257. std::string packagePath = system::join(plugin::pluginsPath, packageFilename);
  258. // Download plugin package
  259. if (!network::requestDownload(downloadUrl, packagePath, &updateProgress, getTokenCookies())) {
  260. WARN("Plugin %s download was unsuccessful", slug.c_str());
  261. return;
  262. }
  263. // updateInfos could possibly change in the checkUpdates() thread, so re-get the UpdateInfo to modify it.
  264. it = updateInfos.find(slug);
  265. if (it == updateInfos.end())
  266. return;
  267. it->second.downloaded = true;
  268. }
  269. void syncUpdates() {
  270. if (settings::token.empty())
  271. return;
  272. // 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.
  273. auto updateInfosClone = updateInfos;
  274. for (auto& pair : updateInfosClone) {
  275. syncUpdate(pair.first);
  276. }
  277. restartRequested = true;
  278. }
  279. std::string appVersion;
  280. std::string appDownloadUrl;
  281. std::string appChangelogUrl;
  282. std::string loginStatus;
  283. std::map<std::string, UpdateInfo> updateInfos;
  284. std::string updateStatus;
  285. std::string updateSlug;
  286. float updateProgress = 0.f;
  287. bool isSyncing = false;
  288. bool restartRequested = false;
  289. } // namespace library
  290. } // namespace rack