CCMain.m 204 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491
  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:nil action:k_action_NULL];
  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:nil action:k_action_NULL];
  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_NULL];
  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_NULL];
  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. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.001 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void) {
  967. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  968. });
  969. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  970. metadataNet.action = actionReadFile;
  971. metadataNet.priority = NSOperationQueuePriorityHigh;
  972. metadataNet.selector = selectorReadFileReloadFolder;
  973. metadataNet.serverUrl = _serverUrl;
  974. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  975. }
  976. #pragma --------------------------------------------------------------------------------------------
  977. #pragma mark ==== Read Folder ====
  978. #pragma --------------------------------------------------------------------------------------------
  979. - (void)readFolderSuccessFailure:(CCMetadataNet *)metadataNet metadataFolder:(tableMetadata *)metadataFolder metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  980. {
  981. // stoprefresh
  982. [_refreshControl endRefreshing];
  983. // Check Active Account
  984. if (![metadataNet.account isEqualToString:metadataNet.account])
  985. return;
  986. // ERROR
  987. if (errorCode != 0) {
  988. _loadingFolder = NO;
  989. // Check Active Account
  990. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  991. return;
  992. // Unauthorized
  993. if (errorCode == kOCErrorServerUnauthorized) {
  994. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  995. } else {
  996. [self tableViewReloadData];
  997. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  998. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  999. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  1000. }
  1001. return;
  1002. }
  1003. // save metadataFolder
  1004. _metadataFolder = metadataFolder;
  1005. if (_isSearchMode == NO) {
  1006. [[NCManageDatabase sharedInstance] setDirectoryWithServerUrl:metadataNet.serverUrl serverUrlTo:nil etag:metadataFolder.etag fileID:metadataFolder.fileID encrypted:metadataFolder.e2eEncrypted];
  1007. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND (status == %d OR status == %d)", metadataNet.directoryID, k_metadataStatusNormal, k_metadataStatusHide] clearDateReadDirectoryID:metadataNet.directoryID];
  1008. [[NCManageDatabase sharedInstance] setDateReadDirectoryWithDirectoryID:metadataNet.directoryID];
  1009. }
  1010. 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];
  1011. // insert in Database
  1012. NSMutableArray *metadatasToInsertInDB = (NSMutableArray *)[[NCManageDatabase sharedInstance] addMetadatas:metadatas serverUrl:metadataNet.serverUrl];
  1013. // reinsert metadatas in Download
  1014. if (metadatasInDownload) {
  1015. (void)[[NCManageDatabase sharedInstance] addMetadatas:metadatasInDownload serverUrl:metadataNet.serverUrl];
  1016. }
  1017. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1018. // File is changed ??
  1019. if (!_isSearchMode && metadatasToInsertInDB)
  1020. [[CCSynchronize sharedSynchronize] verifyChangeMedatas:metadatasToInsertInDB serverUrl:metadataNet.serverUrl account:appDelegate.activeAccount withDownload:NO];
  1021. });
  1022. // Search Mode
  1023. if (_isSearchMode) {
  1024. // Fix managed -> Unmanaged _searchResultMetadatas
  1025. if (metadatasToInsertInDB)
  1026. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatasToInsertInDB];
  1027. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  1028. }
  1029. // this is the same directory
  1030. if ([metadataNet.serverUrl isEqualToString:_serverUrl] && !_isSearchMode) {
  1031. // reload
  1032. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:nil action:k_action_NULL];
  1033. // Enable change user
  1034. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  1035. _loadingFolder = NO;
  1036. [self tableViewReloadData];
  1037. }
  1038. // E2EE Is encrypted folder get metadata
  1039. if (_metadataFolder.e2eEncrypted) {
  1040. // Read Metadata
  1041. if ([CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  1042. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
  1043. NSString *metadata;
  1044. NSError *error = [[NCNetworkingEndToEnd sharedManager] getEndToEndMetadata:&metadata fileID:metadataFolder.fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1045. dispatch_async(dispatch_get_main_queue(), ^{
  1046. if (error) {
  1047. if (error.code != 404)
  1048. [appDelegate messageNotification:@"_e2e_error_get_metadata_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1049. } else {
  1050. if ([[NCEndToEndMetadata sharedInstance] decoderMetadata:metadata privateKey:[CCUtility getEndToEndPrivateKey:appDelegate.activeAccount] serverUrl:self.serverUrl account:appDelegate.activeAccount url:appDelegate.activeUrl] == false)
  1051. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_decode_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1052. else
  1053. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1054. }
  1055. });
  1056. });
  1057. } else {
  1058. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1059. }
  1060. }
  1061. // rewrite title
  1062. [self setTitle];
  1063. }
  1064. - (void)readFolder:(NSString *)serverUrl
  1065. {
  1066. // init control
  1067. if (!serverUrl || !appDelegate.activeAccount || appDelegate.maintenanceMode) {
  1068. [_refreshControl endRefreshing];
  1069. return;
  1070. }
  1071. // Search Mode
  1072. if (_isSearchMode) {
  1073. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1074. _searchFileName = @""; // forced reload searchg
  1075. [self updateSearchResultsForSearchController:self.searchController];
  1076. return;
  1077. }
  1078. _loadingFolder = YES;
  1079. [self tableViewReloadData];
  1080. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  1081. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1082. metadataNet.action = actionReadFolder;
  1083. metadataNet.date = [NSDate date];
  1084. metadataNet.depth = @"1";
  1085. metadataNet.directoryID = directory.directoryID;
  1086. metadataNet.priority = NSOperationQueuePriorityHigh;
  1087. metadataNet.selector = selectorReadFolder;
  1088. metadataNet.serverUrl = serverUrl;
  1089. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1090. }
  1091. #pragma mark -
  1092. #pragma --------------------------------------------------------------------------------------------
  1093. #pragma mark ===== Search =====
  1094. #pragma --------------------------------------------------------------------------------------------
  1095. - (void)searchEnabled:(BOOL)enabled
  1096. {
  1097. if (enabled) {
  1098. if (self.tableView.tableHeaderView != nil)
  1099. return;
  1100. self.definesPresentationContext = YES;
  1101. self.searchController.searchResultsUpdater = self;
  1102. self.searchController.dimsBackgroundDuringPresentation = NO;
  1103. self.searchController.searchBar.translucent = NO;
  1104. [self.searchController.searchBar sizeToFit];
  1105. self.searchController.searchBar.delegate = self;
  1106. self.searchController.searchBar.barTintColor = [NCBrandColor sharedInstance].brand;
  1107. self.searchController.searchBar.backgroundColor = [NCBrandColor sharedInstance].brand;
  1108. self.searchController.searchBar.backgroundImage = [UIImage new];
  1109. // color searchbbar button text (cancel)
  1110. UIButton *searchButton = self.searchController.searchBar.subviews.firstObject.subviews.lastObject;
  1111. if (searchButton && [searchButton isKindOfClass:[UIButton class]]) {
  1112. [searchButton setTitleColor:[NCBrandColor sharedInstance].brandText forState:UIControlStateNormal];
  1113. }
  1114. self.tableView.tableHeaderView = self.searchController.searchBar;
  1115. [self.tableView setContentOffset:CGPointMake(0, self.searchController.searchBar.frame.size.height - self.tableView.contentOffset.y)];
  1116. } else {
  1117. self.tableView.tableHeaderView = nil;
  1118. }
  1119. }
  1120. - (void)searchStartTimer
  1121. {
  1122. NSString *startDirectory = [CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl];
  1123. [[CCActions sharedInstance] search:startDirectory fileName:_searchFileName etag:@"" depth:@"infinity" date:nil contenType:nil selector:selectorSearchFiles delegate:self];
  1124. _noFilesSearchTitle = @"";
  1125. _noFilesSearchDescription = NSLocalizedString(@"_search_in_progress_", nil);
  1126. [self.tableView reloadEmptyDataSet];
  1127. }
  1128. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  1129. {
  1130. // Color text "Cancel"
  1131. [[UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UISearchBar class]]] setTintColor:[NCBrandColor sharedInstance].brandText];
  1132. _isSearchMode = YES;
  1133. [self deleteRefreshControl];
  1134. NSString *fileName = [CCUtility removeForbiddenCharactersServer:searchController.searchBar.text];
  1135. if (fileName.length >= k_minCharsSearch && [fileName isEqualToString:_searchFileName] == NO) {
  1136. _searchFileName = fileName;
  1137. // First : filter
  1138. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1139. if (!directoryID) return;
  1140. NSPredicate *predicate = [NSPredicate predicateWithFormat:@"directoryID == %@ AND fileNameView CONTAINS[cd] %@", directoryID, fileName];
  1141. NSArray *records = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:predicate sorted:nil ascending:NO];
  1142. [_searchResultMetadatas removeAllObjects];
  1143. for (tableMetadata *record in records)
  1144. [_searchResultMetadatas addObject:record];
  1145. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1146. metadataNet.account = appDelegate.activeAccount;
  1147. metadataNet.directoryID = directoryID;
  1148. metadataNet.selector = selectorSearchFiles;
  1149. metadataNet.serverUrl = _serverUrl;
  1150. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:_searchResultMetadatas message:nil errorCode:0];
  1151. // Version >= 12
  1152. if ([[NCManageDatabase sharedInstance] getServerVersion] >= 12) {
  1153. [_timerWaitInput invalidate];
  1154. _timerWaitInput = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(searchStartTimer) userInfo:nil repeats:NO];
  1155. }
  1156. }
  1157. if (_searchResultMetadatas.count == 0 && fileName.length == 0) {
  1158. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1159. }
  1160. }
  1161. - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
  1162. {
  1163. [self cancelSearchBar];
  1164. [self readFolder:_serverUrl];
  1165. }
  1166. - (void)searchSuccessFailure:(CCMetadataNet *)metadataNet metadatas:(NSArray *)metadatas message:(NSString *)message errorCode:(NSInteger)errorCode
  1167. {
  1168. // Check Active Account
  1169. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1170. return;
  1171. if (errorCode == 0) {
  1172. _searchResultMetadatas = [[NSMutableArray alloc] initWithArray:metadatas];
  1173. [self readFolderSuccessFailure:metadataNet metadataFolder:nil metadatas:metadatas message:nil errorCode:0];
  1174. } else {
  1175. // Unauthorized
  1176. if (errorCode == kOCErrorServerUnauthorized)
  1177. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1178. else
  1179. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1180. _searchFileName = @"";
  1181. }
  1182. }
  1183. - (void)cancelSearchBar
  1184. {
  1185. if (self.searchController.active) {
  1186. [self.searchController setActive:NO];
  1187. [self createRefreshControl];
  1188. _isSearchMode = NO;
  1189. _searchFileName = @"";
  1190. _dateReadDataSource = nil;
  1191. _searchResultMetadatas = [NSMutableArray new];
  1192. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1193. }
  1194. //[self setNeedsStatusBarAppearanceUpdate];
  1195. }
  1196. #pragma mark -
  1197. #pragma --------------------------------------------------------------------------------------------
  1198. #pragma mark ===== Delete File or Folder =====
  1199. #pragma --------------------------------------------------------------------------------------------
  1200. - (void)deleteFile
  1201. {
  1202. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1203. return;
  1204. NSArray *metadatas;
  1205. if ([_selectedFileIDsMetadatas count] > 0) {
  1206. metadatas = [_selectedFileIDsMetadatas allValues];
  1207. } else {
  1208. metadatas = [[NSArray alloc] initWithObjects:self.metadata, nil];
  1209. }
  1210. // remove optimization
  1211. _dateReadDataSource = nil;
  1212. [[NCMainCommon sharedInstance ] deleteFileWithMetadatas:metadatas e2ee:_metadataFolder.e2eEncrypted serverUrl:self.serverUrl folderFileID:_metadataFolder.fileID completion:^(NSInteger errorCode, NSString *message) {
  1213. // Reload
  1214. if (_isSearchMode)
  1215. [self readFolder:self.serverUrl];
  1216. else
  1217. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1218. }];
  1219. // End Select Table View
  1220. [self tableViewSelect:NO];
  1221. }
  1222. #pragma --------------------------------------------------------------------------------------------
  1223. #pragma mark ===== Rename / Move =====
  1224. #pragma --------------------------------------------------------------------------------------------
  1225. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1226. {
  1227. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:metadataNet.serverUrl fileID:metadataNet.fileID action:k_action_MOD];
  1228. }
  1229. - (void)renameFile:(NSArray *)arguments
  1230. {
  1231. tableMetadata* metadata = [arguments objectAtIndex:0];
  1232. NSString *fileName = [arguments objectAtIndex:1];
  1233. // E2EE
  1234. if (_metadataFolder.e2eEncrypted) {
  1235. // verify if exists the new fileName
  1236. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@ AND fileName == %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1237. [appDelegate messageNotification:@"_error_e2ee_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  1238. return;
  1239. }
  1240. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1241. 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];
  1242. if (error) {
  1243. dispatch_async(dispatch_get_main_queue(), ^{
  1244. [appDelegate messageNotification:@"_error_e2ee_" description:@"_e2e_error_send_metadata_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1245. });
  1246. } else {
  1247. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1248. // Move file system
  1249. NSString *atPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], metadata.fileNameView];
  1250. NSString *toPath = [NSString stringWithFormat:@"%@/%@", [CCUtility getDirectoryProviderStorageFileID:metadata.fileID], fileName];
  1251. [[NSFileManager defaultManager] moveItemAtPath:atPath toPath:toPath error:nil];
  1252. [[NSFileManager defaultManager] moveItemAtPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageIconFileID:metadata.fileID fileNameView:fileName] error:nil];
  1253. }
  1254. // Unlock
  1255. tableE2eEncryptionLock *tableLock = [[NCManageDatabase sharedInstance] getE2ETokenLockWithServerUrl:self.serverUrl];
  1256. if (tableLock != nil) {
  1257. 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];
  1258. if (error) {
  1259. dispatch_async(dispatch_get_main_queue(), ^{
  1260. [appDelegate messageNotification:@"_e2e_error_unlock_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1261. });
  1262. }
  1263. }
  1264. dispatch_async(dispatch_get_main_queue(), ^{
  1265. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1266. });
  1267. });
  1268. } else {
  1269. // Plain
  1270. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1271. }
  1272. }
  1273. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1274. {
  1275. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1276. [_hud hideHud];
  1277. if (message && errorCode != kOCErrorServerUnauthorized)
  1278. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1279. // End Select Table View
  1280. [self tableViewSelect:NO];
  1281. // reload Datasource
  1282. if (_isSearchMode)
  1283. [self readFolder:metadataNet.serverUrl];
  1284. else
  1285. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1286. }
  1287. }
  1288. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1289. {
  1290. [_queueSelector removeObject:metadataNet.selector];
  1291. if ([_queueSelector count] == 0) {
  1292. [_hud hideHud];
  1293. NSString *fileName = metadataNet.fileName;
  1294. NSString *directoryID = metadataNet.directoryID;
  1295. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1296. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1297. if (!serverUrlTo) return;
  1298. // FILE -> Metadata
  1299. if (metadataNet.directory == NO)
  1300. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1301. // DIRECTORY -> Directory - CCMetadata
  1302. if (metadataNet.directory == YES) {
  1303. // delete all dir / subdir
  1304. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1305. // move metadata
  1306. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1307. // Add new directory
  1308. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1309. (void) [[NCManageDatabase sharedInstance] addDirectoryWithEncrypted:false favorite:false fileID:nil permissions:nil serverUrl:newDirectory];
  1310. }
  1311. // next
  1312. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1313. if ([_selectedFileIDsMetadatas count] > 0) {
  1314. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1315. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1316. } else {
  1317. // End Select Table View
  1318. [self tableViewSelect:NO];
  1319. // reload Datasource
  1320. if (_isSearchMode)
  1321. [self readFolder:metadataNet.serverUrl];
  1322. else
  1323. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1324. }
  1325. }
  1326. }
  1327. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1328. {
  1329. tableMetadata *metadata = [arguments objectAtIndex:0];
  1330. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1331. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1332. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1333. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1334. if (!serverUrl) return;
  1335. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1336. if (!directoryIDTo) return;
  1337. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1338. [ocNetworking readFile:metadata.fileName serverUrl:serverUrlTo account:appDelegate.activeAccount success:^(tableMetadata *metadata) {
  1339. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1340. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1341. }];
  1342. [alert addAction:ok];
  1343. [self presentViewController:alert animated:YES completion:nil];
  1344. // End Select Table View
  1345. [self tableViewSelect:NO];
  1346. // reload Datasource
  1347. [self readFileReloadFolder];
  1348. } failure:^(NSString *message, NSInteger errorCode) {
  1349. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1350. metadataNet.action = actionMoveFileOrFolder;
  1351. metadataNet.directory = metadata.directory;
  1352. metadataNet.fileID = metadata.fileID;
  1353. metadataNet.directoryID = metadata.directoryID;
  1354. metadataNet.directoryIDTo = directoryIDTo;
  1355. metadataNet.fileName = metadata.fileName;
  1356. metadataNet.fileNameView = metadata.fileNameView;
  1357. metadataNet.fileNameTo = metadata.fileName;
  1358. metadataNet.etag = metadata.etag;
  1359. metadataNet.selector = selectorMove;
  1360. metadataNet.serverUrl = serverUrl;
  1361. metadataNet.serverUrlTo = serverUrlTo;
  1362. [_queueSelector addObject:metadataNet.selector];
  1363. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1364. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1365. }];
  1366. }
  1367. // DELEGATE : Move
  1368. - (void)dismissMove
  1369. {
  1370. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1371. }
  1372. // DELEGATE : Move
  1373. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1374. {
  1375. [_queueSelector removeAllObjects];
  1376. // E2EE DENIED
  1377. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1378. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1379. return;
  1380. }
  1381. if ([_selectedFileIDsMetadatas count] > 0) {
  1382. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1383. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1384. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1385. } else {
  1386. _numSelectedFileIDsMetadatas = 1;
  1387. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[self.metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1388. }
  1389. }
  1390. - (void)moveOpenWindow:(NSArray *)indexPaths
  1391. {
  1392. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1393. return;
  1394. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1395. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1396. viewController.delegate = self;
  1397. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1398. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1399. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1400. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1401. viewController.networkingOperationQueue = appDelegate.netQueue;
  1402. // E2EE
  1403. viewController.includeDirectoryE2EEncryption = NO;
  1404. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1405. [self presentViewController:navigationController animated:YES completion:nil];
  1406. }
  1407. #pragma --------------------------------------------------------------------------------------------
  1408. #pragma mark ===== Create folder =====
  1409. #pragma --------------------------------------------------------------------------------------------
  1410. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1411. {
  1412. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1413. if (![fileNameFolder length]) return;
  1414. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  1415. if (!directoryID) return;
  1416. NSString *fileIDTemp = [[NSUUID UUID] UUIDString];
  1417. // Create Directory (temp) on metadata
  1418. tableMetadata *metadata = [CCUtility createMetadataWithAccount:appDelegate.activeAccount date:[NSDate date] directory:YES fileID:fileIDTemp directoryID:directoryID fileName:fileNameFolder etag:@"" size:0 status:k_metadataStatusNormal];
  1419. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1420. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:serverUrl directoryID:nil];
  1421. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1422. // Creeate folder Networking
  1423. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1424. [ocNetworking createFolder:fileNameFolder serverUrl:serverUrl account:appDelegate.activeAccount success:^(NSString *fileID, NSDate *date) {
  1425. // Delete Temp Dir
  1426. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1427. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrl, fileNameFolder];
  1428. if (_metadataFolder.e2eEncrypted) {
  1429. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  1430. NSError *error = [[NCNetworkingEndToEnd sharedManager] markEndToEndFolderEncryptedOnServerUrl:newDirectory fileID:fileID user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl];
  1431. dispatch_async(dispatch_get_main_queue(), ^{
  1432. if (error) {
  1433. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  1434. }
  1435. [self readFolder:self.serverUrl];
  1436. });
  1437. });
  1438. } else {
  1439. [self readFolder:self.serverUrl];
  1440. }
  1441. } failure:^(NSString *message, NSInteger errorCode) {
  1442. // Unauthorized
  1443. if (errorCode == kOCErrorServerUnauthorized)
  1444. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1445. else
  1446. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1447. // Delete Temp Dir
  1448. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileIDTemp] clearDateReadDirectoryID:nil];
  1449. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  1450. // We are in directory fail ?
  1451. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:fileNameFolder]];
  1452. if (vc)
  1453. [vc.navigationController popViewControllerAnimated:YES];
  1454. }];
  1455. }
  1456. #pragma --------------------------------------------------------------------------------------------
  1457. #pragma mark ===== Progress & Task Button =====
  1458. #pragma --------------------------------------------------------------------------------------------
  1459. - (void)triggerProgressTask:(NSNotification *)notification
  1460. {
  1461. [[NCMainCommon sharedInstance] triggerProgressTask:notification sectionDataSourceFileIDIndexPath:sectionDataSource.fileIDIndexPath tableView:self.tableView];
  1462. }
  1463. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1464. {
  1465. UITouch *touch = [[event allTouches] anyObject];
  1466. CGPoint location = [touch locationInView:self.tableView];
  1467. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1468. if ([self indexPathIsValid:indexPath]) {
  1469. tableMetadata *metadataSection = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1470. if (metadataSection) {
  1471. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataSection.fileID]];
  1472. if (metadata)
  1473. [[NCMainCommon sharedInstance] cancelTransferMetadata:metadata reloadDatasource:true];
  1474. }
  1475. }
  1476. }
  1477. - (void)cancelAllTask:(id)sender
  1478. {
  1479. CGPoint location = [sender locationInView:self.tableView];
  1480. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1481. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  1482. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_all_task_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  1483. [[NCMainCommon sharedInstance] cancelAllTransfer];
  1484. }]];
  1485. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) { }]];
  1486. alertController.popoverPresentationController.sourceView = self.tableView;
  1487. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  1488. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  1489. [alertController.view layoutIfNeeded];
  1490. [self presentViewController:alertController animated:YES completion:nil];
  1491. }
  1492. #pragma --------------------------------------------------------------------------------------------
  1493. #pragma mark ===== Shared =====
  1494. #pragma --------------------------------------------------------------------------------------------
  1495. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1496. {
  1497. [_hud hideHud];
  1498. // Check Active Account
  1499. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1500. return;
  1501. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1502. if (result) {
  1503. appDelegate.sharesLink = result[0];
  1504. appDelegate.sharesUserAndGroup = result[1];
  1505. }
  1506. // Notify Shares View
  1507. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1508. if (openWindow) {
  1509. if (_shareOC) {
  1510. [_shareOC reloadData];
  1511. } else {
  1512. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadataNet.fileID]];
  1513. // Apriamo la view
  1514. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1515. _shareOC.delegate = self;
  1516. _shareOC.metadata = metadata;
  1517. _shareOC.serverUrl = metadataNet.serverUrl;
  1518. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1519. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1520. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1521. [self presentViewController:_shareOC animated:YES completion:nil];
  1522. }
  1523. }
  1524. [self tableViewReloadData];
  1525. }
  1526. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1527. {
  1528. [_hud hideHud];
  1529. // Check Active Account
  1530. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1531. return;
  1532. // Unauthorized
  1533. if (errorCode == kOCErrorServerUnauthorized)
  1534. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1535. else
  1536. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1537. if (_shareOC)
  1538. [_shareOC reloadData];
  1539. [self tableViewReloadData];
  1540. }
  1541. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1542. {
  1543. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1544. metadataNet.action = actionShare;
  1545. metadataNet.fileID = metadata.fileID;
  1546. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1547. metadataNet.fileNameView = metadata.fileNameView;
  1548. metadataNet.password = password;
  1549. metadataNet.selector = selectorShare;
  1550. metadataNet.serverUrl = serverUrl;
  1551. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1552. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1553. }
  1554. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1555. {
  1556. [_hud hideHud];
  1557. // Check Active Account
  1558. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1559. return;
  1560. // rimuoviamo la condivisione da db
  1561. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1562. if (result) {
  1563. appDelegate.sharesLink = result[0];
  1564. appDelegate.sharesUserAndGroup = result[1];
  1565. }
  1566. if (_shareOC)
  1567. [_shareOC reloadData];
  1568. [self tableViewReloadData];
  1569. }
  1570. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1571. {
  1572. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1573. metadataNet.action = actionUnShare;
  1574. metadataNet.fileID = metadata.fileID;
  1575. metadataNet.fileName = metadata.fileName;
  1576. metadataNet.fileNameView = metadata.fileNameView;
  1577. metadataNet.selector = selectorUnshare;
  1578. metadataNet.serverUrl = serverUrl;
  1579. metadataNet.share = share;
  1580. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1581. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1582. }
  1583. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  1584. {
  1585. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1586. metadataNet.action = actionUpdateShare;
  1587. metadataNet.fileID = metadata.fileID;
  1588. metadataNet.expirationTime = expirationTime;
  1589. metadataNet.password = password;
  1590. metadataNet.selector = selectorUpdateShare;
  1591. metadataNet.serverUrl = serverUrl;
  1592. metadataNet.share = share;
  1593. metadataNet.sharePermission = permission;
  1594. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1595. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1596. }
  1597. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  1598. {
  1599. [_hud hideHud];
  1600. // Check Active Account
  1601. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1602. return;
  1603. if (_shareOC)
  1604. [_shareOC reloadUserAndGroup:items];
  1605. }
  1606. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1607. {
  1608. [_hud hideHud];
  1609. // Check Active Account
  1610. if (![metadataNet.account isEqualToString:appDelegate.activeAccount])
  1611. return;
  1612. // Unauthorized
  1613. if (errorCode == kOCErrorServerUnauthorized)
  1614. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1615. else
  1616. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1617. }
  1618. - (void)getUserAndGroup:(NSString *)find
  1619. {
  1620. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1621. metadataNet.action = actionGetUserAndGroup;
  1622. metadataNet.optionAny = find;
  1623. metadataNet.selector = selectorGetUserAndGroup;
  1624. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1625. [_hud visibleIndeterminateHud];
  1626. }
  1627. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  1628. {
  1629. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1630. metadataNet.action = actionShareWith;
  1631. metadataNet.fileID = metadata.fileID;
  1632. metadataNet.directoryID = directoryID;
  1633. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1634. metadataNet.fileNameView = metadata.fileNameView;
  1635. metadataNet.serverUrl = serverUrl;
  1636. metadataNet.selector = selectorShare;
  1637. metadataNet.share = user;
  1638. metadataNet.shareeType = shareeType;
  1639. metadataNet.sharePermission = permission;
  1640. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1641. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1642. }
  1643. - (void)openWindowShare:(tableMetadata *)metadata
  1644. {
  1645. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1646. if (!serverUrl) return;
  1647. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1648. metadataNet.action = actionReadShareServer;
  1649. metadataNet.fileID = metadata.fileID;
  1650. metadataNet.fileName = metadata.fileName;
  1651. metadataNet.fileNameView = metadata.fileNameView;
  1652. metadataNet.selector = selectorOpenWindowShare;
  1653. metadataNet.serverUrl = serverUrl;
  1654. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1655. [_hud visibleIndeterminateHud];
  1656. }
  1657. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  1658. {
  1659. CGPoint location = [tapGesture locationInView:self.tableView];
  1660. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1661. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1662. if (metadata)
  1663. [self openWindowShare:metadata];
  1664. }
  1665. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  1666. {
  1667. CGPoint location = [tapGesture locationInView:self.tableView];
  1668. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1669. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  1670. if (metadata) {
  1671. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  1672. vc.metadata = metadata;
  1673. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  1674. [self presentViewController:vc animated:YES completion:nil];
  1675. }
  1676. }
  1677. #pragma --------------------------------------------------------------------------------------------
  1678. #pragma mark ===== Favorite =====
  1679. #pragma --------------------------------------------------------------------------------------------
  1680. - (void)settingFavorite:(tableMetadata *)metadata favorite:(BOOL)favorite
  1681. {
  1682. NSString *fileNameServerUrl = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:self.serverUrl activeUrl:appDelegate.activeUrl];
  1683. OCnetworking *ocNetworking = [[OCnetworking alloc] initWithDelegate:nil metadataNet:nil withUser:appDelegate.activeUser withUserID:appDelegate.activeUserID withPassword:appDelegate.activePassword withUrl:appDelegate.activeUrl];
  1684. [ocNetworking settingFavorite:fileNameServerUrl favorite:favorite completion:^(NSString *message, NSInteger errorCode) {
  1685. if (errorCode == 0) {
  1686. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadata.fileID favorite:favorite];
  1687. _dateReadDataSource = nil;
  1688. if (_isSearchMode)
  1689. [self readFolder:self.serverUrl];
  1690. else
  1691. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1692. if (metadata.directory && favorite) {
  1693. NSString *dir = [CCUtility stringAppendServerUrl:self.serverUrl addFileName:metadata.fileName];
  1694. [appDelegate.activeFavorites addFavoriteFolder:dir];
  1695. }
  1696. if (!metadata.directory && favorite && [CCUtility getFavoriteOffline]) {
  1697. metadata.favorite = favorite;
  1698. metadata.session = k_download_session;
  1699. metadata.sessionError = @"";
  1700. metadata.sessionSelector = selectorDownloadSynchronize;
  1701. metadata.status = k_metadataStatusWaitDownload;
  1702. // Add Metadata for Download
  1703. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1704. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1705. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1706. }
  1707. } else {
  1708. if (errorCode == kOCErrorServerUnauthorized)
  1709. [appDelegate openLoginView:self loginType:k_login_Modify_Password selector:k_intro_login];
  1710. }
  1711. }];
  1712. }
  1713. #pragma --------------------------------------------------------------------------------------------
  1714. #pragma mark ===== Open in... =====
  1715. #pragma --------------------------------------------------------------------------------------------
  1716. - (void)DownloadOpenIn:(tableMetadata *)metadata
  1717. {
  1718. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1719. if (!serverUrl) return;
  1720. metadata.session = k_download_session;
  1721. metadata.sessionError = @"";
  1722. metadata.sessionSelector = selectorOpenIn;
  1723. metadata.status = k_metadataStatusWaitDownload;
  1724. // Add Metadata for Download
  1725. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1726. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  1727. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  1728. }
  1729. - (void)openIn:(tableMetadata *)metadata
  1730. {
  1731. NSURL *url = [NSURL fileURLWithPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView]];
  1732. UIDocumentInteractionController *docController = [UIDocumentInteractionController interactionControllerWithURL:url];
  1733. docController.delegate = self;
  1734. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  1735. CCCellMain *cell = [self.tableView cellForRowAtIndexPath:indexPath];
  1736. if (cell) {
  1737. [docController presentOptionsMenuFromRect:cell.frame inView:self.tableView animated:YES];
  1738. } else {
  1739. [docController presentOptionsMenuFromRect:self.view.frame inView:self.view animated:YES];
  1740. }
  1741. }
  1742. #pragma --------------------------------------------------------------------------------------------
  1743. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  1744. #pragma --------------------------------------------------------------------------------------------
  1745. - (void)orderTable:(NSString *)order
  1746. {
  1747. [CCUtility setOrderSettings:order];
  1748. // Clear data-read of DataSource
  1749. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1750. }
  1751. - (void)ascendingTable:(BOOL)ascending
  1752. {
  1753. [CCUtility setAscendingSettings:ascending];
  1754. // Clear data-read of DataSource
  1755. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1756. }
  1757. - (void)directoryOnTop:(BOOL)directoryOnTop
  1758. {
  1759. [CCUtility setDirectoryOnTop:directoryOnTop];
  1760. // Clear data-read of DataSource
  1761. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1762. }
  1763. - (void)tableGroupBy:(NSString *)groupBy
  1764. {
  1765. [CCUtility setGroupBySettings:groupBy];
  1766. // Clear data-read of DataSource
  1767. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  1768. }
  1769. #pragma --------------------------------------------------------------------------------------------
  1770. #pragma mark ==== Menu LOGO ====
  1771. #pragma --------------------------------------------------------------------------------------------
  1772. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  1773. {
  1774. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  1775. return;
  1776. // Brand
  1777. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  1778. return;
  1779. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  1780. NSMutableArray *menuArray = [NSMutableArray new];
  1781. for (NSString *account in listAccount) {
  1782. CCMenuItem *item = [[CCMenuItem alloc] init];
  1783. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  1784. item.argument = account;
  1785. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ ", account]];
  1786. NSString *fileNamePath = [NSString stringWithFormat:@"%@/%@-avatar.png", [CCUtility getDirectoryUserData], [CCUtility getStringUser:tableAccount.user activeUrl:tableAccount.url]];
  1787. UIImage *avatar = [UIImage imageWithContentsOfFile:fileNamePath];
  1788. if (avatar) {
  1789. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  1790. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  1791. CGSize imageSize = avatarImageView.bounds.size;
  1792. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  1793. CGContextRef context = UIGraphicsGetCurrentContext();
  1794. [avatarImageView.layer renderInContext:context];
  1795. avatar = UIGraphicsGetImageFromCurrentImageContext();
  1796. UIGraphicsEndImageContext();
  1797. } else {
  1798. avatar = [UIImage imageNamed:@"menuLogoUser"];
  1799. }
  1800. item.image = avatar;
  1801. item.target = self;
  1802. if ([account isEqualToString:appDelegate.activeAccount]) {
  1803. item.action = nil;
  1804. [menuArray insertObject:item atIndex:0];
  1805. } else {
  1806. item.action = @selector(changeDefaultAccount:);
  1807. [menuArray addObject:item];
  1808. }
  1809. }
  1810. // Add + new account
  1811. CCMenuItem *item = [[CCMenuItem alloc] init];
  1812. item.title = NSLocalizedString(@"_add_account_", nil);
  1813. item.argument = @"";
  1814. item.image = [UIImage imageNamed:@"add"];
  1815. item.target = self;
  1816. item.action = @selector(addNewAccount:);
  1817. [menuArray addObject:item];
  1818. OptionalConfiguration options;
  1819. Color textColor, backgroundColor;
  1820. textColor.R = 0;
  1821. textColor.G = 0;
  1822. textColor.B = 0;
  1823. backgroundColor.R = 1;
  1824. backgroundColor.G = 1;
  1825. backgroundColor.B = 1;
  1826. options.arrowSize = 9;
  1827. options.marginXSpacing = 7;
  1828. options.marginYSpacing = 10;
  1829. options.intervalSpacing = 20;
  1830. options.menuCornerRadius = 6.5;
  1831. options.maskToBackground = NO;
  1832. options.shadowOfMenu = YES;
  1833. options.hasSeperatorLine = YES;
  1834. options.seperatorLineHasInsets = YES;
  1835. options.textColor = textColor;
  1836. options.menuBackgroundColor = backgroundColor;
  1837. CGRect rect = self.view.frame;
  1838. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  1839. CGFloat safeAreaTop = 0;
  1840. CGFloat offsetY = 35;
  1841. if (@available(iOS 11, *)) {
  1842. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  1843. }
  1844. rect.origin.y = locationY + safeAreaTop + offsetY;
  1845. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  1846. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  1847. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  1848. }
  1849. - (void)changeDefaultAccount:(CCMenuItem *)sender
  1850. {
  1851. 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];
  1852. if (transferInprogress > 0) {
  1853. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1854. return;
  1855. }
  1856. [appDelegate.netQueue cancelAllOperations];
  1857. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1858. // LOGOUT
  1859. [appDelegate unsubscribingNextcloudServerPushNotification];
  1860. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  1861. if (tableAccount) {
  1862. // LOGIN
  1863. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  1864. // go to home sweet home
  1865. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil userInfo:nil];
  1866. [appDelegate subscribingNextcloudServerPushNotification];
  1867. }
  1868. });
  1869. }
  1870. - (void)addNewAccount:(CCMenuItem *)sender
  1871. {
  1872. 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];
  1873. if (transferInprogress > 0) {
  1874. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  1875. return;
  1876. }
  1877. [appDelegate.netQueue cancelAllOperations];
  1878. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1879. [appDelegate openLoginView:self loginType:k_login_Add selector:k_intro_login];
  1880. });
  1881. }
  1882. #pragma --------------------------------------------------------------------------------------------
  1883. #pragma mark ==== ReMenu ====
  1884. #pragma --------------------------------------------------------------------------------------------
  1885. - (void)createReMenuBackgroundView:(REMenu *)menu
  1886. {
  1887. CGFloat safeAreaBottom = 0;
  1888. CGFloat safeAreaTop = 0;
  1889. CGFloat statusBar = 0;
  1890. if (@available(iOS 11, *)) {
  1891. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  1892. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  1893. }
  1894. if ([UIApplication sharedApplication].isStatusBarHidden) {
  1895. statusBar = 13;
  1896. }
  1897. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  1898. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  1899. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  1900. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  1901. [UIView animateWithDuration:0.2 animations:^{
  1902. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  1903. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  1904. if (y>minimum) {
  1905. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  1906. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  1907. }
  1908. }];
  1909. }
  1910. - (void)createReMainMenu
  1911. {
  1912. NSString *ordinamento;
  1913. NSString *groupBy = _directoryGroupBy;
  1914. __block NSString *nuovoOrdinamento;
  1915. NSString *titoloNuovo, *titoloAttuale;
  1916. BOOL ascendente;
  1917. __block BOOL nuovoAscendente;
  1918. UIImage *image;
  1919. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  1920. 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) {
  1921. if ([sectionDataSource.allRecordsDataSource count] > 0) {
  1922. [self tableViewSelect:YES];
  1923. }
  1924. }];
  1925. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  1926. ordinamento = _directoryOrder;
  1927. if ([ordinamento isEqualToString:@"fileName"]) {
  1928. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  1929. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  1930. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  1931. nuovoOrdinamento = @"date";
  1932. }
  1933. if ([ordinamento isEqualToString:@"date"]) {
  1934. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  1935. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  1936. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  1937. nuovoOrdinamento = @"fileName";
  1938. }
  1939. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  1940. [self orderTable:nuovoOrdinamento];
  1941. }];
  1942. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  1943. ascendente = [CCUtility getAscendingSettings];
  1944. if (ascendente) {
  1945. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  1946. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  1947. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  1948. nuovoAscendente = false;
  1949. }
  1950. if (!ascendente) {
  1951. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] multiplier:2 color:[NCBrandColor sharedInstance].icon];
  1952. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  1953. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  1954. nuovoAscendente = true;
  1955. }
  1956. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  1957. [self ascendingTable:nuovoAscendente];
  1958. }];
  1959. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  1960. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  1961. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  1962. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1963. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  1964. else [self tableGroupBy:@"alphabetic"];
  1965. }];
  1966. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  1967. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  1968. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  1969. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"file"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1970. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  1971. else [self tableGroupBy:@"typefile"];
  1972. }];
  1973. // ITEM DATE -------------------------------------------------------------------------------------------------------
  1974. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  1975. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  1976. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1977. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  1978. else [self tableGroupBy:@"date"];
  1979. }];
  1980. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  1981. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  1982. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  1983. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].icon] highlightedImage:nil action:^(REMenuItem *item) {
  1984. if ([CCUtility getDirectoryOnTop])
  1985. [self directoryOnTop:NO];
  1986. else
  1987. [self directoryOnTop:YES];
  1988. }];
  1989. // REMENU --------------------------------------------------------------------------------------------------------------
  1990. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  1991. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  1992. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  1993. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  1994. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  1995. appDelegate.reMainMenu.separatorHeight = 0.5;
  1996. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  1997. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  1998. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  1999. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2000. appDelegate.reMainMenu.textShadowColor = nil;
  2001. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2002. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2003. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2004. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2005. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2006. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2007. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2008. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2009. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2010. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2011. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2012. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2013. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2014. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2015. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2016. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2017. appDelegate.reMainMenu.borderWidth = 0.3;
  2018. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2019. appDelegate.reMainMenu.animationDuration = 0.2;
  2020. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2021. appDelegate.reMainMenu.bounce = NO;
  2022. __weak typeof(self) weakSelf = self;
  2023. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2024. // Backgroun reMenu (Gesture)
  2025. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2026. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2027. }];
  2028. }
  2029. - (void)toggleReMainMenu
  2030. {
  2031. if (appDelegate.reMainMenu.isOpen) {
  2032. [appDelegate.reMainMenu close];
  2033. } else {
  2034. [self createReMainMenu];
  2035. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2036. // Backgroun reMenu & (Gesture)
  2037. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2038. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2039. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2040. }
  2041. }
  2042. - (void)createReSelectMenu
  2043. {
  2044. // ITEM SELECT ALL --------------------------------------------------------------------------------------------------
  2045. 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) {
  2046. [self didSelectAll];
  2047. }];
  2048. // ITEM MOVE --------------------------------------------------------------------------------------------------------
  2049. 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) {
  2050. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2051. }];
  2052. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2053. 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) {
  2054. [self downloadSelectedFilesFolders];
  2055. }];
  2056. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2057. 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) {
  2058. [self saveSelectedFiles];
  2059. }];
  2060. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2061. 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) {
  2062. [self deleteFile];
  2063. }];
  2064. // E2EE
  2065. if (_metadataFolder.e2eEncrypted) {
  2066. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2067. } else {
  2068. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.selectAllItem, appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem, appDelegate.deleteItem]];
  2069. }
  2070. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2071. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2072. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2073. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2074. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2075. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2076. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2077. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2078. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2079. appDelegate.reSelectMenu.textShadowColor = nil;
  2080. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2081. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2082. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2083. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2084. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2085. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2086. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2087. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2088. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2089. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2090. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2091. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2092. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2093. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2094. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2095. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2096. appDelegate.reSelectMenu.borderWidth = 0.3;
  2097. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2098. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2099. appDelegate.reSelectMenu.animationDuration = 0.2;
  2100. appDelegate.reSelectMenu.bounce = NO;
  2101. __weak typeof(self) weakSelf = self;
  2102. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2103. // Backgroun reMenu (Gesture)
  2104. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2105. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2106. }];
  2107. }
  2108. - (void)toggleReSelectMenu
  2109. {
  2110. if (appDelegate.reSelectMenu.isOpen) {
  2111. [appDelegate.reSelectMenu close];
  2112. } else {
  2113. [self createReSelectMenu];
  2114. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2115. // Backgroun reMenu & (Gesture)
  2116. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2117. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2118. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2119. }
  2120. }
  2121. #pragma --------------------------------------------------------------------------------------------
  2122. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2123. #pragma --------------------------------------------------------------------------------------------
  2124. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2125. {
  2126. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2127. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2128. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2129. if ([self indexPathIsValid:indexPath])
  2130. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2131. else
  2132. self.metadata = nil;
  2133. [self becomeFirstResponder];
  2134. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2135. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2136. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2137. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2138. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2139. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2140. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2141. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2142. [menuController setMenuVisible:YES animated:YES];
  2143. }
  2144. }
  2145. - (BOOL)canBecomeFirstResponder
  2146. {
  2147. return YES;
  2148. }
  2149. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2150. {
  2151. // For copy file, copy files, Open in ... :
  2152. //
  2153. // NO Directory
  2154. // NO Error Passcode
  2155. // NO In Session mode (download/upload)
  2156. // NO Template
  2157. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2158. if (_isSelectedMode == NO && self.metadata && !self.metadata.directory && self.metadata.status == k_metadataStatusNormal) return YES;
  2159. else return NO;
  2160. }
  2161. if (@selector(copyFiles:) == action) {
  2162. if (_isSelectedMode) {
  2163. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2164. for (tableMetadata *metadata in selectedMetadatas) {
  2165. if (!metadata.directory && metadata.status == k_metadataStatusNormal)
  2166. return YES;
  2167. }
  2168. }
  2169. return NO;
  2170. }
  2171. if (@selector(pasteFile:) == action) {
  2172. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2173. NSArray *items = [pasteboard items];
  2174. if ([items count] == 1) {
  2175. // Value : (NSData) fileID
  2176. NSDictionary *dic = [items objectAtIndex:0];
  2177. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2178. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2179. if (fileID) {
  2180. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2181. if (metadata) {
  2182. return [CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView];
  2183. } else {
  2184. return NO;
  2185. }
  2186. }
  2187. }
  2188. return NO;
  2189. }
  2190. if (@selector(pasteFiles:) == action) {
  2191. BOOL isValid = NO;
  2192. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2193. NSArray *items = [pasteboard items];
  2194. if ([items count] <= 1) return NO;
  2195. for (NSDictionary *dic in items) {
  2196. // Value : (NSData) fileID
  2197. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2198. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2199. if (fileID) {
  2200. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2201. if (metadata) {
  2202. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2203. isValid = YES;
  2204. } else {
  2205. isValid = NO;
  2206. break;
  2207. }
  2208. } else {
  2209. isValid = NO;
  2210. break;
  2211. }
  2212. } else {
  2213. isValid = NO;
  2214. break;
  2215. }
  2216. }
  2217. return isValid;
  2218. }
  2219. return NO;
  2220. }
  2221. /************************************ COPY ************************************/
  2222. - (void)copyFile:(id)sender
  2223. {
  2224. // Remove all item
  2225. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2226. pasteboard.items = [[NSArray alloc] init];
  2227. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  2228. [self copyFileToPasteboard:self.metadata];
  2229. } else {
  2230. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2231. if (serverUrl) {
  2232. self.metadata.session = k_download_session;
  2233. self.metadata.sessionError = @"";
  2234. self.metadata.sessionSelector = selectorLoadCopy;
  2235. self.metadata.status = k_metadataStatusWaitDownload;
  2236. // Add Metadata for Download
  2237. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  2238. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2239. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  2240. }
  2241. }
  2242. }
  2243. - (void)copyFiles:(id)sender
  2244. {
  2245. // Remove all item
  2246. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2247. pasteboard.items = [[NSArray alloc] init];
  2248. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2249. for (tableMetadata *metadata in selectedMetadatas) {
  2250. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2251. [self copyFileToPasteboard:metadata];
  2252. } else {
  2253. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2254. if (serverUrl) {
  2255. metadata.session = k_download_session;
  2256. metadata.sessionError = @"";
  2257. metadata.sessionSelector = selectorLoadCopy;
  2258. metadata.status = k_metadataStatusWaitDownload;
  2259. // Add Metadata for Download
  2260. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  2261. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2262. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:metadata.fileID action:k_action_MOD];
  2263. }
  2264. }
  2265. }
  2266. [self tableViewSelect:NO];
  2267. }
  2268. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2269. {
  2270. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2271. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2272. // Value : (NSData) fileID
  2273. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2274. [items addObject:item];
  2275. [pasteboard setItems:items];
  2276. }
  2277. /************************************ OPEN IN ... ******************************/
  2278. - (void)openinFile:(id)sender
  2279. {
  2280. [self DownloadOpenIn:self.metadata];
  2281. }
  2282. /************************************ PASTE ************************************/
  2283. - (void)pasteFile:(id)sender
  2284. {
  2285. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2286. [self uploadFilePasteArray:[pasteboard items]];
  2287. }
  2288. - (void)pasteFiles:(id)sender
  2289. {
  2290. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2291. [self uploadFilePasteArray:[pasteboard items]];
  2292. }
  2293. - (void)uploadFilePasteArray:(NSArray *)items
  2294. {
  2295. for (NSDictionary *dic in items) {
  2296. // Value : (NSData) fileID
  2297. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2298. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2299. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:self.serverUrl];
  2300. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", fileID]];
  2301. if (metadata) {
  2302. if ([CCUtility fileProviderStorageExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  2303. NSString *fileName = [[NCUtility sharedInstance] createFileName:metadata.fileNameView directoryID:directoryID];
  2304. NSString *fileID = [directoryID stringByAppendingString:fileName];
  2305. [CCUtility copyFileAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID fileNameView:metadata.fileNameView] toPath:[CCUtility getDirectoryProviderStorageFileID:fileID fileNameView:fileName]];
  2306. tableMetadata *metadataForUpload = [tableMetadata new];
  2307. metadataForUpload.account = appDelegate.activeAccount;
  2308. metadataForUpload.date = [NSDate new];
  2309. metadataForUpload.directoryID = directoryID;
  2310. metadataForUpload.fileID = fileID;
  2311. metadataForUpload.fileName = fileName;
  2312. metadataForUpload.fileNameView = fileName;
  2313. metadataForUpload.session = k_upload_session;
  2314. metadataForUpload.sessionSelector = selectorUploadFile;
  2315. metadataForUpload.size = metadata.size;
  2316. metadataForUpload.status = k_metadataStatusWaitUpload;
  2317. // Add Medtadata for upload
  2318. (void)[[NCManageDatabase sharedInstance] addMetadata:metadataForUpload];
  2319. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2320. }
  2321. }
  2322. }
  2323. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  2324. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2325. }
  2326. #pragma --------------------------------------------------------------------------------------------
  2327. #pragma mark ===== Lock Passcode =====
  2328. #pragma --------------------------------------------------------------------------------------------
  2329. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2330. {
  2331. return _failedAttempts;
  2332. }
  2333. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2334. {
  2335. return _lockUntilDate;
  2336. }
  2337. - (void)passcodeViewCloseButtonPressed:(id)sender
  2338. {
  2339. [self dismissViewControllerAnimated:YES completion:nil];
  2340. }
  2341. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2342. {
  2343. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2344. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2345. _lockUntilDate = nil;
  2346. _failedAttempts = 0;
  2347. aResultHandler(YES);
  2348. } else aResultHandler(NO);
  2349. } else aResultHandler(YES);
  2350. }
  2351. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2352. {
  2353. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2354. switch (aViewController.type) {
  2355. case BKPasscodeViewControllerCheckPasscodeType: {
  2356. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2357. // possiamo procedere alla prossima directory
  2358. [self performSegueDirectoryWithControlPasscode:false];
  2359. // avviamo la sessione Passcode Lock con now
  2360. appDelegate.sessionePasscodeLock = [NSDate date];
  2361. }
  2362. // disattivazione lock cartella
  2363. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2364. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2365. if (!serverUrl)
  2366. return;
  2367. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2368. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2369. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2370. }
  2371. [self tableViewReloadData];
  2372. }
  2373. }
  2374. break;
  2375. default:
  2376. break;
  2377. }
  2378. }
  2379. - (void)comandoLockPassword
  2380. {
  2381. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2382. if (!serverUrl) return;
  2383. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2384. // se non è abilitato il Lock Passcode esci
  2385. if ([[CCUtility getBlockCode] length] == 0) {
  2386. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2387. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2388. [alertController addAction:okAction];
  2389. [self presentViewController:alertController animated:YES completion:nil];
  2390. return;
  2391. }
  2392. // se è richiesta la disattivazione si chiede la password
  2393. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2394. if (directory.lock) {
  2395. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2396. viewController.delegate = self;
  2397. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2398. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2399. viewController.inputViewTitlePassword = YES;
  2400. if ([CCUtility getSimplyBlockCode]) {
  2401. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2402. viewController.passcodeInputView.maximumLength = 6;
  2403. } else {
  2404. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2405. viewController.passcodeInputView.maximumLength = 64;
  2406. }
  2407. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2408. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2409. viewController.touchIDManager = touchIDManager;
  2410. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2411. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2412. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2413. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2414. [self presentViewController:navigationController animated:YES completion:nil];
  2415. return;
  2416. }
  2417. // ---------------- ACTIVATE PASSWORD
  2418. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2419. NSIndexPath *indexPath = [sectionDataSource.fileIDIndexPath objectForKey:self.metadata.fileID];
  2420. if ([self indexPathIsValid:indexPath])
  2421. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2422. } else {
  2423. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2424. }
  2425. }
  2426. #pragma mark -
  2427. #pragma --------------------------------------------------------------------------------------------
  2428. #pragma mark ===== menu action : Favorite, More, Delete [swipe] =====
  2429. #pragma --------------------------------------------------------------------------------------------
  2430. - (BOOL)canOpenMenuAction:(tableMetadata *)metadata
  2431. {
  2432. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2433. return NO;
  2434. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2435. return NO;
  2436. // E2EE
  2437. if (_metadataFolder.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2438. return NO;
  2439. return YES;
  2440. }
  2441. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2442. {
  2443. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2444. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2445. return [self canOpenMenuAction:metadata];
  2446. }
  2447. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2448. {
  2449. }
  2450. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2451. {
  2452. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2453. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2454. if (direction == MGSwipeDirectionRightToLeft) {
  2455. [self actionDelete:indexPath];
  2456. }
  2457. if (direction == MGSwipeDirectionLeftToRight) {
  2458. if (self.metadata.favorite)
  2459. [self settingFavorite:self.metadata favorite:NO];
  2460. else
  2461. [self settingFavorite:self.metadata favorite:YES];
  2462. }
  2463. return YES;
  2464. }
  2465. - (void)actionDelete:(NSIndexPath *)indexPath
  2466. {
  2467. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2468. // Directory locked ?
  2469. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID] addFileName:metadata.fileName];
  2470. if (!lockServerUrl) return;
  2471. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2472. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2473. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2474. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:k_CCErrorInternalError];
  2475. return;
  2476. }
  2477. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2478. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2479. [self performSelector:@selector(deleteFile) withObject:nil];
  2480. }]];
  2481. if (localFile) {
  2482. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_remove_local_file_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2483. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", metadata.fileID]];
  2484. [[NSFileManager defaultManager] removeItemAtPath:[CCUtility getDirectoryProviderStorageFileID:metadata.fileID] error:nil];
  2485. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2486. }]];
  2487. }
  2488. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2489. }]];
  2490. alertController.popoverPresentationController.sourceView = self.tableView;
  2491. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2492. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2493. [alertController.view layoutIfNeeded];
  2494. [self presentViewController:alertController animated:YES completion:nil];
  2495. }
  2496. - (void)actionMore:(UITapGestureRecognizer *)gestureRecognizer
  2497. {
  2498. CGPoint touch = [gestureRecognizer locationInView:self.tableView];
  2499. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touch];
  2500. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2501. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  2502. if (!serverUrl) return;
  2503. NSString *titoloLock, *titleFavorite;
  2504. if (self.metadata.favorite) {
  2505. titleFavorite = NSLocalizedString(@"_remove_favorites_", nil);
  2506. } else {
  2507. titleFavorite = NSLocalizedString(@"_add_favorites_", nil);
  2508. }
  2509. if (self.metadata.directory) {
  2510. // calcolo lockServerUrl
  2511. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2512. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  2513. if (directory.lock)
  2514. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2515. else
  2516. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2517. }
  2518. // ******************************************* AHKActionSheet *******************************************
  2519. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2520. actionSheet.animationDuration = 0.2;
  2521. actionSheet.buttonHeight = 50.0;
  2522. actionSheet.cancelButtonHeight = 50.0f;
  2523. actionSheet.separatorHeight = 5.0f;
  2524. actionSheet.automaticallyTintButtonImages = @(NO);
  2525. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2526. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2527. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2528. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2529. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2530. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2531. // ******************************************* DIRECTORY *******************************************
  2532. if (self.metadata.directory) {
  2533. BOOL lockDirectory = NO;
  2534. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  2535. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName] account:appDelegate.activeAccount];
  2536. // Directory bloccata ?
  2537. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, dirServerUrl]];
  2538. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2539. [actionSheet addButtonWithTitle:self.metadata.fileNameView
  2540. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] multiplier:2 color:[NCBrandColor sharedInstance].brandElement]
  2541. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2542. height:50.0
  2543. type:AHKActionSheetButtonTypeDisabled
  2544. handler:nil
  2545. ];
  2546. [actionSheet addButtonWithTitle: titleFavorite
  2547. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2548. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2549. height: 50.0
  2550. type: AHKActionSheetButtonTypeDefault
  2551. handler: ^(AHKActionSheet *as) {
  2552. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2553. else [self settingFavorite:self.metadata favorite:YES];
  2554. }];
  2555. if (!lockDirectory && !isFolderEncrypted) {
  2556. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2557. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2558. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2559. height:50.0
  2560. type:AHKActionSheetButtonTypeDefault
  2561. handler:^(AHKActionSheet *as) {
  2562. [self openWindowShare:self.metadata];
  2563. }];
  2564. }
  2565. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !self.metadata.e2eEncrypted) {
  2566. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2567. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2568. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2569. height:50.0
  2570. type:AHKActionSheetButtonTypeDefault
  2571. handler:^(AHKActionSheet *as) {
  2572. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2573. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2574. textField.text = self.metadata.fileNameView;
  2575. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2576. //textField.delegate = self;
  2577. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2578. }];
  2579. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2580. NSLog(@"[LOG] Cancel action");
  2581. }];
  2582. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2583. UITextField *fileName = alertController.textFields.firstObject;
  2584. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2585. }];
  2586. okAction.enabled = NO;
  2587. [alertController addAction:cancelAction];
  2588. [alertController addAction:okAction];
  2589. [self presentViewController:alertController animated:YES completion:nil];
  2590. }];
  2591. }
  2592. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2593. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2594. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2595. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2596. height:50.0
  2597. type:AHKActionSheetButtonTypeDefault
  2598. handler:^(AHKActionSheet *as) {
  2599. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2600. }];
  2601. }
  2602. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2603. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2604. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderMedia"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2605. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2606. height:50.0
  2607. type:AHKActionSheetButtonTypeDefault
  2608. handler:^(AHKActionSheet *as) {
  2609. // Settings new folder Automatatic upload
  2610. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:self.metadata.fileName];
  2611. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2612. // Clear data (old) Auto Upload
  2613. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2614. [self readFolder:serverUrl];
  2615. }];
  2616. }
  2617. if (!([self.metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2618. [actionSheet addButtonWithTitle:titoloLock
  2619. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2620. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2621. height:50.0
  2622. type:AHKActionSheetButtonTypeDefault
  2623. handler:^(AHKActionSheet *as) {
  2624. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  2625. }];
  2626. }
  2627. if (!self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2628. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  2629. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2630. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2631. height:50.0
  2632. type:AHKActionSheetButtonTypeDefault
  2633. handler:^(AHKActionSheet *as) {
  2634. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  2635. 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];
  2636. dispatch_async(dispatch_get_main_queue(), ^{
  2637. if (error) {
  2638. [appDelegate messageNotification:@"_e2e_error_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2639. } else {
  2640. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2641. [self readFolder:self.serverUrl];
  2642. }
  2643. });
  2644. });
  2645. }];
  2646. }
  2647. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  2648. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  2649. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"lock"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2650. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2651. height:50.0
  2652. type:AHKActionSheetButtonTypeDefault
  2653. handler:^(AHKActionSheet *as) {
  2654. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2655. 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];
  2656. dispatch_async(dispatch_get_main_queue(), ^{
  2657. if (error) {
  2658. [appDelegate messageNotification:@"_e2e_error_delete_mark_folder_" description:error.localizedDescription visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:error.code];
  2659. } else {
  2660. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, self.metadata.fileName]]];
  2661. [self readFolder:self.serverUrl];
  2662. }
  2663. });
  2664. });
  2665. }];
  2666. }
  2667. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2668. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2669. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2670. height:50.0
  2671. type:AHKActionSheetButtonTypeDestructive
  2672. handler:^(AHKActionSheet *as) {
  2673. [self actionDelete:indexPath];
  2674. }];
  2675. [actionSheet show];
  2676. }
  2677. // ******************************************* FILE *******************************************
  2678. if (!self.metadata.directory) {
  2679. UIImage *iconHeader;
  2680. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  2681. if ([[NSFileManager defaultManager] fileExistsAtPath:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]])
  2682. iconHeader = [UIImage imageWithContentsOfFile:[CCUtility getDirectoryProviderStorageIconFileID:self.metadata.fileID fileNameView:self.metadata.fileNameView]];
  2683. else
  2684. iconHeader = [UIImage imageNamed:self.metadata.iconName];
  2685. [actionSheet addButtonWithTitle: self.metadata.fileNameView
  2686. image: iconHeader
  2687. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2688. height: 50.0
  2689. type: AHKActionSheetButtonTypeDisabled
  2690. handler: nil
  2691. ];
  2692. [actionSheet addButtonWithTitle: titleFavorite
  2693. image: [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[NCBrandColor sharedInstance].yellowFavorite]
  2694. backgroundColor: [NCBrandColor sharedInstance].backgroundView
  2695. height: 50.0
  2696. type: AHKActionSheetButtonTypeDefault
  2697. handler: ^(AHKActionSheet *as) {
  2698. if (self.metadata.favorite) [self settingFavorite:self.metadata favorite:NO];
  2699. else [self settingFavorite:self.metadata favorite:YES];
  2700. }];
  2701. if (!_metadataFolder.e2eEncrypted) {
  2702. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2703. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"share"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2704. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2705. height: 50.0
  2706. type:AHKActionSheetButtonTypeDefault
  2707. handler:^(AHKActionSheet *as) {
  2708. [self openWindowShare:self.metadata];
  2709. }];
  2710. }
  2711. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  2712. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"openFile"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2713. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2714. height: 50.0
  2715. type:AHKActionSheetButtonTypeDefault
  2716. handler:^(AHKActionSheet *as) {
  2717. [self performSelector:@selector(DownloadOpenIn:) withObject:self.metadata];
  2718. }];
  2719. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2720. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"rename"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2721. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2722. height: 50.0
  2723. type:AHKActionSheetButtonTypeDefault
  2724. handler:^(AHKActionSheet *as) {
  2725. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2726. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2727. textField.text = self.metadata.fileNameView;
  2728. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2729. }];
  2730. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2731. NSLog(@"[LOG] Cancel action");
  2732. }];
  2733. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2734. UITextField *fileName = alertController.textFields.firstObject;
  2735. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:self.metadata,fileName.text, nil] waitUntilDone:NO];
  2736. }];
  2737. okAction.enabled = NO;
  2738. [alertController addAction:cancelAction];
  2739. [alertController addAction:okAction];
  2740. [self presentViewController:alertController animated:YES completion:nil];
  2741. }];
  2742. if (!_metadataFolder.e2eEncrypted) {
  2743. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2744. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"move"] multiplier:2 color:[NCBrandColor sharedInstance].icon]
  2745. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2746. height:50.0
  2747. type:AHKActionSheetButtonTypeDefault
  2748. handler:^(AHKActionSheet *as) {
  2749. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2750. }];
  2751. }
  2752. [actionSheet addButtonWithTitle:NSLocalizedString(@"_delete_", nil)
  2753. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor redColor]]
  2754. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2755. height:50.0
  2756. type:AHKActionSheetButtonTypeDestructive
  2757. handler:^(AHKActionSheet *as) {
  2758. [self actionDelete:indexPath];
  2759. }];
  2760. [actionSheet show];
  2761. }
  2762. }
  2763. #pragma --------------------------------------------------------------------------------------------
  2764. #pragma mark - ==== Datasource ====
  2765. #pragma --------------------------------------------------------------------------------------------
  2766. - (void)clearDateReadDataSource:(NSNotification *)notification
  2767. {
  2768. _dateReadDataSource = Nil;
  2769. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:nil action:k_action_NULL];
  2770. }
  2771. - (void)reloadDatasource:(NSString *)serverUrl fileID:(NSString *)fileID action:(NSInteger)action
  2772. {
  2773. // test
  2774. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil || self.view.window == nil)
  2775. return;
  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. [self tableViewReloadData];
  2788. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  2789. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  2790. _noFilesSearchDescription = @"";
  2791. }
  2792. if ([sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  2793. _noFilesSearchTitle = @"";
  2794. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  2795. }
  2796. [self.tableView reloadEmptyDataSet];
  2797. return;
  2798. }
  2799. // Settaggio variabili per le ottimizzazioni
  2800. _directoryGroupBy = [CCUtility getGroupBySettings];
  2801. _directoryOrder = [CCUtility getOrderSettings];
  2802. // Remove optimization for encrypted directory
  2803. if (_metadataFolder.e2eEncrypted)
  2804. _dateReadDataSource = nil;
  2805. // current directoryID
  2806. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  2807. // Controllo data lettura Data Source
  2808. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, serverUrl]];
  2809. // Get MetadataFolder
  2810. if (![serverUrl isEqualToString:[CCUtility getHomeServerUrlActiveUrl:appDelegate.activeUrl]])
  2811. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID == %@", tableDirectory.fileID]];
  2812. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  2813. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  2814. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  2815. _dateReadDataSource = [NSDate date];
  2816. // Data Source
  2817. NSString *sorted = _directoryOrder;
  2818. if ([sorted isEqualToString:@"fileName"])
  2819. sorted = @"fileName";
  2820. if (directoryID) {
  2821. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  2822. CCSectionDataSourceMetadata *sectionDataSourceTemp = [CCSectionDataSourceMetadata new];
  2823. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"directoryID == %@ AND status != %i", directoryID, k_metadataStatusHide] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  2824. sectionDataSourceTemp = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil groupByField:_directoryGroupBy filterFileID:appDelegate.filterFileID filterTypeFileImage:NO filterTypeFileVideo:NO activeAccount:appDelegate.activeAccount];
  2825. // get auto upload folder
  2826. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  2827. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  2828. dispatch_async(dispatch_get_main_queue(), ^{
  2829. sectionDataSource = sectionDataSourceTemp;
  2830. [self tableViewReloadData];
  2831. });
  2832. });
  2833. }
  2834. } else {
  2835. [self tableViewReloadData];
  2836. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  2837. }
  2838. }
  2839. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  2840. {
  2841. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  2842. if (selectedRows.count > 0) {
  2843. for (NSIndexPath *selectionIndex in selectedRows) {
  2844. NSString *fileID = [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  2845. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  2846. [metadatas addObject:metadata];
  2847. }
  2848. }
  2849. return metadatas;
  2850. }
  2851. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  2852. {
  2853. NSInteger totSections =[sectionDataSource.sections count] ;
  2854. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  2855. return nil;
  2856. }
  2857. id valueSection = [sectionDataSource.sections objectAtIndex:section];
  2858. return [sectionDataSource.sectionArrayRow objectForKey:valueSection];
  2859. }
  2860. #pragma --------------------------------------------------------------------------------------------
  2861. #pragma mark - ==== Table ====
  2862. #pragma --------------------------------------------------------------------------------------------
  2863. - (void)tableViewSelect:(BOOL)edit
  2864. {
  2865. // chiudiamo eventuali swipe aperti
  2866. if (edit)
  2867. [self.tableView setEditing:NO animated:NO];
  2868. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  2869. [self.tableView setEditing:edit animated:YES];
  2870. _isSelectedMode = edit;
  2871. if (edit)
  2872. [self setUINavigationBarSelected];
  2873. else
  2874. [self setUINavigationBarDefault];
  2875. [_selectedFileIDsMetadatas removeAllObjects];
  2876. [self setTitle];
  2877. }
  2878. - (void)tableViewReloadData
  2879. {
  2880. // store selected cells before relod
  2881. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  2882. // reload table view
  2883. [self.tableView reloadData];
  2884. // selected cells stored
  2885. for (NSIndexPath *path in indexPaths)
  2886. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  2887. [self setTableViewFooter];
  2888. if (self.tableView.editing)
  2889. [self setTitle];
  2890. //
  2891. [self.tableView reloadEmptyDataSet];
  2892. }
  2893. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  2894. {
  2895. if (tableView.editing == 1) {
  2896. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  2897. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2898. return NO;
  2899. if (metadata == nil || metadata.status != k_metadataStatusNormal)
  2900. return NO;
  2901. else
  2902. return YES;
  2903. } else {
  2904. [_selectedFileIDsMetadatas removeAllObjects];
  2905. }
  2906. return YES;
  2907. }
  2908. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2909. {
  2910. return 60;
  2911. }
  2912. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  2913. {
  2914. return [[sectionDataSource.sectionArrayRow allKeys] count];
  2915. }
  2916. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  2917. {
  2918. return [[sectionDataSource.sectionArrayRow objectForKey:[sectionDataSource.sections objectAtIndex:section]] count];
  2919. }
  2920. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  2921. {
  2922. NSArray *sections = [sectionDataSource.sectionArrayRow allKeys];
  2923. NSString *sectionTitle = [sections objectAtIndex:section];
  2924. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  2925. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  2926. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  2927. return 20.f;
  2928. }
  2929. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  2930. {
  2931. float shift;
  2932. UIVisualEffectView *visualEffectView;
  2933. NSString *titleSection;
  2934. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  2935. return nil;
  2936. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  2937. titleSection = [sectionDataSource.sections objectAtIndex:section];
  2938. if ([[sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  2939. titleSection = [CCUtility getTitleSectionDate:[sectionDataSource.sections objectAtIndex:section]];
  2940. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  2941. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  2942. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  2943. else titleSection = NSLocalizedString(titleSection,nil);
  2944. // Format title
  2945. NSString *currentDevice = [CCUtility currentDevice];
  2946. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  2947. visualEffectView = [[UIVisualEffectView alloc] init];
  2948. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  2949. } else {
  2950. UIVisualEffect *blurEffect;
  2951. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  2952. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  2953. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  2954. }
  2955. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  2956. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2957. shift = - 35;
  2958. else
  2959. shift = - 20;
  2960. } else shift = - 10;
  2961. // Title
  2962. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  2963. titleLabel.backgroundColor = [UIColor clearColor];
  2964. titleLabel.textColor = [UIColor blackColor];
  2965. titleLabel.font = [UIFont systemFontOfSize:12];
  2966. titleLabel.textAlignment = NSTextAlignmentLeft;
  2967. titleLabel.text = titleSection;
  2968. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2969. [visualEffectView.contentView addSubview:titleLabel];
  2970. // Elements
  2971. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  2972. elementLabel.backgroundColor = [UIColor clearColor];
  2973. elementLabel.textColor = [UIColor blackColor];;
  2974. elementLabel.font = [UIFont systemFontOfSize:12];
  2975. elementLabel.textAlignment = NSTextAlignmentRight;
  2976. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  2977. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  2978. NSUInteger rowsCount = [metadatas count];
  2979. if (rowsCount == 0) return nil;
  2980. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  2981. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  2982. [visualEffectView.contentView addSubview:elementLabel];
  2983. return visualEffectView;
  2984. }
  2985. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  2986. {
  2987. return [sectionDataSource.sections indexOfObject:title];
  2988. }
  2989. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  2990. {
  2991. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  2992. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  2993. else
  2994. return nil;
  2995. }
  2996. /*
  2997. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  2998. {
  2999. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3000. }
  3001. }
  3002. */
  3003. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3004. {
  3005. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3006. if (metadata == nil || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata]) {
  3007. return [CCCellMain new];
  3008. }
  3009. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3010. if (serverUrl == nil) {
  3011. return [CCCellMain new];
  3012. }
  3013. // Download thumbnail
  3014. if (metadata.thumbnailExists && !_metadataFolder.e2eEncrypted && ![CCUtility fileProviderStorageIconExists:metadata.fileID fileNameView:metadata.fileNameView]) {
  3015. [self downloadThumbnail:metadata serverUrl:serverUrl indexPath:indexPath];
  3016. }
  3017. UITableViewCell *cell = [[NCMainCommon sharedInstance] cellForRowAtIndexPath:indexPath tableView:tableView metadata:metadata metadataFolder:_metadataFolder serverUrl:self.serverUrl autoUploadFileName:_autoUploadFileName autoUploadDirectory:_autoUploadDirectory];
  3018. // NORMAL - > MAIN
  3019. if ([cell isKindOfClass:[CCCellMain class]]) {
  3020. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3021. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3022. BOOL isShare = false;
  3023. BOOL isMounted = false;
  3024. if (_metadataFolder) {
  3025. isShare = [metadata.permissions containsString:k_permission_shared] && ![_metadataFolder.permissions containsString:k_permission_shared];
  3026. isMounted = [metadata.permissions containsString:k_permission_mounted] && ![_metadataFolder.permissions containsString:k_permission_mounted];
  3027. }
  3028. // Share add Tap
  3029. if (isShare || isMounted || shareLink != nil || shareUserAndGroup != nil) {
  3030. if (isShare || isMounted) {
  3031. // Shared with you
  3032. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3033. [tap setNumberOfTapsRequired:1];
  3034. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3035. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3036. } else if (shareLink != nil || shareUserAndGroup != nil) {
  3037. // You share
  3038. if (metadata.directory) {
  3039. ((CCCellMain *)cell).shared.userInteractionEnabled = NO;
  3040. } else {
  3041. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3042. [tap setNumberOfTapsRequired:1];
  3043. ((CCCellMain *)cell).shared.userInteractionEnabled = YES;
  3044. [((CCCellMain *)cell).shared addGestureRecognizer:tap];
  3045. }
  3046. }
  3047. }
  3048. // More
  3049. if ([self canOpenMenuAction:metadata]) {
  3050. UITapGestureRecognizer *tapMore = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionMore:)];
  3051. [tapMore setNumberOfTapsRequired:1];
  3052. ((CCCellMain *)cell).more.userInteractionEnabled = YES;
  3053. [((CCCellMain *)cell).more addGestureRecognizer:tapMore];
  3054. }
  3055. // MGSwipeButton
  3056. ((CCCellMain *)cell).delegate = self;
  3057. // LEFT
  3058. ((CCCellMain *)cell).leftButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"favorite"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[NCBrandColor sharedInstance].yellowFavorite padding:25]];
  3059. ((CCCellMain *)cell).leftExpansion.buttonIndex = 0;
  3060. ((CCCellMain *)cell).leftExpansion.fillOnTrigger = NO;
  3061. //centerIconOverText
  3062. MGSwipeButton *favoriteButton = (MGSwipeButton *)[((CCCellMain *)cell).leftButtons objectAtIndex:0];
  3063. [favoriteButton centerIconOverText];
  3064. // RIGHT
  3065. ((CCCellMain *)cell).rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"delete"] multiplier:2 color:[UIColor whiteColor]] backgroundColor:[UIColor redColor] padding:25]];
  3066. ((CCCellMain *)cell).rightExpansion.buttonIndex = 0;
  3067. ((CCCellMain *)cell).rightExpansion.fillOnTrigger = NO;
  3068. //centerIconOverText
  3069. MGSwipeButton *deleteButton = (MGSwipeButton *)[((CCCellMain *)cell).rightButtons objectAtIndex:0];
  3070. [deleteButton centerIconOverText];
  3071. }
  3072. // TRANSFER
  3073. if ([cell isKindOfClass:[CCCellMainTransfer class]]) {
  3074. // gesture Transfer
  3075. [((CCCellMainTransfer *)cell).transferButton.stopButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3076. UILongPressGestureRecognizer *stopLongGesture = [UILongPressGestureRecognizer new];
  3077. [stopLongGesture addTarget:self action:@selector(cancelAllTask:)];
  3078. [((CCCellMainTransfer *)cell).transferButton.stopButton addGestureRecognizer:stopLongGesture];
  3079. }
  3080. return cell;
  3081. }
  3082. - (void)setTableViewFooter
  3083. {
  3084. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3085. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3086. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3087. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3088. UIFont *appFont = [UIFont systemFontOfSize:12];
  3089. footerLabel.font = appFont;
  3090. footerLabel.textColor = [UIColor grayColor];
  3091. footerLabel.backgroundColor = [UIColor clearColor];
  3092. footerLabel.textAlignment = NSTextAlignmentCenter;
  3093. NSString *folders;
  3094. NSString *files;
  3095. NSString *footerText;
  3096. if (sectionDataSource.directories > 1) {
  3097. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3098. } else if (sectionDataSource.directories == 1){
  3099. folders = [NSString stringWithFormat:@"%ld %@", (long)sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3100. } else {
  3101. folders = @"";
  3102. }
  3103. if (sectionDataSource.files > 1) {
  3104. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3105. } else if (sectionDataSource.files == 1){
  3106. files = [NSString stringWithFormat:@"%ld %@ %@", (long)sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:sectionDataSource.totalSize]];
  3107. } else {
  3108. files = @"";
  3109. }
  3110. if ([folders isEqualToString:@""]) {
  3111. footerText = files;
  3112. } else if ([files isEqualToString:@""]) {
  3113. footerText = folders;
  3114. } else {
  3115. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3116. }
  3117. footerLabel.text = footerText;
  3118. [footerView addSubview:footerLabel];
  3119. [self.tableView setTableFooterView:footerView];
  3120. }
  3121. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3122. {
  3123. CCCellMain *cell = [tableView cellForRowAtIndexPath:indexPath];
  3124. // settiamo il record file.
  3125. self.metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3126. if (!self.metadata)
  3127. return;
  3128. // se non può essere selezionata deseleziona
  3129. if ([cell isEditing] == NO)
  3130. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3131. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3132. if (self.tableView.editing) {
  3133. [_selectedFileIDsMetadatas setObject:self.metadata forKey:self.metadata.fileID];
  3134. [self setTitle];
  3135. return;
  3136. }
  3137. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3138. if (!serverUrl) return;
  3139. // se è in corso una sessione
  3140. if (self.metadata.status != k_metadataStatusNormal)
  3141. return;
  3142. // file
  3143. if (self.metadata.directory == NO) {
  3144. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3145. if ([CCUtility fileProviderStorageExists:self.metadata.fileID fileNameView:self.metadata.fileNameView]) {
  3146. [[NCNetworkingMain sharedInstance] downloadFileSuccessFailure:self.metadata.fileName fileID:self.metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView errorMessage:@"" errorCode:0];
  3147. } else {
  3148. if (_metadataFolder.e2eEncrypted && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3149. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3150. } else {
  3151. 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) {
  3152. [self shouldPerformSegue];
  3153. } else {
  3154. self.metadata.session = k_download_session;
  3155. self.metadata.sessionError = @"";
  3156. self.metadata.sessionSelector = selectorLoadFileView;
  3157. self.metadata.status = k_metadataStatusWaitDownload;
  3158. // Add Metadata for Download
  3159. (void)[[NCManageDatabase sharedInstance] addMetadata:self.metadata];
  3160. [appDelegate performSelectorOnMainThread:@selector(loadAutoDownloadUpload) withObject:nil waitUntilDone:YES];
  3161. [[NCMainCommon sharedInstance] reloadDatasourceWithServerUrl:self.serverUrl fileID:self.metadata.fileID action:k_action_MOD];
  3162. }
  3163. }
  3164. }
  3165. }
  3166. if (self.metadata.directory) {
  3167. imageTitleSegue = cell.imageTitleSegue;
  3168. [self performSegueDirectoryWithControlPasscode:true];
  3169. }
  3170. }
  3171. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3172. {
  3173. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3174. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3175. [self setTitle];
  3176. }
  3177. - (void)didSelectAll
  3178. {
  3179. for (int i = 0; i < self.tableView.numberOfSections; i++) {
  3180. for (int j = 0; j < [self.tableView numberOfRowsInSection:i]; j++) {
  3181. NSIndexPath *indexPath = [NSIndexPath indexPathForRow:j inSection:i];
  3182. tableMetadata *metadata = [[NCMainCommon sharedInstance] getMetadataFromSectionDataSourceIndexPath:indexPath sectionDataSource:sectionDataSource];
  3183. [_selectedFileIDsMetadatas setObject:metadata forKey:metadata.fileID];
  3184. [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
  3185. }
  3186. }
  3187. [self setTitle];
  3188. }
  3189. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3190. {
  3191. if (!indexPath)
  3192. return NO;
  3193. NSInteger section = indexPath.section;
  3194. NSInteger row = indexPath.row;
  3195. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3196. if (section > lastSectionIndex || lastSectionIndex < 0)
  3197. return NO;
  3198. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3199. if (rowCount < 0)
  3200. return NO;
  3201. return row <= rowCount;
  3202. }
  3203. #pragma --------------------------------------------------------------------------------------------
  3204. #pragma mark ===== Navigation ====
  3205. #pragma --------------------------------------------------------------------------------------------
  3206. - (void)shouldPerformSegue
  3207. {
  3208. // if background return
  3209. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return;
  3210. if (self.view.window == NO)
  3211. return;
  3212. // Collapsed ma siamo già in detail esci
  3213. if (self.splitViewController.isCollapsed)
  3214. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return;
  3215. [self performSegueWithIdentifier:@"segueDetail" sender:self];
  3216. }
  3217. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3218. {
  3219. id viewController = segue.destinationViewController;
  3220. tableMetadata *metadata;
  3221. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3222. UINavigationController *nav = viewController;
  3223. _detailViewController = (CCDetail *)nav.topViewController;
  3224. } else {
  3225. _detailViewController = segue.destinationViewController;
  3226. }
  3227. NSMutableArray *photoDataSource = [NSMutableArray new];
  3228. if ([sender isKindOfClass:[tableMetadata class]]) {
  3229. metadata = sender;
  3230. [photoDataSource addObject:sender];
  3231. } else {
  3232. metadata = self.metadata;
  3233. for (NSString *fileID in sectionDataSource.allFileID) {
  3234. tableMetadata *metadata = [sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3235. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image])
  3236. [photoDataSource addObject:metadata];
  3237. }
  3238. }
  3239. _detailViewController.metadataDetail = metadata;
  3240. _detailViewController.photoDataSource = photoDataSource;
  3241. _detailViewController.dateFilterQuery = nil;
  3242. [_detailViewController setTitle:metadata.fileNameView];
  3243. }
  3244. // can i go to next viewcontroller
  3245. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3246. {
  3247. NSString *nomeDir;
  3248. if (self.tableView.editing == NO) {
  3249. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:self.metadata.directoryID];
  3250. if (!serverUrl) return;
  3251. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:self.metadata.fileName];
  3252. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account == %@ AND serverUrl == %@", appDelegate.activeAccount, lockServerUrl]];
  3253. // 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
  3254. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3255. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3256. viewController.delegate = self;
  3257. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3258. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3259. viewController.inputViewTitlePassword = YES;
  3260. if ([CCUtility getSimplyBlockCode]) {
  3261. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3262. viewController.passcodeInputView.maximumLength = 6;
  3263. } else {
  3264. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3265. viewController.passcodeInputView.maximumLength = 64;
  3266. }
  3267. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3268. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3269. viewController.touchIDManager = touchIDManager;
  3270. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3271. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3272. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3273. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3274. [self presentViewController:navController animated:YES completion:nil];
  3275. return;
  3276. }
  3277. // E2EE Check enable
  3278. if (self.metadata.e2eEncrypted && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO) {
  3279. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3280. return;
  3281. }
  3282. nomeDir = self.metadata.fileName;
  3283. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3284. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3285. if (!viewController) {
  3286. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3287. viewController.serverUrl = serverUrlPush;
  3288. viewController.titleMain = self.metadata.fileName;
  3289. viewController.imageTitle = imageTitleSegue;
  3290. // save self
  3291. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3292. [self.navigationController pushViewController:viewController animated:YES];
  3293. } else {
  3294. if (viewController.isViewLoaded) {
  3295. viewController.titleMain = self.metadata.fileName;
  3296. viewController.imageTitle = imageTitleSegue;
  3297. // Fix : Application tried to present modally an active controller
  3298. if ([self.navigationController isBeingPresented]) {
  3299. // being presented
  3300. } else if ([self.navigationController isMovingToParentViewController]) {
  3301. // being pushed
  3302. } else {
  3303. [self.navigationController pushViewController:viewController animated:YES];
  3304. }
  3305. }
  3306. }
  3307. }
  3308. }
  3309. @end