ContactPhotoSender.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2013-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "ContactPhotoSender.h"
  21. #import "Conversation.h"
  22. #import "Utils.h"
  23. #import "NaClCrypto.h"
  24. #import "MyIdentityStore.h"
  25. #import "ContactSetPhotoMessage.h"
  26. #import "ContactDeletePhotoMessage.h"
  27. #import "ContactRequestPhotoMessage.h"
  28. #import "MessageQueue.h"
  29. #import "NSString+Hex.h"
  30. #import "ActivityIndicatorProxy.h"
  31. #import "SSLCAHelper.h"
  32. #import "Contact.h"
  33. #import "BlobUtil.h"
  34. #import "ThreemaError.h"
  35. #import "ContactStore.h"
  36. #import "EntityManager.h"
  37. #import "UserSettings.h"
  38. #ifdef DEBUG
  39. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  40. #else
  41. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  42. #endif
  43. #define kTimeToUploadNextBlob -60*60*24*7
  44. @implementation ContactPhotoSender {
  45. Contact *toMember;
  46. NSData *boxImageData;
  47. NSData *nonce;
  48. NSData *encryptionKey;
  49. NSMutableData *receivedData;
  50. NSURLConnection *uploadConnection;
  51. void(^onCompletion)(void);
  52. void(^onError)(NSError *error);
  53. }
  54. // MARK: - Profile picture request send
  55. + (void)sendProfilePictureRequest:(NSString *)toIdentity {
  56. DDLogVerbose(@"send profile pic request to %@", toIdentity);
  57. ContactRequestPhotoMessage *msg = [[ContactRequestPhotoMessage alloc] init];
  58. msg.toIdentity = toIdentity;
  59. [[MessageQueue sharedMessageQueue] enqueue:msg];
  60. }
  61. // MARK: - Profile picture send/upload
  62. + (Contact *)shouldSendProfilePictureToContact:(NSString *)identity {
  63. enum SendProfilePicture preference = [UserSettings sharedUserSettings].sendProfilePicture;
  64. if (preference == SendProfilePictureNone) {
  65. return nil;
  66. }
  67. else if (preference == SendProfilePictureContacts) {
  68. NSArray *contactIdentities = [UserSettings sharedUserSettings].profilePictureContactList;
  69. NSSet *selectedContacts = [NSMutableSet setWithArray:contactIdentities];
  70. if (![selectedContacts containsObject:identity]) {
  71. return nil;
  72. }
  73. }
  74. Contact *contact = [[ContactStore sharedContactStore] contactForIdentity:identity];
  75. if (contact.isGatewayId || contact.isEchoEcho) {
  76. return nil;
  77. }
  78. if (!contact.isProfilePictureSended) {
  79. return contact;
  80. }
  81. return nil;
  82. }
  83. + (void)sendProfilePicture:(AbstractMessage *)message {
  84. if ([message allowToSendProfilePicture]) {
  85. Contact *contact = [ContactPhotoSender shouldSendProfilePictureToContact:message.toIdentity];
  86. if (contact) {
  87. // send profile picture
  88. ContactPhotoSender *sender = [[ContactPhotoSender alloc] init];
  89. [sender startWithImageToMember:contact onCompletion:^{
  90. } onError:^(NSError *err) {
  91. }];
  92. }
  93. ContactStore *contactStore = [ContactStore sharedContactStore];
  94. if ([contactStore existsProfilePictureRequest:message.toIdentity]) {
  95. // send profile picture request
  96. [ContactPhotoSender sendProfilePictureRequest:message.toIdentity];
  97. [contactStore removeProfilePictureRequest:message.toIdentity];
  98. }
  99. }
  100. }
  101. - (void)startWithImageToMember:(Contact*)_toMember onCompletion:(void (^)(void))_onCompletion onError:(void (^)(NSError *))_onError {
  102. toMember = _toMember;
  103. onCompletion = _onCompletion;
  104. onError = _onError;
  105. NSMutableDictionary *profilePicture = [[MyIdentityStore sharedMyIdentityStore] profilePicture];
  106. if (profilePicture[@"ProfilePicture"] == nil) {
  107. if (toMember != nil) {
  108. // save to database
  109. EntityManager *entityManager = [[EntityManager alloc] init];
  110. [entityManager performAsyncBlockAndSafe:^{
  111. toMember.profilePictureSended = YES;
  112. toMember.profilePictureUpload = [NSDate date];
  113. }];
  114. /* send to the specified member only */
  115. [self sendDeletePhotoMessageToMember:toMember];
  116. }
  117. dispatch_async(dispatch_get_main_queue(), ^{
  118. onCompletion();
  119. });
  120. } else {
  121. // check if date is older then 2 weeks when uploading blob, when not send only the blob id in the message
  122. NSMutableDictionary *profilePicture = [[MyIdentityStore sharedMyIdentityStore] profilePicture];
  123. NSDate *lastUpload = profilePicture[@"LastUpload"];
  124. NSDate *blobValidDate = [NSDate dateWithTimeIntervalSinceNow:kTimeToUploadNextBlob];
  125. if (lastUpload && [lastUpload earlierDate:blobValidDate] == blobValidDate) {
  126. if (toMember != nil) {
  127. // save to database
  128. EntityManager *entityManager = [[EntityManager alloc] init];
  129. [entityManager performAsyncBlockAndSafe:^{
  130. toMember.profilePictureSended = YES;
  131. toMember.profilePictureUpload = [NSDate date];
  132. }];
  133. /* send to the specified member only */
  134. [self sendSetPhotoMessageToMember:toMember withProfilePicture:profilePicture];
  135. }
  136. dispatch_async(dispatch_get_main_queue(), ^{
  137. onCompletion();
  138. });
  139. } else {
  140. /* Generate random symmetric key and encrypt */
  141. encryptionKey = [[NaClCrypto sharedCrypto] randomBytes:kBlobKeyLen];
  142. boxImageData = [[NaClCrypto sharedCrypto] symmetricEncryptData:profilePicture[@"ProfilePicture"] withKey:encryptionKey nonce:[NSData dataWithBytesNoCopy:kNonce_1 length:sizeof(kNonce_1) freeWhenDone:NO]];
  143. [self startUpload];
  144. }
  145. }
  146. }
  147. - (void)startUpload {
  148. [ActivityIndicatorProxy startActivity];
  149. NSURL *blobUploadUrl = [BlobUtil urlForBlobUpload];
  150. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:blobUploadUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:kBlobUploadTimeout];
  151. request.HTTPMethod = @"POST";
  152. NSString *boundary = @"---------------------------Boundary_Line";
  153. NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
  154. [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
  155. NSMutableData *body = [NSMutableData dataWithCapacity:boxImageData.length + 1024];
  156. [body appendData:[[NSString stringWithFormat:@"--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  157. [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"blob\"; filename=\"blob.bin\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
  158. [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
  159. [body appendData:boxImageData];
  160. [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  161. [request setHTTPBody:body];
  162. [request addValue:[NSString stringWithFormat:@"%lu", (unsigned long)[body length]] forHTTPHeaderField:@"Content-Length"];
  163. receivedData = [NSMutableData data];
  164. uploadConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
  165. }
  166. - (void)uploadCompletedWithBlobId:(NSData*)blobId {
  167. if (toMember != nil) {
  168. /* send to the specified member only */
  169. [self sendSetPhotoMessageToMember:toMember withBlobId:blobId];
  170. }
  171. dispatch_async(dispatch_get_main_queue(), ^{
  172. onCompletion();
  173. });
  174. }
  175. - (void)sendSetPhotoMessageToMember:(Contact*)member withBlobId:(NSData*)blobId {
  176. DDLogVerbose(@"Sending contact photo message to %@", member.identity);
  177. NSMutableDictionary *profilePicture = [[MyIdentityStore sharedMyIdentityStore] profilePicture];
  178. if (!profilePicture) {
  179. profilePicture = [NSMutableDictionary new];
  180. }
  181. [profilePicture setValue:blobId forKey:@"BlobId"];
  182. [profilePicture setValue:[NSNumber numberWithUnsignedInteger:boxImageData.length] forKey:@"Size"];
  183. [profilePicture setValue:encryptionKey forKey:@"EncryptionKey"];
  184. [profilePicture setValue:[NSDate date] forKey:@"LastUpload"];
  185. [[MyIdentityStore sharedMyIdentityStore] setProfilePicture:profilePicture];
  186. ContactSetPhotoMessage *msg = [[ContactSetPhotoMessage alloc] init];
  187. msg.blobId = blobId;
  188. msg.size = (uint32_t)boxImageData.length;
  189. msg.encryptionKey = encryptionKey;
  190. msg.toIdentity = member.identity;
  191. [[MessageQueue sharedMessageQueue] enqueue:msg];
  192. }
  193. - (void)sendSetPhotoMessageToMember:(Contact*)member withProfilePicture:(NSMutableDictionary *)profilePicture {
  194. DDLogVerbose(@"Sending contact photo message to %@", member.identity);
  195. ContactSetPhotoMessage *msg = [[ContactSetPhotoMessage alloc] init];
  196. msg.blobId = profilePicture[@"BlobId"];
  197. msg.size = (uint32_t)[profilePicture[@"Size"] unsignedIntValue];
  198. msg.encryptionKey = profilePicture[@"EncryptionKey"];
  199. msg.toIdentity = member.identity;
  200. [[MessageQueue sharedMessageQueue] enqueue:msg];
  201. }
  202. - (void)sendDeletePhotoMessageToMember:(Contact *)member {
  203. DDLogVerbose(@"Delete contact photo message to %@", member.identity);
  204. ContactDeletePhotoMessage *msg = [[ContactDeletePhotoMessage alloc] init];
  205. msg.toIdentity = member.identity;
  206. [[MessageQueue sharedMessageQueue] enqueue:msg];
  207. }
  208. #pragma mark - URL connection delegate
  209. - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
  210. DDLogVerbose(@"Request succeeded - received %lu bytes", (unsigned long)[receivedData length]);
  211. [ActivityIndicatorProxy stopActivity];
  212. NSString *blobIdHex = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
  213. NSData *blobId = [blobIdHex decodeHex];
  214. if (blobId.length != kBlobIdLen) {
  215. DDLogError(@"Got invalid blob ID from server: %@", blobId);
  216. [self connection:connection didFailWithError:[ThreemaError threemaError:@"Got invalid blob ID from server"]];
  217. return;
  218. }
  219. // save to database
  220. EntityManager *entityManager = [[EntityManager alloc] init];
  221. [entityManager performAsyncBlockAndSafe:^{
  222. toMember.profilePictureSended = YES;
  223. toMember.profilePictureUpload = [NSDate date];
  224. }];
  225. DDLogVerbose(@"Blob ID: %@", blobId);
  226. [self uploadCompletedWithBlobId:blobId];
  227. }
  228. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  229. DDLogError(@"Connection failed - error %@ %@",
  230. [error localizedDescription],
  231. [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
  232. [ActivityIndicatorProxy stopActivity];
  233. onError(error);
  234. }
  235. /* this method ensures that HTTP errors get treated like connection failures etc. as well */
  236. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
  237. [receivedData setLength:0];
  238. NSInteger statusCode = [((NSHTTPURLResponse *)response) statusCode];
  239. if (statusCode >= 400)
  240. {
  241. [connection cancel]; // stop connecting; no more delegate messages
  242. NSDictionary *errorInfo = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
  243. NSLocalizedString(@"Server returned status code %d",@""),
  244. statusCode]
  245. forKey:NSLocalizedDescriptionKey];
  246. NSError *statusError = [NSError errorWithDomain:NSURLErrorDomain
  247. code:statusCode
  248. userInfo:errorInfo];
  249. [self connection:connection didFailWithError:statusError];
  250. }
  251. }
  252. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
  253. [receivedData appendData:data];
  254. }
  255. - (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
  256. return [SSLCAHelper connection:connection canAuthenticateAgainstProtectionSpace:protectionSpace];
  257. }
  258. - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
  259. [SSLCAHelper connection:connection didReceiveAuthenticationChallenge:challenge];
  260. }
  261. - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
  262. return nil;
  263. }
  264. @end