CCUtility.m 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. //
  2. // CCUtility.m
  3. // Nextcloud
  4. //
  5. // Created by Marino Faggiana on 02/02/16.
  6. // Copyright (c) 2017 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. }
  1142. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:fileName];
  1143. [[NSFileManager defaultManager]removeItemAtPath:fileNamePath error:nil];
  1144. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  1145. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1146. if (attributes[NSFileModificationDate]) {
  1147. newMetadata.date = attributes[NSFileModificationDate];
  1148. }
  1149. newMetadata.size = [attributes[NSFileSize] longValue];
  1150. if (newMetadata.e2eEncrypted) {
  1151. newMetadata.fileNameView = fileName;
  1152. } else {
  1153. newMetadata.fileNameView = fileName;
  1154. newMetadata.fileName = fileName;
  1155. }
  1156. completion(newMetadata, fileNamePath);
  1157. }];
  1158. }
  1159. // VIDEO
  1160. if (asset.mediaType == PHAssetMediaTypeVideo) {
  1161. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  1162. options.networkAccessAllowed = YES;
  1163. options.version = PHVideoRequestOptionsVersionOriginal;
  1164. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1165. NSLog(@"cacheAsset: %f", progress);
  1166. if (error) {
  1167. if (notification) {
  1168. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1169. }
  1170. completion(nil, nil);
  1171. }
  1172. };
  1173. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  1174. if ([asset isKindOfClass:[AVURLAsset class]]) {
  1175. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:newMetadata.fileNameView];
  1176. NSURL *fileNamePathURL = [[NSURL alloc] initFileURLWithPath:fileNamePath];
  1177. NSError *error = nil;
  1178. [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
  1179. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
  1180. dispatch_async(dispatch_get_main_queue(), ^{
  1181. if (error) {
  1182. if (notification) {
  1183. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1184. }
  1185. completion(nil, nil);
  1186. } else {
  1187. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1188. if (attributes[NSFileModificationDate]) {
  1189. newMetadata.date = attributes[NSFileModificationDate];
  1190. }
  1191. newMetadata.size = [attributes[NSFileSize] longValue];
  1192. completion(newMetadata, fileNamePath);
  1193. }
  1194. });
  1195. }
  1196. }];
  1197. }
  1198. }
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. #pragma mark ===== E2E Encrypted =====
  1201. #pragma --------------------------------------------------------------------------------------------
  1202. + (NSString *)generateRandomIdentifier
  1203. {
  1204. NSString *UUID = [[NSUUID UUID] UUIDString];
  1205. return [[UUID stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
  1206. }
  1207. + (BOOL)isFolderEncrypted:(NSString *)serverUrl e2eEncrypted:(BOOL)e2eEncrypted account:(NSString *)account
  1208. {
  1209. if (e2eEncrypted) {
  1210. return true;
  1211. } else {
  1212. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1213. while (directory != nil) {
  1214. if (directory.e2eEncrypted == true) {
  1215. return true;
  1216. }
  1217. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  1218. directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1219. }
  1220. return false;
  1221. }
  1222. }
  1223. #pragma --------------------------------------------------------------------------------------------
  1224. #pragma mark ===== Third parts =====
  1225. #pragma --------------------------------------------------------------------------------------------
  1226. + (NSString *)stringValueForKey:(id)key conDictionary:(NSDictionary *)dictionary
  1227. {
  1228. id obj = [dictionary objectForKey:key];
  1229. if ([obj isEqual:[NSNull null]]) return @"";
  1230. if ([obj isKindOfClass:[NSString class]]) {
  1231. return obj;
  1232. }
  1233. else if ([obj isKindOfClass:[NSNumber class]]) {
  1234. return [obj stringValue];
  1235. }
  1236. else {
  1237. return [obj description];
  1238. }
  1239. }
  1240. + (NSString *)currentDevice
  1241. {
  1242. struct utsname systemInfo;
  1243. uname(&systemInfo);
  1244. NSString *deviceName=[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  1245. //NSLog(@"[LOG] Device Name :%@",deviceName);
  1246. return deviceName;
  1247. }
  1248. + (NSString *)getExtension:(NSString*)fileName
  1249. {
  1250. NSMutableArray *fileNameArray =[[NSMutableArray alloc] initWithArray: [fileName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]]];
  1251. NSString *extension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1252. extension = [extension uppercaseString];
  1253. //If the file has a ZIP extension obtain the previous one for check if it is a .pages.zip / .numbers.zip / .key.zip extension
  1254. if ([extension isEqualToString:@"ZIP"]) {
  1255. [fileNameArray removeLastObject];
  1256. NSString *secondExtension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1257. secondExtension = [secondExtension uppercaseString];
  1258. if ([secondExtension isEqualToString:@"PAGES"] || [secondExtension isEqualToString:@"NUMBERS"] || [secondExtension isEqualToString:@"KEY"]) {
  1259. extension = [NSString stringWithFormat:@"%@.%@",secondExtension,extension];
  1260. return extension;
  1261. }
  1262. }
  1263. return extension;
  1264. }
  1265. /*
  1266. * Util method to make a NSDate object from a string from xml
  1267. * @dateString -> Data string from xml
  1268. */
  1269. + (NSDate*)parseDateString:(NSString*)dateString
  1270. {
  1271. //Parse the date in all the formats
  1272. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1273. /*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.*/
  1274. [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
  1275. //This is the format for the concret locale used
  1276. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  1277. NSDate *theDate = nil;
  1278. NSError *error = nil;
  1279. if (![dateFormatter getObjectValue:&theDate forString:dateString range:nil error:&error]) {
  1280. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  1281. }
  1282. return theDate;
  1283. }
  1284. + (NSDate *)datetimeWithOutTime:(NSDate *)datDate
  1285. {
  1286. if (datDate == nil) return nil;
  1287. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:datDate];
  1288. datDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
  1289. return datDate;
  1290. }
  1291. + (NSDate *)datetimeWithOutDate:(NSDate *)datDate
  1292. {
  1293. if (datDate == nil) return nil;
  1294. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:datDate];
  1295. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  1296. }
  1297. + (BOOL)isValidEmail:(NSString *)checkString
  1298. {
  1299. checkString = [checkString lowercaseString];
  1300. BOOL stricterFilter = YES;
  1301. NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  1302. NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
  1303. NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  1304. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  1305. return [emailTest evaluateWithObject:checkString];
  1306. }
  1307. + (NSString *)URLEncodeStringFromString:(NSString *)string
  1308. {
  1309. static CFStringRef charset = CFSTR("!@#$%&*()+'\";:=,/?[] ");
  1310. CFStringRef str = (__bridge CFStringRef)string;
  1311. CFStringEncoding encoding = kCFStringEncodingUTF8;
  1312. return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, str, NULL, charset, encoding));
  1313. }
  1314. + (NSString*)hexRepresentation:(NSData *)data spaces:(BOOL)spaces
  1315. {
  1316. const unsigned char* bytes = (const unsigned char*)[data bytes];
  1317. NSUInteger nbBytes = [data length];
  1318. //If spaces is true, insert a space every this many input bytes (twice this many output characters).
  1319. static const NSUInteger spaceEveryThisManyBytes = 4UL;
  1320. //If spaces is true, insert a line-break instead of a space every this many spaces.
  1321. static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
  1322. const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
  1323. NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);
  1324. NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
  1325. for(NSUInteger i=0; i<nbBytes; ) {
  1326. [hex appendFormat:@"%02X", bytes[i]];
  1327. //We need to increment here so that the every-n-bytes computations are right.
  1328. ++i;
  1329. if (spaces) {
  1330. if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
  1331. else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
  1332. }
  1333. }
  1334. return hex;
  1335. }
  1336. + (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems
  1337. {
  1338. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
  1339. NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject];
  1340. return queryItem.value;
  1341. }
  1342. @end