CCMain.m 211 KB

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