CCMain.m 214 KB

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