CCMain.m 207 KB

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