CCMain.m 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569
  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. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  793. if (!directoryID) return;
  794. for (PHAsset *asset in assets) {
  795. tableMetadata *metadata;
  796. NSString *fileName = [CCUtility createFileName:[asset valueForKey:@"filename"] fileDate:asset.creationDate fileType:asset.mediaType keyFileName:k_keyFileNameMask keyFileNameType:k_keyFileNameType keyFileNameOriginal:k_keyFileNameOriginal];
  797. NSDate *assetDate = asset.creationDate;
  798. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  799. // Create serverUrl if use sub folder
  800. if (useSubFolder) {
  801. [formatter setDateFormat:@"yyyy"];
  802. NSString *yearString = [formatter stringFromDate:assetDate];
  803. [formatter setDateFormat:@"MM"];
  804. NSString *monthString = [formatter stringFromDate:assetDate];
  805. serverUrl = [NSString stringWithFormat:@"%@/%@/%@", autoUploadPath, yearString, monthString];
  806. }
  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. // reinsert metadatas in Download
  937. if (metadatasInDownload) {
  938. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload serverUrl:metadataNet.serverUrl];
  939. }
  940. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  941. // File is changed ??
  942. if (!_isSearchMode && metadatasToInsertInDB)
  943. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  944. });
  945. // Search Mode
  946. if (_isSearchMode) {
  947. // Fix managed -> Unmanaged _searchResultMetadatas
  948. if (metadatasToInsertInDB)
  949. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  950. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  951. }
  952. // this is the same directory
  953. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  954. // reload
  955. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  956. // Enable change user
  957. [_imageTitleHome setUserInteractionEnabled:YES];
  958. _loadingFolder = NO;
  959. [self tableViewReloadData];
  960. }
  961. // E2EE Is encrypted folder get metadata
  962. if (_metadataFolder.e2eEncrypted) {
  963. // Read Metadata
  964. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  965. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  966. NSString *metadata;
  967. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:metadataFolder.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  968. dispatch_async(dispatch_get_main_queue(), ^{
  969. if (error) {
  970. if (error.code != 404)
  971. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  972. } else {
  973. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  974. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  975. else
  976. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  977. }
  978. });
  979. });
  980. } else {
  981. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  982. }
  983. }
  984. // rewrite title
  985. [self setTitle];
  986. }
  987. - (void)readFolder:(NSString *)serverUrl
  988. {
  989. // init control
  990. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  991. [refreshControl endRefreshing];
  992. return;
  993. }
  994. // Search Mode
  995. if (_isSearchMode) {
  996. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  997. _searchFileName = @""; // forced reload searchg
  998. [self updateSearchResultsForSearchController:self.searchController];
  999. return;
  1000. }
  1001. _loadingFolder = YES;
  1002. [self tableViewReloadData];
  1003. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1004. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1005. metadataNet.action = actionReadFolder;
  1006. metadataNet.date = [NSDate date];
  1007. metadataNet.depth = @"1";
  1008. metadataNet.directoryID = directory.directoryID;
  1009. metadataNet.priority = NSOperationQueuePriorityHigh;
  1010. metadataNet.selector = selectorReadFolder;
  1011. metadataNet.serverUrl = serverUrl;
  1012. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1013. }
  1014. #pragma mark -
  1015. #pragma --------------------------------------------------------------------------------------------
  1016. #pragma mark ===== Search =====
  1017. #pragma --------------------------------------------------------------------------------------------
  1018. - (void)searchEnabled:(BOOL)enabled
  1019. {
  1020. if (enabled) {
  1021. if (self.tableView.tableHeaderView != nil)
  1022. return;
  1023. self.definesPresentationContext = YES;
  1024. self.searchController.searchResultsUpdater = self;
  1025. self.searchController.dimsBackgroundDuringPresentation = NO;
  1026. self.searchController.searchBar.translucent = NO;
  1027. [self.searchController.searchBar sizeToFit];
  1028. self.searchController.searchBar.delegate = self;
  1029. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1030. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1031. self.searchController.searchBar.backgroundImage = [UIImage new];
  1032. // color searchbbar button text (cancel)
  1033. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1034. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1035. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1036. }
  1037. self.tableView.tableHeaderView = self.searchController.searchBar;
  1038. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1039. } else {
  1040. self.tableView.tableHeaderView = nil;
  1041. }
  1042. }
  1043. - (void)searchStartTimer
  1044. {
  1045. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1046. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1047. metadataNet.action = actionSearch;
  1048. metadataNet.contentType = nil;
  1049. metadataNet.date = nil;
  1050. metadataNet.directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:startDirectory];
  1051. metadataNet.fileName = _searchFileName;
  1052. metadataNet.etag = @"";
  1053. metadataNet.depth = @"infinity";
  1054. metadataNet.priority = NSOperationQueuePriorityHigh;
  1055. metadataNet.selector = selectorSearchFiles;
  1056. metadataNet.serverUrl = startDirectory;
  1057. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1058. _noFilesSearchTitle = @"";
  1059. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1060. [self.tableView reloadEmptyDataSet];
  1061. }
  1062. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1063. {
  1064. // Color text "Cancel"
  1065. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1066. _isSearchMode = YES;
  1067. [self deleteRefreshControl];
  1068. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1069. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1070. _searchFileName = fileName;
  1071. // First : filter
  1072. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1073. if (!directoryID) return;
  1074. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView CONTAINS[cd] %@", directoryID, fileName];
  1075. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1076. [_searchResultMetadatas removeAllObjects];
  1077. for (tableMetadata *record in records)
  1078. [_searchResultMetadatas addObject:record];
  1079. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1080. metadataNet.account = appDelegate.activeAccount;
  1081. metadataNet.directoryID = directoryID;
  1082. metadataNet.selector = selectorSearchFiles;
  1083. metadataNet.serverUrl = _serverUrl;
  1084. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1085. // Version >= 12
  1086. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1087. [_timerWaitInput invalidate];
  1088. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1089. }
  1090. }
  1091. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1092. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1093. }
  1094. }
  1095. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1096. {
  1097. [self cancelSearchBar];
  1098. [self readFolder:_serverUrl];
  1099. }
  1100. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1101. {
  1102. // Check Active Account
  1103. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1104. return;
  1105. if (errorCode == 0) {
  1106. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1107. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1108. } else {
  1109. // Unauthorized
  1110. if (errorCode == kOCErrorServerUnauthorized)
  1111. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1112. else
  1113. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1114. _searchFileName = @"";
  1115. }
  1116. }
  1117. - (void)cancelSearchBar
  1118. {
  1119. if (self.searchController.active) {
  1120. [self.searchController setActive:NO];
  1121. [self createRefreshControl];
  1122. _isSearchMode = NO;
  1123. _searchFileName = @"";
  1124. _dateReadDataSource = nil;
  1125. _searchResultMetadatas = [NSMutableArray new];
  1126. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1127. }
  1128. //[self setNeedsStatusBarAppearanceUpdate];
  1129. }
  1130. #pragma mark -
  1131. #pragma --------------------------------------------------------------------------------------------
  1132. #pragma mark ===== Delete File or Folder =====
  1133. #pragma --------------------------------------------------------------------------------------------
  1134. - (void)deleteFile
  1135. {
  1136. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1137. return;
  1138. NSArray *metadatas;
  1139. if ([_selectedFileIDsMetadatas count] > 0) {
  1140. metadatas = [_selectedFileIDsMetadatas allValues];
  1141. } else {
  1142. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1143. }
  1144. // remove optimization
  1145. _dateReadDataSource = nil;
  1146. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderFileID:_metadataFolder.fileID completion:^(NSInteger errorCode, NSString *message) {
  1147. // Reload
  1148. if (_isSearchMode)
  1149. [self readFolder:self.serverUrl];
  1150. else
  1151. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1152. }];
  1153. // End Select Table View
  1154. [self tableViewSelect:NO];
  1155. }
  1156. #pragma --------------------------------------------------------------------------------------------
  1157. #pragma mark ===== Rename / Move =====
  1158. #pragma --------------------------------------------------------------------------------------------
  1159. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1160. {
  1161. // Rename metadata
  1162. (void) [[NCManageDatabase sharedInstance] renameMetadataWithFileNameTo:metadataNet.fileNameTo fileID:metadataNet.fileID];
  1163. if (metadataNet.directory) {
  1164. NSString *serverUrl = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadataNet.fileName];
  1165. NSString *serverUrlTo = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadataNet.fileNameTo];
  1166. tableDirectory *directoryTable = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1167. if (directoryTable == nil) {
  1168. [self renameMoveFileOrFolderFailure:metadataNet message:@"Internal error, ServerUrl not found" errorCode:0];
  1169. return;
  1170. }
  1171. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:serverUrl serverUrlTo:serverUrlTo etag:nil fileID:nil encrypted:directoryTable.e2eEncrypted];
  1172. } else {
  1173. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:metadataNet.fileID date:nil exifDate:nil exifLatitude:nil exifLongitude:nil fileName:metadataNet.fileNameTo etag:nil];
  1174. // Move file system
  1175. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadataNet.fileID], metadataNet.fileName];
  1176. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadataNet.fileID], metadataNet.fileNameTo];
  1177. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1178. NSString *atPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileName];
  1179. NSString *toPathIcon = [CCUtility getDirectoryProviderStorageIconFileID:metadataNet.fileID fileNameView:metadataNet.fileNameTo];
  1180. [[NSFileManager defaultManager] moveItemAtPath:atPathIcon toPath:toPathIcon error:nil];
  1181. }
  1182. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:metadataNet.fileID action:k_action_MOD];
  1183. }
  1184. - (void)renameFile:(NSArray *)arguments
  1185. {
  1186. tableMetadata* metadata = [arguments objectAtIndex:0];
  1187. NSString *fileName = [arguments objectAtIndex:1];
  1188. // E2EE
  1189. if (_metadataFolder.e2eEncrypted) {
  1190. // verify if exists the new fileName
  1191. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1192. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1193. return;
  1194. }
  1195. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1196. 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];
  1197. if (error) {
  1198. dispatch_async(dispatch_get_main_queue(), ^{
  1199. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1200. });
  1201. } else {
  1202. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1203. // Move file system
  1204. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1205. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1206. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1207. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1208. }
  1209. // Unlock
  1210. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1211. if (tableLock != nil) {
  1212. 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];
  1213. if (error) {
  1214. dispatch_async(dispatch_get_main_queue(), ^{
  1215. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1216. });
  1217. }
  1218. }
  1219. dispatch_async(dispatch_get_main_queue(), ^{
  1220. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1221. });
  1222. });
  1223. } else {
  1224. // Plain
  1225. NSString *fileNameNew = [CCUtility removeForbiddenCharactersServer:fileName];
  1226. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1227. if ([fileName length] == 0 || [fileName isEqualToString:metadata.fileNameView]) {
  1228. return;
  1229. }
  1230. // Verify if exists the fileName TO
  1231. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1232. [ocNetworking readFile:fileNameNew serverUrl:serverUrl account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1233. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1234. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1235. }];
  1236. [alert addAction:ok];
  1237. [self presentViewController:alert animated:YES completion:nil];
  1238. } failure:^(NSString *message, NSInteger errorCode) {
  1239. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1240. metadataNet.action = actionMoveFileOrFolder;
  1241. metadataNet.directory = metadata.directory;
  1242. metadataNet.fileID = metadata.fileID;
  1243. metadataNet.fileName = metadata.fileName;
  1244. metadataNet.fileNameTo = fileNameNew;
  1245. metadataNet.fileNameView = metadata.fileNameView;
  1246. metadataNet.selector = selectorRename;
  1247. metadataNet.serverUrl = serverUrl;
  1248. metadataNet.serverUrlTo = serverUrl;
  1249. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1250. }];
  1251. }
  1252. }
  1253. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1254. {
  1255. if ([message length] > 0) {
  1256. if ([metadataNet.selector isEqualToString:selectorRename]) {
  1257. [appDelegate messageNotification:@"_rename_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1258. }
  1259. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1260. [appDelegate messageNotification:@"_move_" description:message visible:true delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1261. }
  1262. }
  1263. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1264. [_hud hideHud];
  1265. if (message && errorCode != kOCErrorServerUnauthorized)
  1266. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1267. // End Select Table View
  1268. [self tableViewSelect:NO];
  1269. // reload Datasource
  1270. if (_isSearchMode)
  1271. [self readFolder:metadataNet.serverUrl];
  1272. else
  1273. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1274. }
  1275. }
  1276. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1277. {
  1278. [_queueSelector removeObject:metadataNet.selector];
  1279. if ([_queueSelector count] == 0) {
  1280. [_hud hideHud];
  1281. NSString *fileName = metadataNet.fileName;
  1282. NSString *directoryID = metadataNet.directoryID;
  1283. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1284. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1285. if (!serverUrlTo) return;
  1286. // FILE -> Metadata
  1287. if (metadataNet.directory == NO)
  1288. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1289. // DIRECTORY -> Directory - CCMetadata
  1290. if (metadataNet.directory == YES) {
  1291. // delete all dir / subdir
  1292. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1293. // move metadata
  1294. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1295. // Add new directory
  1296. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1297. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1298. }
  1299. // next
  1300. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1301. if ([_selectedFileIDsMetadatas count] > 0) {
  1302. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1303. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1304. } else {
  1305. // End Select Table View
  1306. [self tableViewSelect:NO];
  1307. // reload Datasource
  1308. if (_isSearchMode)
  1309. [self readFolder:metadataNet.serverUrl];
  1310. else
  1311. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1312. }
  1313. }
  1314. }
  1315. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1316. {
  1317. tableMetadata *metadata = [arguments objectAtIndex:0];
  1318. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1319. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1320. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1321. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1322. if (!serverUrl) return;
  1323. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1324. if (!directoryIDTo) return;
  1325. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1326. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1327. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1328. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1329. }];
  1330. [alert addAction:ok];
  1331. [self presentViewController:alert animated:YES completion:nil];
  1332. // End Select Table View
  1333. [self tableViewSelect:NO];
  1334. // reload Datasource
  1335. [self readFileReloadFolder];
  1336. } failure:^(NSString *message, NSInteger errorCode) {
  1337. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1338. metadataNet.action = actionMoveFileOrFolder;
  1339. metadataNet.directory = metadata.directory;
  1340. metadataNet.fileID = metadata.fileID;
  1341. metadataNet.directoryID = metadata.directoryID;
  1342. metadataNet.directoryIDTo = directoryIDTo;
  1343. metadataNet.fileName = metadata.fileName;
  1344. metadataNet.fileNameView = metadata.fileNameView;
  1345. metadataNet.fileNameTo = metadata.fileName;
  1346. metadataNet.etag = metadata.etag;
  1347. metadataNet.selector = selectorMove;
  1348. metadataNet.serverUrl = serverUrl;
  1349. metadataNet.serverUrlTo = serverUrlTo;
  1350. [_queueSelector addObject:metadataNet.selector];
  1351. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1352. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1353. }];
  1354. }
  1355. // DELEGATE : Select
  1356. - (void)dismissSelectWithServerUrl:(NSString *)serverUrl metadata:(tableMetadata *)metadata type:(NSString *)type
  1357. {
  1358. if (serverUrl == nil) {
  1359. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1360. } else {
  1361. [_queueSelector removeAllObjects];
  1362. // E2EE DENIED
  1363. if ([CCUtility isFolderEncrypted:serverUrl account:appDelegate.activeAccount]) {
  1364. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1365. return;
  1366. }
  1367. if ([_selectedFileIDsMetadatas count] > 0) {
  1368. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1369. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1370. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrl, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1371. } else {
  1372. _numSelectedFileIDsMetadatas = 1;
  1373. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[self.metadata, serverUrl, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1374. }
  1375. }
  1376. }
  1377. - (void)moveOpenWindow:(NSArray *)indexPaths
  1378. {
  1379. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1380. return;
  1381. UINavigationController *navigationController = [[UIStoryboard storyboardWithName:@"NCSelect" bundle:nil] instantiateInitialViewController];
  1382. NCSelect *viewController = (NCSelect *)navigationController.topViewController;
  1383. viewController.delegate = self;
  1384. viewController.hideButtonCreateFolder = false;
  1385. viewController.selectFile = false;
  1386. viewController.includeDirectoryE2EEncryption = false;
  1387. viewController.includeImages = false;
  1388. viewController.type = @"";
  1389. viewController.titleButtonDone = NSLocalizedString(@"_move_", nil);
  1390. viewController.layoutViewSelect = k_layout_view_move;
  1391. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1392. [self presentViewController:navigationController animated:YES completion:nil];
  1393. }
  1394. #pragma --------------------------------------------------------------------------------------------
  1395. #pragma mark ===== Create folder =====
  1396. #pragma --------------------------------------------------------------------------------------------
  1397. - (void)createFolder
  1398. {
  1399. NSString *serverUrl = [appDelegate getTabBarControllerActiveServerUrl];
  1400. NSString *message;
  1401. UIAlertController *alertController;
  1402. if ([serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]]) {
  1403. message = @"/";
  1404. } else {
  1405. message = [serverUrl lastPathComponent];
  1406. }
  1407. alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_create_folder_on_",nil) message:message preferredStyle:UIAlertControllerStyleAlert];
  1408. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  1409. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  1410. textField.autocapitalizationType = UITextAutocapitalizationTypeWords;
  1411. }];
  1412. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  1413. NSLog(@"[LOG] Cancel action");
  1414. }];
  1415. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  1416. UITextField *fileName = alertController.textFields.firstObject;
  1417. [self createFolder:fileName.text serverUrl:serverUrl];
  1418. }];
  1419. okAction.enabled = NO;
  1420. [alertController addAction:cancelAction];
  1421. [alertController addAction:okAction];
  1422. [self presentViewController:alertController animated:YES completion:nil];
  1423. }
  1424. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1425. {
  1426. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1427. if (![fileNameFolder length]) return;
  1428. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1429. if (!directoryID) return;
  1430. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1431. // Create Directory (temp) on metadata
  1432. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp directoryID:directoryID fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal url:@""];
  1433. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1434. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1435. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1436. // Creeate folder Networking
  1437. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1438. [ocNetworking createFolder:fileNameFolder serverUrl:serverUrl account:appDelegate.activeAccount success:^(NSString *fileID, NSDate *date) {
  1439. // Delete Temp Dir
  1440. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1441. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1442. if (_metadataFolder.e2eEncrypted) {
  1443. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1444. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1445. dispatch_async(dispatch_get_main_queue(), ^{
  1446. if (error) {
  1447. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1448. }
  1449. [self readFolder:self.serverUrl];
  1450. });
  1451. });
  1452. } else {
  1453. [self readFolder:self.serverUrl];
  1454. }
  1455. } failure:^(NSString *message, NSInteger errorCode) {
  1456. // Unauthorized
  1457. if (errorCode == kOCErrorServerUnauthorized)
  1458. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1459. else
  1460. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1461. // Delete Temp Dir
  1462. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1463. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1464. // We are in directory fail ?
  1465. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:fileNameFolder]];
  1466. if (vc)
  1467. [vc.navigationController popViewControllerAnimated:YES];
  1468. }];
  1469. }
  1470. #pragma --------------------------------------------------------------------------------------------
  1471. #pragma mark ===== Progress & Task Button =====
  1472. #pragma --------------------------------------------------------------------------------------------
  1473. - (void)triggerProgressTask:(NSNotification *)notification
  1474. {
  1475. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView viewController:self serverUrlViewController:self.serverUrl];
  1476. }
  1477. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1478. {
  1479. UITouch *touch = [[event allTouches] anyObject];
  1480. CGPoint location = [touch locationInView:self.tableView];
  1481. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1482. if ([self indexPathIsValid:indexPath]) {
  1483. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1484. if (metadataSection) {
  1485. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1486. if (metadata)
  1487. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true];
  1488. }
  1489. }
  1490. }
  1491. - (void)cancelAllTask:(id)sender
  1492. {
  1493. CGPoint location = [sender locationInView:self.tableView];
  1494. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1495. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1496. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1497. [[NCMainCommon sharedInstance] cancelAllTransferWithView:self.view];
  1498. }]];
  1499. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1500. alertController.popoverPresentationController.sourceView = self.tableView;
  1501. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1502. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1503. [alertController.view layoutIfNeeded];
  1504. [self presentViewController:alertController animated:YES completion:nil];
  1505. }
  1506. #pragma --------------------------------------------------------------------------------------------
  1507. #pragma mark ===== Shared =====
  1508. #pragma --------------------------------------------------------------------------------------------
  1509. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1510. {
  1511. [_hud hideHud];
  1512. // Check Active Account
  1513. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1514. return;
  1515. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1516. if (result) {
  1517. appDelegate.sharesLink = result[0];
  1518. appDelegate.sharesUserAndGroup = result[1];
  1519. }
  1520. // Notify Shares View
  1521. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1522. if (openWindow) {
  1523. if (_shareOC) {
  1524. [_shareOC reloadData];
  1525. } else {
  1526. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1527. // Apriamo la view
  1528. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1529. _shareOC.delegate = self;
  1530. _shareOC.metadata = metadata;
  1531. _shareOC.serverUrl = metadataNet.serverUrl;
  1532. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1533. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1534. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1535. [self presentViewController:_shareOC animated:YES completion:nil];
  1536. }
  1537. }
  1538. [self tableViewReloadData];
  1539. }
  1540. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1541. {
  1542. [_hud hideHud];
  1543. // Check Active Account
  1544. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1545. return;
  1546. // Unauthorized
  1547. if (errorCode == kOCErrorServerUnauthorized)
  1548. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1549. else
  1550. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1551. if (_shareOC)
  1552. [_shareOC reloadData];
  1553. [self tableViewReloadData];
  1554. }
  1555. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password permission:(NSInteger)permission
  1556. {
  1557. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1558. metadataNet.action = actionShare;
  1559. metadataNet.fileID = metadata.fileID;
  1560. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1561. metadataNet.fileNameView = metadata.fileNameView;
  1562. metadataNet.sharePermission = permission;
  1563. metadataNet.password = password;
  1564. metadataNet.selector = selectorShare;
  1565. metadataNet.serverUrl = serverUrl;
  1566. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1567. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1568. }
  1569. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1570. {
  1571. [_hud hideHud];
  1572. // Check Active Account
  1573. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1574. return;
  1575. // rimuoviamo la condivisione da db
  1576. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1577. if (result) {
  1578. appDelegate.sharesLink = result[0];
  1579. appDelegate.sharesUserAndGroup = result[1];
  1580. }
  1581. if (_shareOC)
  1582. [_shareOC reloadData];
  1583. [self tableViewReloadData];
  1584. }
  1585. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1586. {
  1587. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1588. metadataNet.action = actionUnShare;
  1589. metadataNet.fileID = metadata.fileID;
  1590. metadataNet.fileName = metadata.fileName;
  1591. metadataNet.fileNameView = metadata.fileNameView;
  1592. metadataNet.selector = selectorUnshare;
  1593. metadataNet.serverUrl = serverUrl;
  1594. metadataNet.share = share;
  1595. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1596. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1597. }
  1598. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1599. {
  1600. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1601. metadataNet.action = actionUpdateShare;
  1602. metadataNet.fileID = metadata.fileID;
  1603. metadataNet.expirationTime = expirationTime;
  1604. metadataNet.password = password;
  1605. metadataNet.selector = selectorUpdateShare;
  1606. metadataNet.serverUrl = serverUrl;
  1607. metadataNet.share = share;
  1608. metadataNet.sharePermission = permission;
  1609. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1610. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1611. }
  1612. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1613. {
  1614. [_hud hideHud];
  1615. // Check Active Account
  1616. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1617. return;
  1618. if (_shareOC)
  1619. [_shareOC reloadUserAndGroup:items];
  1620. }
  1621. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1622. {
  1623. [_hud hideHud];
  1624. // Check Active Account
  1625. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1626. return;
  1627. // Unauthorized
  1628. if (errorCode == kOCErrorServerUnauthorized)
  1629. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1630. else
  1631. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1632. }
  1633. - (void)getUserAndGroup:(NSString *)find
  1634. {
  1635. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1636. metadataNet.action = actionGetUserAndGroup;
  1637. metadataNet.optionAny = find;
  1638. metadataNet.selector = selectorGetUserAndGroup;
  1639. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1640. [_hud visibleIndeterminateHud];
  1641. }
  1642. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1643. {
  1644. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1645. metadataNet.action = actionShareWith;
  1646. metadataNet.fileID = metadata.fileID;
  1647. metadataNet.directoryID = directoryID;
  1648. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1649. metadataNet.fileNameView = metadata.fileNameView;
  1650. metadataNet.serverUrl = serverUrl;
  1651. metadataNet.selector = selectorShare;
  1652. metadataNet.share = user;
  1653. metadataNet.shareeType = shareeType;
  1654. metadataNet.sharePermission = permission;
  1655. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1656. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1657. }
  1658. - (void)openWindowShare:(tableMetadata *)metadata
  1659. {
  1660. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1661. if (!serverUrl) return;
  1662. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1663. metadataNet.action = actionReadShareServer;
  1664. metadataNet.fileID = metadata.fileID;
  1665. metadataNet.fileName = metadata.fileName;
  1666. metadataNet.fileNameView = metadata.fileNameView;
  1667. metadataNet.selector = selectorOpenWindowShare;
  1668. metadataNet.serverUrl = serverUrl;
  1669. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1670. [_hud visibleIndeterminateHud];
  1671. }
  1672. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1673. {
  1674. CGPoint location = [tapGesture locationInView:self.tableView];
  1675. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1676. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1677. if (metadata)
  1678. [self openWindowShare:metadata];
  1679. }
  1680. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1681. {
  1682. CGPoint location = [tapGesture locationInView:self.tableView];
  1683. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1684. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1685. if (metadata) {
  1686. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1687. vc.metadata = metadata;
  1688. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1689. [self presentViewController:vc animated:YES completion:nil];
  1690. }
  1691. }
  1692. #pragma --------------------------------------------------------------------------------------------
  1693. #pragma mark ===== Favorite =====
  1694. #pragma --------------------------------------------------------------------------------------------
  1695. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1696. {
  1697. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1698. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1699. [ocNetworking settingFavorite:fileNameServerUrl favorite:favorite completion:^(NSString *message, NSInteger errorCode) {
  1700. if (errorCode == 0) {
  1701. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1702. _dateReadDataSource = nil;
  1703. if (_isSearchMode)
  1704. [self readFolder:self.serverUrl];
  1705. else
  1706. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1707. if (metadata.directory && favorite) {
  1708. NSString *dir = [CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName];
  1709. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1710. }
  1711. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1712. metadata.favorite = favorite;
  1713. metadata.session = k_download_session;
  1714. metadata.sessionError = @"";
  1715. metadata.sessionSelector = selectorDownloadSynchronize;
  1716. metadata.status = k_metadataStatusWaitDownload;
  1717. // Add Metadata for Download
  1718. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1719. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1720. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1721. }
  1722. } else {
  1723. if (errorCode == kOCErrorServerUnauthorized)
  1724. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1725. }
  1726. }];
  1727. }
  1728. #pragma --------------------------------------------------------------------------------------------
  1729. #pragma mark ===== Open in... =====
  1730. #pragma --------------------------------------------------------------------------------------------
  1731. - (void)DownloadOpenIn:(tableMetadata *)metadata
  1732. {
  1733. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1734. if (!serverUrl) return;
  1735. metadata.session = k_download_session;
  1736. metadata.sessionError = @"";
  1737. metadata.sessionSelector = selectorOpenIn;
  1738. metadata.status = k_metadataStatusWaitDownload;
  1739. // Add Metadata for Download
  1740. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1741. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1742. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1743. }
  1744. - (void)openIn:(tableMetadata *)metadata
  1745. {
  1746. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  1747. docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1748. docController.delegate = self;
  1749. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1750. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1751. if (cell) {
  1752. [docController presentOptionsMenuFromRect:cell.frame inView:self.tableView animated:YES];
  1753. } else {
  1754. [docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1755. }
  1756. }
  1757. #pragma --------------------------------------------------------------------------------------------
  1758. #pragma mark ==== Menu LOGO ====
  1759. #pragma --------------------------------------------------------------------------------------------
  1760. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1761. {
  1762. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1763. return;
  1764. // Brand
  1765. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1766. return;
  1767. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1768. NSMutableArray *menuArray = [NSMutableArray new];
  1769. for (NSString *account in listAccount) {
  1770. CCMenuItem *item = [[CCMenuItem alloc] init];
  1771. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1772. item.argument = account;
  1773. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1774. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  1775. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1776. if (avatar) {
  1777. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1778. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1779. CGSize imageSize = avatarImageView.bounds.size;
  1780. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1781. CGContextRef context = UIGraphicsGetCurrentContext();
  1782. [avatarImageView.layer renderInContext:context];
  1783. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1784. UIGraphicsEndImageContext();
  1785. } else {
  1786. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1787. }
  1788. item.image = avatar;
  1789. item.target = self;
  1790. if ([account isEqualToString:appDelegate.activeAccount]) {
  1791. item.action = nil;
  1792. [menuArray insertObject:item atIndex:0];
  1793. } else {
  1794. item.action = @selector(changeDefaultAccount:);
  1795. [menuArray addObject:item];
  1796. }
  1797. }
  1798. // Add + new account
  1799. CCMenuItem *item = [[CCMenuItem alloc] init];
  1800. item.title = NSLocalizedString(@"_add_account_", nil);
  1801. item.argument = @"";
  1802. item.image = [UIImage imageNamed:@"add"];
  1803. item.target = self;
  1804. item.action = @selector(addNewAccount:);
  1805. [menuArray addObject:item];
  1806. OptionalConfiguration options;
  1807. Color textColor, backgroundColor;
  1808. textColor.R = 0;
  1809. textColor.G = 0;
  1810. textColor.B = 0;
  1811. backgroundColor.R = 1;
  1812. backgroundColor.G = 1;
  1813. backgroundColor.B = 1;
  1814. options.arrowSize = 9;
  1815. options.marginXSpacing = 7;
  1816. options.marginYSpacing = 10;
  1817. options.intervalSpacing = 20;
  1818. options.menuCornerRadius = 6.5;
  1819. options.maskToBackground = NO;
  1820. options.shadowOfMenu = YES;
  1821. options.hasSeperatorLine = YES;
  1822. options.seperatorLineHasInsets = YES;
  1823. options.textColor = textColor;
  1824. options.menuBackgroundColor = backgroundColor;
  1825. CGRect rect = self.view.frame;
  1826. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1827. CGFloat safeAreaTop = 0;
  1828. CGFloat offsetY = 35;
  1829. if (@available(iOS 11, *)) {
  1830. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1831. }
  1832. rect.origin.y = locationY + safeAreaTop + offsetY;
  1833. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1834. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1835. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1836. }
  1837. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1838. {
  1839. 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];
  1840. if (transferInprogress > 0) {
  1841. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1842. return;
  1843. }
  1844. [appDelegate.netQueue cancelAllOperations];
  1845. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1846. // LOGOUT
  1847. [appDelegate unsubscribingNextcloudServerPushNotification];
  1848. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1849. if (tableAccount) {
  1850. // LOGIN
  1851. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  1852. // go to home sweet home
  1853. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1854. [appDelegate subscribingNextcloudServerPushNotification];
  1855. }
  1856. });
  1857. }
  1858. - (void)addNewAccount:(CCMenuItem *)sender
  1859. {
  1860. 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];
  1861. if (transferInprogress > 0) {
  1862. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1863. return;
  1864. }
  1865. [appDelegate.netQueue cancelAllOperations];
  1866. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1867. [appDelegate openLoginView:self loginType:k_login_Add selector:k_intro_login];
  1868. });
  1869. }
  1870. #pragma --------------------------------------------------------------------------------------------
  1871. #pragma mark ==== ReMenu ====
  1872. #pragma --------------------------------------------------------------------------------------------
  1873. - (void)createReMenuBackgroundView:(REMenu *)menu
  1874. {
  1875. CGFloat safeAreaBottom = 0;
  1876. CGFloat safeAreaTop = 0;
  1877. CGFloat statusBar = 0;
  1878. if (@available(iOS 11, *)) {
  1879. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1880. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1881. }
  1882. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1883. statusBar = 13;
  1884. }
  1885. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1886. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1887. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1888. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1889. [UIView animateWithDuration:0.2 animations:^{
  1890. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1891. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1892. if (y>minimum) {
  1893. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1894. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1895. }
  1896. }];
  1897. }
  1898. - (void)createReMainMenu
  1899. {
  1900. NSString *title;
  1901. NSString *groupBy = [CCUtility getGroupBySettings];
  1902. NSString *sorted = [CCUtility getOrderSettings];
  1903. BOOL ascending = [CCUtility getAscendingSettings];
  1904. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1905. 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) {
  1906. if ([sectionDataSource.allRecordsDataSource count] > 0) [self tableViewSelect:YES];
  1907. }];
  1908. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1909. if ([sorted isEqualToString:@"fileName"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_a_z_", nil)]; }
  1910. else title = NSLocalizedString(@"_order_by_name_a_z_", nil);
  1911. appDelegate.sortFileNameAZItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameAZ"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1912. [CCUtility setOrderSettings:@"fileName"];
  1913. [CCUtility setAscendingSettings:true];
  1914. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1915. }];
  1916. if ([sorted isEqualToString:@"fileName"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_name_z_a_", nil)]; }
  1917. else title = NSLocalizedString(@"_order_by_name_z_a_", nil);
  1918. appDelegate.sortFileNameZAItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortFileNameZA"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1919. [CCUtility setOrderSettings:@"fileName"];
  1920. [CCUtility setAscendingSettings:false];
  1921. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1922. }];
  1923. if ([sorted isEqualToString:@"date"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_more_recent_", nil)]; }
  1924. else title = NSLocalizedString(@"_order_by_date_more_recent_", nil);
  1925. appDelegate.sortDateMoreRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateMoreRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1926. [CCUtility setOrderSettings:@"date"];
  1927. [CCUtility setAscendingSettings:false];
  1928. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1929. }];
  1930. if ([sorted isEqualToString:@"date"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_date_less_recent_", nil)]; }
  1931. else title = NSLocalizedString(@"_order_by_date_less_recent_", nil);
  1932. appDelegate.sortDateLessRecentItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortDateLessRecent"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1933. [CCUtility setOrderSettings:@"date"];
  1934. [CCUtility setAscendingSettings:true];
  1935. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1936. }];
  1937. if ([sorted isEqualToString:@"size"] && ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_smallest_", nil)]; }
  1938. else title = NSLocalizedString(@"_order_by_size_smallest_", nil);
  1939. appDelegate.sortSmallestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortSmallest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1940. [CCUtility setOrderSettings:@"size"];
  1941. [CCUtility setAscendingSettings:true];
  1942. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1943. }];
  1944. if ([sorted isEqualToString:@"size"] && !ascending) { title = [NSString stringWithFormat:@"✓ %@", NSLocalizedString(@"_order_by_size_largest_", nil)]; }
  1945. else title = NSLocalizedString(@"_order_by_size_largest_", nil);
  1946. appDelegate.sortLargestItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"sortLargest"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1947. [CCUtility setOrderSettings:@"size"];
  1948. [CCUtility setAscendingSettings:false];
  1949. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1950. }];
  1951. // ITEM GROUP ALPHABETIC -----------------------------------------------------------------------------------------------------
  1952. if ([groupBy isEqualToString:@"alphabetic"]) { title = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1953. else { title = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1954. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1955. if ([groupBy isEqualToString:@"alphabetic"]) [CCUtility setGroupBySettings:@"none"];
  1956. else [CCUtility setGroupBySettings:@"alphabetic"];
  1957. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1958. }];
  1959. // ITEM GROUP TYPEFILE -------------------------------------------------------------------------------------------------------
  1960. if ([groupBy isEqualToString:@"typefile"]) { title = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1961. else { title = NSLocalizedString(@"_group_typefile_no_", nil); }
  1962. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1963. if ([groupBy isEqualToString:@"typefile"]) [CCUtility setGroupBySettings:@"none"];
  1964. else [CCUtility setGroupBySettings:@"typefile"];
  1965. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1966. }];
  1967. // ITEM GROUP DATE -------------------------------------------------------------------------------------------------------
  1968. if ([groupBy isEqualToString:@"date"]) { title = NSLocalizedString(@"_group_date_yes_", nil); }
  1969. else { title = NSLocalizedString(@"_group_date_no_", nil); }
  1970. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1971. if ([groupBy isEqualToString:@"date"]) [CCUtility setGroupBySettings:@"none"];
  1972. else [CCUtility setGroupBySettings:@"date"];
  1973. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1974. }];
  1975. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1976. if ([CCUtility getDirectoryOnTop]) { title = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1977. else { title = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1978. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:title subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"foldersOnTop"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1979. if ([CCUtility getDirectoryOnTop]) [CCUtility setDirectoryOnTop:NO];
  1980. else [CCUtility setDirectoryOnTop:YES];
  1981. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1982. }];
  1983. // REMENU --------------------------------------------------------------------------------------------------------------
  1984. 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]];
  1985. appDelegate.reMainMenu.itemHeight = 40;
  1986. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1987. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1988. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1989. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1990. appDelegate.reMainMenu.separatorHeight = 0.5;
  1991. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1992. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1993. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  1994. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  1995. appDelegate.reMainMenu.textShadowColor = nil;
  1996. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  1997. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  1998. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  1999. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2000. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2001. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2002. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2003. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2004. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2005. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2006. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2007. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2008. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2009. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2010. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2011. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2012. appDelegate.reMainMenu.borderWidth = 0.3;
  2013. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2014. appDelegate.reMainMenu.animationDuration = 0.2;
  2015. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2016. appDelegate.reMainMenu.bounce = NO;
  2017. __weak typeof(self) weakSelf = self;
  2018. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2019. // Backgroun reMenu (Gesture)
  2020. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2021. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2022. }];
  2023. }
  2024. - (void)toggleReMainMenu
  2025. {
  2026. if (appDelegate.reMainMenu.isOpen) {
  2027. [appDelegate.reMainMenu close];
  2028. } else {
  2029. [self createReMainMenu];
  2030. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2031. // Backgroun reMenu & (Gesture)
  2032. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2033. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2034. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2035. }
  2036. }
  2037. - (void)createReSelectMenu
  2038. {
  2039. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  2040. 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) {
  2041. [self didSelectAll];
  2042. }];
  2043. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  2044. 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) {
  2045. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2046. }];
  2047. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2048. 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) {
  2049. [self downloadSelectedFilesFolders];
  2050. }];
  2051. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2052. 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) {
  2053. [self saveSelectedFiles];
  2054. }];
  2055. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2056. 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) {
  2057. [self deleteFile];
  2058. }];
  2059. // E2EE
  2060. if (_metadataFolder.e2eEncrypted) {
  2061. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2062. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  2063. } else {
  2064. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2065. }
  2066. } else {
  2067. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2068. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.deleteItem]];
  2069. } else {
  2070. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2071. }
  2072. }
  2073. appDelegate.reSelectMenu.itemHeight = 50;
  2074. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2075. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2076. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2077. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2078. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2079. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2080. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2081. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2082. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2083. appDelegate.reSelectMenu.textShadowColor = nil;
  2084. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2085. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2086. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2087. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2088. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2089. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2090. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2091. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2092. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2093. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2094. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2095. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2096. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2097. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2098. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2099. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2100. appDelegate.reSelectMenu.borderWidth = 0.3;
  2101. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2102. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2103. appDelegate.reSelectMenu.animationDuration = 0.2;
  2104. appDelegate.reSelectMenu.bounce = NO;
  2105. __weak typeof(self) weakSelf = self;
  2106. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2107. // Backgroun reMenu (Gesture)
  2108. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2109. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2110. }];
  2111. }
  2112. - (void)toggleReSelectMenu
  2113. {
  2114. if (appDelegate.reSelectMenu.isOpen) {
  2115. [appDelegate.reSelectMenu close];
  2116. } else {
  2117. [self createReSelectMenu];
  2118. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2119. // Backgroun reMenu & (Gesture)
  2120. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2121. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2122. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2123. }
  2124. }
  2125. #pragma --------------------------------------------------------------------------------------------
  2126. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2127. #pragma --------------------------------------------------------------------------------------------
  2128. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2129. {
  2130. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2131. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2132. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2133. if ([self indexPathIsValid:indexPath])
  2134. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2135. else
  2136. self.metadata = nil;
  2137. [self becomeFirstResponder];
  2138. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2139. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2140. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2141. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2142. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2143. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2144. if ([NCBrandOptions sharedInstance].disable_openin_file) {
  2145. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, pasteFileItem, pasteFilesItem, nil]];
  2146. } else {
  2147. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2148. }
  2149. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2150. [menuController setMenuVisible:YES animated:YES];
  2151. }
  2152. }
  2153. - (BOOL)canBecomeFirstResponder
  2154. {
  2155. return YES;
  2156. }
  2157. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2158. {
  2159. // For copy file, copy files, Open in ... :
  2160. //
  2161. // NO Directory
  2162. // NO Error Passcode
  2163. // NO In Session mode (download/upload)
  2164. // NO Template
  2165. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2166. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  2167. else return NO;
  2168. }
  2169. if (@selector(copyFiles:) == action) {
  2170. if (_isSelectedMode) {
  2171. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2172. for (tableMetadata *metadata in selectedMetadatas) {
  2173. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2174. return YES;
  2175. }
  2176. }
  2177. return NO;
  2178. }
  2179. if (@selector(pasteFile:) == action) {
  2180. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2181. NSArray *items = [pasteboard items];
  2182. if ([items count] == 1) {
  2183. // Value : (NSData) fileID
  2184. NSDictionary *dic = [items objectAtIndex:0];
  2185. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2186. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2187. if (fileID) {
  2188. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2189. if (metadata) {
  2190. return [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView];
  2191. } else {
  2192. return NO;
  2193. }
  2194. }
  2195. }
  2196. return NO;
  2197. }
  2198. if (@selector(pasteFiles:) == action) {
  2199. BOOL isValid = NO;
  2200. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2201. NSArray *items = [pasteboard items];
  2202. if ([items count] <= 1) return NO;
  2203. for (NSDictionary *dic in items) {
  2204. // Value : (NSData) fileID
  2205. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2206. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2207. if (fileID) {
  2208. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2209. if (metadata) {
  2210. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2211. isValid = YES;
  2212. } else {
  2213. isValid = NO;
  2214. break;
  2215. }
  2216. } else {
  2217. isValid = NO;
  2218. break;
  2219. }
  2220. } else {
  2221. isValid = NO;
  2222. break;
  2223. }
  2224. }
  2225. return isValid;
  2226. }
  2227. return NO;
  2228. }
  2229. /************************************ COPY ************************************/
  2230. - (void)copyFile:(id)sender
  2231. {
  2232. // Remove all item
  2233. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2234. pasteboard.items = [[NSArray alloc] init];
  2235. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2236. [self copyFileToPasteboard:self.metadata];
  2237. } else {
  2238. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2239. if (serverUrl) {
  2240. self.metadata.session = k_download_session;
  2241. self.metadata.sessionError = @"";
  2242. self.metadata.sessionSelector = selectorLoadCopy;
  2243. self.metadata.status = k_metadataStatusWaitDownload;
  2244. // Add Metadata for Download
  2245. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2246. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2247. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2248. }
  2249. }
  2250. }
  2251. - (void)copyFiles:(id)sender
  2252. {
  2253. // Remove all item
  2254. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2255. pasteboard.items = [[NSArray alloc] init];
  2256. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2257. for (tableMetadata *metadata in selectedMetadatas) {
  2258. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2259. [self copyFileToPasteboard:metadata];
  2260. } else {
  2261. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2262. if (serverUrl) {
  2263. metadata.session = k_download_session;
  2264. metadata.sessionError = @"";
  2265. metadata.sessionSelector = selectorLoadCopy;
  2266. metadata.status = k_metadataStatusWaitDownload;
  2267. // Add Metadata for Download
  2268. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2269. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2270. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  2271. }
  2272. }
  2273. }
  2274. [self tableViewSelect:NO];
  2275. }
  2276. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2277. {
  2278. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2279. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2280. // Value : (NSData) fileID
  2281. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2282. [items addObject:item];
  2283. [pasteboard setItems:items];
  2284. }
  2285. /************************************ OPEN IN ... ******************************/
  2286. - (void)openinFile:(id)sender
  2287. {
  2288. [self DownloadOpenIn:self.metadata];
  2289. }
  2290. /************************************ PASTE ************************************/
  2291. - (void)pasteFile:(id)sender
  2292. {
  2293. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2294. [self uploadFilePasteArray:[pasteboard items]];
  2295. }
  2296. - (void)pasteFiles:(id)sender
  2297. {
  2298. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2299. [self uploadFilePasteArray:[pasteboard items]];
  2300. }
  2301. - (void)uploadFilePasteArray:(NSArray *)items
  2302. {
  2303. for (NSDictionary *dic in items) {
  2304. // Value : (NSData) fileID
  2305. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2306. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2307. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2308. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2309. if (metadata) {
  2310. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2311. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView directoryID:directoryID];
  2312. NSString *fileID = [directoryID stringByAppendingString:fileName];
  2313. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName]];
  2314. tableMetadata *metadataForUpload = [tableMetadata new];
  2315. metadataForUpload.account = appDelegate.activeAccount;
  2316. metadataForUpload.date = [NSDate new];
  2317. metadataForUpload.directoryID = directoryID;
  2318. metadataForUpload.fileID = fileID;
  2319. metadataForUpload.fileName = fileName;
  2320. metadataForUpload.fileNameView = fileName;
  2321. metadataForUpload.session = k_upload_session;
  2322. metadataForUpload.sessionSelector = selectorUploadFile;
  2323. metadataForUpload.size = metadata.size;
  2324. metadataForUpload.status = k_metadataStatusWaitUpload;
  2325. // Add Medtadata for upload
  2326. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2327. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2328. }
  2329. }
  2330. }
  2331. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2332. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2333. }
  2334. #pragma --------------------------------------------------------------------------------------------
  2335. #pragma mark ===== Lock Passcode =====
  2336. #pragma --------------------------------------------------------------------------------------------
  2337. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2338. {
  2339. return _failedAttempts;
  2340. }
  2341. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2342. {
  2343. return _lockUntilDate;
  2344. }
  2345. - (void)passcodeViewCloseButtonPressed:(id)sender
  2346. {
  2347. [self dismissViewControllerAnimated:YES completion:nil];
  2348. }
  2349. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2350. {
  2351. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2352. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2353. _lockUntilDate = nil;
  2354. _failedAttempts = 0;
  2355. aResultHandler(YES);
  2356. } else aResultHandler(NO);
  2357. } else aResultHandler(YES);
  2358. }
  2359. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2360. {
  2361. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2362. switch (aViewController.type) {
  2363. case BKPasscodeViewControllerCheckPasscodeType: {
  2364. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2365. // possiamo procedere alla prossima directory
  2366. [self performSegueDirectoryWithControlPasscode:false];
  2367. // avviamo la sessione Passcode Lock con now
  2368. appDelegate.sessionePasscodeLock = [NSDate date];
  2369. }
  2370. // disattivazione lock cartella
  2371. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2372. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2373. if (!serverUrl)
  2374. return;
  2375. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2376. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2377. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2378. }
  2379. [self tableViewReloadData];
  2380. }
  2381. }
  2382. break;
  2383. default:
  2384. break;
  2385. }
  2386. }
  2387. - (void)comandoLockPassword
  2388. {
  2389. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2390. if (!serverUrl) return;
  2391. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2392. // se non è abilitato il Lock Passcode esci
  2393. if ([[CCUtility getBlockCode] length] == 0) {
  2394. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2395. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2396. [alertController addAction:okAction];
  2397. [self presentViewController:alertController animated:YES completion:nil];
  2398. return;
  2399. }
  2400. // se è richiesta la disattivazione si chiede la password
  2401. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2402. if (directory.lock) {
  2403. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2404. viewController.delegate = self;
  2405. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2406. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2407. viewController.inputViewTitlePassword = YES;
  2408. if ([CCUtility getSimplyBlockCode]) {
  2409. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2410. viewController.passcodeInputView.maximumLength = 6;
  2411. } else {
  2412. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2413. viewController.passcodeInputView.maximumLength = 64;
  2414. }
  2415. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2416. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2417. viewController.touchIDManager = touchIDManager;
  2418. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2419. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2420. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2421. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2422. [self presentViewController:navigationController animated:YES completion:nil];
  2423. return;
  2424. }
  2425. // ---------------- ACTIVATE PASSWORD
  2426. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2427. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:self.metadata.fileID];
  2428. if ([self indexPathIsValid:indexPath])
  2429. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2430. } else {
  2431. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2432. }
  2433. }
  2434. #pragma mark -
  2435. #pragma --------------------------------------------------------------------------------------------
  2436. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2437. #pragma --------------------------------------------------------------------------------------------
  2438. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2439. {
  2440. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2441. return NO;
  2442. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2443. return NO;
  2444. // E2EE
  2445. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2446. return NO;
  2447. return YES;
  2448. }
  2449. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2450. {
  2451. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2452. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2453. return [self canOpenMenuAction:metadata];
  2454. }
  2455. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2456. {
  2457. }
  2458. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2459. {
  2460. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2461. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2462. if (direction == MGSwipeDirectionRightToLeft) {
  2463. [self actionDelete:indexPath];
  2464. }
  2465. if (direction == MGSwipeDirectionLeftToRight) {
  2466. if (self.metadata.favorite)
  2467. [self settingFavorite:self.metadata favorite:NO];
  2468. else
  2469. [self settingFavorite:self.metadata favorite:YES];
  2470. }
  2471. return YES;
  2472. }
  2473. - (void)actionDelete:(NSIndexPath *)indexPath
  2474. {
  2475. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2476. // Directory locked ?
  2477. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID] addFileName:metadata.fileName];
  2478. if (!lockServerUrl) return;
  2479. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2480. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2481. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2482. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2483. return;
  2484. }
  2485. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2486. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2487. [self performSelector:@selector(deleteFile) withObject:nil];
  2488. }]];
  2489. if (localFile) {
  2490. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2491. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2492. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  2493. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2494. }]];
  2495. }
  2496. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2497. }]];
  2498. alertController.popoverPresentationController.sourceView = self.tableView;
  2499. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2500. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2501. [alertController.view layoutIfNeeded];
  2502. [self presentViewController:alertController animated:YES completion:nil];
  2503. }
  2504. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2505. {
  2506. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2507. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2508. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2509. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2510. if (!serverUrl) return;
  2511. NSString *titoloLock, *titleFavorite;
  2512. if (self.metadata.favorite) {
  2513. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2514. } else {
  2515. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2516. }
  2517. if (self.metadata.directory) {
  2518. // calcolo lockServerUrl
  2519. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2520. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2521. if (directory.lock)
  2522. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2523. else
  2524. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2525. }
  2526. // ******************************************* AHKActionSheet *******************************************
  2527. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2528. actionSheet.animationDuration = 0.2;
  2529. actionSheet.buttonHeight = 50.0;
  2530. actionSheet.cancelButtonHeight = 50.0f;
  2531. actionSheet.separatorHeight = 5.0f;
  2532. actionSheet.automaticallyTintButtonImages = @(NO);
  2533. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2534. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2535. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2536. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2537. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2538. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2539. // ******************************************* DIRECTORY *******************************************
  2540. if (self.metadata.directory) {
  2541. BOOL lockDirectory = NO;
  2542. BOOL optionOffline = NO;
  2543. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2544. NSString *firstServerUrl = [CCUtility firtsPathComponentFromServerUrl:dirServerUrl activeUrl:appDelegate.activeUrl];
  2545. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2546. // Directory bloccata ?
  2547. tableDirectory *directoryForLock = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2548. if (directoryForLock.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2549. // Directory set as offline ?
  2550. tableDirectory *directoryOffline = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl CONTAINS %@ AND offline == true", appDelegate.activeAccount, firstServerUrl]];
  2551. if (directoryOffline == nil) {
  2552. optionOffline = YES;
  2553. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2554. optionOffline = YES;
  2555. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2556. optionOffline = YES;
  2557. }
  2558. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2559. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2560. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2561. height:50.0
  2562. type:AHKActionSheetButtonTypeDisabled
  2563. handler:nil
  2564. ];
  2565. [actionSheet addButtonWithTitle: titleFavorite
  2566. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2567. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2568. height: 50.0
  2569. type: AHKActionSheetButtonTypeDefault
  2570. handler: ^(AHKActionSheet *as) {
  2571. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2572. else [self settingFavorite:self.metadata favorite:YES];
  2573. }];
  2574. if (!lockDirectory && !isFolderEncrypted) {
  2575. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2576. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2577. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2578. height:50.0
  2579. type:AHKActionSheetButtonTypeDefault
  2580. handler:^(AHKActionSheet *as) {
  2581. [self openWindowShare:self.metadata];
  2582. }];
  2583. }
  2584. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2585. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2586. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2587. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2588. height:50.0
  2589. type:AHKActionSheetButtonTypeDefault
  2590. handler:^(AHKActionSheet *as) {
  2591. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2592. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2593. textField.text = self.metadata.fileNameView;
  2594. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2595. //textField.delegate = self;
  2596. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2597. }];
  2598. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2599. NSLog(@"[LOG] Cancel action");
  2600. }];
  2601. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2602. UITextField *fileName = alertController.textFields.firstObject;
  2603. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2604. }];
  2605. okAction.enabled = NO;
  2606. [alertController addAction:cancelAction];
  2607. [alertController addAction:okAction];
  2608. [self presentViewController:alertController animated:YES completion:nil];
  2609. }];
  2610. }
  2611. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2612. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2613. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2614. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2615. height:50.0
  2616. type:AHKActionSheetButtonTypeDefault
  2617. handler:^(AHKActionSheet *as) {
  2618. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2619. }];
  2620. }
  2621. if (!isFolderEncrypted && optionOffline) {
  2622. NSString *title;
  2623. if (directoryOffline == nil) {
  2624. title = NSLocalizedString(@"_set_available_offline_", nil);
  2625. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2626. title = NSLocalizedString(@"_remove_available_offline_", nil);
  2627. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2628. title = NSLocalizedString(@"_set_available_offline_", nil);
  2629. }
  2630. [actionSheet addButtonWithTitle:title
  2631. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2632. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2633. height:50.0
  2634. type:AHKActionSheetButtonTypeDefault
  2635. handler:^(AHKActionSheet *as) {
  2636. if (directoryOffline == nil) {
  2637. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true];
  2638. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload];
  2639. } else if (directoryOffline.serverUrl.length == dirServerUrl.length) {
  2640. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:false];
  2641. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2642. } else if (directoryOffline.serverUrl.length > dirServerUrl.length) {
  2643. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:directoryOffline.serverUrl offline:false];
  2644. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:dirServerUrl offline:true];
  2645. [[CCSynchronize sharedSynchronize] readFolder:dirServerUrl selector:selectorReadFolderWithDownload];
  2646. }
  2647. }];
  2648. }
  2649. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2650. [actionSheet addButtonWithTitle:titoloLock
  2651. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2652. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2653. height:50.0
  2654. type:AHKActionSheetButtonTypeDefault
  2655. handler:^(AHKActionSheet *as) {
  2656. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2657. }];
  2658. }
  2659. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2660. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2661. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2662. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2663. height:50.0
  2664. type:AHKActionSheetButtonTypeDefault
  2665. handler:^(AHKActionSheet *as) {
  2666. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2667. 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];
  2668. dispatch_async(dispatch_get_main_queue(), ^{
  2669. if (error) {
  2670. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2671. } else {
  2672. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2673. [self readFolder:self.serverUrl];
  2674. }
  2675. });
  2676. });
  2677. }];
  2678. }
  2679. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2680. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2681. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2682. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2683. height:50.0
  2684. type:AHKActionSheetButtonTypeDefault
  2685. handler:^(AHKActionSheet *as) {
  2686. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2687. 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];
  2688. dispatch_async(dispatch_get_main_queue(), ^{
  2689. if (error) {
  2690. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2691. } else {
  2692. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2693. [self readFolder:self.serverUrl];
  2694. }
  2695. });
  2696. });
  2697. }];
  2698. }
  2699. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2700. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2701. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2702. height:50.0
  2703. type:AHKActionSheetButtonTypeDestructive
  2704. handler:^(AHKActionSheet *as) {
  2705. [self actionDelete:indexPath];
  2706. }];
  2707. [actionSheet show];
  2708. }
  2709. // ******************************************* FILE *******************************************
  2710. if (!self.metadata.directory) {
  2711. UIImage *iconHeader;
  2712. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2713. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]])
  2714. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]];
  2715. else
  2716. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2717. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2718. image: iconHeader
  2719. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2720. height: 50.0
  2721. type: AHKActionSheetButtonTypeDisabled
  2722. handler: nil
  2723. ];
  2724. [actionSheet addButtonWithTitle: titleFavorite
  2725. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2726. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2727. height: 50.0
  2728. type: AHKActionSheetButtonTypeDefault
  2729. handler: ^(AHKActionSheet *as) {
  2730. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2731. else [self settingFavorite:self.metadata favorite:YES];
  2732. }];
  2733. if (!_metadataFolder.e2eEncrypted) {
  2734. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2735. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2736. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2737. height: 50.0
  2738. type:AHKActionSheetButtonTypeDefault
  2739. handler:^(AHKActionSheet *as) {
  2740. [self openWindowShare:self.metadata];
  2741. }];
  2742. }
  2743. if (![NCBrandOptions sharedInstance].disable_openin_file) {
  2744. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2745. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2746. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2747. height: 50.0
  2748. type:AHKActionSheetButtonTypeDefault
  2749. handler:^(AHKActionSheet *as) {
  2750. [self performSelector:@selector(DownloadOpenIn:) withObject:self.metadata];
  2751. }];
  2752. }
  2753. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2754. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2755. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2756. height: 50.0
  2757. type:AHKActionSheetButtonTypeDefault
  2758. handler:^(AHKActionSheet *as) {
  2759. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2760. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2761. textField.text = self.metadata.fileNameView;
  2762. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2763. }];
  2764. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2765. NSLog(@"[LOG] Cancel action");
  2766. }];
  2767. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2768. UITextField *fileName = alertController.textFields.firstObject;
  2769. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2770. }];
  2771. okAction.enabled = NO;
  2772. [alertController addAction:cancelAction];
  2773. [alertController addAction:okAction];
  2774. [self presentViewController:alertController animated:YES completion:nil];
  2775. }];
  2776. if (!_metadataFolder.e2eEncrypted) {
  2777. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2778. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2779. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2780. height:50.0
  2781. type:AHKActionSheetButtonTypeDefault
  2782. handler:^(AHKActionSheet *as) {
  2783. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2784. }];
  2785. }
  2786. if (!_metadataFolder.e2eEncrypted) {
  2787. NSString *title;
  2788. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", self.metadata.fileID]];
  2789. if (localFile == nil || localFile.offline == false) { title = NSLocalizedString(@"_set_available_offline_", nil); }
  2790. else { title = NSLocalizedString(@"_remove_available_offline_", nil); }
  2791. [actionSheet addButtonWithTitle:title
  2792. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"offline"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2793. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2794. height:50.0
  2795. type:AHKActionSheetButtonTypeDefault
  2796. handler:^(AHKActionSheet *as) {
  2797. if (localFile == nil || ![CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2798. self.metadata.session = k_download_session;
  2799. self.metadata.sessionError = @"";
  2800. self.metadata.sessionSelector = selectorLoadOffline;
  2801. self.metadata.status = k_metadataStatusWaitDownload;
  2802. // Add Metadata for Download
  2803. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2804. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2805. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2806. } else if (localFile.offline == false) {
  2807. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:true];
  2808. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2809. } else {
  2810. [[NCManageDatabase sharedInstance] setLocalFileWithFileID:self.metadata.fileID offline:false];
  2811. [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  2812. }
  2813. }];
  2814. }
  2815. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2816. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2817. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2818. height:50.0
  2819. type:AHKActionSheetButtonTypeDestructive
  2820. handler:^(AHKActionSheet *as) {
  2821. [self actionDelete:indexPath];
  2822. }];
  2823. [actionSheet show];
  2824. }
  2825. }
  2826. #pragma --------------------------------------------------------------------------------------------
  2827. #pragma mark - ==== Datasource ====
  2828. #pragma --------------------------------------------------------------------------------------------
  2829. - (void)clearDateReadDataSource:(NSNotification *)notification
  2830. {
  2831. _dateReadDataSource = Nil;
  2832. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2833. }
  2834. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID action:(NSInteger)action
  2835. {
  2836. // test
  2837. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2838. return;
  2839. // Search Mode
  2840. if (_isSearchMode) {
  2841. // Create metadatas
  2842. NSMutableArray *metadatas = [NSMutableArray new];
  2843. for (tableMetadata *resultMetadata in _searchResultMetadatas) {
  2844. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", resultMetadata.fileID]];
  2845. if (metadata) {
  2846. [metadatas addObject:metadata];
  2847. }
  2848. }
  2849. sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:metadatas listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2850. [self tableViewReloadData];
  2851. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2852. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2853. _noFilesSearchDescription = @"";
  2854. }
  2855. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2856. _noFilesSearchTitle = @"";
  2857. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2858. }
  2859. [self.tableView reloadEmptyDataSet];
  2860. return;
  2861. }
  2862. // Se non siamo nella dir appropriata esci
  2863. if ([serverUrl isEqualToString:self.serverUrl] == NO || self.serverUrl == nil) {
  2864. return;
  2865. }
  2866. // Remove optimization for encrypted directory
  2867. if (_metadataFolder.e2eEncrypted)
  2868. _dateReadDataSource = nil;
  2869. // Controllo data lettura Data Source
  2870. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2871. // Get MetadataFolder
  2872. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2873. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  2874. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2875. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2876. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2877. _dateReadDataSource = [NSDate date];
  2878. // Data Source
  2879. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2880. CCSectionDataSourceMetadata *sectionDataSourceTemp = [self queryDatasourceWithReloadData:NO serverUrl:serverUrl];
  2881. dispatch_async(dispatch_get_main_queue(), ^{
  2882. sectionDataSource = sectionDataSourceTemp;
  2883. [self tableViewReloadData];
  2884. });
  2885. });
  2886. } else {
  2887. [self tableViewReloadData];
  2888. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2889. }
  2890. }
  2891. - (CCSectionDataSourceMetadata *)queryDatasourceWithReloadData:(BOOL)withReloadData serverUrl:(NSString *)serverUrl
  2892. {
  2893. // test
  2894. if (appDelegate.activeAccount.length == 0 || serverUrl == nil) {
  2895. return nil;
  2896. }
  2897. // current directoryID
  2898. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  2899. if (directoryID == nil) {
  2900. return nil;
  2901. }
  2902. // get auto upload folder
  2903. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2904. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2905. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2906. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND status != %i", directoryID, k_metadataStatusHide] sorted:[CCUtility getOrderSettings] ascending:[CCUtility getAscendingSettings]];
  2907. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:[CCUtility getGroupBySettings] filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2908. if (withReloadData) {
  2909. sectionDataSource = sectionDataSourceTemp;
  2910. [self tableViewReloadData];
  2911. }
  2912. return sectionDataSourceTemp;
  2913. }
  2914. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2915. {
  2916. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2917. if (selectedRows.count > 0) {
  2918. for (NSIndexPath *selectionIndex in selectedRows) {
  2919. NSString *fileID = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2920. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  2921. [metadatas addObject:metadata];
  2922. }
  2923. }
  2924. return metadatas;
  2925. }
  2926. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2927. {
  2928. NSInteger totSections =[sectionDataSource.sections count] ;
  2929. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2930. return nil;
  2931. }
  2932. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2933. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2934. }
  2935. #pragma --------------------------------------------------------------------------------------------
  2936. #pragma mark - ==== Table ====
  2937. #pragma --------------------------------------------------------------------------------------------
  2938. - (void)tableViewSelect:(BOOL)edit
  2939. {
  2940. // chiudiamo eventuali swipe aperti
  2941. if (edit)
  2942. [self.tableView setEditing:NO animated:NO];
  2943. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2944. [self.tableView setEditing:edit animated:YES];
  2945. _isSelectedMode = edit;
  2946. if (edit)
  2947. [self setUINavigationBarSelected];
  2948. else
  2949. [self setUINavigationBarDefault];
  2950. [_selectedFileIDsMetadatas removeAllObjects];
  2951. [self setTitle];
  2952. }
  2953. - (void)tableViewReloadData
  2954. {
  2955. // store selected cells before relod
  2956. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2957. // reload table view
  2958. [self.tableView reloadData];
  2959. // selected cells stored
  2960. for (NSIndexPath *path in indexPaths)
  2961. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2962. [self setTableViewFooter];
  2963. if (self.tableView.editing)
  2964. [self setTitle];
  2965. //
  2966. [self.tableView reloadEmptyDataSet];
  2967. }
  2968. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2969. {
  2970. if (tableView.editing == 1) {
  2971. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2972. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2973. return NO;
  2974. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2975. return NO;
  2976. else
  2977. return YES;
  2978. } else {
  2979. [_selectedFileIDsMetadatas removeAllObjects];
  2980. }
  2981. return YES;
  2982. }
  2983. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2984. {
  2985. return 60;
  2986. }
  2987. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2988. {
  2989. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2990. }
  2991. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2992. {
  2993. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2994. }
  2995. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2996. {
  2997. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2998. NSString *sectionTitle = [sections objectAtIndex:section];
  2999. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3000. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3001. if ([[CCUtility getGroupBySettings] isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3002. return 20.f;
  3003. }
  3004. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3005. {
  3006. float shift;
  3007. UIVisualEffectView *visualEffectView;
  3008. NSString *titleSection;
  3009. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3010. return nil;
  3011. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3012. titleSection = [sectionDataSource.sections objectAtIndex:section];
  3013. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3014. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  3015. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3016. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3017. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3018. else titleSection = NSLocalizedString(titleSection,nil);
  3019. // Format title
  3020. NSString *currentDevice = [CCUtility currentDevice];
  3021. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3022. visualEffectView = [[UIVisualEffectView alloc] init];
  3023. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3024. } else {
  3025. UIVisualEffect *blurEffect;
  3026. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3027. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3028. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3029. }
  3030. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"]) {
  3031. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3032. shift = - 35;
  3033. else
  3034. shift = - 20;
  3035. } else shift = - 10;
  3036. // Title
  3037. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3038. titleLabel.backgroundColor = [UIColor clearColor];
  3039. titleLabel.textColor = [UIColor blackColor];
  3040. titleLabel.font = [UIFont systemFontOfSize:12];
  3041. titleLabel.textAlignment = NSTextAlignmentLeft;
  3042. titleLabel.text = titleSection;
  3043. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3044. [visualEffectView.contentView addSubview:titleLabel];
  3045. // Elements
  3046. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3047. elementLabel.backgroundColor = [UIColor clearColor];
  3048. elementLabel.textColor = [UIColor blackColor];;
  3049. elementLabel.font = [UIFont systemFontOfSize:12];
  3050. elementLabel.textAlignment = NSTextAlignmentRight;
  3051. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3052. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3053. NSUInteger rowsCount = [metadatas count];
  3054. if (rowsCount == 0) return nil;
  3055. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3056. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3057. [visualEffectView.contentView addSubview:elementLabel];
  3058. return visualEffectView;
  3059. }
  3060. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3061. {
  3062. return [sectionDataSource.sections indexOfObject:title];
  3063. }
  3064. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3065. {
  3066. if ([[CCUtility getGroupBySettings] isEqualToString:@"alphabetic"])
  3067. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3068. else
  3069. return nil;
  3070. }
  3071. /*
  3072. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3073. {
  3074. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3075. }
  3076. }
  3077. */
  3078. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3079. {
  3080. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3081. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3082. return [CCCellMain new];
  3083. }
  3084. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3085. if (serverUrl == nil) {
  3086. return [CCCellMain new];
  3087. }
  3088. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  3089. // NORMAL - > MAIN
  3090. if ([cell isKindOfClass:[CCCellMain class]]) {
  3091. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3092. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3093. BOOL isShare = false;
  3094. BOOL isMounted = false;
  3095. if (_metadataFolder) {
  3096. isShare = [metadata.permissions containsString:k_permission_shared] && ![_metadataFolder.permissions containsString:k_permission_shared];
  3097. isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_metadataFolder.permissions containsString:k_permission_mounted];
  3098. }
  3099. // Share add Tap
  3100. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  3101. if (isShare || isMounted) {
  3102. // Shared with you
  3103. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3104. [tap setNumberOfTapsRequired:1];
  3105. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3106. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3107. } else if (shareLink != nil || shareUserAndGroup != nil) {
  3108. // You share
  3109. if (metadata.directory) {
  3110. ((CCCellMain *)cell).shared.userInteractionEnabled = NO;
  3111. } else {
  3112. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3113. [tap setNumberOfTapsRequired:1];
  3114. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3115. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3116. }
  3117. }
  3118. }
  3119. // More
  3120. if ([self canOpenMenuAction:metadata]) {
  3121. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3122. [tapMore setNumberOfTapsRequired:1];
  3123. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  3124. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  3125. }
  3126. // MGSwipeButton
  3127. ((CCCellMain *)cell).delegate = self;
  3128. // LEFT
  3129. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:1 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3130. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  3131. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  3132. //centerIconOverText
  3133. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  3134. [favoriteButton centerIconOverText];
  3135. // RIGHT
  3136. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3137. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  3138. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  3139. //centerIconOverText
  3140. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  3141. [deleteButton centerIconOverText];
  3142. }
  3143. // TRANSFER
  3144. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  3145. // gesture Transfer
  3146. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3147. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3148. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3149. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3150. }
  3151. return cell;
  3152. }
  3153. - (void)setTableViewFooter
  3154. {
  3155. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3156. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3157. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3158. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3159. UIFont *appFont = [UIFont systemFontOfSize:12];
  3160. footerLabel.font = appFont;
  3161. footerLabel.textColor = [UIColor grayColor];
  3162. footerLabel.backgroundColor = [UIColor clearColor];
  3163. footerLabel.textAlignment = NSTextAlignmentCenter;
  3164. NSString *folders;
  3165. NSString *files;
  3166. NSString *footerText;
  3167. if (sectionDataSource.directories > 1) {
  3168. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3169. } else if (sectionDataSource.directories == 1){
  3170. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3171. } else {
  3172. folders = @"";
  3173. }
  3174. if (sectionDataSource.files > 1) {
  3175. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3176. } else if (sectionDataSource.files == 1){
  3177. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3178. } else {
  3179. files = @"";
  3180. }
  3181. if ([folders isEqualToString:@""]) {
  3182. footerText = files;
  3183. } else if ([files isEqualToString:@""]) {
  3184. footerText = folders;
  3185. } else {
  3186. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3187. }
  3188. footerLabel.text = footerText;
  3189. [footerView addSubview:footerLabel];
  3190. [self.tableView setTableFooterView:footerView];
  3191. }
  3192. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3193. {
  3194. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3195. // settiamo il record file.
  3196. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3197. if (!self.metadata)
  3198. return;
  3199. // se non può essere selezionata deseleziona
  3200. if ([cell isEditing] == NO)
  3201. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3202. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3203. if (self.tableView.editing) {
  3204. [_selectedFileIDsMetadatas setObject:self.metadata forKey:self.metadata.fileID];
  3205. [self setTitle];
  3206. return;
  3207. }
  3208. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3209. if (!serverUrl) return;
  3210. // se è in corso una sessione
  3211. if (self.metadata.status != k_metadataStatusNormal)
  3212. return;
  3213. // file
  3214. if (self.metadata.directory == NO) {
  3215. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3216. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  3217. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName fileID:self.metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3218. } else {
  3219. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3220. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3221. } else {
  3222. 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) {
  3223. [self shouldPerformSegue:self.metadata];
  3224. } else if ([self.metadata.typeFile isEqualToString: k_metadataTypeFile_document] && [[NCViewerRichdocument sharedInstance] isRichDocument:self.metadata]) {
  3225. [self shouldPerformSegue:self.metadata];
  3226. } else {
  3227. self.metadata.session = k_download_session;
  3228. self.metadata.sessionError = @"";
  3229. self.metadata.sessionSelector = selectorLoadFileView;
  3230. self.metadata.status = k_metadataStatusWaitDownload;
  3231. // Add Metadata for Download
  3232. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3233. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3234. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  3235. }
  3236. }
  3237. }
  3238. }
  3239. if (self.metadata.directory) {
  3240. imageTitleSegue = cell.imageTitleSegue;
  3241. [self performSegueDirectoryWithControlPasscode:true];
  3242. }
  3243. }
  3244. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3245. {
  3246. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3247. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3248. [self setTitle];
  3249. }
  3250. - (void)didSelectAll
  3251. {
  3252. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3253. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3254. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3255. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3256. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3257. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3258. }
  3259. }
  3260. [self setTitle];
  3261. }
  3262. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3263. {
  3264. if (!indexPath)
  3265. return NO;
  3266. NSInteger section = indexPath.section;
  3267. NSInteger row = indexPath.row;
  3268. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3269. if (section > lastSectionIndex || lastSectionIndex < 0)
  3270. return NO;
  3271. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3272. if (rowCount < 0)
  3273. return NO;
  3274. return row <= rowCount;
  3275. }
  3276. #pragma --------------------------------------------------------------------------------------------
  3277. #pragma mark ===== Navigation ====
  3278. #pragma --------------------------------------------------------------------------------------------
  3279. - (void)shouldPerformSegue:(tableMetadata *)metadata
  3280. {
  3281. // if background return
  3282. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3283. if (self.view.window == NO)
  3284. return;
  3285. // Collapsed ma siamo già in detail esci
  3286. if (self.splitViewController.isCollapsed)
  3287. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3288. // Metadata for push detail
  3289. self.metadataForPushDetail = metadata;
  3290. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3291. }
  3292. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3293. {
  3294. id viewController = segue.destinationViewController;
  3295. tableMetadata *metadata;
  3296. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3297. UINavigationController *nav = viewController;
  3298. _detailViewController = (CCDetail *)nav.topViewController;
  3299. } else {
  3300. _detailViewController = segue.destinationViewController;
  3301. }
  3302. NSMutableArray *photoDataSource = [NSMutableArray new];
  3303. if ([sender isKindOfClass:[tableMetadata class]]) {
  3304. metadata = sender;
  3305. [photoDataSource addObject:sender];
  3306. } else {
  3307. metadata = self.metadataForPushDetail;
  3308. for (NSString *fileID in sectionDataSource.allFileID) {
  3309. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3310. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3311. [photoDataSource addObject:metadata];
  3312. }
  3313. }
  3314. _detailViewController.metadataDetail = metadata;
  3315. _detailViewController.photoDataSource = photoDataSource;
  3316. _detailViewController.dateFilterQuery = nil;
  3317. [_detailViewController setTitle:metadata.fileNameView];
  3318. }
  3319. // can i go to next viewcontroller
  3320. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3321. {
  3322. NSString *nomeDir;
  3323. if (self.tableView.editing == NO) {
  3324. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3325. if (!serverUrl) return;
  3326. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  3327. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3328. // 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
  3329. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3330. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3331. viewController.delegate = self;
  3332. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3333. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3334. viewController.inputViewTitlePassword = YES;
  3335. if ([CCUtility getSimplyBlockCode]) {
  3336. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3337. viewController.passcodeInputView.maximumLength = 6;
  3338. } else {
  3339. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3340. viewController.passcodeInputView.maximumLength = 64;
  3341. }
  3342. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3343. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3344. viewController.touchIDManager = touchIDManager;
  3345. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3346. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3347. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3348. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3349. [self presentViewController:navController animated:YES completion:nil];
  3350. return;
  3351. }
  3352. // E2EE Check enable
  3353. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3354. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3355. return;
  3356. }
  3357. nomeDir = self.metadata.fileName;
  3358. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3359. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3360. if (!viewController) {
  3361. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3362. viewController.serverUrl = serverUrlPush;
  3363. viewController.titleMain = self.metadata.fileName;
  3364. viewController.imageTitle = imageTitleSegue;
  3365. // save self
  3366. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3367. [self.navigationController pushViewController:viewController animated:YES];
  3368. } else {
  3369. if (viewController.isViewLoaded) {
  3370. viewController.titleMain = self.metadata.fileName;
  3371. viewController.imageTitle = imageTitleSegue;
  3372. // Fix : Application tried to present modally an active controller
  3373. if ([self.navigationController isBeingPresented]) {
  3374. // being presented
  3375. } else if ([self.navigationController isMovingToParentViewController]) {
  3376. // being pushed
  3377. } else {
  3378. [self.navigationController pushViewController:viewController animated:YES];
  3379. }
  3380. }
  3381. }
  3382. }
  3383. }
  3384. @end