CCMain.m 226 KB

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