The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

455 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #pragma once
  20. //==============================================================================
  21. struct NetWorkerThread : public Thread,
  22. private AsyncUpdater
  23. {
  24. NetWorkerThread() : Thread ("License") {}
  25. ~NetWorkerThread()
  26. {
  27. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  28. signalThreadShouldExit();
  29. cancelPendingUpdate();
  30. finished.signal();
  31. {
  32. ScopedLock lock (weakReferenceLock);
  33. if (currentInputStream != nullptr)
  34. currentInputStream->cancel();
  35. }
  36. waitForThreadToExit (-1);
  37. }
  38. //==============================================================================
  39. void executeOnMessageThreadAndBlock (std::function<void()> f, bool signalWhenFinished = true)
  40. {
  41. // only call this on the worker thread
  42. jassert (Thread::getCurrentThreadId() == getThreadId());
  43. if (! isWaiting)
  44. {
  45. ScopedValueSetter<bool> reentrant (isWaiting, true);
  46. finished.reset();
  47. if (! threadShouldExit())
  48. {
  49. functionToExecute = [signalWhenFinished, f, this] () { f(); if (signalWhenFinished) finished.signal(); };
  50. triggerAsyncUpdate();
  51. finished.wait (-1);
  52. }
  53. }
  54. else
  55. {
  56. // only one task at a time
  57. jassertfalse;
  58. return;
  59. }
  60. }
  61. WebInputStream* getSharedWebInputStream (const URL& url, const bool usePost)
  62. {
  63. ScopedLock lock (weakReferenceLock);
  64. if (threadShouldExit())
  65. return nullptr;
  66. jassert (currentInputStream == nullptr);
  67. return (currentInputStream = new WeakWebInputStream (*this, url, usePost));
  68. }
  69. bool isWaiting = false;
  70. WaitableEvent finished;
  71. private:
  72. //==============================================================================
  73. void handleAsyncUpdate() override
  74. {
  75. if (functionToExecute)
  76. {
  77. std::function<void()> f;
  78. std::swap (f, functionToExecute);
  79. if (! threadShouldExit())
  80. f();
  81. }
  82. }
  83. //==============================================================================
  84. struct WeakWebInputStream : public WebInputStream
  85. {
  86. WeakWebInputStream (NetWorkerThread& workerThread, const URL& url, const bool usePost)
  87. : WebInputStream (url, usePost), owner (workerThread) {}
  88. ~WeakWebInputStream()
  89. {
  90. ScopedLock lock (owner.weakReferenceLock);
  91. owner.currentInputStream = nullptr;
  92. }
  93. NetWorkerThread& owner;
  94. WeakReference<WeakWebInputStream>::Master masterReference;
  95. friend class WeakReference<WeakWebInputStream>;
  96. };
  97. //==============================================================================
  98. friend struct WeakWebInputStream;
  99. std::function<void()> functionToExecute;
  100. CriticalSection weakReferenceLock;
  101. WebInputStream* currentInputStream = nullptr;
  102. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NetWorkerThread)
  103. };
  104. //==============================================================================
  105. //==============================================================================
  106. //==============================================================================
  107. struct LicenseThread : NetWorkerThread
  108. {
  109. LicenseThread (LicenseController& licenseController, bool shouldSelectNewLicense)
  110. : owner (licenseController), selectNewLicense (shouldSelectNewLicense)
  111. {
  112. startThread();
  113. }
  114. String getAuthToken()
  115. {
  116. if (owner.state.authToken.isNotEmpty())
  117. return owner.state.authToken;
  118. selectNewLicense = false;
  119. HashMap<String, String> result;
  120. if (! queryWebview ("https://auth.roli.com/signin/projucer?redirect=projucer://receive-auth-token?token=",
  121. "receive-auth-token", result))
  122. return {};
  123. return result["token"];
  124. }
  125. // returns true if any information was updated
  126. void updateUserInfo (LicenseState& stateToUpdate)
  127. {
  128. jassert (stateToUpdate.authToken.isNotEmpty());
  129. auto accessTokenHeader = "x-access-token: " + stateToUpdate.authToken;
  130. if (ScopedPointer<WebInputStream> shared
  131. = getSharedWebInputStream (URL ("https://api.roli.com/api/v1/user"), false))
  132. {
  133. const int statusCode = shared->withExtraHeaders (accessTokenHeader).getStatusCode();
  134. if (statusCode == 200)
  135. {
  136. var result = JSON::parse (shared->readEntireStreamAsString());
  137. shared = nullptr;
  138. auto newState = licenseStateFromJSON (result, stateToUpdate.authToken, stateToUpdate.avatar);
  139. if (newState.type != LicenseState::Type::notLoggedIn)
  140. stateToUpdate = newState;
  141. }
  142. else if (statusCode == 401)
  143. {
  144. selectNewLicense = false;
  145. // un-authorised: token has expired
  146. stateToUpdate = LicenseState();
  147. }
  148. }
  149. }
  150. void updateLicenseType (LicenseState& stateToUpdate)
  151. {
  152. bool requiredWebview = false;
  153. String licenseChooserPage = "https://juce.com/webviews/select_license";
  154. jassert (stateToUpdate.authToken.isNotEmpty());
  155. jassert (stateToUpdate.type != LicenseState::Type::notLoggedIn);
  156. auto accessTokenHeader = "x-access-token: " + stateToUpdate.authToken;
  157. StringArray licenses;
  158. while ((licenses.isEmpty() || selectNewLicense) && ! threadShouldExit())
  159. {
  160. static Identifier licenseTypeIdentifier ("type");
  161. static Identifier licenseStatusIdentifier ("status");
  162. static Identifier projucerLicenseTypeIdentifier ("licence_type");
  163. static Identifier productNameIdentifier ("product_name");
  164. static Identifier licenseIdentifier ("licence");
  165. static Identifier serialIdentifier ("serial_number");
  166. static Identifier versionIdentifier ("product_version");
  167. static Identifier searchInternalIdentifier ("search_internal_id");
  168. if (! selectNewLicense)
  169. {
  170. ScopedPointer<WebInputStream> shared = getSharedWebInputStream (URL ("https://api.roli.com/api/v1/user/licences?search_internal_id=com.roli.projucer&version=5"),
  171. false);
  172. if (shared == nullptr)
  173. break;
  174. var json = JSON::parse (shared->withExtraHeaders (accessTokenHeader)
  175. .readEntireStreamAsString());
  176. shared = nullptr;
  177. if (auto* jsonLicenses = json.getArray())
  178. {
  179. for (auto& v : *jsonLicenses)
  180. {
  181. if (auto* obj = v.getDynamicObject())
  182. {
  183. const String& productType = obj->getProperty (projucerLicenseTypeIdentifier);
  184. const String& status = obj->getProperty (licenseStatusIdentifier);
  185. if (productType.isNotEmpty() && (status.isEmpty() || status == "active"))
  186. licenses.add (productType);
  187. }
  188. }
  189. }
  190. if (! licenses.isEmpty())
  191. break;
  192. }
  193. // ask the user to select a license
  194. HashMap<String, String> result;
  195. requiredWebview = true;
  196. if (! queryWebview (licenseChooserPage, {}, result))
  197. break;
  198. const String& redirectURL = result["page-redirect"];
  199. const String& productKey = result["register-product"];
  200. const String& chosenLicenseType = result["redeem-licence-type"];
  201. if (redirectURL.isNotEmpty())
  202. {
  203. licenseChooserPage = "https://juce.com/webviews/register-product";
  204. continue;
  205. }
  206. if (productKey.isNotEmpty())
  207. {
  208. DynamicObject::Ptr redeamObject = new DynamicObject();
  209. redeamObject->setProperty (serialIdentifier, productKey);
  210. String postData (JSON::toString (var (redeamObject.get())));
  211. ScopedPointer<WebInputStream> shared = getSharedWebInputStream (URL ("https://api.roli.com/api/v1/user/products").withPOSTData (postData),
  212. true);
  213. if (shared == nullptr)
  214. break;
  215. int statusCode = shared->withExtraHeaders (accessTokenHeader)
  216. .withExtraHeaders ("Content-Type: application/json")
  217. .getStatusCode();
  218. licenseChooserPage = String ("https://juce.com/webviews/register-product?error=")
  219. + String (statusCode == 404 ? "invalid" : "server");
  220. if (statusCode == 200)
  221. selectNewLicense = false;
  222. continue;
  223. }
  224. if (chosenLicenseType.isNotEmpty())
  225. {
  226. // redeem the license
  227. DynamicObject::Ptr jsonLicenseObject = new DynamicObject();
  228. jsonLicenseObject->setProperty (projucerLicenseTypeIdentifier, chosenLicenseType);
  229. jsonLicenseObject->setProperty (versionIdentifier, 5);
  230. DynamicObject::Ptr jsonLicenseRequest = new DynamicObject();
  231. jsonLicenseRequest->setProperty (licenseIdentifier, var (jsonLicenseObject.get()));
  232. jsonLicenseRequest->setProperty (searchInternalIdentifier, "com.roli.projucer");
  233. jsonLicenseRequest->setProperty (licenseTypeIdentifier, "software");
  234. String postData (JSON::toString (var (jsonLicenseRequest.get())));
  235. ScopedPointer<WebInputStream> shared
  236. = getSharedWebInputStream (URL ("https://api.roli.com/api/v1/user/products/redeem").withPOSTData (postData), true);
  237. if (shared != nullptr)
  238. {
  239. int statusCode = shared->withExtraHeaders (accessTokenHeader)
  240. .withExtraHeaders ("Content-Type: application/json")
  241. .getStatusCode();
  242. if (statusCode == 200)
  243. selectNewLicense = false;
  244. continue;
  245. }
  246. }
  247. break;
  248. }
  249. HashMap<String, String> result;
  250. if (requiredWebview && ! threadShouldExit())
  251. queryWebview ("https://juce.com/webviews/registration-complete", "licence_provisioned", result);
  252. stateToUpdate.type = getBestLicenseTypeFromLicenses (licenses);
  253. }
  254. //==============================================================================
  255. void run() override
  256. {
  257. LicenseState workState (owner.state);
  258. while (! threadShouldExit())
  259. {
  260. workState.authToken = getAuthToken();
  261. if (workState.authToken.isEmpty())
  262. return;
  263. // read the user information
  264. updateUserInfo (workState);
  265. if (threadShouldExit())
  266. return;
  267. updateIfChanged (workState);
  268. // if the last step logged us out then retry
  269. if (workState.authToken.isEmpty())
  270. continue;
  271. // check if the license has changed
  272. updateLicenseType (workState);
  273. if (threadShouldExit())
  274. return;
  275. updateIfChanged (workState);
  276. closeWebviewOnMessageThread (0);
  277. finished.wait (60 * 5 * 1000);
  278. }
  279. }
  280. //==============================================================================
  281. LicenseState licenseStateFromJSON (const var& json, const String& authToken, const Image& fallbackAvatar)
  282. {
  283. static Identifier usernameIdentifier ("username");
  284. static Identifier emailIdentifier ("email");
  285. static Identifier avatarURLIdentifier ("avatar_url");
  286. LicenseState result;
  287. if (auto* obj = json.getDynamicObject())
  288. {
  289. result.type = LicenseState::Type::noLicenseChosenYet;
  290. result.username = obj->getProperty (usernameIdentifier);
  291. result.authToken = authToken;
  292. result.email = obj->getProperty (emailIdentifier);
  293. result.avatar = fallbackAvatar;
  294. String avatarURL = obj->getProperty (avatarURLIdentifier);
  295. if (avatarURL.isNotEmpty())
  296. {
  297. if (ScopedPointer<WebInputStream> shared = getSharedWebInputStream (URL (avatarURL), false))
  298. {
  299. MemoryBlock mb;
  300. shared->readIntoMemoryBlock (mb);
  301. result.avatar = ImageFileFormat::loadFrom (mb.getData(), mb.getSize());
  302. }
  303. }
  304. }
  305. return result;
  306. }
  307. //==============================================================================
  308. bool queryWebview (const String& startURL, const String& valueToQuery, HashMap<String, String>& result)
  309. {
  310. executeOnMessageThreadAndBlock ([&] () { owner.queryWebview (startURL, valueToQuery, result); }, false);
  311. return (! threadShouldExit());
  312. }
  313. void closeWebviewOnMessageThread (int result)
  314. {
  315. executeOnMessageThreadAndBlock ([this, result] () { owner.closeWebview (result); });
  316. }
  317. static bool stringArrayContainsSubstring (const StringArray& stringArray, const String& substring)
  318. {
  319. jassert (substring.isNotEmpty());
  320. for (auto element : stringArray)
  321. if (element.containsIgnoreCase (substring))
  322. return true;
  323. return false;
  324. }
  325. static LicenseState::Type getBestLicenseTypeFromLicenses (const StringArray& licenses)
  326. {
  327. if (stringArrayContainsSubstring (licenses, "juce-pro")) return LicenseState::Type::pro;
  328. else if (stringArrayContainsSubstring (licenses, "juce-indie")) return LicenseState::Type::indie;
  329. else if (stringArrayContainsSubstring (licenses, "juce-personal")) return LicenseState::Type::personal;
  330. else if (stringArrayContainsSubstring (licenses, "juce-edu")) return LicenseState::Type::edu;
  331. return LicenseState::Type::noLicenseChosenYet;
  332. }
  333. void updateIfChanged (const LicenseState& newState)
  334. {
  335. LicenseState updatedState (owner.state);
  336. bool changed = false;
  337. bool shouldUpdateLicenseType = (newState.type != LicenseState::Type::noLicenseChosenYet
  338. || updatedState.type == LicenseState::Type::notLoggedIn);
  339. if (newState.type != LicenseState::Type::notLoggedIn) updatedState.avatar = newState.avatar;
  340. if (owner.state.type != newState.type && shouldUpdateLicenseType) { updatedState.type = newState.type; changed = true; }
  341. if (owner.state.authToken != newState.authToken) { updatedState.authToken = newState.authToken; changed = true; }
  342. if (owner.state.username != newState.username) { updatedState.username = newState.username; changed = true; }
  343. if (owner.state.email != newState.email) { updatedState.email = newState.email; changed = true; }
  344. if (owner.state.avatar.isValid() != newState.avatar.isValid()) { changed = true; }
  345. if (changed)
  346. executeOnMessageThreadAndBlock ([this, updatedState]() { owner.updateState (updatedState); });
  347. }
  348. //==============================================================================
  349. LicenseController& owner;
  350. bool selectNewLicense;
  351. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (LicenseThread)
  352. };