CCUtility.m 43 KB

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