CCUtility.m 46 KB

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