CCUtility.m 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879
  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 "NCBridgeSwift.h"
  25. #import "NSNotificationCenter+MainThread.h"
  26. #import <OpenSSL/OpenSSL.h>
  27. #import <CoreLocation/CoreLocation.h>
  28. #include <sys/stat.h>
  29. #define INTRO_MessageType @"MessageType_"
  30. #define E2E_certificate @"EndToEndCertificate_"
  31. #define E2E_PrivateKey @"EndToEndPrivateKey_"
  32. #define E2E_Passphrase @"EndToEndPassphrase_"
  33. #define E2E_PublicKey @"EndToEndPublicKeyServer_"
  34. @implementation CCUtility
  35. #pragma --------------------------------------------------------------------------------------------
  36. #pragma mark ======================= KeyChainStore ==================================
  37. #pragma --------------------------------------------------------------------------------------------
  38. + (void)deleteAllChainStore
  39. {
  40. [UICKeyChainStore removeAllItems];
  41. [UICKeyChainStore removeAllItemsForService:NCGlobal.shared.serviceShareKeyChain];
  42. }
  43. + (void)storeAllChainInService
  44. {
  45. UICKeyChainStore *store = [UICKeyChainStore keyChainStore];
  46. NSArray *items = store.allItems;
  47. for (NSDictionary *item in items) {
  48. [UICKeyChainStore setString:[item objectForKey:@"value"] forKey:[item objectForKey:@"key"] service:NCGlobal.shared.serviceShareKeyChain];
  49. [UICKeyChainStore removeItemForKey:[item objectForKey:@"key"]];
  50. }
  51. }
  52. #pragma ------------------------------ GET/SET
  53. + (NSString *)getPasscode
  54. {
  55. return [UICKeyChainStore stringForKey:@"passcodeBlock" service:NCGlobal.shared.serviceShareKeyChain];
  56. }
  57. + (void)setPasscode:(NSString *)passcode
  58. {
  59. [UICKeyChainStore setString:passcode forKey:@"passcodeBlock" service:NCGlobal.shared.serviceShareKeyChain];
  60. }
  61. + (BOOL)getNotPasscodeAtStart
  62. {
  63. return [[UICKeyChainStore stringForKey:@"notPasscodeAtStart" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  64. }
  65. + (void)setNotPasscodeAtStart:(BOOL)set
  66. {
  67. NSString *sSet = (set) ? @"true" : @"false";
  68. [UICKeyChainStore setString:sSet forKey:@"notPasscodeAtStart" service:NCGlobal.shared.serviceShareKeyChain];
  69. }
  70. + (BOOL)getEnableTouchFaceID
  71. {
  72. NSString *valueString = [UICKeyChainStore stringForKey:@"enableTouchFaceID" service:NCGlobal.shared.serviceShareKeyChain];
  73. // Default TRUE
  74. if (valueString == nil) {
  75. [self setEnableTouchFaceID:YES];
  76. return true;
  77. }
  78. return [valueString boolValue];
  79. }
  80. + (void)setEnableTouchFaceID:(BOOL)set
  81. {
  82. NSString *sSet = (set) ? @"true" : @"false";
  83. [UICKeyChainStore setString:sSet forKey:@"enableTouchFaceID" service:NCGlobal.shared.serviceShareKeyChain];
  84. }
  85. + (NSString *)getGroupBySettings
  86. {
  87. NSString *groupby = [UICKeyChainStore stringForKey:@"groupby" service:NCGlobal.shared.serviceShareKeyChain];
  88. if (groupby == nil) {
  89. [self setGroupBySettings:@"none"];
  90. return @"none";
  91. }
  92. return @"none";
  93. //return groupby;
  94. }
  95. + (void)setGroupBySettings:(NSString *)groupby
  96. {
  97. [UICKeyChainStore setString:groupby forKey:@"groupby" service:NCGlobal.shared.serviceShareKeyChain];
  98. }
  99. + (BOOL)getIntro
  100. {
  101. // Set compatibility old version don't touch me
  102. if ([[UICKeyChainStore stringForKey:[INTRO_MessageType stringByAppendingString:@"Intro"] service:NCGlobal.shared.serviceShareKeyChain] boolValue] == YES) {
  103. [CCUtility setIntro:YES];
  104. return YES;
  105. }
  106. return [[UICKeyChainStore stringForKey:@"intro" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  107. }
  108. + (BOOL)getIntroMessageOldVersion
  109. {
  110. NSString *key = [INTRO_MessageType stringByAppendingString:@"Intro"];
  111. return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  112. }
  113. + (void)setIntro:(BOOL)set
  114. {
  115. NSString *sIntro = (set) ? @"true" : @"false";
  116. [UICKeyChainStore setString:sIntro forKey:@"intro" service:NCGlobal.shared.serviceShareKeyChain];
  117. }
  118. + (NSString *)getIncrementalNumber
  119. {
  120. long number = [[UICKeyChainStore stringForKey:@"incrementalnumber" service:NCGlobal.shared.serviceShareKeyChain] intValue];
  121. number++;
  122. if (number >= 9999) number = 1;
  123. [UICKeyChainStore setString:[NSString stringWithFormat:@"%ld", number] forKey:@"incrementalnumber" service:NCGlobal.shared.serviceShareKeyChain];
  124. return [NSString stringWithFormat:@"%04ld", number];
  125. }
  126. + (NSString *)getAccountExt
  127. {
  128. return [UICKeyChainStore stringForKey:@"accountExt" service:NCGlobal.shared.serviceShareKeyChain];
  129. }
  130. + (void)setAccountExt:(NSString *)account
  131. {
  132. [UICKeyChainStore setString:account forKey:@"accountExt" service:NCGlobal.shared.serviceShareKeyChain];
  133. }
  134. + (NSString *)getServerUrlExt
  135. {
  136. return [UICKeyChainStore stringForKey:@"serverUrlExt" service:NCGlobal.shared.serviceShareKeyChain];
  137. }
  138. + (void)setServerUrlExt:(NSString *)serverUrl
  139. {
  140. [UICKeyChainStore setString:serverUrl forKey:@"serverUrlExt" service:NCGlobal.shared.serviceShareKeyChain];
  141. }
  142. + (NSString *)getTitleServerUrlExt
  143. {
  144. return [UICKeyChainStore stringForKey:@"titleServerUrlExt" service:NCGlobal.shared.serviceShareKeyChain];
  145. }
  146. + (void)setTitleServerUrlExt:(NSString *)titleServerUrl
  147. {
  148. [UICKeyChainStore setString:titleServerUrl forKey:@"titleServerUrlExt" service:NCGlobal.shared.serviceShareKeyChain];
  149. }
  150. + (NSString *)getFileNameExt
  151. {
  152. return [UICKeyChainStore stringForKey:@"fileNameExt" service:NCGlobal.shared.serviceShareKeyChain];
  153. }
  154. + (void)setFileNameExt:(NSString *)fileName
  155. {
  156. [UICKeyChainStore setString:fileName forKey:@"fileNameExt" service:NCGlobal.shared.serviceShareKeyChain];
  157. }
  158. + (NSString *)getEmail
  159. {
  160. return [UICKeyChainStore stringForKey:@"email" service:NCGlobal.shared.serviceShareKeyChain];
  161. }
  162. + (void)setEmail:(NSString *)email
  163. {
  164. [UICKeyChainStore setString:email forKey:@"email" service:NCGlobal.shared.serviceShareKeyChain];
  165. }
  166. + (NSString *)getHint
  167. {
  168. return [UICKeyChainStore stringForKey:@"hint" service:NCGlobal.shared.serviceShareKeyChain];
  169. }
  170. + (void)setHint:(NSString *)hint
  171. {
  172. [UICKeyChainStore setString:hint forKey:@"hint" service:NCGlobal.shared.serviceShareKeyChain];
  173. }
  174. + (BOOL)getOriginalFileName:(NSString *)key
  175. {
  176. return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  177. }
  178. + (void)setOriginalFileName:(BOOL)value key:(NSString *)key
  179. {
  180. NSString *sValue = (value) ? @"true" : @"false";
  181. [UICKeyChainStore setString:sValue forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  182. }
  183. + (NSString *)getFileNameMask:(NSString *)key
  184. {
  185. NSString *mask = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  186. if (mask == nil)
  187. mask = @"";
  188. return mask;
  189. }
  190. + (void)setFileNameMask:(NSString *)mask key:(NSString *)key
  191. {
  192. [UICKeyChainStore setString:mask forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  193. }
  194. + (BOOL)getFileNameType:(NSString *)key
  195. {
  196. return [[UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  197. }
  198. + (void)setFileNameType:(BOOL)prefix key:(NSString *)key
  199. {
  200. NSString *sPrefix = (prefix) ? @"true" : @"false";
  201. [UICKeyChainStore setString:sPrefix forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  202. }
  203. + (BOOL)getActivityVerboseHigh
  204. {
  205. return [[UICKeyChainStore stringForKey:@"activityVerboseHigh" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  206. }
  207. + (void)setActivityVerboseHigh:(BOOL)high
  208. {
  209. NSString *sHigh = (high) ? @"true" : @"false";
  210. [UICKeyChainStore setString:sHigh forKey:@"activityVerboseHigh" service:NCGlobal.shared.serviceShareKeyChain];
  211. }
  212. + (BOOL)getShowHiddenFiles
  213. {
  214. return [[UICKeyChainStore stringForKey:@"showHiddenFiles" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  215. }
  216. + (void)setShowHiddenFiles:(BOOL)show
  217. {
  218. NSString *sShow = (show) ? @"true" : @"false";
  219. [UICKeyChainStore setString:sShow forKey:@"showHiddenFiles" service:NCGlobal.shared.serviceShareKeyChain];
  220. }
  221. + (BOOL)getFormatCompatibility
  222. {
  223. NSString *valueString = [UICKeyChainStore stringForKey:@"formatCompatibility" service:NCGlobal.shared.serviceShareKeyChain];
  224. // Default TRUE
  225. if (valueString == nil) {
  226. [self setFormatCompatibility:YES];
  227. return true;
  228. }
  229. return [valueString boolValue];
  230. }
  231. + (void)setFormatCompatibility:(BOOL)set
  232. {
  233. NSString *sSet = (set) ? @"true" : @"false";
  234. [UICKeyChainStore setString:sSet forKey:@"formatCompatibility" service:NCGlobal.shared.serviceShareKeyChain];
  235. }
  236. + (NSString *)getEndToEndCertificate:(NSString *)account
  237. {
  238. NSString *key, *certificate;
  239. key = [E2E_certificate stringByAppendingString:account];
  240. certificate = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  241. // OLD VERSION
  242. if (certificate == nil) {
  243. key = [@"EndToEndPublicKey_" stringByAppendingString:account];
  244. certificate = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  245. }
  246. return certificate;
  247. }
  248. + (void)setEndToEndCertificate:(NSString *)account certificate:(NSString *)certificate
  249. {
  250. NSString *key = [E2E_certificate stringByAppendingString:account];
  251. [UICKeyChainStore setString:certificate forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  252. }
  253. + (NSString *)getEndToEndPrivateKey:(NSString *)account
  254. {
  255. NSString *key = [E2E_PrivateKey stringByAppendingString:account];
  256. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  257. }
  258. + (void)setEndToEndPrivateKey:(NSString *)account privateKey:(NSString *)privateKey
  259. {
  260. NSString *key = [E2E_PrivateKey stringByAppendingString:account];
  261. [UICKeyChainStore setString:privateKey forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  262. }
  263. + (NSString *)getEndToEndPublicKey:(NSString *)account
  264. {
  265. NSString *key = [E2E_PublicKey stringByAppendingString:account];
  266. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  267. }
  268. + (void)setEndToEndPublicKey:(NSString *)account publicKey:(NSString *)publicKey
  269. {
  270. NSString *key = [E2E_PublicKey stringByAppendingString:account];
  271. [UICKeyChainStore setString:publicKey forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  272. }
  273. + (NSString *)getEndToEndPassphrase:(NSString *)account
  274. {
  275. NSString *key = [E2E_Passphrase stringByAppendingString:account];
  276. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  277. }
  278. + (void)setEndToEndPassphrase:(NSString *)account passphrase:(NSString *)passphrase
  279. {
  280. NSString *key = [E2E_Passphrase stringByAppendingString:account];
  281. [UICKeyChainStore setString:passphrase forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  282. }
  283. + (BOOL)isEndToEndEnabled:(NSString *)account
  284. {
  285. BOOL isE2EEEnabled = [[NCManageDatabase shared] getCapabilitiesServerBoolWithAccount:account elements:NCElementsJSON.shared.capabilitiesE2EEEnabled exists:false];
  286. NSString* versionE2EE = [[NCManageDatabase shared] getCapabilitiesServerStringWithAccount:account elements:NCElementsJSON.shared.capabilitiesE2EEApiVersion];
  287. NSString *certificate = [self getEndToEndCertificate:account];
  288. NSString *publicKey = [self getEndToEndPublicKey:account];
  289. NSString *privateKey = [self getEndToEndPrivateKey:account];
  290. NSString *passphrase = [self getEndToEndPassphrase:account];
  291. if (passphrase.length > 0 && privateKey.length > 0 && certificate.length > 0 && publicKey.length > 0 && isE2EEEnabled && [versionE2EE isEqual:[[NCGlobal shared] e2eeVersion]]) {
  292. return YES;
  293. } else {
  294. return NO;
  295. }
  296. }
  297. + (void)clearAllKeysEndToEnd:(NSString *)account
  298. {
  299. [self setEndToEndCertificate:account certificate:nil];
  300. [self setEndToEndPrivateKey:account privateKey:nil];
  301. [self setEndToEndPublicKey:account publicKey:nil];
  302. [self setEndToEndPassphrase:account passphrase:nil];
  303. // OLD
  304. [UICKeyChainStore setString:nil forKey:[@"EndToEndPublicKey_" stringByAppendingString:account] service:NCGlobal.shared.serviceShareKeyChain];
  305. }
  306. + (BOOL)getDisableFilesApp
  307. {
  308. return [[UICKeyChainStore stringForKey:@"disablefilesapp" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  309. }
  310. + (void)setDisableFilesApp:(BOOL)disable
  311. {
  312. NSString *sDisable = (disable) ? @"true" : @"false";
  313. [UICKeyChainStore setString:sDisable forKey:@"disablefilesapp" service:NCGlobal.shared.serviceShareKeyChain];
  314. }
  315. + (void)setPushNotificationPublicKey:(NSString *)account data:(NSData *)data
  316. {
  317. NSString *key = [@"PNPublicKey" stringByAppendingString:account];
  318. [UICKeyChainStore setData:data forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  319. }
  320. + (NSData *)getPushNotificationPublicKey:(NSString *)account
  321. {
  322. NSString *key = [@"PNPublicKey" stringByAppendingString:account];
  323. return [UICKeyChainStore dataForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  324. }
  325. + (void)setPushNotificationSubscribingPublicKey:(NSString *)account publicKey:(NSString *)publicKey
  326. {
  327. NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account];
  328. [UICKeyChainStore setString:publicKey forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  329. }
  330. + (NSString *)getPushNotificationSubscribingPublicKey:(NSString *)account
  331. {
  332. NSString *key = [@"PNSubscribingPublicKey" stringByAppendingString:account];
  333. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  334. }
  335. + (void)setPushNotificationPrivateKey:(NSString *)account data:(NSData *)data
  336. {
  337. NSString *key = [@"PNPrivateKey" stringByAppendingString:account];
  338. [UICKeyChainStore setData:data forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  339. }
  340. + (NSData *)getPushNotificationPrivateKey:(NSString *)account
  341. {
  342. NSString *key = [@"PNPrivateKey" stringByAppendingString:account];
  343. return [UICKeyChainStore dataForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  344. }
  345. + (void)setPushNotificationToken:(NSString *)account token:(NSString *)token
  346. {
  347. NSString *key = [@"PNToken" stringByAppendingString:account];
  348. [UICKeyChainStore setString:token forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  349. }
  350. + (NSString *)getPushNotificationToken:(NSString *)account
  351. {
  352. NSString *key = [@"PNToken" stringByAppendingString:account];
  353. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  354. }
  355. + (void)setPushNotificationDeviceIdentifier:(NSString *)account deviceIdentifier:(NSString *)deviceIdentifier
  356. {
  357. NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account];
  358. [UICKeyChainStore setString:deviceIdentifier forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  359. }
  360. + (NSString *)getPushNotificationDeviceIdentifier:(NSString *)account
  361. {
  362. NSString *key = [@"PNDeviceIdentifier" stringByAppendingString:account];
  363. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  364. }
  365. + (void)setPushNotificationDeviceIdentifierSignature:(NSString *)account deviceIdentifierSignature:(NSString *)deviceIdentifierSignature
  366. {
  367. NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account];
  368. [UICKeyChainStore setString:deviceIdentifierSignature forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  369. }
  370. + (NSString *)getPushNotificationDeviceIdentifierSignature:(NSString *)account
  371. {
  372. NSString *key = [@"PNDeviceIdentifierSignature" stringByAppendingString:account];
  373. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  374. }
  375. + (void)clearAllKeysPushNotification:(NSString *)account
  376. {
  377. [self setPushNotificationPublicKey:account data:nil];
  378. [self setPushNotificationSubscribingPublicKey:account publicKey:nil];
  379. [self setPushNotificationPrivateKey:account data:nil];
  380. [self setPushNotificationToken:account token:nil];
  381. [self setPushNotificationDeviceIdentifier:account deviceIdentifier:nil];
  382. [self setPushNotificationDeviceIdentifierSignature:account deviceIdentifierSignature:nil];
  383. }
  384. + (NSInteger)getMediaWidthImage
  385. {
  386. NSString *width = [UICKeyChainStore stringForKey:@"mediaWidthImage" service:NCGlobal.shared.serviceShareKeyChain];
  387. if (width == nil) {
  388. return 80;
  389. } else {
  390. return [width integerValue];
  391. }
  392. }
  393. + (void)setMediaWidthImage:(NSInteger)width
  394. {
  395. NSString *widthString = [@(width) stringValue];
  396. [UICKeyChainStore setString:widthString forKey:@"mediaWidthImage" service:NCGlobal.shared.serviceShareKeyChain];
  397. }
  398. + (BOOL)getDisableCrashservice
  399. {
  400. return [[UICKeyChainStore stringForKey:@"crashservice" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  401. }
  402. + (void)setDisableCrashservice:(BOOL)disable
  403. {
  404. NSString *sDisable = (disable) ? @"true" : @"false";
  405. [UICKeyChainStore setString:sDisable forKey:@"crashservice" service:NCGlobal.shared.serviceShareKeyChain];
  406. }
  407. + (void)setPassword:(NSString *)account password:(NSString *)password
  408. {
  409. NSString *key = [@"password" stringByAppendingString:account];
  410. [UICKeyChainStore setString:password forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  411. }
  412. + (NSString *)getPassword:(NSString *)account
  413. {
  414. NSString *key = [@"password" stringByAppendingString:account];
  415. NSString *result = [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  416. if (result == nil) { result = @""; }
  417. return result;
  418. }
  419. + (void)setHCBusinessType:(NSString *)professions
  420. {
  421. [UICKeyChainStore setString:professions forKey:@"businessType" service:NCGlobal.shared.serviceShareKeyChain];
  422. }
  423. + (NSString *)getHCBusinessType
  424. {
  425. return [UICKeyChainStore stringForKey:@"businessType" service:NCGlobal.shared.serviceShareKeyChain];
  426. }
  427. + (NSData *)getDatabaseEncryptionKey
  428. {
  429. NSData *key = [UICKeyChainStore dataForKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain];
  430. if (key == nil) {
  431. NSMutableData *key = [NSMutableData dataWithLength:64];
  432. (void)SecRandomCopyBytes(kSecRandomDefault, key.length, (uint8_t *)key.mutableBytes);
  433. [UICKeyChainStore setData:key forKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain];
  434. return key;
  435. } else {
  436. return key;
  437. }
  438. }
  439. + (void)setDatabaseEncryptionKey:(NSData *)data
  440. {
  441. [UICKeyChainStore setData:data forKey:@"databaseEncryptionKey" service:NCGlobal.shared.serviceShareKeyChain];
  442. }
  443. + (NSString *)getCertificateError:(NSString *)account
  444. {
  445. NSString *key = [@"certificateError" stringByAppendingString:account];
  446. return [UICKeyChainStore stringForKey:key service:NCGlobal.shared.serviceShareKeyChain];
  447. }
  448. + (void)setCertificateError:(NSString *)account host:(NSString *)host
  449. {
  450. // In background do not write the error
  451. #if !defined(EXTENSION)
  452. UIApplicationState state = [[UIApplication sharedApplication] applicationState];
  453. if (state == UIApplicationStateBackground || state == UIApplicationStateInactive) {
  454. return;
  455. }
  456. NSString *key = [@"certificateError" stringByAppendingString:account];
  457. [UICKeyChainStore setString:host forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  458. #else
  459. return;
  460. #endif
  461. }
  462. + (void)clearCertificateError:(NSString *)account
  463. {
  464. NSString *key = [@"certificateError" stringByAppendingString:account];
  465. [UICKeyChainStore setString:nil forKey:key service:NCGlobal.shared.serviceShareKeyChain];
  466. }
  467. + (BOOL)getDisableLocalCacheAfterUpload
  468. {
  469. return [[UICKeyChainStore stringForKey:@"disableLocalCacheAfterUpload" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  470. }
  471. + (void)setDisableLocalCacheAfterUpload:(BOOL)disable
  472. {
  473. NSString *sDisable = (disable) ? @"true" : @"false";
  474. [UICKeyChainStore setString:sDisable forKey:@"disableLocalCacheAfterUpload" service:NCGlobal.shared.serviceShareKeyChain];
  475. }
  476. + (BOOL)getLivePhoto
  477. {
  478. NSString *valueString = [UICKeyChainStore stringForKey:@"livePhoto" service:NCGlobal.shared.serviceShareKeyChain];
  479. // Default TRUE
  480. if (valueString == nil) {
  481. [self setLivePhoto:YES];
  482. return true;
  483. }
  484. return [valueString boolValue];
  485. }
  486. + (void)setLivePhoto:(BOOL)set
  487. {
  488. NSString *sSet = (set) ? @"true" : @"false";
  489. [UICKeyChainStore setString:sSet forKey:@"livePhoto" service:NCGlobal.shared.serviceShareKeyChain];
  490. }
  491. + (NSString *)getMediaSortDate
  492. {
  493. NSString *valueString = [UICKeyChainStore stringForKey:@"mediaSortDate" service:NCGlobal.shared.serviceShareKeyChain];
  494. // Default TRUE
  495. if (valueString == nil) {
  496. [self setMediaSortDate:@"date"];
  497. return @"date";
  498. }
  499. return valueString;
  500. }
  501. + (void)setMediaSortDate:(NSString *)value
  502. {
  503. [UICKeyChainStore setString:value forKey:@"mediaSortDate" service:NCGlobal.shared.serviceShareKeyChain];
  504. }
  505. + (NSInteger)getTextRecognitionStatus
  506. {
  507. NSString *value = [UICKeyChainStore stringForKey:@"textRecognitionStatus" service:NCGlobal.shared.serviceShareKeyChain];
  508. if (value == nil) {
  509. return 0;
  510. } else {
  511. return [value integerValue];
  512. }
  513. }
  514. + (void)setTextRecognitionStatus:(NSInteger)value
  515. {
  516. NSString *valueString = [@(value) stringValue];
  517. [UICKeyChainStore setString:valueString forKey:@"textRecognitionStatus" service:NCGlobal.shared.serviceShareKeyChain];
  518. }
  519. + (NSString *)getDirectoryScanDocuments
  520. {
  521. return [UICKeyChainStore stringForKey:@"directoryScanDocuments" service:NCGlobal.shared.serviceShareKeyChain];
  522. }
  523. + (void)setDirectoryScanDocuments:(NSString *)value
  524. {
  525. [UICKeyChainStore setString:value forKey:@"directoryScanDocuments" service:NCGlobal.shared.serviceShareKeyChain];
  526. }
  527. + (NSInteger)getLogLevel
  528. {
  529. NSString *value = [UICKeyChainStore stringForKey:@"logLevel" service:NCGlobal.shared.serviceShareKeyChain];
  530. if (value == nil) {
  531. return 1;
  532. } else {
  533. return [value integerValue];
  534. }
  535. }
  536. + (void)setLogLevel:(NSInteger)value
  537. {
  538. NSString *valueString = [@(value) stringValue];
  539. [UICKeyChainStore setString:valueString forKey:@"logLevel" service:NCGlobal.shared.serviceShareKeyChain];
  540. }
  541. + (BOOL)getAudioMute
  542. {
  543. return [[UICKeyChainStore stringForKey:@"audioMute" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  544. }
  545. + (void)setAudioMute:(BOOL)set
  546. {
  547. NSString *sSet = (set) ? @"true" : @"false";
  548. [UICKeyChainStore setString:sSet forKey:@"audioMute" service:NCGlobal.shared.serviceShareKeyChain];
  549. }
  550. + (BOOL)getAutomaticDownloadImage
  551. {
  552. return [[UICKeyChainStore stringForKey:@"automaticDownloadImage" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  553. }
  554. + (void)setAutomaticDownloadImage:(BOOL)set
  555. {
  556. NSString *sSet = (set) ? @"true" : @"false";
  557. [UICKeyChainStore setString:sSet forKey:@"automaticDownloadImage" service:NCGlobal.shared.serviceShareKeyChain];
  558. }
  559. + (BOOL)getAccountRequest
  560. {
  561. return [[UICKeyChainStore stringForKey:@"accountRequest" service:NCGlobal.shared.serviceShareKeyChain] boolValue];
  562. }
  563. + (void)setAccountRequest:(BOOL)set
  564. {
  565. NSString *sSet = (set) ? @"true" : @"false";
  566. [UICKeyChainStore setString:sSet forKey:@"accountRequest" service:NCGlobal.shared.serviceShareKeyChain];
  567. }
  568. + (NSInteger)getChunkSize
  569. {
  570. NSString *size = [UICKeyChainStore stringForKey:@"chunkSize" service:NCGlobal.shared.serviceShareKeyChain];
  571. if (size == nil) {
  572. return 0;
  573. } else {
  574. return [size integerValue];
  575. }
  576. }
  577. + (void)setChunkSize:(NSInteger)size
  578. {
  579. NSString *sizeString = [@(size) stringValue];
  580. [UICKeyChainStore setString:sizeString forKey:@"chunkSize" service:NCGlobal.shared.serviceShareKeyChain];
  581. }
  582. + (NSInteger)getCleanUpDay
  583. {
  584. NSString *size = [UICKeyChainStore stringForKey:@"cleanUpDay" service:NCGlobal.shared.serviceShareKeyChain];
  585. if (size == nil) {
  586. return 0;
  587. } else {
  588. return [size integerValue];
  589. }
  590. }
  591. + (void)setCleanUpDay:(NSInteger)days
  592. {
  593. NSString *daysString = [@(days) stringValue];
  594. [UICKeyChainStore setString:daysString forKey:@"cleanUpDay" service:NCGlobal.shared.serviceShareKeyChain];
  595. }
  596. + (PDFDisplayDirection)getPDFDisplayDirection
  597. {
  598. NSString *direction = [UICKeyChainStore stringForKey:@"PDFDisplayDirection" service:NCGlobal.shared.serviceShareKeyChain];
  599. if (direction == nil) {
  600. return kPDFDisplayDirectionVertical;
  601. } else {
  602. return [direction integerValue];
  603. }
  604. }
  605. + (void)setPDFDisplayDirection:(PDFDisplayDirection)direction
  606. {
  607. NSString *directionString = [@(direction) stringValue];
  608. [UICKeyChainStore setString:directionString forKey:@"PDFDisplayDirection" service:NCGlobal.shared.serviceShareKeyChain];
  609. }
  610. #pragma --------------------------------------------------------------------------------------------
  611. #pragma mark ===== Various =====
  612. #pragma --------------------------------------------------------------------------------------------
  613. + (BOOL)addSkipBackupAttributeToItemAtURL:(NSURL *)URL
  614. {
  615. assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
  616. NSError *error = nil;
  617. BOOL success = [URL setResourceValue:[NSNumber numberWithBool: YES] forKey: NSURLIsExcludedFromBackupKey error: &error];
  618. if(!success){
  619. NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
  620. }
  621. return success;
  622. }
  623. + (NSString *)getUserAgent
  624. {
  625. NSString *appVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
  626. NSString *userAgent = [[NCBrandOptions shared] userAgent];
  627. return [NSString stringWithFormat:@"Mozilla/5.0 (iOS) %@/%@", userAgent, appVersion];
  628. }
  629. + (NSString *)dateDiff:(NSDate *) convertedDate
  630. {
  631. NSDate *todayDate = [NSDate date];
  632. double ti = [convertedDate timeIntervalSinceDate:todayDate];
  633. ti = ti * -1;
  634. if (ti < 60) {
  635. return NSLocalizedString(@"_less_a_minute_", nil);
  636. } else if (ti < 3600) {
  637. int diff = round(ti / 60);
  638. if (diff == 1) {
  639. return NSLocalizedString(@"_a_minute_ago_", nil);
  640. } else {
  641. return [NSString stringWithFormat:NSLocalizedString(@"_minutes_ago_", nil), diff];
  642. }
  643. } else if (ti < 86400) {
  644. int diff = round(ti / 60 / 60);
  645. if (diff == 1) {
  646. return NSLocalizedString(@"_an_hour_ago_", nil);
  647. } else {
  648. return[NSString stringWithFormat:NSLocalizedString(@"_hours_ago_", nil), diff];
  649. }
  650. } else if (ti < 86400 * 30) {
  651. int diff = round(ti / 60 / 60 / 24);
  652. if (diff == 1) {
  653. return NSLocalizedString(@"_a_day_ago_", nil);
  654. } else {
  655. return[NSString stringWithFormat:NSLocalizedString(@"_days_ago_", nil), diff];
  656. }
  657. } else {
  658. // Older than one month
  659. NSDateFormatter *df = [[NSDateFormatter alloc] init];
  660. [df setFormatterBehavior:NSDateFormatterBehavior10_4];
  661. [df setDateStyle:NSDateFormatterMediumStyle];
  662. return [df stringFromDate:convertedDate];
  663. }
  664. }
  665. + (NSString *)transformedSize:(int64_t)value
  666. {
  667. NSString *string = [NSByteCountFormatter stringFromByteCount:value countStyle:NSByteCountFormatterCountStyleBinary];
  668. return string;
  669. }
  670. // Remove do not forbidden characters for Nextcloud Server
  671. + (NSString *)removeForbiddenCharactersServer:(NSString *)fileName
  672. {
  673. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"/", nil];
  674. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  675. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  676. }
  677. return fileName;
  678. }
  679. // Remove do not forbidden characters for File System Server
  680. + (NSString *)removeForbiddenCharactersFileSystem:(NSString *)fileName
  681. {
  682. NSArray *arrayForbiddenCharacters = [NSArray arrayWithObjects:@"\\",@"<",@">",@":",@"\"",@"|",@"?",@"*",@"/", nil];
  683. for (NSString *currentCharacter in arrayForbiddenCharacters) {
  684. fileName = [fileName stringByReplacingOccurrencesOfString:currentCharacter withString:@""];
  685. }
  686. return fileName;
  687. }
  688. + (NSString*)stringAppendServerUrl:(NSString *)serverUrl addFileName:(NSString *)addFileName
  689. {
  690. NSString *result;
  691. if (serverUrl == nil || addFileName == nil) return nil;
  692. if ([addFileName isEqualToString:@""]) return serverUrl;
  693. if ([serverUrl isEqualToString:@"/"]) result = [serverUrl stringByAppendingString:addFileName];
  694. else result = [NSString stringWithFormat:@"%@/%@", serverUrl, addFileName];
  695. return result;
  696. }
  697. + (NSString *)createRandomString:(int)numChars
  698. {
  699. NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  700. NSMutableString *randomString = [NSMutableString stringWithCapacity: numChars];
  701. for (int i=0; i < numChars; i++) {
  702. [randomString appendFormat: @"%C", [letters characterAtIndex: arc4random_uniform((unsigned int)[letters length]) % [letters length]]];
  703. }
  704. return [NSString stringWithFormat:@"%@", randomString];
  705. }
  706. + (NSString *)createFileNameDate:(NSString *)fileName extension:(NSString *)extension
  707. {
  708. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  709. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  710. NSString *fileNameDate = [formatter stringFromDate:[NSDate date]];
  711. NSString *returnFileName;
  712. if ([fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  713. returnFileName = [NSString stringWithFormat:@"%@.%@", fileNameDate, extension];
  714. }
  715. if (![fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  716. returnFileName = [NSString stringWithFormat:@"%@ %@", fileName, fileNameDate];
  717. }
  718. if ([fileName isEqualToString:@""] && [extension isEqualToString:@""]) {
  719. returnFileName = fileNameDate;
  720. }
  721. if (![fileName isEqualToString:@""] && ![extension isEqualToString:@""]) {
  722. returnFileName = [NSString stringWithFormat:@"%@ %@.%@", fileName, fileNameDate, extension];
  723. }
  724. return returnFileName;
  725. }
  726. + (NSString *)createFileName:(NSString *)fileName fileDate:(NSDate *)fileDate fileType:(PHAssetMediaType)fileType keyFileName:(NSString *)keyFileName keyFileNameType:(NSString *)keyFileNameType keyFileNameOriginal:(NSString *)keyFileNameOriginal forcedNewFileName:(BOOL)forcedNewFileName
  727. {
  728. BOOL addFileNameType = NO;
  729. // Original FileName ?
  730. if ([self getOriginalFileName:keyFileNameOriginal] && !forcedNewFileName) {
  731. return fileName;
  732. }
  733. NSString *numberFileName;
  734. if ([fileName length] > 8) numberFileName = [fileName substringWithRange:NSMakeRange(04, 04)];
  735. else numberFileName = [CCUtility getIncrementalNumber];
  736. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  737. [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
  738. [formatter setDateFormat:@"yy-MM-dd HH-mm-ss"];
  739. NSString *fileNameDate = [formatter stringFromDate:fileDate];
  740. NSString *fileNameType = @"";
  741. if (fileType == PHAssetMediaTypeImage)
  742. fileNameType = NSLocalizedString(@"_photo_", nil);
  743. if (fileType == PHAssetMediaTypeVideo)
  744. fileNameType = NSLocalizedString(@"_video_", nil);
  745. if (fileType == PHAssetMediaTypeAudio)
  746. fileNameType = NSLocalizedString(@"_audio_", nil);
  747. if (fileType == PHAssetMediaTypeUnknown)
  748. fileNameType = NSLocalizedString(@"_unknown_", nil);
  749. // Use File Name Type
  750. if (keyFileNameType)
  751. addFileNameType = [CCUtility getFileNameType:keyFileNameType];
  752. NSString *fileNameExt = [[fileName pathExtension] lowercaseString];
  753. if (keyFileName) {
  754. fileName = [CCUtility getFileNameMask:keyFileName];
  755. if ([fileName length] > 0) {
  756. [formatter setDateFormat:@"dd"];
  757. NSString *dayNumber = [formatter stringFromDate:fileDate];
  758. [formatter setDateFormat:@"MMM"];
  759. NSString *month = [formatter stringFromDate:fileDate];
  760. [formatter setDateFormat:@"MM"];
  761. NSString *monthNumber = [formatter stringFromDate:fileDate];
  762. [formatter setDateFormat:@"yyyy"];
  763. NSString *year = [formatter stringFromDate:fileDate];
  764. [formatter setDateFormat:@"yy"];
  765. NSString *yearNumber = [formatter stringFromDate:fileDate];
  766. [formatter setDateFormat:@"HH"];
  767. NSString *hour24 = [formatter stringFromDate:fileDate];
  768. [formatter setDateFormat:@"hh"];
  769. NSString *hour12 = [formatter stringFromDate:fileDate];
  770. [formatter setDateFormat:@"mm"];
  771. NSString *minute = [formatter stringFromDate:fileDate];
  772. [formatter setDateFormat:@"ss"];
  773. NSString *second = [formatter stringFromDate:fileDate];
  774. [formatter setDateFormat:@"a"];
  775. NSString *ampm = [formatter stringFromDate:fileDate];
  776. // Replace string with date
  777. fileName = [fileName stringByReplacingOccurrencesOfString:@"DD" withString:dayNumber];
  778. fileName = [fileName stringByReplacingOccurrencesOfString:@"MMM" withString:month];
  779. fileName = [fileName stringByReplacingOccurrencesOfString:@"MM" withString:monthNumber];
  780. fileName = [fileName stringByReplacingOccurrencesOfString:@"YYYY" withString:year];
  781. fileName = [fileName stringByReplacingOccurrencesOfString:@"YY" withString:yearNumber];
  782. fileName = [fileName stringByReplacingOccurrencesOfString:@"HH" withString:hour24];
  783. fileName = [fileName stringByReplacingOccurrencesOfString:@"hh" withString:hour12];
  784. fileName = [fileName stringByReplacingOccurrencesOfString:@"mm" withString:minute];
  785. fileName = [fileName stringByReplacingOccurrencesOfString:@"ss" withString:second];
  786. fileName = [fileName stringByReplacingOccurrencesOfString:@"ampm" withString:ampm];
  787. if (addFileNameType)
  788. fileName = [NSString stringWithFormat:@"%@%@%@.%@", fileNameType, fileName, numberFileName, fileNameExt];
  789. else
  790. fileName = [NSString stringWithFormat:@"%@%@.%@", fileName, numberFileName, fileNameExt];
  791. fileName = [fileName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
  792. } else {
  793. if (addFileNameType)
  794. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  795. else
  796. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  797. }
  798. } else {
  799. if (addFileNameType)
  800. fileName = [NSString stringWithFormat:@"%@ %@ %@.%@", fileNameType, fileNameDate, numberFileName, fileNameExt];
  801. else
  802. fileName = [NSString stringWithFormat:@"%@ %@.%@", fileNameDate, numberFileName, fileNameExt];
  803. }
  804. return fileName;
  805. }
  806. + (void)createDirectoryStandard
  807. {
  808. NSString *path;
  809. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  810. NSLog(@"[LOG] Dir Group");
  811. NSLog(@"%@", [dirGroup path]);
  812. NSLog(@"[LOG] Program application ");
  813. NSLog(@"%@", [[CCUtility getDirectoryDocuments] stringByDeletingLastPathComponent]);
  814. // create Directory Documents
  815. path = [CCUtility getDirectoryDocuments];
  816. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  817. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  818. // create Directory audio => Library, Application Support, audio
  819. path = [CCUtility getDirectoryAudio];
  820. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  821. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  822. // create Directory database Nextcloud
  823. path = [[dirGroup URLByAppendingPathComponent:[[NCGlobal shared] appDatabaseNextcloud]] path];
  824. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  825. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  826. [[NSFileManager defaultManager] setAttributes:@{NSFileProtectionKey:NSFileProtectionNone} ofItemAtPath:path error:nil];
  827. // create Directory User Data
  828. path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appUserData] path];
  829. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  830. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  831. // create Directory Provider Storage
  832. path = [CCUtility getDirectoryProviderStorage];
  833. if (![[NSFileManager defaultManager] fileExistsAtPath: path])
  834. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  835. // create Directory Scan
  836. path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appScan] path];
  837. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  838. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  839. // create Directory Temp
  840. path = NSTemporaryDirectory();
  841. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  842. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  843. // create Directory Background
  844. path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appBackground] path];
  845. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  846. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  847. // Directory Excluded From Backup
  848. [CCUtility addSkipBackupAttributeToItemAtURL:[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]];
  849. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.directoryProviderStorage]];
  850. [CCUtility addSkipBackupAttributeToItemAtURL:[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appUserData]];
  851. #ifdef DEBUG
  852. NSLog(@"[LOG] Copy DB on Documents directory");
  853. NSString *atPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [[dirGroup URLByAppendingPathComponent:[[NCGlobal shared] appDatabaseNextcloud]] path]];
  854. NSString *toPathDB = [NSString stringWithFormat:@"%@/nextcloud.realm", [CCUtility getDirectoryDocuments]];
  855. [[NSFileManager defaultManager] removeItemAtPath:toPathDB error:nil];
  856. [[NSFileManager defaultManager] copyItemAtPath:atPathDB toPath:toPathDB error:nil];
  857. #endif
  858. }
  859. + (NSURL *)getDirectoryGroup
  860. {
  861. NSURL *path = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:[NCBrandOptions shared].capabilitiesGroups];
  862. return path;
  863. }
  864. + (NSString *)getUserUrlBase:(NSString *)user urlBase:(NSString *)urlBase
  865. {
  866. NSString *baseUrl = [urlBase lowercaseString];
  867. NSString *dirUserBaseUrl = @"";
  868. if ([user length] && [baseUrl length]) {
  869. if ([baseUrl hasPrefix:@"https://"]) baseUrl = [baseUrl substringFromIndex:8];
  870. if ([baseUrl hasPrefix:@"http://"]) baseUrl = [baseUrl substringFromIndex:7];
  871. dirUserBaseUrl = [NSString stringWithFormat:@"%@-%@", user, baseUrl];
  872. dirUserBaseUrl = [[self removeForbiddenCharactersFileSystem:dirUserBaseUrl] lowercaseString];
  873. }
  874. return dirUserBaseUrl;
  875. }
  876. // Return the path of directory Documents -> NSDocumentDirectory
  877. + (NSString *)getDirectoryDocuments
  878. {
  879. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  880. return [paths objectAtIndex:0];
  881. }
  882. + (NSString *)getDirectoryReaderMetadata
  883. {
  884. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  885. return [NSString stringWithFormat:@"%@/Reader Metadata", [paths objectAtIndex:0]];
  886. }
  887. // Return the path of directory Audio
  888. + (NSString *)getDirectoryAudio
  889. {
  890. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
  891. return [NSString stringWithFormat:@"%@/%@", [paths objectAtIndex:0], @"audio"];
  892. }
  893. // Return the path of directory Cetificates
  894. + (NSString *)getDirectoryCerificates
  895. {
  896. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appCertificates] path];
  897. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  898. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  899. return path;
  900. }
  901. + (NSString *)getDirectoryUserData
  902. {
  903. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appUserData] path];
  904. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  905. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  906. return path;
  907. }
  908. + (NSString *)getDirectoryProviderStorage
  909. {
  910. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.directoryProviderStorage] path];
  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
  916. {
  917. NSString *path = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorage], ocId];
  918. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  919. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  920. return path;
  921. }
  922. + (NSString *)getDirectoryProviderStorageOcId:(NSString *)ocId fileNameView:(NSString *)fileNameView
  923. {
  924. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@", [self getDirectoryProviderStorageOcId:ocId], fileNameView];
  925. // if do not exists create file 0 length
  926. if ([[NSFileManager defaultManager] fileExistsAtPath:fileNamePath] == NO) {
  927. [[NSFileManager defaultManager] createFileAtPath:fileNamePath contents:nil attributes:nil];
  928. }
  929. return fileNamePath;
  930. }
  931. + (NSString *)getDirectoryProviderStorageIconOcId:(NSString *)ocId etag:(NSString *)etag
  932. {
  933. return [NSString stringWithFormat:@"%@/%@.small.%@", [self getDirectoryProviderStorageOcId:ocId], etag, [NCGlobal shared].extensionPreview];
  934. }
  935. + (NSString *)getDirectoryProviderStoragePreviewOcId:(NSString *)ocId etag:(NSString *)etag
  936. {
  937. return [NSString stringWithFormat:@"%@/%@.preview.%@", [self getDirectoryProviderStorageOcId:ocId], etag, [NCGlobal shared].extensionPreview];
  938. }
  939. + (BOOL)fileProviderStorageExists:(NSString *)ocId fileNameView:(NSString *)fileNameView
  940. {
  941. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  942. unsigned long long fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  943. if (fileSize > 0) return true;
  944. else return false;
  945. }
  946. + (int64_t)fileProviderStorageSize:(NSString *)ocId fileNameView:(NSString *)fileNameView
  947. {
  948. NSString *fileNamePath = [self getDirectoryProviderStorageOcId:ocId fileNameView:fileNameView];
  949. int64_t fileSize = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePath error:nil] fileSize];
  950. return fileSize;
  951. }
  952. + (BOOL)fileProviderStoragePreviewIconExists:(NSString *)ocId etag:(NSString *)etag
  953. {
  954. NSString *fileNamePathPreview = [self getDirectoryProviderStoragePreviewOcId:ocId etag:etag];
  955. NSString *fileNamePathIcon = [self getDirectoryProviderStorageIconOcId:ocId etag:etag];
  956. unsigned long long fileSizePreview = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePathPreview error:nil] fileSize];
  957. unsigned long long fileSizeIcon = [[[NSFileManager defaultManager] attributesOfItemAtPath:fileNamePathIcon error:nil] fileSize];
  958. if (fileSizePreview > 0 && fileSizeIcon > 0) return true;
  959. else return false;
  960. }
  961. + (void)removeGroupApplicationSupport
  962. {
  963. NSURL *dirGroup = [CCUtility getDirectoryGroup];
  964. NSString *path = [[dirGroup URLByAppendingPathComponent:NCGlobal.shared.appApplicationSupport] path];
  965. [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
  966. }
  967. + (void)removeGroupLibraryDirectory
  968. {
  969. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryScan] error:nil];
  970. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryUserData] error:nil];
  971. }
  972. + (void)removeGroupDirectoryProviderStorage
  973. {
  974. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorage] error:nil];
  975. }
  976. + (void)removeDocumentsDirectory
  977. {
  978. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryDocuments] error:nil];
  979. }
  980. + (void)removeTemporaryDirectory
  981. {
  982. [[NSFileManager defaultManager] removeItemAtPath:NSTemporaryDirectory() error:nil];
  983. }
  984. + (void)emptyTemporaryDirectory
  985. {
  986. NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
  987. for (NSString *file in tmpDirectory) {
  988. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
  989. }
  990. }
  991. + (NSString *)getTitleSectionDate:(NSDate *)date
  992. {
  993. NSString *title;
  994. NSDate *today = [NSDate date];
  995. NSDate *yesterday = [today dateByAddingTimeInterval: -86400.0];
  996. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:[NSDate distantPast]]]) {
  997. title = NSLocalizedString(@"_no_date_", nil);
  998. } else {
  999. title = [NSDateFormatter localizedStringFromDate:date dateStyle:NSDateFormatterLongStyle timeStyle:0];
  1000. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:today]])
  1001. title = [NSString stringWithFormat:NSLocalizedString(@"_today_", nil)];
  1002. if ([date isEqualToDate:[CCUtility datetimeWithOutTime:yesterday]])
  1003. title = [NSString stringWithFormat:NSLocalizedString(@"_yesterday_", nil)];
  1004. }
  1005. return title;
  1006. }
  1007. + (void)moveFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  1008. {
  1009. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  1010. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  1011. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  1012. }
  1013. + (void)copyFileAtPath:(NSString *)atPath toPath:(NSString *)toPath
  1014. {
  1015. [[NSFileManager defaultManager] removeItemAtPath:toPath error:nil];
  1016. [[NSFileManager defaultManager] copyItemAtPath:atPath toPath:toPath error:nil];
  1017. }
  1018. + (void)removeFileAtPath:(NSString *)atPath
  1019. {
  1020. [[NSFileManager defaultManager] removeItemAtPath:atPath error:nil];
  1021. }
  1022. + (void)createDirectoryAtPath:(NSString *)atPath
  1023. {
  1024. [[NSFileManager defaultManager] createDirectoryAtPath:atPath withIntermediateDirectories:true attributes:nil error:nil];
  1025. }
  1026. + (NSString *)returnPathfromServerUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase account:(NSString *)account
  1027. {
  1028. NSString *homeServer = [[NCUtilityFileSystem shared] getHomeServerWithAccount:account];
  1029. NSString *path = [serverUrl stringByReplacingOccurrencesOfString:homeServer withString:@""];
  1030. return path;
  1031. }
  1032. + (NSString *)returnFileNamePathFromFileName:(NSString *)metadataFileName serverUrl:(NSString *)serverUrl urlBase:(NSString *)urlBase account:(NSString *)account
  1033. {
  1034. if (metadataFileName == nil || serverUrl == nil || urlBase == nil) {
  1035. return @"";
  1036. }
  1037. NSString *homeServer = [[NCUtilityFileSystem shared] getHomeServerWithAccount:account];
  1038. NSString *fileName = [NSString stringWithFormat:@"%@/%@", [serverUrl stringByReplacingOccurrencesOfString:homeServer withString:@""], metadataFileName];
  1039. if ([fileName hasPrefix:@"/"]) fileName = [fileName substringFromIndex:1];
  1040. return fileName;
  1041. }
  1042. + (NSArray *)createNameSubFolder:(NSArray *)assets
  1043. {
  1044. NSMutableOrderedSet *datesSubFolder = [NSMutableOrderedSet new];
  1045. for (PHAsset *asset in assets) {
  1046. NSDate *assetDate = asset.creationDate;
  1047. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  1048. [formatter setDateFormat:@"yyyy"];
  1049. NSString *yearString = [formatter stringFromDate:assetDate];
  1050. if (yearString)
  1051. [datesSubFolder addObject:yearString];
  1052. [formatter setDateFormat:@"MM"];
  1053. NSString *monthString = [formatter stringFromDate:assetDate];
  1054. monthString = [NSString stringWithFormat:@"%@/%@", yearString, monthString];
  1055. if (monthString)
  1056. [datesSubFolder addObject:monthString];
  1057. }
  1058. return (NSArray *)datesSubFolder;
  1059. }
  1060. + (NSString *)getMimeType:(NSString *)fileNameView
  1061. {
  1062. CFStringRef fileUTI = nil;
  1063. NSString *returnFileUTI = nil;
  1064. if ([fileNameView isEqualToString:@"."]) {
  1065. return returnFileUTI;
  1066. } else {
  1067. CFStringRef fileExtension = (__bridge CFStringRef)[fileNameView pathExtension];
  1068. NSString *ext = (__bridge NSString *)fileExtension;
  1069. ext = ext.uppercaseString;
  1070. fileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileExtension, NULL);
  1071. if (fileUTI != nil) {
  1072. returnFileUTI = (__bridge NSString *)fileUTI;
  1073. CFRelease(fileUTI);
  1074. }
  1075. }
  1076. return returnFileUTI;
  1077. }
  1078. + (NSString *)getDirectoryScan
  1079. {
  1080. NSString *path = [[[CCUtility getDirectoryGroup] URLByAppendingPathComponent:NCGlobal.shared.appScan] path];
  1081. if (![[NSFileManager defaultManager] fileExistsAtPath:path])
  1082. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
  1083. return path;
  1084. }
  1085. + (void)extractImageVideoFromAssetLocalIdentifierForUpload:(tableMetadata *)metadataForUpload notification:(BOOL)notification completion:(void(^)(tableMetadata *metadata, NSString* fileNamePath))completion
  1086. {
  1087. if (metadataForUpload == nil) {
  1088. return completion(nil, nil);
  1089. }
  1090. tableMetadata *metadata = [[NCManageDatabase shared] copyObjectWithMetadata:metadataForUpload];
  1091. PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[metadata.assetLocalIdentifier] options:nil];
  1092. if (!result.count) {
  1093. if (notification) {
  1094. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(NCGlobal.shared.errorInternalError), @"errorDescription": @"_err_file_not_found_"}];
  1095. }
  1096. return completion(nil, nil);
  1097. }
  1098. PHAsset *asset = result[0];
  1099. NSDate *creationDate = asset.creationDate;
  1100. NSDate *modificationDate = asset.modificationDate;
  1101. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1102. // IMAGE
  1103. if (asset.mediaType == PHAssetMediaTypeImage) {
  1104. PHImageRequestOptions *options = [PHImageRequestOptions new];
  1105. options.networkAccessAllowed = YES;
  1106. options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
  1107. options.synchronous = YES;
  1108. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1109. NSLog(@"cacheAsset: %f", progress);
  1110. if (error) {
  1111. if (notification) {
  1112. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Image request iCloud failed [%@]", error.description]}];
  1113. }
  1114. return completion(nil, nil);
  1115. }
  1116. };
  1117. [[PHImageManager defaultManager] requestImageDataForAsset:asset options:options resultHandler:^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
  1118. NSError *error = nil;
  1119. NSString *extensionAsset = [[[asset valueForKey:@"filename"] pathExtension] uppercaseString];
  1120. NSString *fileName = metadata.fileNameView;
  1121. if ([extensionAsset isEqualToString:@"HEIC"] && [CCUtility getFormatCompatibility]) {
  1122. CIImage *ciImage = [CIImage imageWithData:imageData];
  1123. CIContext *context = [CIContext context];
  1124. imageData = [context JPEGRepresentationOfImage:ciImage colorSpace:ciImage.colorSpace options:@{}];
  1125. NSString *fileNameJPEG = [[metadata.fileName lastPathComponent] stringByDeletingPathExtension];
  1126. fileName = [fileNameJPEG stringByAppendingString:@".jpg"];
  1127. metadata.contentType = @"image/jpeg";
  1128. metadata.ext = @"jpg";
  1129. }
  1130. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:fileName];
  1131. [[NSFileManager defaultManager]removeItemAtPath:fileNamePath error:nil];
  1132. [imageData writeToFile:fileNamePath options:NSDataWritingAtomic error:&error];
  1133. if (metadata.e2eEncrypted) {
  1134. metadata.fileNameView = fileName;
  1135. } else {
  1136. metadata.fileNameView = fileName;
  1137. metadata.fileName = fileName;
  1138. }
  1139. metadata.creationDate = creationDate;
  1140. metadata.date = modificationDate;
  1141. metadata.size = [[NCUtilityFileSystem shared] getFileSizeWithFilePath:fileNamePath];
  1142. dispatch_async(dispatch_get_main_queue(), ^{
  1143. completion(metadata, fileNamePath);
  1144. });
  1145. }];
  1146. }
  1147. // VIDEO
  1148. if (asset.mediaType == PHAssetMediaTypeVideo) {
  1149. PHVideoRequestOptions *options = [PHVideoRequestOptions new];
  1150. options.networkAccessAllowed = YES;
  1151. options.version = PHVideoRequestOptionsVersionOriginal;
  1152. options.progressHandler = ^(double progress, NSError *error, BOOL *stop, NSDictionary *info) {
  1153. NSLog(@"cacheAsset: %f", progress);
  1154. if (error) {
  1155. if (notification) {
  1156. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1157. }
  1158. completion(nil, nil);
  1159. }
  1160. };
  1161. [[PHImageManager defaultManager] requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
  1162. if ([asset isKindOfClass:[AVURLAsset class]]) {
  1163. NSString *fileNamePath = [NSTemporaryDirectory() stringByAppendingString:metadata.fileNameView];
  1164. NSURL *fileNamePathURL = [[NSURL alloc] initFileURLWithPath:fileNamePath];
  1165. NSError *error = nil;
  1166. //NSDictionary *attributes = [NSDictionary dictionaryWithObjectsAndKeys: modificationDate, NSFileModificationDate, creationDate, NSFileCreationDate, NULL];
  1167. [[NSFileManager defaultManager] removeItemAtURL:fileNamePathURL error:nil];
  1168. [[NSFileManager defaultManager] copyItemAtURL:[(AVURLAsset *)asset URL] toURL:fileNamePathURL error:&error];
  1169. //[[NSFileManager defaultManager] setAttributes: attributes ofItemAtPath:fileNamePath error:nil];
  1170. dispatch_async(dispatch_get_main_queue(), ^{
  1171. if (error) {
  1172. if (notification) {
  1173. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:NCGlobal.shared.notificationCenterUploadedFile object:nil userInfo:@{@"ocId": metadata.ocId, @"errorCode": @(error.code), @"errorDescription": [NSString stringWithFormat:@"Video request iCloud failed [%@]", error.description]}];
  1174. }
  1175. completion(nil, nil);
  1176. } else {
  1177. metadata.creationDate = creationDate;
  1178. metadata.date = modificationDate;
  1179. metadata.size = [[NCUtilityFileSystem shared] getFileSizeWithFilePath:fileNamePath];
  1180. completion(metadata, fileNamePath);
  1181. }
  1182. });
  1183. }
  1184. }];
  1185. }
  1186. });
  1187. }
  1188. + (void)extractLivePhotoAsset:(PHAsset*)asset filePath:(NSString *)filePath withCompletion:(void (^)(NSURL* url))completion
  1189. {
  1190. [CCUtility removeFileAtPath:filePath];
  1191. NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
  1192. PHLivePhotoRequestOptions *options = [PHLivePhotoRequestOptions new];
  1193. options.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
  1194. options.networkAccessAllowed = YES;
  1195. [[PHImageManager defaultManager] requestLivePhotoForAsset:asset targetSize:[UIScreen mainScreen].bounds.size contentMode:PHImageContentModeDefault options:options resultHandler:^(PHLivePhoto * _Nullable livePhoto, NSDictionary * _Nullable info) {
  1196. if (livePhoto) {
  1197. NSArray *assetResources = [PHAssetResource assetResourcesForLivePhoto:livePhoto];
  1198. PHAssetResource *videoResource = nil;
  1199. for(PHAssetResource *resource in assetResources){
  1200. if (resource.type == PHAssetResourceTypePairedVideo) {
  1201. videoResource = resource;
  1202. break;
  1203. }
  1204. }
  1205. if(videoResource){
  1206. [[PHAssetResourceManager defaultManager] writeDataForAssetResource:videoResource toFile:fileUrl options:nil completionHandler:^(NSError * _Nullable error) {
  1207. if (!error) {
  1208. completion(fileUrl);
  1209. } else { completion(nil); }
  1210. }];
  1211. } else { completion(nil); }
  1212. } else { completion(nil); }
  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 urlBase:(NSString *)urlBase
  1224. {
  1225. NSString *home = [[NCUtilityFileSystem shared] getHomeServerWithAccount:account];
  1226. if (e2eEncrypted) {
  1227. return true;
  1228. } else if ([serverUrl isEqualToString:home] || [serverUrl isEqualToString:@".."]) {
  1229. return false;
  1230. } else {
  1231. tableDirectory *directory = [[NCManageDatabase shared] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1232. while (directory != nil && ![directory.serverUrl isEqualToString:home]) {
  1233. if (directory.e2eEncrypted == true) {
  1234. return true;
  1235. }
  1236. serverUrl = [[NCUtilityFileSystem shared] deletingLastPathComponentWithAccount:account serverUrl:serverUrl];
  1237. directory = [[NCManageDatabase shared] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", account, serverUrl]];
  1238. }
  1239. return false;
  1240. }
  1241. }
  1242. #pragma --------------------------------------------------------------------------------------------
  1243. #pragma mark ===== Share Permissions =====
  1244. #pragma --------------------------------------------------------------------------------------------
  1245. + (NSInteger) getPermissionsValueByCanEdit:(BOOL)canEdit andCanCreate:(BOOL)canCreate andCanChange:(BOOL)canChange andCanDelete:(BOOL)canDelete andCanShare:(BOOL)canShare andIsFolder:(BOOL) isFolder
  1246. {
  1247. NSInteger permissionsValue = NCGlobal.shared.permissionReadShare;
  1248. if (canEdit && !isFolder) {
  1249. permissionsValue = permissionsValue + NCGlobal.shared.permissionUpdateShare;
  1250. }
  1251. if (canCreate & isFolder) {
  1252. permissionsValue = permissionsValue + NCGlobal.shared.permissionCreateShare;
  1253. }
  1254. if (canChange && isFolder) {
  1255. permissionsValue = permissionsValue + NCGlobal.shared.permissionUpdateShare;
  1256. }
  1257. if (canDelete & isFolder) {
  1258. permissionsValue = permissionsValue + NCGlobal.shared.permissionDeleteShare;
  1259. }
  1260. if (canShare) {
  1261. permissionsValue = permissionsValue + NCGlobal.shared.permissionShareShare;
  1262. }
  1263. return permissionsValue;
  1264. }
  1265. + (BOOL) isPermissionToCanCreate:(NSInteger) permissionValue {
  1266. BOOL canCreate = ((permissionValue & NCGlobal.shared.permissionCreateShare) > 0);
  1267. return canCreate;
  1268. }
  1269. + (BOOL) isPermissionToCanChange:(NSInteger) permissionValue {
  1270. BOOL canChange = ((permissionValue & NCGlobal.shared.permissionUpdateShare) > 0);
  1271. return canChange;
  1272. }
  1273. + (BOOL) isPermissionToCanDelete:(NSInteger) permissionValue {
  1274. BOOL canDelete = ((permissionValue & NCGlobal.shared.permissionDeleteShare) > 0);
  1275. return canDelete;
  1276. }
  1277. + (BOOL) isPermissionToCanShare:(NSInteger) permissionValue {
  1278. BOOL canShare = ((permissionValue & NCGlobal.shared.permissionShareShare) > 0);
  1279. return canShare;
  1280. }
  1281. + (BOOL) isAnyPermissionToEdit:(NSInteger) permissionValue {
  1282. BOOL canCreate = [self isPermissionToCanCreate:permissionValue];
  1283. BOOL canChange = [self isPermissionToCanChange:permissionValue];
  1284. BOOL canDelete = [self isPermissionToCanDelete:permissionValue];
  1285. BOOL canEdit = (canCreate || canChange || canDelete);
  1286. return canEdit;
  1287. }
  1288. + (BOOL) isPermissionToRead:(NSInteger) permissionValue {
  1289. BOOL canRead = ((permissionValue & NCGlobal.shared.permissionReadShare) > 0);
  1290. return canRead;
  1291. }
  1292. + (BOOL) isPermissionToReadCreateUpdate:(NSInteger) permissionValue {
  1293. BOOL canRead = [self isPermissionToRead:permissionValue];
  1294. BOOL canCreate = [self isPermissionToCanCreate:permissionValue];
  1295. BOOL canChange = [self isPermissionToCanChange:permissionValue];
  1296. BOOL canEdit = (canCreate && canChange && canRead);
  1297. return canEdit;
  1298. }
  1299. #pragma --------------------------------------------------------------------------------------------
  1300. #pragma mark ===== EXIF =====
  1301. #pragma --------------------------------------------------------------------------------------------
  1302. + (void)setExif:(tableMetadata *)metadata withCompletionHandler:(void(^)(double latitude, double longitude, NSString *location, NSDate *date, NSString *lensModel))completition
  1303. {
  1304. NSString *dateTime;
  1305. NSString *latitudeRef;
  1306. NSString *longitudeRef;
  1307. NSString *stringLatitude = @"0";
  1308. NSString *stringLongitude = @"0";
  1309. __block NSString *location = @"";
  1310. double latitude = 0;
  1311. double longitude = 0;
  1312. NSDate *date = nil;
  1313. long fileSize = 0;
  1314. int pixelY = 0;
  1315. int pixelX = 0;
  1316. NSString *lensModel;
  1317. if (![metadata.classFile isEqualToString:@"image"] || ![CCUtility fileProviderStorageExists:metadata.ocId fileNameView:metadata.fileNameView]) {
  1318. completition(latitude, longitude, location, date, lensModel);
  1319. return;
  1320. }
  1321. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageOcId:metadata.ocId fileNameView:metadata.fileNameView]];
  1322. CGImageSourceRef originalSource = CGImageSourceCreateWithURL((CFURLRef) url, NULL);
  1323. if (!originalSource) {
  1324. completition(latitude, longitude, location, date, lensModel);
  1325. return;
  1326. }
  1327. CFDictionaryRef fileProperties = CGImageSourceCopyProperties(originalSource, nil);
  1328. if (!fileProperties) {
  1329. CFRelease(originalSource);
  1330. completition(latitude, longitude, location, date, lensModel);
  1331. return;
  1332. }
  1333. // FILES PROPERTIES
  1334. NSNumber *fileSizeNumber = CFDictionaryGetValue(fileProperties, kCGImagePropertyFileSize);
  1335. fileSize = [fileSizeNumber longValue];
  1336. CFDictionaryRef imageProperties = CGImageSourceCopyPropertiesAtIndex(originalSource, 0, NULL);
  1337. if (!imageProperties) {
  1338. CFRelease(originalSource);
  1339. CFRelease(fileProperties);
  1340. completition(latitude, longitude, location, date, lensModel);
  1341. return;
  1342. }
  1343. CFDictionaryRef tiff = CFDictionaryGetValue(imageProperties, kCGImagePropertyTIFFDictionary);
  1344. CFDictionaryRef gps = CFDictionaryGetValue(imageProperties, kCGImagePropertyGPSDictionary);
  1345. CFDictionaryRef exif = CFDictionaryGetValue(imageProperties, kCGImagePropertyExifDictionary);
  1346. if (exif) {
  1347. NSString *sPixelX = (NSString *)CFDictionaryGetValue(exif, kCGImagePropertyExifPixelXDimension);
  1348. pixelX = [sPixelX intValue];
  1349. NSString *sPixelY = (NSString *)CFDictionaryGetValue(exif, kCGImagePropertyExifPixelYDimension);
  1350. pixelY = [sPixelY intValue];
  1351. lensModel = (NSString *)CFDictionaryGetValue(exif, kCGImagePropertyExifLensModel);
  1352. dateTime = (NSString *)CFDictionaryGetValue(exif, kCGImagePropertyExifDateTimeOriginal);
  1353. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1354. [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
  1355. date = [dateFormatter dateFromString:dateTime];
  1356. }
  1357. if (tiff) {
  1358. dateTime = (NSString *)CFDictionaryGetValue(tiff, kCGImagePropertyTIFFDateTime);
  1359. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1360. [dateFormatter setDateFormat:@"yyyy:MM:dd HH:mm:ss"];
  1361. date = [dateFormatter dateFromString:dateTime];
  1362. }
  1363. if (gps) {
  1364. latitude = [(NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLatitude) doubleValue];
  1365. longitude = [(NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLongitude) doubleValue];
  1366. latitudeRef = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLatitudeRef);
  1367. longitudeRef = (NSString *)CFDictionaryGetValue(gps, kCGImagePropertyGPSLongitudeRef);
  1368. // conversion 4 decimal +N -S
  1369. // The latitude in degrees. Positive values indicate latitudes north of the equator. Negative values indicate latitudes south of the equator.
  1370. if ([latitudeRef isEqualToString:@"N"]) {
  1371. stringLatitude = [NSString stringWithFormat:@"+%.4f", latitude];
  1372. } else {
  1373. stringLatitude = [NSString stringWithFormat:@"-%.4f", latitude];
  1374. }
  1375. // conversion 4 decimal +E -W
  1376. // The longitude in degrees. Measurements are relative to the zero meridian, with positive values extending east of the meridian
  1377. // and negative values extending west of the meridian.
  1378. if ([longitudeRef isEqualToString:@"E"]) {
  1379. stringLongitude = [NSString stringWithFormat:@"+%.4f", longitude];
  1380. } else {
  1381. stringLongitude = [NSString stringWithFormat:@"-%.4f", longitude];
  1382. }
  1383. if (latitude == 0 || longitude == 0) {
  1384. stringLatitude = @"0";
  1385. stringLongitude = @"0";
  1386. }
  1387. }
  1388. // Wite data EXIF in DB
  1389. if (tiff || gps) {
  1390. [[NCManageDatabase shared] setLocalFileWithOcId:metadata.ocId exifDate:date exifLatitude:stringLatitude exifLongitude:stringLongitude exifLensModel:lensModel];
  1391. if ([stringLatitude doubleValue] != 0 || [stringLongitude doubleValue] != 0) {
  1392. // If exists already geocoder data in TableGPS exit
  1393. location = [[NCManageDatabase shared] getLocationFromGeoLatitude:stringLatitude longitude:stringLongitude];
  1394. if (location != nil) {
  1395. CFRelease(originalSource);
  1396. CFRelease(imageProperties);
  1397. CFRelease(fileProperties);
  1398. completition(latitude, longitude, location, date, lensModel);
  1399. return;
  1400. }
  1401. CLGeocoder *geocoder = [[CLGeocoder alloc] init];
  1402. CLLocation *llocation = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
  1403. [geocoder reverseGeocodeLocation:llocation completionHandler:^(NSArray *placemarks, NSError *error) {
  1404. if (error == nil && [placemarks count] > 0) {
  1405. CLPlacemark *placemark = [placemarks lastObject];
  1406. NSString *thoroughfare = @"";
  1407. NSString *postalCode = @"";
  1408. NSString *locality = @"";
  1409. NSString *administrativeArea = @"";
  1410. NSString *country = @"";
  1411. if (placemark.thoroughfare) thoroughfare = placemark.thoroughfare;
  1412. if (placemark.postalCode) postalCode = placemark.postalCode;
  1413. if (placemark.locality) locality = placemark.locality;
  1414. if (placemark.administrativeArea) administrativeArea = placemark.administrativeArea;
  1415. if (placemark.country) country = placemark.country;
  1416. location = [NSString stringWithFormat:@"%@ %@ %@ %@ %@", thoroughfare, postalCode, locality, administrativeArea, country];
  1417. location = [location stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  1418. // GPS
  1419. if ([location length] > 0) {
  1420. [[NCManageDatabase shared] addGeocoderLocation:location placemarkAdministrativeArea:placemark.administrativeArea placemarkCountry:placemark.country placemarkLocality:placemark.locality placemarkPostalCode:placemark.postalCode placemarkThoroughfare:placemark.thoroughfare latitude:stringLatitude longitude:stringLongitude];
  1421. }
  1422. CFRelease(originalSource);
  1423. CFRelease(imageProperties);
  1424. CFRelease(fileProperties);
  1425. completition(latitude, longitude, location, date, lensModel);
  1426. }
  1427. }];
  1428. } else {
  1429. CFRelease(originalSource);
  1430. CFRelease(imageProperties);
  1431. CFRelease(fileProperties);
  1432. completition(latitude, longitude, location, date, lensModel);
  1433. }
  1434. } else {
  1435. CFRelease(originalSource);
  1436. CFRelease(imageProperties);
  1437. CFRelease(fileProperties);
  1438. completition(latitude, longitude, location, date, lensModel);
  1439. }
  1440. }
  1441. #pragma --------------------------------------------------------------------------------------------
  1442. #pragma mark ===== Third parts =====
  1443. #pragma --------------------------------------------------------------------------------------------
  1444. + (NSString *)getExtension:(NSString*)fileName
  1445. {
  1446. NSMutableArray *fileNameArray =[[NSMutableArray alloc] initWithArray: [fileName componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]]];
  1447. NSString *extension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1448. extension = [extension uppercaseString];
  1449. //If the file has a ZIP extension obtain the previous one for check if it is a .pages.zip / .numbers.zip / .key.zip extension
  1450. if ([extension isEqualToString:@"ZIP"]) {
  1451. [fileNameArray removeLastObject];
  1452. NSString *secondExtension = [NSString stringWithFormat:@"%@",[fileNameArray lastObject]];
  1453. secondExtension = [secondExtension uppercaseString];
  1454. if ([secondExtension isEqualToString:@"PAGES"] || [secondExtension isEqualToString:@"NUMBERS"] || [secondExtension isEqualToString:@"KEY"]) {
  1455. extension = [NSString stringWithFormat:@"%@.%@",secondExtension,extension];
  1456. return extension;
  1457. }
  1458. }
  1459. return extension;
  1460. }
  1461. + (NSDate *)datetimeWithOutTime:(NSDate *)datDate
  1462. {
  1463. if (datDate == nil) return nil;
  1464. NSDateComponents* comps = [[NSCalendar currentCalendar] components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:datDate];
  1465. datDate = [[NSCalendar currentCalendar] dateFromComponents:comps];
  1466. return datDate;
  1467. }
  1468. + (NSString *)valueForKey:(NSString *)key fromQueryItems:(NSArray *)queryItems
  1469. {
  1470. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name=%@", key];
  1471. NSURLQueryItem *queryItem = [[queryItems filteredArrayUsingPredicate:predicate] firstObject];
  1472. return queryItem.value;
  1473. }
  1474. + (NSDate *)getATime:(const char *)path
  1475. {
  1476. struct stat st;
  1477. stat(path, &st);
  1478. time_t accessed = st.st_atime;
  1479. NSDate *date = [NSDate dateWithTimeIntervalSince1970:accessed];
  1480. return date;
  1481. }
  1482. @end