-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathOneSignalAttachmentHandler.m
More file actions
422 lines (346 loc) · 17.3 KB
/
OneSignalAttachmentHandler.m
File metadata and controls
422 lines (346 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
/*
Modified MIT License
Copyright 2021 OneSignal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import "OneSignalAttachmentHandler.h"
#import "OneSignalNotificationCategoryController.h"
#import "OSMacros.h"
@interface DirectDownloadDelegate : NSObject <NSURLSessionDataDelegate> {
NSError* error;
NSURLResponse* response;
BOOL done;
NSFileHandle* outputHandle;
}
@property (readonly, getter=isDone) BOOL done;
@property (readonly) NSError* error;
@property (readonly) NSURLResponse* response;
@end
@implementation DirectDownloadDelegate
@synthesize error, response, done;
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
NSError * __autoreleasing fileHandleError;
NSError * __autoreleasing *fileHandleErrorPointer = &fileHandleError;
if (@available(iOS 13.0, *)) {
// We need to use NSInvocation for reflection because performSelector cannot take pointer parameters
SEL writeDataSelector = NSSelectorFromString(@"writeData:error:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[NSFileHandle instanceMethodSignatureForSelector:writeDataSelector]];
[invocation setTarget:outputHandle];
[invocation setSelector:writeDataSelector];
/*
From Apple's Documentation on NSInvocation:
Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively;
you should set these values directly with the target and selector properties.
Use indices 2 and greater for the arguments normally passed in a message.
*/
[invocation setArgument:&data atIndex:2];
[invocation setArgument:&fileHandleErrorPointer atIndex:3];
[invocation invoke];
} else {
@try {
[outputHandle writeData:data];
} @catch (NSException *e) {
NSDictionary *userInfo = @{
NSLocalizedDescriptionKey : @"Failed to write attachment data to filehandle",
};
fileHandleError = [NSError errorWithDomain:@"com.onesignal.download" code:0 userInfo:userInfo];
}
}
if (fileHandleError != nil) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:[NSString stringWithFormat:@"OneSignal Error encountered while downloading attachment: %@", fileHandleError]];
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)aResponse completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
response = aResponse;
long long expectedLength = response.expectedContentLength;
if (expectedLength > MAX_NOTIFICATION_MEDIA_SIZE_BYTES) { //Enforcing 50 mb limit on media before downloading
completionHandler(NSURLSessionResponseCancel);
return;
}
completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)anError {
error = anError;
done = YES;
[outputHandle closeFile];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)anError {
done = YES;
error = anError;
[outputHandle closeFile];
}
- (id)initWithFilePath:(NSString*)path {
if (self = [super init]) {
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
outputHandle = [NSFileHandle fileHandleForWritingAtPath:path];
}
return self;
}
@end
@interface NSURLSession (DirectDownload)
+ (NSString *)downloadItemAtURL:(NSURL *)url toFile:(NSString *)localPath error:(NSError **)error;
@end
@implementation NSURLSession (DirectDownload)
+ (NSString *)downloadItemAtURL:(NSURL *)url toFile:(NSString *)localPath error:(NSError **)error {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
DirectDownloadDelegate *delegate = [[DirectDownloadDelegate alloc] initWithFilePath:localPath];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:delegate delegateQueue:nil];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
[session finishTasksAndInvalidate];
while (![delegate isDone]) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1.0]];
}
NSError *downloadError = [delegate error];
if (downloadError != nil) {
if (error)
*error = downloadError;
return nil;
}
return delegate.response.MIMEType;
}
@end
@implementation OneSignalAttachmentHandler
+ (void)addActionButtons:(OSNotification*)notification
toNotificationContent:(UNMutableNotificationContent*)content {
if (!notification.actionButtons || notification.actionButtons.count == 0)
return;
let actionArray = [NSMutableArray new];
for(NSDictionary* button in notification.actionButtons) {
let action = [self createActionForButton:button];
[actionArray addObject:action];
}
NSArray* finalActionArray;
if (actionArray.count == 2)
finalActionArray = [[actionArray reverseObjectEnumerator] allObjects];
else
finalActionArray = actionArray;
// Get a full list of categories so we don't replace any exisiting ones.
var allCategories = OneSignalNotificationCategoryController.sharedInstance.existingCategories;
let newCategoryIdentifier = [OneSignalNotificationCategoryController.sharedInstance registerNotificationCategoryForNotificationId:notification.notificationId];
let category = [UNNotificationCategory categoryWithIdentifier:newCategoryIdentifier
actions:finalActionArray
intentIdentifiers:@[]
options:UNNotificationCategoryOptionCustomDismissAction];
if (allCategories) {
let newCategorySet = [NSMutableSet new];
for(UNNotificationCategory *existingCategory in allCategories) {
if (![existingCategory.identifier isEqualToString:newCategoryIdentifier])
[newCategorySet addObject:existingCategory];
}
[newCategorySet addObject:category];
allCategories = newCategorySet;
}
else
allCategories = [[NSMutableSet alloc] initWithArray:@[category]];
[UNUserNotificationCenter.currentNotificationCenter setNotificationCategories:allCategories];
// List Categories again so iOS refreshes it's internal list.
// Required otherwise buttons will not display or won't update.
// This is a blackbox assumption, the delay on the main thread this call creates might be giving
// some iOS background thread time to flush to disk.
allCategories = OneSignalNotificationCategoryController.sharedInstance.existingCategories;
content.categoryIdentifier = newCategoryIdentifier;
}
+ (void)addAttachments:(OSNotification*)notification
toNotificationContent:(UNMutableNotificationContent*)content {
if (!notification.attachments)
return;
let unAttachments = [NSMutableArray new];
for(NSString* key in notification.attachments) {
let URI = [OneSignalCoreHelper trimURLSpacing:[notification.attachments valueForKey:key]];
let nsURL = [NSURL URLWithString:URI];
// Remote media attachment */
if (nsURL && [self isWWWScheme:nsURL]) {
// Synchroneously download file and chache it
let name = [self downloadMediaAndSaveInBundle:URI];
if (!name)
continue;
let paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
let filePath = [paths[0] stringByAppendingPathComponent:name];
let url = [NSURL fileURLWithPath:filePath];
NSError* error;
let attachment = [UNNotificationAttachment
attachmentWithIdentifier:key
URL:url
options:0
error:&error];
if (attachment)
[unAttachments addObject:attachment];
}
// Local in bundle resources
else {
let files = [[NSMutableArray<NSString*> alloc] initWithArray:[URI componentsSeparatedByString:@"."]];
if (files.count < 2)
continue;
let extension = [files lastObject];
[files removeLastObject];
let name = [files componentsJoinedByString:@"."];
//Make sure resource exists
let url = [[NSBundle mainBundle] URLForResource:name withExtension:extension];
if (url) {
NSError *error;
id attachment = [UNNotificationAttachment
attachmentWithIdentifier:key
URL:url
options:0
error:&error];
if (attachment)
[unAttachments addObject:attachment];
}
}
}
content.attachments = unAttachments;
}
+ (UNNotificationAction *)createActionForButton:(NSDictionary *)button {
NSString *buttonId = button[@"id"];
NSString *buttonText = button[@"text"];
if (@available(iOS 15.0, *)) {
// Using reflection for Xcode versions lower than 13
id icon; // UNNotificationActionIcon
let UNNotificationActionIconClass = NSClassFromString(@"UNNotificationActionIcon");
if (UNNotificationActionIconClass) {
if (button[@"systemIcon"]) {
icon = [UNNotificationActionIconClass performSelector:@selector(iconWithSystemImageName:)
withObject:button[@"systemIcon"]];
} else if (button[@"templateIcon"]) {
icon = [UNNotificationActionIconClass performSelector:@selector(iconWithTemplateImageName:)
withObject:button[@"templateIcon"]];
}
}
// We need to use NSInvocation because performSelector only allows up to 2 arguments
SEL actionSelector = NSSelectorFromString(@"actionWithIdentifier:title:options:icon:");
UNNotificationAction * __unsafe_unretained action;
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UNNotificationAction methodSignatureForSelector:actionSelector]];
[invocation setTarget:[UNNotificationAction class]];
[invocation setSelector:actionSelector];
/*
From Apple's Documentation on NSInvocation:
Indices 0 and 1 indicate the hidden arguments self and _cmd, respectively;
you should set these values directly with the target and selector properties.
Use indices 2 and greater for the arguments normally passed in a message.
*/
NSUInteger actionOption = UNNotificationActionOptionForeground;
[invocation setArgument:&buttonId atIndex:2];
[invocation setArgument:&buttonText atIndex:3];
[invocation setArgument:&actionOption atIndex:4];
[invocation setArgument:&icon atIndex:5];
[invocation invoke];
[invocation getReturnValue:&action];
return action;
} else {
return [UNNotificationAction actionWithIdentifier:buttonId
title:buttonText
options:UNNotificationActionOptionForeground];
}
}
/*
Synchroneously downloads an attachment
On success returns bundle resource name, otherwise returns nil
*/
+ (NSString *)downloadMediaAndSaveInBundle:(NSString *)urlString {
let url = [NSURL URLWithString:urlString];
//Download the file
var name = [self randomStringWithLength:10];
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* filePath = [paths[0] stringByAppendingPathComponent:name];
//guard against situations where for example, available storage is too low
@try {
NSError* error;
let mimeType = [NSURLSession downloadItemAtURL:url toFile:filePath error:&error];
if (error) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:[NSString stringWithFormat:@"Encountered an error while attempting to download file with URL: %@", error]];
return nil;
}
NSString *extension = [self getSupportedFileExtensionFromURL:url mimeType:mimeType];
if (!extension || [extension isEqualToString:@""])
return nil;
name = [NSString stringWithFormat:@"%@.%@", name, extension];
let newPath = [paths[0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", name]];
[[NSFileManager defaultManager] moveItemAtPath:filePath toPath:newPath error:&error];
if (error) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:[NSString stringWithFormat:@"Encountered an error while attempting to download file with URL: %@", error]];
return nil;
}
let standardUserDefaults = OneSignalUserDefaults.initStandard;
NSArray* cachedFiles = [standardUserDefaults getSavedObjectForKey:OSUD_TEMP_CACHED_NOTIFICATION_MEDIA defaultValue:nil];
NSMutableArray* appendedCache;
if (cachedFiles) {
appendedCache = [[NSMutableArray alloc] initWithArray:cachedFiles];
[appendedCache addObject:name];
}
else
appendedCache = [[NSMutableArray alloc] initWithObjects:name, nil];
[standardUserDefaults saveObjectForKey:OSUD_TEMP_CACHED_NOTIFICATION_MEDIA withValue:appendedCache];
return name;
} @catch (NSException *exception) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:[NSString stringWithFormat:@"OneSignal encountered an exception while downloading file (%@), exception: %@", url, exception.description]];
return nil;
}
}
+ (BOOL)isWWWScheme:(NSURL*)url {
NSString* urlScheme = [url.scheme lowercaseString];
return [urlScheme isEqualToString:@"http"] || [urlScheme isEqualToString:@"https"];
}
+(NSString*)randomStringWithLength:(int)length {
let letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let randomString = [[NSMutableString alloc] initWithCapacity:length];
for(var i = 0; i < length; i++) {
let ln = (uint32_t)letters.length;
let rand = arc4random_uniform(ln);
[randomString appendFormat:@"%C", [letters characterAtIndex:rand]];
}
return randomString;
}
/*
The preference order for file type determination is as follows:
1. URL Query parameter called 'filename', such as test.jpg. The SDK will extract the file extension from it
2. MIME type
3. File extension in the actual URL
4. A file extension extracted by searching through all URL Query parameters
*/
+ (NSString *)getSupportedFileExtensionFromURL:(NSURL *)url mimeType:(NSString *)mimeType {
//Try to get extension from the filename parameter
NSString* extension = [[url valueFromQueryParameter:@"filename"]
supportedFileExtension];
if (extension && [ONESIGNAL_SUPPORTED_ATTACHMENT_TYPES containsObject:extension]) {
return extension;
}
//Use the MIME type for the extension
if (mimeType != nil && ![mimeType isEqualToString:@""]) {
extension = mimeType.fileExtensionForMimeType;
if (extension && [ONESIGNAL_SUPPORTED_ATTACHMENT_TYPES containsObject:extension]) {
return extension;
}
}
//Try using url.pathExtension
extension = url.pathExtension;
if (extension && [ONESIGNAL_SUPPORTED_ATTACHMENT_TYPES containsObject:extension]) {
return extension;
}
//Try getting an extension from the query
extension = url.supportedFileExtensionFromQueryItems;
if (extension && [ONESIGNAL_SUPPORTED_ATTACHMENT_TYPES containsObject:extension]) {
return extension;
}
return nil;
}
@end