Audio plugin host https://kx.studio/carla
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.

999 lines
46KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. namespace PushNotificationsDelegateDetails
  21. {
  22. //==============================================================================
  23. using Action = PushNotifications::Settings::Action;
  24. using Category = PushNotifications::Settings::Category;
  25. void* actionToNSAction (const Action& a, bool iOSEarlierThan10)
  26. {
  27. if (iOSEarlierThan10)
  28. {
  29. auto action = [[UIMutableUserNotificationAction alloc] init];
  30. action.identifier = juceStringToNS (a.identifier);
  31. action.title = juceStringToNS (a.title);
  32. action.behavior = a.style == Action::text ? UIUserNotificationActionBehaviorTextInput
  33. : UIUserNotificationActionBehaviorDefault;
  34. action.parameters = varObjectToNSDictionary (a.parameters);
  35. action.activationMode = a.triggerInBackground ? UIUserNotificationActivationModeBackground
  36. : UIUserNotificationActivationModeForeground;
  37. action.destructive = (bool) a.destructive;
  38. [action autorelease];
  39. return action;
  40. }
  41. else
  42. {
  43. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  44. if (a.style == Action::text)
  45. {
  46. return [UNTextInputNotificationAction actionWithIdentifier: juceStringToNS (a.identifier)
  47. title: juceStringToNS (a.title)
  48. options: NSUInteger (a.destructive << 1 | (! a.triggerInBackground) << 2)
  49. textInputButtonTitle: juceStringToNS (a.textInputButtonText)
  50. textInputPlaceholder: juceStringToNS (a.textInputPlaceholder)];
  51. }
  52. return [UNNotificationAction actionWithIdentifier: juceStringToNS (a.identifier)
  53. title: juceStringToNS (a.title)
  54. options: NSUInteger (a.destructive << 1 | (! a.triggerInBackground) << 2)];
  55. #else
  56. return nullptr;
  57. #endif
  58. }
  59. }
  60. void* categoryToNSCategory (const Category& c, bool iOSEarlierThan10)
  61. {
  62. if (iOSEarlierThan10)
  63. {
  64. auto category = [[UIMutableUserNotificationCategory alloc] init];
  65. category.identifier = juceStringToNS (c.identifier);
  66. auto actions = [NSMutableArray arrayWithCapacity: (NSUInteger) c.actions.size()];
  67. for (const auto& a : c.actions)
  68. {
  69. auto* action = (UIUserNotificationAction*) actionToNSAction (a, iOSEarlierThan10);
  70. [actions addObject: action];
  71. }
  72. [category setActions: actions forContext: UIUserNotificationActionContextDefault];
  73. [category setActions: actions forContext: UIUserNotificationActionContextMinimal];
  74. [category autorelease];
  75. return category;
  76. }
  77. else
  78. {
  79. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  80. auto actions = [NSMutableArray arrayWithCapacity: (NSUInteger) c.actions.size()];
  81. for (const auto& a : c.actions)
  82. {
  83. auto* action = (UNNotificationAction*) actionToNSAction (a, iOSEarlierThan10);
  84. [actions addObject: action];
  85. }
  86. return [UNNotificationCategory categoryWithIdentifier: juceStringToNS (c.identifier)
  87. actions: actions
  88. intentIdentifiers: @[]
  89. options: c.sendDismissAction ? UNNotificationCategoryOptionCustomDismissAction : 0];
  90. #else
  91. return nullptr;
  92. #endif
  93. }
  94. }
  95. //==============================================================================
  96. UILocalNotification* juceNotificationToUILocalNotification (const PushNotifications::Notification& n)
  97. {
  98. auto notification = [[UILocalNotification alloc] init];
  99. notification.alertTitle = juceStringToNS (n.title);
  100. notification.alertBody = juceStringToNS (n.body);
  101. notification.category = juceStringToNS (n.category);
  102. notification.applicationIconBadgeNumber = n.badgeNumber;
  103. auto triggerTime = Time::getCurrentTime() + RelativeTime (n.triggerIntervalSec);
  104. notification.fireDate = [NSDate dateWithTimeIntervalSince1970: triggerTime.toMilliseconds() / 1000.];
  105. notification.userInfo = varObjectToNSDictionary (n.properties);
  106. auto soundToPlayString = n.soundToPlay.toString (true);
  107. if (soundToPlayString == "default_os_sound")
  108. notification.soundName = UILocalNotificationDefaultSoundName;
  109. else if (soundToPlayString.isNotEmpty())
  110. notification.soundName = juceStringToNS (soundToPlayString);
  111. return notification;
  112. }
  113. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  114. UNNotificationRequest* juceNotificationToUNNotificationRequest (const PushNotifications::Notification& n)
  115. {
  116. // content
  117. auto content = [[UNMutableNotificationContent alloc] init];
  118. content.title = juceStringToNS (n.title);
  119. content.subtitle = juceStringToNS (n.subtitle);
  120. content.threadIdentifier = juceStringToNS (n.groupId);
  121. content.body = juceStringToNS (n.body);
  122. content.categoryIdentifier = juceStringToNS (n.category);
  123. content.badge = [NSNumber numberWithInt: n.badgeNumber];
  124. auto soundToPlayString = n.soundToPlay.toString (true);
  125. if (soundToPlayString == "default_os_sound")
  126. content.sound = [UNNotificationSound defaultSound];
  127. else if (soundToPlayString.isNotEmpty())
  128. content.sound = [UNNotificationSound soundNamed: juceStringToNS (soundToPlayString)];
  129. auto* propsDict = (NSMutableDictionary*) varObjectToNSDictionary (n.properties);
  130. [propsDict setObject: juceStringToNS (soundToPlayString) forKey: nsStringLiteral ("com.juce.soundName")];
  131. content.userInfo = propsDict;
  132. // trigger
  133. UNTimeIntervalNotificationTrigger* trigger = nil;
  134. if (std::abs (n.triggerIntervalSec) >= 0.001)
  135. {
  136. BOOL shouldRepeat = n.repeat && n.triggerIntervalSec >= 60;
  137. trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval: n.triggerIntervalSec repeats: shouldRepeat];
  138. }
  139. // request
  140. // each notification on iOS 10 needs to have an identifier, otherwise it will not show up
  141. jassert (n.identifier.isNotEmpty());
  142. UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier: juceStringToNS (n.identifier)
  143. content: content
  144. trigger: trigger];
  145. [content autorelease];
  146. return request;
  147. }
  148. #endif
  149. String getUserResponseFromNSDictionary (NSDictionary* dictionary)
  150. {
  151. if (dictionary == nil || dictionary.count == 0)
  152. return {};
  153. jassert (dictionary.count == 1);
  154. for (NSString* key in dictionary)
  155. {
  156. const auto keyString = nsStringToJuce (key);
  157. id value = dictionary[key];
  158. if ([value isKindOfClass: [NSString class]])
  159. return nsStringToJuce ((NSString*) value);
  160. }
  161. jassertfalse;
  162. return {};
  163. }
  164. //==============================================================================
  165. var getNotificationPropertiesFromDictionaryVar (const var& dictionaryVar)
  166. {
  167. DynamicObject* dictionaryVarObject = dictionaryVar.getDynamicObject();
  168. if (dictionaryVarObject == nullptr)
  169. return {};
  170. const auto& properties = dictionaryVarObject->getProperties();
  171. DynamicObject::Ptr propsVarObject = new DynamicObject();
  172. for (int i = 0; i < properties.size(); ++i)
  173. {
  174. auto propertyName = properties.getName (i).toString();
  175. if (propertyName == "aps")
  176. continue;
  177. propsVarObject->setProperty (propertyName, properties.getValueAt (i));
  178. }
  179. return var (propsVarObject.get());
  180. }
  181. //==============================================================================
  182. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  183. double getIntervalSecFromUNNotificationTrigger (UNNotificationTrigger* t)
  184. {
  185. if (t != nil)
  186. {
  187. if ([t isKindOfClass: [UNTimeIntervalNotificationTrigger class]])
  188. {
  189. auto* trigger = (UNTimeIntervalNotificationTrigger*) t;
  190. return trigger.timeInterval;
  191. }
  192. else if ([t isKindOfClass: [UNCalendarNotificationTrigger class]])
  193. {
  194. auto* trigger = (UNCalendarNotificationTrigger*) t;
  195. NSDate* date = [trigger.dateComponents date];
  196. NSDate* dateNow = [NSDate date];
  197. return [dateNow timeIntervalSinceDate: date];
  198. }
  199. }
  200. return 0.;
  201. }
  202. PushNotifications::Notification unNotificationRequestToJuceNotification (UNNotificationRequest* r)
  203. {
  204. PushNotifications::Notification n;
  205. n.identifier = nsStringToJuce (r.identifier);
  206. n.title = nsStringToJuce (r.content.title);
  207. n.subtitle = nsStringToJuce (r.content.subtitle);
  208. n.body = nsStringToJuce (r.content.body);
  209. n.groupId = nsStringToJuce (r.content.threadIdentifier);
  210. n.category = nsStringToJuce (r.content.categoryIdentifier);
  211. n.badgeNumber = r.content.badge.intValue;
  212. auto userInfoVar = nsDictionaryToVar (r.content.userInfo);
  213. if (auto* object = userInfoVar.getDynamicObject())
  214. {
  215. static const Identifier soundName ("com.juce.soundName");
  216. n.soundToPlay = URL (object->getProperty (soundName).toString());
  217. object->removeProperty (soundName);
  218. }
  219. n.properties = userInfoVar;
  220. n.triggerIntervalSec = getIntervalSecFromUNNotificationTrigger (r.trigger);
  221. n.repeat = r.trigger != nil && r.trigger.repeats;
  222. return n;
  223. }
  224. PushNotifications::Notification unNotificationToJuceNotification (UNNotification* n)
  225. {
  226. return unNotificationRequestToJuceNotification (n.request);
  227. }
  228. #endif
  229. PushNotifications::Notification uiLocalNotificationToJuceNotification (UILocalNotification* n)
  230. {
  231. PushNotifications::Notification notif;
  232. notif.title = nsStringToJuce (n.alertTitle);
  233. notif.body = nsStringToJuce (n.alertBody);
  234. if (n.fireDate != nil)
  235. {
  236. NSDate* dateNow = [NSDate date];
  237. NSDate* fireDate = n.fireDate;
  238. notif.triggerIntervalSec = [dateNow timeIntervalSinceDate: fireDate];
  239. }
  240. notif.soundToPlay = URL (nsStringToJuce (n.soundName));
  241. notif.badgeNumber = (int) n.applicationIconBadgeNumber;
  242. notif.category = nsStringToJuce (n.category);
  243. notif.properties = nsDictionaryToVar (n.userInfo);
  244. return notif;
  245. }
  246. Action uiUserNotificationActionToAction (UIUserNotificationAction* a)
  247. {
  248. Action action;
  249. action.identifier = nsStringToJuce (a.identifier);
  250. action.title = nsStringToJuce (a.title);
  251. action.style = a.behavior == UIUserNotificationActionBehaviorTextInput
  252. ? Action::text
  253. : Action::button;
  254. action.triggerInBackground = a.activationMode == UIUserNotificationActivationModeBackground;
  255. action.destructive = a.destructive;
  256. action.parameters = nsDictionaryToVar (a.parameters);
  257. return action;
  258. }
  259. Category uiUserNotificationCategoryToCategory (UIUserNotificationCategory* c)
  260. {
  261. Category category;
  262. category.identifier = nsStringToJuce (c.identifier);
  263. for (UIUserNotificationAction* a in [c actionsForContext: UIUserNotificationActionContextDefault])
  264. category.actions.add (uiUserNotificationActionToAction (a));
  265. return category;
  266. }
  267. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  268. Action unNotificationActionToAction (UNNotificationAction* a)
  269. {
  270. Action action;
  271. action.identifier = nsStringToJuce (a.identifier);
  272. action.title = nsStringToJuce (a.title);
  273. action.triggerInBackground = ! (a.options & UNNotificationActionOptionForeground);
  274. action.destructive = a.options & UNNotificationActionOptionDestructive;
  275. if ([a isKindOfClass: [UNTextInputNotificationAction class]])
  276. {
  277. auto* textAction = (UNTextInputNotificationAction*)a;
  278. action.style = Action::text;
  279. action.textInputButtonText = nsStringToJuce (textAction.textInputButtonTitle);
  280. action.textInputPlaceholder = nsStringToJuce (textAction.textInputPlaceholder);
  281. }
  282. else
  283. {
  284. action.style = Action::button;
  285. }
  286. return action;
  287. }
  288. Category unNotificationCategoryToCategory (UNNotificationCategory* c)
  289. {
  290. Category category;
  291. category.identifier = nsStringToJuce (c.identifier);
  292. category.sendDismissAction = c.options & UNNotificationCategoryOptionCustomDismissAction;
  293. for (UNNotificationAction* a in c.actions)
  294. category.actions.add (unNotificationActionToAction (a));
  295. return category;
  296. }
  297. #endif
  298. PushNotifications::Notification nsDictionaryToJuceNotification (NSDictionary* dictionary)
  299. {
  300. const var dictionaryVar = nsDictionaryToVar (dictionary);
  301. const var apsVar = dictionaryVar.getProperty ("aps", {});
  302. if (! apsVar.isObject())
  303. return {};
  304. var alertVar = apsVar.getProperty ("alert", {});
  305. const var titleVar = alertVar.getProperty ("title", {});
  306. const var bodyVar = alertVar.isObject() ? alertVar.getProperty ("body", {}) : alertVar;
  307. const var categoryVar = apsVar.getProperty ("category", {});
  308. const var soundVar = apsVar.getProperty ("sound", {});
  309. const var badgeVar = apsVar.getProperty ("badge", {});
  310. const var threadIdVar = apsVar.getProperty ("thread-id", {});
  311. PushNotifications::Notification notification;
  312. notification.title = titleVar .toString();
  313. notification.body = bodyVar .toString();
  314. notification.groupId = threadIdVar.toString();
  315. notification.category = categoryVar.toString();
  316. notification.soundToPlay = URL (soundVar.toString());
  317. notification.badgeNumber = (int) badgeVar;
  318. notification.properties = getNotificationPropertiesFromDictionaryVar (dictionaryVar);
  319. return notification;
  320. }
  321. }
  322. //==============================================================================
  323. struct PushNotificationsDelegate
  324. {
  325. PushNotificationsDelegate() : delegate ([getClass().createInstance() init])
  326. {
  327. Class::setThis (delegate.get(), this);
  328. id<UIApplicationDelegate> appDelegate = [[UIApplication sharedApplication] delegate];
  329. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  330. if ([appDelegate respondsToSelector: @selector (setPushNotificationsDelegateToUse:)])
  331. [appDelegate performSelector: @selector (setPushNotificationsDelegateToUse:) withObject: delegate.get()];
  332. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  333. }
  334. virtual ~PushNotificationsDelegate() {}
  335. virtual void didRegisterUserNotificationSettings (UIUserNotificationSettings* notificationSettings) = 0;
  336. virtual void registeredForRemoteNotifications (NSData* deviceToken) = 0;
  337. virtual void failedToRegisterForRemoteNotifications (NSError* error) = 0;
  338. virtual void didReceiveRemoteNotification (NSDictionary* userInfo) = 0;
  339. virtual void didReceiveRemoteNotificationFetchCompletionHandler (NSDictionary* userInfo,
  340. void (^completionHandler)(UIBackgroundFetchResult result)) = 0;
  341. virtual void handleActionForRemoteNotificationCompletionHandler (NSString* actionIdentifier,
  342. NSDictionary* userInfo,
  343. NSDictionary* responseInfo,
  344. void (^completionHandler)()) = 0;
  345. virtual void didReceiveLocalNotification (UILocalNotification* notification) = 0;
  346. virtual void handleActionForLocalNotificationCompletionHandler (NSString* actionIdentifier,
  347. UILocalNotification* notification,
  348. void (^completionHandler)()) = 0;
  349. virtual void handleActionForLocalNotificationWithResponseCompletionHandler (NSString* actionIdentifier,
  350. UILocalNotification* notification,
  351. NSDictionary* responseInfo,
  352. void (^completionHandler)()) = 0;
  353. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  354. virtual void willPresentNotificationWithCompletionHandler (UNNotification* notification,
  355. void (^completionHandler)(UNNotificationPresentationOptions options)) = 0;
  356. virtual void didReceiveNotificationResponseWithCompletionHandler (UNNotificationResponse* response,
  357. void (^completionHandler)()) = 0;
  358. #endif
  359. protected:
  360. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  361. NSUniquePtr<NSObject<UIApplicationDelegate, UNUserNotificationCenterDelegate>> delegate;
  362. #else
  363. NSUniquePtr<NSObject<UIApplicationDelegate>> delegate;
  364. #endif
  365. private:
  366. //==============================================================================
  367. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  368. struct Class : public ObjCClass<NSObject<UIApplicationDelegate, UNUserNotificationCenterDelegate>>
  369. {
  370. Class() : ObjCClass<NSObject<UIApplicationDelegate, UNUserNotificationCenterDelegate>> ("JucePushNotificationsDelegate_")
  371. #else
  372. struct Class : public ObjCClass<NSObject<UIApplicationDelegate>>
  373. {
  374. Class() : ObjCClass<NSObject<UIApplicationDelegate>> ("JucePushNotificationsDelegate_")
  375. #endif
  376. {
  377. addIvar<PushNotificationsDelegate*> ("self");
  378. addMethod (@selector (application:didRegisterUserNotificationSettings:), didRegisterUserNotificationSettings);
  379. addMethod (@selector (application:didRegisterForRemoteNotificationsWithDeviceToken:), registeredForRemoteNotifications);
  380. addMethod (@selector (application:didFailToRegisterForRemoteNotificationsWithError:), failedToRegisterForRemoteNotifications);
  381. addMethod (@selector (application:didReceiveRemoteNotification:), didReceiveRemoteNotification);
  382. addMethod (@selector (application:didReceiveRemoteNotification:fetchCompletionHandler:), didReceiveRemoteNotificationFetchCompletionHandler);
  383. addMethod (@selector (application:handleActionWithIdentifier:forRemoteNotification:withResponseInfo:completionHandler:), handleActionForRemoteNotificationCompletionHandler);
  384. addMethod (@selector (application:didReceiveLocalNotification:), didReceiveLocalNotification);
  385. addMethod (@selector (application:handleActionWithIdentifier:forLocalNotification:completionHandler:), handleActionForLocalNotificationCompletionHandler);
  386. addMethod (@selector (application:handleActionWithIdentifier:forLocalNotification:withResponseInfo:completionHandler:), handleActionForLocalNotificationWithResponseCompletionHandler);
  387. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  388. addMethod (@selector (userNotificationCenter:willPresentNotification:withCompletionHandler:), willPresentNotificationWithCompletionHandler);
  389. addMethod (@selector (userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:), didReceiveNotificationResponseWithCompletionHandler);
  390. #endif
  391. registerClass();
  392. }
  393. //==============================================================================
  394. static PushNotificationsDelegate& getThis (id self) { return *getIvar<PushNotificationsDelegate*> (self, "self"); }
  395. static void setThis (id self, PushNotificationsDelegate* d) { object_setInstanceVariable (self, "self", d); }
  396. //==============================================================================
  397. static void didRegisterUserNotificationSettings (id self, SEL, UIApplication*,
  398. UIUserNotificationSettings* settings) { getThis (self).didRegisterUserNotificationSettings (settings); }
  399. static void registeredForRemoteNotifications (id self, SEL, UIApplication*,
  400. NSData* deviceToken) { getThis (self).registeredForRemoteNotifications (deviceToken); }
  401. static void failedToRegisterForRemoteNotifications (id self, SEL, UIApplication*,
  402. NSError* error) { getThis (self).failedToRegisterForRemoteNotifications (error); }
  403. static void didReceiveRemoteNotification (id self, SEL, UIApplication*,
  404. NSDictionary* userInfo) { getThis (self).didReceiveRemoteNotification (userInfo); }
  405. static void didReceiveRemoteNotificationFetchCompletionHandler (id self, SEL, UIApplication*,
  406. NSDictionary* userInfo,
  407. void (^completionHandler)(UIBackgroundFetchResult result)) { getThis (self).didReceiveRemoteNotificationFetchCompletionHandler (userInfo, completionHandler); }
  408. static void handleActionForRemoteNotificationCompletionHandler (id self, SEL, UIApplication*,
  409. NSString* actionIdentifier,
  410. NSDictionary* userInfo,
  411. NSDictionary* responseInfo,
  412. void (^completionHandler)()) { getThis (self).handleActionForRemoteNotificationCompletionHandler (actionIdentifier, userInfo, responseInfo, completionHandler); }
  413. static void didReceiveLocalNotification (id self, SEL, UIApplication*,
  414. UILocalNotification* notification) { getThis (self).didReceiveLocalNotification (notification); }
  415. static void handleActionForLocalNotificationCompletionHandler (id self, SEL, UIApplication*,
  416. NSString* actionIdentifier,
  417. UILocalNotification* notification,
  418. void (^completionHandler)()) { getThis (self).handleActionForLocalNotificationCompletionHandler (actionIdentifier, notification, completionHandler); }
  419. static void handleActionForLocalNotificationWithResponseCompletionHandler (id self, SEL, UIApplication*,
  420. NSString* actionIdentifier,
  421. UILocalNotification* notification,
  422. NSDictionary* responseInfo,
  423. void (^completionHandler)()) { getThis (self). handleActionForLocalNotificationWithResponseCompletionHandler (actionIdentifier, notification, responseInfo, completionHandler); }
  424. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  425. static void willPresentNotificationWithCompletionHandler (id self, SEL, UNUserNotificationCenter*,
  426. UNNotification* notification,
  427. void (^completionHandler)(UNNotificationPresentationOptions options)) { getThis (self).willPresentNotificationWithCompletionHandler (notification, completionHandler); }
  428. static void didReceiveNotificationResponseWithCompletionHandler (id self, SEL, UNUserNotificationCenter*,
  429. UNNotificationResponse* response,
  430. void (^completionHandler)()) { getThis (self).didReceiveNotificationResponseWithCompletionHandler (response, completionHandler); }
  431. #endif
  432. };
  433. //==============================================================================
  434. static Class& getClass()
  435. {
  436. static Class c;
  437. return c;
  438. }
  439. };
  440. //==============================================================================
  441. bool PushNotifications::Notification::isValid() const noexcept
  442. {
  443. const bool iOSEarlierThan10 = std::floor (NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max;
  444. if (iOSEarlierThan10)
  445. return title.isNotEmpty() && body.isNotEmpty() && category.isNotEmpty();
  446. return title.isNotEmpty() && body.isNotEmpty() && identifier.isNotEmpty() && category.isNotEmpty();
  447. }
  448. //==============================================================================
  449. struct PushNotifications::Pimpl : private PushNotificationsDelegate
  450. {
  451. Pimpl (PushNotifications& p)
  452. : owner (p)
  453. {
  454. }
  455. void requestPermissionsWithSettings (const PushNotifications::Settings& settingsToUse)
  456. {
  457. settings = settingsToUse;
  458. auto categories = [NSMutableSet setWithCapacity: (NSUInteger) settings.categories.size()];
  459. if (iOSEarlierThan10)
  460. {
  461. for (const auto& c : settings.categories)
  462. {
  463. auto* category = (UIUserNotificationCategory*) PushNotificationsDelegateDetails::categoryToNSCategory (c, iOSEarlierThan10);
  464. [categories addObject: category];
  465. }
  466. UIUserNotificationType type = NSUInteger ((bool)settings.allowBadge << 0
  467. | (bool)settings.allowSound << 1
  468. | (bool)settings.allowAlert << 2);
  469. UIUserNotificationSettings* s = [UIUserNotificationSettings settingsForTypes: type categories: categories];
  470. [[UIApplication sharedApplication] registerUserNotificationSettings: s];
  471. }
  472. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  473. else
  474. {
  475. for (const auto& c : settings.categories)
  476. {
  477. auto* category = (UNNotificationCategory*) PushNotificationsDelegateDetails::categoryToNSCategory (c, iOSEarlierThan10);
  478. [categories addObject: category];
  479. }
  480. UNAuthorizationOptions authOptions = NSUInteger ((bool)settings.allowBadge << 0
  481. | (bool)settings.allowSound << 1
  482. | (bool)settings.allowAlert << 2);
  483. [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories: categories];
  484. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions: authOptions
  485. completionHandler: ^(BOOL /*granted*/, NSError* /*error*/)
  486. {
  487. requestSettingsUsed();
  488. }];
  489. }
  490. #endif
  491. [[UIApplication sharedApplication] registerForRemoteNotifications];
  492. }
  493. void requestSettingsUsed()
  494. {
  495. if (iOSEarlierThan10)
  496. {
  497. UIUserNotificationSettings* s = [UIApplication sharedApplication].currentUserNotificationSettings;
  498. settings.allowBadge = s.types & UIUserNotificationTypeBadge;
  499. settings.allowSound = s.types & UIUserNotificationTypeSound;
  500. settings.allowAlert = s.types & UIUserNotificationTypeAlert;
  501. for (UIUserNotificationCategory *c in s.categories)
  502. settings.categories.add (PushNotificationsDelegateDetails::uiUserNotificationCategoryToCategory (c));
  503. owner.listeners.call ([&] (Listener& l) { l.notificationSettingsReceived (settings); });
  504. }
  505. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  506. else
  507. {
  508. [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:
  509. ^(UNNotificationSettings* s)
  510. {
  511. [[UNUserNotificationCenter currentNotificationCenter] getNotificationCategoriesWithCompletionHandler:
  512. ^(NSSet<UNNotificationCategory*>* categories)
  513. {
  514. settings.allowBadge = s.badgeSetting == UNNotificationSettingEnabled;
  515. settings.allowSound = s.soundSetting == UNNotificationSettingEnabled;
  516. settings.allowAlert = s.alertSetting == UNNotificationSettingEnabled;
  517. for (UNNotificationCategory* c in categories)
  518. settings.categories.add (PushNotificationsDelegateDetails::unNotificationCategoryToCategory (c));
  519. owner.listeners.call ([&] (Listener& l) { l.notificationSettingsReceived (settings); });
  520. }
  521. ];
  522. }];
  523. }
  524. #endif
  525. }
  526. bool areNotificationsEnabled() const { return true; }
  527. void sendLocalNotification (const Notification& n)
  528. {
  529. if (iOSEarlierThan10)
  530. {
  531. auto* notification = PushNotificationsDelegateDetails::juceNotificationToUILocalNotification (n);
  532. [[UIApplication sharedApplication] scheduleLocalNotification: notification];
  533. [notification release];
  534. }
  535. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  536. else
  537. {
  538. UNNotificationRequest* request = PushNotificationsDelegateDetails::juceNotificationToUNNotificationRequest (n);
  539. [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest: request
  540. withCompletionHandler: ^(NSError* error)
  541. {
  542. jassert (error == nil);
  543. if (error != nil)
  544. NSLog (nsStringLiteral ("addNotificationRequest error: %@"), error);
  545. }];
  546. }
  547. #endif
  548. }
  549. void getDeliveredNotifications() const
  550. {
  551. if (iOSEarlierThan10)
  552. {
  553. // Not supported on this platform
  554. jassertfalse;
  555. owner.listeners.call ([] (Listener& l) { l.deliveredNotificationsListReceived ({}); });
  556. }
  557. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  558. else
  559. {
  560. [[UNUserNotificationCenter currentNotificationCenter] getDeliveredNotificationsWithCompletionHandler:
  561. ^(NSArray<UNNotification*>* notifications)
  562. {
  563. Array<PushNotifications::Notification> notifs;
  564. for (UNNotification* n in notifications)
  565. notifs.add (PushNotificationsDelegateDetails::unNotificationToJuceNotification (n));
  566. owner.listeners.call ([&] (Listener& l) { l.deliveredNotificationsListReceived (notifs); });
  567. }];
  568. }
  569. #endif
  570. }
  571. void removeAllDeliveredNotifications()
  572. {
  573. if (iOSEarlierThan10)
  574. {
  575. // Not supported on this platform
  576. jassertfalse;
  577. }
  578. else
  579. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  580. {
  581. [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  582. }
  583. #endif
  584. }
  585. void removeDeliveredNotification (const String& identifier)
  586. {
  587. if (iOSEarlierThan10)
  588. {
  589. ignoreUnused (identifier);
  590. // Not supported on this platform
  591. jassertfalse;
  592. }
  593. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  594. else
  595. {
  596. NSArray<NSString*>* identifiers = [NSArray arrayWithObject: juceStringToNS (identifier)];
  597. [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers: identifiers];
  598. }
  599. #endif
  600. }
  601. void setupChannels (const Array<ChannelGroup>& groups, const Array<Channel>& channels)
  602. {
  603. ignoreUnused (groups, channels);
  604. }
  605. void getPendingLocalNotifications() const
  606. {
  607. if (iOSEarlierThan10)
  608. {
  609. Array<PushNotifications::Notification> notifs;
  610. for (UILocalNotification* n in [UIApplication sharedApplication].scheduledLocalNotifications)
  611. notifs.add (PushNotificationsDelegateDetails::uiLocalNotificationToJuceNotification (n));
  612. owner.listeners.call ([&] (Listener& l) { l.pendingLocalNotificationsListReceived (notifs); });
  613. }
  614. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  615. else
  616. {
  617. [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:
  618. ^(NSArray<UNNotificationRequest*>* requests)
  619. {
  620. Array<PushNotifications::Notification> notifs;
  621. for (UNNotificationRequest* r : requests)
  622. notifs.add (PushNotificationsDelegateDetails::unNotificationRequestToJuceNotification (r));
  623. owner.listeners.call ([&] (Listener& l) { l.pendingLocalNotificationsListReceived (notifs); });
  624. }
  625. ];
  626. }
  627. #endif
  628. }
  629. void removePendingLocalNotification (const String& identifier)
  630. {
  631. if (iOSEarlierThan10)
  632. {
  633. // Not supported on this platform
  634. jassertfalse;
  635. }
  636. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  637. else
  638. {
  639. NSArray<NSString*>* identifiers = [NSArray arrayWithObject: juceStringToNS (identifier)];
  640. [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers: identifiers];
  641. }
  642. #endif
  643. }
  644. void removeAllPendingLocalNotifications()
  645. {
  646. if (iOSEarlierThan10)
  647. {
  648. [[UIApplication sharedApplication] cancelAllLocalNotifications];
  649. }
  650. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  651. else
  652. {
  653. [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
  654. }
  655. #endif
  656. }
  657. String getDeviceToken()
  658. {
  659. // You need to call requestPermissionsWithSettings() first.
  660. jassert (initialised);
  661. return deviceToken;
  662. }
  663. //==============================================================================
  664. //PushNotificationsDelegate
  665. void didRegisterUserNotificationSettings (UIUserNotificationSettings*) override
  666. {
  667. requestSettingsUsed();
  668. }
  669. void registeredForRemoteNotifications (NSData* deviceTokenToUse) override
  670. {
  671. deviceToken = [deviceTokenToUse]() -> String
  672. {
  673. auto length = deviceTokenToUse.length;
  674. if (auto* buffer = (const unsigned char*) deviceTokenToUse.bytes)
  675. {
  676. NSMutableString* hexString = [NSMutableString stringWithCapacity: (length * 2)];
  677. for (NSUInteger i = 0; i < length; ++i)
  678. [hexString appendFormat:@"%02x", buffer[i]];
  679. return nsStringToJuce ([hexString copy]);
  680. }
  681. return {};
  682. }();
  683. initialised = true;
  684. owner.listeners.call ([&] (Listener& l) { l.deviceTokenRefreshed (deviceToken); });
  685. }
  686. void failedToRegisterForRemoteNotifications (NSError* error) override
  687. {
  688. ignoreUnused (error);
  689. deviceToken.clear();
  690. }
  691. void didReceiveRemoteNotification (NSDictionary* userInfo) override
  692. {
  693. auto n = PushNotificationsDelegateDetails::nsDictionaryToJuceNotification (userInfo);
  694. owner.listeners.call ([&] (Listener& l) { l.handleNotification (false, n); });
  695. }
  696. void didReceiveRemoteNotificationFetchCompletionHandler (NSDictionary* userInfo,
  697. void (^completionHandler)(UIBackgroundFetchResult result)) override
  698. {
  699. didReceiveRemoteNotification (userInfo);
  700. completionHandler (UIBackgroundFetchResultNewData);
  701. }
  702. void handleActionForRemoteNotificationCompletionHandler (NSString* actionIdentifier,
  703. NSDictionary* userInfo,
  704. NSDictionary* responseInfo,
  705. void (^completionHandler)()) override
  706. {
  707. auto n = PushNotificationsDelegateDetails::nsDictionaryToJuceNotification (userInfo);
  708. auto actionString = nsStringToJuce (actionIdentifier);
  709. auto response = PushNotificationsDelegateDetails::getUserResponseFromNSDictionary (responseInfo);
  710. owner.listeners.call ([&] (Listener& l) { l.handleNotificationAction (false, n, actionString, response); });
  711. completionHandler();
  712. }
  713. void didReceiveLocalNotification (UILocalNotification* notification) override
  714. {
  715. auto n = PushNotificationsDelegateDetails::uiLocalNotificationToJuceNotification (notification);
  716. owner.listeners.call ([&] (Listener& l) { l.handleNotification (true, n); });
  717. }
  718. void handleActionForLocalNotificationCompletionHandler (NSString* actionIdentifier,
  719. UILocalNotification* notification,
  720. void (^completionHandler)()) override
  721. {
  722. handleActionForLocalNotificationWithResponseCompletionHandler (actionIdentifier,
  723. notification,
  724. nil,
  725. completionHandler);
  726. }
  727. void handleActionForLocalNotificationWithResponseCompletionHandler (NSString* actionIdentifier,
  728. UILocalNotification* notification,
  729. NSDictionary* responseInfo,
  730. void (^completionHandler)()) override
  731. {
  732. auto n = PushNotificationsDelegateDetails::uiLocalNotificationToJuceNotification (notification);
  733. auto actionString = nsStringToJuce (actionIdentifier);
  734. auto response = PushNotificationsDelegateDetails::getUserResponseFromNSDictionary (responseInfo);
  735. owner.listeners.call ([&] (Listener& l) { l.handleNotificationAction (true, n, actionString, response); });
  736. completionHandler();
  737. }
  738. #if defined (__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  739. void willPresentNotificationWithCompletionHandler (UNNotification* notification,
  740. void (^completionHandler)(UNNotificationPresentationOptions options)) override
  741. {
  742. NSUInteger options = NSUInteger ((int)settings.allowBadge << 0
  743. | (int)settings.allowSound << 1
  744. | (int)settings.allowAlert << 2);
  745. ignoreUnused (notification);
  746. completionHandler (options);
  747. }
  748. void didReceiveNotificationResponseWithCompletionHandler (UNNotificationResponse* response,
  749. void (^completionHandler)()) override
  750. {
  751. const bool remote = [response.notification.request.trigger isKindOfClass: [UNPushNotificationTrigger class]];
  752. auto actionString = nsStringToJuce (response.actionIdentifier);
  753. if (actionString == "com.apple.UNNotificationDefaultActionIdentifier")
  754. actionString.clear();
  755. else if (actionString == "com.apple.UNNotificationDismissActionIdentifier")
  756. actionString = "com.juce.NotificationDeleted";
  757. auto n = PushNotificationsDelegateDetails::unNotificationToJuceNotification (response.notification);
  758. String responseString;
  759. if ([response isKindOfClass: [UNTextInputNotificationResponse class]])
  760. {
  761. UNTextInputNotificationResponse* textResponse = (UNTextInputNotificationResponse*)response;
  762. responseString = nsStringToJuce (textResponse.userText);
  763. }
  764. owner.listeners.call ([&] (Listener& l) { l.handleNotificationAction (! remote, n, actionString, responseString); });
  765. completionHandler();
  766. }
  767. #endif
  768. void subscribeToTopic (const String& topic) { ignoreUnused (topic); }
  769. void unsubscribeFromTopic (const String& topic) { ignoreUnused (topic); }
  770. void sendUpstreamMessage (const String& serverSenderId,
  771. const String& collapseKey,
  772. const String& messageId,
  773. const String& messageType,
  774. int timeToLive,
  775. const StringPairArray& additionalData)
  776. {
  777. ignoreUnused (serverSenderId, collapseKey, messageId, messageType);
  778. ignoreUnused (timeToLive, additionalData);
  779. }
  780. private:
  781. PushNotifications& owner;
  782. const bool iOSEarlierThan10 = std::floor (NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max;
  783. bool initialised = false;
  784. String deviceToken;
  785. PushNotifications::Settings settings;
  786. };
  787. } // namespace juce