CCMain.m 207 KB

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