CCMain.m 211 KB

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