CCMain.m 209 KB

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