CCMain.m 211 KB

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