CCMain.m 206 KB

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