CCUtility.m 68 KB

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