CCMain.m 202 KB

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