CCUtility.m 46 KB

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