FDOSSManager.m 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. //
  2. // FDOSSManager.m
  3. // FDNetworkObjC
  4. //
  5. // Created by bogokj on 2020/8/13.
  6. //
  7. #import "FDOSSManager.h"
  8. #import <AliyunOSSiOS/AliyunOSSiOS.h>
  9. #import <MJExtension/MJExtension.h>
  10. #import "FDOSSResponseModel.h"
  11. #define OSS_STS_URL @"http://oss-cn-shanghai.aliyuncs.com/app-server/sts.php"
  12. @interface FDOSSManager ()
  13. @property(nonatomic, strong) OSSClient *client;
  14. @property(nonatomic, strong) FDOSSResponseModel *model;
  15. @property(nonatomic, copy) fd_ossSetUpHandler fd_ossSetUpHandler;
  16. @end
  17. @implementation FDOSSManager
  18. + (FDOSSManager *)defaultManager{
  19. static FDOSSManager *manager = nil;
  20. static dispatch_once_t predicate;
  21. dispatch_once(&predicate, ^{
  22. manager = [[self alloc] init];
  23. });
  24. return manager;
  25. }
  26. - (void)onRecieveNoti:(NSNotification *)noti{
  27. NSDictionary *dict = noti.object;
  28. // NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[kFDNetworkObjCBundle pathForResource:@"oss" ofType:@"json"]] options:NSJSONReadingMutableContainers error:nil];
  29. self.model = [FDOSSResponseModel mj_objectWithKeyValues:dict];
  30. id<OSSCredentialProvider>credential = [[OSSFederationCredentialProvider alloc] initWithFederationTokenGetter:^OSSFederationToken * {
  31. return [self getFederationToken];
  32. }];
  33. self.client = [[OSSClient alloc] initWithEndpoint:self.model.endpoint credentialProvider:credential];
  34. if (self.fd_ossSetUpHandler) {
  35. self.fd_ossSetUpHandler();
  36. }
  37. }
  38. - (void)setup:(fd_ossSetUpHandler)finish{
  39. self.fd_ossSetUpHandler = finish;
  40. if (!self.model) {
  41. // NSDictionary *dict = @{@"ctl":@"app",@"act":@"aliyun_sts",@"lat":@"117.089291",@"lng":@"36.184758",@"sdk_type":@"ios",@"sdk_version":@"2020042701",@"sdk_version_name":@"6.14.08",@"xpoint":@"117.089291",@"ypoint":@"36.184758",@"i_type":@"lib"};
  42. // NSString *aesKey = @"1400406262000000";
  43. // NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
  44. // NSString *paramAESStr = [data AES256EncryptWithKey:aesKey];
  45. // NSMutableDictionary *param = [NSMutableDictionary dictionaryWithDictionary:dict];
  46. // [param setObject:paramAESStr forKey:@"requestData"];
  47. // [[FDNetwork shareInstance] POST:@"http://kh.xyzc.anbig.com/mapi/index.php" param:param success:^(FDNetworkResponseModel * _Nonnull result) {
  48. // NSLog(@"");
  49. // } failure:^(NSString * _Nonnull error) {
  50. // NSLog(@"");
  51. // }];
  52. [[NSNotificationCenter defaultCenter] postNotificationName:kFDOSSManagerSendNoti object:nil];
  53. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRecieveNoti:) name:kFDOSSManagerRecieveNoti object:nil];
  54. }else{
  55. self.fd_ossSetUpHandler();
  56. }
  57. }
  58. - (OSSFederationToken *)getFederationToken
  59. {
  60. NSURL * url = [NSURL URLWithString:OSS_STS_URL];
  61. NSURLRequest * request = [NSURLRequest requestWithURL:url];
  62. OSSTaskCompletionSource * tcs = [OSSTaskCompletionSource taskCompletionSource];
  63. NSURLSession * session = [NSURLSession sharedSession];
  64. NSURLSessionTask * sessionTask = [session dataTaskWithRequest:request
  65. completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
  66. if (error) {
  67. [tcs setError:error];
  68. return;
  69. }
  70. [tcs setResult:data];
  71. }];
  72. [sessionTask resume];
  73. // 实现这个回调需要同步返回Token,所以要waitUntilFinished
  74. [tcs.task waitUntilFinished];
  75. if (tcs.task.error) {
  76. return nil;
  77. } else {
  78. OSSFederationToken * token = [OSSFederationToken new];
  79. token.tAccessKey = self.model.AccessKeyId;
  80. token.tSecretKey = self.model.AccessKeySecret;
  81. token.tToken = self.model.SecurityToken;
  82. token.expirationTimeInGMTFormat = self.model.Expiration;
  83. return token;
  84. }
  85. }
  86. - (void)UPLOAD:(NSData *)fileData progress:(fd_ossProgressHandler)progress success:(fd_ossSuccessHandler)success failure:(fd_ossFaliureHandler)faliure{
  87. OSSPutObjectRequest* put = [OSSPutObjectRequest new];
  88. put.bucketName = self.model.bucket;
  89. put.objectKey = [self getObjectKey];
  90. put.uploadingData = fileData; // Directly upload NSData
  91. put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  92. if (progress) {
  93. progress((float)totalByteSent/(float)totalBytesExpectedToSend);
  94. }
  95. };
  96. if (self.model.callbackUrl) {
  97. put.callbackParam = @{@"callbackUrl": self.model.callbackUrl,@"callbackBody": @"filename=${object}"};
  98. }
  99. OSSTask * putTask = [self.client putObject:put];
  100. [putTask continueWithBlock:^id(OSSTask *task) {
  101. if (!task.error) {
  102. if (success) {
  103. NSString *resultStr = [NSString stringWithFormat:@"%@%@",self.model.oss_domain,put.objectKey];
  104. success(resultStr);
  105. }
  106. } else {
  107. if (faliure) {
  108. faliure(task.error);
  109. }
  110. }
  111. return nil;
  112. }];
  113. }
  114. - (NSString *)getObjectKey
  115. {
  116. NSDate *currentDate = [NSDate date];//获取当前时间日期
  117. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  118. [dateFormatter setDateFormat:@"YYYYMMddhhmmssSSS"];
  119. NSString *dateString = [dateFormatter stringFromDate:currentDate];
  120. NSString *nameString = [NSString stringWithFormat:@"%@%d.png",dateString,arc4random()%10000/1000];
  121. NSString *objectKey = [NSString stringWithFormat:@"%@%@",self.model.dir,nameString];
  122. return objectKey;
  123. }
  124. @end