CCMain.m 214 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577
  1. //
  2. // CCMain.m
  3. // Nextcloud iOS
  4. //
  5. // Created by Marino Faggiana on 04/09/14.
  6. // Copyright (c) 2017 Marino Faggiana. All rights reserved.
  7. //
  8. // Author Marino Faggiana <m.faggiana@twsweb.it>
  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 <JDStatusBarNotification/JDStatusBarNotification.h>
  24. #import "CCMain.h"
  25. #import "AppDelegate.h"
  26. #import "CCMedia.h"
  27. #import "CCSynchronize.h"
  28. #import "OCActivity.h"
  29. #import "OCNotifications.h"
  30. #import "OCNotificationsAction.h"
  31. #import "OCFrameworkConstants.h"
  32. #import "OCCapabilities.h"
  33. #import "NCAutoUpload.h"
  34. #import "NCBridgeSwift.h"
  35. #import "NCNetworkingEndToEnd.h"
  36. #import "PKDownloadButton.h"
  37. @interface CCMain () <UITextViewDelegate, createFormUploadAssetsDelegate, MGSwipeTableCellDelegate, CCLoginDelegate, CCLoginDelegateWeb, NCSelectDelegate>
  38. {
  39. AppDelegate *appDelegate;
  40. BOOL _isRoot;
  41. BOOL _isViewDidLoad;
  42. NSMutableDictionary *_selectedFileIDsMetadatas;
  43. NSUInteger _numSelectedFileIDsMetadatas;
  44. NSMutableArray *_queueSelector;
  45. UIImageView *_imageTitleHome;
  46. NSUInteger _failedAttempts;
  47. NSDate *_lockUntilDate;
  48. UIRefreshControl *refreshControl;
  49. UIDocumentInteractionController *docController;
  50. CCHud *_hud;
  51. // Datasource
  52. CCSectionDataSourceMetadata *sectionDataSource;
  53. NSDate *_dateReadDataSource;
  54. // Search
  55. BOOL _isSearchMode;
  56. NSString *_searchFileName;
  57. NSMutableArray *_searchResultMetadatas;
  58. NSString *_noFilesSearchTitle;
  59. NSString *_noFilesSearchDescription;
  60. NSTimer *_timerWaitInput;
  61. // Automatic Upload Folder
  62. NSString *_autoUploadFileName;
  63. NSString *_autoUploadDirectory;
  64. // Folder
  65. BOOL _loadingFolder;
  66. tableMetadata *_metadataFolder;
  67. // Image Title Segue
  68. UIImage *imageTitleSegue;
  69. }
  70. @end
  71. @implementation CCMain
  72. #pragma --------------------------------------------------------------------------------------------
  73. #pragma mark ===== Init =====
  74. #pragma --------------------------------------------------------------------------------------------
  75. - (id)initWithCoder:(NSCoder *)aDecoder
  76. {
  77. if (self = [super initWithCoder:aDecoder]) {
  78. appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  79. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initializeMain:) name:@"initializeMain" object:nil];
  80. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clearDateReadDataSource:) name:@"clearDateReadDataSource" object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setTitle) name:@"setTitleMain" object:nil];
  82. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(triggerProgressTask:) name:@"NotificationProgressTask" object:nil];
  83. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeTheming) name:@"changeTheming" object:nil];
  84. // Active Main
  85. appDelegate.activeMain = self;
  86. }
  87. return self;
  88. }
  89. #pragma --------------------------------------------------------------------------------------------
  90. #pragma mark ===== View =====
  91. #pragma --------------------------------------------------------------------------------------------
  92. - (void)viewDidLoad
  93. {
  94. [super viewDidLoad];
  95. // init object
  96. self.metadata = [tableMetadata new];
  97. _hud = [[CCHud alloc] initWithView:[[[UIApplication sharedApplication] delegate] window]];
  98. _selectedFileIDsMetadatas = [NSMutableDictionary new];
  99. _queueSelector = [NSMutableArray new];
  100. _isViewDidLoad = YES;
  101. _searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  102. _searchResultMetadatas = [NSMutableArray new];
  103. _searchFileName = @"";
  104. _noFilesSearchTitle = @"";
  105. _noFilesSearchDescription = @"";
  106. // delegate
  107. self.tableView.delegate = self;
  108. self.tableView.tableFooterView = [UIView new];
  109. self.tableView.separatorColor = [NCBrandColor sharedInstance].seperator;
  110. self.tableView.emptyDataSetDelegate = self;
  111. self.tableView.emptyDataSetSource = self;
  112. self.searchController.delegate = self;
  113. self.searchController.searchBar.delegate = self;
  114. // Register cell
  115. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMain" bundle:nil] forCellReuseIdentifier:@"CellMain"];
  116. [self.tableView registerNib:[UINib nibWithNibName:@"CCCellMainTransfer" bundle:nil] forCellReuseIdentifier:@"CellMainTransfer"];
  117. // long press recognizer TableView
  118. UILongPressGestureRecognizer* longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(onLongPressTableView:)];
  119. [self.tableView addGestureRecognizer:longPressRecognizer];
  120. // Pull-to-Refresh
  121. [self createRefreshControl];
  122. // Register for 3D Touch Previewing if available
  123. if ([self.traitCollection respondsToSelector:@selector(forceTouchCapability)] && (self.traitCollection.forceTouchCapability == UIForceTouchCapabilityAvailable))
  124. {
  125. [self registerForPreviewingWithDelegate:self sourceView:self.view];
  126. }
  127. // reMenu Background
  128. _reMenuBackgroundView = [UIView new];
  129. _reMenuBackgroundView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  130. // if this is not Main (the Main uses inizializeMain)
  131. if (_isRoot == NO && appDelegate.activeAccount.length > 0) {
  132. // Read (File) Folder
  133. [self readFileReloadFolder];
  134. }
  135. // Title
  136. [self setTitle];
  137. }
  138. - (void)viewWillAppear:(BOOL)animated
  139. {
  140. [super viewWillAppear:animated];
  141. // test
  142. if (appDelegate.activeAccount.length == 0)
  143. return;
  144. // Color
  145. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  146. [appDelegate aspectTabBar:self.tabBarController.tabBar hidden:NO];
  147. // Plus Button
  148. [appDelegate plusButtonVisibile:true];
  149. if (_isSelectedMode)
  150. [self setUINavigationBarSelected];
  151. else
  152. [self setUINavigationBarDefault];
  153. // If not editing mode remove _selectedFileIDs
  154. if (!self.tableView.editing)
  155. [_selectedFileIDsMetadatas removeAllObjects];
  156. // Search Bar
  157. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  158. [self searchEnabled:NO];
  159. } else {
  160. [self searchEnabled:YES];
  161. }
  162. // Query data source
  163. if (!_isSearchMode) {
  164. [self queryDatasourceWithReloadData:YES serverUrl:self.serverUrl];
  165. }
  166. }
  167. - (void)viewDidAppear:(BOOL)animated
  168. {
  169. [super viewDidAppear:animated];
  170. // Active Main
  171. appDelegate.activeMain = self;
  172. // Test viewDidLoad
  173. if (_isViewDidLoad) {
  174. _isViewDidLoad = NO;
  175. } else {
  176. if (appDelegate.activeAccount.length > 0 && [_selectedFileIDsMetadatas count] == 0) {
  177. // Read (file) Folder
  178. [self readFileReloadFolder];
  179. }
  180. }
  181. // Title
  182. [self setTitle];
  183. }
  184. - (void)viewWillDisappear:(BOOL)animated
  185. {
  186. [super viewWillDisappear:animated];
  187. [self closeAllMenu];
  188. }
  189. - (void)didReceiveMemoryWarning
  190. {
  191. [super didReceiveMemoryWarning];
  192. // Dispose of any resources that can be recreated.
  193. }
  194. - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
  195. {
  196. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
  197. [self closeAllMenu];
  198. [coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> context) {
  199. if (self.view.frame.size.width == ([[UIScreen mainScreen] bounds].size.width*([[UIScreen mainScreen] bounds].size.width<[[UIScreen mainScreen] bounds].size.height))+([[UIScreen mainScreen] bounds].size.height*([[UIScreen mainScreen] bounds].size.width>[[UIScreen mainScreen] bounds].size.height))) {
  200. // Portrait
  201. } else {
  202. // Landscape
  203. }
  204. [self.tableView reloadData];
  205. }];
  206. }
  207. - (BOOL)prefersStatusBarHidden
  208. {
  209. return NO;
  210. }
  211. // detect scroll for remove keyboard in search mode
  212. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  213. {
  214. if (_isSearchMode && scrollView == self.tableView) {
  215. [self.searchController.searchBar endEditing:YES];
  216. }
  217. }
  218. - (void)changeTheming
  219. {
  220. if (self.isViewLoaded && self.view.window)
  221. [appDelegate changeTheming:self];
  222. // Refresh control
  223. refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  224. refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  225. // color searchbar
  226. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  227. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  228. // color searchbbar button text (cancel)
  229. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  230. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  231. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  232. }
  233. // Title
  234. [self setTitle];
  235. // Reload Table View
  236. [self tableViewReloadData];
  237. }
  238. #pragma --------------------------------------------------------------------------------------------
  239. #pragma mark ===== Initizlize Mail =====
  240. #pragma --------------------------------------------------------------------------------------------
  241. //
  242. // Callers :
  243. //
  244. // loginSuccess (delagate)
  245. // ChangeDefaultAccount (delegate)
  246. // Split : inizialize
  247. // Settings Advanced : removeAllFiles
  248. //
  249. - (void)initializeMain:(NSNotification *)notification
  250. {
  251. _dateReadDataSource = nil;
  252. // test
  253. if (appDelegate.activeAccount.length == 0)
  254. return;
  255. if ([appDelegate.listMainVC count] == 0 || _isRoot) {
  256. // This is Root home main add list
  257. appDelegate.homeMain = self;
  258. _isRoot = YES;
  259. _serverUrl = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  260. [appDelegate.listMainVC setObject:self forKey:_serverUrl];
  261. // go Home
  262. [self.navigationController popToRootViewControllerAnimated:NO];
  263. // setting Networking
  264. [[CCNetworking sharedNetworking] settingAccount];
  265. // Remove search mode
  266. [self cancelSearchBar];
  267. // populate shared Link & User
  268. NSArray *results = [[NCManageDatabase sharedInstance] getShares];
  269. if (results) {
  270. appDelegate.sharesLink = results[0];
  271. appDelegate.sharesUserAndGroup = results[1];
  272. }
  273. // Setting Theming
  274. [appDelegate settingThemingColorBrand];
  275. // Detail
  276. // If AVPlayer in play -> Stop
  277. if (appDelegate.player != nil && appDelegate.player.rate != 0) {
  278. [appDelegate.player pause];
  279. }
  280. for (UIView *view in [appDelegate.activeDetail.view subviews]) {
  281. if ([view isKindOfClass:[UIImageView class]] == NO) { // View Image Nextcloud
  282. [view removeFromSuperview];
  283. }
  284. }
  285. appDelegate.activeDetail.title = nil;
  286. // remove all Notification Messages
  287. [appDelegate.listOfNotifications removeAllObjects];
  288. // Not Photos Video in library ? then align and Init Auto Upload
  289. NSArray *recordsPhotoLibrary = [[NCManageDatabase sharedInstance] getPhotoLibraryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@", appDelegate.activeAccount]];
  290. if ([recordsPhotoLibrary count] == 0) {
  291. [[NCAutoUpload sharedInstance] alignPhotoLibrary];
  292. }
  293. [[NCAutoUpload sharedInstance] initStateAutoUpload];
  294. NSLog(@"[LOG] Request Service Server Nextcloud");
  295. [[NCService sharedInstance] startRequestServicesServer];
  296. // Clear datasorce
  297. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl fileID:nil action:k_action_NULL];
  298. // Read this folder
  299. [self readFileReloadFolder];
  300. } else {
  301. // reload datasource
  302. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:_serverUrl fileID:nil action:k_action_NULL];
  303. }
  304. }
  305. #pragma --------------------------------------------------------------------------------------------
  306. #pragma mark ==== DZNEmptyDataSetSource ====
  307. #pragma --------------------------------------------------------------------------------------------
  308. - (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
  309. {
  310. if (_loadingFolder)
  311. return NO;
  312. else
  313. return YES;
  314. }
  315. - (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
  316. {
  317. return [NCBrandColor sharedInstance].backgroundView;
  318. }
  319. - (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
  320. {
  321. if (_isSearchMode)
  322. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"searchBig"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  323. else
  324. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"filesNoFiles"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement];
  325. }
  326. - (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
  327. {
  328. if (_loadingFolder && refreshControl.isRefreshing == NO) {
  329. UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
  330. activityView.transform = CGAffineTransformMakeScale(1.5f, 1.5f);
  331. activityView.color = [NCBrandColor sharedInstance].brandElement;
  332. [activityView startAnimating];
  333. return activityView;
  334. }
  335. return nil;
  336. }
  337. - (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
  338. {
  339. NSString *text;
  340. if (_isSearchMode) {
  341. text = _noFilesSearchTitle;
  342. } else {
  343. text = [NSString stringWithFormat:@"%@", NSLocalizedString(@"_files_no_files_", nil)];
  344. }
  345. NSDictionary *attributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:20.0f], NSForegroundColorAttributeName:[UIColor lightGrayColor]};
  346. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  347. }
  348. - (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
  349. {
  350. NSString *text;
  351. if (_isSearchMode) {
  352. text = _noFilesSearchDescription;
  353. } else {
  354. text = [NSString stringWithFormat:@"\n%@", NSLocalizedString(@"_no_file_pull_down_", nil)];
  355. }
  356. NSMutableParagraphStyle *paragraph = [NSMutableParagraphStyle new];
  357. paragraph.lineBreakMode = NSLineBreakByWordWrapping;
  358. paragraph.alignment = NSTextAlignmentCenter;
  359. NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:14.0], NSForegroundColorAttributeName: [UIColor lightGrayColor], NSParagraphStyleAttributeName: paragraph};
  360. return [[NSAttributedString alloc] initWithString:text attributes:attributes];
  361. }
  362. #pragma --------------------------------------------------------------------------------------------
  363. #pragma mark ===== Text Field =====
  364. #pragma --------------------------------------------------------------------------------------------
  365. - (void)minCharTextFieldDidChange:(UITextField *)sender
  366. {
  367. UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
  368. if (alertController)
  369. {
  370. UITextField *fileName = alertController.textFields.firstObject;
  371. UIAlertAction *okAction = alertController.actions.lastObject;
  372. okAction.enabled = fileName.text.length > 0;
  373. }
  374. }
  375. - (void)textFieldDidBeginEditing:(UITextField *)textField{
  376. [textField selectAll:textField];
  377. }
  378. #pragma --------------------------------------------------------------------------------------------
  379. #pragma mark ===== Graphic Window =====
  380. #pragma --------------------------------------------------------------------------------------------
  381. - (void)createRefreshControl
  382. {
  383. refreshControl = [UIRefreshControl new];
  384. if (@available(iOS 10, *)) {
  385. _tableView.refreshControl = refreshControl;
  386. } else {
  387. [_tableView addSubview:refreshControl];
  388. }
  389. refreshControl.tintColor = [NCBrandColor sharedInstance].brandText;
  390. refreshControl.backgroundColor = [NCBrandColor sharedInstance].brand;
  391. [refreshControl addTarget:self action:@selector(refreshControlTarget) forControlEvents:UIControlEventValueChanged];
  392. }
  393. - (void)deleteRefreshControl
  394. {
  395. [refreshControl endRefreshing];
  396. for (UIView *subview in [_tableView subviews]) {
  397. if (subview == refreshControl)
  398. [subview removeFromSuperview];
  399. }
  400. if (@available(iOS 10, *)) {
  401. self.tableView.refreshControl = nil;
  402. }
  403. refreshControl = nil;
  404. }
  405. - (void)refreshControlTarget
  406. {
  407. [self readFolder:_serverUrl];
  408. // Actuate `Peek` feedback (weak boom)
  409. AudioServicesPlaySystemSound(1519);
  410. [_imageTitleHome setUserInteractionEnabled:NO];
  411. }
  412. - (void)setTitle
  413. {
  414. // Color text self.navigationItem.title
  415. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  416. if (_isSelectedMode) {
  417. NSUInteger totali = [sectionDataSource.allRecordsDataSource count];
  418. NSUInteger selezionati = [[self.tableView indexPathsForSelectedRows] count];
  419. self.navigationItem.titleView = nil;
  420. self.navigationItem.title = [NSString stringWithFormat:@"%@ : %lu / %lu", NSLocalizedString(@"_selected_", nil), (unsigned long)selezionati, (unsigned long)totali];
  421. } else {
  422. // we are in home : LOGO BRAND
  423. if ([_serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  424. self.navigationItem.title = nil;
  425. UIImage *image = [self getImageLogoHome];
  426. _imageTitleHome = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 60, 30)]; // IMAGE = 120 x 60
  427. _imageTitleHome.contentMode = UIViewContentModeScaleAspectFill;
  428. if ([[[UIDevice currentDevice] systemVersion] floatValue] < 10.0) {
  429. _imageTitleHome.translatesAutoresizingMaskIntoConstraints = YES; //iOS 9
  430. } else {
  431. _imageTitleHome.translatesAutoresizingMaskIntoConstraints = NO; //iOS >= 9
  432. }
  433. _imageTitleHome.image = image;
  434. // backbutton
  435. self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:nil action:nil];
  436. [_imageTitleHome setUserInteractionEnabled:YES];
  437. UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(menuLogo:)];
  438. [singleTap setNumberOfTapsRequired:1];
  439. [_imageTitleHome addGestureRecognizer:singleTap];
  440. self.navigationItem.titleView = _imageTitleHome;
  441. } else {
  442. NSString *shareLink, *shareUserAndGroup;
  443. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadataFolder.directoryID];
  444. if (serverUrl) {
  445. shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  446. shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:_metadataFolder.fileName]];
  447. }
  448. self.navigationItem.title = _titleMain;
  449. if (self.imageTitle) {
  450. [CCGraphics addImageToTitle:_titleMain colorTitle:[NCBrandColor sharedInstance].brandText imageTitle:[CCGraphics changeThemingColorImage:self.imageTitle multiplier:2 color:[NCBrandColor sharedInstance].brandText] imageRight:NO navigationItem:self.navigationItem];
  451. } else {
  452. self.navigationItem.titleView = nil;
  453. }
  454. }
  455. }
  456. }
  457. - (UIImage *)getImageLogoHome
  458. {
  459. UIImage *imageThemingLogo = [UIImage imageNamed:@"themingLogo"];
  460. NSInteger multiplier = 2;
  461. NSString *fileNameThemingLogo = [NSString stringWithFormat:@"%@/%@-themingLogo.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl]];
  462. UIImage *image = [UIImage imageWithContentsOfFile:fileNameThemingLogo];
  463. if (image != nil) {
  464. imageThemingLogo = image;
  465. multiplier = 1;
  466. }
  467. if ([NCBrandOptions sharedInstance].use_themingLogo) {
  468. if ([appDelegate.reachability isReachable] == NO) {
  469. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[NCBrandColor sharedInstance].icon];
  470. } else {
  471. tableCapabilities *capabilities = [[NCManageDatabase sharedInstance] getCapabilites];
  472. if ([capabilities.themingColor isEqualToString:@"#FFFFFF"])
  473. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[UIColor blackColor]];
  474. else
  475. return [CCGraphics changeThemingColorImage:imageThemingLogo multiplier:multiplier color:[UIColor whiteColor]];
  476. }
  477. } else {
  478. if ([appDelegate.reachability isReachable] == NO)
  479. return [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"themingLogo"] multiplier:multiplier color:[NCBrandColor sharedInstance].icon];
  480. else
  481. return [UIImage imageNamed:@"themingLogo"];
  482. }
  483. }
  484. - (void)setUINavigationBarDefault
  485. {
  486. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  487. UIBarButtonItem *buttonMore, *buttonNotification;
  488. // =
  489. buttonMore = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"navigationControllerMenu"] style:UIBarButtonItemStylePlain target:self action:@selector(toggleReMainMenu)];
  490. buttonMore.enabled = true;
  491. // <
  492. self.navigationController.navigationBar.hidden = NO;
  493. // Notification
  494. if ([appDelegate.listOfNotifications count] > 0) {
  495. buttonNotification = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"notification"] style:UIBarButtonItemStylePlain target:self action:@selector(viewNotification)];
  496. buttonNotification.tintColor = [NCBrandColor sharedInstance].brandText;
  497. buttonNotification.enabled = true;
  498. }
  499. if (buttonNotification)
  500. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, buttonNotification, nil];
  501. else
  502. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  503. self.navigationItem.leftBarButtonItem = nil;
  504. }
  505. - (void)setUINavigationBarSelected
  506. {
  507. [appDelegate aspectNavigationControllerBar:self.navigationController.navigationBar online:[appDelegate.reachability isReachable] hidden:NO];
  508. UIImage *icon = [UIImage imageNamed:@"navigationControllerMenu"];
  509. UIBarButtonItem *buttonMore = [[UIBarButtonItem alloc] initWithImage:icon style:UIBarButtonItemStylePlain target:self action:@selector(toggleReSelectMenu)];
  510. UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIBarButtonItemStylePlain target:self action:@selector(cancelSelect)];
  511. self.navigationItem.leftBarButtonItem = leftButton;
  512. self.navigationItem.rightBarButtonItems = [[NSArray alloc] initWithObjects:buttonMore, nil];
  513. }
  514. - (void)cancelSelect
  515. {
  516. [self tableViewSelect:NO];
  517. [appDelegate.reSelectMenu close];
  518. }
  519. - (void)closeAllMenu
  520. {
  521. // close Menu
  522. [appDelegate.reSelectMenu close];
  523. [appDelegate.reMainMenu close];
  524. // Close Menu Logo
  525. [CCMenuAccount dismissMenu];
  526. }
  527. #pragma --------------------------------------------------------------------------------------------
  528. #pragma mark ===== Document Picker =====
  529. #pragma --------------------------------------------------------------------------------------------
  530. - (void)documentMenuWasCancelled:(UIDocumentMenuViewController *)documentMenu
  531. {
  532. NSLog(@"[LOG] Cancelled");
  533. }
  534. - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller
  535. {
  536. NSLog(@"[LOG] Cancelled");
  537. }
  538. - (void)documentMenu:(UIDocumentMenuViewController *)documentMenu didPickDocumentPicker:(UIDocumentPickerViewController *)documentPicker
  539. {
  540. documentPicker.delegate = self;
  541. [self presentViewController:documentPicker animated:YES completion:nil];
  542. }
  543. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
  544. {
  545. if (controller.documentPickerMode == UIDocumentPickerModeImport) {
  546. NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
  547. __block NSError *error;
  548. [coordinator coordinateReadingItemAtURL:url options:NSFileCoordinatorReadingForUploading error:&error byAccessor:^(NSURL *newURL) {
  549. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  550. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  551. NSString *fileName = [[NCUtility sharedInstance] createFileName:[url lastPathComponent] directoryID:directoryID];
  552. NSString *fileID = [directoryID stringByAppendingString:fileName];
  553. NSData *data = [NSData dataWithContentsOfURL:newURL];
  554. if (data && error == nil) {
  555. if ([data writeToFile:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName] options:NSDataWritingAtomic error:&error]) {
  556. tableMetadata *metadataForUpload = [tableMetadata new];
  557. metadataForUpload.account = appDelegate.activeAccount;
  558. metadataForUpload.date = [NSDate new];
  559. metadataForUpload.directoryID = directoryID;
  560. metadataForUpload.fileID = fileID;
  561. metadataForUpload.fileName = fileName;
  562. metadataForUpload.fileNameView = fileName;
  563. metadataForUpload.session = k_upload_session;
  564. metadataForUpload.sessionSelector = selectorUploadFile;
  565. metadataForUpload.size = data.length;
  566. metadataForUpload.status = k_metadataStatusWaitUpload;
  567. // Check il file already exists
  568. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView == %@", directoryID, fileName]];
  569. if (metadata) {
  570. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileName message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  571. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  572. // NO OVERWITE
  573. }];
  574. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  575. // Remove record metadata
  576. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  577. // Add Medtadata for upload
  578. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  579. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  580. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  581. }];
  582. [alertController addAction:cancelAction];
  583. [alertController addAction:overwriteAction];
  584. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  585. alertWindow.rootViewController = [[UIViewController alloc]init];
  586. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  587. [alertWindow makeKeyAndVisible];
  588. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  589. } else {
  590. // Add Medtadata for upload
  591. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  592. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  593. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  594. }
  595. } else {
  596. [appDelegate messageNotification:@"_error_" description:error.description visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  597. }
  598. } else {
  599. [appDelegate messageNotification:@"_error_" description:@"_read_file_error_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  600. }
  601. }];
  602. }
  603. }
  604. - (void)openImportDocumentPicker
  605. {
  606. UIDocumentMenuViewController *documentProviderMenu = [[UIDocumentMenuViewController alloc] initWithDocumentTypes:@[@"public.data"] inMode:UIDocumentPickerModeImport];
  607. documentProviderMenu.modalPresentationStyle = UIModalPresentationFormSheet;
  608. documentProviderMenu.popoverPresentationController.sourceView = self.tabBarController.tabBar;
  609. documentProviderMenu.popoverPresentationController.sourceRect = self.tabBarController.tabBar.bounds;
  610. documentProviderMenu.delegate = self;
  611. [self presentViewController:documentProviderMenu animated:YES completion:nil];
  612. }
  613. #pragma --------------------------------------------------------------------------------------------
  614. #pragma mark ===== Assets Picker =====
  615. #pragma --------------------------------------------------------------------------------------------
  616. -(void)dismissFormUploadAssets
  617. {
  618. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  619. }
  620. - (void)openAssetsPickerController
  621. {
  622. NCPhotosPickerViewController *viewController = [[NCPhotosPickerViewController alloc] init:self];
  623. [viewController openPhotosPickerViewControllerWithPhAssets:^(NSArray<PHAsset *> * _Nonnull assets) {
  624. if (assets.count > 0) {
  625. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  626. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  627. NCCreateFormUploadAssets *form = [[NCCreateFormUploadAssets alloc] initWithServerUrl:serverUrl assets:(NSMutableArray *)assets cryptated:NO session:k_upload_session delegate:self];
  628. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:form];
  629. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  630. [self presentViewController:navigationController animated:YES completion:nil];
  631. });
  632. }
  633. }];
  634. }
  635. #pragma --------------------------------------------------------------------------------------------
  636. #pragma mark ===== Save selected File =====
  637. #pragma --------------------------------------------------------------------------------------------
  638. - (void)saveToPhotoAlbum:(tableMetadata *)metadata
  639. {
  640. NSString *fileNamePath = [CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView];
  641. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  642. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] && status == PHAuthorizationStatusAuthorized) {
  643. UIImage *image = [UIImage imageWithContentsOfFile:fileNamePath];
  644. if (image)
  645. UIImageWriteToSavedPhotosAlbum(image, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  646. else
  647. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  648. }
  649. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_video] && status == PHAuthorizationStatusAuthorized) {
  650. if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(fileNamePath)) {
  651. UISaveVideoAtPathToSavedPhotosAlbum(fileNamePath, self, @selector(saveSelectedFilesSelector: didFinishSavingWithError: contextInfo:), nil);
  652. } else {
  653. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  654. }
  655. }
  656. if (status != PHAuthorizationStatusAuthorized) {
  657. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_access_photo_not_enabled_", nil) message:NSLocalizedString(@"_access_photo_not_enabled_msg_", nil) preferredStyle:UIAlertControllerStyleAlert];
  658. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  659. [alertController addAction:okAction];
  660. [self presentViewController:alertController animated:YES completion:nil];
  661. }
  662. }
  663. - (void)saveSelectedFilesSelector:(NSString *)path didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
  664. {
  665. if (error)
  666. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_not_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  667. else
  668. [appDelegate messageNotification:@"_save_selected_files_" description:@"_file_saved_cameraroll_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:error.code];
  669. }
  670. - (void)saveSelectedFiles
  671. {
  672. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  673. return;
  674. NSLog(@"[LOG] Start download selected files ...");
  675. [_hud visibleHudTitle:@"" mode:MBProgressHUDModeIndeterminate color:nil];
  676. NSArray *metadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  677. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.01 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  678. for (tableMetadata *metadata in metadatas) {
  679. if (metadata.directory == NO && ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video])) {
  680. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  681. if (serverUrl) {
  682. metadata.session = k_download_session;
  683. metadata.sessionError = @"";
  684. metadata.sessionSelector = selectorSave;
  685. metadata.status = k_metadataStatusWaitDownload;
  686. // Add Metadata for Download
  687. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  688. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  689. }
  690. }
  691. }
  692. [_hud hideHud];
  693. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  694. });
  695. [self tableViewSelect:NO];
  696. }
  697. #pragma --------------------------------------------------------------------------------------------
  698. #pragma mark ==== View Notification ====
  699. #pragma --------------------------------------------------------------------------------------------
  700. - (void)viewNotification
  701. {
  702. if ([appDelegate.listOfNotifications count] > 0) {
  703. CCNotification *notificationVC = [[UIStoryboard storyboardWithName:@"CCNotification" bundle:nil] instantiateViewControllerWithIdentifier:@"CCNotification"];
  704. [notificationVC setModalPresentationStyle:UIModalPresentationFormSheet];
  705. [self presentViewController:notificationVC animated:YES completion:nil];
  706. }
  707. }
  708. #pragma --------------------------------------------------------------------------------------------
  709. #pragma mark === Delegate Login ===
  710. #pragma --------------------------------------------------------------------------------------------
  711. - (void)loginSuccess:(NSInteger)loginType
  712. {
  713. [_imageTitleHome setUserInteractionEnabled:NO];
  714. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  715. // go to home sweet home
  716. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  717. [_imageTitleHome setUserInteractionEnabled:YES];
  718. });
  719. [appDelegate subscribingNextcloudServerPushNotification];
  720. }
  721. #pragma mark -
  722. #pragma --------------------------------------------------------------------------------------------
  723. #pragma mark ===== Peek & Pop =====
  724. #pragma --------------------------------------------------------------------------------------------
  725. - (UIViewController *)previewingContext:(id<UIViewControllerPreviewing>)previewingContext viewControllerForLocation:(CGPoint)location
  726. {
  727. CGPoint convertedLocation = [self.view convertPoint:location toView:self.tableView];
  728. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:convertedLocation];
  729. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  730. if (metadata.hasPreview == 1) {
  731. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  732. if (cell) {
  733. previewingContext.sourceRect = cell.frame;
  734. CCPeekPop *vc = [[UIStoryboard storyboardWithName:@"CCPeekPop" bundle:nil] instantiateViewControllerWithIdentifier:@"PeekPopImagePreview"];
  735. vc.delegate = self;
  736. vc.metadata = metadata;
  737. return vc;
  738. }
  739. }
  740. return nil;
  741. }
  742. - (void)previewingContext:(id<UIViewControllerPreviewing>)previewingContext commitViewController:(UIViewController *)viewControllerToCommit
  743. {
  744. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:previewingContext.sourceRect.origin];
  745. [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
  746. }
  747. #pragma --------------------------------------------------------------------------------------------
  748. #pragma mark ==== Download ====
  749. #pragma --------------------------------------------------------------------------------------------
  750. - (void)downloadSelectedFilesFolders
  751. {
  752. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  753. return;
  754. NSLog(@"[LOG] Start download selected ...");
  755. [_hud visibleHudTitle:NSLocalizedString(@"_downloading_progress_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  756. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  757. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  758. for (tableMetadata *metadata in selectedMetadatas) {
  759. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  760. if (serverUrl == nil) continue;
  761. if (metadata.directory) {
  762. [[CCSynchronize sharedSynchronize] readFolder:[CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName] selector:selectorReadFolderWithDownload];
  763. } else {
  764. [[CCSynchronize sharedSynchronize] readFile:metadata.fileID fileName:metadata.fileName serverUrl:serverUrl selector:selectorReadFileWithDownload];
  765. }
  766. }
  767. [_hud hideHud];
  768. });
  769. [self tableViewSelect:NO];
  770. }
  771. #pragma --------------------------------------------------------------------------------------------
  772. #pragma mark ===== Upload new Photos/Videos =====
  773. #pragma --------------------------------------------------------------------------------------------
  774. //
  775. // This procedure with performSelectorOnMainThread it's necessary after (Bridge) for use the function "Sync" in OCNetworking
  776. //
  777. - (void)uploadFileAsset:(NSMutableArray *)assets serverUrl:(NSString *)serverUrl useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  778. {
  779. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  780. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  781. // if request create the folder for Auto Upload & the subfolders
  782. if ([autoUploadPath isEqualToString:serverUrl])
  783. if (![[NCAutoUpload sharedInstance] createAutoUploadFolderWithSubFolder:useSubFolder assets:(PHFetchResult *)assets selector:selectorUploadFile])
  784. return;
  785. dispatch_async(dispatch_get_main_queue(), ^{
  786. [self uploadFileAsset:assets serverUrl:serverUrl autoUploadPath:autoUploadPath useSubFolder:useSubFolder session:session];
  787. });
  788. });
  789. }
  790. - (void)uploadFileAsset:(NSArray *)assets serverUrl:(NSString *)serverUrl autoUploadPath:(NSString *)autoUploadPath useSubFolder:(BOOL)useSubFolder session:(NSString *)session
  791. {
  792. for (PHAsset *asset in assets) {
  793. tableMetadata *metadata;
  794. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  795. NSDate *assetDate = asset.creationDate;
  796. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  797. // Create serverUrl if use sub folder
  798. if (useSubFolder) {
  799. [formatter setDateFormat:@"yyyy"];
  800. NSString *yearString = [formatter stringFromDate:assetDate];
  801. [formatter setDateFormat:@"MM"];
  802. NSString *monthString = [formatter stringFromDate:assetDate];
  803. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  804. }
  805. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  806. if (!directoryID) return;
  807. // Check if is in upload
  808. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileName == %@ AND session != ''", directoryID, fileName];
  809. NSArray *isRecordInSessions = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  810. if ([isRecordInSessions count] > 0)
  811. continue;
  812. // Prepare record metadata
  813. tableMetadata *metadataForUpload = [tableMetadata new];
  814. metadataForUpload.account = appDelegate.activeAccount;
  815. metadataForUpload.assetLocalIdentifier = asset.localIdentifier;
  816. metadataForUpload.date = [NSDate new];
  817. metadataForUpload.directoryID = directoryID;
  818. metadataForUpload.fileID = [directoryID stringByAppendingString:fileName];
  819. metadataForUpload.fileName = fileName;
  820. metadataForUpload.fileNameView = fileName;
  821. metadataForUpload.session = session;
  822. metadataForUpload.sessionSelector = selectorUploadFile;
  823. metadataForUpload.size = [[NCUtility sharedInstance] getFileSizeWithAsset:asset];
  824. metadataForUpload.status = k_metadataStatusWaitUpload;
  825. NSString *fileNameExtension = [fileName pathExtension];
  826. NSString *fileNameWithoutExtension = [fileName stringByDeletingPathExtension];
  827. if ([[fileNameExtension lowercaseString] isEqualToString:@"heic"] && [CCUtility getFormatCompatibility]) {
  828. NSString *fileNameCompatibility = [fileNameWithoutExtension stringByAppendingString:@".jpg"];
  829. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView == %@", directoryID, fileNameCompatibility]];
  830. } else {
  831. metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView == %@", directoryID, fileName]];
  832. }
  833. // Check il file already exists
  834. if (metadata) {
  835. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:fileNameWithoutExtension message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  836. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  837. // NO OVERWITE
  838. }];
  839. UIAlertAction *overwriteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_overwrite_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  840. // Remove record metadata
  841. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID] clearDateReadDirectoryID:metadata.directoryID];
  842. // Add Medtadata for upload
  843. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  844. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  845. }];
  846. [alertController addAction:cancelAction];
  847. [alertController addAction:overwriteAction];
  848. UIWindow *alertWindow = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
  849. alertWindow.rootViewController = [[UIViewController alloc]init];
  850. alertWindow.windowLevel = UIWindowLevelAlert + 1;
  851. [alertWindow makeKeyAndVisible];
  852. [alertWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
  853. } else {
  854. // Add Medtadata for upload
  855. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  856. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  857. }
  858. }
  859. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  860. }
  861. #pragma --------------------------------------------------------------------------------------------
  862. #pragma mark ==== Read File ====
  863. #pragma --------------------------------------------------------------------------------------------
  864. - (void)readFileSuccessFailure:(CCMetadataNet *)metadataNet metadata:(tableMetadata *)metadata message:(NSString *)message errorCode:(NSInteger)errorCode
  865. {
  866. // Check Active Account
  867. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  868. return;
  869. if (errorCode == 0) {
  870. // Read Folder
  871. if ([metadataNet.selector isEqualToString:selectorReadFileReloadFolder]) {
  872. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", metadataNet.account, metadataNet.serverUrl]];
  873. // Change etag, read folder
  874. if ([metadata.etag isEqualToString:directory.etag] == NO) {
  875. [self readFolder:metadataNet.serverUrl];
  876. }
  877. }
  878. } else {
  879. // Unauthorized
  880. if (errorCode == kOCErrorServerUnauthorized)
  881. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  882. }
  883. }
  884. - (void)readFileReloadFolder
  885. {
  886. if (!_serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode)
  887. return;
  888. // Load Datasource
  889. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  890. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  891. });
  892. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  893. metadataNet.action = actionReadFile;
  894. metadataNet.priority = NSOperationQueuePriorityHigh;
  895. metadataNet.selector = selectorReadFileReloadFolder;
  896. metadataNet.serverUrl = _serverUrl;
  897. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  898. }
  899. #pragma --------------------------------------------------------------------------------------------
  900. #pragma mark ==== Read Folder ====
  901. #pragma --------------------------------------------------------------------------------------------
  902. - (void)readFolderSuccessFailure:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  903. {
  904. // stoprefresh
  905. [refreshControl endRefreshing];
  906. // Check Active Account
  907. if (![metadataNet.account isEqualToString:metadataNet.account])
  908. return;
  909. // ERROR
  910. if (errorCode != 0) {
  911. _loadingFolder = NO;
  912. // Check Active Account
  913. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  914. return;
  915. // Unauthorized
  916. if (errorCode == kOCErrorServerUnauthorized) {
  917. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  918. } else {
  919. [self tableViewReloadData];
  920. [_imageTitleHome setUserInteractionEnabled:YES];
  921. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  922. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  923. }
  924. return;
  925. }
  926. // save metadataFolder
  927. _metadataFolder = metadataFolder;
  928. if (_isSearchMode == NO) {
  929. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  930. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusNormal, k_metadataStatusHide] clearDateReadDirectoryID:metadataNet.directoryID];
  931. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  932. }
  933. NSArray *metadatasInDownload = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusWaitDownload, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusDownloadError] sorted:nil ascending:NO];
  934. // insert in Database
  935. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas serverUrl:metadataNet.serverUrl];
  936. // insert in Database the /
  937. if (metadataFolder != nil) {
  938. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataFolder];
  939. }
  940. // reinsert metadatas in Download
  941. if (metadatasInDownload) {
  942. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload serverUrl:metadataNet.serverUrl];
  943. }
  944. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  945. // File is changed ??
  946. if (!_isSearchMode && metadatasToInsertInDB)
  947. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  948. });
  949. // Search Mode
  950. if (_isSearchMode) {
  951. // Fix managed -> Unmanaged _searchResultMetadatas
  952. if (metadatasToInsertInDB)
  953. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  954. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  955. }
  956. // this is the same directory
  957. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  958. // reload
  959. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  960. // Enable change user
  961. [_imageTitleHome setUserInteractionEnabled:YES];
  962. _loadingFolder = NO;
  963. [self tableViewReloadData];
  964. }
  965. // E2EE Is encrypted folder get metadata
  966. if (_metadataFolder.e2eEncrypted) {
  967. // Read Metadata
  968. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  969. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  970. NSString *metadata;
  971. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:metadataFolder.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  972. dispatch_async(dispatch_get_main_queue(), ^{
  973. if (error) {
  974. if (error.code != 404)
  975. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  976. } else {
  977. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  978. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  979. else
  980. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  981. }
  982. });
  983. });
  984. } else {
  985. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  986. }
  987. }
  988. // rewrite title
  989. [self setTitle];
  990. }
  991. - (void)readFolder:(NSString *)serverUrl
  992. {
  993. // init control
  994. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  995. [refreshControl endRefreshing];
  996. return;
  997. }
  998. // Search Mode
  999. if (_isSearchMode) {
  1000. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1001. _searchFileName = @""; // forced reload searchg
  1002. [self updateSearchResultsForSearchController:self.searchController];
  1003. return;
  1004. }
  1005. _loadingFolder = YES;
  1006. [self tableViewReloadData];
  1007. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1008. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1009. metadataNet.action = actionReadFolder;
  1010. metadataNet.date = [NSDate date];
  1011. metadataNet.depth = @"1";
  1012. metadataNet.directoryID = directory.directoryID;
  1013. metadataNet.priority = NSOperationQueuePriorityHigh;
  1014. metadataNet.selector = selectorReadFolder;
  1015. metadataNet.serverUrl = serverUrl;
  1016. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1017. }
  1018. #pragma mark -
  1019. #pragma --------------------------------------------------------------------------------------------
  1020. #pragma mark ===== Search =====
  1021. #pragma --------------------------------------------------------------------------------------------
  1022. - (void)searchEnabled:(BOOL)enabled
  1023. {
  1024. if (enabled) {
  1025. if (self.tableView.tableHeaderView != nil)
  1026. return;
  1027. self.definesPresentationContext = YES;
  1028. self.searchController.searchResultsUpdater = self;
  1029. self.searchController.dimsBackgroundDuringPresentation = NO;
  1030. self.searchController.searchBar.translucent = NO;
  1031. [self.searchController.searchBar sizeToFit];
  1032. self.searchController.searchBar.delegate = self;
  1033. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1034. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1035. self.searchController.searchBar.backgroundImage = [UIImage new];
  1036. // color searchbbar button text (cancel)
  1037. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1038. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1039. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1040. }
  1041. self.tableView.tableHeaderView = self.searchController.searchBar;
  1042. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1043. } else {
  1044. self.tableView.tableHeaderView = nil;
  1045. }
  1046. }
  1047. - (void)searchStartTimer
  1048. {
  1049. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1050. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1051. metadataNet.action = actionSearch;
  1052. metadataNet.contentType = nil;
  1053. metadataNet.date = nil;
  1054. metadataNet.directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:startDirectory];
  1055. metadataNet.fileName = _searchFileName;
  1056. metadataNet.etag = @"";
  1057. metadataNet.depth = @"infinity";
  1058. metadataNet.priority = NSOperationQueuePriorityHigh;
  1059. metadataNet.selector = selectorSearchFiles;
  1060. metadataNet.serverUrl = startDirectory;
  1061. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1062. _noFilesSearchTitle = @"";
  1063. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1064. [self.tableView reloadEmptyDataSet];
  1065. }
  1066. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1067. {
  1068. // Color text "Cancel"
  1069. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1070. _isSearchMode = YES;
  1071. [self deleteRefreshControl];
  1072. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1073. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1074. _searchFileName = fileName;
  1075. // First : filter
  1076. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1077. if (!directoryID) return;
  1078. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView CONTAINS[cd] %@", directoryID, fileName];
  1079. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1080. [_searchResultMetadatas removeAllObjects];
  1081. for (tableMetadata *record in records)
  1082. [_searchResultMetadatas addObject:record];
  1083. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1084. metadataNet.account = appDelegate.activeAccount;
  1085. metadataNet.directoryID = directoryID;
  1086. metadataNet.selector = selectorSearchFiles;
  1087. metadataNet.serverUrl = _serverUrl;
  1088. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1089. // Version >= 12
  1090. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1091. [_timerWaitInput invalidate];
  1092. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1093. }
  1094. }
  1095. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1096. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1097. }
  1098. }
  1099. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1100. {
  1101. [self cancelSearchBar];
  1102. [self readFolder:_serverUrl];
  1103. }
  1104. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1105. {
  1106. // Check Active Account
  1107. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1108. return;
  1109. if (errorCode == 0) {
  1110. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1111. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1112. } else {
  1113. // Unauthorized
  1114. if (errorCode == kOCErrorServerUnauthorized)
  1115. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1116. else
  1117. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1118. _searchFileName = @"";
  1119. }
  1120. }
  1121. - (void)cancelSearchBar
  1122. {
  1123. if (self.searchController.active) {
  1124. [self.searchController setActive:NO];
  1125. [self createRefreshControl];
  1126. _isSearchMode = NO;
  1127. _searchFileName = @"";
  1128. _dateReadDataSource = nil;
  1129. _searchResultMetadatas = [NSMutableArray new];
  1130. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1131. }
  1132. //[self setNeedsStatusBarAppearanceUpdate];
  1133. }
  1134. #pragma mark -
  1135. #pragma --------------------------------------------------------------------------------------------
  1136. #pragma mark ===== Delete File or Folder =====
  1137. #pragma --------------------------------------------------------------------------------------------
  1138. - (void)deleteFile
  1139. {
  1140. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1141. return;
  1142. NSArray *metadatas;
  1143. if ([_selectedFileIDsMetadatas count] > 0) {
  1144. metadatas = [_selectedFileIDsMetadatas allValues];
  1145. } else {
  1146. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1147. }
  1148. // remove optimization
  1149. _dateReadDataSource = nil;
  1150. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderFileID:_metadataFolder.fileID completion:^(NSInteger errorCode, NSString *message) {
  1151. // Reload
  1152. if (_isSearchMode)
  1153. [self readFolder:self.serverUrl];
  1154. else
  1155. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1156. }];
  1157. // End Select Table View
  1158. [self tableViewSelect:NO];
  1159. }
  1160. #pragma --------------------------------------------------------------------------------------------
  1161. #pragma mark ===== Rename / Move =====
  1162. #pragma --------------------------------------------------------------------------------------------
  1163. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1164. {
  1165. // Rename metadata
  1166. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:metadataNet.fileNameTo fileID:metadataNet.fileID];
  1167. if (metadataNet.directory) {
  1168. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadataNet.fileName];
  1169. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadataNet.fileNameTo];
  1170. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1171. if (directoryTable == nil) {
  1172. [self renameMoveFileOrFolderFailure:metadataNet message:@"Internal error, ServerUrl not found" errorCode:0];
  1173. return;
  1174. }
  1175. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:nil fileID:nil encrypted:directoryTable.e2eEncrypted];
  1176. } else {
  1177. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadataNet.fileID date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:metadataNet.fileNameTo etag:nil];
  1178. // Move file system
  1179. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadataNet.fileID], metadataNet.fileName];
  1180. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadataNet.fileID], metadataNet.fileNameTo];
  1181. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1182. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileName];
  1183. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileNameTo];
  1184. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1185. }
  1186. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:metadataNet.fileID action:k_action_MOD];
  1187. }
  1188. - (void)renameFile:(NSArray *)arguments
  1189. {
  1190. tableMetadata* metadata = [arguments objectAtIndex:0];
  1191. NSString *fileName = [arguments objectAtIndex:1];
  1192. // E2EE
  1193. if (_metadataFolder.e2eEncrypted) {
  1194. // verify if exists the new fileName
  1195. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1196. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1197. return;
  1198. }
  1199. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1200. NSError *error = [[NCNetworkingEndToEnd sharedManager] sendEndToEndMetadataOnServerUrl:self.serverUrl fileNameRename:metadata.fileName fileNameNewRename:fileName account:appDelegate.activeAccount user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1201. if (error) {
  1202. dispatch_async(dispatch_get_main_queue(), ^{
  1203. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1204. });
  1205. } else {
  1206. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1207. // Move file system
  1208. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1209. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1210. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1211. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1212. }
  1213. // Unlock
  1214. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1215. if (tableLock != nil) {
  1216. NSError *error = [[NCNetworkingEndToEnd sharedManager] unlockEndToEndFolderEncryptedOnServerUrl:self.serverUrl fileID:_metadataFolder.fileID token:tableLock.token user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1217. if (error) {
  1218. dispatch_async(dispatch_get_main_queue(), ^{
  1219. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1220. });
  1221. }
  1222. }
  1223. dispatch_async(dispatch_get_main_queue(), ^{
  1224. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1225. });
  1226. });
  1227. } else {
  1228. // Plain
  1229. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1230. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1231. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1232. return;
  1233. }
  1234. // Verify if exists the fileName TO
  1235. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1236. [ocNetworking readFile:fileNameNew serverUrl:serverUrl account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1237. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1238. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1239. }];
  1240. [alert addAction:ok];
  1241. [self presentViewController:alert animated:YES completion:nil];
  1242. } failure:^(NSString *message, NSInteger errorCode) {
  1243. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1244. metadataNet.action = actionMoveFileOrFolder;
  1245. metadataNet.directory = metadata.directory;
  1246. metadataNet.fileID = metadata.fileID;
  1247. metadataNet.fileName = metadata.fileName;
  1248. metadataNet.fileNameTo = fileNameNew;
  1249. metadataNet.fileNameView = metadata.fileNameView;
  1250. metadataNet.selector = selectorRename;
  1251. metadataNet.serverUrl = serverUrl;
  1252. metadataNet.serverUrlTo = serverUrl;
  1253. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1254. }];
  1255. }
  1256. }
  1257. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1258. {
  1259. if ([message length] > 0) {
  1260. if ([metadataNet.selector isEqualToString:selectorRename]) {
  1261. [appDelegate messageNotification:@"_rename_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1262. }
  1263. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1264. [appDelegate messageNotification:@"_move_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1265. }
  1266. }
  1267. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1268. [_hud hideHud];
  1269. if (message && errorCode != kOCErrorServerUnauthorized)
  1270. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1271. // End Select Table View
  1272. [self tableViewSelect:NO];
  1273. // reload Datasource
  1274. if (_isSearchMode)
  1275. [self readFolder:metadataNet.serverUrl];
  1276. else
  1277. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1278. }
  1279. }
  1280. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1281. {
  1282. [_queueSelector removeObject:metadataNet.selector];
  1283. if ([_queueSelector count] == 0) {
  1284. [_hud hideHud];
  1285. NSString *fileName = metadataNet.fileName;
  1286. NSString *directoryID = metadataNet.directoryID;
  1287. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1288. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1289. if (!serverUrlTo) return;
  1290. // FILE -> Metadata
  1291. if (metadataNet.directory == NO)
  1292. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1293. // DIRECTORY -> Directory - CCMetadata
  1294. if (metadataNet.directory == YES) {
  1295. // delete all dir / subdir
  1296. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1297. // move metadata
  1298. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1299. // Add new directory
  1300. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1301. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1302. }
  1303. // next
  1304. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1305. if ([_selectedFileIDsMetadatas count] > 0) {
  1306. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1307. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1308. } else {
  1309. // End Select Table View
  1310. [self tableViewSelect:NO];
  1311. // reload Datasource
  1312. if (_isSearchMode)
  1313. [self readFolder:metadataNet.serverUrl];
  1314. else
  1315. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1316. }
  1317. }
  1318. }
  1319. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1320. {
  1321. tableMetadata *metadata = [arguments objectAtIndex:0];
  1322. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1323. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1324. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1325. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1326. if (!serverUrl) return;
  1327. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1328. if (!directoryIDTo) return;
  1329. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1330. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1331. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1332. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1333. }];
  1334. [alert addAction:ok];
  1335. [self presentViewController:alert animated:YES completion:nil];
  1336. // End Select Table View
  1337. [self tableViewSelect:NO];
  1338. // reload Datasource
  1339. [self readFileReloadFolder];
  1340. } failure:^(NSString *message, NSInteger errorCode) {
  1341. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1342. metadataNet.action = actionMoveFileOrFolder;
  1343. metadataNet.directory = metadata.directory;
  1344. metadataNet.fileID = metadata.fileID;
  1345. metadataNet.directoryID = metadata.directoryID;
  1346. metadataNet.directoryIDTo = directoryIDTo;
  1347. metadataNet.fileName = metadata.fileName;
  1348. metadataNet.fileNameView = metadata.fileNameView;
  1349. metadataNet.fileNameTo = metadata.fileName;
  1350. metadataNet.etag = metadata.etag;
  1351. metadataNet.selector = selectorMove;
  1352. metadataNet.serverUrl = serverUrl;
  1353. metadataNet.serverUrlTo = serverUrlTo;
  1354. [_queueSelector addObject:metadataNet.selector];
  1355. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1356. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1357. }];
  1358. }
  1359. // DELEGATE : Select
  1360. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1361. {
  1362. if (serverUrl == nil) {
  1363. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1364. } else {
  1365. [_queueSelector removeAllObjects];
  1366. // E2EE DENIED
  1367. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1368. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1369. return;
  1370. }
  1371. if ([_selectedFileIDsMetadatas count] > 0) {
  1372. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1373. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1374. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrl, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1375. } else {
  1376. _numSelectedFileIDsMetadatas = 1;
  1377. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[self.metadata, serverUrl, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1378. }
  1379. }
  1380. }
  1381. - (void)moveOpenWindow:(NSArray *)indexPaths
  1382. {
  1383. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1384. return;
  1385. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1386. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1387. viewController.delegate = self;
  1388. viewController.hideButtonCreateFolder = false;
  1389. viewController.selectFile = false;
  1390. viewController.includeDirectoryE2EEncryption = false;
  1391. viewController.includeImages = false;
  1392. viewController.type = @"";
  1393. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1394. viewController.layoutViewSelect = k_layout_view_move;
  1395. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1396. [self presentViewController:navigationController animated:YES completion:nil];
  1397. }
  1398. #pragma --------------------------------------------------------------------------------------------
  1399. #pragma mark ===== Create folder =====
  1400. #pragma --------------------------------------------------------------------------------------------
  1401. - (void)createFolder
  1402. {
  1403. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1404. NSString *message;
  1405. UIAlertController *alertController;
  1406. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1407. message = @"/";
  1408. } else {
  1409. message = [serverUrl lastPathComponent];
  1410. }
  1411. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1412. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1413. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1414. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  1415. }];
  1416. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1417. NSLog(@"[LOG] Cancel action");
  1418. }];
  1419. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1420. UITextField *fileName = alertController.textFields.firstObject;
  1421. [self createFolder:fileName.text serverUrl:serverUrl];
  1422. }];
  1423. okAction.enabled = NO;
  1424. [alertController addAction:cancelAction];
  1425. [alertController addAction:okAction];
  1426. [self presentViewController:alertController animated:YES completion:nil];
  1427. }
  1428. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1429. {
  1430. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1431. if (![fileNameFolder length]) return;
  1432. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1433. if (!directoryID) return;
  1434. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1435. // Create Directory (temp) on metadata
  1436. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp directoryID:directoryID fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal url:@""];
  1437. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1438. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1439. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1440. // Creeate folder Networking
  1441. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1442. [ocNetworking createFolder:fileNameFolder serverUrl:serverUrl account:appDelegate.activeAccount success:^(NSString *fileID, NSDate *date) {
  1443. // Delete Temp Dir
  1444. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1445. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1446. if (_metadataFolder.e2eEncrypted) {
  1447. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1448. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1449. dispatch_async(dispatch_get_main_queue(), ^{
  1450. if (error) {
  1451. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1452. }
  1453. [self readFolder:self.serverUrl];
  1454. });
  1455. });
  1456. } else {
  1457. [self readFolder:self.serverUrl];
  1458. }
  1459. } failure:^(NSString *message, NSInteger errorCode) {
  1460. // Unauthorized
  1461. if (errorCode == kOCErrorServerUnauthorized)
  1462. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1463. else
  1464. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1465. // Delete Temp Dir
  1466. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1467. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1468. // We are in directory fail ?
  1469. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:fileNameFolder]];
  1470. if (vc)
  1471. [vc.navigationController popViewControllerAnimated:YES];
  1472. }];
  1473. }
  1474. #pragma --------------------------------------------------------------------------------------------
  1475. #pragma mark ===== Progress & Task Button =====
  1476. #pragma --------------------------------------------------------------------------------------------
  1477. - (void)triggerProgressTask:(NSNotification *)notification
  1478. {
  1479. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1480. }
  1481. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1482. {
  1483. UITouch *touch = [[event allTouches] anyObject];
  1484. CGPoint location = [touch locationInView:self.tableView];
  1485. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1486. if ([self indexPathIsValid:indexPath]) {
  1487. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1488. if (metadataSection) {
  1489. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1490. if (metadata)
  1491. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true];
  1492. }
  1493. }
  1494. }
  1495. - (void)cancelAllTask:(id)sender
  1496. {
  1497. CGPoint location = [sender locationInView:self.tableView];
  1498. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1499. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1500. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1501. [[NCMainCommon sharedInstance] cancelAllTransferWithView:self.view];
  1502. }]];
  1503. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1504. alertController.popoverPresentationController.sourceView = self.tableView;
  1505. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1506. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1507. [alertController.view layoutIfNeeded];
  1508. [self presentViewController:alertController animated:YES completion:nil];
  1509. }
  1510. #pragma --------------------------------------------------------------------------------------------
  1511. #pragma mark ===== Shared =====
  1512. #pragma --------------------------------------------------------------------------------------------
  1513. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1514. {
  1515. [_hud hideHud];
  1516. // Check Active Account
  1517. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1518. return;
  1519. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1520. if (result) {
  1521. appDelegate.sharesLink = result[0];
  1522. appDelegate.sharesUserAndGroup = result[1];
  1523. }
  1524. // Notify Shares View
  1525. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1526. if (openWindow) {
  1527. if (_shareOC) {
  1528. [_shareOC reloadData];
  1529. } else {
  1530. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1531. // Apriamo la view
  1532. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1533. _shareOC.delegate = self;
  1534. _shareOC.metadata = metadata;
  1535. _shareOC.serverUrl = metadataNet.serverUrl;
  1536. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1537. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1538. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1539. [self presentViewController:_shareOC animated:YES completion:nil];
  1540. }
  1541. }
  1542. [self tableViewReloadData];
  1543. }
  1544. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1545. {
  1546. [_hud hideHud];
  1547. // Check Active Account
  1548. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1549. return;
  1550. // Unauthorized
  1551. if (errorCode == kOCErrorServerUnauthorized)
  1552. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1553. else
  1554. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1555. if (_shareOC)
  1556. [_shareOC reloadData];
  1557. [self tableViewReloadData];
  1558. }
  1559. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1560. {
  1561. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1562. metadataNet.action = actionShare;
  1563. metadataNet.fileID = metadata.fileID;
  1564. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1565. metadataNet.fileNameView = metadata.fileNameView;
  1566. metadataNet.hideDownload = hideDownload;
  1567. metadataNet.sharePermission = permission;
  1568. metadataNet.password = password;
  1569. metadataNet.selector = selectorShare;
  1570. metadataNet.serverUrl = serverUrl;
  1571. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1572. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1573. }
  1574. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1575. {
  1576. [_hud hideHud];
  1577. // Check Active Account
  1578. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1579. return;
  1580. // rimuoviamo la condivisione da db
  1581. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1582. if (result) {
  1583. appDelegate.sharesLink = result[0];
  1584. appDelegate.sharesUserAndGroup = result[1];
  1585. }
  1586. if (_shareOC)
  1587. [_shareOC reloadData];
  1588. [self tableViewReloadData];
  1589. }
  1590. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1591. {
  1592. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1593. metadataNet.action = actionUnShare;
  1594. metadataNet.fileID = metadata.fileID;
  1595. metadataNet.fileName = metadata.fileName;
  1596. metadataNet.fileNameView = metadata.fileNameView;
  1597. metadataNet.selector = selectorUnshare;
  1598. metadataNet.serverUrl = serverUrl;
  1599. metadataNet.share = share;
  1600. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1601. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1602. }
  1603. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission hideDownload:(BOOL)hideDownload
  1604. {
  1605. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1606. metadataNet.action = actionUpdateShare;
  1607. metadataNet.fileID = metadata.fileID;
  1608. metadataNet.expirationTime = expirationTime;
  1609. metadataNet.hideDownload = hideDownload;
  1610. metadataNet.password = password;
  1611. metadataNet.selector = selectorUpdateShare;
  1612. metadataNet.serverUrl = serverUrl;
  1613. metadataNet.share = share;
  1614. metadataNet.sharePermission = permission;
  1615. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1616. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1617. }
  1618. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1619. {
  1620. [_hud hideHud];
  1621. // Check Active Account
  1622. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1623. return;
  1624. if (_shareOC)
  1625. [_shareOC reloadUserAndGroup:items];
  1626. }
  1627. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1628. {
  1629. [_hud hideHud];
  1630. // Check Active Account
  1631. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1632. return;
  1633. // Unauthorized
  1634. if (errorCode == kOCErrorServerUnauthorized)
  1635. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1636. else
  1637. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1638. }
  1639. - (void)getUserAndGroup:(NSString *)find
  1640. {
  1641. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1642. metadataNet.action = actionGetUserAndGroup;
  1643. metadataNet.optionAny = find;
  1644. metadataNet.selector = selectorGetUserAndGroup;
  1645. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1646. [_hud visibleIndeterminateHud];
  1647. }
  1648. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1649. {
  1650. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1651. metadataNet.action = actionShareWith;
  1652. metadataNet.fileID = metadata.fileID;
  1653. metadataNet.directoryID = directoryID;
  1654. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1655. metadataNet.fileNameView = metadata.fileNameView;
  1656. metadataNet.serverUrl = serverUrl;
  1657. metadataNet.selector = selectorShare;
  1658. metadataNet.share = user;
  1659. metadataNet.shareeType = shareeType;
  1660. metadataNet.sharePermission = permission;
  1661. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1662. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1663. }
  1664. - (void)openWindowShare:(tableMetadata *)metadata
  1665. {
  1666. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1667. if (!serverUrl) return;
  1668. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1669. metadataNet.action = actionReadShareServer;
  1670. metadataNet.fileID = metadata.fileID;
  1671. metadataNet.fileName = metadata.fileName;
  1672. metadataNet.fileNameView = metadata.fileNameView;
  1673. metadataNet.selector = selectorOpenWindowShare;
  1674. metadataNet.serverUrl = serverUrl;
  1675. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1676. [_hud visibleIndeterminateHud];
  1677. }
  1678. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1679. {
  1680. CGPoint location = [tapGesture locationInView:self.tableView];
  1681. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1682. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1683. if (metadata)
  1684. [self openWindowShare:metadata];
  1685. }
  1686. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1687. {
  1688. CGPoint location = [tapGesture locationInView:self.tableView];
  1689. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1690. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1691. if (metadata) {
  1692. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1693. vc.metadata = metadata;
  1694. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1695. [self presentViewController:vc animated:YES completion:nil];
  1696. }
  1697. }
  1698. #pragma --------------------------------------------------------------------------------------------
  1699. #pragma mark ===== Favorite =====
  1700. #pragma --------------------------------------------------------------------------------------------
  1701. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1702. {
  1703. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1704. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1705. [ocNetworking settingFavorite:fileNameServerUrl favorite:favorite completion:^(NSString *message, NSInteger errorCode) {
  1706. if (errorCode == 0) {
  1707. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1708. _dateReadDataSource = nil;
  1709. if (_isSearchMode)
  1710. [self readFolder:self.serverUrl];
  1711. else
  1712. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1713. if (metadata.directory && favorite) {
  1714. NSString *dir = [CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName];
  1715. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1716. }
  1717. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1718. metadata.favorite = favorite;
  1719. metadata.session = k_download_session;
  1720. metadata.sessionError = @"";
  1721. metadata.sessionSelector = selectorDownloadSynchronize;
  1722. metadata.status = k_metadataStatusWaitDownload;
  1723. // Add Metadata for Download
  1724. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1725. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1726. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1727. }
  1728. } else {
  1729. if (errorCode == kOCErrorServerUnauthorized)
  1730. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1731. }
  1732. }];
  1733. }
  1734. #pragma --------------------------------------------------------------------------------------------
  1735. #pragma mark ===== Open in... =====
  1736. #pragma --------------------------------------------------------------------------------------------
  1737. - (void)DownloadOpenIn:(tableMetadata *)metadata
  1738. {
  1739. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1740. if (!serverUrl) return;
  1741. metadata.session = k_download_session;
  1742. metadata.sessionError = @"";
  1743. metadata.sessionSelector = selectorOpenIn;
  1744. metadata.status = k_metadataStatusWaitDownload;
  1745. // Add Metadata for Download
  1746. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1747. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1748. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1749. }
  1750. - (void)openIn:(tableMetadata *)metadata
  1751. {
  1752. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  1753. docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1754. docController.delegate = self;
  1755. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1756. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1757. if (cell) {
  1758. [docController presentOptionsMenuFromRect:cell.frame inView:self.tableView animated:YES];
  1759. } else {
  1760. [docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1761. }
  1762. }
  1763. #pragma --------------------------------------------------------------------------------------------
  1764. #pragma mark ==== Menu LOGO ====
  1765. #pragma --------------------------------------------------------------------------------------------
  1766. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1767. {
  1768. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1769. return;
  1770. // Brand
  1771. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1772. return;
  1773. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1774. NSMutableArray *menuArray = [NSMutableArray new];
  1775. for (NSString *account in listAccount) {
  1776. CCMenuItem *item = [[CCMenuItem alloc] init];
  1777. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1778. item.argument = account;
  1779. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1780. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  1781. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1782. if (avatar) {
  1783. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1784. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1785. CGSize imageSize = avatarImageView.bounds.size;
  1786. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1787. CGContextRef context = UIGraphicsGetCurrentContext();
  1788. [avatarImageView.layer renderInContext:context];
  1789. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1790. UIGraphicsEndImageContext();
  1791. } else {
  1792. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1793. }
  1794. item.image = avatar;
  1795. item.target = self;
  1796. if ([account isEqualToString:appDelegate.activeAccount]) {
  1797. item.action = nil;
  1798. [menuArray insertObject:item atIndex:0];
  1799. } else {
  1800. item.action = @selector(changeDefaultAccount:);
  1801. [menuArray addObject:item];
  1802. }
  1803. }
  1804. // Add + new account
  1805. CCMenuItem *item = [[CCMenuItem alloc] init];
  1806. item.title = NSLocalizedString(@"_add_account_", nil);
  1807. item.argument = @"";
  1808. item.image = [UIImage imageNamed:@"add"];
  1809. item.target = self;
  1810. item.action = @selector(addNewAccount:);
  1811. [menuArray addObject:item];
  1812. OptionalConfiguration options;
  1813. Color textColor, backgroundColor;
  1814. textColor.R = 0;
  1815. textColor.G = 0;
  1816. textColor.B = 0;
  1817. backgroundColor.R = 1;
  1818. backgroundColor.G = 1;
  1819. backgroundColor.B = 1;
  1820. options.arrowSize = 9;
  1821. options.marginXSpacing = 7;
  1822. options.marginYSpacing = 10;
  1823. options.intervalSpacing = 20;
  1824. options.menuCornerRadius = 6.5;
  1825. options.maskToBackground = NO;
  1826. options.shadowOfMenu = YES;
  1827. options.hasSeperatorLine = YES;
  1828. options.seperatorLineHasInsets = YES;
  1829. options.textColor = textColor;
  1830. options.menuBackgroundColor = backgroundColor;
  1831. CGRect rect = self.view.frame;
  1832. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1833. CGFloat safeAreaTop = 0;
  1834. CGFloat offsetY = 35;
  1835. if (@available(iOS 11, *)) {
  1836. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1837. }
  1838. rect.origin.y = locationY + safeAreaTop + offsetY;
  1839. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1840. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1841. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1842. }
  1843. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1844. {
  1845. NSInteger transferInprogress = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  1846. if (transferInprogress > 0) {
  1847. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1848. return;
  1849. }
  1850. [appDelegate.netQueue cancelAllOperations];
  1851. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1852. // LOGOUT
  1853. [appDelegate unsubscribingNextcloudServerPushNotification];
  1854. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1855. if (tableAccount) {
  1856. // LOGIN
  1857. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  1858. // go to home sweet home
  1859. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1860. [appDelegate subscribingNextcloudServerPushNotification];
  1861. }
  1862. });
  1863. }
  1864. - (void)addNewAccount:(CCMenuItem *)sender
  1865. {
  1866. NSInteger transferInprogress = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND (status == %d OR status == %d OR status == %d OR status == %d)", appDelegate.activeAccount, k_metadataStatusInDownload, k_metadataStatusDownloading, k_metadataStatusInUpload, k_metadataStatusUploading] sorted:@"fileName" ascending:true] count];
  1867. if (transferInprogress > 0) {
  1868. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1869. return;
  1870. }
  1871. [appDelegate.netQueue cancelAllOperations];
  1872. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1873. [appDelegate openLoginView:self loginType:k_login_Add selector:k_intro_login];
  1874. });
  1875. }
  1876. #pragma --------------------------------------------------------------------------------------------
  1877. #pragma mark ==== ReMenu ====
  1878. #pragma --------------------------------------------------------------------------------------------
  1879. - (void)createReMenuBackgroundView:(REMenu *)menu
  1880. {
  1881. CGFloat safeAreaBottom = 0;
  1882. CGFloat safeAreaTop = 0;
  1883. CGFloat statusBar = 0;
  1884. if (@available(iOS 11, *)) {
  1885. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1886. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1887. }
  1888. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1889. statusBar = 13;
  1890. }
  1891. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1892. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1893. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1894. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1895. [UIView animateWithDuration:0.2 animations:^{
  1896. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1897. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1898. if (y>minimum) {
  1899. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1900. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1901. }
  1902. }];
  1903. }
  1904. - (void)createReMainMenu
  1905. {
  1906. NSString *title;
  1907. NSString *groupBy = [CCUtility getGroupBySettings];
  1908. NSString *sorted = [CCUtility getOrderSettings];
  1909. BOOL ascending = [CCUtility getAscendingSettings];
  1910. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1911. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"select"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1912. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1913. }];
  1914. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1915. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1916. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1917. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1918. [CCUtility setOrderSettings:@"fileName"];
  1919. [CCUtility setAscendingSettings:true];
  1920. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1921. }];
  1922. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1923. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1924. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1925. [CCUtility setOrderSettings:@"fileName"];
  1926. [CCUtility setAscendingSettings:false];
  1927. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1928. }];
  1929. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1930. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1931. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1932. [CCUtility setOrderSettings:@"date"];
  1933. [CCUtility setAscendingSettings:false];
  1934. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1935. }];
  1936. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1937. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1938. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1939. [CCUtility setOrderSettings:@"date"];
  1940. [CCUtility setAscendingSettings:true];
  1941. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1942. }];
  1943. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1944. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1945. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1946. [CCUtility setOrderSettings:@"size"];
  1947. [CCUtility setAscendingSettings:true];
  1948. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1949. }];
  1950. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1951. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1952. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1953. [CCUtility setOrderSettings:@"size"];
  1954. [CCUtility setAscendingSettings:false];
  1955. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1956. }];
  1957. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1958. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1959. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1960. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1961. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1962. else [CCUtility setGroupBySettings:@"alphabetic"];
  1963. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1964. }];
  1965. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1966. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1967. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1968. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1969. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1970. else [CCUtility setGroupBySettings:@"typefile"];
  1971. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1972. }];
  1973. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1974. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1975. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1976. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1977. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1978. else [CCUtility setGroupBySettings:@"date"];
  1979. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1980. }];
  1981. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1982. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1983. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1984. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1985. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1986. else [CCUtility setDirectoryOnTop:YES];
  1987. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1988. }];
  1989. // REMENU --------------------------------------------------------------------------------------------------------------
  1990. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.sortFileNameAZItem, appDelegate.sortFileNameZAItem, appDelegate.sortDateMoreRecentItem, appDelegate.sortDateLessRecentItem, appDelegate.sortSmallestItem, appDelegate.sortLargestItem,appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  1991. appDelegate.reMainMenu.itemHeight = 40;
  1992. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1993. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1994. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1995. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1996. appDelegate.reMainMenu.separatorHeight = 0.5;
  1997. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1998. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1999. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2000. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2001. appDelegate.reMainMenu.textShadowColor = nil;
  2002. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2003. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2004. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2005. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2006. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2007. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2008. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2009. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2010. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2011. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2012. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2013. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2014. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2015. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2016. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2017. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2018. appDelegate.reMainMenu.borderWidth = 0.3;
  2019. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2020. appDelegate.reMainMenu.animationDuration = 0.2;
  2021. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2022. appDelegate.reMainMenu.bounce = NO;
  2023. __weak typeof(self) weakSelf = self;
  2024. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2025. // Backgroun reMenu (Gesture)
  2026. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2027. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2028. }];
  2029. }
  2030. - (void)toggleReMainMenu
  2031. {
  2032. if (appDelegate.reMainMenu.isOpen) {
  2033. [appDelegate.reMainMenu close];
  2034. } else {
  2035. [self createReMainMenu];
  2036. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2037. // Backgroun reMenu & (Gesture)
  2038. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2039. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2040. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2041. }
  2042. }
  2043. - (void)createReSelectMenu
  2044. {
  2045. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  2046. appDelegate.selectAllItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_all_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"selectAll"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2047. [self didSelectAll];
  2048. }];
  2049. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  2050. appDelegate.moveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_move_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2051. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2052. }];
  2053. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2054. appDelegate.downloadItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_download_selected_files_folders_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"downloadSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2055. [self downloadSelectedFilesFolders];
  2056. }];
  2057. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2058. appDelegate.saveItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_save_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"saveSelectedFiles"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2059. [self saveSelectedFiles];
  2060. }];
  2061. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2062. appDelegate.deleteItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_delete_selected_files_", nil) subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  2063. [self deleteFile];
  2064. }];
  2065. // E2EE
  2066. if (_metadataFolder.e2eEncrypted) {
  2067. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2068. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  2069. } else {
  2070. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2071. }
  2072. } else {
  2073. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2074. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  2075. } else {
  2076. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2077. }
  2078. }
  2079. appDelegate.reSelectMenu.itemHeight = 50;
  2080. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2081. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2082. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2083. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2084. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2085. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2086. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2087. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2088. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2089. appDelegate.reSelectMenu.textShadowColor = nil;
  2090. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2091. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2092. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2093. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2094. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2095. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2096. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2097. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2098. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2099. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2100. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2101. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2102. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2103. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2104. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2105. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2106. appDelegate.reSelectMenu.borderWidth = 0.3;
  2107. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2108. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2109. appDelegate.reSelectMenu.animationDuration = 0.2;
  2110. appDelegate.reSelectMenu.bounce = NO;
  2111. __weak typeof(self) weakSelf = self;
  2112. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2113. // Backgroun reMenu (Gesture)
  2114. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2115. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2116. }];
  2117. }
  2118. - (void)toggleReSelectMenu
  2119. {
  2120. if (appDelegate.reSelectMenu.isOpen) {
  2121. [appDelegate.reSelectMenu close];
  2122. } else {
  2123. [self createReSelectMenu];
  2124. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2125. // Backgroun reMenu & (Gesture)
  2126. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2127. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2128. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2129. }
  2130. }
  2131. #pragma --------------------------------------------------------------------------------------------
  2132. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2133. #pragma --------------------------------------------------------------------------------------------
  2134. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2135. {
  2136. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2137. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2138. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2139. if ([self indexPathIsValid:indexPath])
  2140. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2141. else
  2142. self.metadata = nil;
  2143. [self becomeFirstResponder];
  2144. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2145. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2146. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2147. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2148. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2149. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2150. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2151. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, pasteFileItem, pasteFilesItem, nil]];
  2152. } else {
  2153. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2154. }
  2155. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2156. [menuController setMenuVisible:YES animated:YES];
  2157. }
  2158. }
  2159. - (BOOL)canBecomeFirstResponder
  2160. {
  2161. return YES;
  2162. }
  2163. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2164. {
  2165. // For copy file, copy files, Open in ... :
  2166. //
  2167. // NO Directory
  2168. // NO Error Passcode
  2169. // NO In Session mode (download/upload)
  2170. // NO Template
  2171. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2172. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  2173. else return NO;
  2174. }
  2175. if (@selector(copyFiles:) == action) {
  2176. if (_isSelectedMode) {
  2177. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2178. for (tableMetadata *metadata in selectedMetadatas) {
  2179. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2180. return YES;
  2181. }
  2182. }
  2183. return NO;
  2184. }
  2185. if (@selector(pasteFile:) == action) {
  2186. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2187. NSArray *items = [pasteboard items];
  2188. if ([items count] == 1) {
  2189. // Value : (NSData) fileID
  2190. NSDictionary *dic = [items objectAtIndex:0];
  2191. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2192. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2193. if (fileID) {
  2194. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2195. if (metadata) {
  2196. return [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView];
  2197. } else {
  2198. return NO;
  2199. }
  2200. }
  2201. }
  2202. return NO;
  2203. }
  2204. if (@selector(pasteFiles:) == action) {
  2205. BOOL isValid = NO;
  2206. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2207. NSArray *items = [pasteboard items];
  2208. if ([items count] <= 1) return NO;
  2209. for (NSDictionary *dic in items) {
  2210. // Value : (NSData) fileID
  2211. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2212. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2213. if (fileID) {
  2214. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2215. if (metadata) {
  2216. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2217. isValid = YES;
  2218. } else {
  2219. isValid = NO;
  2220. break;
  2221. }
  2222. } else {
  2223. isValid = NO;
  2224. break;
  2225. }
  2226. } else {
  2227. isValid = NO;
  2228. break;
  2229. }
  2230. }
  2231. return isValid;
  2232. }
  2233. return NO;
  2234. }
  2235. /************************************ COPY ************************************/
  2236. - (void)copyFile:(id)sender
  2237. {
  2238. // Remove all item
  2239. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2240. pasteboard.items = [[NSArray alloc] init];
  2241. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2242. [self copyFileToPasteboard:self.metadata];
  2243. } else {
  2244. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2245. if (serverUrl) {
  2246. self.metadata.session = k_download_session;
  2247. self.metadata.sessionError = @"";
  2248. self.metadata.sessionSelector = selectorLoadCopy;
  2249. self.metadata.status = k_metadataStatusWaitDownload;
  2250. // Add Metadata for Download
  2251. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2252. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2253. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2254. }
  2255. }
  2256. }
  2257. - (void)copyFiles:(id)sender
  2258. {
  2259. // Remove all item
  2260. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2261. pasteboard.items = [[NSArray alloc] init];
  2262. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2263. for (tableMetadata *metadata in selectedMetadatas) {
  2264. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2265. [self copyFileToPasteboard:metadata];
  2266. } else {
  2267. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2268. if (serverUrl) {
  2269. metadata.session = k_download_session;
  2270. metadata.sessionError = @"";
  2271. metadata.sessionSelector = selectorLoadCopy;
  2272. metadata.status = k_metadataStatusWaitDownload;
  2273. // Add Metadata for Download
  2274. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2275. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2276. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  2277. }
  2278. }
  2279. }
  2280. [self tableViewSelect:NO];
  2281. }
  2282. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2283. {
  2284. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2285. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2286. // Value : (NSData) fileID
  2287. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2288. [items addObject:item];
  2289. [pasteboard setItems:items];
  2290. }
  2291. /************************************ OPEN IN ... ******************************/
  2292. - (void)openinFile:(id)sender
  2293. {
  2294. [self DownloadOpenIn:self.metadata];
  2295. }
  2296. /************************************ PASTE ************************************/
  2297. - (void)pasteFile:(id)sender
  2298. {
  2299. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2300. [self uploadFilePasteArray:[pasteboard items]];
  2301. }
  2302. - (void)pasteFiles:(id)sender
  2303. {
  2304. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2305. [self uploadFilePasteArray:[pasteboard items]];
  2306. }
  2307. - (void)uploadFilePasteArray:(NSArray *)items
  2308. {
  2309. for (NSDictionary *dic in items) {
  2310. // Value : (NSData) fileID
  2311. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2312. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2313. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2314. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2315. if (metadata) {
  2316. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2317. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView directoryID:directoryID];
  2318. NSString *fileID = [directoryID stringByAppendingString:fileName];
  2319. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName]];
  2320. tableMetadata *metadataForUpload = [tableMetadata new];
  2321. metadataForUpload.account = appDelegate.activeAccount;
  2322. metadataForUpload.date = [NSDate new];
  2323. metadataForUpload.directoryID = directoryID;
  2324. metadataForUpload.fileID = fileID;
  2325. metadataForUpload.fileName = fileName;
  2326. metadataForUpload.fileNameView = fileName;
  2327. metadataForUpload.session = k_upload_session;
  2328. metadataForUpload.sessionSelector = selectorUploadFile;
  2329. metadataForUpload.size = metadata.size;
  2330. metadataForUpload.status = k_metadataStatusWaitUpload;
  2331. // Add Medtadata for upload
  2332. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2333. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2334. }
  2335. }
  2336. }
  2337. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2338. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2339. }
  2340. #pragma --------------------------------------------------------------------------------------------
  2341. #pragma mark ===== Lock Passcode =====
  2342. #pragma --------------------------------------------------------------------------------------------
  2343. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2344. {
  2345. return _failedAttempts;
  2346. }
  2347. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2348. {
  2349. return _lockUntilDate;
  2350. }
  2351. - (void)passcodeViewCloseButtonPressed:(id)sender
  2352. {
  2353. [self dismissViewControllerAnimated:YES completion:nil];
  2354. }
  2355. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2356. {
  2357. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2358. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2359. _lockUntilDate = nil;
  2360. _failedAttempts = 0;
  2361. aResultHandler(YES);
  2362. } else aResultHandler(NO);
  2363. } else aResultHandler(YES);
  2364. }
  2365. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2366. {
  2367. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2368. switch (aViewController.type) {
  2369. case BKPasscodeViewControllerCheckPasscodeType: {
  2370. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2371. // possiamo procedere alla prossima directory
  2372. [self performSegueDirectoryWithControlPasscode:false];
  2373. // avviamo la sessione Passcode Lock con now
  2374. appDelegate.sessionePasscodeLock = [NSDate date];
  2375. }
  2376. // disattivazione lock cartella
  2377. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2378. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2379. if (!serverUrl)
  2380. return;
  2381. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2382. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2383. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2384. }
  2385. [self tableViewReloadData];
  2386. }
  2387. }
  2388. break;
  2389. default:
  2390. break;
  2391. }
  2392. }
  2393. - (void)comandoLockPassword
  2394. {
  2395. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2396. if (!serverUrl) return;
  2397. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2398. // se non è abilitato il Lock Passcode esci
  2399. if ([[CCUtility getBlockCode] length] == 0) {
  2400. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2401. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2402. [alertController addAction:okAction];
  2403. [self presentViewController:alertController animated:YES completion:nil];
  2404. return;
  2405. }
  2406. // se è richiesta la disattivazione si chiede la password
  2407. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2408. if (directory.lock) {
  2409. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2410. viewController.delegate = self;
  2411. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2412. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2413. viewController.inputViewTitlePassword = YES;
  2414. if ([CCUtility getSimplyBlockCode]) {
  2415. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2416. viewController.passcodeInputView.maximumLength = 6;
  2417. } else {
  2418. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2419. viewController.passcodeInputView.maximumLength = 64;
  2420. }
  2421. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2422. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2423. viewController.touchIDManager = touchIDManager;
  2424. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2425. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2426. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2427. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2428. [self presentViewController:navigationController animated:YES completion:nil];
  2429. return;
  2430. }
  2431. // ---------------- ACTIVATE PASSWORD
  2432. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2433. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:self.metadata.fileID];
  2434. if ([self indexPathIsValid:indexPath])
  2435. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2436. } else {
  2437. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2438. }
  2439. }
  2440. #pragma mark -
  2441. #pragma --------------------------------------------------------------------------------------------
  2442. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2443. #pragma --------------------------------------------------------------------------------------------
  2444. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2445. {
  2446. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2447. return NO;
  2448. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2449. return NO;
  2450. // E2EE
  2451. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2452. return NO;
  2453. return YES;
  2454. }
  2455. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2456. {
  2457. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2458. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2459. return [self canOpenMenuAction:metadata];
  2460. }
  2461. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2462. {
  2463. }
  2464. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2465. {
  2466. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2467. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2468. if (direction == MGSwipeDirectionRightToLeft) {
  2469. [self actionDelete:indexPath];
  2470. }
  2471. if (direction == MGSwipeDirectionLeftToRight) {
  2472. if (self.metadata.favorite)
  2473. [self settingFavorite:self.metadata favorite:NO];
  2474. else
  2475. [self settingFavorite:self.metadata favorite:YES];
  2476. }
  2477. return YES;
  2478. }
  2479. - (void)actionDelete:(NSIndexPath *)indexPath
  2480. {
  2481. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2482. // Directory locked ?
  2483. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID] addFileName:metadata.fileName];
  2484. if (!lockServerUrl) return;
  2485. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2486. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2487. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2488. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2489. return;
  2490. }
  2491. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2492. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2493. [self performSelector:@selector(deleteFile) withObject:nil];
  2494. }]];
  2495. if (localFile) {
  2496. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2497. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2498. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  2499. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2500. }]];
  2501. }
  2502. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2503. }]];
  2504. alertController.popoverPresentationController.sourceView = self.tableView;
  2505. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2506. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2507. [alertController.view layoutIfNeeded];
  2508. [self presentViewController:alertController animated:YES completion:nil];
  2509. }
  2510. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2511. {
  2512. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2513. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2514. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2515. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2516. if (!serverUrl) return;
  2517. NSString *titoloLock, *titleFavorite;
  2518. if (self.metadata.favorite) {
  2519. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2520. } else {
  2521. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2522. }
  2523. if (self.metadata.directory) {
  2524. // calcolo lockServerUrl
  2525. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2526. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2527. if (directory.lock)
  2528. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2529. else
  2530. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2531. }
  2532. // ******************************************* AHKActionSheet *******************************************
  2533. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2534. actionSheet.animationDuration = 0.2;
  2535. actionSheet.buttonHeight = 50.0;
  2536. actionSheet.cancelButtonHeight = 50.0f;
  2537. actionSheet.separatorHeight = 5.0f;
  2538. actionSheet.automaticallyTintButtonImages = @(NO);
  2539. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2540. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2541. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2542. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2543. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2544. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2545. // ******************************************* DIRECTORY *******************************************
  2546. if (self.metadata.directory) {
  2547. BOOL lockDirectory = NO;
  2548. BOOL optionOffline = NO;
  2549. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2550. NSString *firstServerUrl = [CCUtility firtsPathComponentFromServerUrl:dirServerUrl activeUrl:appDelegate.activeUrl];
  2551. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2552. // Directory bloccata ?
  2553. tableDirectory *directoryForLock = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2554. if (directoryForLock.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2555. // Directory set as offline ?
  2556. tableDirectory *directoryOffline = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl CONTAINS %@ AND offline == true", appDelegate.activeAccount, firstServerUrl]];
  2557. if (directoryOffline == nil) {
  2558. optionOffline = YES;
  2559. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2560. optionOffline = YES;
  2561. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2562. optionOffline = YES;
  2563. }
  2564. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2565. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2566. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2567. height:50.0
  2568. type:AHKActionSheetButtonTypeDisabled
  2569. handler:nil
  2570. ];
  2571. [actionSheet addButtonWithTitle: titleFavorite
  2572. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2573. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2574. height: 50.0
  2575. type: AHKActionSheetButtonTypeDefault
  2576. handler: ^(AHKActionSheet *as) {
  2577. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2578. else [self settingFavorite:self.metadata favorite:YES];
  2579. }];
  2580. if (!lockDirectory && !isFolderEncrypted) {
  2581. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2582. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2583. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2584. height:50.0
  2585. type:AHKActionSheetButtonTypeDefault
  2586. handler:^(AHKActionSheet *as) {
  2587. [self openWindowShare:self.metadata];
  2588. }];
  2589. }
  2590. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2591. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2592. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2593. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2594. height:50.0
  2595. type:AHKActionSheetButtonTypeDefault
  2596. handler:^(AHKActionSheet *as) {
  2597. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2598. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2599. textField.text = self.metadata.fileNameView;
  2600. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2601. //textField.delegate = self;
  2602. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2603. }];
  2604. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2605. NSLog(@"[LOG] Cancel action");
  2606. }];
  2607. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2608. UITextField *fileName = alertController.textFields.firstObject;
  2609. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2610. }];
  2611. okAction.enabled = NO;
  2612. [alertController addAction:cancelAction];
  2613. [alertController addAction:okAction];
  2614. [self presentViewController:alertController animated:YES completion:nil];
  2615. }];
  2616. }
  2617. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2618. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2619. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2620. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2621. height:50.0
  2622. type:AHKActionSheetButtonTypeDefault
  2623. handler:^(AHKActionSheet *as) {
  2624. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2625. }];
  2626. }
  2627. if (!isFolderEncrypted && optionOffline) {
  2628. NSString *title;
  2629. if (directoryOffline == nil) {
  2630. title = NSLocalizedString(@"_set_available_offline_", nil);
  2631. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2632. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2633. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2634. title = NSLocalizedString(@"_set_available_offline_", nil);
  2635. }
  2636. [actionSheet addButtonWithTitle:title
  2637. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2638. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2639. height:50.0
  2640. type:AHKActionSheetButtonTypeDefault
  2641. handler:^(AHKActionSheet *as) {
  2642. if (directoryOffline == nil) {
  2643. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true];
  2644. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload];
  2645. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2646. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false];
  2647. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2648. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2649. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:directoryOffline.serverUrl offline:false];
  2650. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true];
  2651. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload];
  2652. }
  2653. }];
  2654. }
  2655. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2656. [actionSheet addButtonWithTitle:titoloLock
  2657. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2658. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2659. height:50.0
  2660. type:AHKActionSheetButtonTypeDefault
  2661. handler:^(AHKActionSheet *as) {
  2662. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2663. }];
  2664. }
  2665. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2666. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2667. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2668. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2669. height:50.0
  2670. type:AHKActionSheetButtonTypeDefault
  2671. handler:^(AHKActionSheet *as) {
  2672. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2673. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] fileID:self.metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2674. dispatch_async(dispatch_get_main_queue(), ^{
  2675. if (error) {
  2676. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2677. } else {
  2678. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2679. [self readFolder:self.serverUrl];
  2680. }
  2681. });
  2682. });
  2683. }];
  2684. }
  2685. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2686. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2687. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2688. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2689. height:50.0
  2690. type:AHKActionSheetButtonTypeDefault
  2691. handler:^(AHKActionSheet *as) {
  2692. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2693. NSError *error = [[NCNetworkingEndToEnd sharedManager] deletemarkEndToEndFolderEncryptedOnServerUrl:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] fileID:self.metadata.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  2694. dispatch_async(dispatch_get_main_queue(), ^{
  2695. if (error) {
  2696. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2697. } else {
  2698. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2699. [self readFolder:self.serverUrl];
  2700. }
  2701. });
  2702. });
  2703. }];
  2704. }
  2705. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2706. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2707. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2708. height:50.0
  2709. type:AHKActionSheetButtonTypeDestructive
  2710. handler:^(AHKActionSheet *as) {
  2711. [self actionDelete:indexPath];
  2712. }];
  2713. [actionSheet show];
  2714. }
  2715. // ******************************************* FILE *******************************************
  2716. if (!self.metadata.directory) {
  2717. UIImage *iconHeader;
  2718. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2719. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]])
  2720. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]];
  2721. else
  2722. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2723. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2724. image: iconHeader
  2725. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2726. height: 50.0
  2727. type: AHKActionSheetButtonTypeDisabled
  2728. handler: nil
  2729. ];
  2730. [actionSheet addButtonWithTitle: titleFavorite
  2731. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2732. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2733. height: 50.0
  2734. type: AHKActionSheetButtonTypeDefault
  2735. handler: ^(AHKActionSheet *as) {
  2736. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2737. else [self settingFavorite:self.metadata favorite:YES];
  2738. }];
  2739. if (!_metadataFolder.e2eEncrypted) {
  2740. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2741. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2742. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2743. height: 50.0
  2744. type:AHKActionSheetButtonTypeDefault
  2745. handler:^(AHKActionSheet *as) {
  2746. [self openWindowShare:self.metadata];
  2747. }];
  2748. }
  2749. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2750. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2751. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2752. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2753. height: 50.0
  2754. type:AHKActionSheetButtonTypeDefault
  2755. handler:^(AHKActionSheet *as) {
  2756. [self performSelector:@selector(DownloadOpenIn:) withObject:self.metadata];
  2757. }];
  2758. }
  2759. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2760. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2761. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2762. height: 50.0
  2763. type:AHKActionSheetButtonTypeDefault
  2764. handler:^(AHKActionSheet *as) {
  2765. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2766. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2767. textField.text = self.metadata.fileNameView;
  2768. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2769. }];
  2770. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2771. NSLog(@"[LOG] Cancel action");
  2772. }];
  2773. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2774. UITextField *fileName = alertController.textFields.firstObject;
  2775. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2776. }];
  2777. okAction.enabled = NO;
  2778. [alertController addAction:cancelAction];
  2779. [alertController addAction:okAction];
  2780. [self presentViewController:alertController animated:YES completion:nil];
  2781. }];
  2782. if (!_metadataFolder.e2eEncrypted) {
  2783. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2784. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2785. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2786. height:50.0
  2787. type:AHKActionSheetButtonTypeDefault
  2788. handler:^(AHKActionSheet *as) {
  2789. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2790. }];
  2791. }
  2792. if (!_metadataFolder.e2eEncrypted) {
  2793. NSString *title;
  2794. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadata.fileID]];
  2795. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2796. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2797. [actionSheet addButtonWithTitle:title
  2798. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2799. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2800. height:50.0
  2801. type:AHKActionSheetButtonTypeDefault
  2802. handler:^(AHKActionSheet *as) {
  2803. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2804. self.metadata.session = k_download_session;
  2805. self.metadata.sessionError = @"";
  2806. self.metadata.sessionSelector = selectorLoadOffline;
  2807. self.metadata.status = k_metadataStatusWaitDownload;
  2808. // Add Metadata for Download
  2809. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2810. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2811. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2812. } else if (localFile.offline == false) {
  2813. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:true];
  2814. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2815. } else {
  2816. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:false];
  2817. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2818. }
  2819. }];
  2820. }
  2821. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2822. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2823. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2824. height:50.0
  2825. type:AHKActionSheetButtonTypeDestructive
  2826. handler:^(AHKActionSheet *as) {
  2827. [self actionDelete:indexPath];
  2828. }];
  2829. [actionSheet show];
  2830. }
  2831. }
  2832. #pragma --------------------------------------------------------------------------------------------
  2833. #pragma mark - ==== Datasource ====
  2834. #pragma --------------------------------------------------------------------------------------------
  2835. - (void)clearDateReadDataSource:(NSNotification *)notification
  2836. {
  2837. _dateReadDataSource = Nil;
  2838. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2839. }
  2840. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID action:(NSInteger)action
  2841. {
  2842. // test
  2843. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2844. return;
  2845. // Search Mode
  2846. if (_isSearchMode) {
  2847. // Create metadatas
  2848. NSMutableArray *metadatas = [NSMutableArray new];
  2849. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2850. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", resultMetadata.fileID]];
  2851. if (metadata) {
  2852. [metadatas addObject:metadata];
  2853. }
  2854. }
  2855. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2856. [self tableViewReloadData];
  2857. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2858. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2859. _noFilesSearchDescription = @"";
  2860. }
  2861. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2862. _noFilesSearchTitle = @"";
  2863. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2864. }
  2865. [self.tableView reloadEmptyDataSet];
  2866. return;
  2867. }
  2868. // Se non siamo nella dir appropriata esci
  2869. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2870. return;
  2871. }
  2872. // Remove optimization for encrypted directory
  2873. if (_metadataFolder.e2eEncrypted)
  2874. _dateReadDataSource = nil;
  2875. // Controllo data lettura Data Source
  2876. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2877. // Get MetadataFolder
  2878. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2879. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND directoryID == %@", appDelegate.activeAccount, k_directoryID_root]];
  2880. else
  2881. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  2882. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2883. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2884. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2885. _dateReadDataSource = [NSDate date];
  2886. // Data Source
  2887. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2888. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2889. dispatch_async(dispatch_get_main_queue(), ^{
  2890. sectionDataSource = sectionDataSourceTemp;
  2891. [self tableViewReloadData];
  2892. });
  2893. });
  2894. } else {
  2895. [self tableViewReloadData];
  2896. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2897. }
  2898. }
  2899. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2900. {
  2901. // test
  2902. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2903. return nil;
  2904. }
  2905. // current directoryID
  2906. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  2907. if (directoryID == nil) {
  2908. return nil;
  2909. }
  2910. // get auto upload folder
  2911. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2912. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2913. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2914. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND status != %i", directoryID, k_metadataStatusHide] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  2915. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2916. if (withReloadData) {
  2917. sectionDataSource = sectionDataSourceTemp;
  2918. [self tableViewReloadData];
  2919. }
  2920. return sectionDataSourceTemp;
  2921. }
  2922. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2923. {
  2924. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2925. if (selectedRows.count > 0) {
  2926. for (NSIndexPath *selectionIndex in selectedRows) {
  2927. NSString *fileID = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2928. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  2929. [metadatas addObject:metadata];
  2930. }
  2931. }
  2932. return metadatas;
  2933. }
  2934. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2935. {
  2936. NSInteger totSections =[sectionDataSource.sections count] ;
  2937. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2938. return nil;
  2939. }
  2940. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2941. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2942. }
  2943. #pragma --------------------------------------------------------------------------------------------
  2944. #pragma mark - ==== Table ====
  2945. #pragma --------------------------------------------------------------------------------------------
  2946. - (void)tableViewSelect:(BOOL)edit
  2947. {
  2948. // chiudiamo eventuali swipe aperti
  2949. if (edit)
  2950. [self.tableView setEditing:NO animated:NO];
  2951. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2952. [self.tableView setEditing:edit animated:YES];
  2953. _isSelectedMode = edit;
  2954. if (edit)
  2955. [self setUINavigationBarSelected];
  2956. else
  2957. [self setUINavigationBarDefault];
  2958. [_selectedFileIDsMetadatas removeAllObjects];
  2959. [self setTitle];
  2960. }
  2961. - (void)tableViewReloadData
  2962. {
  2963. // store selected cells before relod
  2964. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2965. // reload table view
  2966. [self.tableView reloadData];
  2967. // selected cells stored
  2968. for (NSIndexPath *path in indexPaths)
  2969. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2970. [self setTableViewFooter];
  2971. if (self.tableView.editing)
  2972. [self setTitle];
  2973. //
  2974. [self.tableView reloadEmptyDataSet];
  2975. }
  2976. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2977. {
  2978. if (tableView.editing == 1) {
  2979. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2980. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2981. return NO;
  2982. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2983. return NO;
  2984. else
  2985. return YES;
  2986. } else {
  2987. [_selectedFileIDsMetadatas removeAllObjects];
  2988. }
  2989. return YES;
  2990. }
  2991. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2992. {
  2993. return 60;
  2994. }
  2995. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2996. {
  2997. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2998. }
  2999. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3000. {
  3001. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  3002. }
  3003. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3004. {
  3005. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  3006. NSString *sectionTitle = [sections objectAtIndex:section];
  3007. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3008. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3009. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3010. return 20.f;
  3011. }
  3012. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3013. {
  3014. float shift;
  3015. UIVisualEffectView *visualEffectView;
  3016. NSString *titleSection;
  3017. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3018. return nil;
  3019. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3020. titleSection = [sectionDataSource.sections objectAtIndex:section];
  3021. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3022. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  3023. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3024. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3025. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3026. else titleSection = NSLocalizedString(titleSection,nil);
  3027. // Format title
  3028. NSString *currentDevice = [CCUtility currentDevice];
  3029. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3030. visualEffectView = [[UIVisualEffectView alloc] init];
  3031. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3032. } else {
  3033. UIVisualEffect *blurEffect;
  3034. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3035. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3036. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3037. }
  3038. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  3039. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3040. shift = - 35;
  3041. else
  3042. shift = - 20;
  3043. } else shift = - 10;
  3044. // Title
  3045. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3046. titleLabel.backgroundColor = [UIColor clearColor];
  3047. titleLabel.textColor = [UIColor blackColor];
  3048. titleLabel.font = [UIFont systemFontOfSize:12];
  3049. titleLabel.textAlignment = NSTextAlignmentLeft;
  3050. titleLabel.text = titleSection;
  3051. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3052. [visualEffectView.contentView addSubview:titleLabel];
  3053. // Elements
  3054. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3055. elementLabel.backgroundColor = [UIColor clearColor];
  3056. elementLabel.textColor = [UIColor blackColor];;
  3057. elementLabel.font = [UIFont systemFontOfSize:12];
  3058. elementLabel.textAlignment = NSTextAlignmentRight;
  3059. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3060. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3061. NSUInteger rowsCount = [metadatas count];
  3062. if (rowsCount == 0) return nil;
  3063. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3064. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3065. [visualEffectView.contentView addSubview:elementLabel];
  3066. return visualEffectView;
  3067. }
  3068. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3069. {
  3070. return [sectionDataSource.sections indexOfObject:title];
  3071. }
  3072. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3073. {
  3074. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  3075. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3076. else
  3077. return nil;
  3078. }
  3079. /*
  3080. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3081. {
  3082. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3083. }
  3084. }
  3085. */
  3086. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3087. {
  3088. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3089. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3090. return [CCCellMain new];
  3091. }
  3092. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3093. if (serverUrl == nil) {
  3094. return [CCCellMain new];
  3095. }
  3096. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  3097. // NORMAL - > MAIN
  3098. if ([cell isKindOfClass:[CCCellMain class]]) {
  3099. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3100. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3101. BOOL isShare = false;
  3102. BOOL isMounted = false;
  3103. if (_metadataFolder) {
  3104. isShare = [metadata.permissions containsString:k_permission_shared] && ![_metadataFolder.permissions containsString:k_permission_shared];
  3105. isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_metadataFolder.permissions containsString:k_permission_mounted];
  3106. }
  3107. // Share add Tap
  3108. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  3109. if (isShare || isMounted) {
  3110. // Shared with you
  3111. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3112. [tap setNumberOfTapsRequired:1];
  3113. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3114. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3115. } else if (shareLink != nil || shareUserAndGroup != nil) {
  3116. // You share
  3117. if (metadata.directory) {
  3118. ((CCCellMain *)cell).shared.userInteractionEnabled = NO;
  3119. } else {
  3120. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3121. [tap setNumberOfTapsRequired:1];
  3122. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3123. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3124. }
  3125. }
  3126. }
  3127. // More
  3128. if ([self canOpenMenuAction:metadata]) {
  3129. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3130. [tapMore setNumberOfTapsRequired:1];
  3131. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  3132. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  3133. }
  3134. // MGSwipeButton
  3135. ((CCCellMain *)cell).delegate = self;
  3136. // LEFT
  3137. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:1 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3138. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  3139. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  3140. //centerIconOverText
  3141. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  3142. [favoriteButton centerIconOverText];
  3143. // RIGHT
  3144. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3145. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  3146. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  3147. //centerIconOverText
  3148. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  3149. [deleteButton centerIconOverText];
  3150. }
  3151. // TRANSFER
  3152. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  3153. // gesture Transfer
  3154. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3155. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3156. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3157. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3158. }
  3159. return cell;
  3160. }
  3161. - (void)setTableViewFooter
  3162. {
  3163. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3164. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3165. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3166. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3167. UIFont *appFont = [UIFont systemFontOfSize:12];
  3168. footerLabel.font = appFont;
  3169. footerLabel.textColor = [UIColor grayColor];
  3170. footerLabel.backgroundColor = [UIColor clearColor];
  3171. footerLabel.textAlignment = NSTextAlignmentCenter;
  3172. NSString *folders;
  3173. NSString *files;
  3174. NSString *footerText;
  3175. if (sectionDataSource.directories > 1) {
  3176. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3177. } else if (sectionDataSource.directories == 1){
  3178. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3179. } else {
  3180. folders = @"";
  3181. }
  3182. if (sectionDataSource.files > 1) {
  3183. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3184. } else if (sectionDataSource.files == 1){
  3185. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3186. } else {
  3187. files = @"";
  3188. }
  3189. if ([folders isEqualToString:@""]) {
  3190. footerText = files;
  3191. } else if ([files isEqualToString:@""]) {
  3192. footerText = folders;
  3193. } else {
  3194. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3195. }
  3196. footerLabel.text = footerText;
  3197. [footerView addSubview:footerLabel];
  3198. [self.tableView setTableFooterView:footerView];
  3199. }
  3200. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3201. {
  3202. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3203. // settiamo il record file.
  3204. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3205. if (!self.metadata)
  3206. return;
  3207. // se non può essere selezionata deseleziona
  3208. if ([cell isEditing] == NO)
  3209. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3210. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3211. if (self.tableView.editing) {
  3212. [_selectedFileIDsMetadatas setObject:self.metadata forKey:self.metadata.fileID];
  3213. [self setTitle];
  3214. return;
  3215. }
  3216. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3217. if (!serverUrl) return;
  3218. // se è in corso una sessione
  3219. if (self.metadata.status != k_metadataStatusNormal)
  3220. return;
  3221. // file
  3222. if (self.metadata.directory == NO) {
  3223. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3224. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  3225. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName fileID:self.metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3226. } else {
  3227. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3228. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3229. } else {
  3230. if (([self.metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_audio] || [self.metadata.typeFile isEqualToString: k_metadataTypeFile_image]) && _metadataFolder.e2eEncrypted == NO) {
  3231. [self shouldPerformSegue:self.metadata];
  3232. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCViewerRichdocument sharedInstance] isRichDocument:self.metadata]) {
  3233. [self shouldPerformSegue:self.metadata];
  3234. } else {
  3235. self.metadata.session = k_download_session;
  3236. self.metadata.sessionError = @"";
  3237. self.metadata.sessionSelector = selectorLoadFileView;
  3238. self.metadata.status = k_metadataStatusWaitDownload;
  3239. // Add Metadata for Download
  3240. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3241. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3242. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  3243. }
  3244. }
  3245. }
  3246. }
  3247. if (self.metadata.directory) {
  3248. imageTitleSegue = cell.imageTitleSegue;
  3249. [self performSegueDirectoryWithControlPasscode:true];
  3250. }
  3251. }
  3252. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3253. {
  3254. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3255. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3256. [self setTitle];
  3257. }
  3258. - (void)didSelectAll
  3259. {
  3260. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3261. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3262. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3263. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3264. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3265. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3266. }
  3267. }
  3268. [self setTitle];
  3269. }
  3270. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3271. {
  3272. if (!indexPath)
  3273. return NO;
  3274. NSInteger section = indexPath.section;
  3275. NSInteger row = indexPath.row;
  3276. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3277. if (section > lastSectionIndex || lastSectionIndex < 0)
  3278. return NO;
  3279. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3280. if (rowCount < 0)
  3281. return NO;
  3282. return row <= rowCount;
  3283. }
  3284. #pragma --------------------------------------------------------------------------------------------
  3285. #pragma mark ===== Navigation ====
  3286. #pragma --------------------------------------------------------------------------------------------
  3287. - (void)shouldPerformSegue:(tableMetadata *)metadata
  3288. {
  3289. // if background return
  3290. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3291. if (self.view.window == NO)
  3292. return;
  3293. // Collapsed ma siamo già in detail esci
  3294. if (self.splitViewController.isCollapsed)
  3295. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3296. // Metadata for push detail
  3297. self.metadataForPushDetail = metadata;
  3298. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3299. }
  3300. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3301. {
  3302. id viewController = segue.destinationViewController;
  3303. tableMetadata *metadata;
  3304. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3305. UINavigationController *nav = viewController;
  3306. _detailViewController = (CCDetail *)nav.topViewController;
  3307. } else {
  3308. _detailViewController = segue.destinationViewController;
  3309. }
  3310. NSMutableArray *photoDataSource = [NSMutableArray new];
  3311. if ([sender isKindOfClass:[tableMetadata class]]) {
  3312. metadata = sender;
  3313. [photoDataSource addObject:sender];
  3314. } else {
  3315. metadata = self.metadataForPushDetail;
  3316. for (NSString *fileID in sectionDataSource.allFileID) {
  3317. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3318. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3319. [photoDataSource addObject:metadata];
  3320. }
  3321. }
  3322. _detailViewController.metadataDetail = metadata;
  3323. _detailViewController.photoDataSource = photoDataSource;
  3324. _detailViewController.dateFilterQuery = nil;
  3325. [_detailViewController setTitle:metadata.fileNameView];
  3326. }
  3327. // can i go to next viewcontroller
  3328. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3329. {
  3330. NSString *nomeDir;
  3331. if (self.tableView.editing == NO) {
  3332. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3333. if (!serverUrl) return;
  3334. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  3335. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3336. // SE siamo in presenza di una directory bloccata E è attivo il block E la sessione password Lock è senza data ALLORA chiediamo la password per procedere
  3337. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3338. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3339. viewController.delegate = self;
  3340. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3341. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3342. viewController.inputViewTitlePassword = YES;
  3343. if ([CCUtility getSimplyBlockCode]) {
  3344. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3345. viewController.passcodeInputView.maximumLength = 6;
  3346. } else {
  3347. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3348. viewController.passcodeInputView.maximumLength = 64;
  3349. }
  3350. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3351. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3352. viewController.touchIDManager = touchIDManager;
  3353. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3354. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3355. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3356. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3357. [self presentViewController:navController animated:YES completion:nil];
  3358. return;
  3359. }
  3360. // E2EE Check enable
  3361. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3362. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3363. return;
  3364. }
  3365. nomeDir = self.metadata.fileName;
  3366. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3367. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3368. if (!viewController) {
  3369. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3370. viewController.serverUrl = serverUrlPush;
  3371. viewController.titleMain = self.metadata.fileName;
  3372. viewController.imageTitle = imageTitleSegue;
  3373. // save self
  3374. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3375. [self.navigationController pushViewController:viewController animated:YES];
  3376. } else {
  3377. if (viewController.isViewLoaded) {
  3378. viewController.titleMain = self.metadata.fileName;
  3379. viewController.imageTitle = imageTitleSegue;
  3380. // Fix : Application tried to present modally an active controller
  3381. if ([self.navigationController isBeingPresented]) {
  3382. // being presented
  3383. } else if ([self.navigationController isMovingToParentViewController]) {
  3384. // being pushed
  3385. } else {
  3386. [self.navigationController pushViewController:viewController animated:YES];
  3387. }
  3388. }
  3389. }
  3390. }
  3391. }
  3392. @end