CCMain.m 206 KB

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