CCUtility.m 45 KB

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