Utils.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2012-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 <CommonCrypto/CommonCrypto.h>
  21. #import <sys/utsname.h>
  22. #import "NSString+Hex.h"
  23. #import <CoreLocation/CoreLocation.h>
  24. #import <time.h>
  25. #import <sys/sysctl.h>
  26. #import "UserSettings.h"
  27. #import "BundleUtil.h"
  28. #import "LicenseStore.h"
  29. #import <UserNotifications/UserNotifications.h>
  30. #import "ThreemaFramework/ThreemaFramework-swift.h"
  31. #import "UIImage+ColoredImage.h"
  32. #import "Utils.h"
  33. #define OVERLAY_DIAMETER 80.0
  34. #ifdef DEBUG
  35. static const DDLogLevel ddLogLevel = DDLogLevelVerbose;
  36. #else
  37. static const DDLogLevel ddLogLevel = DDLogLevelWarning;
  38. #endif
  39. @implementation Utils
  40. + (unsigned)unitFlags {
  41. #pragma clang diagnostic push
  42. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  43. return NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
  44. #pragma clang diagnostic pop
  45. }
  46. + (BOOL)isSameDayWithDate1:(NSDate*)date1 date2:(NSDate*)date2 {
  47. NSCalendar* calendar = [NSCalendar currentCalendar];
  48. unsigned unitFlags = [self unitFlags];
  49. NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];
  50. NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];
  51. return [comp1 day] == [comp2 day] &&
  52. [comp1 month] == [comp2 month] &&
  53. [comp1 year] == [comp2 year];
  54. }
  55. + (NSError*)threemaError:(NSString*)message {
  56. return [self threemaError:message withCode:kGeneralErrorCode];
  57. }
  58. + (NSError*)threemaError:(NSString*)message withCode:(NSInteger)code {
  59. NSDictionary *userDict = [NSDictionary dictionaryWithObject:message
  60. forKey:NSLocalizedDescriptionKey];
  61. return [NSError errorWithDomain:@"ThreemaErrorDomain" code:code userInfo:userDict];
  62. }
  63. + (NSString*)formatShortLastMessageDate:(NSDate*)date {
  64. NSLocale *locale = [NSLocale currentLocale];
  65. NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
  66. NSDate *now = [[NSDate alloc] init];
  67. NSDateComponents *components = [gregorian components:[self unitFlags] fromDate:now];
  68. NSDate *midnight = [gregorian dateFromComponents:components];
  69. NSDateFormatter *df = [[NSDateFormatter alloc] init];
  70. [df setLocale:locale];
  71. /* today? */
  72. if ([date compare:midnight] == NSOrderedDescending) {
  73. /* show only time */
  74. df.dateStyle = NSDateFormatterNoStyle;
  75. df.timeStyle = NSDateFormatterShortStyle;
  76. } else {
  77. df.doesRelativeDateFormatting = YES;
  78. df.dateStyle = NSDateFormatterShortStyle;
  79. df.timeStyle = NSDateFormatterNoStyle;
  80. }
  81. return [df stringFromDate:date];
  82. }
  83. + (NSString*)getClientVersion {
  84. /* Format: 1.0b234;I;de/CH;iPhone7,2;9.3 */
  85. NSString *appAndBuildVersion = [Utils appAndBuildVersion];
  86. struct utsname systemInfo;
  87. uname(&systemInfo);
  88. NSString *machine = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  89. NSString *clientVersion = [NSString stringWithFormat:@"%@;I;%@/%@;%@;%@", appAndBuildVersion,
  90. [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode],
  91. [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode],
  92. machine, [[UIDevice currentDevice] systemVersion]];
  93. return clientVersion;
  94. }
  95. + (NSString *)appAndBuildVersion {
  96. NSBundle *mainBundle = [NSBundle mainBundle];
  97. NSString *version = [mainBundle objectForInfoDictionaryKey: @"CFBundleShortVersionString"];
  98. NSString *suffix = [mainBundle objectForInfoDictionaryKey: @"ThreemaVersionSuffix"];
  99. if (suffix != nil)
  100. version = [version stringByAppendingString:suffix];
  101. NSString *build = [mainBundle objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey];
  102. return [NSString stringWithFormat:@"%@b%@", version, build];
  103. }
  104. + (void)reverseGeocodeNearLatitude:(double)latitude longitude:(double)longitude accuracy:(double)accuracy completion:(void (^)(NSString *label))completion onError:(void(^)(NSError *error))onError {
  105. CLGeocoder *geocoder = [[CLGeocoder alloc] init];
  106. CLLocation *location = [[CLLocation alloc] initWithCoordinate:CLLocationCoordinate2DMake(latitude, longitude) altitude:0 horizontalAccuracy:accuracy verticalAccuracy:-1 timestamp:[NSDate date]];
  107. [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
  108. if (placemarks == nil) {
  109. DDLogWarn(@"Reverse geocode failed: %@", error);
  110. onError(error);
  111. return;
  112. }
  113. CLPlacemark *placemark = [placemarks objectAtIndex:0];
  114. NSString *label;
  115. NSArray *addressLines = [placemark.addressDictionary objectForKey:@"FormattedAddressLines"];
  116. if (addressLines == nil) {
  117. label = placemark.name;
  118. } else {
  119. label = [addressLines componentsJoinedByString:@", "];
  120. }
  121. completion(label);
  122. }];
  123. }
  124. + (time_t)systemUptime {
  125. struct timeval boottime;
  126. int mib[2] = {CTL_KERN, KERN_BOOTTIME};
  127. size_t size = sizeof(boottime);
  128. time_t now;
  129. time_t uptime = -1;
  130. (void)time(&now);
  131. if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && boottime.tv_sec != 0) {
  132. uptime = now - boottime.tv_sec;
  133. }
  134. return uptime;
  135. }
  136. + (NSString *)timeStringForSeconds: (NSInteger) totalSeconds {
  137. NSInteger minutes = totalSeconds / 60;
  138. NSInteger seconds = totalSeconds % 60;
  139. return [NSString stringWithFormat:@"%02ld:%02ld", (long)minutes, (long)seconds];
  140. }
  141. + (NSString *)accessabilityTimeStringForSeconds: (NSInteger) totalSeconds {
  142. NSDateComponentsFormatter* formatter = [[NSDateComponentsFormatter alloc] init];
  143. formatter.unitsStyle = NSDateComponentsFormatterUnitsStyleFull;
  144. formatter.collapsesLargestUnit = YES;
  145. formatter.allowedUnits = NSCalendarUnitMinute | NSCalendarUnitSecond;
  146. return [formatter stringFromTimeInterval:totalSeconds];
  147. }
  148. + (NSString *)accessibilityStringAtTime:(NSTimeInterval)timeInterval withPrefix:(NSString *)prefixKey {
  149. NSString *accessabilityTime = [self accessabilityTimeStringForSeconds:timeInterval];
  150. NSString *at = [BundleUtil localizedStringForKey:prefixKey];
  151. return [NSString stringWithFormat:@"%@ %@", at, accessabilityTime];
  152. }
  153. + (NSDate*)parseISO8601DateString:(NSString*)dateString {
  154. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  155. dateFormatter.dateFormat = @"YYYY-MM-dd'T'HH:mm:ssZZZ";
  156. return [dateFormatter dateFromString:dateString];
  157. }
  158. + (NSString *)formatDataLength:(CGFloat)numBytes {
  159. if (numBytes > 256.0 * 1024.0) {
  160. return [NSString stringWithFormat:@"%.1f MB", numBytes / (1024.0 * 1024.0)];
  161. } else {
  162. return [NSString stringWithFormat:@"%.1f kB", numBytes / 1024.0];
  163. }
  164. }
  165. + (NSString *)stringFromContacts:(NSArray *)contacts {
  166. NSMutableString *result = [NSMutableString string];
  167. NSInteger count = [contacts count];
  168. [contacts enumerateObjectsUsingBlock:^(Contact *contact, NSUInteger idx, BOOL *stop) {
  169. [result appendString:contact.displayName];
  170. if (idx < count - 1) {
  171. [result appendString:@" / "];
  172. }
  173. }];
  174. return [result description];
  175. }
  176. + (BOOL)isValidEmail:(NSString *)email {
  177. // most basic verification: contains @ and .
  178. if (email.length < 2) {
  179. return NO;
  180. }
  181. NSString *regExPattern = @"^.+@.+\\..+$";
  182. NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
  183. NSUInteger regExMatches = [regEx numberOfMatchesInString:email options:0 range:NSMakeRange(0, [email length])];
  184. return regExMatches == 1;
  185. }
  186. + (UIView *)view:(UIView *)view getSuperviewOfKind:(Class)class {
  187. UIView *tmpView = view;
  188. while (tmpView.superview) {
  189. if ([tmpView isKindOfClass:class]) {
  190. return tmpView;
  191. }
  192. tmpView = tmpView.superview;
  193. }
  194. return nil;
  195. }
  196. + (UIViewAnimationOptions)animationOptionsFor:(NSNotification *)notification animationDuration:(NSTimeInterval*)animationDuration {
  197. NSNumber *durationValue = notification.userInfo[UIKeyboardAnimationDurationUserInfoKey];
  198. *animationDuration = durationValue.doubleValue;
  199. NSNumber *curveValue = notification.userInfo[UIKeyboardAnimationCurveUserInfoKey];
  200. UIViewAnimationCurve animationCurve = curveValue.intValue;
  201. return (animationCurve << 16 | UIViewAnimationOptionBeginFromCurrentState);
  202. }
  203. + (UIImage *)makeThumbWithOverlayFor:(UIImage *)image {
  204. UIGraphicsBeginImageContext(image.size);
  205. [image drawInRect:CGRectMake(0.0, 0.0, image.size.width, image.size.height)];
  206. UIImage *playOverlayImage = [[BundleUtil imageNamed:@"Play"] imageWithTint:[UIColor whiteColor]];
  207. CGSize playImageSize = CGSizeMake(OVERLAY_DIAMETER,OVERLAY_DIAMETER);
  208. CGFloat x = (image.size.width - playImageSize.width)/2.0;
  209. CGFloat y = (image.size.height - playImageSize.height)/2.0;
  210. [playOverlayImage drawInRect:CGRectMake(x, y, playImageSize.width, playImageSize.height) blendMode:kCGBlendModeNormal alpha:0.8];
  211. UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
  212. UIGraphicsEndImageContext();
  213. return resultImage;
  214. }
  215. + (NSData*)truncatedUTF8String:(NSString*)str maxLength:(NSUInteger)maxLength {
  216. /* Keep removing characters at the end until the encoded length is less than
  217. or equal to the desired maximum length. This avoids producing invalid UTF-8 encoded strings
  218. which are possible if the encoded byte array is truncated, potentially in the middle of
  219. an encoded multi-byte character.
  220. */
  221. NSString *curString = str;
  222. NSData *data = [curString dataUsingEncoding:NSUTF8StringEncoding];
  223. while (data.length > maxLength) {
  224. /* Note: some characters (e.g. Emojis) don't fit in UTF-16, which is what NSString deals with,
  225. so we need to correctly determine the offset to cut off and can't simply remove the last "character". */
  226. NSUInteger lastCharIndex = curString.length - 1;
  227. NSRange rangeOfLastChar = [curString rangeOfComposedCharacterSequenceAtIndex:lastCharIndex];
  228. curString = [curString substringToIndex:rangeOfLastChar.location];
  229. data = [curString dataUsingEncoding:NSUTF8StringEncoding];
  230. }
  231. return data;
  232. }
  233. + (BOOL)hideThreemaTypeIconForContact:(Contact *)contact {
  234. if (contact.isEchoEcho || contact.isGatewayId) {
  235. return YES;
  236. }
  237. if ([LicenseStore requiresLicenseKey]) {
  238. return [[UserSettings sharedUserSettings].workIdentities containsObject:contact.identity];
  239. } else {
  240. return ![[UserSettings sharedUserSettings].workIdentities containsObject:contact.identity];
  241. }
  242. }
  243. + (UIImage *)threemaTypeIcon {
  244. if ([LicenseStore requiresLicenseKey]) {
  245. return [StyleKit houseIcon];
  246. } else {
  247. return [StyleKit workIcon];
  248. }
  249. }
  250. + (NSArray *)getTrimmedMessages:(NSString *)message {
  251. NSMutableArray *trimmedMessages = nil;
  252. // Enforce maximum text message length
  253. NSData *trimmedMessageData = [message dataUsingEncoding:NSUTF8StringEncoding];
  254. if (trimmedMessageData.length > kMaxMessageLen) {
  255. trimmedMessages = [NSMutableArray new];
  256. BOOL finished = NO;
  257. NSString *tmpTrimmedMessage = [NSString stringWithString:message];
  258. while (!finished) {
  259. NSString *checkString = nil;
  260. if ([tmpTrimmedMessage lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > kMaxMessageLen) {
  261. NSRange lastWhiteSpaceRange= [tmpTrimmedMessage rangeOfString: @" " options: NSBackwardsSearch];
  262. if (lastWhiteSpaceRange.location != NSNotFound) {
  263. checkString = [tmpTrimmedMessage substringWithRange:NSMakeRange(0, lastWhiteSpaceRange.location)];
  264. if (checkString.length == 0) {
  265. NSRange range = [tmpTrimmedMessage rangeOfComposedCharacterSequenceAtIndex:tmpTrimmedMessage.length-1];
  266. checkString = [tmpTrimmedMessage substringWithRange:NSMakeRange(0, range.location)];
  267. }
  268. } else {
  269. NSRange range = [tmpTrimmedMessage rangeOfComposedCharacterSequenceAtIndex:tmpTrimmedMessage.length-1];
  270. checkString = [tmpTrimmedMessage substringWithRange:NSMakeRange(0, range.location)];
  271. }
  272. } else {
  273. checkString = tmpTrimmedMessage;
  274. }
  275. if ([checkString lengthOfBytesUsingEncoding:NSUTF8StringEncoding] <= kMaxMessageLen) {
  276. NSRange stringLocation = [message rangeOfString:checkString options:NSLiteralSearch];
  277. if (stringLocation.location == NSNotFound) {
  278. NSLog(@"FAILED!!!!!!!!!!!!");
  279. return nil;
  280. }
  281. [trimmedMessages addObject:checkString];
  282. message = [message substringWithRange:NSMakeRange(stringLocation.location + stringLocation.length, message.length - (stringLocation.location + stringLocation.length))];
  283. tmpTrimmedMessage = [NSString stringWithString:message];
  284. if (tmpTrimmedMessage.length == 0) {
  285. finished = YES;
  286. }
  287. } else {
  288. tmpTrimmedMessage = checkString;
  289. }
  290. }
  291. }
  292. return trimmedMessages;
  293. }
  294. + (void)sendErrorLocalNotification:(NSString *)title body:(NSString *)body userInfo:(NSDictionary *)userInfo {
  295. UNMutableNotificationContent *notification = [[UNMutableNotificationContent alloc] init];
  296. notification.title = title;
  297. notification.body = body;
  298. if (userInfo != nil) {
  299. notification.userInfo = userInfo;
  300. } else {
  301. notification.userInfo = @{@"threema": @{@"cmd": @"error"}};
  302. }
  303. if (![[UserSettings sharedUserSettings].pushGroupSound isEqualToString:@"none"]) {
  304. notification.sound = [UNNotificationSound soundNamed:[NSString stringWithFormat:@"%@.caf", [UserSettings sharedUserSettings].pushGroupSound]];
  305. }
  306. NSString *notificationIdentifier = @"ErrorMessage";
  307. UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:notificationIdentifier content:notification trigger:nil];
  308. UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
  309. [center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
  310. }];
  311. }
  312. @end