OSSManager.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. //
  2. // OSSManager.m
  3. // AliyunOSSSDK-iOS-Example
  4. //
  5. // Created by huaixu on 2018/10/23.
  6. // Copyright © 2018 aliyun. All rights reserved.
  7. //
  8. #import "OSSManager.h"
  9. #import "OssNetApi.h"
  10. #import <AliyunOSSiOS/OSSService.h>
  11. #import "ChatsStore.h"
  12. #import "GDBManager.h"
  13. #import "GWebSocket.h"
  14. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  15. #define endpoint @"https://oss-ap-southeast-1.aliyuncs.com"//生产服务器
  16. @interface OSSManager ()
  17. @property (nonatomic, strong) OSSPutObjectRequest *normalUploadRequest;
  18. @property (nonatomic, strong) OSSGetObjectRequest *normalDloadRequest;
  19. @end
  20. @implementation OSSManager
  21. + (instancetype)sharedManager {
  22. static OSSManager *_manager = nil;
  23. static dispatch_once_t onceToken;
  24. dispatch_once(&onceToken, ^{
  25. _manager = [[OSSManager alloc] init];
  26. });
  27. return _manager;
  28. }
  29. - (instancetype)init {
  30. if (self = [super init]) {
  31. _uploadTanck = [NSMutableArray new];
  32. }
  33. return self;
  34. }
  35. -(void)getOSSInfo{
  36. if (!_uploadTanck) {
  37. _uploadTanck = [NSMutableArray new];
  38. }
  39. NSDictionary *dic = [UDManager.shareInstance getDDManager:nkOSSinfo];
  40. if(dic){
  41. self.OSSInfo = dic.copy;
  42. [self initmyAliyunOSS];
  43. }
  44. [OssNetApi getOSSInfo:nil succ:^(int code, NSDictionary * res) {
  45. NSLog(@"res:%@",res);
  46. NSString *codeV =res[@"code"];
  47. if(codeV.intValue==200){
  48. self.OSSInfo = res[@"data"];
  49. if(self.OSSInfo){
  50. [self initmyAliyunOSS];
  51. [UDManager.shareInstance setDDManager:self.OSSInfo key:nkOSSinfo];
  52. }
  53. }
  54. } fail:^(NSError * _Nonnull error) {
  55. }];
  56. }
  57. -(void)initmyAliyunOSS{
  58. if(self.OSSInfo){
  59. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  60. //NSString *endpoint = @"https://oss-ap-southeast-1.aliyuncs.com";
  61. // 旧版本图片服务的endpoint
  62. // NSString *oldimgendpoint = @"http://img-ap-southeast-1.aliyuncs.com";
  63. // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
  64. NSString *accessKeyId = self.OSSInfo[@"accessKeyId"];
  65. NSString *accessKeySecret = self.OSSInfo[@"accessKeySecret"];
  66. // 从STS服务获取的安全令牌(SecurityToken)。
  67. NSString *securityToken = self.OSSInfo[@"securityToken"];
  68. // NSString *expiration = self.OSSInfo[@"expiration"];
  69. id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
  70. OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
  71. cfg.maxRetryCount = 3;
  72. cfg.timeoutIntervalForRequest = 15;
  73. cfg.isHttpdnsEnable = NO;
  74. cfg.crc64Verifiable = YES;
  75. OSSClient *defaultClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  76. [OSSManager sharedManager].defaultClient = defaultClient;
  77. //旧的图片服务
  78. // OSSClient *defaultImgClient = [[OSSClient alloc] initWithEndpoint:oldimgendpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  79. // [OSSManager sharedManager].imageClient = defaultImgClient;
  80. }
  81. }
  82. //普通上传
  83. - (void)asyncPutFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  84. if([OSSManager sharedManager].defaultClient==nil){
  85. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  86. [self getOSSInfo];
  87. return;
  88. }
  89. if (![objectKey oss_isNotEmpty]) {
  90. NSError *error = [NSError errorWithDomain:NSInvalidArgumentException code:0 userInfo:@{NSLocalizedDescriptionKey: @"objectKey should not be nil"}];
  91. if(self.delegate){
  92. NSDictionary *dic=@{
  93. @"state":@"3",
  94. @"pcent":@"",
  95. @"thrid":strtime
  96. };
  97. [self.delegate stateChange:dic];
  98. }
  99. return;
  100. }
  101. NSLog(@"objectKey:%@",objectKey);
  102. _normalUploadRequest = [OSSPutObjectRequest new];
  103. _normalUploadRequest.bucketName = self.OSSInfo[@"bucket"];
  104. _normalUploadRequest.objectKey = objectKey;
  105. _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  106. _normalUploadRequest.isAuthenticationRequired = YES;
  107. weakSelf(self);
  108. _normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  109. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  110. // NSLog(@"上传文件进度: %f", progress);
  111. NSInteger pcent =progress*100;
  112. if(weakself.delegate){
  113. NSDictionary *dic=@{
  114. @"state":@"1",
  115. @"pcent":[NSString stringWithFormat:@"%ld",(long)pcent],
  116. @"thrid":strtime
  117. };
  118. [weakself.delegate stateChange:dic];
  119. }
  120. };
  121. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  122. OSSTask * task = [[OSSManager sharedManager].defaultClient putObject:self->_normalUploadRequest];
  123. [task continueWithBlock:^id(OSSTask *task) {
  124. dispatch_async(dispatch_get_main_queue(), ^{
  125. if (task.error) {
  126. [self updataFileMsg:strtime state:@"1"];
  127. if(self.delegate){
  128. NSDictionary *dic=@{
  129. @"state":@"3",
  130. @"pcent":@"",
  131. @"thrid":strtime
  132. };
  133. [self.delegate stateChange:dic];
  134. }
  135. } else {
  136. NSLog(@"上传文件完成");
  137. [self updataFileMsg:strtime state:@"2"];
  138. if(self.delegate){
  139. NSDictionary *dic=@{
  140. @"state":@"2",
  141. @"pcent":@"",
  142. @"thrid":strtime
  143. };
  144. [self.delegate stateChange:dic];
  145. }
  146. }
  147. });
  148. return nil;
  149. }];
  150. });
  151. }
  152. //断点续传
  153. - (void)asyncResumableUploadFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  154. if([OSSManager sharedManager].defaultClient==nil){
  155. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  156. [self getOSSInfo];
  157. return;
  158. }
  159. // 获取UploadId上传文件。
  160. OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
  161. resumableUpload.bucketName = self.OSSInfo[@"bucket"];
  162. // objectKey等同于objectName,表示断点上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
  163. resumableUpload.objectKey = objectKey;
  164. resumableUpload.partSize = 1024 * 1024;
  165. resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  166. // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  167. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  168. // NSLog(@"上传文件进度: %f", progress);
  169. NSInteger pcent =progress*100;
  170. if(self.delegate){
  171. NSDictionary *dic=@{
  172. @"state":@"1",
  173. @"pcent":[NSString stringWithFormat:@"%ld",(long)pcent],
  174. @"thrid":strtime
  175. };
  176. [self.delegate stateChange:dic];
  177. }
  178. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  179. // prgress(pcent,strtime);
  180. // });
  181. };
  182. NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  183. // 设置断点记录保存路径。
  184. resumableUpload.recordDirectoryPath = cachesDir;
  185. // 将参数deleteUploadIdOnCancelling设置为NO,表示不删除断点记录文件,上传失败后将从断点记录处继续上传直到文件上传完成。如果不设置此参数,即保留默认值YES,表示删除断点记录文件,下次再上传同一文件时则重新上传。
  186. resumableUpload.deleteUploadIdOnCancelling = NO;
  187. resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  188. OSSTask * resumeTask = [[OSSManager sharedManager].defaultClient resumableUpload:resumableUpload];
  189. [self addUploadTanckobj:resumeTask thrid:strtime];
  190. [resumeTask continueWithBlock:^id(OSSTask *task) {
  191. if (task.error) {
  192. NSLog(@"error: %@", task.error);
  193. if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
  194. // 此任务无法续传,需获取新的uploadId重新上传。
  195. }
  196. [self updataFileMsg:strtime state:@"3"];
  197. // if(self.delegate){
  198. // NSDictionary *dic=@{
  199. // @"state":@"3",
  200. // @"pcent":@"",
  201. // @"thrid":strtime
  202. // };
  203. // [self.delegate stateChange:dic];
  204. // }
  205. } else {
  206. NSLog(@"Upload file success");
  207. [self updataFileMsg:strtime state:@"2"];
  208. // if(self.delegate){
  209. // NSDictionary *dic=@{
  210. // @"state":@"2",
  211. // @"pcent":@"",
  212. // @"thrid":strtime
  213. // };
  214. // [self.delegate stateChange:dic];
  215. // }
  216. }
  217. return nil;
  218. }];
  219. // [resumeTask waitUntilFinished];
  220. // [resumableUpload cancel];
  221. }
  222. -(void)addUploadTanckobj:(OSSTask *)task thrid:(NSString *)thrid{
  223. NSDictionary *item = @{
  224. @"task":task,
  225. @"thrid":thrid
  226. };
  227. [_uploadTanck addObject:item];
  228. }
  229. -(BOOL)isuploadTanck:(NSString *)thrid{
  230. // NSLog(@"stopUploadTanck-------------2");
  231. if(_uploadTanck.count>0){
  232. for (NSDictionary *item in _uploadTanck) {
  233. NSString *th = item[@"thrid"];
  234. NSLog(@"stopUploadTanck-------------3");
  235. if([th isEqualToString:thrid]){
  236. NSLog(@"stopUploadTanck-------------4");
  237. return true;
  238. }
  239. }
  240. }
  241. return false;
  242. }
  243. -(void)removeUploadTanckobj:(NSString *)thrid{
  244. if(_uploadTanck.count>0){
  245. for (NSDictionary *item in _uploadTanck) {
  246. NSString *th = item[@"thrid"];
  247. if([th isEqualToString:thrid]){
  248. [_uploadTanck removeObject:item];
  249. return;
  250. }
  251. }
  252. }
  253. }
  254. -(void)stopUploadTanck:(NSString *)thrid{
  255. NSLog(@"stopUploadTanck-------------2");
  256. if(_uploadTanck.count>0){
  257. for (NSDictionary *item in _uploadTanck) {
  258. NSString *th = item[@"thrid"];
  259. NSLog(@"stopUploadTanck-------------3");
  260. if([th isEqualToString:thrid]){
  261. OSSTask *task = item[@"task"];
  262. NSLog(@"stopUploadTanck-------------4");
  263. //[task cancel];取消传输
  264. return;
  265. }
  266. }
  267. }
  268. }
  269. -(void)updataFileMsg:(NSString *)thrid state:(NSString *)state{
  270. [GDBManager.shareInstance selectLocalmsgWithLocaltime:thrid succ:^(NSArray * _Nullable array) {
  271. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  272. if(array){
  273. if(array.count>0){
  274. NSDictionary *msg =array[0];
  275. NSString *msgtype = msg[@"messageType"];
  276. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  277. return;
  278. }
  279. NSDictionary *extend=msg[@"extend"];
  280. NSMutableDictionary *mextend = [extend mutableCopy];
  281. NSMutableDictionary *mmsg = [msg mutableCopy];
  282. if([state isEqualToString:@"2"]){
  283. NSString *localPath =extend[@"localurl"];
  284. NSURL *loaclUrl = [NSURL URLWithString:localPath];
  285. NSString *url = [NSString stringWithFormat:@"http://oss.abtim-my.com/%@",loaclUrl.lastPathComponent];
  286. [mextend setObject:url forKey:@"url"];
  287. [mmsg setObject:mextend forKey:@"extend"];
  288. [mmsg setObject:@"" forKey:@"id"];
  289. }
  290. else if([state isEqualToString:@"3"]){
  291. [mextend setObject:@"" forKey:@"url"];
  292. [mextend setObject:@"" forKey:@"fileName"];
  293. [mextend setObject:[NSNumber numberWithInt:1] forKey:@"fileError"];
  294. [mmsg setObject:mextend forKey:@"extend"];
  295. [mmsg setObject:@"" forKey:@"id"];
  296. }
  297. NSDictionary *sendInfo = @{
  298. @"code":@"2",
  299. @"message":mmsg,
  300. };
  301. NSError *error;
  302. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  303. if (!jsonData) {
  304. NSLog(@"Got an error: %@", error);
  305. } else {
  306. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  307. // NSLog(@"%@", jsonString);
  308. NSLog(@"----发送文件消息2----");
  309. [GWebSocket.shareInstance sendMsg:jsonString];
  310. }
  311. }
  312. }
  313. } fail:^(NSString * _Nullable error) {
  314. ;
  315. }];
  316. }
  317. @end