CCUtility.m 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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. NSString *sDisable = [UICKeyChainStore stringForKey:@"darkMode" service:k_serviceShareKeyChain];
  512. if(!sDisable){
  513. if (@available(iOS 13.0, *)) {
  514. if ([CCUtility getDarkModeDetect]) {
  515. if ([[UITraitCollection currentTraitCollection] userInterfaceStyle] == UIUserInterfaceStyleDark) {
  516. sDisable = @"YES";
  517. [CCUtility setDarkMode:YES];
  518. } else {
  519. sDisable = @"NO";
  520. [CCUtility setDarkMode:NO];
  521. }
  522. }
  523. }
  524. }
  525. return [sDisable boolValue];
  526. }
  527. + (void)setDarkMode:(BOOL)disable
  528. {
  529. NSString *sDisable = (disable) ? @"true" : @"false";
  530. [UICKeyChainStore setString:sDisable forKey:@"darkMode" service:k_serviceShareKeyChain];
  531. }
  532. + (BOOL)getDarkModeDetect
  533. {
  534. NSString *valueString = [UICKeyChainStore stringForKey:@"darkModeDetect" service:k_serviceShareKeyChain];
  535. // Default TRUE
  536. if (valueString == nil) {
  537. [self setDarkModeDetect:YES];
  538. return true;
  539. }
  540. return [valueString boolValue];
  541. }
  542. + (void)setDarkModeDetect:(BOOL)disable
  543. {
  544. NSString *sDisable = (disable) ? @"true" : @"false";
  545. [UICKeyChainStore setString:sDisable forKey:@"darkModeDetect" service:k_serviceShareKeyChain];
  546. }
  547. + (BOOL)getLivePhoto
  548. {
  549. NSString *valueString = [UICKeyChainStore stringForKey:@"livePhoto" service:k_serviceShareKeyChain];
  550. // Default TRUE
  551. if (valueString == nil) {
  552. [self setLivePhoto:YES];
  553. return true;
  554. }
  555. return [valueString boolValue];
  556. }
  557. + (void)setLivePhoto:(BOOL)set
  558. {
  559. NSString *sSet = (set) ? @"true" : @"false";
  560. [UICKeyChainStore setString:sSet forKey:@"livePhoto" service:k_serviceShareKeyChain];
  561. }
  562. #pragma --------------------------------------------------------------------------------------------
  563. #pragma mark ===== Various =====
  564. #pragma --------------------------------------------------------------------------------------------
  565. + (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
  566. {
  567. assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
  568. NSError *error = nil;
  569. BOOL success = [URL setResourceValue:[NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error];
  570. if(!success){
  571. NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
  572. }
  573. return success;
  574. }
  575. + (NSString *)getUserAgent
  576. {
  577. NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  578. NSString *userAgent = [[NCBrandOptions sharedInstance] userAgent];
  579. return [NSString stringWithFormat:@"Mozilla/5.0 (iOS) %@/%@", userAgent, appVersion];
  580. }
  581. + (NSString *)dateDiff:(NSDate *) convertedDate
  582. {
  583. NSDate *todayDate = [NSDate date];
  584. double ti = [convertedDate timeIntervalSinceDate:todayDate];
  585. ti = ti * -1;
  586. if (ti < 60) {
  587. // This minute
  588. return NSLocalizedString(@"_less_a_minute_", nil);
  589. } else if (ti < 3600) {
  590. // This hour
  591. int diff = round(ti / 60);
  592. return [NSString stringWithFormat:NSLocalizedString(@"_minutes_ago_", nil), diff];
  593. } else if (ti < 86400) {
  594. // This day
  595. int diff = round(ti / 60 / 60);
  596. return[NSString stringWithFormat:NSLocalizedString(@"_hours_ago_", nil), diff];
  597. } else if (ti < 86400 * 30) {
  598. // This month
  599. int diff = round(ti / 60 / 60 / 24);
  600. return[NSString stringWithFormat:NSLocalizedString(@"_days_ago_", nil), diff];
  601. } else {
  602. // Older than one month
  603. NSDateFormatter *df = [[NSDateFormatter alloc] init];
  604. [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  605. [df setDateStyle:NSDateFormatterMediumStyle];
  606. return [df stringFromDate:convertedDate];
  607. }
  608. }
  609. + (NSDate *)dateEnUsPosixFromCloud:(NSString *)dateString
  610. {
  611. NSDate *date = [NSDate date];
  612. NSError *error;
  613. NSDateFormatter *dateFormatter = [NSDateFormatter new];
  614. NSLocale *enUSPOSIXLocale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
  615. [dateFormatter setLocale:enUSPOSIXLocale];
  616. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  617. if (![dateFormatter getObjectValue:&date forString:dateString range:nil error:&error]) {
  618. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  619. date = [NSDate date];
  620. }
  621. return date;
  622. }
  623. + (NSString *)transformedSize:(double)value
  624. {
  625. NSString *string = [NSByteCountFormatter stringFromByteCount:value countStyle:NSByteCountFormatterCountStyleBinary];
  626. return string;
  627. }
  628. // Remove do not forbidden characters for Nextcloud Server
  629. + (NSString *)removeForbiddenCharactersServer:(NSString *)fileName
  630. {
  631. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"/", nil];
  632. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  633. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  634. }
  635. return fileName;
  636. }
  637. // Remove do not forbidden characters for File System Server
  638. + (NSString *)removeForbiddenCharactersFileSystem:(NSString *)fileName
  639. {
  640. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"\\",@"<",@">",@":",@"\"",@"|",@"?",@"*",@"/", nil];
  641. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  642. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  643. }
  644. return fileName;
  645. }
  646. + (NSString*)stringAppendServerUrl:(NSString *)serverUrl addFileName:(NSString *)addFileName
  647. {
  648. NSString *result;
  649. if (serverUrl == nil || addFileName == nil) return nil;
  650. if ([addFileName isEqualToString:@""]) return serverUrl;
  651. if ([serverUrl isEqualToString:@"/"]) result = [serverUrl stringByAppendingString:addFileName];
  652. else result = [NSString stringWithFormat:@"%@/%@", serverUrl, addFileName];
  653. return result;
  654. }
  655. + (NSString *)createRandomString:(int)numChars
  656. {
  657. NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  658. NSMutableString *randomString = [NSMutableString stringWithCapacity: numChars];
  659. for (int i=0; i < numChars; i++) {
  660. [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((unsigned int)[letters length]) % [letters length]]];
  661. }
  662. return [NSString stringWithFormat:@"%@", randomString];
  663. }
  664. + (NSString *)createFileNameDate:(NSString *)fileName extension:(NSString *)extension
  665. {
  666. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  667. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  668. NSString *fileNameDate = [formatter stringFromDate:[NSDate date]];
  669. NSString *returnFileName;
  670. if ([fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  671. returnFileName = [NSString stringWithFormat:@"%@.%@", fileNameDate, extension];
  672. }
  673. if (![fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  674. returnFileName = [NSString stringWithFormat:@"%@ %@", fileName, fileNameDate];
  675. }
  676. if ([fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  677. returnFileName = fileNameDate;
  678. }
  679. if (![fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  680. returnFileName = [NSString stringWithFormat:@"%@ %@.%@", fileName, fileNameDate, extension];
  681. }
  682. return returnFileName;
  683. }
  684. + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fileType:(PHAssetMediaType)fileType keyFileName:(NSString *)keyFileName keyFileNameType:(NSString *)keyFileNameType keyFileNameOriginal:(NSString *)keyFileNameOriginal
  685. {
  686. BOOL addFileNameType = NO;
  687. // Original FileName ?
  688. if ([self getOriginalFileName:keyFileNameOriginal]) {
  689. return fileName;
  690. }
  691. NSString *numberFileName;
  692. if ([fileName length] > 8) numberFileName = [fileName substringWithRange:NSMakeRange(04, 04)];
  693. else numberFileName = [CCUtility getIncrementalNumber];
  694. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  695. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  696. NSString *fileNameDate = [formatter stringFromDate:fileDate];
  697. NSString *fileNameType = @"";
  698. if (fileType == PHAssetMediaTypeImage)
  699. fileNameType = NSLocalizedString(@"_photo_", nil);
  700. if (fileType == PHAssetMediaTypeVideo)
  701. fileNameType = NSLocalizedString(@"_video_", nil);
  702. if (fileType == PHAssetMediaTypeAudio)
  703. fileNameType = NSLocalizedString(@"_audio_", nil);
  704. if (fileType == PHAssetMediaTypeUnknown)
  705. fileNameType = NSLocalizedString(@"_unknown_", nil);
  706. // Use File Name Type
  707. if (keyFileNameType)
  708. addFileNameType = [CCUtility getFileNameType:keyFileNameType];
  709. NSString *fileNameExt = [[fileName pathExtension] lowercaseString];
  710. if (keyFileName) {
  711. fileName = [CCUtility getFileNameMask:keyFileName];
  712. if ([fileName length] > 0) {
  713. [formatter setDateFormat:@"dd"];
  714. NSString *dayNumber = [formatter stringFromDate:fileDate];
  715. [formatter setDateFormat:@"MMM"];
  716. NSString *month = [formatter stringFromDate:fileDate];
  717. [formatter setDateFormat:@"MM"];
  718. NSString *monthNumber = [formatter stringFromDate:fileDate];
  719. [formatter setDateFormat:@"yyyy"];
  720. NSString *year = [formatter stringFromDate:fileDate];
  721. [formatter setDateFormat:@"yy"];
  722. NSString *yearNumber = [formatter stringFromDate:fileDate];
  723. [formatter setDateFormat:@"HH"];
  724. NSString *hour24 = [formatter stringFromDate:fileDate];
  725. [formatter setDateFormat:@"hh"];
  726. NSString *hour12 = [formatter stringFromDate:fileDate];
  727. [formatter setDateFormat:@"mm"];
  728. NSString *minute = [formatter stringFromDate:fileDate];
  729. [formatter setDateFormat:@"ss"];
  730. NSString *second = [formatter stringFromDate:fileDate];
  731. [formatter setDateFormat:@"a"];
  732. NSString *ampm = [formatter stringFromDate:fileDate];
  733. // Replace string with date
  734. fileName = [fileName stringByReplacingOccurrencesOfString:@"DD" withString:dayNumber];
  735. fileName = [fileName stringByReplacingOccurrencesOfString:@"MMM" withString:month];
  736. fileName = [fileName stringByReplacingOccurrencesOfString:@"MM" withString:monthNumber];
  737. fileName = [fileName stringByReplacingOccurrencesOfString:@"YYYY" withString:year];
  738. fileName = [fileName stringByReplacingOccurrencesOfString:@"YY" withString:yearNumber];
  739. fileName = [fileName stringByReplacingOccurrencesOfString:@"HH" withString:hour24];
  740. fileName = [fileName stringByReplacingOccurrencesOfString:@"hh" withString:hour12];
  741. fileName = [fileName stringByReplacingOccurrencesOfString:@"mm" withString:minute];
  742. fileName = [fileName stringByReplacingOccurrencesOfString:@"ss" withString:second];
  743. fileName = [fileName stringByReplacingOccurrencesOfString:@"ampm" withString:ampm];
  744. if (addFileNameType)
  745. fileName = [NSString stringWithFormat:@"%@%@%@.%@", fileNameType, fileName, numberFileName, fileNameExt];
  746. else
  747. fileName = [NSString stringWithFormat:@"%@%@.%@", fileName, numberFileName, fileNameExt];
  748. fileName = [fileName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  749. } else {
  750. if (addFileNameType)
  751. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  752. else
  753. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  754. }
  755. } else {
  756. if (addFileNameType)
  757. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  758. else
  759. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  760. }
  761. return fileName;
  762. }
  763. + (void)createDirectoryStandard
  764. {
  765. NSString *path;
  766. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  767. NSLog(@"[LOG] Dir Group");
  768. NSLog(@"%@", [dirGroup path]);
  769. NSLog(@"[LOG] Program application ");
  770. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  771. // create Directory Documents
  772. path = [CCUtility getDirectoryDocuments];
  773. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  774. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  775. // create Directory audio => Library, Application Support, audio
  776. path = [CCUtility getDirectoryAudio];
  777. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  778. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  779. // create Directory database Nextcloud
  780. path = [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path];
  781. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  782. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  783. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  784. // create Directory User Data
  785. path = [[dirGroup URLByAppendingPathComponent:k_appUserData] path];
  786. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  787. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  788. // create Directory Provider Storage
  789. path = [CCUtility getDirectoryProviderStorage];
  790. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  791. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  792. // create Directory Scan
  793. path = [[dirGroup URLByAppendingPathComponent:k_appScan] path];
  794. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  795. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  796. // create Directory Temp
  797. path = NSTemporaryDirectory();
  798. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  799. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  800. // Directory Excluded From Backup
  801. [CCUtility addSkipBackupAttributeToItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];
  802. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_DirectoryProviderStorage]];
  803. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appUserData]];
  804. #ifdef DEBUG
  805. NSLog(@"[LOG] Copy DB on Documents directory");
  806. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:k_appDatabaseNextcloud] path]];
  807. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  808. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  809. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  810. #endif
  811. }
  812. + (NSURL *)getDirectoryGroup
  813. {
  814. NSURL *path = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions sharedInstance].capabilitiesGroups];
  815. return path;
  816. }
  817. + (NSString *)getHomeServerUrlActiveUrl:(NSString *)activeUrl
  818. {
  819. if (activeUrl == nil)
  820. return @"";
  821. return [activeUrl stringByAppendingString:k_webDAV];
  822. }
  823. + (NSString *)getStringUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  824. {
  825. NSString *baseUrl = [activeUrl lowercaseString];
  826. NSString *dirUserBaseUrl = @"";
  827. if ([activeUser length] && [baseUrl length]) {
  828. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  829. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  830. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", activeUser, baseUrl];
  831. dirUserBaseUrl = [[self removeForbiddenCharactersFileSystem:dirUserBaseUrl] lowercaseString];
  832. }
  833. return dirUserBaseUrl;
  834. }
  835. // Return path of User
  836. + (NSString *)getDirectoryActiveUser:(NSString *)activeUser activeUrl:(NSString *)activeUrl
  837. {
  838. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  839. NSString *user = activeUser;
  840. NSString *baseUrl = [activeUrl lowercaseString];
  841. NSString *dirUserBaseUrl = nil;
  842. NSString *dirApplicationUserGroup = nil;
  843. if ([user length] && [baseUrl length]) {
  844. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  845. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  846. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", user, baseUrl];
  847. dirUserBaseUrl = [[self removeForbiddenCharactersFileSystem:dirUserBaseUrl] lowercaseString];
  848. } else return @"";
  849. dirApplicationUserGroup = [[dirGroup URLByAppendingPathComponent:k_appApplicationSupport] path];
  850. dirUserBaseUrl = [NSString stringWithFormat:@"%@/%@", dirApplicationUserGroup, dirUserBaseUrl];
  851. if (![[NSFileManager defaultManager] fileExistsAtPath: dirUserBaseUrl]) {
  852. [[NSFileManager defaultManager] createDirectoryAtPath:dirUserBaseUrl withIntermediateDirectories:YES attributes:nil error:nil];
  853. }
  854. return dirUserBaseUrl;
  855. }
  856. // Return the path of directory Documents -> NSDocumentDirectory
  857. + (NSString *)getDirectoryDocuments
  858. {
  859. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  860. return [paths objectAtIndex:0];
  861. }
  862. + (NSString *)getDirectoryReaderMetadata
  863. {
  864. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  865. return [NSString stringWithFormat:@"%@/Reader Metadata", [paths objectAtIndex:0]];
  866. }
  867. // Return the path of directory Audio
  868. + (NSString *)getDirectoryAudio
  869. {
  870. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  871. return [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"audio"];
  872. }
  873. // Return the path of directory Cetificates
  874. + (NSString *)getDirectoryCerificates
  875. {
  876. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appCertificates] path];
  877. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  878. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  879. return path;
  880. }
  881. + (NSString *)getDirectoryUserData
  882. {
  883. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appUserData] path];
  884. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  885. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  886. return path;
  887. }
  888. + (NSString *)getDirectoryProviderStorage
  889. {
  890. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_DirectoryProviderStorage] path];
  891. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  892. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  893. return path;
  894. }
  895. + (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId
  896. {
  897. NSString *path = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorage], ocId];
  898. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  899. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  900. return path;
  901. }
  902. + (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView
  903. {
  904. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorageOcId:ocId], fileNameView];
  905. // if do not exists create file 0 length
  906. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath] == NO) {
  907. [[NSFileManager defaultManager] createFileAtPath:fileNamePath contents:nil attributes:nil];
  908. }
  909. return fileNamePath;
  910. }
  911. + (NSString *)getDirectoryProviderStorageIconOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView
  912. {
  913. return [NSString stringWithFormat:@"%@/%@.ico", [self getDirectoryProviderStorageOcId:ocId], fileNameView];
  914. }
  915. + (BOOL)fileProviderStorageExists:(NSString *)ocId fileNameView:(NSString *)fileNameView
  916. {
  917. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  918. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  919. if (fileSize > 0) return true;
  920. else return false;
  921. }
  922. + (double)fileProviderStorageSize:(NSString *)ocId fileNameView:(NSString *)fileNameView
  923. {
  924. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  925. double fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  926. return fileSize;
  927. }
  928. + (BOOL)fileProviderStorageIconExists:(NSString *)ocId fileNameView:(NSString *)fileNameView
  929. {
  930. NSString *fileNamePath = [self getDirectoryProviderStorageIconOcId:ocId fileNameView:fileNameView];
  931. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  932. if (fileSize > 0) return true;
  933. else return false;
  934. }
  935. + (void)removeGroupApplicationSupport
  936. {
  937. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  938. NSString *path = [[dirGroup URLByAppendingPathComponent:k_appApplicationSupport] path];
  939. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  940. }
  941. + (void)removeGroupLibraryDirectory
  942. {
  943. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryScan] error:nil];
  944. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryUserData] error:nil];
  945. }
  946. + (void)removeGroupDirectoryProviderStorage
  947. {
  948. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorage] error:nil];
  949. }
  950. + (void)removeDocumentsDirectory
  951. {
  952. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryDocuments] error:nil];
  953. }
  954. + (void)removeTemporaryDirectory
  955. {
  956. [[NSFileManager defaultManager] removeItemAtPath:NSTemporaryDirectory() error:nil];
  957. }
  958. + (void)emptyTemporaryDirectory
  959. {
  960. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  961. for (NSString *file in tmpDirectory) {
  962. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  963. }
  964. }
  965. + (NSString *)getTitleSectionDate:(NSDate *)date
  966. {
  967. NSString *title;
  968. NSDate *today = [NSDate date];
  969. NSDate *yesterday = [today dateByAddingTimeInterval: -86400.0];
  970. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:[NSDate distantPast]]]) {
  971. title = NSLocalizedString(@"_no_date_", nil);
  972. } else {
  973. title = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterFullStyle timeStyle:0];
  974. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:today]])
  975. title = [NSString stringWithFormat:NSLocalizedString(@"_today_", nil)];
  976. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:yesterday]])
  977. title = [NSString stringWithFormat:NSLocalizedString(@"_yesterday_", nil)];
  978. }
  979. return title;
  980. }
  981. + (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  982. {
  983. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  984. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  985. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  986. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  987. }
  988. }
  989. + (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  990. {
  991. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  992. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  993. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  994. }
  995. }
  996. + (void)removeFileAtPath:(NSString *)atPath
  997. {
  998. if ([[NSFileManager defaultManager] fileExistsAtPath:atPath]) {
  999. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  1000. }
  1001. }
  1002. + (void)createDirectoryAtPath:(NSString *)atPath
  1003. {
  1004. [[NSFileManager defaultManager] createDirectoryAtPath:atPath withIntermediateDirectories:true attributes:nil error:nil];
  1005. }
  1006. + (NSString *)deletingLastPathComponentFromServerUrl:(NSString *)serverUrl
  1007. {
  1008. NSURL *url = [[NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]] URLByDeletingLastPathComponent];
  1009. NSString *pather = [[url absoluteString] stringByRemovingPercentEncoding];
  1010. return [pather substringToIndex: [pather length] - 1];
  1011. }
  1012. + (NSString *)firtsPathComponentFromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1013. {
  1014. NSString *firstPath = serverUrl;
  1015. NSURL *serverUrlURL = [NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  1016. NSURL *activeUrlURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@/", [activeUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]], k_webDAV]];
  1017. while ([[serverUrlURL absoluteString] isEqualToString:[activeUrlURL absoluteString]] == false) {
  1018. firstPath = [serverUrlURL absoluteString];
  1019. serverUrlURL = [serverUrlURL URLByDeletingLastPathComponent];
  1020. }
  1021. if ([firstPath hasSuffix:@"/"]) firstPath = [firstPath substringToIndex:[firstPath length] - 1];
  1022. return firstPath;
  1023. }
  1024. + (NSString *)getLastPathFromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1025. {
  1026. if ([serverUrl isEqualToString:activeUrl])
  1027. return @"";
  1028. NSURL *serverUrlURL = [NSURL URLWithString:[serverUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]];
  1029. NSString *fileName = [serverUrlURL lastPathComponent];
  1030. return fileName;
  1031. }
  1032. + (NSString *)returnPathfromServerUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1033. {
  1034. NSString *path = [serverUrl stringByReplacingOccurrencesOfString:[activeUrl stringByAppendingString:k_webDAV] withString:@""];
  1035. return path;
  1036. }
  1037. + (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl activeUrl:(NSString *)activeUrl
  1038. {
  1039. if (metadataFileName == nil || serverUrl == nil || activeUrl == nil) {
  1040. return @"";
  1041. }
  1042. NSString *fileName = [NSString stringWithFormat:@"%@/%@", [serverUrl stringByReplacingOccurrencesOfString:[CCUtility getHomeServerUrlActiveUrl:activeUrl] withString:@""], metadataFileName];
  1043. if ([fileName hasPrefix:@"/"]) fileName = [fileName substringFromIndex:1];
  1044. return fileName;
  1045. }
  1046. + (NSArray *)createNameSubFolder:(PHFetchResult *)alassets
  1047. {
  1048. NSMutableOrderedSet *datesSubFolder = [NSMutableOrderedSet new];
  1049. for (PHAsset *asset in alassets) {
  1050. NSDate *assetDate = asset.creationDate;
  1051. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1052. [formatter setDateFormat:@"yyyy"];
  1053. NSString *yearString = [formatter stringFromDate:assetDate];
  1054. if (yearString)
  1055. [datesSubFolder addObject:yearString];
  1056. [formatter setDateFormat:@"MM"];
  1057. NSString *monthString = [formatter stringFromDate:assetDate];
  1058. monthString = [NSString stringWithFormat:@"%@/%@", yearString, monthString];
  1059. if (monthString)
  1060. [datesSubFolder addObject:monthString];
  1061. }
  1062. return (NSArray *)datesSubFolder;
  1063. }
  1064. + (NSString *)getMimeType:(NSString *)fileNameView
  1065. {
  1066. CFStringRef fileUTI = nil;
  1067. NSString *returnFileUTI = nil;
  1068. if ([fileNameView isEqualToString:@"."]) {
  1069. return returnFileUTI;
  1070. } else {
  1071. CFStringRef fileExtension = (__bridge CFStringRef)[fileNameView pathExtension];
  1072. NSString *ext = (__bridge NSString *)fileExtension;
  1073. ext = ext.uppercaseString;
  1074. fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  1075. if (fileUTI != nil) {
  1076. returnFileUTI = (__bridge NSString *)fileUTI;
  1077. CFRelease(fileUTI);
  1078. }
  1079. }
  1080. return returnFileUTI;
  1081. }
  1082. + (NSString *)getDirectoryScan
  1083. {
  1084. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:k_appScan] path];
  1085. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  1086. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  1087. return path;
  1088. }
  1089. + (void)writeData:(NSData *)data fileNamePath:(NSString *)fileNamePath
  1090. {
  1091. [data writeToFile:fileNamePath atomically:YES];
  1092. }
  1093. + (void)selectFileNameFrom:(UITextField *)textField
  1094. {
  1095. UITextPosition *endPosition;
  1096. NSRange rangeDot = [textField.text rangeOfString:@"." options:NSBackwardsSearch];
  1097. if (rangeDot.location != NSNotFound) {
  1098. endPosition = [textField positionFromPosition:textField.beginningOfDocument offset:rangeDot.location];
  1099. } else {
  1100. endPosition = textField.endOfDocument;
  1101. }
  1102. UITextRange *textRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:endPosition];
  1103. textField.selectedTextRange = textRange;
  1104. }
  1105. + (NSString *)getTimeIntervalSince197
  1106. {
  1107. return [NSString stringWithFormat:@"%f", [[NSDate date] timeIntervalSince1970]];
  1108. }
  1109. + (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadata notification:(BOOL)notification completion:(void(^)(tableMetadata *newMetadata, NSString* fileNamePath))completion
  1110. {
  1111. tableMetadata *newMetadata = [[NCManageDatabase sharedInstance] initNewMetadata:metadata];
  1112. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1113. if (!result.count) {
  1114. if (notification) {
  1115. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Error photo/video not found, remove from upload"}];
  1116. }
  1117. completion(nil, nil);
  1118. return;
  1119. }
  1120. PHAsset *asset = result[0];
  1121. NSDate *creationDate = asset.creationDate;
  1122. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", metadata.account]];
  1123. if (tableAccount == nil) {
  1124. if (notification) {
  1125. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(k_CCErrorInternalError), @"errorDescription": @"Upload error, account not found"}];
  1126. }
  1127. completion(nil, nil);
  1128. return;
  1129. }
  1130. // IMAGE
  1131. if (asset.mediaType == PHAssetMediaTypeImage) {
  1132. PHImageRequestOptions *options = [PHImageRequestOptions new];
  1133. options.networkAccessAllowed = YES; // iCloud
  1134. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  1135. options.synchronous = YES;
  1136. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1137. NSLog(@"cacheAsset: %f", progress);
  1138. if (error) {
  1139. if (notification) {
  1140. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description]}];
  1141. }
  1142. completion(nil, nil);
  1143. return;
  1144. }
  1145. };
  1146. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  1147. NSError *error = nil;
  1148. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  1149. NSString *fileName = metadata.fileNameView;
  1150. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  1151. CIImage *ciImage = [CIImage imageWithData:imageData];
  1152. CIContext *context = [CIContext context];
  1153. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  1154. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  1155. fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  1156. newMetadata.contentType = @"image/jpeg";
  1157. }
  1158. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:fileName];
  1159. [[NSFileManager defaultManager]removeItemAtPath:fileNamePath error:nil];
  1160. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  1161. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1162. newMetadata.creationDate = creationDate;
  1163. newMetadata.date = attributes[NSFileModificationDate];
  1164. newMetadata.size = [attributes[NSFileSize] longValue];
  1165. if (newMetadata.e2eEncrypted) {
  1166. newMetadata.fileNameView = fileName;
  1167. } else {
  1168. newMetadata.fileNameView = fileName;
  1169. newMetadata.fileName = fileName;
  1170. }
  1171. completion(newMetadata, fileNamePath);
  1172. }];
  1173. }
  1174. // VIDEO
  1175. if (asset.mediaType == PHAssetMediaTypeVideo) {
  1176. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  1177. options.networkAccessAllowed = YES;
  1178. options.version = PHVideoRequestOptionsVersionOriginal;
  1179. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1180. NSLog(@"cacheAsset: %f", progress);
  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. }
  1187. };
  1188. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  1189. if ([asset isKindOfClass:[AVURLAsset class]]) {
  1190. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:newMetadata.fileNameView];
  1191. NSURL *fileNamePathURL = [[NSURL alloc] initFileURLWithPath:fileNamePath];
  1192. NSError *error = nil;
  1193. [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
  1194. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
  1195. dispatch_async(dispatch_get_main_queue(), ^{
  1196. if (error) {
  1197. if (notification) {
  1198. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_notificationCenter_uploadedFile object:nil userInfo:@{@"metadata": metadata, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1199. }
  1200. completion(nil, nil);
  1201. } else {
  1202. NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil];
  1203. newMetadata.creationDate = creationDate;
  1204. if (attributes[NSFileModificationDate]) {
  1205. newMetadata.date = attributes[NSFileModificationDate];
  1206. }
  1207. newMetadata.size = [attributes[NSFileSize] longValue];
  1208. completion(newMetadata, fileNamePath);
  1209. }
  1210. });
  1211. }
  1212. }];
  1213. }
  1214. }
  1215. #pragma --------------------------------------------------------------------------------------------
  1216. #pragma mark ===== E2E Encrypted =====
  1217. #pragma --------------------------------------------------------------------------------------------
  1218. + (NSString *)generateRandomIdentifier
  1219. {
  1220. NSString *UUID = [[NSUUID UUID] UUIDString];
  1221. return [[UUID stringByReplacingOccurrencesOfString:@"-" withString:@""] lowercaseString];
  1222. }
  1223. + (BOOL)isFolderEncrypted:(NSString *)serverUrl e2eEncrypted:(BOOL)e2eEncrypted account:(NSString *)account
  1224. {
  1225. if (e2eEncrypted) {
  1226. return true;
  1227. } else {
  1228. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1229. while (directory != nil) {
  1230. if (directory.e2eEncrypted == true) {
  1231. return true;
  1232. }
  1233. serverUrl = [CCUtility deletingLastPathComponentFromServerUrl:serverUrl];
  1234. directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1235. }
  1236. return false;
  1237. }
  1238. }
  1239. #pragma --------------------------------------------------------------------------------------------
  1240. #pragma mark ===== Third parts =====
  1241. #pragma --------------------------------------------------------------------------------------------
  1242. + (NSString *)stringValueForKey:(id)key conDictionary:(NSDictionary *)dictionary
  1243. {
  1244. id obj = [dictionary objectForKey:key];
  1245. if ([obj isEqual:[NSNull null]]) return @"";
  1246. if ([obj isKindOfClass:[NSString class]]) {
  1247. return obj;
  1248. }
  1249. else if ([obj isKindOfClass:[NSNumber class]]) {
  1250. return [obj stringValue];
  1251. }
  1252. else {
  1253. return [obj description];
  1254. }
  1255. }
  1256. + (NSString *)currentDevice
  1257. {
  1258. struct utsname systemInfo;
  1259. uname(&systemInfo);
  1260. NSString *deviceName=[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
  1261. //NSLog(@"[LOG] Device Name :%@",deviceName);
  1262. return deviceName;
  1263. }
  1264. + (NSString *)getExtension:(NSString*)fileName
  1265. {
  1266. NSMutableArray *fileNameArray =[[NSMutableArray alloc] initWithArray: [fileName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]]];
  1267. NSString *extension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1268. extension = [extension uppercaseString];
  1269. //If the file has a ZIP extension obtain the previous one for check if it is a .pages.zip / .numbers.zip / .key.zip extension
  1270. if ([extension isEqualToString:@"ZIP"]) {
  1271. [fileNameArray removeLastObject];
  1272. NSString *secondExtension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1273. secondExtension = [secondExtension uppercaseString];
  1274. if ([secondExtension isEqualToString:@"PAGES"] || [secondExtension isEqualToString:@"NUMBERS"] || [secondExtension isEqualToString:@"KEY"]) {
  1275. extension = [NSString stringWithFormat:@"%@.%@",secondExtension,extension];
  1276. return extension;
  1277. }
  1278. }
  1279. return extension;
  1280. }
  1281. /*
  1282. * Util method to make a NSDate object from a string from xml
  1283. * @dateString -> Data string from xml
  1284. */
  1285. + (NSDate*)parseDateString:(NSString*)dateString
  1286. {
  1287. //Parse the date in all the formats
  1288. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1289. /*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.*/
  1290. [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
  1291. //This is the format for the concret locale used
  1292. [dateFormatter setDateFormat:@"EEE, dd MMM y HH:mm:ss zzz"];
  1293. NSDate *theDate = nil;
  1294. NSError *error = nil;
  1295. if (![dateFormatter getObjectValue:&theDate forString:dateString range:nil error:&error]) {
  1296. NSLog(@"[LOG] Date '%@' could not be parsed: %@", dateString, error);
  1297. }
  1298. return theDate;
  1299. }
  1300. + (NSDate *)datetimeWithOutTime:(NSDate *)datDate
  1301. {
  1302. if (datDate == nil) return nil;
  1303. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:datDate];
  1304. datDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
  1305. return datDate;
  1306. }
  1307. + (NSDate *)datetimeWithOutDate:(NSDate *)datDate
  1308. {
  1309. if (datDate == nil) return nil;
  1310. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:datDate];
  1311. return [[NSCalendar currentCalendar] dateFromComponents:comps];
  1312. }
  1313. + (BOOL)isValidEmail:(NSString *)checkString
  1314. {
  1315. checkString = [checkString lowercaseString];
  1316. BOOL stricterFilter = YES;
  1317. NSString *stricterFilterString = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
  1318. NSString *laxString = @".+@.+\\.[A-Za-z]{2}[A-Za-z]*";
  1319. NSString *emailRegex = stricterFilter ? stricterFilterString : laxString;
  1320. NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
  1321. return [emailTest evaluateWithObject:checkString];
  1322. }
  1323. + (NSString *)URLEncodeStringFromString:(NSString *)string
  1324. {
  1325. static CFStringRef charset = CFSTR("!@#$%&*()+'\";:=,/?[] ");
  1326. CFStringRef str = (__bridge CFStringRef)string;
  1327. CFStringEncoding encoding = kCFStringEncodingUTF8;
  1328. return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, str, NULL, charset, encoding));
  1329. }
  1330. + (NSString*)hexRepresentation:(NSData *)data spaces:(BOOL)spaces
  1331. {
  1332. const unsigned char* bytes = (const unsigned char*)[data bytes];
  1333. NSUInteger nbBytes = [data length];
  1334. //If spaces is true, insert a space every this many input bytes (twice this many output characters).
  1335. static const NSUInteger spaceEveryThisManyBytes = 4UL;
  1336. //If spaces is true, insert a line-break instead of a space every this many spaces.
  1337. static const NSUInteger lineBreakEveryThisManySpaces = 4UL;
  1338. const NSUInteger lineBreakEveryThisManyBytes = spaceEveryThisManyBytes * lineBreakEveryThisManySpaces;
  1339. NSUInteger strLen = 2*nbBytes + (spaces ? nbBytes/spaceEveryThisManyBytes : 0);
  1340. NSMutableString* hex = [[NSMutableString alloc] initWithCapacity:strLen];
  1341. for(NSUInteger i=0; i<nbBytes; ) {
  1342. [hex appendFormat:@"%02X", bytes[i]];
  1343. //We need to increment here so that the every-n-bytes computations are right.
  1344. ++i;
  1345. if (spaces) {
  1346. if (i % lineBreakEveryThisManyBytes == 0) [hex appendString:@"\n"];
  1347. else if (i % spaceEveryThisManyBytes == 0) [hex appendString:@" "];
  1348. }
  1349. }
  1350. return hex;
  1351. }
  1352. + (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems
  1353. {
  1354. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
  1355. NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject];
  1356. return queryItem.value;
  1357. }
  1358. @end