CCMain.m 212 KB

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