PageRenderTime 679ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Funtions.m

http://maildelivery.googlecode.com/
Objective C | 325 lines | 253 code | 52 blank | 20 comment | 44 complexity | 794701a8f869d75e21040d46ff36dcf0 MD5 | raw file
  1. //
  2. // Funtions.m
  3. // MailDelivery
  4. //
  5. // Created by Dante Palacios on 26/08/09.
  6. // Copyright 2009 Dante Palacios. All rights reserved.
  7. //
  8. #import <WebKit/WebKit.h>
  9. #import <QTKit/QTKit.h>
  10. #import "Message.h"
  11. #import "Keychain.h"
  12. #import "KeychainItem.h"
  13. #import "NSAttributedStringAdditions.h"
  14. #import "NSDictionaryAdditions.h"
  15. #import "NSDataAdditions.h"
  16. #import "NSStringAdditions.h"
  17. #import "Funtions.h"
  18. #import "Macros.h"
  19. NSString *KeychainGetPasswordForAccount(NSDictionary *account)
  20. {
  21. return [[[Keychain sharedKeychain] keychainItemForAccount:account] password];
  22. }
  23. BOOL KeychainSetPasswordForAccount(NSString *password, NSDictionary *account)
  24. {
  25. KeychainItem *item = [[Keychain sharedKeychain] addKeychainItemForAccount:account];
  26. if (item)
  27. {
  28. [item setPassword:password];
  29. return YES;
  30. }
  31. return NO;
  32. }
  33. BOOL IsImageFile(NSString *path)
  34. {
  35. NSArray *types = [NSImage imageFileTypes];
  36. for (NSString *type in types)
  37. {
  38. if ([type isCaseInsensitiveEqualToString:[path pathExtension]]) return YES;
  39. }
  40. return NO;
  41. }
  42. BOOL IsMovieFile(NSString *path) {
  43. NSWorkspace *sharedWorkspace = [NSWorkspace sharedWorkspace];
  44. NSString *type = [sharedWorkspace typeOfFile:path error:nil];
  45. if (type)
  46. {
  47. if ([sharedWorkspace type:type conformsToType:@"public.movie"]) return YES;
  48. }
  49. if (IsAudioFile(path)) return NO;
  50. NSArray *types = [QTMovie movieFileTypes:QTIncludeCommonTypes];
  51. for (type in types)
  52. {
  53. if ([type isCaseInsensitiveEqualToString:[path pathExtension]]) return YES;
  54. }
  55. return NO;
  56. }
  57. BOOL IsAudioFile(NSString *path)
  58. {
  59. NSWorkspace *sharedWorkspace = [NSWorkspace sharedWorkspace];
  60. NSString *type = [sharedWorkspace typeOfFile:path error:nil];
  61. if (type)
  62. {
  63. return [sharedWorkspace type:type conformsToType:@"public.audio"];
  64. }
  65. return NO;
  66. }
  67. BOOL IsValidEmail(NSString *emailAddress)
  68. {
  69. if (!emailAddress.length) return NO;
  70. NSString *emailRegEx =
  71. @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
  72. @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
  73. @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
  74. @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
  75. @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
  76. @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
  77. @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
  78. return [[NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegEx] evaluateWithObject:emailAddress];
  79. }
  80. BOOL IsMobileMeHost(NSString *hostName)
  81. {
  82. return !hostName.length ? NO : ([hostName isCaseInsensitiveEqualToString:@"smtp.mac.com"] || [hostName isCaseInsensitiveEqualToString:@"smtp.me.com"]);
  83. }
  84. CFNetDiagnosticStatus MailDeliveryValidateConnectionWithURL(NSURL *url, NSString **diagnosticDescription)
  85. {
  86. CFStringRef description = nil;
  87. CFNetDiagnosticRef diagnostic = CFNetDiagnosticCreateWithURL(NULL, (CFURLRef)url);
  88. CFNetDiagnosticStatus status = CFNetDiagnosticCopyNetworkStatusPassively(diagnostic, &description);
  89. CFRelease(diagnostic);
  90. if (diagnosticDescription)
  91. {
  92. *diagnosticDescription = (NSString *)description;
  93. }
  94. if (description)
  95. {
  96. CFRelease(description);
  97. }
  98. return status;
  99. }
  100. CFNetDiagnosticStatus MailDeliveryValidateInternetConnection(NSString **diagnosticDescription) {
  101. return MailDeliveryValidateConnectionWithURL([NSURL URLWithString:@"https://code.google.com/p/maildelivery/"], diagnosticDescription);
  102. }
  103. NSString *HumanReadableFileSizeUsingFormat(NSNumber *fileSize, NSString *format) {
  104. unsigned long long sizeInBytes = [fileSize unsignedLongLongValue];
  105. CGFloat finalValue = 0;
  106. NSString *suffix = @"";
  107. if (!format.length)
  108. {
  109. format = @"#,###.##;0.00;(#,##0.00)";
  110. }
  111. if (sizeInBytes < 1024)
  112. {
  113. suffix = MDLocalizedString(@"bytes", @"");
  114. finalValue = (CGFloat)sizeInBytes;
  115. }
  116. else if (sizeInBytes < 1024 * 1024)
  117. {
  118. suffix = MDLocalizedString(@"KB", @"");
  119. finalValue = ((CGFloat)sizeInBytes/1024.0);
  120. }
  121. else if (sizeInBytes < 1024 * 1024 * 1024)
  122. {
  123. suffix = MDLocalizedString(@"MB", @"");
  124. finalValue = ((CGFloat)sizeInBytes/1024.0/1024.0);
  125. }
  126. else
  127. {
  128. suffix = MDLocalizedString(@"GB", @"");
  129. finalValue = ((CGFloat)sizeInBytes/1024.0/1024.0/1024.0);
  130. }
  131. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  132. [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
  133. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  134. [formatter setDecimalSeparator:@","];
  135. [formatter setFormat:format];
  136. NSString *humanReadableSize = [formatter stringFromNumber:[NSNumber numberWithDouble:finalValue]];
  137. [formatter release];
  138. return [NSString stringWithFormat:@"%@ %@", humanReadableSize, suffix];
  139. }
  140. OSStatus GetCertificateRefForEmail(NSString *email, SecKeychainItemRef *itemRef)
  141. {
  142. NSCParameterAssert(email);
  143. SecKeychainAttributeList attrList;
  144. SecKeychainAttribute attrib;
  145. attrList.count = 1;
  146. attrList.attr = &attrib;
  147. attrib.tag = kSecAlias;
  148. attrib.data = (void *) [email UTF8String];
  149. attrib.length = (UInt32)strlen(attrib.data);
  150. SecKeychainSearchRef searchRef = nil;
  151. OSStatus status = SecKeychainSearchCreateFromAttributes(NULL, kSecCertificateItemClass, &attrList, &searchRef);
  152. if (status != noErr)
  153. {
  154. NSLog(@"GetCertificateRefForEmail err* %s", GetMacOSStatusErrorString(status));
  155. return status;
  156. }
  157. status = SecKeychainSearchCopyNext(searchRef, itemRef);
  158. if (searchRef) CFRelease(searchRef);
  159. return status;
  160. }
  161. NSString *MIMETypeOfFile(NSString *filename)
  162. {
  163. NSString *extension = filename.pathExtension;
  164. if (!extension.length) return nil;
  165. CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)extension, NULL);
  166. if (!UTI) return nil;
  167. NSString *mimeType = nil;
  168. CFStringRef registeredType = UTTypeCopyPreferredTagWithClass(UTI, kUTTagClassMIMEType);
  169. if (!registeredType)
  170. {
  171. if ([extension isEqualToString:@"m4v"])
  172. mimeType = @"video/x-m4v";
  173. else if([extension isEqualToString:@"m4p"])
  174. mimeType = @"audio/x-m4p";
  175. else if ([extension isEqualToString:@"p7m"])
  176. mimeType = @"application/pkcs7-mime";
  177. else
  178. mimeType = @"application/octet-stream";
  179. }
  180. else
  181. {
  182. mimeType = NSMakeCollectable(registeredType);
  183. }
  184. CFRelease(UTI);
  185. return mimeType;
  186. }
  187. void MailDeliveryLog(NSString *format, ...)
  188. {
  189. }
  190. BOOL MailContentsOfURL(NSURL *URL, NSString **errorDescription)
  191. {
  192. NSCParameterAssert(URL);
  193. /*CFURLRef mailerURLRef;
  194. NSURL * mailtoURL = [NSURL URLWithString:@"mailto:xxx"];
  195. OSStatus err = LSGetApplicationForURL((CFURLRef)mailtoURL, kLSRolesAll, NULL, &mailerURLRef);
  196. if (err != noErr)
  197. {
  198. if (errorDescription) *errorDescription = [NSString stringWithFormat:@"%s", GetMacOSStatusErrorString(err)];
  199. return NO;
  200. }
  201. NSString *mailerPath = [(NSURL*)mailerURLRef path];
  202. CFRelease(mailerURLRef);
  203. NSBundle *bundle = [NSBundle bundleWithPath:mailerPath];*/
  204. NSBundle *bundle = [NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.apple.mail"]];
  205. if (!bundle)
  206. {
  207. if (errorDescription) *errorDescription = MDLocalizedString(@"Bundle for mailer not found", @"error description");
  208. return NO;
  209. }
  210. NSDictionary *infoPlist = [bundle infoDictionary];
  211. NSNumber *mailPageSupported = [infoPlist objectForKey:@"MailPageSupported"];
  212. if (!mailPageSupported || ![mailPageSupported boolValue])
  213. {
  214. if (errorDescription) *errorDescription = [NSString stringWithFormat:MDLocalizedString(@"\"%@\" does not support sending Web pages", @"error description format"), [bundle objectForInfoDictionaryKey:(NSString *) kCFBundleNameKey]];
  215. return NO;
  216. }
  217. NSString *bundleId = [bundle bundleIdentifier];
  218. const char *bundleIdChar = [bundleId UTF8String];
  219. if (!bundleIdChar)
  220. {
  221. if (errorDescription) *errorDescription = @"";
  222. return NO;
  223. }
  224. if (![[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:bundleId options:NSWorkspaceLaunchAsync additionalEventParamDescriptor:nil launchIdentifier:NULL])
  225. {
  226. if (errorDescription) *errorDescription = [NSString stringWithFormat:MDLocalizedString(@"Failed to launch application \"%@\"", @"error description format"), bundleId];
  227. return NO;
  228. }
  229. WebView *webView = [[WebView alloc] initWithFrame:NSZeroRect];
  230. [[webView mainFrame] loadRequest:[NSURLRequest requestWithURL:URL]];
  231. while ([webView isLoading])
  232. {
  233. CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true);
  234. }
  235. WebArchive *webArchive = [[[webView mainFrame] dataSource] webArchive];
  236. NSString *subject = [[[webView mainFrame] dataSource] pageTitle];
  237. [webView release];
  238. if (!webArchive)
  239. {
  240. if (errorDescription) *errorDescription = @"";
  241. return NO;
  242. }
  243. NSAppleEventDescriptor *dataDesc = [NSAppleEventDescriptor descriptorWithDescriptorType:'tdta' data:webArchive.data];
  244. NSAppleEventDescriptor *subjectDesc = [NSAppleEventDescriptor descriptorWithString:subject];
  245. NSAppleEventDescriptor *targetDesc = [NSAppleEventDescriptor descriptorWithDescriptorType:typeApplicationBundleID bytes:bundleIdChar length:strlen(bundleIdChar)];
  246. NSAppleEventDescriptor *appleEvent = [NSAppleEventDescriptor appleEventWithEventClass:'mail' eventID:'mlpg' targetDescriptor:targetDesc returnID:kAutoGenerateReturnID transactionID:kAnyTransactionID];
  247. [appleEvent setParamDescriptor:dataDesc forKeyword:keyDirectObject];
  248. [appleEvent setParamDescriptor:subjectDesc forKeyword:'urln'];
  249. OSStatus err = AESendMessage([appleEvent aeDesc], NULL, kAECanInteract, kAEDefaultTimeout);
  250. if (err != noErr)
  251. {
  252. if (errorDescription) *errorDescription = [NSString stringWithFormat:@"%s", GetMacOSStatusErrorString(err)];
  253. return NO;
  254. }
  255. return YES;
  256. }
  257. BOOL MailLinkToURL(NSURL *URL, NSString **errorDescription)
  258. {
  259. NSCParameterAssert(URL);
  260. NSString *title = @"Page title";
  261. NSString *subject = [NSString stringWithFormat:@"SUBJECT=%@", [title stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
  262. NSString *body = [NSString stringWithFormat:@"BODY=%@", [[NSString stringWithFormat:@"\n\n<%@>", [URL absoluteString]] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
  263. return [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@?%@&%@", @"", subject, body]]];
  264. }