1// Copyright 2015-present 650 Industries. All rights reserved.
2
3#import <ExpoFileSystem/EXSessionCancelableUploadTaskDelegate.h>
4
5@interface EXSessionCancelableUploadTaskDelegate ()
6
7@property (strong, nonatomic, readonly) EXUploadDelegateOnSendCallback onSendCallback;
8@property (weak, nonatomic) EXTaskHandlersManager *manager;
9@property (strong, nonatomic) NSString *uuid;
10
11@end
12
13@implementation EXSessionCancelableUploadTaskDelegate
14
15- (nonnull instancetype)initWithResolve:(EXPromiseResolveBlock)resolve
16                                 reject:(EXPromiseRejectBlock)reject
17                         onSendCallback:(EXUploadDelegateOnSendCallback)onSendCallback
18                       resumableManager:(EXTaskHandlersManager *)manager
19                                   uuid:(NSString *)uuid;
20{
21  if (self = [super initWithResolve:resolve
22                             reject:reject]) {
23    _onSendCallback = onSendCallback;
24    _manager = manager;
25    _uuid = uuid;
26  }
27  return self;
28}
29
30- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
31{
32  if (error) {
33    // The task was paused by us. So, we shouldn't throw.
34    if (error.code == NSURLErrorCancelled) {
35      self.resolve([NSNull null]);
36      [_manager unregisterTask:_uuid];
37      return;
38    }
39  }
40
41  [super URLSession:session task:task didCompleteWithError:error];
42  [_manager unregisterTask:_uuid];
43}
44
45- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
46                                didSendBodyData:(int64_t)bytesSent
47                                 totalBytesSent:(int64_t)totalBytesSent
48                       totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
49{
50  if (_onSendCallback && bytesSent > 0) {
51    _onSendCallback(task, bytesSent, totalBytesSent, totalBytesExpectedToSend);
52  }
53}
54
55@end
56