CCMain.m 207 KB

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