CCMain.m 206 KB

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