CCMain.m 209 KB

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