APPNotificationOptions.m 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. /*
  2. * Apache 2.0 License
  3. *
  4. * Copyright (c) Sebastian Katzer 2017
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apache License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://opensource.org/licenses/Apache-2.0/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. */
  21. #import "APPNotificationOptions.h"
  22. #import "UNUserNotificationCenter+APPLocalNotification.h"
  23. @import CoreLocation;
  24. @import UserNotifications;
  25. @interface APPNotificationOptions ()
  26. // The dictionary which contains all notification properties
  27. @property(nonatomic, retain) NSDictionary* dict;
  28. @end
  29. @implementation APPNotificationOptions : NSObject
  30. @synthesize dict;
  31. #pragma mark -
  32. #pragma mark Initialization
  33. /**
  34. * Initialize by using the given property values.
  35. *
  36. * @param [ NSDictionary* ] dict A key-value property map.
  37. *
  38. * @return [ APPNotificationOptions ]
  39. */
  40. - (id) initWithDict:(NSDictionary*)dictionary
  41. {
  42. self = [self init];
  43. self.dict = dictionary;
  44. [self actions];
  45. return self;
  46. }
  47. #pragma mark -
  48. #pragma mark Properties
  49. /**
  50. * The ID for the notification.
  51. *
  52. * @return [ NSNumber* ]
  53. */
  54. - (NSNumber*) id
  55. {
  56. NSInteger id = [[dict objectForKey:@"id"] integerValue];
  57. return [NSNumber numberWithInteger:id];
  58. }
  59. /**
  60. * The ID for the notification.
  61. *
  62. * @return [ NSString* ]
  63. */
  64. - (NSString*) identifier
  65. {
  66. return [NSString stringWithFormat:@"%@", self.id];
  67. }
  68. /**
  69. * The title for the notification.
  70. *
  71. * @return [ NSString* ]
  72. */
  73. - (NSString*) title
  74. {
  75. return [dict objectForKey:@"title"];
  76. }
  77. /**
  78. * The subtitle for the notification.
  79. *
  80. * @return [ NSString* ]
  81. */
  82. - (NSString*) subtitle
  83. {
  84. NSArray *parts = [self.title componentsSeparatedByString:@"\n"];
  85. return parts.count < 2 ? @"" : [parts objectAtIndex:1];
  86. }
  87. /**
  88. * The text for the notification.
  89. *
  90. * @return [ NSString* ]
  91. */
  92. - (NSString*) text
  93. {
  94. return [dict objectForKey:@"text"];
  95. }
  96. /**
  97. * Show notification.
  98. *
  99. * @return [ BOOL ]
  100. */
  101. - (BOOL) silent
  102. {
  103. return [[dict objectForKey:@"silent"] boolValue];
  104. }
  105. /**
  106. * Show notification in foreground.
  107. *
  108. * @return [ BOOL ]
  109. */
  110. - (int) priority
  111. {
  112. return [[dict objectForKey:@"priority"] intValue];
  113. }
  114. /**
  115. * The badge number for the notification.
  116. *
  117. * @return [ NSNumber* ]
  118. */
  119. - (NSNumber*) badge
  120. {
  121. id value = [dict objectForKey:@"badge"];
  122. return (value == NULL) ? NULL : [NSNumber numberWithInt:[value intValue]];
  123. }
  124. /**
  125. * The category of the notification.
  126. *
  127. * @return [ NSString* ]
  128. */
  129. - (NSString*) categoryId
  130. {
  131. NSString* value = [dict objectForKey:@"actionGroupId"];
  132. return value.length ? value : kAPPGeneralCategory;
  133. }
  134. /**
  135. * The sound file for the notification.
  136. *
  137. * @return [ UNNotificationSound* ]
  138. */
  139. - (UNNotificationSound*) sound
  140. {
  141. NSString* path = [dict objectForKey:@"sound"];
  142. NSString* file;
  143. if ([path isKindOfClass:NSNumber.class]) {
  144. return [path boolValue] ? [UNNotificationSound defaultSound] : NULL;
  145. }
  146. if (!path.length)
  147. return NULL;
  148. if ([path hasPrefix:@"file:/"]) {
  149. file = [self soundNameForAsset:path];
  150. } else
  151. if ([path hasPrefix:@"res:"]) {
  152. file = [self soundNameForResource:path];
  153. }
  154. return [UNNotificationSound soundNamed:file];
  155. }
  156. /**
  157. * Additional content to attach.
  158. *
  159. * @return [ UNNotificationSound* ]
  160. */
  161. - (NSArray<UNNotificationAttachment *> *) attachments
  162. {
  163. NSArray* paths = [dict objectForKey:@"attachments"];
  164. NSMutableArray* attachments = [[NSMutableArray alloc] init];
  165. if (!paths)
  166. return attachments;
  167. for (NSString* path in paths) {
  168. NSURL* url = [self urlForAttachmentPath:path];
  169. UNNotificationAttachment* attachment;
  170. attachment = [UNNotificationAttachment attachmentWithIdentifier:path
  171. URL:url
  172. options:NULL
  173. error:NULL];
  174. if (attachment) {
  175. [attachments addObject:attachment];
  176. }
  177. }
  178. return attachments;
  179. }
  180. /**
  181. * Additional actions for the notification.
  182. *
  183. * @return [ NSArray* ]
  184. */
  185. - (NSArray<UNNotificationAction *> *) actions
  186. {
  187. NSArray* items = [dict objectForKey:@"actions"];
  188. NSMutableArray* actions = [[NSMutableArray alloc] init];
  189. if (!items)
  190. return actions;
  191. for (NSDictionary* item in items) {
  192. NSString* id = [item objectForKey:@"id"];
  193. NSString* title = [item objectForKey:@"title"];
  194. NSString* type = [item objectForKey:@"type"];
  195. UNNotificationActionOptions options = UNNotificationActionOptionNone;
  196. UNNotificationAction* action;
  197. if ([[item objectForKey:@"launch"] boolValue]) {
  198. options = UNNotificationActionOptionForeground;
  199. }
  200. if ([[item objectForKey:@"ui"] isEqualToString:@"decline"]) {
  201. options = options | UNNotificationActionOptionDestructive;
  202. }
  203. if ([[item objectForKey:@"needsAuth"] boolValue]) {
  204. options = options | UNNotificationActionOptionAuthenticationRequired;
  205. }
  206. if ([type isEqualToString:@"input"]) {
  207. NSString* submitTitle = [item objectForKey:@"submitTitle"];
  208. NSString* placeholder = [item objectForKey:@"emptyText"];
  209. if (!submitTitle.length) {
  210. submitTitle = @"Submit";
  211. }
  212. action = [UNTextInputNotificationAction actionWithIdentifier:id
  213. title:title
  214. options:options
  215. textInputButtonTitle:submitTitle
  216. textInputPlaceholder:placeholder];
  217. } else
  218. if (!type.length || [type isEqualToString:@"button"]) {
  219. action = [UNNotificationAction actionWithIdentifier:id
  220. title:title
  221. options:options];
  222. } else {
  223. NSLog(@"Unknown action type: %@", type);
  224. }
  225. if (action) {
  226. [actions addObject:action];
  227. }
  228. }
  229. return actions;
  230. }
  231. #pragma mark -
  232. #pragma mark Public
  233. /**
  234. * Specify how and when to trigger the notification.
  235. *
  236. * @return [ UNNotificationTrigger* ]
  237. */
  238. - (UNNotificationTrigger*) trigger
  239. {
  240. NSString* type = [self valueForTriggerOption:@"type"];
  241. if ([type isEqualToString:@"location"])
  242. return [self triggerWithRegion];
  243. if (![type isEqualToString:@"calendar"])
  244. NSLog(@"Unknown type: %@", type);
  245. if ([self isRepeating])
  246. return [self repeatingTrigger];
  247. return [self nonRepeatingTrigger];
  248. }
  249. /**
  250. * The notification's user info dict.
  251. *
  252. * @return [ NSDictionary* ]
  253. */
  254. - (NSDictionary*) userInfo
  255. {
  256. if ([dict objectForKey:@"updatedAt"]) {
  257. NSMutableDictionary* data = [dict mutableCopy];
  258. [data removeObjectForKey:@"updatedAt"];
  259. return data;
  260. }
  261. return dict;
  262. }
  263. #pragma mark -
  264. #pragma mark Private
  265. - (id) valueForTriggerOption:(NSString*)key
  266. {
  267. return [[dict objectForKey:@"trigger"] objectForKey:key];
  268. }
  269. /**
  270. * The date when to fire the notification.
  271. *
  272. * @return [ NSDate* ]
  273. */
  274. - (NSDate*) triggerDate
  275. {
  276. double timestamp = [[self valueForTriggerOption:@"at"] doubleValue];
  277. return [NSDate dateWithTimeIntervalSince1970:timestamp];
  278. }
  279. /**
  280. * If the notification shall be repeating.
  281. *
  282. * @return [ BOOL ]
  283. */
  284. - (BOOL) isRepeating
  285. {
  286. id every = [self valueForTriggerOption:@"every"];
  287. if ([every isKindOfClass:NSString.class])
  288. return ((NSString*) every).length > 0;
  289. if ([every isKindOfClass:NSDictionary.class])
  290. return ((NSDictionary*) every).count > 0;
  291. return every > 0;
  292. }
  293. /**
  294. * Non repeating trigger.
  295. *
  296. * @return [ UNTimeIntervalNotificationTrigger* ]
  297. */
  298. - (UNNotificationTrigger*) nonRepeatingTrigger
  299. {
  300. id timestamp = [self valueForTriggerOption:@"at"];
  301. if (timestamp) {
  302. return [self triggerWithDateMatchingComponents:NO];
  303. }
  304. return [UNTimeIntervalNotificationTrigger
  305. triggerWithTimeInterval:[self timeInterval] repeats:NO];
  306. }
  307. /**
  308. * Repeating trigger.
  309. *
  310. * @return [ UNNotificationTrigger* ]
  311. */
  312. - (UNNotificationTrigger*) repeatingTrigger
  313. {
  314. id every = [self valueForTriggerOption:@"every"];
  315. if ([every isKindOfClass:NSString.class])
  316. return [self triggerWithDateMatchingComponents:YES];
  317. if ([every isKindOfClass:NSDictionary.class])
  318. return [self triggerWithCustomDateMatchingComponents];
  319. return [self triggerWithTimeInterval];
  320. }
  321. /**
  322. * A trigger based on a calendar time defined by the user.
  323. *
  324. * @return [ UNTimeIntervalNotificationTrigger* ]
  325. */
  326. - (UNTimeIntervalNotificationTrigger*) triggerWithTimeInterval
  327. {
  328. double ticks = [[self valueForTriggerOption:@"every"] doubleValue];
  329. NSString* unit = [self valueForTriggerOption:@"unit"];
  330. double seconds = [self convertTicksToSeconds:ticks unit:unit];
  331. if (seconds < 60) {
  332. NSLog(@"time interval must be at least 60 sec if repeating");
  333. seconds = 60;
  334. }
  335. return [UNTimeIntervalNotificationTrigger
  336. triggerWithTimeInterval:seconds repeats:YES];
  337. }
  338. /**
  339. * A repeating trigger based on a calendar time intervals defined by the plugin.
  340. *
  341. * @return [ UNCalendarNotificationTrigger* ]
  342. */
  343. - (UNCalendarNotificationTrigger*) triggerWithDateMatchingComponents:(BOOL)repeats
  344. {
  345. NSCalendar* cal = [[NSCalendar alloc]
  346. initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  347. NSDateComponents *date = [cal components:[self repeatInterval]
  348. fromDate:[self triggerDate]];
  349. date.timeZone = [NSTimeZone defaultTimeZone];
  350. return [UNCalendarNotificationTrigger
  351. triggerWithDateMatchingComponents:date repeats:repeats];
  352. }
  353. /**
  354. * A repeating trigger based on a calendar time intervals defined by the user.
  355. *
  356. * @return [ UNCalendarNotificationTrigger* ]
  357. */
  358. - (UNCalendarNotificationTrigger*) triggerWithCustomDateMatchingComponents
  359. {
  360. NSCalendar* cal = [[NSCalendar alloc]
  361. initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  362. NSDateComponents *date = [self customDateComponents];
  363. date.calendar = cal;
  364. date.timeZone = [NSTimeZone defaultTimeZone];
  365. return [UNCalendarNotificationTrigger
  366. triggerWithDateMatchingComponents:date repeats:YES];
  367. }
  368. /**
  369. * A repeating trigger based on a location region.
  370. *
  371. * @return [ UNLocationNotificationTrigger* ]
  372. */
  373. - (UNLocationNotificationTrigger*) triggerWithRegion
  374. {
  375. NSArray* center = [self valueForTriggerOption:@"center"];
  376. double radius = [[self valueForTriggerOption:@"radius"] doubleValue];
  377. CLLocationCoordinate2D coord =
  378. CLLocationCoordinate2DMake([center[0] doubleValue], [center[1] doubleValue]);
  379. CLCircularRegion* region =
  380. [[CLCircularRegion alloc] initWithCenter:coord
  381. radius:radius
  382. identifier:self.identifier];
  383. region.notifyOnEntry = [[self valueForTriggerOption:@"notifyOnEntry"] boolValue];
  384. region.notifyOnExit = [[self valueForTriggerOption:@"notifyOnExit"] boolValue];
  385. return [UNLocationNotificationTrigger triggerWithRegion:region
  386. repeats:YES];
  387. }
  388. /**
  389. * The time interval between the next fire date and now.
  390. *
  391. * @return [ double ]
  392. */
  393. - (double) timeInterval
  394. {
  395. double ticks = [[self valueForTriggerOption:@"in"] doubleValue];
  396. NSString* unit = [self valueForTriggerOption:@"unit"];
  397. double seconds = [self convertTicksToSeconds:ticks unit:unit];
  398. return MAX(0.01f, seconds);
  399. }
  400. /**
  401. * The repeat interval for the notification.
  402. *
  403. * @return [ NSCalendarUnit ]
  404. */
  405. - (NSCalendarUnit) repeatInterval
  406. {
  407. NSString* interval = [self valueForTriggerOption:@"every"];
  408. NSCalendarUnit units = NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  409. if ([interval isEqualToString:@"minute"])
  410. return NSCalendarUnitSecond;
  411. if ([interval isEqualToString:@"hour"])
  412. return NSCalendarUnitMinute|NSCalendarUnitSecond;
  413. if ([interval isEqualToString:@"day"])
  414. return NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  415. if ([interval isEqualToString:@"week"])
  416. return NSCalendarUnitWeekday|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  417. if ([interval isEqualToString:@"month"])
  418. return NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  419. if ([interval isEqualToString:@"year"])
  420. return NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond;
  421. return units;
  422. }
  423. /**
  424. * The repeat interval for the notification.
  425. *
  426. * @return [ NSDateComponents* ]
  427. */
  428. - (NSDateComponents*) customDateComponents
  429. {
  430. NSDateComponents* date = [[NSDateComponents alloc] init];
  431. NSDictionary* every = [self valueForTriggerOption:@"every"];
  432. date.second = 0;
  433. for (NSString* key in every) {
  434. long value = [[every valueForKey:key] longValue];
  435. if ([key isEqualToString:@"minute"]) {
  436. date.minute = value;
  437. } else
  438. if ([key isEqualToString:@"hour"]) {
  439. date.hour = value;
  440. } else
  441. if ([key isEqualToString:@"day"]) {
  442. date.day = value;
  443. } else
  444. if ([key isEqualToString:@"weekday"]) {
  445. date.weekday = value;
  446. } else
  447. if ([key isEqualToString:@"weekdayOrdinal"]) {
  448. date.weekdayOrdinal = value;
  449. } else
  450. if ([key isEqualToString:@"week"]) {
  451. date.weekOfYear = value;
  452. } else
  453. if ([key isEqualToString:@"weekOfMonth"]) {
  454. date.weekOfMonth = value;
  455. } else
  456. if ([key isEqualToString:@"month"]) {
  457. date.month = value;
  458. } else
  459. if ([key isEqualToString:@"quarter"]) {
  460. date.quarter = value;
  461. } else
  462. if ([key isEqualToString:@"year"]) {
  463. date.year = value;
  464. }
  465. }
  466. return date;
  467. }
  468. /**
  469. * Convert an assets path to an valid sound name attribute.
  470. *
  471. * @param [ NSString* ] path A relative assets file path.
  472. *
  473. * @return [ NSString* ]
  474. */
  475. - (NSString*) soundNameForAsset:(NSString*)path
  476. {
  477. return [path stringByReplacingOccurrencesOfString:@"file:/"
  478. withString:@"www"];
  479. }
  480. /**
  481. * Convert a ressource path to an valid sound name attribute.
  482. *
  483. * @param [ NSString* ] path A relative ressource file path.
  484. *
  485. * @return [ NSString* ]
  486. */
  487. - (NSString*) soundNameForResource:(NSString*)path
  488. {
  489. return [path pathComponents].lastObject;
  490. }
  491. /**
  492. * URL for the specified attachment path.
  493. *
  494. * @param [ NSString* ] path Absolute/relative path or a base64 data.
  495. *
  496. * @return [ NSURL* ]
  497. */
  498. - (NSURL*) urlForAttachmentPath:(NSString*)path
  499. {
  500. if ([path hasPrefix:@"file:///"])
  501. {
  502. return [self urlForFile:path];
  503. }
  504. else if ([path hasPrefix:@"res:"])
  505. {
  506. return [self urlForResource:path];
  507. }
  508. else if ([path hasPrefix:@"file://"])
  509. {
  510. return [self urlForAsset:path];
  511. }
  512. else if ([path hasPrefix:@"base64:"])
  513. {
  514. return [self urlFromBase64:path];
  515. }
  516. NSFileManager* fm = [NSFileManager defaultManager];
  517. if (![fm fileExistsAtPath:path]){
  518. NSLog(@"File not found: %@", path);
  519. }
  520. return [NSURL fileURLWithPath:path];
  521. }
  522. /**
  523. * URL to an absolute file path.
  524. *
  525. * @param [ NSString* ] path An absolute file path.
  526. *
  527. * @return [ NSURL* ]
  528. */
  529. - (NSURL*) urlForFile:(NSString*)path
  530. {
  531. NSFileManager* fm = [NSFileManager defaultManager];
  532. NSString* absPath;
  533. absPath = [path stringByReplacingOccurrencesOfString:@"file://"
  534. withString:@""];
  535. if (![fm fileExistsAtPath:absPath]) {
  536. NSLog(@"File not found: %@", absPath);
  537. }
  538. return [NSURL fileURLWithPath:absPath];
  539. }
  540. /**
  541. * URL to a resource file.
  542. *
  543. * @param [ NSString* ] path A relative file path.
  544. *
  545. * @return [ NSURL* ]
  546. */
  547. - (NSURL*) urlForResource:(NSString*)path
  548. {
  549. NSFileManager* fm = [NSFileManager defaultManager];
  550. NSBundle* mainBundle = [NSBundle mainBundle];
  551. NSString* bundlePath = [mainBundle resourcePath];
  552. if ([path isEqualToString:@"res://icon"]) {
  553. path = @"res://AppIcon60x60@3x.png";
  554. }
  555. NSString* absPath;
  556. absPath = [path stringByReplacingOccurrencesOfString:@"res:/"
  557. withString:@""];
  558. absPath = [bundlePath stringByAppendingString:absPath];
  559. if (![fm fileExistsAtPath:absPath]) {
  560. NSLog(@"File not found: %@", absPath);
  561. }
  562. return [NSURL fileURLWithPath:absPath];
  563. }
  564. /**
  565. * URL to an asset file.
  566. *
  567. * @param path A relative www file path.
  568. *
  569. * @return [ NSURL* ]
  570. */
  571. - (NSURL*) urlForAsset:(NSString*)path
  572. {
  573. NSFileManager* fm = [NSFileManager defaultManager];
  574. NSBundle* mainBundle = [NSBundle mainBundle];
  575. NSString* bundlePath = [mainBundle bundlePath];
  576. NSString* absPath;
  577. absPath = [path stringByReplacingOccurrencesOfString:@"file:/"
  578. withString:@"/www"];
  579. absPath = [bundlePath stringByAppendingString:absPath];
  580. if (![fm fileExistsAtPath:absPath]) {
  581. NSLog(@"File not found: %@", absPath);
  582. }
  583. return [NSURL fileURLWithPath:absPath];
  584. }
  585. /**
  586. * URL for a base64 encoded string.
  587. *
  588. * @param [ NSString* ] base64String Base64 encoded string.
  589. *
  590. * @return [ NSURL* ]
  591. */
  592. - (NSURL*) urlFromBase64:(NSString*)base64String
  593. {
  594. NSString *filename = [self basenameFromAttachmentPath:base64String];
  595. NSUInteger length = [base64String length];
  596. NSRegularExpression *regex;
  597. NSString *dataString;
  598. regex = [NSRegularExpression regularExpressionWithPattern:@"^base64:[^/]+.."
  599. options:NSRegularExpressionCaseInsensitive
  600. error:Nil];
  601. dataString = [regex stringByReplacingMatchesInString:base64String
  602. options:0
  603. range:NSMakeRange(0, length)
  604. withTemplate:@""];
  605. NSData* data = [[NSData alloc] initWithBase64EncodedString:dataString
  606. options:0];
  607. return [self urlForData:data withFileName:filename];
  608. }
  609. /**
  610. * Extract the attachments basename.
  611. *
  612. * @param [ NSString* ] path The file path or base64 data.
  613. *
  614. * @return [ NSString* ]
  615. */
  616. - (NSString*) basenameFromAttachmentPath:(NSString*)path
  617. {
  618. if ([path hasPrefix:@"base64:"]) {
  619. NSString* pathWithoutPrefix;
  620. pathWithoutPrefix = [path stringByReplacingOccurrencesOfString:@"base64:"
  621. withString:@""];
  622. return [pathWithoutPrefix substringToIndex:
  623. [pathWithoutPrefix rangeOfString:@"//"].location];
  624. }
  625. return path;
  626. }
  627. /**
  628. * Write the data into a temp file.
  629. *
  630. * @param [ NSData* ] data The data to save to file.
  631. * @param [ NSString* ] name The name of the file.
  632. *
  633. * @return [ NSURL* ]
  634. */
  635. - (NSURL*) urlForData:(NSData*)data withFileName:(NSString*) filename
  636. {
  637. NSFileManager* fm = [NSFileManager defaultManager];
  638. NSString* tempDir = NSTemporaryDirectory();
  639. [fm createDirectoryAtPath:tempDir withIntermediateDirectories:YES
  640. attributes:NULL
  641. error:NULL];
  642. NSString* absPath = [tempDir stringByAppendingPathComponent:filename];
  643. NSURL* url = [NSURL fileURLWithPath:absPath];
  644. [data writeToURL:url atomically:NO];
  645. if (![fm fileExistsAtPath:absPath]) {
  646. NSLog(@"File not found: %@", absPath);
  647. }
  648. return url;
  649. }
  650. /**
  651. * Convert the amount of ticks into seconds.
  652. *
  653. * @param [ double ] ticks The amount of ticks.
  654. * @param [ NSString* ] unit The unit of the ticks (minute, hour, day, ...)
  655. *
  656. * @return [ double ] Amount of ticks in seconds.
  657. */
  658. - (double) convertTicksToSeconds:(double)ticks unit:(NSString*)unit
  659. {
  660. if ([unit isEqualToString:@"second"]) {
  661. return ticks;
  662. } else
  663. if ([unit isEqualToString:@"minute"]) {
  664. return ticks * 60;
  665. } else
  666. if ([unit isEqualToString:@"hour"]) {
  667. return ticks * 60 * 60;
  668. } else
  669. if ([unit isEqualToString:@"day"]) {
  670. return ticks * 60 * 60 * 24;
  671. } else
  672. if ([unit isEqualToString:@"week"]) {
  673. return ticks * 60 * 60 * 24 * 7;
  674. } else
  675. if ([unit isEqualToString:@"month"]) {
  676. return ticks * 60 * 60 * 24 * 30.438;
  677. } else
  678. if ([unit isEqualToString:@"quarter"]) {
  679. return ticks * 60 * 60 * 24 * 91.313;
  680. } else
  681. if ([unit isEqualToString:@"year"]) {
  682. return ticks * 60 * 60 * 24 * 365;
  683. }
  684. return 0;
  685. }
  686. @end