CCMain.m 206 KB

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