ShareAppService.m 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. //
  2. // ShareAppService.m
  3. // ShareExtension
  4. //
  5. // Created by Tom Lee on 2020/10/7.
  6. // Copyright © 2020 WildFireChat. All rights reserved.
  7. //
  8. #import "ShareAppService.h"
  9. #import "AFNetworking.h"
  10. #import "WFCConfig.h"
  11. #import "SharePredefine.h"
  12. #import "ShareUtility.h"
  13. static ShareAppService *sharedSingleton = nil;
  14. #define AUTHORIZATION_HEADER @"authToken"
  15. @implementation ShareAppService
  16. + (ShareAppService *)sharedAppService {
  17. if (sharedSingleton == nil) {
  18. @synchronized (self) {
  19. if (sharedSingleton == nil) {
  20. sharedSingleton = [[ShareAppService alloc] init];
  21. }
  22. }
  23. }
  24. return sharedSingleton;
  25. }
  26. - (void)sendLinkMessage:(SharedConversation *)conversation link:(NSString *)link title:(NSString *)title thumbnailLink:(NSString *)thumbnailLink success:(void(^)(NSDictionary *dict))successBlock error:(void(^)(NSString *message))errorBlock {
  27. NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
  28. [dataDict setObject:link forKey:@"u"];
  29. if (thumbnailLink) {
  30. [dataDict setObject:thumbnailLink forKey:@"t"];
  31. }
  32. if(!title) {
  33. title = link;
  34. }
  35. NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict
  36. options:kNilOptions
  37. error:nil];
  38. [self post:@"/messages/send"
  39. data:@{@"type":@(conversation.type),
  40. @"target":conversation.target,
  41. @"line":@(conversation.line),
  42. @"content_type":@(8),
  43. @"content_searchable":title,
  44. @"content_binary":[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]
  45. }
  46. success:successBlock
  47. error:errorBlock];
  48. }
  49. - (void)sendTextMessage:(SharedConversation *)conversation text:(NSString *)text success:(void(^)(NSDictionary *dict))successBlock error:(void(^)(NSString *message))errorBlock {
  50. [self post:@"/messages/send"
  51. data:@{@"type":@(conversation.type),
  52. @"target":conversation.target,
  53. @"line":@(conversation.line),
  54. @"content_type":@(1),
  55. @"content_searchable":text
  56. }
  57. success:successBlock
  58. error:errorBlock];
  59. }
  60. - (void)sendImageMessage:(SharedConversation *)conversation mediaUrl:(NSString *)mediaUrl thubnail:(UIImage *)thubnail success:(void(^)(NSDictionary *dict))successBlock error:(void(^)(NSString *message))errorBlock {
  61. NSData *data = UIImageJPEGRepresentation(thubnail, 0.4);
  62. [self post:@"/messages/send"
  63. data:@{@"type":@(conversation.type),
  64. @"target":conversation.target,
  65. @"line":@(conversation.line),
  66. @"content_type":@(3),
  67. @"content_media_type":@(1),
  68. @"content_remote_url":mediaUrl,
  69. @"content_searchable":@"[图片]",
  70. @"content_binary":[data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]
  71. }
  72. success:successBlock
  73. error:errorBlock];
  74. }
  75. - (void)sendFileMessage:(SharedConversation *)conversation mediaUrl:(NSString *)mediaUrl fileName:(NSString *)fileName size:(long long)size success:(void(^)(NSDictionary *dict))successBlock error:(void(^)(NSString *message))errorBlock {
  76. [self post:@"/messages/send"
  77. data:@{@"type":@(conversation.type),
  78. @"target":conversation.target,
  79. @"line":@(conversation.line),
  80. @"content_type":@(5),
  81. @"content_media_type":@(4),
  82. @"content_remote_url":mediaUrl,
  83. @"content_searchable":fileName,
  84. @"content":[NSString stringWithFormat:@"%lld", size]
  85. }
  86. success:successBlock
  87. error:errorBlock];
  88. }
  89. - (void)uploadFiles:(NSString *)file
  90. mediaType:(int)mediaType
  91. fullImage:(BOOL)fullImage
  92. progress:(void(^)(int sentcount, int total))progressBlock
  93. success:(void(^)(NSString *url))successBlock
  94. error:(void(^)(NSString *errorMsg))errorBlock {
  95. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  96. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  97. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
  98. NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:WFC_SHARE_APP_GROUP_ID];//此处id要与开发者中心创建时一致
  99. NSString *authToken = [sharedDefaults objectForKey:WFC_SHARE_APPSERVICE_AUTH_TOKEN];
  100. if(authToken.length) {
  101. [manager.requestSerializer setValue:authToken forHTTPHeaderField:AUTHORIZATION_HEADER];
  102. } else {
  103. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:WFC_SHARE_APP_GROUP_ID] cookies]) {
  104. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
  105. }
  106. }
  107. NSString *url = [APP_SERVER_ADDRESS stringByAppendingFormat:@"/media/upload/%d", mediaType];
  108. [manager
  109. POST:url
  110. parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  111. NSString *fileName = [[NSURL URLWithString:file] lastPathComponent];
  112. if (mediaType == 1 && !fullImage) {
  113. UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:file]]];
  114. image = [ShareUtility generateThumbnail:image withWidth:1024 withHeight:1024];
  115. NSData *imgData = UIImageJPEGRepresentation(image, 0.85);
  116. [formData appendPartWithFileData:imgData name:@"file" fileName:fileName mimeType:@"application/octet-stream"];
  117. } else {
  118. NSData *logData = [NSData dataWithContentsOfURL:[NSURL URLWithString:file]];
  119. if (!logData.length) {
  120. logData = [@"empty" dataUsingEncoding:NSUTF8StringEncoding];
  121. }
  122. [formData appendPartWithFileData:logData name:@"file" fileName:fileName mimeType:@"application/octet-stream"];
  123. }
  124. }
  125. progress:^(NSProgress * progress) {
  126. if (progressBlock) {
  127. progressBlock((int)progress.completedUnitCount, (int)progress.totalUnitCount);
  128. }
  129. }
  130. success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  131. if ([responseObject isKindOfClass:[NSDictionary class]]) {
  132. NSDictionary *dict = (NSDictionary *)responseObject;
  133. if([dict[@"code"] intValue] == 0) {
  134. NSDictionary *result = dict[@"result"];
  135. if (result && result[@"url"]) {
  136. successBlock(result[@"url"]);
  137. return;
  138. }
  139. }
  140. }
  141. errorBlock(@"服务器响应错误");
  142. }
  143. failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  144. NSLog(@"上传失败:%@", error);
  145. errorBlock(error.localizedFailureReason);
  146. }];
  147. });
  148. }
  149. - (void)uploadData:(NSData *)data
  150. mediaType:(int)mediaType
  151. progress:(void(^)(int sentcount, int total))progressBlock
  152. success:(void(^)(NSString *url))successBlock
  153. error:(void(^)(NSString *errorMsg))errorBlock {
  154. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  155. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  156. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
  157. NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:WFC_SHARE_APP_GROUP_ID];//此处id要与开发者中心创建时一致
  158. NSString *authToken = [sharedDefaults objectForKey:WFC_SHARE_APPSERVICE_AUTH_TOKEN];
  159. if(authToken.length) {
  160. [manager.requestSerializer setValue:authToken forHTTPHeaderField:AUTHORIZATION_HEADER];
  161. } else {
  162. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:WFC_SHARE_APP_GROUP_ID] cookies]) {
  163. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
  164. }
  165. }
  166. NSString *url = [APP_SERVER_ADDRESS stringByAppendingFormat:@"/media/upload/%d", mediaType];
  167. [manager
  168. POST:url
  169. parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  170. CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
  171. NSString *fileName = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuidObject));
  172. CFRelease(uuidObject);
  173. [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"application/octet-stream"];
  174. }
  175. progress:^(NSProgress * progress) {
  176. if (progressBlock) {
  177. progressBlock((int)progress.completedUnitCount, (int)progress.totalUnitCount);
  178. }
  179. }
  180. success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  181. if ([responseObject isKindOfClass:[NSDictionary class]]) {
  182. NSDictionary *dict = (NSDictionary *)responseObject;
  183. if([dict[@"code"] intValue] == 0) {
  184. NSDictionary *result = dict[@"result"];
  185. if (result && result[@"url"]) {
  186. successBlock(result[@"url"]);
  187. return;
  188. }
  189. }
  190. }
  191. errorBlock(@"服务器响应错误");
  192. }
  193. failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  194. NSLog(@"上传失败:%@", error);
  195. errorBlock(error.localizedFailureReason);
  196. }];
  197. });
  198. }
  199. - (void)post:(NSString *)path data:(id)data success:(void(^)(NSDictionary *dict))successBlock error:(void(^)(NSString *message))errorBlock {
  200. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  201. manager.requestSerializer = [AFJSONRequestSerializer serializer];
  202. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
  203. NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:WFC_SHARE_APP_GROUP_ID];//此处id要与开发者中心创建时一致
  204. NSString *authToken = [sharedDefaults objectForKey:WFC_SHARE_APPSERVICE_AUTH_TOKEN];
  205. if(authToken.length) {
  206. [manager.requestSerializer setValue:authToken forHTTPHeaderField:AUTHORIZATION_HEADER];
  207. } else {
  208. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:WFC_SHARE_APP_GROUP_ID] cookies]) {
  209. [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
  210. }
  211. }
  212. [manager POST:[APP_SERVER_ADDRESS stringByAppendingPathComponent:path]
  213. parameters:data
  214. progress:nil
  215. success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  216. NSDictionary *dict = responseObject;
  217. dispatch_async(dispatch_get_main_queue(), ^{
  218. successBlock(dict);
  219. if([dict[@"code"] intValue] == 0) {
  220. if(successBlock) successBlock(dict[@"result"]);
  221. } else {
  222. if(errorBlock) errorBlock(@"error");
  223. }
  224. });
  225. }
  226. failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  227. dispatch_async(dispatch_get_main_queue(), ^{
  228. errorBlock(error.localizedDescription);
  229. });
  230. }];
  231. }
  232. - (BOOL)isLogin {
  233. NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:WFC_SHARE_APP_GROUP_ID];
  234. return [[NSHTTPCookieStorage sharedCookieStorageForGroupContainerIdentifier:WFC_SHARE_APP_GROUP_ID] cookiesForURL:[NSURL URLWithString:APP_SERVER_ADDRESS]].count > 0 || [sharedDefaults objectForKey:WFC_SHARE_APPSERVICE_AUTH_TOKEN];
  235. }
  236. @end