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.

365 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(APP_VERSION_MAJOR.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. // Reject plugins with ABI mismatch
  181. if (!string::startsWith(update.version, APP_VERSION_MAJOR + ".")) {
  182. continue;
  183. }
  184. // Check if update is needed
  185. plugin::Plugin* p = plugin::getPlugin(slug);
  186. if (p && p->version == update.version)
  187. continue;
  188. // Require that plugin is available
  189. json_t* availableJ = json_object_get(manifestJ, "available");
  190. if (!json_boolean_value(availableJ))
  191. continue;
  192. // Get changelog URL
  193. json_t* changelogUrlJ = json_object_get(manifestJ, "changelogUrl");
  194. if (changelogUrlJ)
  195. update.changelogUrl = json_string_value(changelogUrlJ);
  196. // Add update to updates map
  197. updateInfos[slug] = update;
  198. }
  199. // Get module whitelist
  200. {
  201. std::string whitelistUrl = API_URL + "/modules";
  202. json_t* whitelistResJ = network::requestJson(network::METHOD_GET, whitelistUrl, NULL, getTokenCookies());
  203. if (!whitelistResJ) {
  204. WARN("Request for module whitelist failed");
  205. updateStatus = "Could not query updates";
  206. return;
  207. }
  208. DEFER({json_decref(whitelistResJ);});
  209. std::map<std::string, std::set<std::string>> moduleWhitelist;
  210. json_t* pluginsJ = json_object_get(whitelistResJ, "plugins");
  211. // Iterate plugins
  212. const char* pluginSlug;
  213. json_t* modulesJ;
  214. json_object_foreach(pluginsJ, pluginSlug, modulesJ) {
  215. // Iterate modules in plugin
  216. size_t moduleIndex;
  217. json_t* moduleSlugJ;
  218. json_array_foreach(modulesJ, moduleIndex, moduleSlugJ) {
  219. std::string moduleSlug = json_string_value(moduleSlugJ);
  220. // Insert module in whitelist
  221. moduleWhitelist[pluginSlug].insert(moduleSlug);
  222. }
  223. }
  224. settings::moduleWhitelist = moduleWhitelist;
  225. }
  226. updateStatus = "";
  227. }
  228. bool hasUpdates() {
  229. for (auto& pair : updateInfos) {
  230. if (!pair.second.downloaded)
  231. return true;
  232. }
  233. return false;
  234. }
  235. void syncUpdate(const std::string& slug) {
  236. if (settings::token.empty())
  237. return;
  238. isSyncing = true;
  239. DEFER({isSyncing = false;});
  240. // Get the UpdateInfo object
  241. auto it = updateInfos.find(slug);
  242. if (it == updateInfos.end())
  243. return;
  244. UpdateInfo update = it->second;
  245. updateSlug = slug;
  246. DEFER({updateSlug = "";});
  247. // Set progress to 0%
  248. updateProgress = 0.f;
  249. DEFER({updateProgress = 0.f;});
  250. INFO("Downloading plugin %s v%s for %s", slug.c_str(), update.version.c_str(), APP_ARCH.c_str());
  251. // Get download URL
  252. std::string downloadUrl = API_URL + "/download";
  253. downloadUrl += "?slug=" + network::encodeUrl(slug);
  254. downloadUrl += "&version=" + network::encodeUrl(update.version);
  255. downloadUrl += "&arch=" + network::encodeUrl(APP_ARCH);
  256. // Get file path
  257. std::string packageFilename = slug + "-" + update.version + "-" + APP_ARCH + ".vcvplugin";
  258. std::string packagePath = system::join(plugin::pluginsPath, packageFilename);
  259. // Download plugin package
  260. if (!network::requestDownload(downloadUrl, packagePath, &updateProgress, getTokenCookies())) {
  261. WARN("Plugin %s download was unsuccessful", slug.c_str());
  262. return;
  263. }
  264. // updateInfos could possibly change in the checkUpdates() thread, so re-get the UpdateInfo to modify it.
  265. it = updateInfos.find(slug);
  266. if (it == updateInfos.end())
  267. return;
  268. it->second.downloaded = true;
  269. }
  270. void syncUpdates() {
  271. if (settings::token.empty())
  272. return;
  273. // 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.
  274. auto updateInfosClone = updateInfos;
  275. for (auto& pair : updateInfosClone) {
  276. syncUpdate(pair.first);
  277. }
  278. restartRequested = true;
  279. }
  280. std::string appVersion;
  281. std::string appDownloadUrl;
  282. std::string appChangelogUrl;
  283. std::string loginStatus;
  284. std::map<std::string, UpdateInfo> updateInfos;
  285. std::string updateStatus;
  286. std::string updateSlug;
  287. float updateProgress = 0.f;
  288. bool isSyncing = false;
  289. bool restartRequested = false;
  290. } // namespace library
  291. } // namespace rack