CCUtility.m 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720
  1. //
  2. // CCUtility.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 02/02/16.
  6. // Copyright (c) 2016 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <marino.faggiana@nextcloud.com>
  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 <OpenSSL/OpenSSL.h>
  27. #define INTRO_MessageType @"MessageType_"
  28. #define E2E_PublicKey @"EndToEndPublicKey_"
  29. #define E2E_PrivateKey @"EndToEndPrivateKey_"
  30. #define E2E_Passphrase @"EndToEndPassphrase_"
  31. #define E2E_PublicKeyServer @"EndToEndPublicKeyServer_"
  32. @implementation CCUtility
  33. #pragma --------------------------------------------------------------------------------------------
  34. #pragma mark ======================= KeyChainStore ==================================
  35. #pragma --------------------------------------------------------------------------------------------
  36. + (void)deleteAllChainStore
  37. {
  38. [UICKeyChainStore removeAllItems];
  39. [UICKeyChainStore removeAllItemsForService:k_serviceShareKeyChain];
  40. }
  41. + (void)storeAllChainInService
  42. {
  43. UICKeyChainStore *store = [UICKeyChainStore keyChainStore];
  44. NSArray *items = store.allItems;
  45. for (NSDictionary *item in items) {
  46. [UICKeyChainStore setString:[item objectForKey:@"value"] forKey:[item objectForKey:@"key"] service:k_serviceShareKeyChain];
  47. [UICKeyChainStore removeItemForKey:[item objectForKey:@"key"]];
  48. }
  49. }
  50. #pragma ------------------------------ GET/SET
  51. + (NSString *)getVersion
  52. {
  53. return [UICKeyChainStore stringForKey:@"version" service:k_serviceShareKeyChain];
  54. }
  55. + (NSString *)setVersion
  56. {
  57. NSString *version = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  58. [UICKeyChainStore setString:version forKey:@"version" service:k_serviceShareKeyChain];
  59. return version;
  60. }
  61. + (NSString *)getBuild
  62. {
  63. return [UICKeyChainStore stringForKey:@"build" service:k_serviceShareKeyChain];
  64. }
  65. + (NSString *)setBuild
  66. {
  67. NSString *build = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
  68. [UICKeyChainStore setString:build forKey:@"build" service:k_serviceShareKeyChain];
  69. return build;
  70. }
  71. + (NSString *)getPasscode
  72. {
  73. return [UICKeyChainStore stringForKey:@"passcodeBlock" service:k_serviceShareKeyChain];
  74. }
  75. + (void)setPasscode:(NSString *)passcode
  76. {
  77. [UICKeyChainStore setString:passcode forKey:@"passcodeBlock" service:k_serviceShareKeyChain];
  78. }
  79. + (BOOL)getNotPasscodeAtStart
  80. {
  81. return [[UICKeyChainStore stringForKey:@"notPasscodeAtStart" service:k_serviceShareKeyChain] boolValue];
  82. }
  83. + (void)setNotPasscodeAtStart:(BOOL)set
  84. {
  85. NSString *sSet = (set) ? @"true" : @"false";
  86. [UICKeyChainStore setString:sSet forKey:@"notPasscodeAtStart" service:k_serviceShareKeyChain];
  87. }
  88. + (NSString *)getOrderSettings
  89. {
  90. NSString *order = [UICKeyChainStore stringForKey:@"order" service:k_serviceShareKeyChain];
  91. if (order == nil) {
  92. [self setOrderSettings:@"fileName"];
  93. return @"fileName";
  94. }
  95. return order;
  96. }
  97. + (void)setOrderSettings:(NSString *)order
  98. {
  99. [UICKeyChainStore setString:order forKey:@"order" service:k_serviceShareKeyChain];
  100. }
  101. + (BOOL)getAscendingSettings
  102. {
  103. NSString *ascending = [UICKeyChainStore stringForKey:@"ascending" service:k_serviceShareKeyChain];
  104. if (ascending == nil) {
  105. [self setAscendingSettings:YES];
  106. return YES;
  107. }
  108. return [ascending boolValue];
  109. }
  110. + (void)setAscendingSettings:(BOOL)ascendente
  111. {
  112. NSString *sAscendente = (ascendente) ? @"true" : @"false";
  113. [UICKeyChainStore setString:sAscendente forKey:@"ascending" service:k_serviceShareKeyChain];
  114. }
  115. + (NSString *)getGroupBySettings
  116. {
  117. NSString *groupby = [UICKeyChainStore stringForKey:@"groupby" service:k_serviceShareKeyChain];
  118. if (groupby == nil) {
  119. [self setGroupBySettings:@"none"];
  120. return @"none";
  121. }
  122. return groupby;
  123. }
  124. + (void)setGroupBySettings:(NSString *)groupby
  125. {
  126. [UICKeyChainStore setString:groupby forKey:@"groupby" service:k_serviceShareKeyChain];
  127. }
  128. + (BOOL)getIntro
  129. {
  130. // Set compatibility old version don't touch me
  131. if ([[UICKeyChainStore stringForKey:[INTRO_MessageType stringByAppendingString:@"Intro"] service:k_serviceShareKeyChain] boolValue] == YES) {
  132. [CCUtility setIntro:YES];
  133. return YES;
  134. }
  135. return [[UICKeyChainStore stringForKey:@"intro" service:k_serviceShareKeyChain] boolValue];
  136. }
  137. + (BOOL)getIntroMessageOldVersion
  138. {
  139. NSString *key = [INTRO_MessageType stringByAppendingString:@"Intro"];
  140. return [[UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain] boolValue];
  141. }
  142. + (void)setIntro:(BOOL)set
  143. {
  144. NSString *sIntro = (set) ? @"true" : @"false";
  145. [UICKeyChainStore setString:sIntro forKey:@"intro" service:k_serviceShareKeyChain];
  146. }
  147. + (NSString *)getIncrementalNumber
  148. {
  149. long number = [[UICKeyChainStore stringForKey:@"incrementalnumber" service:k_serviceShareKeyChain] intValue];
  150. number++;
  151. if (number >= 9999) number = 1;
  152. [UICKeyChainStore setString:[NSString stringWithFormat:@"%ld", number] forKey:@"incrementalnumber"];
  153. return [NSString stringWithFormat:@"%04ld", number];
  154. }
  155. + (NSString *)getActiveAccountExt
  156. {
  157. return [UICKeyChainStore stringForKey:@"activeAccountExt" service:k_serviceShareKeyChain];
  158. }
  159. + (void)setActiveAccountExt:(NSString *)activeAccount
  160. {
  161. [UICKeyChainStore setString:activeAccount forKey:@"activeAccountExt" service:k_serviceShareKeyChain];
  162. }
  163. + (NSString *)getServerUrlExt
  164. {
  165. return [UICKeyChainStore stringForKey:@"serverUrlExt" service:k_serviceShareKeyChain];
  166. }
  167. + (void)setServerUrlExt:(NSString *)serverUrl
  168. {
  169. [UICKeyChainStore setString:serverUrl forKey:@"serverUrlExt" service:k_serviceShareKeyChain];
  170. }
  171. + (NSString *)getTitleServerUrlExt
  172. {
  173. return [UICKeyChainStore stringForKey:@"titleServerUrlExt" service:k_serviceShareKeyChain];
  174. }
  175. + (void)setTitleServerUrlExt:(NSString *)titleServerUrl
  176. {
  177. [UICKeyChainStore setString:titleServerUrl forKey:@"titleServerUrlExt" service:k_serviceShareKeyChain];
  178. }
  179. + (NSString *)getFileNameExt
  180. {
  181. return [UICKeyChainStore stringForKey:@"fileNameExt" service:k_serviceShareKeyChain];
  182. }
  183. + (void)setFileNameExt:(NSString *)fileName
  184. {
  185. [UICKeyChainStore setString:fileName forKey:@"fileNameExt" service:k_serviceShareKeyChain];
  186. }
  187. + (NSString *)getEmail
  188. {
  189. return [UICKeyChainStore stringForKey:@"email" service:k_serviceShareKeyChain];
  190. }
  191. + (void)setEmail:(NSString *)email
  192. {
  193. [UICKeyChainStore setString:email forKey:@"email" service:k_serviceShareKeyChain];
  194. }
  195. + (NSString *)getHint
  196. {
  197. return [UICKeyChainStore stringForKey:@"hint" service:k_serviceShareKeyChain];
  198. }
  199. + (void)setHint:(NSString *)hint
  200. {
  201. [UICKeyChainStore setString:hint forKey:@"hint" service:k_serviceShareKeyChain];
  202. }
  203. + (BOOL)getDirectoryOnTop
  204. {
  205. NSString *valueString = [UICKeyChainStore stringForKey:@"directoryOnTop" service:k_serviceShareKeyChain];
  206. // Default TRUE
  207. if (valueString == nil) {
  208. [self setDirectoryOnTop:YES];
  209. return true;
  210. }
  211. return [valueString boolValue];
  212. }
  213. + (void)setDirectoryOnTop:(BOOL)directoryOnTop
  214. {
  215. NSString *sDirectoryOnTop = (directoryOnTop) ? @"true" : @"false";
  216. [UICKeyChainStore setString:sDirectoryOnTop forKey:@"directoryOnTop" service:k_serviceShareKeyChain];
  217. }
  218. + (BOOL)getOriginalFileName:(NSString *)key
  219. {
  220. return [[UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain] boolValue];
  221. }
  222. + (void)setOriginalFileName:(BOOL)value key:(NSString *)key
  223. {
  224. NSString *sValue = (value) ? @"true" : @"false";
  225. [UICKeyChainStore setString:sValue forKey:key service:k_serviceShareKeyChain];
  226. }
  227. + (NSString *)getFileNameMask:(NSString *)key
  228. {
  229. NSString *mask = [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  230. if (mask == nil)
  231. mask = @"";
  232. return mask;
  233. }
  234. + (void)setFileNameMask:(NSString *)mask key:(NSString *)key
  235. {
  236. [UICKeyChainStore setString:mask forKey:key service:k_serviceShareKeyChain];
  237. }
  238. + (BOOL)getFileNameType:(NSString *)key
  239. {
  240. return [[UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain] boolValue];
  241. }
  242. + (void)setFileNameType:(BOOL)prefix key:(NSString *)key
  243. {
  244. NSString *sPrefix = (prefix) ? @"true" : @"false";
  245. [UICKeyChainStore setString:sPrefix forKey:key service:k_serviceShareKeyChain];
  246. }
  247. + (BOOL)getFavoriteOffline
  248. {
  249. return [[UICKeyChainStore stringForKey:@"favoriteOffline" service:k_serviceShareKeyChain] boolValue];
  250. }
  251. + (void)setFavoriteOffline:(BOOL)offline
  252. {
  253. NSString *sFavoriteOffline = (offline) ? @"true" : @"false";
  254. [UICKeyChainStore setString:sFavoriteOffline forKey:@"favoriteOffline" service:k_serviceShareKeyChain];
  255. }
  256. + (BOOL)getActivityVerboseHigh
  257. {
  258. return [[UICKeyChainStore stringForKey:@"activityVerboseHigh" service:k_serviceShareKeyChain] boolValue];
  259. }
  260. + (void)setActivityVerboseHigh:(BOOL)high
  261. {
  262. NSString *sHigh = (high) ? @"true" : @"false";
  263. [UICKeyChainStore setString:sHigh forKey:@"activityVerboseHigh" service:k_serviceShareKeyChain];
  264. }
  265. + (BOOL)getShowHiddenFiles
  266. {
  267. return [[UICKeyChainStore stringForKey:@"showHiddenFiles" service:k_serviceShareKeyChain] boolValue];
  268. }
  269. + (void)setShowHiddenFiles:(BOOL)show
  270. {
  271. NSString *sShow = (show) ? @"true" : @"false";
  272. [UICKeyChainStore setString:sShow forKey:@"showHiddenFiles" service:k_serviceShareKeyChain];
  273. }
  274. + (BOOL)getFormatCompatibility
  275. {
  276. NSString *valueString = [UICKeyChainStore stringForKey:@"formatCompatibility" service:k_serviceShareKeyChain];
  277. // Default TRUE
  278. if (valueString == nil) {
  279. [self setFormatCompatibility:YES];
  280. return true;
  281. }
  282. return [valueString boolValue];
  283. }
  284. + (void)setFormatCompatibility:(BOOL)set
  285. {
  286. NSString *sSet = (set) ? @"true" : @"false";
  287. [UICKeyChainStore setString:sSet forKey:@"formatCompatibility" service:k_serviceShareKeyChain];
  288. }
  289. + (NSString *)getEndToEndPublicKey:(NSString *)account
  290. {
  291. NSString *key = [E2E_PublicKey stringByAppendingString:account];
  292. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  293. }
  294. + (void)setEndToEndPublicKey:(NSString *)account publicKey:(NSString *)publicKey
  295. {
  296. NSString *key = [E2E_PublicKey stringByAppendingString:account];
  297. [UICKeyChainStore setString:publicKey forKey:key service:k_serviceShareKeyChain];
  298. }
  299. + (NSString *)getEndToEndPrivateKey:(NSString *)account
  300. {
  301. NSString *key = [E2E_PrivateKey stringByAppendingString:account];
  302. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  303. }
  304. + (void)setEndToEndPrivateKey:(NSString *)account privateKey:(NSString *)privateKey
  305. {
  306. NSString *key = [E2E_PrivateKey stringByAppendingString:account];
  307. [UICKeyChainStore setString:privateKey forKey:key service:k_serviceShareKeyChain];
  308. }
  309. + (NSString *)getEndToEndPassphrase:(NSString *)account
  310. {
  311. NSString *key = [E2E_Passphrase stringByAppendingString:account];
  312. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  313. }
  314. + (void)setEndToEndPassphrase:(NSString *)account passphrase:(NSString *)passphrase
  315. {
  316. NSString *key = [E2E_Passphrase stringByAppendingString:account];
  317. [UICKeyChainStore setString:passphrase forKey:key service:k_serviceShareKeyChain];
  318. }
  319. + (NSString *)getEndToEndPublicKeyServer:(NSString *)account
  320. {
  321. NSString *key = [E2E_PublicKeyServer stringByAppendingString:account];
  322. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  323. }
  324. + (void)setEndToEndPublicKeyServer:(NSString *)account publicKey:(NSString *)publicKey
  325. {
  326. NSString *key = [E2E_PublicKeyServer stringByAppendingString:account];
  327. [UICKeyChainStore setString:publicKey forKey:key service:k_serviceShareKeyChain];
  328. }
  329. + (BOOL)isEndToEndEnabled:(NSString *)account
  330. {
  331. BOOL isE2EEEnabled = [[NCManageDatabase sharedInstance] getCapabilitiesServerBoolWithAccount:account elements:NCElementsJSON.shared.capabilitiesE2EEEnabled exists:false];
  332. NSString *publicKey = [self getEndToEndPublicKey:account];
  333. NSString *privateKey = [self getEndToEndPrivateKey:account];
  334. NSString *passphrase = [self getEndToEndPassphrase:account];
  335. NSString *publicKeyServer = [self getEndToEndPublicKeyServer:account];
  336. if (passphrase.length > 0 && privateKey.length > 0 && publicKey.length > 0 && publicKeyServer.length > 0 && isE2EEEnabled) {
  337. return YES;
  338. } else {
  339. return NO;
  340. }
  341. }
  342. + (void)clearAllKeysEndToEnd:(NSString *)account
  343. {
  344. [self setEndToEndPublicKey:account publicKey:nil];
  345. [self setEndToEndPrivateKey:account privateKey:nil];
  346. [self setEndToEndPassphrase:account passphrase:nil];
  347. [self setEndToEndPublicKeyServer:account publicKey:nil];
  348. }
  349. + (BOOL)getDisableFilesApp
  350. {
  351. return [[UICKeyChainStore stringForKey:@"disablefilesapp" service:k_serviceShareKeyChain] boolValue];
  352. }
  353. + (void)setDisableFilesApp:(BOOL)disable
  354. {
  355. NSString *sDisable = (disable) ? @"true" : @"false";
  356. [UICKeyChainStore setString:sDisable forKey:@"disablefilesapp" service:k_serviceShareKeyChain];
  357. }
  358. + (void)setPushNotificationPublicKey:(NSString *)account data:(NSData *)data
  359. {
  360. NSString *key = [@"PNPublicKey" stringByAppendingString:account];
  361. [UICKeyChainStore setData:data forKey:key service:k_serviceShareKeyChain];
  362. }
  363. + (NSData *)getPushNotificationPublicKey:(NSString *)account
  364. {
  365. NSString *key = [@"PNPublicKey" stringByAppendingString:account];
  366. return [UICKeyChainStore dataForKey:key service:k_serviceShareKeyChain];
  367. }
  368. + (void)setPushNotificationSubscribingPublicKey:(NSString *)account publicKey:(NSString *)publicKey
  369. {
  370. NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account];
  371. [UICKeyChainStore setString:publicKey forKey:key service:k_serviceShareKeyChain];
  372. }
  373. + (NSString *)getPushNotificationSubscribingPublicKey:(NSString *)account
  374. {
  375. NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account];
  376. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  377. }
  378. + (void)setPushNotificationPrivateKey:(NSString *)account data:(NSData *)data
  379. {
  380. NSString *key = [@"PNPrivateKey" stringByAppendingString:account];
  381. [UICKeyChainStore setData:data forKey:key service:k_serviceShareKeyChain];
  382. }
  383. + (NSData *)getPushNotificationPrivateKey:(NSString *)account
  384. {
  385. NSString *key = [@"PNPrivateKey" stringByAppendingString:account];
  386. return [UICKeyChainStore dataForKey:key service:k_serviceShareKeyChain];
  387. }
  388. + (void)setPushNotificationToken:(NSString *)account token:(NSString *)token
  389. {
  390. NSString *key = [@"PNToken" stringByAppendingString:account];
  391. [UICKeyChainStore setString:token forKey:key service:k_serviceShareKeyChain];
  392. }
  393. + (NSString *)getPushNotificationToken:(NSString *)account
  394. {
  395. NSString *key = [@"PNToken" stringByAppendingString:account];
  396. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  397. }
  398. + (void)setPushNotificationDeviceIdentifier:(NSString *)account deviceIdentifier:(NSString *)deviceIdentifier
  399. {
  400. NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account];
  401. [UICKeyChainStore setString:deviceIdentifier forKey:key service:k_serviceShareKeyChain];
  402. }
  403. + (NSString *)getPushNotificationDeviceIdentifier:(NSString *)account
  404. {
  405. NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account];
  406. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  407. }
  408. + (void)setPushNotificationDeviceIdentifierSignature:(NSString *)account deviceIdentifierSignature:(NSString *)deviceIdentifierSignature
  409. {
  410. NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account];
  411. [UICKeyChainStore setString:deviceIdentifierSignature forKey:key service:k_serviceShareKeyChain];
  412. }
  413. + (NSString *)getPushNotificationDeviceIdentifierSignature:(NSString *)account
  414. {
  415. NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account];
  416. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  417. }
  418. + (void)clearAllKeysPushNotification:(NSString *)account
  419. {
  420. [self setPushNotificationPublicKey:account data:nil];
  421. [self setPushNotificationSubscribingPublicKey:account publicKey:nil];
  422. [self setPushNotificationPrivateKey:account data:nil];
  423. [self setPushNotificationToken:account token:nil];
  424. [self setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  425. [self setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  426. }
  427. + (NSInteger)getMediaWidthImage
  428. {
  429. NSString *width = [UICKeyChainStore stringForKey:@"mediaWidthImage" service:k_serviceShareKeyChain];
  430. if (width == nil) {
  431. return 80;
  432. } else {
  433. return [width integerValue];
  434. }
  435. }
  436. + (void)setMediaWidthImage:(NSInteger)width
  437. {
  438. NSString *widthString = [@(width) stringValue];
  439. [UICKeyChainStore setString:widthString forKey:@"mediaWidthImage" service:k_serviceShareKeyChain];
  440. }
  441. + (BOOL)getDisableCrashservice
  442. {
  443. return [[UICKeyChainStore stringForKey:@"crashservice" service:k_serviceShareKeyChain] boolValue];
  444. }
  445. + (void)setDisableCrashservice:(BOOL)disable
  446. {
  447. NSString *sDisable = (disable) ? @"true" : @"false";
  448. [UICKeyChainStore setString:sDisable forKey:@"crashservice" service:k_serviceShareKeyChain];
  449. }
  450. + (void)setPassword:(NSString *)account password:(NSString *)password
  451. {
  452. NSString *key = [@"password" stringByAppendingString:account];
  453. [UICKeyChainStore setString:password forKey:key service:k_serviceShareKeyChain];
  454. }
  455. + (NSString *)getPassword:(NSString *)account
  456. {
  457. NSString *key = [@"password" stringByAppendingString:account];
  458. return [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  459. }
  460. + (void)setHCBusinessType:(NSString *)professions
  461. {
  462. [UICKeyChainStore setString:professions forKey:@"businessType" service:k_serviceShareKeyChain];
  463. }
  464. + (NSString *)getHCBusinessType
  465. {
  466. return [UICKeyChainStore stringForKey:@"businessType" service:k_serviceShareKeyChain];
  467. }
  468. + (NSData *)getDatabaseEncryptionKey
  469. {
  470. NSData *key = [UICKeyChainStore dataForKey:@"databaseEncryptionKey" service:k_serviceShareKeyChain];
  471. if (key == nil) {
  472. NSMutableData *key = [NSMutableData dataWithLength:64];
  473. (void)SecRandomCopyBytes(kSecRandomDefault, key.length, (uint8_t *)key.mutableBytes);
  474. [UICKeyChainStore setData:key forKey:@"databaseEncryptionKey" service:k_serviceShareKeyChain];
  475. return key;
  476. } else {
  477. return key;
  478. }
  479. }
  480. + (void)setDatabaseEncryptionKey:(NSData *)data
  481. {
  482. [UICKeyChainStore setData:data forKey:@"databaseEncryptionKey" service:k_serviceShareKeyChain];
  483. }
  484. + (BOOL)getCertificateError:(NSString *)account
  485. {
  486. NSString *key = [@"certificateError" stringByAppendingString:account];
  487. NSString *error = [UICKeyChainStore stringForKey:key service:k_serviceShareKeyChain];
  488. if (error == nil) {
  489. [self setCertificateError:account error:NO];
  490. return NO;
  491. }
  492. return [error boolValue];
  493. }
  494. + (void)setCertificateError:(NSString *)account error:(BOOL)error
  495. {
  496. NSString *key = [@"certificateError" stringByAppendingString:account];
  497. NSString *sError = (error) ? @"true" : @"false";
  498. [UICKeyChainStore setString:sError forKey:key service:k_serviceShareKeyChain];
  499. }
  500. + (BOOL)getDisableLocalCacheAfterUpload
  501. {
  502. return [[UICKeyChainStore stringForKey:@"disableLocalCacheAfterUpload" service:k_serviceShareKeyChain] boolValue];
  503. }
  504. + (void)setDisableLocalCacheAfterUpload:(BOOL)disable
  505. {
  506. NSString *sDisable = (disable) ? @"true" : @"false";
  507. [UICKeyChainStore setString:sDisable forKey:@"disableLocalCacheAfterUpload" service:k_serviceShareKeyChain];
  508. }
  509. + (BOOL)getDarkMode
  510. {
  511. return [[UICKeyChainStore stringForKey:@"darkMode" service:k_serviceShareKeyChain] boolValue];
  512. }
  513. + (void)setDarkMode:(BOOL)disable
  514. {
  515. NSString *sDisable = (disable) ? @"true" : @"false";
  516. [UICKeyChainStore setString:sDisable forKey:@"darkMode" service:k_serviceShareKeyChain];
  517. }
  518. + (BOOL)getDarkModeDetect
  519. {
  520. NSString *valueString = [UICKeyChainStore stringForKey:@"darkModeDetect" service:k_serviceShareKeyChain];
  521. // Default TRUE
  522. if (valueString == nil) {
  523. [self setDarkModeDetect:YES];
  524. return true;
  525. }
  526. return [valueString boolValue];
  527. }
  528. + (void)setDarkModeDetect:(BOOL)disable
  529. {
  530. NSString *sDisable = (disable) ? @"true" : @"false";
  531. [UICKeyChainStore setString:sDisable forKey:@"darkModeDetect" service:k_serviceShareKeyChain];
  532. }
  533. + (BOOL)getLivePhoto
  534. {
  535. NSString *valueString = [UICKeyChainStore stringForKey:@"livePhoto" service:k_serviceShareKeyChain];
  536. // Default TRUE
  537. if (valueString == nil) {
  538. [self setLivePhoto:YES];
  539. return true;
  540. }
  541. return [valueString boolValue];
  542. }
  543. + (void)setLivePhoto:(BOOL)set
  544. {
  545. NSString *sSet = (set) ? @"true" : @"false";
  546. [UICKeyChainStore setString:sSet forKey:@"livePhoto" service:k_serviceShareKeyChain];
  547. }
  548. #pragma --------------------------------------------------------------------------------------------
  549. #pragma mark ===== Various =====
  550. #pragma --------------------------------------------------------------------------------------------
  551. + (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
  552. {
  553. assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
  554. NSError *error = nil;
  555. BOOL success = [URL setResourceValue:[NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error];
  556. if(!success){
  557. NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
  558. }
  559. return success;
  560. }
  561. + (NSString *)getUserAgent
  562. {
  563. NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  564. NSString *userAgent = [[NCBrandOptions sharedInstance] userAgent];
  565. return [NSString stringWithFormat:@"Mozilla/5.0 (iOS) %@/%@", userAgent, appVersion];
  566. }
  567. + (NSString *)dateDiff:(NSDate *) convertedDate
  568. {
  569. NSDate *todayDate = [NSDate date];
  570. double ti = [convertedDate timeIntervalSinceDate:todayDate];
  571. ti = ti * -1;
  572. if (ti < 60) {
  573. // This minute
  574. return NSLocalizedString(@"_less_a_minute_", nil);
  575. } else if (ti < 3600) {
  576. // This hour
  577. int diff = round(ti / 60);
  578. return [NSString stringWithFormat:NSLocalizedString(@"_minutes_ago_", nil), diff];
  579. } else if (ti < 86400) {
  580. // This day
  581. int diff = round(ti / 60 / 60);
  582. return[NSString stringWithFormat:NSLocalizedString(@"_hours_ago_", nil), diff];
  583. } else if (ti < 86400 * 30) {
  584. // This month
  585. int diff = round(ti / 60 / 60 / 24);
  586. return[NSString stringWithFormat:NSLocalizedString(@"_days_ago_", nil), diff];
  587. } else {
  588. // Older than one month
  589. NSDateFormatter *df = [[NSDateFormatter alloc] init];
  590. [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  591. [df setDateStyle:NSDateFormatterMediumStyle];
  592. return [df stringFromDate:convertedDate];
  593. }
  594. }
  595. + (NSDate *)dateEnUsPosixFromCloud:(NSString *)dateString
  596. {
  597. NSDate *date = [NSDate date];
  598. NSError *error;
  599. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  600. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  601. [dateFormatter setLocale:enUSPOSIXLocale];
  602. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  603. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  604. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  605. date = [NSDate date];
  606. }
  607. return date;
  608. }
  609. + (NSString *)transformedSize:(double)value
  610. {
  611. NSString *string = [NSByteCountFormatter stringFromByteCount:value countStyle:NSByteCountFormatterCountStyleBinary];
  612. return string;
  613. }
  614. // Remove do not forbidden characters for Nextcloud Server
  615. + (NSString *)removeForbiddenCharactersServer:(NSString *)fileName
  616. {
  617. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"/", nil];
  618. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  619. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  620. }
  621. return fileName;
  622. }
  623. // Remove do not forbidden characters for File System Server
  624. + (NSString *)removeForbiddenCharactersFileSystem:(NSString *)fileName
  625. {
  626. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"\\",@"<",@">",@":",@"\"",@"|",@"?",@"*",@"/", nil];
  627. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  628. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  629. }
  630. return fileName;
  631. }
  632. + (NSString*)stringAppendServerUrl:(NSString *)serverUrl addFileName:(NSString *)addFileName
  633. {
  634. NSString *result;
  635. if (serverUrl == nil || addFileName == nil) return nil;
  636. if ([addFileName isEqualToString:@""]) return serverUrl;
  637. if ([serverUrl isEqualToString:@"/"]) result = [serverUrl stringByAppendingString:addFileName];
  638. else result = [NSString stringWithFormat:@"%@/%@", serverUrl, addFileName];
  639. return result;
  640. }
  641. + (NSString *)createRandomString:(int)numChars
  642. {
  643. NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  644. NSMutableString *randomString = [NSMutableString stringWithCapacity: numChars];
  645. for (int i=0; i < numChars; i++) {
  646. [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((unsigned int)[letters length]) % [letters length]]];
  647. }
  648. return [NSString stringWithFormat:@"%@", randomString];
  649. }
  650. + (NSString *)createFileNameDate:(NSString *)fileName extension:(NSString *)extension
  651. {
  652. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  653. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  654. NSString *fileNameDate = [formatter stringFromDate:[NSDate date]];
  655. NSString *returnFileName;
  656. if ([fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  657. returnFileName = [NSString stringWithFormat:@"%@.%@", fileNameDate, extension];
  658. }
  659. if (![fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  660. returnFileName = [NSString stringWithFormat:@"%@ %@", fileName, fileNameDate];
  661. }
  662. if ([fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  663. returnFileName = fileNameDate;
  664. }
  665. if (![fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  666. returnFileName = [NSString stringWithFormat:@"%@ %@.%@", fileName, fileNameDate, extension];
  667. }
  668. return returnFileName;
  669. }
  670. + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fileType:(PHAssetMediaType)fileType keyFileName:(NSString *)keyFileName keyFileNameType:(NSString *)keyFileNameType keyFileNameOriginal:(NSString *)keyFileNameOriginal
  671. {
  672. BOOL addFileNameType = NO;
  673. // Original FileName ?
  674. if ([self getOriginalFileName:keyFileNameOriginal]) {
  675. return fileName;
  676. }
  677. NSString *numberFileName;
  678. if ([fileName length] > 8) numberFileName = [fileName substringWithRange:NSMakeRange(04, 04)];
  679. else numberFileName = [CCUtility getIncrementalNumber];
  680. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  681. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  682. NSString *fileNameDate = [formatter stringFromDate:fileDate];
  683. NSString *fileNameType = @"";
  684. if (fileType == PHAssetMediaTypeImage)
  685. fileNameType = NSLocalizedString(@"_photo_", nil);
  686. if (fileType == PHAssetMediaTypeVideo)
  687. fileNameType = NSLocalizedString(@"_video_", nil);
  688. if (fileType == PHAssetMediaTypeAudio)
  689. fileNameType = NSLocalizedString(@"_audio_", nil);
  690. if (fileType == PHAssetMediaTypeUnknown)
  691. fileNameType = NSLocalizedString(@"_unknown_", nil);
  692. // Use File Name Type
  693. if (keyFileNameType)
  694. addFileNameType = [CCUtility getFileNameType:keyFileNameType];
  695. NSString *fileNameExt = [[fileName pathExtension] lowercaseString];
  696. if (keyFileName) {
  697. fileName = [CCUtility getFileNameMask:keyFileName];
  698. if ([fileName length] > 0) {
  699. [formatter setDateFormat:@"dd"];
  700. NSString *dayNumber = [formatter stringFromDate:fileDate];
  701. [formatter setDateFormat:@"MMM"];
  702. NSString *month = [formatter stringFromDate:fileDate];
  703. [formatter setDateFormat:@"MM"];
  704. NSString *monthNumber = [formatter stringFromDate:fileDate];
  705. [formatter setDateFormat:@"yyyy"];
  706. NSString *year = [formatter stringFromDate:fileDate];
  707. [formatter setDateFormat:@"yy"];
  708. NSString *yearNumber = [formatter stringFromDate:fileDate];
  709. [formatter setDateFormat:@"HH"];
  710. NSString *hour24 = [formatter stringFromDate:fileDate];
  711. [formatter setDateFormat:@"hh"];
  712. NSString *hour12 = [formatter stringFromDate:fileDate];
  713. [formatter setDateFormat:@"mm"];
  714. NSString *minute = [formatter stringFromDate:fileDate];
  715. [formatter setDateFormat:@"ss"];
  716. NSString *second = [formatter stringFromDate:fileDate];
  717. [formatter setDateFormat:@"a"];
  718. NSString *ampm = [formatter stringFromDate:fileDate];
  719. // Replace string with date
  720. fileName = [fileName stringByReplacingOccurrencesOfString:@"DD" withString:dayNumber];
  721. fileName = [fileName stringByReplacingOccurrencesOfString:@"MMM" withString:month];
  722. fileName = [fileName stringByReplacingOccurrencesOfString:@"MM" withString:monthNumber];
  723. fileName = [fileName stringByReplacingOccurrencesOfString:@"YYYY" withString:year];
  724. fileName = [fileName stringByReplacingOccurrencesOfString:@"YY" withString:yearNumber];
  725. fileName = [fileName stringByReplacingOccurrencesOfString:@"HH" withString:hour24];
  726. fileName = [fileName stringByReplacingOccurrencesOfString:@"hh" withString:hour12];
  727. fileName = [fileName stringByReplacingOccurrencesOfString:@"mm" withString:minute];
  728. fileName = [fileName stringByReplacingOccurrencesOfString:@"ss" withString:second];
  729. fileName = [fileName stringByReplacingOccurrencesOfString:@"ampm" withString:ampm];
  730. if (addFileNameType)
  731. fileName = [NSString stringWithFormat:@"%@%@%@.%@", fileNameType, fileName, numberFileName, fileNameExt];
  732. else
  733. fileName = [NSString stringWithFormat:@"%@%@.%@", fileName, numberFileName, fileNameExt];
  734. fileName = [fileName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  735. } else {
  736. if (addFileNameType)
  737. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  738. else
  739. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  740. }
  741. } else {
  742. if (addFileNameType)
  743. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  744. else
  745. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  746. }
  747. return fileName;
  748. }
  749. + (void)createDirectoryStandard
  750. {
  751. NSString *path;
  752. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  753. NSLog(@"[LOG] Dir Group");
  754. NSLog(@"%@", [dirGroup path]);
  755. NSLog(@"[LOG] Program application ");
  756. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  757. // create Directory Documents
  758. path = [CCUtility getDirectoryDocuments];
  759. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  760. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  761. // create Directory audio => Library, Application Support, audio
  762. path = [CCUtility getDirectoryAudio];
  763. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  764. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  765. // create Directory database Nextcloud
  766. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  767. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  768. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  769. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  770. // create Directory User Data
  771. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  772. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  773. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  774. // create Directory Provider Storage
  775. path = [CCUtility getDirectoryProviderStorage];
  776. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  777. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  778. // create Directory Scan
  779. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  780. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  781. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  782. // create Directory Temp
  783. path = NSTemporaryDirectory();
  784. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  785. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  786. // Directory Excluded From Backup
  787. [CCUtility addSkipBackupAttributeToItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];
  788. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_DirectoryProviderStorage]];
  789. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appUserData]];
  790. #ifdef DEBUG
  791. NSLog(@"[LOG] Copy DB on Documents directory");
  792. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  793. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  794. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  795. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  796. #endif
  797. }
  798. + (NSURL *)getDirectoryGroup
  799. {
  800. NSURL *path = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  801. return path;
  802. }
  803. + (NSString *)getHomeServerUrlActiveUrl:(NSString *)activeUrl
  804. {
  805. if (activeUrl == nil)
  806. return @"";
  807. return [activeUrl stringByAppendingString:k_webDAV];
  808. }
  809. + (NSString *)getStringUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  810. {
  811. NSString *baseUrl = [activeUrl lowercaseString];
  812. NSString *dirUserBaseUrl = @"";
  813. if ([activeUser length] && [baseUrl length]) {
  814. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  815. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  816. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", activeUser, baseUrl];
  817. dirUserBaseUrl = [[self removeForbiddenCharactersFileSystem:dirUserBaseUrl] lowercaseString];
  818. }
  819. return dirUserBaseUrl;
  820. }
  821. // Return path of User
  822. + (NSString *)getDirectoryActiveUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  823. {
  824. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  825. NSString *user = activeUser;
  826. NSString *baseUrl = [activeUrl lowercaseString];
  827. NSString *dirUserBaseUrl = nil;
  828. NSString *dirApplicationUserGroup = nil;
  829. if ([user length] && [baseUrl length]) {
  830. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  831. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  832. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", user, baseUrl];
  833. dirUserBaseUrl = [[self removeForbiddenCharactersFileSystem:dirUserBaseUrl] lowercaseString];
  834. } else return @"";
  835. dirApplicationUserGroup = [[dirGroup URLByAppendingPathComponent:k_appApplicationSupport] path];
  836. dirUserBaseUrl = [NSString stringWithFormat:@"%@/%@", dirApplicationUserGroup, dirUserBaseUrl];
  837. if (![[NSFileManager defaultManager] fileExistsAtPath: dirUserBaseUrl]) {
  838. [[NSFileManager defaultManager] createDirectoryAtPath:dirUserBaseUrl withIntermediateDirectories:YES attributes:nil error:nil];
  839. }
  840. return dirUserBaseUrl;
  841. }
  842. // Return the path of directory Documents -> NSDocumentDirectory
  843. + (NSString *)getDirectoryDocuments
  844. {
  845. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  846. return [paths objectAtIndex:0];
  847. }
  848. + (NSString *)getDirectoryReaderMetadata
  849. {
  850. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  851. return [NSString stringWithFormat:@"%@/Reader Metadata", [paths objectAtIndex:0]];
  852. }
  853. // Return the path of directory Audio
  854. + (NSString *)getDirectoryAudio
  855. {
  856. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  857. return [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"audio"];
  858. }
  859. // Return the path of directory Cetificates
  860. + (NSString *)getDirectoryCerificates
  861. {
  862. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appCertificates] path];
  863. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  864. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  865. return path;
  866. }
  867. + (NSString *)getDirectoryUserData
  868. {
  869. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appUserData] path];
  870. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  871. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  872. return path;
  873. }
  874. + (NSString *)getDirectoryProviderStorage
  875. {
  876. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_DirectoryProviderStorage] path];
  877. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  878. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  879. return path;
  880. }
  881. + (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId
  882. {
  883. NSString *path = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorage], ocId];
  884. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  885. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  886. return path;
  887. }
  888. + (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView
  889. {
  890. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorageOcId:ocId], fileNameView];
  891. // if do not exists create file 0 length
  892. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath] == NO) {
  893. [[NSFileManager defaultManager] createFileAtPath:fileNamePath contents:nil attributes:nil];
  894. }
  895. return fileNamePath;
  896. }
  897. + (NSString *)getDirectoryProviderStorageIconOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView
  898. {
  899. return [NSString stringWithFormat:@"%@/%@.ico", [self getDirectoryProviderStorageOcId:ocId], fileNameView];
  900. }
  901. + (BOOL)fileProviderStorageExists:(NSString *)ocId fileNameView:(NSString *)fileNameView
  902. {
  903. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  904. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  905. if (fileSize > 0) return true;
  906. else return false;
  907. }
  908. + (double)fileProviderStorageSize:(NSString *)ocId fileNameView:(NSString *)fileNameView
  909. {
  910. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  911. double fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  912. return fileSize;
  913. }
  914. + (BOOL)fileProviderStorageIconExists:(NSString *)ocId fileNameView:(NSString *)fileNameView
  915. {
  916. NSString *fileNamePath = [self getDirectoryProviderStorageIconOcId:ocId fileNameView:fileNameView];
  917. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  918. if (fileSize > 0) return true;
  919. else return false;
  920. }
  921. + (void)removeGroupApplicationSupport
  922. {
  923. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  924. NSString *path = [[dirGroup URLByAppendingPathComponent:k_appApplicationSupport] path];
  925. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  926. }
  927. + (void)removeGroupLibraryDirectory
  928. {
  929. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryScan] error:nil];
  930. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryUserData] error:nil];
  931. }
  932. + (void)removeGroupDirectoryProviderStorage
  933. {
  934. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorage] error:nil];
  935. }
  936. + (void)removeDocumentsDirectory
  937. {
  938. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryDocuments] error:nil];
  939. }
  940. + (void)removeTemporaryDirectory
  941. {
  942. [[NSFileManager defaultManager] removeItemAtPath:NSTemporaryDirectory() error:nil];
  943. }
  944. + (void)emptyTemporaryDirectory
  945. {
  946. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  947. for (NSString *file in tmpDirectory) {
  948. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  949. }
  950. }
  951. + (NSString *)getTitleSectionDate:(NSDate *)date
  952. {
  953. NSString *title;
  954. NSDate *today = [NSDate date];
  955. NSDate *yesterday = [today dateByAddingTimeInterval: -86400.0];
  956. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:[NSDate distantPast]]]) {
  957. title = NSLocalizedString(@"_no_date_", nil);
  958. } else {
  959. title = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:0];
  960. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:today]])
  961. title = [NSString stringWithFormat:NSLocalizedString(@"_today_", nil)];
  962. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:yesterday]])
  963. title = [NSString stringWithFormat:NSLocalizedString(@"_yesterday_", nil)];
  964. }
  965. return title;
  966. }
  967. + (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  968. {
  969. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  970. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  971. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  972. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  973. }
  974. }
  975. + (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  976. {
  977. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  978. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  979. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  980. }
  981. }
  982. + (void)removeFileAtPath:(NSString *)atPath
  983. {
  984. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  985. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  986. }
  987. }
  988. + (void)createDirectoryAtPath:(NSString *)atPath
  989. {
  990. [[NSFileManager defaultManager] createDirectoryAtPath:atPath withIntermediateDirectories:true attributes:nil error:nil];
  991. }
  992. + (NSString *)deletingLastPathComponentFromServerUrl:(NSString *)serverUrl
  993. {
  994. NSURL *url = [[NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]] URLByDeletingLastPathComponent];
  995. NSString *pather = [[url absoluteString] stringByRemovingPercentEncoding];
  996. return [pather substringToIndex: [pather length] - 1];
  997. }
  998. + (NSString *)firtsPathComponentFromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  999. {
  1000. NSString *firstPath = serverUrl;
  1001. NSURL *serverUrlURL = [NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  1002. NSURL *activeUrlURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/", [activeUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]], k_webDAV]];
  1003. while ([[serverUrlURL absoluteString] isEqualToString:[activeUrlURL absoluteString]] == false) {
  1004. firstPath = [serverUrlURL absoluteString];
  1005. serverUrlURL = [serverUrlURL URLByDeletingLastPathComponent];
  1006. }
  1007. if ([firstPath hasSuffix:@"/"]) firstPath = [firstPath substringToIndex:[firstPath length] - 1];
  1008. return firstPath;
  1009. }
  1010. + (NSString *)getLastPathFromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1011. {
  1012. if ([serverUrl isEqualToString:activeUrl])
  1013. return @"";
  1014. NSURL *serverUrlURL = [NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  1015. NSString *fileName = [serverUrlURL lastPathComponent];
  1016. return fileName;
  1017. }
  1018. + (NSString *)returnPathfromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1019. {
  1020. NSString *path = [serverUrl stringByReplacingOccurrencesOfString:[activeUrl stringByAppendingString:k_webDAV] withString:@""];
  1021. return path;
  1022. }
  1023. + (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1024. {
  1025. if (metadataFileName == nil || serverUrl == nil || activeUrl == nil) {
  1026. return @"";
  1027. }
  1028. NSString *fileName = [NSString stringWithFormat:@"%@/%@", [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:activeUrl] withString:@""], metadataFileName];
  1029. if ([fileName hasPrefix:@"/"]) fileName = [fileName substringFromIndex:1];
  1030. return fileName;
  1031. }
  1032. + (NSArray *)createNameSubFolder:(PHFetchResult *)alassets
  1033. {
  1034. NSMutableOrderedSet *datesSubFolder = [NSMutableOrderedSet new];
  1035. for (PHAsset *asset in alassets) {
  1036. NSDate *assetDate = asset.creationDate;
  1037. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1038. [formatter setDateFormat:@"yyyy"];
  1039. NSString *yearString = [formatter stringFromDate:assetDate];
  1040. if (yearString)
  1041. [datesSubFolder addObject:yearString];
  1042. [formatter setDateFormat:@"MM"];
  1043. NSString *monthString = [formatter stringFromDate:assetDate];
  1044. monthString = [NSString stringWithFormat:@"%@/%@", yearString, monthString];
  1045. if (monthString)
  1046. [datesSubFolder addObject:monthString];
  1047. }
  1048. return (NSArray *)datesSubFolder;
  1049. }
  1050. + (NSString *)getMimeType:(NSString *)fileNameView
  1051. {
  1052. CFStringRef fileUTI = nil;
  1053. NSString *returnFileUTI = nil;
  1054. if ([fileNameView isEqualToString:@"."]) {
  1055. return returnFileUTI;
  1056. } else {
  1057. CFStringRef fileExtension = (__bridge CFStringRef)[fileNameView pathExtension];
  1058. NSString *ext = (__bridge NSString *)fileExtension;
  1059. ext = ext.uppercaseString;
  1060. fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  1061. if (fileUTI != nil) {
  1062. returnFileUTI = (__bridge NSString *)fileUTI;
  1063. CFRelease(fileUTI);
  1064. }
  1065. }
  1066. return returnFileUTI;
  1067. }
  1068. + (NSString *)getDirectoryScan
  1069. {
  1070. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appScan] path];
  1071. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  1072. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  1073. return path;
  1074. }
  1075. + (void)writeData:(NSData *)data fileNamePath:(NSString *)fileNamePath
  1076. {
  1077. [data writeToFile:fileNamePath atomically:YES];
  1078. }
  1079. + (void)selectFileNameFrom:(UITextField *)textField
  1080. {
  1081. UITextPosition *endPosition;
  1082. NSRange rangeDot = [textField.text rangeOfString:@"." options:NSBackwardsSearch];
  1083. if (rangeDot.location != NSNotFound) {
  1084. endPosition = [textField positionFromPosition:textField.beginningOfDocument offset:rangeDot.location];
  1085. } else {
  1086. endPosition = textField.endOfDocument;
  1087. }
  1088. UITextRange *textRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:endPosition];
  1089. textField.selectedTextRange = textRange;
  1090. }
  1091. + (NSString *)getTimeIntervalSince197
  1092. {
  1093. return [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
  1094. }
  1095. + (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadata notification:(BOOL)notification completion:(void(^)(tableMetadata *newMetadata, NSString* fileNamePath))completion
  1096. {
  1097. tableMetadata *newMetadata = [[NCManageDatabase sharedInstance] initNewMetadata:metadata];
  1098. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1099. if (!result.count) {
  1100. if (notification) {
  1101. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Error photo/video not found, remove from upload"}];
  1102. }
  1103. completion(nil, nil);
  1104. return;
  1105. }
  1106. PHAsset *asset = result[0];
  1107. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  1108. if (tableAccount == nil) {
  1109. if (notification) {
  1110. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  1111. }
  1112. completion(nil, nil);
  1113. return;
  1114. }
  1115. // IMAGE
  1116. if (asset.mediaType == PHAssetMediaTypeImage) {
  1117. PHImageRequestOptions *options = [PHImageRequestOptions new];
  1118. options.networkAccessAllowed = YES; // iCloud
  1119. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  1120. options.synchronous = YES;
  1121. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1122. NSLog(@"cacheAsset: %f", progress);
  1123. if (error) {
  1124. if (notification) {
  1125. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description]}];
  1126. }
  1127. completion(nil, nil);
  1128. return;
  1129. }
  1130. };
  1131. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  1132. NSError *error = nil;
  1133. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  1134. NSString *fileName = metadata.fileNameView;
  1135. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  1136. CIImage *ciImage = [CIImage imageWithData:imageData];
  1137. CIContext *context = [CIContext context];
  1138. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  1139. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  1140. fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  1141. newMetadata.contentType = @"image/jpeg";
  1142. }
  1143. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:fileName];
  1144. [[NSFileManager defaultManager]removeItemAtPath:fileNamePath error:nil];
  1145. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  1146. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1147. if (attributes[NSFileModificationDate]) {
  1148. newMetadata.date = attributes[NSFileModificationDate];
  1149. }
  1150. newMetadata.size = [attributes[NSFileSize] longValue];
  1151. if (newMetadata.e2eEncrypted) {
  1152. newMetadata.fileNameView = fileName;
  1153. } else {
  1154. newMetadata.fileNameView = fileName;
  1155. newMetadata.fileName = fileName;
  1156. }
  1157. completion(newMetadata, fileNamePath);
  1158. }];
  1159. }
  1160. // VIDEO
  1161. if (asset.mediaType == PHAssetMediaTypeVideo) {
  1162. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  1163. options.networkAccessAllowed = YES;
  1164. options.version = PHVideoRequestOptionsVersionOriginal;
  1165. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1166. NSLog(@"cacheAsset: %f", progress);
  1167. if (error) {
  1168. if (notification) {
  1169. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1170. }
  1171. completion(nil, nil);
  1172. }
  1173. };
  1174. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  1175. if ([asset isKindOfClass:[AVURLAsset class]]) {
  1176. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:newMetadata.fileNameView];
  1177. NSURL *fileNamePathURL = [[NSURL alloc] initFileURLWithPath:fileNamePath];
  1178. NSError *error = nil;
  1179. [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
  1180. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
  1181. dispatch_async(dispatch_get_main_queue(), ^{
  1182. if (error) {
  1183. if (notification) {
  1184. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1185. }
  1186. completion(nil, nil);
  1187. } else {
  1188. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1189. if (attributes[NSFileModificationDate]) {
  1190. newMetadata.date = attributes[NSFileModificationDate];
  1191. }
  1192. newMetadata.size = [attributes[NSFileSize] longValue];
  1193. completion(newMetadata, fileNamePath);
  1194. }
  1195. });
  1196. }
  1197. }];
  1198. }
  1199. }
  1200. #pragma --------------------------------------------------------------------------------------------
  1201. #pragma mark ===== E2E Encrypted =====
  1202. #pragma --------------------------------------------------------------------------------------------
  1203. + (NSString *)generateRandomIdentifier
  1204. {
  1205. NSString *UUID = [[NSUUID UUID] UUIDString];
  1206. return [[UUID stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
  1207. }
  1208. + (BOOL)isFolderEncrypted:(NSString *)serverUrl e2eEncrypted:(BOOL)e2eEncrypted account:(NSString *)account
  1209. {
  1210. if (e2eEncrypted) {
  1211. return true;
  1212. } else {
  1213. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1214. while (directory != nil) {
  1215. if (directory.e2eEncrypted == true) {
  1216. return true;
  1217. }
  1218. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  1219. directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1220. }
  1221. return false;
  1222. }
  1223. }
  1224. #pragma --------------------------------------------------------------------------------------------
  1225. #pragma mark ===== Third parts =====
  1226. #pragma --------------------------------------------------------------------------------------------
  1227. + (NSString *)stringValueForKey:(id)key conDictionary:(NSDictionary *)dictionary
  1228. {
  1229. id obj = [dictionary objectForKey:key];
  1230. if ([obj isEqual:[NSNull null]]) return @"";
  1231. if ([obj isKindOfClass:[NSString class]]) {
  1232. return obj;
  1233. }
  1234. else if ([obj isKindOfClass:[NSNumber class]]) {
  1235. return [obj stringValue];
  1236. }
  1237. else {
  1238. return [obj description];
  1239. }
  1240. }
  1241. + (NSString *)currentDevice
  1242. {
  1243. struct utsname systemInfo;
  1244. uname(&systemInfo);
  1245. NSString *deviceName=[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  1246. //NSLog(@"[LOG] Device Name :%@",deviceName);
  1247. return deviceName;
  1248. }
  1249. + (NSString *)getExtension:(NSString*)fileName
  1250. {
  1251. NSMutableArray *fileNameArray =[[NSMutableArray alloc] initWithArray: [fileName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]]];
  1252. NSString *extension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1253. extension = [extension uppercaseString];
  1254. //If the file has a ZIP extension obtain the previous one for check if it is a .pages.zip / .numbers.zip / .key.zip extension
  1255. if ([extension isEqualToString:@"ZIP"]) {
  1256. [fileNameArray removeLastObject];
  1257. NSString *secondExtension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1258. secondExtension = [secondExtension uppercaseString];
  1259. if ([secondExtension isEqualToString:@"PAGES"] || [secondExtension isEqualToString:@"NUMBERS"] || [secondExtension isEqualToString:@"KEY"]) {
  1260. extension = [NSString stringWithFormat:@"%@.%@",secondExtension,extension];
  1261. return extension;
  1262. }
  1263. }
  1264. return extension;
  1265. }
  1266. /*
  1267. * Util method to make a NSDate object from a string from xml
  1268. * @dateString -> Data string from xml
  1269. */
  1270. + (NSDate*)parseDateString:(NSString*)dateString
  1271. {
  1272. //Parse the date in all the formats
  1273. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1274. /*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.*/
  1275. [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
  1276. //This is the format for the concret locale used
  1277. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  1278. NSDate *theDate = nil;
  1279. NSError *error = nil;
  1280. if (![dateFormatter getObjectValue:&theDate forString:dateString range:nil error:&error]) {
  1281. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  1282. }
  1283. return theDate;
  1284. }
  1285. + (NSDate *)datetimeWithOutTime:(NSDate *)datDate
  1286. {
  1287. if (datDate == nil) return nil;
  1288. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:datDate];
  1289. datDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
  1290. return datDate;
  1291. }
  1292. + (NSDate *)datetimeWithOutDate:(NSDate *)datDate
  1293. {
  1294. if (datDate == nil) return nil;
  1295. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:datDate];
  1296. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  1297. }
  1298. + (BOOL)isValidEmail:(NSString *)checkString
  1299. {
  1300. checkString = [checkString lowercaseString];
  1301. BOOL stricterFilter = YES;
  1302. NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  1303. NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
  1304. NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  1305. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  1306. return [emailTest evaluateWithObject:checkString];
  1307. }
  1308. + (NSString *)URLEncodeStringFromString:(NSString *)string
  1309. {
  1310. static CFStringRef charset = CFSTR("!@#$%&*()+'\";:=,/?[] ");
  1311. CFStringRef str = (__bridge CFStringRef)string;
  1312. CFStringEncoding encoding = kCFStringEncodingUTF8;
  1313. return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, str, NULL, charset, encoding));
  1314. }
  1315. + (NSString*)hexRepresentation:(NSData *)data spaces:(BOOL)spaces
  1316. {
  1317. const unsigned char* bytes = (const unsigned char*)[data bytes];
  1318. NSUInteger nbBytes = [data length];
  1319. //If spaces is true, insert a space every this many input bytes (twice this many output characters).
  1320. static const NSUInteger spaceEveryThisManyBytes = 4UL;
  1321. //If spaces is true, insert a line-break instead of a space every this many spaces.
  1322. static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
  1323. const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
  1324. NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);
  1325. NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
  1326. for(NSUInteger i=0; i<nbBytes; ) {
  1327. [hex appendFormat:@"%02X", bytes[i]];
  1328. //We need to increment here so that the every-n-bytes computations are right.
  1329. ++i;
  1330. if (spaces) {
  1331. if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
  1332. else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
  1333. }
  1334. }
  1335. return hex;
  1336. }
  1337. + (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems
  1338. {
  1339. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
  1340. NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject];
  1341. return queryItem.value;
  1342. }
  1343. @end