CCMain.m 205 KB

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