CCMain.m 228 KB

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