CCMain.m 240 KB

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