CCMain.m 238 KB

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