CCUtility.m 72 KB

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