CCMain.m 229 KB

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