CCUtility.m 67 KB

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