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.

992 lines
46KB

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