CCMain.m 239 KB

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