CCMain.m 207 KB

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