OSSManager.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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:(void (^_Nullable)(bool))success{
  36. if (!_uploadTanck) {
  37. _uploadTanck = [NSMutableArray new];
  38. }
  39. [OssNetApi getOSSInfo:nil succ:^(int code, NSDictionary * res) {
  40. NSLog(@"res:%@",res);
  41. NSString *codeV =res[@"code"];
  42. if(codeV.intValue==200){
  43. self.OSSInfo = res[@"data"];
  44. if(self.OSSInfo){
  45. [UDManager.shareInstance setDDManager:self.OSSInfo key:nkOSSinfo];
  46. success(true);
  47. }
  48. }
  49. else{
  50. success(false);
  51. }
  52. } fail:^(NSError * _Nonnull error) {
  53. success(false);
  54. }];
  55. }
  56. -(void)initmyAliyunOSS{
  57. if(self.OSSInfo){
  58. // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
  59. //NSString *endpoint = @"https://oss-ap-southeast-1.aliyuncs.com";
  60. // 旧版本图片服务的endpoint
  61. // NSString *oldimgendpoint = @"http://img-ap-southeast-1.aliyuncs.com";
  62. // 从STS服务获取的临时访问密钥(AccessKey ID和AccessKey Secret)。
  63. NSString *accessKeyId = self.OSSInfo[@"accessKeyId"];
  64. NSString *accessKeySecret = self.OSSInfo[@"accessKeySecret"];
  65. // 从STS服务获取的安全令牌(SecurityToken)。
  66. NSString *securityToken = self.OSSInfo[@"securityToken"];
  67. // NSString *expiration = self.OSSInfo[@"expiration"];
  68. id<OSSCredentialProvider> credentialProvider = [[OSSStsTokenCredentialProvider alloc] initWithAccessKeyId:accessKeyId secretKeyId:accessKeySecret securityToken:securityToken];
  69. OSSClientConfiguration *cfg = [[OSSClientConfiguration alloc] init];
  70. cfg.maxRetryCount = 5;
  71. cfg.timeoutIntervalForRequest = 15;
  72. cfg.isHttpdnsEnable = NO;
  73. cfg.crc64Verifiable = YES;
  74. OSSClient *defaultClient = [[OSSClient alloc] initWithEndpoint:endpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  75. [OSSManager sharedManager].defaultClient = defaultClient;
  76. NSDate *now = [NSDate date];
  77. NSTimeInterval trt = [now timeIntervalSince1970];
  78. self.initIme = trt;
  79. //旧的图片服务
  80. // OSSClient *defaultImgClient = [[OSSClient alloc] initWithEndpoint:oldimgendpoint credentialProvider:credentialProvider clientConfiguration:cfg];
  81. // [OSSManager sharedManager].imageClient = defaultImgClient;
  82. }
  83. }
  84. //普通上传
  85. - (void)asyncPutFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  86. if([self chectToken]){
  87. if([OSSManager sharedManager].defaultClient==nil){
  88. [self getOSSInfo:^(bool code){
  89. if(code){
  90. [self initmyAliyunOSS];
  91. [self prasyncPutFile:objectKey localFilePath:filePath thrid:strtime];
  92. }
  93. else{
  94. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  95. }
  96. }];
  97. }
  98. else{
  99. [self prasyncPutFile:objectKey localFilePath:filePath thrid:strtime];
  100. }
  101. }
  102. else{
  103. [self getOSSInfo:^(bool code){
  104. if(code){
  105. [self initmyAliyunOSS];
  106. [self prasyncPutFile:objectKey localFilePath:filePath thrid:strtime];
  107. }
  108. else{
  109. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  110. }
  111. }];
  112. }
  113. }
  114. -(void)prasyncPutFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  115. if (![objectKey oss_isNotEmpty]) {
  116. if(self.delegate){
  117. NSDictionary *dic=@{
  118. @"state":@"3",
  119. @"pcent":@"",
  120. @"thrid":strtime
  121. };
  122. [self.delegate stateChange:dic];
  123. }
  124. return;
  125. }
  126. NSLog(@"objectKey:%@",objectKey);
  127. _normalUploadRequest = [OSSPutObjectRequest new];
  128. _normalUploadRequest.bucketName = self.OSSInfo[@"bucket"];
  129. _normalUploadRequest.objectKey = objectKey;
  130. _normalUploadRequest.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  131. _normalUploadRequest.isAuthenticationRequired = YES;
  132. weakSelf(self);
  133. _normalUploadRequest.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  134. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  135. // NSLog(@"上传文件进度: %f", progress);
  136. NSInteger pcent =progress*100;
  137. if(weakself.delegate){
  138. NSDictionary *dic=@{
  139. @"state":@"1",
  140. @"pcent":[NSString stringWithFormat:@"%ld",(long)pcent],
  141. @"thrid":strtime
  142. };
  143. [weakself.delegate stateChange:dic];
  144. }
  145. };
  146. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  147. OSSTask * task = [[OSSManager sharedManager].defaultClient putObject:self->_normalUploadRequest];
  148. [task continueWithBlock:^id(OSSTask *task) {
  149. dispatch_async(dispatch_get_main_queue(), ^{
  150. if (task.error) {
  151. [self updataFileMsg:strtime state:@"1"];
  152. if(self.delegate){
  153. NSDictionary *dic=@{
  154. @"state":@"3",
  155. @"pcent":@"",
  156. @"thrid":strtime
  157. };
  158. [self.delegate stateChange:dic];
  159. }
  160. } else {
  161. NSLog(@"上传文件完成");
  162. [self updataFileMsg:strtime state:@"2"];
  163. if(self.delegate){
  164. NSDictionary *dic=@{
  165. @"state":@"2",
  166. @"pcent":@"",
  167. @"thrid":strtime
  168. };
  169. [self.delegate stateChange:dic];
  170. }
  171. }
  172. });
  173. return nil;
  174. }];
  175. });
  176. }
  177. //断点续传
  178. - (void)asyncResumableUploadFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  179. if([self chectToken]){
  180. if([OSSManager sharedManager].defaultClient==nil){
  181. [self getOSSInfo:^(bool code){
  182. if(code){
  183. [self initmyAliyunOSS];
  184. [self PrasyncResumableUploadFile:objectKey localFilePath:filePath thrid:strtime];
  185. }
  186. else{
  187. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  188. }
  189. }];
  190. }
  191. else{
  192. [self PrasyncResumableUploadFile:objectKey localFilePath:filePath thrid:strtime];
  193. }
  194. }
  195. else{
  196. [self getOSSInfo:^(bool code){
  197. if(code){
  198. [self initmyAliyunOSS];
  199. [self PrasyncResumableUploadFile:objectKey localFilePath:filePath thrid:strtime];
  200. }
  201. else{
  202. [MBProgressHUD showWithText:@"OSS文件服务初始化失败!請重試"];
  203. }
  204. }];
  205. }
  206. }
  207. -(void)PrasyncResumableUploadFile:(NSString *)objectKey localFilePath:(NSString *)filePath thrid:(NSString *)strtime{
  208. // 获取UploadId上传文件。
  209. OSSResumableUploadRequest * resumableUpload = [OSSResumableUploadRequest new];
  210. resumableUpload.bucketName = self.OSSInfo[@"bucket"];
  211. // objectKey等同于objectName,表示断点上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg
  212. resumableUpload.objectKey = objectKey;
  213. resumableUpload.partSize = 1024 * 1024;
  214. resumableUpload.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
  215. // NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
  216. CGFloat progress = 1.f * totalByteSent / totalBytesExpectedToSend;
  217. // NSLog(@"上传文件进度: %f", progress);
  218. NSInteger pcent =progress*100;
  219. if(self.delegate){
  220. NSDictionary *dic=@{
  221. @"state":@"1",
  222. @"pcent":[NSString stringWithFormat:@"%ld",(long)pcent],
  223. @"thrid":strtime
  224. };
  225. [self.delegate stateChange:dic];
  226. }
  227. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  228. // prgress(pcent,strtime);
  229. // });
  230. };
  231. NSString *cachesDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  232. // 设置断点记录保存路径。
  233. resumableUpload.recordDirectoryPath = cachesDir;
  234. // 将参数deleteUploadIdOnCancelling设置为NO,表示不删除断点记录文件,上传失败后将从断点记录处继续上传直到文件上传完成。如果不设置此参数,即保留默认值YES,表示删除断点记录文件,下次再上传同一文件时则重新上传。
  235. resumableUpload.deleteUploadIdOnCancelling = NO;
  236. resumableUpload.uploadingFileURL = [NSURL fileURLWithPath:filePath];
  237. OSSTask * resumeTask = [[OSSManager sharedManager].defaultClient resumableUpload:resumableUpload];
  238. [self addUploadTanckobj:resumeTask thrid:strtime];
  239. [resumeTask continueWithBlock:^id(OSSTask *task) {
  240. if (task.error) {
  241. NSLog(@"error: %@", task.error);
  242. if ([task.error.domain isEqualToString:OSSClientErrorDomain] && task.error.code == OSSClientErrorCodeCannotResumeUpload) {
  243. // 此任务无法续传,需获取新的uploadId重新上传。
  244. }
  245. [self updataFileMsg:strtime state:@"3"];
  246. // if(self.delegate){
  247. // NSDictionary *dic=@{
  248. // @"state":@"3",
  249. // @"pcent":@"",
  250. // @"thrid":strtime
  251. // };
  252. // [self.delegate stateChange:dic];
  253. // }
  254. } else {
  255. NSLog(@"Upload file success");
  256. [self updataFileMsg:strtime state:@"2"];
  257. // if(self.delegate){
  258. // NSDictionary *dic=@{
  259. // @"state":@"2",
  260. // @"pcent":@"",
  261. // @"thrid":strtime
  262. // };
  263. // [self.delegate stateChange:dic];
  264. // }
  265. }
  266. return nil;
  267. }];
  268. // [resumeTask waitUntilFinished];
  269. // [resumableUpload cancel];
  270. }
  271. -(void)addUploadTanckobj:(OSSTask *)task thrid:(NSString *)thrid{
  272. NSDictionary *item = @{
  273. @"task":task,
  274. @"thrid":thrid
  275. };
  276. [_uploadTanck addObject:item];
  277. }
  278. -(BOOL)isuploadTanck:(NSString *)thrid{
  279. // NSLog(@"stopUploadTanck-------------2");
  280. if(_uploadTanck.count>0){
  281. for (NSDictionary *item in _uploadTanck) {
  282. NSString *th = item[@"thrid"];
  283. NSLog(@"stopUploadTanck-------------3");
  284. if([th isEqualToString:thrid]){
  285. NSLog(@"stopUploadTanck-------------4");
  286. return true;
  287. }
  288. }
  289. }
  290. return false;
  291. }
  292. -(void)removeUploadTanckobj:(NSString *)thrid{
  293. if(_uploadTanck.count>0){
  294. for (NSDictionary *item in _uploadTanck) {
  295. NSString *th = item[@"thrid"];
  296. if([th isEqualToString:thrid]){
  297. [_uploadTanck removeObject:item];
  298. return;
  299. }
  300. }
  301. }
  302. }
  303. -(void)stopUploadTanck:(NSString *)thrid{
  304. NSLog(@"stopUploadTanck-------------2");
  305. if(_uploadTanck.count>0){
  306. for (NSDictionary *item in _uploadTanck) {
  307. NSString *th = item[@"thrid"];
  308. NSLog(@"stopUploadTanck-------------3");
  309. if([th isEqualToString:thrid]){
  310. OSSTask *task = item[@"task"];
  311. NSLog(@"stopUploadTanck-------------4");
  312. //[task cancel];取消传输
  313. return;
  314. }
  315. }
  316. }
  317. }
  318. -(void)updataFileMsg:(NSString *)thrid state:(NSString *)state{
  319. [GDBManager.shareInstance selectLocalmsgWithLocaltime:thrid succ:^(NSArray * _Nullable array) {
  320. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  321. if(array){
  322. if(array.count>0){
  323. NSDictionary *msg =array[0];
  324. NSString *msgtype = msg[@"messageType"];
  325. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  326. return;
  327. }
  328. NSDictionary *extend=msg[@"extend"];
  329. NSMutableDictionary *mextend = [extend mutableCopy];
  330. NSMutableDictionary *mmsg = [msg mutableCopy];
  331. if([state isEqualToString:@"2"]){
  332. NSString *localPath =extend[@"localurl"];
  333. NSURL *loaclUrl = [NSURL URLWithString:localPath];
  334. NSString *url = [NSString stringWithFormat:@"http://oss.abtim-my.com/%@",loaclUrl.lastPathComponent];
  335. [mextend setObject:url forKey:@"url"];
  336. [mextend setObject:[NSNumber numberWithInt:0] forKey:@"fileError"];
  337. [mmsg setObject:mextend forKey:@"extend"];
  338. [mmsg setObject:@"" forKey:@"id"];
  339. }
  340. else if([state isEqualToString:@"3"]){
  341. [mextend setObject:@"" forKey:@"url"];
  342. [mextend setObject:@"" forKey:@"fileName"];
  343. [mextend setObject:[NSNumber numberWithInt:1] forKey:@"fileError"];
  344. [mmsg setObject:mextend forKey:@"extend"];
  345. [mmsg setObject:@"" forKey:@"id"];
  346. [ChatsStore.shareInstance reciveMsg:mmsg];
  347. return;
  348. }
  349. NSDictionary *sendInfo = @{
  350. @"code":@"2",
  351. @"message":mmsg,
  352. };
  353. NSError *error;
  354. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  355. if (!jsonData) {
  356. NSLog(@"Got an error: %@", error);
  357. } else {
  358. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  359. // NSLog(@"%@", jsonString);
  360. NSLog(@"----发送文件消息2----");
  361. [GWebSocket.shareInstance sendMsg:jsonString];
  362. }
  363. }
  364. }
  365. } fail:^(NSString * _Nullable error) {
  366. ;
  367. }];
  368. }
  369. -(BOOL)chectToken{
  370. if(self.initIme>0){
  371. NSDate *now = [NSDate date];
  372. NSTimeInterval trt = [now timeIntervalSince1970];
  373. NSInteger time = trt;
  374. time =time-self.initIme;
  375. NSLog(@"chectToken------:%ld",(long)time);
  376. if(time>2000){
  377. return false;
  378. }
  379. else{
  380. return true;
  381. }
  382. }
  383. else{
  384. return false;
  385. }
  386. return false;
  387. }
  388. @end