CCMain.m 238 KB

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