CCUtility.m 45 KB

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