CCUtility.m 50 KB

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