CCMain.m 208 KB

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