CCMain.m 210 KB

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