OSSManager.m 17 KB

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