CCMain.m 205 KB

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