CCMain.m 211 KB

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