CCUtility.m 71 KB

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