CCMain.m 225 KB

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