CCUtility.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217
  1. //
  2. // CCUtility.m
  3. // Crypto Cloud Technology Nextcloud
  4. //
  5. // Created by Marino Faggiana on 02/02/16.
  6. // Copyright (c) 2014 TWS. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  9. //
  10. // This program is free software: you can redistribute it and/or modify
  11. // it under the terms of the GNU General Public License as published by
  12. // the Free Software Foundation, either version 3 of the License, or
  13. // (at your option) any later version.
  14. //
  15. // This program is distributed in the hope that it will be useful,
  16. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. // GNU General Public License for more details.
  19. //
  20. // You should have received a copy of the GNU General Public License
  21. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. //
  23. #import "CCUtility.h"
  24. #import "CCGraphics.h"
  25. #import <netinet/in.h>
  26. #import <openssl/x509.h>
  27. #import <openssl/bio.h>
  28. #import <openssl/err.h>
  29. #import <openssl/pem.h>
  30. @implementation CCUtility
  31. #pragma --------------------------------------------------------------------------------------------
  32. #pragma mark ======================= KeyChainStore ==================================
  33. #pragma --------------------------------------------------------------------------------------------
  34. + (void)deleteAllChainStore
  35. {
  36. [UICKeyChainStore removeAllItems];
  37. [UICKeyChainStore removeAllItemsForService:serviceShareKeyChain];
  38. }
  39. + (void)storeAllChainInService
  40. {
  41. UICKeyChainStore *store = [UICKeyChainStore keyChainStore];
  42. NSArray *items = store.allItems;
  43. for (NSDictionary *item in items) {
  44. [UICKeyChainStore setString:[item objectForKey:@"value"] forKey:[item objectForKey:@"key"] service:serviceShareKeyChain];
  45. [UICKeyChainStore removeItemForKey:[item objectForKey:@"key"]];
  46. }
  47. }
  48. #pragma ------------------------------ ADMIN
  49. + (void)adminRemoveIntro
  50. {
  51. NSString *version = [self getVersionCryptoCloud];
  52. [UICKeyChainStore setString:nil forKey:version service:serviceShareKeyChain];
  53. }
  54. + (void)adminRemovePasscode
  55. {
  56. NSString *uuid = [self getUUID];
  57. [UICKeyChainStore setString:nil forKey:uuid service:serviceShareKeyChain];
  58. }
  59. + (void)adminRemoveVersion
  60. {
  61. [UICKeyChainStore setString:@"0.0" forKey:@"version" service:serviceShareKeyChain];
  62. }
  63. #pragma ------------------------------ SET
  64. + (void)setKeyChainPasscodeForUUID:(NSString *)uuid conPasscode:(NSString *)passcode
  65. {
  66. [UICKeyChainStore setString:passcode forKey:uuid service:serviceShareKeyChain];
  67. }
  68. + (NSString *)setVersionCryptoCloud
  69. {
  70. NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  71. [UICKeyChainStore setString:version forKey:@"version" service:serviceShareKeyChain];
  72. return version;
  73. }
  74. + (void)setBlockCode:(NSString *)blockcode
  75. {
  76. [UICKeyChainStore setString:blockcode forKey:@"blockcode" service:serviceShareKeyChain];
  77. }
  78. + (void)setSimplyBlockCode:(BOOL)simply
  79. {
  80. NSString *sSimply = (simply) ? @"true" : @"false";
  81. [UICKeyChainStore setString:sSimply forKey:@"simplyblockcode" service:serviceShareKeyChain];
  82. }
  83. + (void)setOnlyLockDir:(BOOL)lockDir
  84. {
  85. NSString *sLockDir = (lockDir) ? @"true" : @"false";
  86. [UICKeyChainStore setString:sLockDir forKey:@"onlylockdir" service:serviceShareKeyChain];
  87. }
  88. + (void)setOptimizedPhoto:(BOOL)resize
  89. {
  90. NSString *sOptimizedPhoto = (resize) ? @"true" : @"false";
  91. [UICKeyChainStore setString:sOptimizedPhoto forKey:@"optimizedphoto" service:serviceShareKeyChain];
  92. }
  93. + (void)setUploadAndRemovePhoto:(BOOL)remove
  94. {
  95. NSString *sRemovePhoto = (remove) ? @"true" : @"false";
  96. [UICKeyChainStore setString:sRemovePhoto forKey:@"uploadremovephoto" service:serviceShareKeyChain];
  97. }
  98. + (void)setSynchronizationsOnlyWiFi:(BOOL)onlyWiFi
  99. {
  100. NSString *sSynchronizationsOnlyWiFi = (onlyWiFi) ? @"true" : @"false";
  101. [UICKeyChainStore setString:sSynchronizationsOnlyWiFi forKey:@"synchronizationsonlywifi" service:serviceShareKeyChain];
  102. }
  103. + (void)setOrderSettings:(NSString *)order
  104. {
  105. [UICKeyChainStore setString:order forKey:@"order" service:serviceShareKeyChain];
  106. }
  107. + (void)setAscendingSettings:(BOOL)ascendente
  108. {
  109. NSString *sAscendente = (ascendente) ? @"true" : @"false";
  110. [UICKeyChainStore setString:sAscendente forKey:@"ascending" service:serviceShareKeyChain];
  111. }
  112. + (void)setGroupBySettings:(NSString *)groupby
  113. {
  114. [UICKeyChainStore setString:groupby forKey:@"groupby" service:serviceShareKeyChain];
  115. }
  116. + (void)setIntro:(NSString *)version
  117. {
  118. [UICKeyChainStore setString:@"true" forKey:version service:serviceShareKeyChain];
  119. }
  120. + (void)setMessageJailbroken:(BOOL)message
  121. {
  122. NSString *sMessage = (message) ? @"true" : @"false";
  123. [UICKeyChainStore setString:sMessage forKey:@"jailbroken" service:serviceShareKeyChain];
  124. }
  125. + (void)setActiveAccountShareExt:(NSString *)activeAccount
  126. {
  127. [UICKeyChainStore setString:activeAccount forKey:@"activeAccountShareExt" service:serviceShareKeyChain];
  128. }
  129. + (void)setCryptatedShareExt:(BOOL)cryptated
  130. {
  131. NSString *sCryptated = (cryptated) ? @"true" : @"false";
  132. [UICKeyChainStore setString:sCryptated forKey:@"cryptatedShareExt" service:serviceShareKeyChain];
  133. }
  134. + (void)setServerUrlShareExt:(NSString *)serverUrl
  135. {
  136. [UICKeyChainStore setString:serverUrl forKey:@"serverUrlShareExt" service:serviceShareKeyChain];
  137. }
  138. + (void)setTitleServerUrlShareExt:(NSString *)titleServerUrl
  139. {
  140. [UICKeyChainStore setString:titleServerUrl forKey:@"titleServerUrlShareExt" service:serviceShareKeyChain];
  141. }
  142. + (void)setEmail:(NSString *)email
  143. {
  144. [UICKeyChainStore setString:email forKey:@"email" service:serviceShareKeyChain];
  145. }
  146. + (void)setHint:(NSString *)hint
  147. {
  148. [UICKeyChainStore setString:hint forKey:@"hint" service:serviceShareKeyChain];
  149. }
  150. + (void)setDirectoryOnTop:(BOOL)directoryOnTop
  151. {
  152. NSString *sDirectoryOnTop = (directoryOnTop) ? @"true" : @"false";
  153. [UICKeyChainStore setString:sDirectoryOnTop forKey:@"directoryOnTop" service:serviceShareKeyChain];
  154. }
  155. + (void)setFileNameMask:(NSString *)fileNameMask
  156. {
  157. [UICKeyChainStore setString:fileNameMask forKey:@"fileNameMask" service:serviceShareKeyChain];
  158. }
  159. + (void)setCreateMenuEncrypted:(BOOL)encrypted
  160. {
  161. NSString *sEncrypted = (encrypted) ? @"true" : @"false";
  162. [UICKeyChainStore setString:sEncrypted forKey:@"createMenuEncrypted" service:serviceShareKeyChain];
  163. }
  164. #pragma ------------------------------ GET
  165. + (NSString *)getKeyChainPasscodeForUUID:(NSString *)uuid
  166. {
  167. if (!uuid) return nil;
  168. NSString *passcode = [UICKeyChainStore stringForKey:uuid service:serviceShareKeyChain];
  169. return passcode;
  170. }
  171. + (NSString *)getUUID
  172. {
  173. #if TARGET_IPHONE_SIMULATOR
  174. NSUUID *deviceId = [[NSUUID alloc]initWithUUIDString:UUID_SIM];
  175. return [deviceId UUIDString];
  176. #else
  177. NSString *uuid = [[UIDevice currentDevice] identifierForVendor].UUIDString;
  178. return uuid;
  179. #endif
  180. }
  181. + (NSString *)getNameCurrentDevice
  182. {
  183. return [[UIDevice currentDevice] name];
  184. }
  185. + (NSString *)getVersionCryptoCloud
  186. {
  187. return [UICKeyChainStore stringForKey:@"version" service:serviceShareKeyChain];
  188. }
  189. + (NSString *)getBlockCode
  190. {
  191. return [UICKeyChainStore stringForKey:@"blockcode" service:serviceShareKeyChain];
  192. }
  193. + (BOOL)getSimplyBlockCode
  194. {
  195. NSString *simplyBlockCode = [UICKeyChainStore stringForKey:@"simplyblockcode" service:serviceShareKeyChain];
  196. if (simplyBlockCode == nil) {
  197. [self setSimplyBlockCode:YES];
  198. return YES;
  199. }
  200. return [simplyBlockCode boolValue];
  201. }
  202. + (BOOL)getOnlyLockDir
  203. {
  204. return [[UICKeyChainStore stringForKey:@"onlylockdir" service:serviceShareKeyChain] boolValue];
  205. }
  206. + (BOOL)getOptimizedPhoto
  207. {
  208. return [[UICKeyChainStore stringForKey:@"optimizedphoto" service:serviceShareKeyChain] boolValue];
  209. }
  210. + (BOOL)getUploadAndRemovePhoto
  211. {
  212. return [[UICKeyChainStore stringForKey:@"uploadremovephoto" service:serviceShareKeyChain] boolValue];
  213. }
  214. + (BOOL)getSynchronizationsOnlyWiFi
  215. {
  216. return [[UICKeyChainStore stringForKey:@"synchronizationsonlywifi" service:serviceShareKeyChain] boolValue];
  217. }
  218. + (NSString *)getOrderSettings
  219. {
  220. NSString *order = [UICKeyChainStore stringForKey:@"order" service:serviceShareKeyChain];
  221. if (order == nil) {
  222. [self setOrderSettings:@"fileName"];
  223. return @"fileName";
  224. }
  225. return order;
  226. }
  227. + (BOOL)getAscendingSettings
  228. {
  229. NSString *ascending = [UICKeyChainStore stringForKey:@"ascending" service:serviceShareKeyChain];
  230. if (ascending == nil) {
  231. [self setAscendingSettings:YES];
  232. return YES;
  233. }
  234. return [ascending boolValue];
  235. }
  236. + (NSString *)getGroupBySettings
  237. {
  238. NSString *groupby = [UICKeyChainStore stringForKey:@"groupby" service:serviceShareKeyChain];
  239. if (groupby == nil) {
  240. [self setGroupBySettings:@"none"];
  241. return @"none";
  242. }
  243. return groupby;
  244. }
  245. + (BOOL)getIntro:(NSString *)version
  246. {
  247. return [[UICKeyChainStore stringForKey:version service:serviceShareKeyChain] boolValue];
  248. }
  249. + (NSString *)getIncrementalNumber
  250. {
  251. long number = [[UICKeyChainStore stringForKey:@"incrementalnumber" service:serviceShareKeyChain] intValue];
  252. number++;
  253. if (number >= 9999) number = 1;
  254. [UICKeyChainStore setString:[NSString stringWithFormat:@"%ld", number] forKey:@"incrementalnumber"];
  255. return [NSString stringWithFormat:@"%04ld", number];
  256. }
  257. + (BOOL)getMessageJailbroken
  258. {
  259. return [[UICKeyChainStore stringForKey:@"jailbroken" service:serviceShareKeyChain] boolValue];
  260. }
  261. + (NSString *)getActiveAccountShareExt
  262. {
  263. return [UICKeyChainStore stringForKey:@"activeAccountShareExt" service:serviceShareKeyChain];
  264. }
  265. + (BOOL)getCryptatedShareExt
  266. {
  267. return [[UICKeyChainStore stringForKey:@"cryptatedShareExt" service:serviceShareKeyChain] boolValue];
  268. }
  269. + (NSString *)getServerUrlShareExt
  270. {
  271. return [UICKeyChainStore stringForKey:@"serverUrlShareExt" service:serviceShareKeyChain];
  272. }
  273. + (NSString *)getTitleServerUrlShareExt
  274. {
  275. return [UICKeyChainStore stringForKey:@"titleServerUrlShareExt" service:serviceShareKeyChain];
  276. }
  277. + (NSString *)getEmail
  278. {
  279. return [UICKeyChainStore stringForKey:@"email" service:serviceShareKeyChain];
  280. }
  281. + (NSString *)getHint
  282. {
  283. return [UICKeyChainStore stringForKey:@"hint" service:serviceShareKeyChain];
  284. }
  285. + (BOOL)getDirectoryOnTop
  286. {
  287. return [[UICKeyChainStore stringForKey:@"directoryOnTop" service:serviceShareKeyChain] boolValue];
  288. }
  289. + (NSString *)getFileNameMask
  290. {
  291. NSString *mask = [UICKeyChainStore stringForKey:@"fileNameMask" service:serviceShareKeyChain];
  292. if (mask == nil)
  293. mask = @"";
  294. return mask;
  295. }
  296. + (BOOL)getCreateMenuEncrypted
  297. {
  298. return [[UICKeyChainStore stringForKey:@"createMenuEncrypted" service:serviceShareKeyChain] boolValue];
  299. }
  300. #pragma --------------------------------------------------------------------------------------------
  301. #pragma mark ===== Varius =====
  302. #pragma --------------------------------------------------------------------------------------------
  303. + (NSString *)getUserAgent:(NSString *)typeCloud
  304. {
  305. NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  306. if ([typeCloud isEqualToString:typeCloudOwnCloud])
  307. return [NSString stringWithFormat:@"%@%@",@"Mozilla/5.0 (iOS) CryptoCloud-iOS/",appVersion];
  308. if ([typeCloud isEqualToString:typeCloudNextcloud])
  309. return [NSString stringWithFormat:@"%@%@",@"Mozilla/5.0 (iOS) Nextcloud-iOS/",appVersion];
  310. return [NSString stringWithFormat:@"%@%@",@"Mozilla/5.0 (iOS) Nextcloud-iOS/",appVersion];
  311. }
  312. + (NSString *)dateDiff:(NSDate *) convertedDate
  313. {
  314. NSDateFormatter *df = [[NSDateFormatter alloc] init];
  315. [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  316. [df setDateFormat:@"EEE, dd MMM yy HH:mm:ss VVVV"];
  317. //NSDate *convertedDate = [df dateFromString:origDate];
  318. //NSDate *convertedDate = [NSDate dateWithTimeIntervalSince1970:origDate];
  319. NSDate *todayDate = [NSDate date];
  320. double ti = [convertedDate timeIntervalSinceDate:todayDate];
  321. ti = ti * -1;
  322. if(ti < 1) {
  323. return NSLocalizedString(@"_never_", nil);
  324. } else if (ti < 60) {
  325. return NSLocalizedString(@"_less_a_minute_", nil);
  326. } else if (ti < 3600) {
  327. int diff = round(ti / 60);
  328. return [NSString stringWithFormat:NSLocalizedString(@"_minutes_ago_", nil), diff];
  329. } else if (ti < 86400) {
  330. int diff = round(ti / 60 / 60);
  331. return[NSString stringWithFormat:NSLocalizedString(@"_hours_ago_", nil), diff];
  332. } else if (ti < 2629743) {
  333. int diff = round(ti / 60 / 60 / 24);
  334. return[NSString stringWithFormat:NSLocalizedString(@"_days_ago_", nil), diff];
  335. } else {
  336. return NSLocalizedString(@"_over_30_days_", nil);
  337. }
  338. }
  339. + (NSString *)transformedSize:(double)value
  340. {
  341. int multiplyFactor = 0;
  342. NSArray *tokens = [NSArray arrayWithObjects:@"bytes",@"KB",@"MB",@"GB",@"TB",nil];
  343. while (value > 1024) {
  344. value /= 1024;
  345. multiplyFactor++;
  346. }
  347. return [NSString stringWithFormat:@"%4.2f %@",value, [tokens objectAtIndex:multiplyFactor]];
  348. }
  349. // Remove do not forbidden characters
  350. + (NSString *)removeForbiddenCharacters:(NSString *)fileName
  351. {
  352. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"\\",@"<",@">",@":",@"\"",@"|",@"?",@"*",@"/", nil];
  353. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  354. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  355. }
  356. return fileName;
  357. }
  358. + (NSString*)stringAppendServerUrl:(NSString *)serverUrl addServerUrl:(NSString *)addServerUrl
  359. {
  360. NSString *result;
  361. if (serverUrl == nil || addServerUrl == nil) return nil;
  362. if ([serverUrl isEqualToString:@"/"]) result = [serverUrl stringByAppendingString:addServerUrl];
  363. else result = [NSString stringWithFormat:@"%@/%@", serverUrl, addServerUrl];
  364. return result;
  365. }
  366. + (NSString *)createID
  367. {
  368. int numeroCaratteri = 16;
  369. NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  370. NSMutableString *randomString = [NSMutableString stringWithCapacity: numeroCaratteri];
  371. for (int i=0; i < numeroCaratteri; i++) {
  372. [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((unsigned int)[letters length]) % [letters length]]];
  373. }
  374. return [NSString stringWithFormat:@"%@", randomString];
  375. }
  376. + (NSString *)createFileNameFromAsset:(PHAsset *)asset
  377. {
  378. NSDate *assetDate = asset.creationDate;
  379. NSString *assetFileName = [asset valueForKey:@"filename"];
  380. NSString *numberFileName;
  381. if ([assetFileName length] > 8) numberFileName = [assetFileName substringWithRange:NSMakeRange(04, 04)];
  382. else numberFileName = [CCUtility getIncrementalNumber];
  383. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  384. [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
  385. NSString *filenameDate = [formatter stringFromDate:assetDate];
  386. NSString *filenameExt = [[assetFileName pathExtension] lowercaseString];
  387. NSString *fileNameUpload = [NSString stringWithFormat:@"%@ %@.%@", filenameDate, numberFileName, filenameExt];
  388. return fileNameUpload;
  389. }
  390. + (NSString *)getHomeServerUrlActiveUrl:(NSString *)activeUrl typeCloud:(NSString *)typeCloud
  391. {
  392. if (activeUrl == nil || typeCloud == nil) return nil;
  393. NSString *home;
  394. if ([typeCloud isEqualToString:typeCloudOwnCloud] || [typeCloud isEqualToString:typeCloudNextcloud])
  395. home = [activeUrl stringByAppendingString:webDAV];
  396. return home;
  397. }
  398. // Return path of User Crypto Cloud / <user dir>
  399. + (NSString *)getDirectoryActiveUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  400. {
  401. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  402. NSString *user = activeUser;
  403. NSString *baseUrl = [activeUrl lowercaseString];
  404. NSString *dirUserBaseUrl = nil;
  405. NSString *dirApplicationUserGroup = nil;
  406. if ([user length] && [baseUrl length]) {
  407. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  408. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  409. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", user, baseUrl];
  410. dirUserBaseUrl = [[self removeForbiddenCharacters:dirUserBaseUrl] lowercaseString];
  411. } else return @"";
  412. dirApplicationUserGroup = [[dirGroup URLByAppendingPathComponent:appApplicationSupport] path];
  413. dirUserBaseUrl = [NSString stringWithFormat:@"%@/%@", dirApplicationUserGroup, dirUserBaseUrl];
  414. if (![[NSFileManager defaultManager] fileExistsAtPath: dirUserBaseUrl]) {
  415. [[NSFileManager defaultManager] createDirectoryAtPath:dirUserBaseUrl withIntermediateDirectories:YES attributes:nil error:nil];
  416. }
  417. return dirUserBaseUrl;
  418. }
  419. + (NSString *)getOLDDirectoryActiveUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  420. {
  421. NSString *user = activeUser;
  422. NSString *baseUrl = [activeUrl lowercaseString];
  423. NSString *dirUserBaseUrl = nil;
  424. if ([user length] && [baseUrl length]) {
  425. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  426. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  427. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", user, baseUrl];
  428. dirUserBaseUrl = [[self removeForbiddenCharacters:dirUserBaseUrl] lowercaseString];
  429. } else return @"";
  430. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  431. dirUserBaseUrl = [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], dirUserBaseUrl];
  432. return dirUserBaseUrl;
  433. }
  434. // Return the path of directory Local -> NSDocumentDirectory
  435. + (NSString *)getDirectoryLocal
  436. {
  437. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  438. return [paths objectAtIndex:0];
  439. }
  440. // Return the path of directory Crypto Cloud / Audio
  441. + (NSString *)getDirectoryAudio
  442. {
  443. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  444. return [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"audio"];
  445. }
  446. // Return the path of directory Cetificates
  447. + (NSString *)getDirectoryCerificates
  448. {
  449. NSURL *dirGroup = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:capabilitiesGroups];
  450. NSString *dir = [[dirGroup URLByAppendingPathComponent:appCertificates] path];
  451. if (![[NSFileManager defaultManager] fileExistsAtPath:dir])
  452. [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
  453. return dir;
  454. }
  455. + (NSString *)getTitleSectionDate:(NSDate *)date
  456. {
  457. NSString * title;
  458. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:[NSDate distantPast]]]) {
  459. title = NSLocalizedString(@"_no_date_", nil);
  460. } else {
  461. title = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:0];
  462. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:[NSDate date]]])
  463. title = [NSString stringWithFormat:NSLocalizedString(@"_today_", nil)];
  464. }
  465. return title;
  466. }
  467. + (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  468. {
  469. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  470. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  471. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  472. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  473. }
  474. }
  475. + (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  476. {
  477. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  478. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  479. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  480. }
  481. }
  482. + (void)removeAllFileID_UPLOAD_ActiveUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  483. {
  484. NSString *file;
  485. NSString *dir;
  486. dir = [self getDirectoryActiveUser:activeUser activeUrl:activeUrl];
  487. NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:dir];
  488. while (file = [enumerator nextObject]) {
  489. if ([file rangeOfString:@"ID_UPLOAD_"].location != NSNotFound)
  490. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", dir, file] error:nil];
  491. }
  492. }
  493. + (NSString *)deletingLastPathComponentFromServerUrl:(NSString *)serverUrl
  494. {
  495. NSURL *url = [[NSURL URLWithString:[serverUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] URLByDeletingLastPathComponent];
  496. NSString *pather = [[url absoluteString] stringByRemovingPercentEncoding];
  497. return [pather substringToIndex: [pather length] - 1];
  498. }
  499. + (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl typeCloud:(NSString *)typeCloud
  500. {
  501. NSString *fileName = [NSString stringWithFormat:@"%@/%@", [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:activeUrl typeCloud:typeCloud] withString:@""], metadataFileName];
  502. if ([fileName hasPrefix:@"/"]) fileName = [fileName substringFromIndex:1];
  503. return fileName;
  504. }
  505. + (void)sendMailEncryptPass:(NSString *)recipient validateEmail:(BOOL)validateEmail form:(id)form
  506. {
  507. BOOL error = NO;
  508. if (validateEmail)
  509. error = ![self isValidEmail:recipient];
  510. if (!error)
  511. error = ![MFMailComposeViewController canSendMail];
  512. if (!error) {
  513. NSString *key = [CCUtility getKeyChainPasscodeForUUID:[CCUtility getUUID]];
  514. MFMailComposeViewController *mc = [[MFMailComposeViewController alloc] init];
  515. mc.mailComposeDelegate = form;
  516. [mc setSubject:[self localizableBrand:@"_title_mail_encryptpass_" table:nil]];
  517. NSString *htmlMsg =[NSString stringWithFormat:@"<html><body><p>%@ : %@ , %@</p></body></html>", NSLocalizedString(@"_text1_mail_encryptpass_", nil), key, NSLocalizedString(@"_text2_mail_encryptpass_", nil)];
  518. NSData *jpegData = UIImageJPEGRepresentation([UIImage imageNamed:image_brandSfondoiPad], 1.0);
  519. [mc addAttachmentData:jpegData mimeType:@"image/jpeg" fileName:@"cryptocloud.png"];
  520. [mc setMessageBody:htmlMsg isHTML:YES];
  521. if ([self isValidEmail:recipient])
  522. [mc setToRecipients:@[recipient]];
  523. [form presentViewController:mc animated:YES completion:NULL];
  524. } else {
  525. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_mail_not_can_send_mail_", nil) preferredStyle:UIAlertControllerStyleAlert];
  526. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault
  527. handler:^(UIAlertAction * action) {
  528. [alert dismissViewControllerAnimated:YES completion:nil];
  529. }];
  530. [alert addAction:ok];
  531. [form presentViewController:alert animated:YES completion:nil];
  532. }
  533. }
  534. + (NSString *)localizableBrand:(NSString *)localize table:(NSString *)table
  535. {
  536. NSString *translate;
  537. if (table)
  538. translate = NSLocalizedStringFromTable(localize, table, nil);
  539. else
  540. translate = NSLocalizedString(localize, nil);
  541. translate = [translate stringByReplacingOccurrencesOfString:@"_brand_" withString:_brand_];
  542. translate = [translate stringByReplacingOccurrencesOfString:@"_mail_me_" withString:_mail_me_];
  543. return translate;
  544. }
  545. #pragma --------------------------------------------------------------------------------------------
  546. #pragma mark ===== CCMetadata =====
  547. #pragma --------------------------------------------------------------------------------------------
  548. + (CCMetadata *)trasformedOCFileToCCMetadata:(OCFileDto *)itemDto fileNamePrint:(NSString *)fileNamePrint serverUrl:(NSString *)serverUrl directoryID:(NSString *)directoryID cameraFolderName:(NSString *)cameraFolderName cameraFolderPath:(NSString *)cameraFolderPath activeAccount:(NSString *)activeAccount directoryUser:(NSString *)directoryUser typeCloud:(NSString *)typeCloud
  549. {
  550. CCMetadata *metadata = [[CCMetadata alloc] init];
  551. metadata.account = activeAccount;
  552. metadata.cryptated = NO;
  553. metadata.date = [NSDate dateWithTimeIntervalSince1970:itemDto.date];
  554. metadata.directory = itemDto.isDirectory;
  555. metadata.errorPasscode = false;
  556. metadata.fileID = itemDto.ocId;
  557. metadata.directoryID = directoryID;
  558. metadata.fileName = [CCUtility removeForbiddenCharacters:itemDto.fileName];
  559. metadata.fileNameData = [CCUtility trasformedFileNamePlistInCrypto:metadata.fileName];
  560. metadata.fileNamePrint = [CCUtility removeForbiddenCharacters:fileNamePrint];
  561. metadata.iconName = @"";
  562. metadata.model = @"";
  563. metadata.nameCurrentDevice = [CCUtility getNameCurrentDevice];
  564. metadata.permissions = itemDto.permissions;
  565. metadata.protocol = @"";
  566. metadata.rev = itemDto.etag;
  567. metadata.size = itemDto.size;
  568. metadata.title = @"";
  569. metadata.type = metadataType_file;
  570. metadata.typeFile = @"";
  571. metadata.typeCloud = typeCloud;
  572. metadata.uuid = [CCUtility getUUID];
  573. switch ([self getTypeFileName:metadata.fileName]) {
  574. case metadataTypeFilenamePlist:
  575. metadata.cryptated = YES;
  576. metadata.fileNamePrint = NSLocalizedString(@"_download_plist_", nil);
  577. [self insertInformationPlist:metadata directoryUser:directoryUser];
  578. break;
  579. case metadataTypeFilenameCrypto:
  580. metadata.cryptated = YES;
  581. metadata.fileNamePrint = @"";
  582. break;
  583. }
  584. [self insertTypeFileIconName:metadata directory:serverUrl cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath];
  585. return metadata;
  586. }
  587. + (void)insertTypeFileIconName:(CCMetadata *)metadata directory:(NSString *)directory cameraFolderName:(NSString *)cameraFolderName cameraFolderPath:(NSString *)cameraFolderPath
  588. {
  589. if ([metadata.type isEqualToString:metadataType_model]) {
  590. metadata.typeFile = metadataTypeFile_template;
  591. } else if (!metadata.directory) {
  592. CFStringRef fileExtension = (__bridge CFStringRef)[metadata.fileNamePrint pathExtension];
  593. CFStringRef fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  594. NSString *ext = (__bridge NSString *)fileExtension;
  595. ext = ext.uppercaseString;
  596. // thumbnailExists for typeCloudOwnCloud
  597. if ([metadata.typeCloud isEqualToString:typeCloudOwnCloud] || [metadata.typeCloud isEqualToString:typeCloudNextcloud]) {
  598. if([ext isEqualToString:@"JPG"] || [ext isEqualToString:@"PNG"] || [ext isEqualToString:@"JPEG"] || [ext isEqualToString:@"GIF"] || [ext isEqualToString:@"BMP"] || [ext isEqualToString:@"MP3"] || [ext isEqualToString:@"MOV"] || [ext isEqualToString:@"MP4"] || [ext isEqualToString:@"M4V"] || [ext isEqualToString:@"3GP"])
  599. metadata.thumbnailExists = YES;
  600. else
  601. metadata.thumbnailExists = NO;
  602. }
  603. // if wrong code, icon protect
  604. if (metadata.errorPasscode) {
  605. metadata.typeFile = metadataTypeFile_unknown;
  606. metadata.iconName = image_plist;
  607. return;
  608. }
  609. // Type compress
  610. if (UTTypeConformsTo(fileUTI, kUTTypeZipArchive) && [(__bridge NSString *)fileUTI containsString:@"org.openxmlformats"] == NO && [(__bridge NSString *)fileUTI containsString:@"oasis"] == NO) {
  611. metadata.typeFile = metadataTypeFile_compress;
  612. if (metadata.cryptated) metadata.iconName = image_typeFileCompress;
  613. else metadata.iconName = image_typeFileCompress;
  614. }
  615. // Type image
  616. else if (UTTypeConformsTo(fileUTI, kUTTypeImage)) {
  617. metadata.typeFile = metadataTypeFile_image;
  618. if (metadata.cryptated) metadata.iconName = image_photocrypto;
  619. else metadata.iconName = image_photo;
  620. }
  621. // Type Video
  622. else if (UTTypeConformsTo(fileUTI, kUTTypeMovie)) {
  623. metadata.typeFile = metadataTypeFile_video;
  624. if (metadata.cryptated) metadata.iconName = image_moviecrypto;
  625. else metadata.iconName = image_movie;
  626. }
  627. // Type Audio
  628. else if (UTTypeConformsTo(fileUTI, kUTTypeAudio)) {
  629. metadata.typeFile = metadataTypeFile_audio;
  630. if (metadata.cryptated) metadata.iconName = image_audiocrypto;
  631. else metadata.iconName = image_audio;
  632. }
  633. // Type Document [DOC] [PDF] [XLS] [TXT] (RTF = "public.rtf" - ODT = "org.oasis-open.opendocument.text") [MD]
  634. else if (UTTypeConformsTo(fileUTI, kUTTypeContent) || [ext isEqualToString:@"MD"]) {
  635. metadata.typeFile = metadataTypeFile_document;
  636. if (metadata.cryptated) metadata.iconName = image_documentcrypto;
  637. else metadata.iconName = image_document;
  638. NSString *typeFile = (__bridge NSString *)fileUTI;
  639. if ([typeFile isEqualToString:@"com.adobe.pdf"]) {
  640. if (metadata.cryptated) metadata.iconName = image_pdfcrypto;
  641. else metadata.iconName = image_pdf;
  642. }
  643. if ([typeFile isEqualToString:@"org.openxmlformats.spreadsheetml.sheet"]) {
  644. if (metadata.cryptated) metadata.iconName = image_xlscrypto;
  645. else metadata.iconName = image_xls;
  646. }
  647. if ([typeFile isEqualToString:@"com.microsoft.excel.xls"]) {
  648. if (metadata.cryptated) metadata.iconName = image_xlscrypto;
  649. else metadata.iconName = image_xls;
  650. }
  651. if ([typeFile isEqualToString:@"public.plain-text"] || [ext isEqualToString:@"MD"]) {
  652. if (metadata.cryptated) metadata.iconName = image_txtcrypto;
  653. else metadata.iconName = image_txt;
  654. }
  655. if ([typeFile isEqualToString:@"public.html"]) {
  656. if (metadata.cryptated) metadata.iconName = image_filetype_htlm_crypto;
  657. else metadata.iconName = image_filetype_htlm;
  658. }
  659. } else {
  660. // Type unknown
  661. metadata.typeFile = metadataTypeFile_unknown;
  662. // icon uTorrent
  663. if ([(__bridge NSString *)fileExtension isEqualToString:@"torrent"]) {
  664. if (metadata.cryptated) metadata.iconName = image_utorrentcrypto;
  665. else metadata.iconName = image_utorrent;
  666. } else {
  667. if (metadata.cryptated) metadata.iconName = image_plist;
  668. else metadata.iconName = image_file;
  669. }
  670. }
  671. } else {
  672. // icon directory
  673. metadata.typeFile = metadataTypeFile_directory;
  674. if (metadata.cryptated) metadata.iconName = image_foldercrypto;
  675. else metadata.iconName = image_folder;
  676. if([metadata.fileName isEqualToString:cameraFolderName] && [directory isEqualToString:cameraFolderPath])
  677. metadata.iconName = image_folderphotocamera;
  678. }
  679. }
  680. + (void)insertInformationPlist:(CCMetadata *)metadata directoryUser:(NSString *)directoryUser
  681. {
  682. NSString *fileNamePlist, *temp, *passcode;
  683. NSError *error;
  684. CCCrypto *crypto = [[CCCrypto alloc] init];
  685. // find the plist
  686. // 1) directory temp
  687. // 2) directory serverUrl
  688. temp = [NSTemporaryDirectory() stringByAppendingString:metadata.fileName];
  689. if ([[NSFileManager defaultManager] fileExistsAtPath:temp]) fileNamePlist = temp;
  690. else {
  691. temp = [NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileName];
  692. if ([[NSFileManager defaultManager] fileExistsAtPath:temp]) fileNamePlist = temp;
  693. }
  694. if (!fileNamePlist) return;
  695. NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:fileNamePlist];
  696. NSString *title = [data objectForKey:@"title"];
  697. NSString *len = [data objectForKey:@"len"];
  698. NSString *uuid = [data objectForKey:@"uuid"];
  699. // AutoInsert password if possible Versione 1.3
  700. [crypto autoInsertPasscodeUUID:uuid text:title];
  701. passcode = [crypto getKeyPasscode:uuid];
  702. metadata.cryptated = YES;
  703. metadata.directory = [[data objectForKey:@"dir"] boolValue];
  704. metadata.iconName = [data objectForKey:@"icon"];
  705. metadata.model = [data objectForKey:@"model"];
  706. metadata.nameCurrentDevice = [data objectForKey:@"namecurrentdevice"];
  707. metadata.protocol = [data objectForKey:@"protocol"];
  708. metadata.size = (long) [len longLongValue];
  709. if ([data objectForKey:@"image"] == nil)
  710. metadata.thumbnailExists = NO;
  711. else
  712. metadata.thumbnailExists = YES;
  713. metadata.title = title;
  714. metadata.type = [data objectForKey:@"type"];
  715. metadata.uuid = uuid;
  716. // Optimization V2.12
  717. if (![[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", directoryUser, metadata.fileID]] && !metadata.directory) {
  718. // exists image V1.8
  719. NSData *imageData = [data objectForKey:@"image"];
  720. if (imageData) {
  721. if (passcode) imageData = [RNDecryptor decryptData:imageData withSettings:kRNCryptorAES256Settings password:passcode error:&error];
  722. else imageData = nil;
  723. if (imageData && error == nil) {
  724. UIImage *image = [UIImage imageWithData:imageData];
  725. if (image) {
  726. if (image.size.width == 128 && image.size.height == 128)
  727. [CCGraphics saveIcoWithFileID:metadata.fileID image:image writeToFile:[NSString stringWithFormat:@"%@/%@.ico", directoryUser, metadata.fileID] copy:NO move:NO fromPath:nil toPath:nil];
  728. else
  729. [CCGraphics saveIcoWithFileID:metadata.fileID image:[CCGraphics scaleImage:image toSize:CGSizeMake(128, 128)] writeToFile:[NSString stringWithFormat:@"%@/%@.ico", directoryUser, metadata.fileID] copy:NO move:NO fromPath:nil toPath:nil];
  730. }
  731. }
  732. }
  733. }
  734. if (passcode) {
  735. metadata.fileNamePrint = [AESCrypt decrypt:title password:passcode];
  736. if ([metadata.fileNamePrint length]) {
  737. metadata.errorPasscode = false;
  738. } else {
  739. // succede che è stata inserito un Passcode nuovo per lo stesso UUID
  740. metadata.fileNamePrint = NSLocalizedString(@"_insert_password_", nil);
  741. metadata.errorPasscode = true;
  742. }
  743. } else {
  744. metadata.errorPasscode = true;
  745. if (!metadata.uuid) metadata.fileNamePrint = NSLocalizedString(@"_download_plist_", nil);
  746. else metadata.fileNamePrint = NSLocalizedString(@"_insert_password_", nil);
  747. }
  748. }
  749. + (CCMetadata *)insertFileSystemInMetadata:(NSString *)fileName directory:(NSString *)directory activeAccount:(NSString *)activeAccount cameraFolderName:(NSString *)cameraFolderName cameraFolderPath:(NSString *)cameraFolderPath
  750. {
  751. CCMetadata *metadata = [[CCMetadata alloc] init];
  752. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", directory, fileName];
  753. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  754. metadata.account = activeAccount;
  755. metadata.date = attributes[NSFileModificationDate];
  756. BOOL isDirectory;
  757. [[NSFileManager defaultManager] fileExistsAtPath:fileNamePath isDirectory:&isDirectory];
  758. metadata.directory = isDirectory;
  759. metadata.errorPasscode = false;
  760. metadata.fileID = fileName;
  761. metadata.directoryID = directory;
  762. metadata.fileName = fileName;
  763. metadata.fileNameData = fileName;
  764. metadata.fileNamePrint = fileName;
  765. metadata.nameCurrentDevice = [CCUtility getNameCurrentDevice];
  766. metadata.protocol = versionProtocolPlist;
  767. metadata.size = [attributes[NSFileSize] longValue];
  768. metadata.thumbnailExists = false;
  769. metadata.type = metadataType_local;
  770. metadata.title = @"";
  771. metadata.uuid = [CCUtility getUUID];
  772. if ([CCUtility isCryptoPlistString:fileName])
  773. [CCUtility insertInformationPlist:metadata directoryUser:directory];
  774. [self insertTypeFileIconName:metadata directory:directory cameraFolderName:cameraFolderName cameraFolderPath:cameraFolderPath];
  775. return metadata;
  776. }
  777. // Return file name plist -> crypto
  778. + (NSString *)trasformedFileNamePlistInCrypto:(NSString *)fileName
  779. {
  780. if([self isCryptoPlistString:fileName])
  781. return [fileName substringToIndex:[fileName length] - 6];
  782. return fileName;
  783. }
  784. // Return file name crypto -> plist
  785. + (NSString *)trasformedFileNameCryptoInPlist:(NSString *)fileName
  786. {
  787. if([self isCryptoString:fileName])
  788. return [fileName stringByAppendingString:@".plist"];
  789. return fileName;
  790. }
  791. // It's file crypto ? 64 + crypto = 70
  792. + (BOOL)isCryptoString:(NSString *)fileName
  793. {
  794. NSString *crypto;
  795. if ([fileName length] != 70) return false;
  796. crypto = [fileName substringWithRange:NSMakeRange(64, 6)];
  797. if ([crypto isEqualToString:@"crypto"]) return true;
  798. else return false;
  799. }
  800. // It's file crypto.plist ? 64 + crypto.plist = 76
  801. + (BOOL)isCryptoPlistString:(NSString *)fileName
  802. {
  803. NSString *cryptoPlist;
  804. if ([fileName length] != 76) return false;
  805. cryptoPlist = [fileName substringWithRange:NSMakeRange(64, 12)];
  806. if ([cryptoPlist isEqualToString:@"crypto.plist"]) return true;
  807. else return false;
  808. }
  809. // It's file plain
  810. + (BOOL)isFileNotCryptated:(NSString *)filename
  811. {
  812. if ([self isCryptoPlistString:filename] == NO && [self isCryptoString:filename] == NO) return true;
  813. else return false;
  814. }
  815. // It's file encrypted
  816. + (BOOL)isFileCryptated:(NSString *)filename
  817. {
  818. if ([self isCryptoPlistString:filename] == YES || [self isCryptoString:filename] == YES) return true;
  819. else return false;
  820. }
  821. + (NSInteger)getTypeFileName:(NSString *)fileName
  822. {
  823. NSUInteger len = [fileName length];
  824. switch (len) {
  825. case 70:
  826. if ([[fileName substringWithRange:NSMakeRange(64, 6)] isEqualToString:@"crypto"]) return metadataTypeFilenameCrypto;
  827. else return metadataTypeFilenamePlain;
  828. break;
  829. case 76:
  830. if ([[fileName substringWithRange:NSMakeRange(64, 12)] isEqualToString:@"crypto.plist"]) return metadataTypeFilenamePlist;
  831. else return metadataTypeFilenamePlain;
  832. break;
  833. default:
  834. return metadataTypeFilenamePlain;
  835. break;
  836. }
  837. return metadataTypeFilenamePlain;
  838. }
  839. #pragma --------------------------------------------------------------------------------------------
  840. #pragma mark ===== Third parts =====
  841. #pragma --------------------------------------------------------------------------------------------
  842. + (NSString *)stringValueForKey:(id)key conDictionary:(NSDictionary *)dictionary
  843. {
  844. id obj = [dictionary objectForKey:key];
  845. if ([obj isEqual:[NSNull null]]) return @"";
  846. if ([obj isKindOfClass:[NSString class]]) {
  847. return obj;
  848. }
  849. else if ([obj isKindOfClass:[NSNumber class]]) {
  850. return [obj stringValue];
  851. }
  852. else {
  853. return [obj description];
  854. }
  855. }
  856. + (NSString *)currentDevice
  857. {
  858. struct utsname systemInfo;
  859. uname(&systemInfo);
  860. NSString *deviceName=[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  861. //NSLog(@"[LOG] Device Name :%@",deviceName);
  862. return deviceName;
  863. }
  864. + (NSString *)getExtension:(NSString*)fileName
  865. {
  866. NSMutableArray *fileNameArray =[[NSMutableArray alloc] initWithArray: [fileName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]]];
  867. NSString *extension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  868. extension = [extension uppercaseString];
  869. //If the file has a ZIP extension obtain the previous one for check if it is a .pages.zip / .numbers.zip / .key.zip extension
  870. if ([extension isEqualToString:@"ZIP"]) {
  871. [fileNameArray removeLastObject];
  872. NSString *secondExtension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  873. secondExtension = [secondExtension uppercaseString];
  874. if ([secondExtension isEqualToString:@"PAGES"] || [secondExtension isEqualToString:@"NUMBERS"] || [secondExtension isEqualToString:@"KEY"]) {
  875. extension = [NSString stringWithFormat:@"%@.%@",secondExtension,extension];
  876. return extension;
  877. }
  878. }
  879. return extension;
  880. }
  881. /*
  882. * Util method to make a NSDate object from a string from xml
  883. * @dateString -> Data string from xml
  884. */
  885. + (NSDate*)parseDateString:(NSString*)dateString
  886. {
  887. //Parse the date in all the formats
  888. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  889. /*In most cases the best locale to choose is "en_US_POSIX", a locale that's specifically designed to yield US English results regardless of both user and system preferences. "en_US_POSIX" is also invariant in time (if the US, at some point in the future, changes the way it formats dates, "en_US" will change to reflect the new behaviour, but "en_US_POSIX" will not). It will behave consistently for all users.*/
  890. [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
  891. //This is the format for the concret locale used
  892. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  893. NSDate *theDate = nil;
  894. NSError *error = nil;
  895. if (![dateFormatter getObjectValue:&theDate forString:dateString range:nil error:&error]) {
  896. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  897. }
  898. return theDate;
  899. }
  900. + (ALAssetsLibrary *)defaultAssetsLibrary
  901. {
  902. static dispatch_once_t pred = 0;
  903. static ALAssetsLibrary *library = nil;
  904. dispatch_once(&pred, ^{
  905. library = [[ALAssetsLibrary alloc] init];
  906. });
  907. return library;
  908. }
  909. + (NSDate *)datetimeWithOutTime:(NSDate *)datDate
  910. {
  911. if (datDate == nil) return nil;
  912. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:datDate];
  913. datDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
  914. return datDate;
  915. }
  916. + (NSDate *)datetimeWithOutDate:(NSDate *)datDate
  917. {
  918. if (datDate == nil) return nil;
  919. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:datDate];
  920. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  921. }
  922. + (BOOL)isValidEmail:(NSString *)checkString
  923. {
  924. checkString = [checkString lowercaseString];
  925. BOOL stricterFilter = YES;
  926. NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  927. NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
  928. NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  929. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  930. return [emailTest evaluateWithObject:checkString];
  931. }
  932. @end