CCMain.m 240 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385
  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. // E2E LOCK
  1497. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  1498. if (tableE2eEncryption) {
  1499. }
  1500. [[CCActions sharedInstance] deleteFileOrFolder:metadata delegate:self];
  1501. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_delete_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1502. }
  1503. - (void)deleteFile
  1504. {
  1505. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1506. return;
  1507. [_queueSelector removeAllObjects];
  1508. if ([_selectedFileIDsMetadatas count] > 0) {
  1509. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1510. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1511. [self deleteFileOrFolder:[metadatas objectAtIndex:0] numFile:[_selectedFileIDsMetadatas count] ofFile:_numSelectedFileIDsMetadatas];
  1512. } else {
  1513. _numSelectedFileIDsMetadatas = 1;
  1514. [self deleteFileOrFolder:_metadata numFile:1 ofFile:_numSelectedFileIDsMetadatas];
  1515. }
  1516. }
  1517. #pragma --------------------------------------------------------------------------------------------
  1518. #pragma mark ===== Rename / Move =====
  1519. #pragma --------------------------------------------------------------------------------------------
  1520. - (void)renameSuccess:(CCMetadataNet *)metadataNet
  1521. {
  1522. [self readFolder:metadataNet.serverUrl];
  1523. }
  1524. - (void)renameFile:(NSArray *)arguments
  1525. {
  1526. tableMetadata* metadata = [arguments objectAtIndex:0];
  1527. NSString *fileName = [arguments objectAtIndex:1];
  1528. // E2E
  1529. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount]) {
  1530. // verify if exists the new fileName
  1531. if ([[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@ AND fileName = %@", appDelegate.activeAccount, self.serverUrl, fileName]]) {
  1532. [appDelegate messageNotification:@"_error_" description:@"_file_already_exists_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1533. return;
  1534. }
  1535. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1536. NSString *token;
  1537. 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];
  1538. if (error) {
  1539. dispatch_async(dispatch_get_main_queue(), ^{
  1540. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"Error to send metadata %d", (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1541. });
  1542. } else {
  1543. [[NCManageDatabase sharedInstance] setMetadataFileNameViewWithDirectoryID:metadata.directoryID fileName:metadata.fileName newFileNameView:fileName];
  1544. }
  1545. // Unlock
  1546. if (token) {
  1547. NSError *error = [[NCNetworkingSync sharedManager] unlockEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadataFolder.fileID token:token];
  1548. if (error) {
  1549. dispatch_async(dispatch_get_main_queue(), ^{
  1550. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  1551. });
  1552. }
  1553. }
  1554. dispatch_async(dispatch_get_main_queue(), ^{
  1555. [self reloadDatasource];
  1556. });
  1557. });
  1558. } else {
  1559. // Plain
  1560. [[CCActions sharedInstance] renameFileOrFolder:metadata fileName:fileName delegate:self];
  1561. }
  1562. }
  1563. - (void)renameMoveFileOrFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1564. {
  1565. if ([metadataNet.selector isEqualToString:selectorMove]) {
  1566. [_hud hideHud];
  1567. if (message && errorCode != kOCErrorServerUnauthorized)
  1568. [appDelegate messageNotification:@"_move_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1569. // End Select Table View
  1570. [self tableViewSelect:NO];
  1571. // reload Datasource
  1572. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1573. [self readFolder:metadataNet.serverUrl];
  1574. else
  1575. [self reloadDatasource];
  1576. }
  1577. }
  1578. - (void)moveSuccess:(CCMetadataNet *)metadataNet
  1579. {
  1580. [_queueSelector removeObject:metadataNet.selector];
  1581. if ([_queueSelector count] == 0) {
  1582. [_hud hideHud];
  1583. NSString *fileName = metadataNet.fileName;
  1584. NSString *directoryID = metadataNet.directoryID;
  1585. NSString *directoryIDTo = metadataNet.directoryIDTo;
  1586. NSString *serverUrlTo = [[NCManageDatabase sharedInstance] getServerUrl:directoryIDTo];
  1587. if (!serverUrlTo) return;
  1588. // FILE -> Metadata
  1589. if (metadataNet.directory == NO)
  1590. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1591. // DIRECTORY -> Directory - CCMetadata
  1592. if (metadataNet.directory == YES) {
  1593. // delete all dir / subdir
  1594. [[NCManageDatabase sharedInstance] deleteDirectoryAndSubDirectoryWithServerUrl:[CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:fileName]];
  1595. // move metadata
  1596. [[NCManageDatabase sharedInstance] moveMetadataWithFileName:fileName directoryID:directoryID directoryIDTo:directoryIDTo];
  1597. // Add new directory
  1598. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", serverUrlTo, fileName];
  1599. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1600. }
  1601. // next
  1602. [_selectedFileIDsMetadatas removeObjectForKey:metadataNet.fileID];
  1603. if ([_selectedFileIDsMetadatas count] > 0) {
  1604. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1605. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1606. } else {
  1607. // End Select Table View
  1608. [self tableViewSelect:NO];
  1609. // reload Datasource
  1610. if ([metadataNet.selectorPost isEqualToString:selectorReadFolderForced] || _isSearchMode)
  1611. [self readFolder:metadataNet.serverUrl];
  1612. else
  1613. [self reloadDatasource];
  1614. }
  1615. }
  1616. }
  1617. - (void)moveFileOrFolderMetadata:(NSArray *)arguments
  1618. {
  1619. tableMetadata *metadata = [arguments objectAtIndex:0];
  1620. NSString *serverUrlTo = [arguments objectAtIndex:1];
  1621. NSInteger numFile = [[arguments objectAtIndex:2] integerValue];
  1622. NSInteger ofFile = [[arguments objectAtIndex:3] integerValue];
  1623. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  1624. if (!serverUrl) return;
  1625. NSString *directoryIDTo = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrlTo];
  1626. if (!directoryIDTo) return;
  1627. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  1628. NSArray *items;
  1629. NSError *error = [[NCNetworkingSync sharedManager] readFile:[NSString stringWithFormat:@"%@/%@", serverUrlTo, metadata.fileName] user:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword items:&items];
  1630. if(!error) {
  1631. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  1632. UIAlertController * alert= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_error_", nil) message:NSLocalizedString(@"_file_already_exists_", nil) preferredStyle:UIAlertControllerStyleAlert];
  1633. UIAlertAction* ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
  1634. }];
  1635. [alert addAction:ok];
  1636. [self presentViewController:alert animated:YES completion:nil];
  1637. // End Select Table View
  1638. [self tableViewSelect:NO];
  1639. // reload Datasource
  1640. [self readFileReloadFolder];
  1641. });
  1642. return;
  1643. }
  1644. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1645. metadataNet.action = actionMoveFileOrFolder;
  1646. metadataNet.directory = metadata.directory;
  1647. metadataNet.fileID = metadata.fileID;
  1648. metadataNet.directoryID = metadata.directoryID;
  1649. metadataNet.directoryIDTo = directoryIDTo;
  1650. metadataNet.fileName = metadata.fileName;
  1651. metadataNet.fileNameView = metadata.fileNameView;
  1652. metadataNet.fileNameTo = metadata.fileName;
  1653. metadataNet.etag = metadata.etag;
  1654. metadataNet.selector = selectorMove;
  1655. metadataNet.serverUrl = serverUrl;
  1656. metadataNet.serverUrlTo = serverUrlTo;
  1657. [_queueSelector addObject:metadataNet.selector];
  1658. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1659. dispatch_async(dispatch_get_main_queue(), ^{
  1660. [_hud visibleHudTitle:[NSString stringWithFormat:NSLocalizedString(@"_move_file_n_", nil), ofFile - numFile + 1, ofFile] mode:MBProgressHUDModeIndeterminate color:nil];
  1661. });
  1662. });
  1663. }
  1664. // DELEGATE : Move
  1665. - (void)dismissMove
  1666. {
  1667. [self reloadDatasource];
  1668. }
  1669. // DELEGATE : Move
  1670. - (void)moveServerUrlTo:(NSString *)serverUrlTo title:(NSString *)title
  1671. {
  1672. [_queueSelector removeAllObjects];
  1673. // E2E DENIED
  1674. if ([CCUtility isFolderEncrypted:serverUrlTo account:appDelegate.activeAccount]) {
  1675. [appDelegate messageNotification:@"_move_" description:@"Not possible move files to encrypted directory" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  1676. return;
  1677. }
  1678. if ([_selectedFileIDsMetadatas count] > 0) {
  1679. _numSelectedFileIDsMetadatas = [_selectedFileIDsMetadatas count];
  1680. NSArray *metadatas = [_selectedFileIDsMetadatas allValues];
  1681. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[[metadatas objectAtIndex:0], serverUrlTo, [NSNumber numberWithInteger:[_selectedFileIDsMetadatas count]], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1682. } else {
  1683. _numSelectedFileIDsMetadatas = 1;
  1684. [self performSelectorOnMainThread:@selector(moveFileOrFolderMetadata:) withObject:@[_metadata, serverUrlTo, [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:_numSelectedFileIDsMetadatas]] waitUntilDone:NO];
  1685. }
  1686. }
  1687. - (void)moveOpenWindow:(NSArray *)indexPaths
  1688. {
  1689. if (_isSelectedMode && [_selectedFileIDsMetadatas count] == 0)
  1690. return;
  1691. UINavigationController* navigationController = [[UIStoryboard storyboardWithName:@"CCMove" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMove"];
  1692. CCMove *viewController = (CCMove *)navigationController.topViewController;
  1693. viewController.delegate = self;
  1694. viewController.move.title = NSLocalizedString(@"_move_", nil);
  1695. viewController.tintColor = [NCBrandColor sharedInstance].brandText;
  1696. viewController.barTintColor = [NCBrandColor sharedInstance].brand;
  1697. viewController.tintColorTitle = [NCBrandColor sharedInstance].brandText;
  1698. viewController.networkingOperationQueue = appDelegate.netQueue;
  1699. // E2E
  1700. viewController.includeDirectoryE2EEncryption = NO;
  1701. [navigationController setModalPresentationStyle:UIModalPresentationFormSheet];
  1702. [self presentViewController:navigationController animated:YES completion:nil];
  1703. }
  1704. #pragma --------------------------------------------------------------------------------------------
  1705. #pragma mark ===== Create folder =====
  1706. #pragma --------------------------------------------------------------------------------------------
  1707. - (void)createFolderFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1708. {
  1709. // Unauthorized
  1710. if (errorCode == kOCErrorServerUnauthorized)
  1711. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1712. if (message && errorCode != kOCErrorServerUnauthorized)
  1713. [appDelegate messageNotification:@"_create_folder_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1714. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID] clearDateReadDirectoryID:nil];
  1715. [self reloadDatasource];
  1716. // We are in directory fail ?
  1717. CCMain *vc = [appDelegate.listMainVC objectForKey:[CCUtility stringAppendServerUrl:_serverUrl addFileName:metadataNet.fileName]];
  1718. if (vc)
  1719. [vc.navigationController popViewControllerAnimated:YES];
  1720. }
  1721. - (void)createFolderSuccess:(CCMetadataNet *)metadataNet
  1722. {
  1723. NSString *newDirectory = [NSString stringWithFormat:@"%@/%@", metadataNet.serverUrl, metadataNet.fileName];
  1724. (void)[[NCManageDatabase sharedInstance] addDirectoryWithServerUrl:newDirectory permissions:nil encrypted:false];
  1725. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID]];
  1726. if (metadata) {
  1727. [[NCManageDatabase sharedInstance] deleteMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileName = %@ AND directoryID = %@", metadataNet.fileName, metadataNet.directoryID] clearDateReadDirectoryID:nil];
  1728. metadata.fileID = metadataNet.fileID;
  1729. metadata.date = metadataNet.date;
  1730. metadata.permissions = @"RDNVCK";
  1731. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1732. [self reloadDatasource];
  1733. } else {
  1734. [self readFileReloadFolder];
  1735. }
  1736. }
  1737. - (void)createFolder:(NSString *)fileNameFolder serverUrl:(NSString *)serverUrl
  1738. {
  1739. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1740. fileNameFolder = [CCUtility removeForbiddenCharactersServer:fileNameFolder];
  1741. if (![fileNameFolder length]) return;
  1742. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:_serverUrl];
  1743. if (!directoryID) return;
  1744. metadataNet.action = actionCreateFolder;
  1745. metadataNet.directoryID = directoryID;
  1746. metadataNet.fileID = [[NSUUID UUID] UUIDString];
  1747. metadataNet.fileName = fileNameFolder;
  1748. metadataNet.selector = selectorCreateFolder;
  1749. metadataNet.serverUrl = serverUrl;
  1750. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1751. // Create Directory on metadata
  1752. 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];
  1753. (void)[[NCManageDatabase sharedInstance] addMetadata:metadata];
  1754. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_serverUrl directoryID:nil];
  1755. [self reloadDatasource];
  1756. }
  1757. #pragma --------------------------------------------------------------------------------------------
  1758. #pragma mark ===== Progress & Task Button =====
  1759. #pragma --------------------------------------------------------------------------------------------
  1760. - (void)triggerProgressTask:(NSNotification *)notification
  1761. {
  1762. NSDictionary *dict = notification.userInfo;
  1763. NSString *fileID = [dict valueForKey:@"fileID"];
  1764. NSString *serverUrl = [dict valueForKey:@"serverUrl"];
  1765. float progress = [[dict valueForKey:@"progress"] floatValue];
  1766. // Check
  1767. if (!fileID || [fileID isEqualToString: @""])
  1768. return;
  1769. [appDelegate.listProgressMetadata setObject:[NSNumber numberWithFloat:progress] forKey:fileID];
  1770. if (![serverUrl isEqualToString:_serverUrl])
  1771. return;
  1772. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:fileID];
  1773. if ([self indexPathIsValid:indexPath]) {
  1774. CCTransfersCell *cell = (CCTransfersCell *)[self.tableView cellForRowAtIndexPath:indexPath];
  1775. cell.progressView.progressTintColor = [UIColor blackColor];
  1776. cell.progressView.hidden = NO;
  1777. [cell.progressView setProgress:progress];
  1778. }
  1779. }
  1780. - (void)reloadTaskButton:(id)sender withEvent:(UIEvent *)event
  1781. {
  1782. UITouch * touch = [[event allTouches] anyObject];
  1783. CGPoint location = [touch locationInView:self.tableView];
  1784. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1785. if ([self indexPathIsValid:indexPath]) {
  1786. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1787. if (metadataSection) {
  1788. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1789. if (metadata)
  1790. [self reloadTaskButton:metadata];
  1791. }
  1792. }
  1793. }
  1794. - (void)reloadTaskButton:(tableMetadata *)metadata
  1795. {
  1796. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1797. __block NSURLSessionTask *findTask;
  1798. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1799. NSString *fileID = metadata.fileID;
  1800. // DOWNLOAD
  1801. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1802. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1803. for (NSURLSessionUploadTask *task in downloadTasks)
  1804. if (task.taskIdentifier == sessionTaskIdentifier) {
  1805. findTask = task;
  1806. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1807. [task cancel];
  1808. }
  1809. if (!findTask) {
  1810. [appDelegate.listChangeTask setObject:@"reloadDownload" forKey:fileID];
  1811. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1812. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1813. }
  1814. }];
  1815. }
  1816. // UPLOAD
  1817. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1818. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1819. for (NSURLSessionUploadTask *task in uploadTasks)
  1820. if (task.taskIdentifier == sessionTaskIdentifier) {
  1821. findTask = task;
  1822. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1823. [task cancel];
  1824. }
  1825. if (!findTask) {
  1826. [appDelegate.listChangeTask setObject:@"reloadUpload" forKey:fileID];
  1827. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1828. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1829. }
  1830. }];
  1831. }
  1832. }
  1833. - (void)cancelTaskButton:(id)sender withEvent:(UIEvent *)event
  1834. {
  1835. UITouch * touch = [[event allTouches] anyObject];
  1836. CGPoint location = [touch locationInView:self.tableView];
  1837. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1838. if ([self indexPathIsValid:indexPath]) {
  1839. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1840. if (metadataSection) {
  1841. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1842. if (metadata)
  1843. [self cancelTaskButton:metadata reloadTable:YES];
  1844. }
  1845. }
  1846. }
  1847. - (void)cancelTaskButton:(tableMetadata *)metadata reloadTable:(BOOL)reloadTable
  1848. {
  1849. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1850. __block NSURLSessionTask *findTask;
  1851. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1852. NSString *fileID = metadata.fileID;
  1853. // DOWNLOAD
  1854. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  1855. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1856. for (NSURLSessionTask *task in downloadTasks)
  1857. if (task.taskIdentifier == sessionTaskIdentifier) {
  1858. findTask = task;
  1859. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1860. [task cancel];
  1861. }
  1862. if (!findTask) {
  1863. [appDelegate.listChangeTask setObject:@"cancelDownload" forKey:fileID];
  1864. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1865. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1866. }
  1867. }];
  1868. }
  1869. // UPLOAD
  1870. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1871. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1872. for (NSURLSessionUploadTask *task in uploadTasks)
  1873. if (task.taskIdentifier == sessionTaskIdentifier) {
  1874. findTask = task;
  1875. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1876. [task cancel];
  1877. }
  1878. if (!findTask) {
  1879. [appDelegate.listChangeTask setObject:@"cancelUpload" forKey:fileID];
  1880. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1881. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1882. }
  1883. }];
  1884. }
  1885. }
  1886. - (void)stopTaskButton:(id)sender withEvent:(UIEvent *)event
  1887. {
  1888. UITouch * touch = [[event allTouches] anyObject];
  1889. CGPoint location = [touch locationInView:self.tableView];
  1890. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  1891. if ([self indexPathIsValid:indexPath]) {
  1892. tableMetadata *metadataSection = [self getMetadataFromSectionDataSource:indexPath];
  1893. if (metadataSection) {
  1894. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataSection.fileID]];
  1895. if (metadata)
  1896. [self stopTaskButton:metadata];
  1897. }
  1898. }
  1899. }
  1900. - (void)stopTaskButton:(tableMetadata *)metadata
  1901. {
  1902. NSURLSession *session = [[CCNetworking sharedNetworking] getSessionfromSessionDescription:metadata.session];
  1903. __block NSURLSessionTask *findTask;
  1904. NSInteger sessionTaskIdentifier = metadata.sessionTaskIdentifier;
  1905. NSString *fileID = metadata.fileID;
  1906. // UPLOAD
  1907. if ([metadata.session length] > 0 && [metadata.session containsString:@"upload"]) {
  1908. [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
  1909. for (NSURLSessionUploadTask *task in uploadTasks)
  1910. if (task.taskIdentifier == sessionTaskIdentifier) {
  1911. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1912. findTask = task;
  1913. [task cancel];
  1914. }
  1915. if (!findTask) {
  1916. [appDelegate.listChangeTask setObject:@"stopUpload" forKey:fileID];
  1917. NSArray *object = [[NSArray alloc] initWithObjects:session, fileID, findTask, nil];
  1918. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:k_networkingSessionNotification object:object];
  1919. }
  1920. }];
  1921. }
  1922. }
  1923. #pragma --------------------------------------------------------------------------------------------
  1924. #pragma mark ===== Shared =====
  1925. #pragma --------------------------------------------------------------------------------------------
  1926. - (void)readSharedSuccess:(CCMetadataNet *)metadataNet items:(NSDictionary *)items openWindow:(BOOL)openWindow
  1927. {
  1928. [_hud hideHud];
  1929. // change account ?
  1930. tableAccount *record = [[NCManageDatabase sharedInstance] getAccountActive];
  1931. if([record.account isEqualToString:metadataNet.account] == NO)
  1932. return;
  1933. NSArray *result = [[NCManageDatabase sharedInstance] updateShare:items activeUrl:appDelegate.activeUrl];
  1934. if (result) {
  1935. appDelegate.sharesLink = result[0];
  1936. appDelegate.sharesUserAndGroup = result[1];
  1937. }
  1938. // Notify Shares View
  1939. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"SharesReloadDatasource" object:nil userInfo:nil];
  1940. if (openWindow) {
  1941. if (_shareOC) {
  1942. [_shareOC reloadData];
  1943. } else {
  1944. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  1945. // Apriamo la view
  1946. _shareOC = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareOC"];
  1947. _shareOC.delegate = self;
  1948. _shareOC.metadata = metadata;
  1949. _shareOC.serverUrl = metadataNet.serverUrl;
  1950. _shareOC.shareLink = [appDelegate.sharesLink objectForKey:metadata.fileID];
  1951. _shareOC.shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:metadata.fileID];
  1952. [_shareOC setModalPresentationStyle:UIModalPresentationFormSheet];
  1953. [self presentViewController:_shareOC animated:YES completion:nil];
  1954. }
  1955. }
  1956. [self tableViewReloadData];
  1957. }
  1958. - (void)shareFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  1959. {
  1960. [_hud hideHud];
  1961. // Unauthorized
  1962. if (errorCode == kOCErrorServerUnauthorized)
  1963. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  1964. if (errorCode != kOCErrorServerUnauthorized)
  1965. [appDelegate messageNotification:@"_share_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  1966. if (_shareOC)
  1967. [_shareOC reloadData];
  1968. [self tableViewReloadData];
  1969. }
  1970. - (void)share:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password
  1971. {
  1972. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1973. metadataNet.action = actionShare;
  1974. metadataNet.fileID = metadata.fileID;
  1975. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  1976. metadataNet.fileNameView = metadata.fileNameView;
  1977. metadataNet.password = password;
  1978. metadataNet.selector = selectorShare;
  1979. metadataNet.serverUrl = serverUrl;
  1980. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  1981. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  1982. }
  1983. - (void)unShareSuccess:(CCMetadataNet *)metadataNet
  1984. {
  1985. [_hud hideHud];
  1986. // rimuoviamo la condivisione da db
  1987. NSArray *result = [[NCManageDatabase sharedInstance] unShare:metadataNet.share fileName:metadataNet.fileName serverUrl:metadataNet.serverUrl sharesLink:appDelegate.sharesLink sharesUserAndGroup:appDelegate.sharesUserAndGroup];
  1988. if (result) {
  1989. appDelegate.sharesLink = result[0];
  1990. appDelegate.sharesUserAndGroup = result[1];
  1991. }
  1992. if (_shareOC)
  1993. [_shareOC reloadData];
  1994. [self tableViewReloadData];
  1995. }
  1996. - (void)unShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl
  1997. {
  1998. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  1999. metadataNet.action = actionUnShare;
  2000. metadataNet.fileID = metadata.fileID;
  2001. metadataNet.fileName = metadata.fileName;
  2002. metadataNet.fileNameView = metadata.fileNameView;
  2003. metadataNet.selector = selectorUnshare;
  2004. metadataNet.serverUrl = serverUrl;
  2005. metadataNet.share = share;
  2006. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2007. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2008. }
  2009. - (void)updateShare:(NSString *)share metadata:(tableMetadata *)metadata serverUrl:(NSString *)serverUrl password:(NSString *)password expirationTime:(NSString *)expirationTime permission:(NSInteger)permission
  2010. {
  2011. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2012. metadataNet.action = actionUpdateShare;
  2013. metadataNet.fileID = metadata.fileID;
  2014. metadataNet.expirationTime = expirationTime;
  2015. metadataNet.password = password;
  2016. metadataNet.selector = selectorUpdateShare;
  2017. metadataNet.serverUrl = serverUrl;
  2018. metadataNet.share = share;
  2019. metadataNet.sharePermission = permission;
  2020. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2021. [_hud visibleHudTitle:NSLocalizedString(@"_updating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2022. }
  2023. - (void)getUserAndGroupSuccess:(CCMetadataNet *)metadataNet items:(NSArray *)items
  2024. {
  2025. [_hud hideHud];
  2026. if (_shareOC)
  2027. [_shareOC reloadUserAndGroup:items];
  2028. }
  2029. - (void)getUserAndGroupFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2030. {
  2031. [_hud hideHud];
  2032. // Unauthorized
  2033. if (errorCode == kOCErrorServerUnauthorized)
  2034. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2035. if (errorCode != kOCErrorServerUnauthorized)
  2036. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2037. }
  2038. - (void)getUserAndGroup:(NSString *)find
  2039. {
  2040. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2041. metadataNet.action = actionGetUserAndGroup;
  2042. metadataNet.options = find;
  2043. metadataNet.selector = selectorGetUserAndGroup;
  2044. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2045. [_hud visibleIndeterminateHud];
  2046. }
  2047. - (void)shareUserAndGroup:(NSString *)user shareeType:(NSInteger)shareeType permission:(NSInteger)permission metadata:(tableMetadata *)metadata directoryID:(NSString *)directoryID serverUrl:(NSString *)serverUrl
  2048. {
  2049. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2050. metadataNet.action = actionShareWith;
  2051. metadataNet.fileID = metadata.fileID;
  2052. metadataNet.directoryID = directoryID;
  2053. metadataNet.fileName = [CCUtility returnFileNamePathFromFileName:metadata.fileName serverUrl:serverUrl activeUrl:appDelegate.activeUrl];
  2054. metadataNet.fileNameView = metadata.fileNameView;
  2055. metadataNet.serverUrl = serverUrl;
  2056. metadataNet.selector = selectorShare;
  2057. metadataNet.share = user;
  2058. metadataNet.shareeType = shareeType;
  2059. metadataNet.sharePermission = permission;
  2060. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2061. [_hud visibleHudTitle:NSLocalizedString(@"_creating_sharing_", nil) mode:MBProgressHUDModeIndeterminate color:nil];
  2062. }
  2063. - (void)openWindowShare:(tableMetadata *)metadata
  2064. {
  2065. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2066. if (!serverUrl) return;
  2067. CCMetadataNet *metadataNet = [[CCMetadataNet alloc] initWithAccount:appDelegate.activeAccount];
  2068. metadataNet.action = actionReadShareServer;
  2069. metadataNet.fileID = metadata.fileID;
  2070. metadataNet.fileName = metadata.fileName;
  2071. metadataNet.fileNameView = metadata.fileNameView;
  2072. metadataNet.selector = selectorOpenWindowShare;
  2073. metadataNet.serverUrl = serverUrl;
  2074. [appDelegate addNetworkingOperationQueue:appDelegate.netQueue delegate:self metadataNet:metadataNet];
  2075. [_hud visibleIndeterminateHud];
  2076. }
  2077. - (void)tapActionShared:(UITapGestureRecognizer *)tapGesture
  2078. {
  2079. CGPoint location = [tapGesture locationInView:self.tableView];
  2080. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2081. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2082. if (metadata)
  2083. [self openWindowShare:metadata];
  2084. }
  2085. - (void)tapActionConnectionMounted:(UITapGestureRecognizer *)tapGesture
  2086. {
  2087. CGPoint location = [tapGesture locationInView:self.tableView];
  2088. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:location];
  2089. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2090. if (metadata) {
  2091. CCShareInfoCMOC *vc = [[UIStoryboard storyboardWithName:@"CCShare" bundle:nil] instantiateViewControllerWithIdentifier:@"CCShareInfoCMOC"];
  2092. vc.metadata = metadata;
  2093. [vc setModalPresentationStyle:UIModalPresentationFormSheet];
  2094. [self presentViewController:vc animated:YES completion:nil];
  2095. }
  2096. }
  2097. #pragma --------------------------------------------------------------------------------------------
  2098. #pragma mark ===== Favorite =====
  2099. #pragma --------------------------------------------------------------------------------------------
  2100. - (void)settingFavoriteSuccess:(CCMetadataNet *)metadataNet
  2101. {
  2102. _dateReadDataSource = nil;
  2103. [[NCManageDatabase sharedInstance] setMetadataFavoriteWithFileID:metadataNet.fileID favorite:[metadataNet.options boolValue]];
  2104. if (_isSearchMode)
  2105. [self readFolder:metadataNet.serverUrl];
  2106. else
  2107. [self reloadDatasource:metadataNet.serverUrl];
  2108. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadataNet.fileID]];
  2109. if (metadata.directory && metadata.favorite) {
  2110. NSString *dir = [CCUtility stringAppendServerUrl:metadataNet.serverUrl addFileName:metadata.fileName];
  2111. [appDelegate.activeFavorites addFavoriteFolder:dir];
  2112. }
  2113. }
  2114. - (void)settingFavoriteFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2115. {
  2116. // Unauthorized
  2117. if (errorCode == kOCErrorServerUnauthorized)
  2118. [appDelegate openLoginView:self loginType:loginModifyPasswordUser];
  2119. NSLog(@"[LOG] Setting Favorite failure error %d, %@", (int)errorCode, message);
  2120. }
  2121. - (void)addFavorite:(tableMetadata *)metadata
  2122. {
  2123. if (metadata.directory) {
  2124. [[CCActions sharedInstance] settingFavorite:metadata favorite:YES delegate:self];
  2125. } else {
  2126. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2127. if (serverUrl)
  2128. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorAddFavorite selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2129. }
  2130. }
  2131. - (void)removeFavorite:(tableMetadata *)metadata
  2132. {
  2133. [[CCActions sharedInstance] settingFavorite:metadata favorite:NO delegate:self];
  2134. }
  2135. #pragma --------------------------------------------------------------------------------------------
  2136. #pragma mark ===== E2E Encryption =====
  2137. #pragma --------------------------------------------------------------------------------------------
  2138. - (void)unlockEndToEndFolderEncryptedSuccess:(CCMetadataNet *)metadataNet
  2139. {
  2140. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2141. [appDelegate messageNotification:@"_success_" description:@"_e2e_remove_folder_lock_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeSuccess errorCode:0];
  2142. }
  2143. - (void)unlockEndToEndFolderEncryptedFailure:(CCMetadataNet *)metadataNet message:(NSString *)message errorCode:(NSInteger)errorCode
  2144. {
  2145. if (errorCode == 404)
  2146. [[NCManageDatabase sharedInstance] setDirectoryE2ETokenLockWithFileID:metadataNet.fileID token:@""];
  2147. [appDelegate messageNotification:@"_error_" description:message visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:errorCode];
  2148. }
  2149. #pragma --------------------------------------------------------------------------------------------
  2150. #pragma mark ===== Open in... =====
  2151. #pragma --------------------------------------------------------------------------------------------
  2152. - (void)openIn:(tableMetadata *)metadata
  2153. {
  2154. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  2155. if (!serverUrl) return;
  2156. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorOpenIn selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2157. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:metadata.fileID];
  2158. if ([self indexPathIsValid:indexPath])
  2159. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2160. }
  2161. #pragma --------------------------------------------------------------------------------------------
  2162. #pragma mark ===== Remove Local File =====
  2163. #pragma --------------------------------------------------------------------------------------------
  2164. - (void)removeLocalFile:(tableMetadata *)metadata
  2165. {
  2166. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2167. if (!serverUrl) return;
  2168. [[NCManageDatabase sharedInstance] deleteLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  2169. [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID] error:nil];
  2170. [self reloadDatasource:serverUrl];
  2171. }
  2172. #pragma --------------------------------------------------------------------------------------------
  2173. #pragma mark ===== Order Table & GroupBy & DirectoryOnTop =====
  2174. #pragma --------------------------------------------------------------------------------------------
  2175. - (void)orderTable:(NSString *)order
  2176. {
  2177. [CCUtility setOrderSettings:order];
  2178. // Clear data-read of DataSource
  2179. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2180. }
  2181. - (void)ascendingTable:(BOOL)ascending
  2182. {
  2183. [CCUtility setAscendingSettings:ascending];
  2184. // Clear data-read of DataSource
  2185. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2186. }
  2187. - (void)directoryOnTop:(BOOL)directoryOnTop
  2188. {
  2189. [CCUtility setDirectoryOnTop:directoryOnTop];
  2190. // Clear data-read of DataSource
  2191. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2192. }
  2193. - (void)tableGroupBy:(NSString *)groupBy
  2194. {
  2195. [CCUtility setGroupBySettings:groupBy];
  2196. // Clear data-read of DataSource
  2197. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"clearDateReadDataSource" object:nil];
  2198. }
  2199. #pragma --------------------------------------------------------------------------------------------
  2200. #pragma mark ==== Menu LOGO ====
  2201. #pragma --------------------------------------------------------------------------------------------
  2202. - (void)menuLogo:(UIGestureRecognizer *)theGestureRecognizer
  2203. {
  2204. if (appDelegate.reSelectMenu.isOpen || appDelegate.reMainMenu.isOpen)
  2205. return;
  2206. // Brand
  2207. if ([NCBrandOptions sharedInstance].disable_multiaccount)
  2208. return;
  2209. NSUInteger numInSession = [[[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND session != ''", appDelegate.activeAccount] sorted:nil ascending:NO] count];
  2210. NSUInteger numInQueue = [appDelegate.netQueue operationCount];
  2211. if (numInSession+numInQueue > 0) {
  2212. [JDStatusBarNotification showWithStatus:NSLocalizedString(@"_transfers_in_queue_", nil) dismissAfter:k_dismissAfterSecond styleName:JDStatusBarStyleDefault];
  2213. return;
  2214. }
  2215. NSArray *listAccount = [[NCManageDatabase sharedInstance] getAccounts];
  2216. NSMutableArray *menuArray = [NSMutableArray new];
  2217. for (NSString *account in listAccount) {
  2218. if ([account isEqualToString:appDelegate.activeAccount]) continue;
  2219. CCMenuItem *item = [[CCMenuItem alloc] init];
  2220. item.title = [account stringByTruncatingToWidth:self.view.bounds.size.width - 100 withFont:[UIFont systemFontOfSize:12.0] atEnd:YES];
  2221. item.argument = account;
  2222. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ ", account]];
  2223. NSString *directoryUser = [CCUtility getDirectoryActiveUser:tableAccount.user activeUrl:tableAccount.url];
  2224. UIImage *avatar = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/avatar.png", directoryUser]];
  2225. if (avatar) {
  2226. avatar = [CCGraphics scaleImage:avatar toSize:CGSizeMake(25, 25) isAspectRation:YES];
  2227. CCAvatar *avatarImageView = [[CCAvatar alloc] initWithImage:avatar borderColor:[UIColor lightGrayColor] borderWidth:0.5];
  2228. CGSize imageSize = avatarImageView.bounds.size;
  2229. UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
  2230. CGContextRef context = UIGraphicsGetCurrentContext();
  2231. [avatarImageView.layer renderInContext:context];
  2232. avatar = UIGraphicsGetImageFromCurrentImageContext();
  2233. UIGraphicsEndImageContext();
  2234. } else {
  2235. avatar = [UIImage imageNamed:@"menuLogoUser"];
  2236. }
  2237. item.image = avatar;
  2238. item.target = self;
  2239. item.action = @selector(changeDefaultAccount:);
  2240. [menuArray addObject:item];
  2241. }
  2242. // Add + new account
  2243. CCMenuItem *item = [[CCMenuItem alloc] init];
  2244. item.title = NSLocalizedString(@"_add_account_", nil);
  2245. item.argument = @"";
  2246. item.image = [UIImage imageNamed:@"settingsAccountNextcloud"];
  2247. item.target = self;
  2248. item.action = @selector(addNewAccount:);
  2249. [menuArray addObject:item];
  2250. OptionalConfiguration options;
  2251. Color textColor, backgroundColor;
  2252. textColor.R = 0;
  2253. textColor.G = 0;
  2254. textColor.B = 0;
  2255. backgroundColor.R = 1;
  2256. backgroundColor.G = 1;
  2257. backgroundColor.B = 1;
  2258. options.arrowSize = 9;
  2259. options.marginXSpacing = 7;
  2260. options.marginYSpacing = 10;
  2261. options.intervalSpacing = 20;
  2262. options.menuCornerRadius = 6.5;
  2263. options.maskToBackground = NO;
  2264. options.shadowOfMenu = YES;
  2265. options.hasSeperatorLine = YES;
  2266. options.seperatorLineHasInsets = YES;
  2267. options.textColor = textColor;
  2268. options.menuBackgroundColor = backgroundColor;
  2269. CGRect rect = self.view.frame;
  2270. CGFloat locationY = [theGestureRecognizer locationInView: self.navigationController.navigationBar].y;
  2271. CGFloat safeAreaTop = 0;
  2272. CGFloat offsetY = 35;
  2273. if (@available(iOS 11, *)) {
  2274. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top / 2;
  2275. }
  2276. rect.origin.y = locationY + safeAreaTop + offsetY;
  2277. rect.size.height = rect.size.height - locationY - safeAreaTop - offsetY;
  2278. [CCMenuAccount setTitleFont:[UIFont systemFontOfSize:12.0]];
  2279. [CCMenuAccount showMenuInView:self.navigationController.view fromRect:rect menuItems:menuArray withOptions:options];
  2280. }
  2281. - (void)changeDefaultAccount:(CCMenuItem *)sender
  2282. {
  2283. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:NO];
  2284. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2285. tableAccount *tableAccount = [[NCManageDatabase sharedInstance] setAccountActive:[sender argument]];
  2286. if (tableAccount) {
  2287. [appDelegate settingActiveAccount:tableAccount.account activeUrl:tableAccount.url activeUser:tableAccount.user activeUserID:tableAccount.userID activePassword:tableAccount.password];
  2288. // go to home sweet home
  2289. [[NSNotificationCenter defaultCenter] postNotificationOnMainThreadName:@"initializeMain" object:nil];
  2290. [_ImageTitleHomeCryptoCloud setUserInteractionEnabled:YES];
  2291. }
  2292. });
  2293. }
  2294. - (void)addNewAccount:(CCMenuItem *)sender
  2295. {
  2296. [appDelegate.netQueue cancelAllOperations];
  2297. [[CCNetworking sharedNetworking] settingSessionsDownload:YES upload:YES taskStatus:k_taskStatusCancel activeAccount:appDelegate.activeAccount activeUser:appDelegate.activeUser activeUrl:appDelegate.activeUrl];
  2298. [appDelegate openLoginView:self loginType:loginAdd];
  2299. }
  2300. #pragma --------------------------------------------------------------------------------------------
  2301. #pragma mark ==== ReMenu ====
  2302. #pragma --------------------------------------------------------------------------------------------
  2303. - (void)createReMenuBackgroundView:(REMenu *)menu
  2304. {
  2305. CGFloat safeAreaBottom = 0;
  2306. CGFloat safeAreaTop = 0;
  2307. CGFloat statusBar = 0;
  2308. if (@available(iOS 11, *)) {
  2309. safeAreaTop = [UIApplication sharedApplication].delegate.window.safeAreaInsets.top;
  2310. safeAreaBottom = [UIApplication sharedApplication].delegate.window.safeAreaInsets.bottom;
  2311. }
  2312. if ([UIApplication sharedApplication].isStatusBarHidden) {
  2313. statusBar = 13;
  2314. }
  2315. CGFloat computeNavigationBarOffset = [menu computeNavigationBarOffset];
  2316. UIViewController *rootController = [[[[UIApplication sharedApplication]delegate] window] rootViewController];
  2317. CGRect globalPositionMenu = [menu.menuView convertRect:menu.menuView.bounds toView:rootController.view];
  2318. _reMenuBackgroundView.frame = CGRectMake(0, computeNavigationBarOffset, globalPositionMenu.size.width, rootController.view.frame.size.height);
  2319. [UIView animateWithDuration:0.2 animations:^{
  2320. CGFloat minimum = safeAreaBottom + self.tabBarController.tabBar.frame.size.height;
  2321. CGFloat y = rootController.view.frame.size.height - menu.menuView.frame.size.height - globalPositionMenu.origin.y + statusBar;
  2322. if (y>minimum) {
  2323. _reMenuBackgroundView.frame = CGRectMake(0, rootController.view.frame.size.height, globalPositionMenu.size.width, - y);
  2324. [self.tabBarController.view addSubview:_reMenuBackgroundView];
  2325. }
  2326. }];
  2327. }
  2328. - (void)createReMainMenu
  2329. {
  2330. NSString *ordinamento;
  2331. NSString *groupBy = _directoryGroupBy;
  2332. __block NSString *nuovoOrdinamento;
  2333. NSString *titoloNuovo, *titoloAttuale;
  2334. BOOL ascendente;
  2335. __block BOOL nuovoAscendente;
  2336. UIImage *image;
  2337. // ITEM SELECT ----------------------------------------------------------------------------------------------------
  2338. appDelegate.selezionaItem = [[REMenuItem alloc] initWithTitle:NSLocalizedString(@"_select_", nil)subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"seleziona"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2339. if ([_sectionDataSource.allRecordsDataSource count] > 0) {
  2340. [self tableViewSelect:YES];
  2341. }
  2342. }];
  2343. // ITEM ORDER ----------------------------------------------------------------------------------------------------
  2344. ordinamento = _directoryOrder;
  2345. if ([ordinamento isEqualToString:@"fileName"]) {
  2346. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdeyByDate"] color:[NCBrandColor sharedInstance].brandElement];
  2347. titoloNuovo = NSLocalizedString(@"_order_by_date_", nil);
  2348. titoloAttuale = NSLocalizedString(@"_current_order_name_", nil);
  2349. nuovoOrdinamento = @"date";
  2350. }
  2351. if ([ordinamento isEqualToString:@"date"]) {
  2352. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrderByFileName"] color:[NCBrandColor sharedInstance].brandElement];
  2353. titoloNuovo = NSLocalizedString(@"_order_by_name_", nil);
  2354. titoloAttuale = NSLocalizedString(@"_current_order_date_", nil);
  2355. nuovoOrdinamento = @"fileName";
  2356. }
  2357. appDelegate.ordinaItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2358. [self orderTable:nuovoOrdinamento];
  2359. }];
  2360. // ITEM ASCENDING -----------------------------------------------------------------------------------------------------
  2361. ascendente = [CCUtility getAscendingSettings];
  2362. if (ascendente) {
  2363. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoDiscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2364. titoloNuovo = NSLocalizedString(@"_sort_descending_", nil);
  2365. titoloAttuale = NSLocalizedString(@"_current_sort_ascending_", nil);
  2366. nuovoAscendente = false;
  2367. }
  2368. if (!ascendente) {
  2369. image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuOrdinamentoAscendente"] color:[NCBrandColor sharedInstance].brandElement];
  2370. titoloNuovo = NSLocalizedString(@"_sort_ascending_", nil);
  2371. titoloAttuale = NSLocalizedString(@"_current_sort_descending_", nil);
  2372. nuovoAscendente = true;
  2373. }
  2374. appDelegate.ascendenteItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:titoloAttuale image:image highlightedImage:nil action:^(REMenuItem *item) {
  2375. [self ascendingTable:nuovoAscendente];
  2376. }];
  2377. // ITEM ALPHABETIC -----------------------------------------------------------------------------------------------------
  2378. if ([groupBy isEqualToString:@"alphabetic"]) { titoloNuovo = NSLocalizedString(@"_group_alphabetic_yes_", nil); }
  2379. else { titoloNuovo = NSLocalizedString(@"_group_alphabetic_no_", nil); }
  2380. appDelegate.alphabeticItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByAlphabetic"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2381. if ([groupBy isEqualToString:@"alphabetic"]) [self tableGroupBy:@"none"];
  2382. else [self tableGroupBy:@"alphabetic"];
  2383. }];
  2384. // ITEM TYPEFILE -------------------------------------------------------------------------------------------------------
  2385. if ([groupBy isEqualToString:@"typefile"]) { titoloNuovo = NSLocalizedString(@"_group_typefile_yes_", nil); }
  2386. else { titoloNuovo = NSLocalizedString(@"_group_typefile_no_", nil); }
  2387. appDelegate.typefileItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByTypeFile"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2388. if ([groupBy isEqualToString:@"typefile"]) [self tableGroupBy:@"none"];
  2389. else [self tableGroupBy:@"typefile"];
  2390. }];
  2391. // ITEM DATE -------------------------------------------------------------------------------------------------------
  2392. if ([groupBy isEqualToString:@"date"]) { titoloNuovo = NSLocalizedString(@"_group_date_yes_", nil); }
  2393. else { titoloNuovo = NSLocalizedString(@"_group_date_no_", nil); }
  2394. appDelegate.dateItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"MenuGroupByDate"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2395. if ([groupBy isEqualToString:@"date"]) [self tableGroupBy:@"none"];
  2396. else [self tableGroupBy:@"date"];
  2397. }];
  2398. // ITEM DIRECTORY ON TOP ------------------------------------------------------------------------------------------------
  2399. if ([CCUtility getDirectoryOnTop]) { titoloNuovo = NSLocalizedString(@"_directory_on_top_yes_", nil); }
  2400. else { titoloNuovo = NSLocalizedString(@"_directory_on_top_no_", nil); }
  2401. appDelegate.directoryOnTopItem = [[REMenuItem alloc] initWithTitle:titoloNuovo subtitle:@"" image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"menuDirectoryOnTop"] color:[NCBrandColor sharedInstance].brandElement] highlightedImage:nil action:^(REMenuItem *item) {
  2402. if ([CCUtility getDirectoryOnTop])
  2403. [self directoryOnTop:NO];
  2404. else
  2405. [self directoryOnTop:YES];
  2406. }];
  2407. // REMENU --------------------------------------------------------------------------------------------------------------
  2408. appDelegate.reMainMenu = [[REMenu alloc] initWithItems:@[appDelegate.selezionaItem, appDelegate.ordinaItem, appDelegate.ascendenteItem, appDelegate.alphabeticItem, appDelegate.typefileItem, appDelegate.dateItem, appDelegate.directoryOnTopItem]];
  2409. appDelegate.reMainMenu.imageOffset = CGSizeMake(5, -1);
  2410. appDelegate.reMainMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2411. appDelegate.reMainMenu.imageOffset = CGSizeMake(0, 0);
  2412. appDelegate.reMainMenu.waitUntilAnimationIsComplete = NO;
  2413. appDelegate.reMainMenu.separatorHeight = 0.5;
  2414. appDelegate.reMainMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2415. appDelegate.reMainMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2416. appDelegate.reMainMenu.textColor = [UIColor blackColor];
  2417. appDelegate.reMainMenu.textAlignment = NSTextAlignmentLeft;
  2418. appDelegate.reMainMenu.textShadowColor = nil;
  2419. appDelegate.reMainMenu.textOffset = CGSizeMake(50, 0.0);
  2420. appDelegate.reMainMenu.font = [UIFont systemFontOfSize:14.0];
  2421. appDelegate.reMainMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2422. appDelegate.reMainMenu.highlightedSeparatorColor = nil;
  2423. appDelegate.reMainMenu.highlightedTextColor = [UIColor blackColor];
  2424. appDelegate.reMainMenu.highlightedTextShadowColor = nil;
  2425. appDelegate.reMainMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2426. appDelegate.reMainMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1];
  2427. appDelegate.reMainMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2428. appDelegate.reMainMenu.subtitleTextShadowColor = nil;
  2429. appDelegate.reMainMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2430. appDelegate.reMainMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2431. appDelegate.reMainMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2432. appDelegate.reMainMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2433. appDelegate.reMainMenu.subtitleHighlightedTextShadowColor = nil;
  2434. appDelegate.reMainMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2435. appDelegate.reMainMenu.borderWidth = 0.3;
  2436. appDelegate.reMainMenu.borderColor = [UIColor lightGrayColor];
  2437. appDelegate.reMainMenu.animationDuration = 0.2;
  2438. appDelegate.reMainMenu.closeAnimationDuration = 0.2;
  2439. appDelegate.reMainMenu.bounce = NO;
  2440. __weak typeof(self) weakSelf = self;
  2441. [appDelegate.reMainMenu setClosePreparationBlock:^{
  2442. // Backgroun reMenu (Gesture)
  2443. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2444. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2445. }];
  2446. }
  2447. - (void)toggleReMainMenu
  2448. {
  2449. if (appDelegate.reMainMenu.isOpen) {
  2450. [appDelegate.reMainMenu close];
  2451. } else {
  2452. [self createReMainMenu];
  2453. [appDelegate.reMainMenu showFromNavigationController:self.navigationController];
  2454. // Backgroun reMenu & (Gesture)
  2455. [self createReMenuBackgroundView:appDelegate.reMainMenu];
  2456. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReMainMenu)];
  2457. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2458. }
  2459. }
  2460. - (void)createReSelectMenu
  2461. {
  2462. // ITEM DELETE ------------------------------------------------------------------------------------------------------
  2463. 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) {
  2464. [self deleteFile];
  2465. }];
  2466. // ITEM MOVE ------------------------------------------------------------------------------------------------------
  2467. 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) {
  2468. [self moveOpenWindow:[self.tableView indexPathsForSelectedRows]];
  2469. }];
  2470. // ITEM DOWNLOAD ----------------------------------------------------------------------------------------------------
  2471. 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) {
  2472. [self downloadSelectedFilesFolders];
  2473. }];
  2474. // ITEM SAVE IMAGE & VIDEO -------------------------------------------------------------------------------------------
  2475. 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) {
  2476. [self saveSelectedFiles];
  2477. }];
  2478. appDelegate.reSelectMenu = [[REMenu alloc] initWithItems:@[appDelegate.deleteItem,appDelegate.moveItem, appDelegate.downloadItem, appDelegate.saveItem]];
  2479. appDelegate.reSelectMenu.imageOffset = CGSizeMake(5, -1);
  2480. appDelegate.reSelectMenu.separatorOffset = CGSizeMake(50.0, 0.0);
  2481. appDelegate.reSelectMenu.imageOffset = CGSizeMake(0, 0);
  2482. appDelegate.reSelectMenu.waitUntilAnimationIsComplete = NO;
  2483. appDelegate.reSelectMenu.separatorHeight = 0.5;
  2484. appDelegate.reSelectMenu.separatorColor = [NCBrandColor sharedInstance].seperator;
  2485. appDelegate.reSelectMenu.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  2486. appDelegate.reSelectMenu.textColor = [UIColor blackColor];
  2487. appDelegate.reSelectMenu.textAlignment = NSTextAlignmentLeft;
  2488. appDelegate.reSelectMenu.textShadowColor = nil;
  2489. appDelegate.reSelectMenu.textOffset = CGSizeMake(50, 0.0);
  2490. appDelegate.reSelectMenu.font = [UIFont systemFontOfSize:14.0];
  2491. appDelegate.reSelectMenu.highlightedBackgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  2492. appDelegate.reSelectMenu.highlightedSeparatorColor = nil;
  2493. appDelegate.reSelectMenu.highlightedTextColor = [UIColor blackColor];
  2494. appDelegate.reSelectMenu.highlightedTextShadowColor = nil;
  2495. appDelegate.reSelectMenu.highlightedTextShadowOffset = CGSizeMake(0, 0);
  2496. appDelegate.reSelectMenu.subtitleTextColor = [UIColor colorWithWhite:0.425 alpha:1.000];
  2497. appDelegate.reSelectMenu.subtitleTextAlignment = NSTextAlignmentLeft;
  2498. appDelegate.reSelectMenu.subtitleTextShadowColor = nil;
  2499. appDelegate.reSelectMenu.subtitleTextShadowOffset = CGSizeMake(0, 0.0);
  2500. appDelegate.reSelectMenu.subtitleTextOffset = CGSizeMake(50, 0.0);
  2501. appDelegate.reSelectMenu.subtitleFont = [UIFont systemFontOfSize:12.0];
  2502. appDelegate.reSelectMenu.subtitleHighlightedTextColor = [UIColor lightGrayColor];
  2503. appDelegate.reSelectMenu.subtitleHighlightedTextShadowColor = nil;
  2504. appDelegate.reSelectMenu.subtitleHighlightedTextShadowOffset = CGSizeMake(0, 0);
  2505. appDelegate.reSelectMenu.borderWidth = 0.3;
  2506. appDelegate.reSelectMenu.borderColor = [UIColor lightGrayColor];
  2507. appDelegate.reSelectMenu.closeAnimationDuration = 0.2;
  2508. appDelegate.reSelectMenu.animationDuration = 0.2;
  2509. appDelegate.reSelectMenu.bounce = NO;
  2510. __weak typeof(self) weakSelf = self;
  2511. [appDelegate.reSelectMenu setClosePreparationBlock:^{
  2512. // Backgroun reMenu (Gesture)
  2513. [weakSelf.reMenuBackgroundView removeFromSuperview];
  2514. [weakSelf.reMenuBackgroundView removeGestureRecognizer:weakSelf.singleFingerTap];
  2515. }];
  2516. }
  2517. - (void)toggleReSelectMenu
  2518. {
  2519. if (appDelegate.reSelectMenu.isOpen) {
  2520. [appDelegate.reSelectMenu close];
  2521. } else {
  2522. [self createReSelectMenu];
  2523. [appDelegate.reSelectMenu showFromNavigationController:self.navigationController];
  2524. // Backgroun reMenu & (Gesture)
  2525. [self createReMenuBackgroundView:appDelegate.reSelectMenu];
  2526. _singleFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(toggleReSelectMenu)];
  2527. [_reMenuBackgroundView addGestureRecognizer:_singleFingerTap];
  2528. }
  2529. }
  2530. #pragma --------------------------------------------------------------------------------------------
  2531. #pragma mark ===== Long Press Recognized Table View / Menu Controller =====
  2532. #pragma --------------------------------------------------------------------------------------------
  2533. - (void)onLongPressTableView:(UILongPressGestureRecognizer*)recognizer
  2534. {
  2535. if (recognizer.state == UIGestureRecognizerStateBegan) {
  2536. CGPoint touchPoint = [recognizer locationInView:self.tableView];
  2537. NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:touchPoint];
  2538. if ([self indexPathIsValid:indexPath])
  2539. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2540. else
  2541. _metadata = nil;
  2542. [self becomeFirstResponder];
  2543. UIMenuController *menuController = [UIMenuController sharedMenuController];
  2544. UIMenuItem *copyFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_file_", nil) action:@selector(copyFile:)];
  2545. UIMenuItem *copyFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_copy_files_", nil) action:@selector(copyFiles:)];
  2546. UIMenuItem *openinFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_open_in_", nil) action:@selector(openinFile:)];
  2547. UIMenuItem *pasteFileItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_file_", nil) action:@selector(pasteFile:)];
  2548. UIMenuItem *pasteFilesItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"_paste_files_", nil) action:@selector(pasteFiles:)];
  2549. [menuController setMenuItems:[NSArray arrayWithObjects:copyFileItem, copyFilesItem, openinFileItem, pasteFileItem, pasteFilesItem, nil]];
  2550. [menuController setTargetRect:CGRectMake(touchPoint.x, touchPoint.y, 0.0f, 0.0f) inView:self.tableView];
  2551. [menuController setMenuVisible:YES animated:YES];
  2552. }
  2553. }
  2554. - (BOOL)canBecomeFirstResponder
  2555. {
  2556. return YES;
  2557. }
  2558. - (BOOL)canPerformAction:(SEL)action withSender:(id)sender
  2559. {
  2560. // For copy file, copy files, Open in ... :
  2561. //
  2562. // NO Directory
  2563. // NO Error Passcode
  2564. // NO In Session mode (download/upload)
  2565. // NO Template
  2566. if (@selector(copyFile:) == action || @selector(openinFile:) == action) {
  2567. if (_isSelectedMode == NO && _metadata && !_metadata.directory && [_metadata.session length] == 0) return YES;
  2568. else return NO;
  2569. }
  2570. if (@selector(copyFiles:) == action) {
  2571. if (_isSelectedMode) {
  2572. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2573. for (tableMetadata *metadata in selectedMetadatas) {
  2574. if (!metadata.directory && metadata.session.length == 0)
  2575. return YES;
  2576. }
  2577. }
  2578. return NO;
  2579. }
  2580. if (@selector(pasteFile:) == action) {
  2581. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2582. NSArray *items = [pasteboard items];
  2583. if ([items count] == 1) {
  2584. // Value : (NSData) fileID
  2585. NSDictionary *dic = [items objectAtIndex:0];
  2586. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2587. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2588. if (fileID) {
  2589. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2590. if (metadata) {
  2591. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2592. if (account) {
  2593. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2594. if (directoryUser)
  2595. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]])
  2596. return YES;
  2597. }
  2598. }
  2599. }
  2600. }
  2601. return NO;
  2602. }
  2603. if (@selector(pasteFiles:) == action) {
  2604. BOOL isValid = NO;
  2605. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2606. NSArray *items = [pasteboard items];
  2607. if ([items count] <= 1) return NO;
  2608. for (NSDictionary *dic in items) {
  2609. // Value : (NSData) fileID
  2610. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2611. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2612. if (fileID) {
  2613. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2614. if (metadata) {
  2615. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2616. if (account) {
  2617. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2618. if (directoryUser) {
  2619. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2620. isValid = YES;
  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. } else {
  2638. isValid = NO;
  2639. break;
  2640. }
  2641. }
  2642. return isValid;
  2643. }
  2644. return NO;
  2645. }
  2646. /************************************ COPY ************************************/
  2647. - (void)copyFile:(id)sender
  2648. {
  2649. // Remove all item
  2650. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2651. pasteboard.items = [[NSArray alloc] init];
  2652. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser,_metadata.fileID]]) {
  2653. [self copyFileToPasteboard:_metadata];
  2654. } else {
  2655. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2656. if (serverUrl)
  2657. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2658. }
  2659. }
  2660. - (void)copyFiles:(id)sender
  2661. {
  2662. // Remove all item
  2663. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2664. pasteboard.items = [[NSArray alloc] init];
  2665. NSArray *selectedMetadatas = [self getMetadatasFromSelectedRows:[self.tableView indexPathsForSelectedRows]];
  2666. for (tableMetadata *metadata in selectedMetadatas) {
  2667. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]]) {
  2668. [self copyFileToPasteboard:metadata];
  2669. } else {
  2670. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2671. if (serverUrl)
  2672. [[CCNetworking sharedNetworking] downloadFile:metadata.fileName fileID:metadata.fileID serverUrl:serverUrl selector:selectorLoadCopy selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  2673. }
  2674. }
  2675. [self tableViewSelect:NO];
  2676. }
  2677. - (void)copyFileToPasteboard:(tableMetadata *)metadata
  2678. {
  2679. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2680. NSMutableArray *items = [[NSMutableArray alloc] initWithArray:pasteboard.items];
  2681. // Value : (NSData) fileID
  2682. NSDictionary *item = [NSDictionary dictionaryWithObjectsAndKeys:[NSKeyedArchiver archivedDataWithRootObject:metadata.fileID], k_metadataKeyedUnarchiver,nil];
  2683. [items addObject:item];
  2684. [pasteboard setItems:items];
  2685. }
  2686. /************************************ OPEN IN ... ******************************/
  2687. - (void)openinFile:(id)sender
  2688. {
  2689. [self openIn:_metadata];
  2690. }
  2691. /************************************ PASTE ************************************/
  2692. - (void)pasteFile:(id)sender
  2693. {
  2694. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2695. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2696. }
  2697. - (void)pasteFiles:(id)sender
  2698. {
  2699. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  2700. [self uploadFilePasteArray:[pasteboard items] cryptated:NO];
  2701. }
  2702. - (void)uploadFilePasteArray:(NSArray *)items cryptated:(BOOL)cryptated
  2703. {
  2704. float timer = 0;
  2705. for (NSDictionary *dic in items) {
  2706. // Value : (NSData) fileID
  2707. NSData *dataFileID = [dic objectForKey: k_metadataKeyedUnarchiver];
  2708. NSString *fileID = [NSKeyedUnarchiver unarchiveObjectWithData:dataFileID];
  2709. tableMetadata *metadata = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", fileID]];
  2710. if (metadata) {
  2711. tableAccount *account = [[NCManageDatabase sharedInstance] getAccountWithPredicate:[NSPredicate predicateWithFormat:@"account = %@", metadata.account]];
  2712. if (account) {
  2713. NSString *directoryUser = [CCUtility getDirectoryActiveUser:account.user activeUrl:account.url];
  2714. if (directoryUser) {
  2715. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, fileID]]) {
  2716. [CCUtility copyFileAtPath:[NSString stringWithFormat:@"%@/%@", directoryUser, metadata.fileID] toPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileNameView]];
  2717. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timer * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
  2718. [[CCNetworking sharedNetworking] uploadFile:metadata.fileNameView serverUrl:_serverUrl session:k_upload_session taskStatus:k_taskStatusResume selector:@"" selectorPost:@"" errorCode:0 delegate:nil];
  2719. });
  2720. timer += 0.1;
  2721. }
  2722. }
  2723. }
  2724. }
  2725. }
  2726. }
  2727. #pragma --------------------------------------------------------------------------------------------
  2728. #pragma mark ===== Lock Passcode =====
  2729. #pragma --------------------------------------------------------------------------------------------
  2730. - (NSUInteger)passcodeViewControllerNumberOfFailedAttempts:(CCBKPasscode *)aViewController
  2731. {
  2732. return _failedAttempts;
  2733. }
  2734. - (NSDate *)passcodeViewControllerLockUntilDate:(CCBKPasscode *)aViewController
  2735. {
  2736. return _lockUntilDate;
  2737. }
  2738. - (void)passcodeViewCloseButtonPressed:(id)sender
  2739. {
  2740. [self dismissViewControllerAnimated:YES completion:nil];
  2741. }
  2742. - (void)passcodeViewController:(CCBKPasscode *)aViewController authenticatePasscode:(NSString *)aPasscode resultHandler:(void (^)(BOOL))aResultHandler
  2743. {
  2744. if (aViewController.fromType == CCBKPasscodeFromLockScreen || aViewController.fromType == CCBKPasscodeFromLockDirectory || aViewController.fromType == CCBKPasscodeFromDisactivateDirectory ) {
  2745. if ([aPasscode isEqualToString:[CCUtility getBlockCode]]) {
  2746. _lockUntilDate = nil;
  2747. _failedAttempts = 0;
  2748. aResultHandler(YES);
  2749. } else aResultHandler(NO);
  2750. } else aResultHandler(YES);
  2751. }
  2752. - (void)passcodeViewController:(CCBKPasscode *)aViewController didFinishWithPasscode:(NSString *)aPasscode
  2753. {
  2754. [aViewController dismissViewControllerAnimated:YES completion:nil];
  2755. switch (aViewController.type) {
  2756. case BKPasscodeViewControllerCheckPasscodeType: {
  2757. if (aViewController.fromType == CCBKPasscodeFromLockDirectory) {
  2758. // possiamo procedere alla prossima directory
  2759. [self performSegueDirectoryWithControlPasscode:false];
  2760. // avviamo la sessione Passcode Lock con now
  2761. appDelegate.sessionePasscodeLock = [NSDate date];
  2762. }
  2763. // disattivazione lock cartella
  2764. if (aViewController.fromType == CCBKPasscodeFromDisactivateDirectory) {
  2765. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2766. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2767. if (![[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:NO]) {
  2768. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2769. }
  2770. [self tableViewReloadData];
  2771. }
  2772. }
  2773. break;
  2774. default:
  2775. break;
  2776. }
  2777. }
  2778. - (void)comandoLockPassword
  2779. {
  2780. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2781. if (!serverUrl) return;
  2782. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2783. // se non è abilitato il Lock Passcode esci
  2784. if ([[CCUtility getBlockCode] length] == 0) {
  2785. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_warning_", nil) message:NSLocalizedString(@"_only_lock_passcode_", nil) preferredStyle:UIAlertControllerStyleAlert];
  2786. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {}];
  2787. [alertController addAction:okAction];
  2788. [self presentViewController:alertController animated:YES completion:nil];
  2789. return;
  2790. }
  2791. // se è richiesta la disattivazione si chiede la password
  2792. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2793. if (directory.lock) {
  2794. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  2795. viewController.delegate = self;
  2796. viewController.fromType = CCBKPasscodeFromDisactivateDirectory;
  2797. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  2798. viewController.inputViewTitlePassword = YES;
  2799. if ([CCUtility getSimplyBlockCode]) {
  2800. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  2801. viewController.passcodeInputView.maximumLength = 6;
  2802. } else {
  2803. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  2804. viewController.passcodeInputView.maximumLength = 64;
  2805. }
  2806. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  2807. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  2808. viewController.touchIDManager = touchIDManager;
  2809. viewController.title = NSLocalizedString(@"_passcode_protection_", nil);
  2810. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  2811. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  2812. UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
  2813. [self presentViewController:navigationController animated:YES completion:nil];
  2814. return;
  2815. }
  2816. // ---------------- ACTIVATE PASSWORD
  2817. if ([[NCManageDatabase sharedInstance] setDirectoryLockWithServerUrl:lockServerUrl lock:YES]) {
  2818. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  2819. if ([self indexPathIsValid:indexPath])
  2820. [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  2821. } else {
  2822. [appDelegate messageNotification:@"_error_" description:@"_error_operation_canc_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2823. }
  2824. }
  2825. #pragma mark -
  2826. #pragma --------------------------------------------------------------------------------------------
  2827. #pragma mark ===== Swipe Tablet -> menu =====
  2828. #pragma --------------------------------------------------------------------------------------------
  2829. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction
  2830. {
  2831. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2832. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  2833. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  2834. return NO;
  2835. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  2836. return NO;
  2837. // E2E
  2838. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && [CCUtility isEndToEndEnabled:appDelegate.activeAccount] == NO)
  2839. return NO;
  2840. return YES;
  2841. }
  2842. -(void)swipeTableCell:(nonnull MGSwipeTableCell *)cell didChangeSwipeState:(MGSwipeState)state gestureIsActive:(BOOL)gestureIsActive
  2843. {
  2844. }
  2845. - (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
  2846. {
  2847. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  2848. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  2849. if (direction == MGSwipeDirectionRightToLeft) {
  2850. // Delete
  2851. if (index == 0)
  2852. [self swipeDelete:indexPath];
  2853. // More
  2854. if (index == 1)
  2855. [self swipeMore:indexPath];
  2856. }
  2857. if (direction == MGSwipeDirectionLeftToRight) {
  2858. if (_metadata.favorite)
  2859. [self removeFavorite:_metadata];
  2860. else
  2861. [self addFavorite:_metadata];
  2862. }
  2863. return YES;
  2864. }
  2865. - (void)swipeDelete:(NSIndexPath *)indexPath
  2866. {
  2867. // Directory locked ?
  2868. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:[[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID] addFileName:_metadata.fileName];
  2869. if (!lockServerUrl) return;
  2870. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2871. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) {
  2872. [appDelegate messageNotification:@"_error_" description:@"_folder_blocked_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  2873. return;
  2874. }
  2875. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  2876. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_delete_", nil) style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
  2877. [self performSelector:@selector(deleteFile) withObject:nil];
  2878. }]];
  2879. [alertController addAction: [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2880. [alertController dismissViewControllerAnimated:YES completion:nil];
  2881. }]];
  2882. alertController.popoverPresentationController.sourceView = self.view;
  2883. alertController.popoverPresentationController.sourceRect = [self.tableView rectForRowAtIndexPath:indexPath];
  2884. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  2885. [alertController.view layoutIfNeeded];
  2886. [self presentViewController:alertController animated:YES completion:nil];
  2887. }
  2888. - (void)swipeMore:(NSIndexPath *)indexPath
  2889. {
  2890. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  2891. if (!serverUrl) return;
  2892. NSString *titoloLock, *titleFavorite;
  2893. if (_metadata.favorite) {
  2894. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_remove_favorites_", nil)];
  2895. } else {
  2896. titleFavorite = [NSString stringWithFormat:NSLocalizedString(@"_add_favorites_", nil)];
  2897. }
  2898. if (_metadata.directory) {
  2899. // calcolo lockServerUrl
  2900. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2901. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  2902. if (directory.lock)
  2903. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_remove_passcode_", nil)];
  2904. else
  2905. titoloLock = [NSString stringWithFormat:NSLocalizedString(@"_protect_passcode_", nil)];
  2906. }
  2907. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", _metadata.fileID]];
  2908. // ******************************************* AHKActionSheet *******************************************
  2909. AHKActionSheet *actionSheet = [[AHKActionSheet alloc] initWithView:self.tabBarController.view title:nil];
  2910. actionSheet.animationDuration = 0.2;
  2911. actionSheet.buttonHeight = 50.0;
  2912. actionSheet.cancelButtonHeight = 50.0f;
  2913. actionSheet.separatorHeight = 5.0f;
  2914. actionSheet.automaticallyTintButtonImages = @(NO);
  2915. actionSheet.encryptedButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[NCBrandColor sharedInstance].encrypted };
  2916. actionSheet.buttonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor blackColor] };
  2917. actionSheet.cancelButtonTextAttributes = @{ NSFontAttributeName:[UIFont boldSystemFontOfSize:17], NSForegroundColorAttributeName:[UIColor blackColor] };
  2918. actionSheet.disableButtonTextAttributes = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor darkGrayColor] };
  2919. actionSheet.separatorColor = [NCBrandColor sharedInstance].seperator;
  2920. actionSheet.cancelButtonTitle = NSLocalizedString(@"_cancel_",nil);
  2921. // ******************************************* DIRECTORY *******************************************
  2922. if (_metadata.directory) {
  2923. BOOL lockDirectory = NO;
  2924. NSString *dirServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  2925. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:[NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName] account:appDelegate.activeAccount];
  2926. // Directory bloccata ?
  2927. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, dirServerUrl]];
  2928. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil) lockDirectory = YES;
  2929. [actionSheet addButtonWithTitle:_metadata.fileNameView
  2930. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement]
  2931. backgroundColor:[NCBrandColor sharedInstance].tabBar
  2932. height:50.0
  2933. type:AHKActionSheetButtonTypeDisabled
  2934. handler:nil
  2935. ];
  2936. if (!lockDirectory && !isFolderEncrypted) {
  2937. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  2938. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement]
  2939. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2940. height:50.0
  2941. type:AHKActionSheetButtonTypeDefault
  2942. handler:^(AHKActionSheet *as) {
  2943. [self openWindowShare:_metadata];
  2944. }];
  2945. }
  2946. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !_metadata.e2eEncrypted) {
  2947. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  2948. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  2949. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2950. height:50.0
  2951. type:AHKActionSheetButtonTypeDefault
  2952. handler:^(AHKActionSheet *as) {
  2953. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  2954. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  2955. textField.text = _metadata.fileNameView;
  2956. //textField.selectedTextRange = [textField textRangeFromPosition:textField.beginningOfDocument toPosition:textField.endOfDocument];
  2957. //textField.delegate = self;
  2958. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  2959. }];
  2960. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  2961. NSLog(@"[LOG] Cancel action");
  2962. }];
  2963. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  2964. UITextField *fileName = alertController.textFields.firstObject;
  2965. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  2966. }];
  2967. okAction.enabled = NO;
  2968. [alertController addAction:cancelAction];
  2969. [alertController addAction:okAction];
  2970. [self presentViewController:alertController animated:YES completion:nil];
  2971. }];
  2972. }
  2973. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES) && !lockDirectory && !isFolderEncrypted) {
  2974. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  2975. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  2976. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2977. height:50.0
  2978. type:AHKActionSheetButtonTypeDefault
  2979. handler:^(AHKActionSheet *as) {
  2980. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  2981. }];
  2982. }
  2983. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  2984. [actionSheet addButtonWithTitle:NSLocalizedString(@"_folder_automatic_upload_", nil)
  2985. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement]
  2986. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  2987. height:50.0
  2988. type:AHKActionSheetButtonTypeDefault
  2989. handler:^(AHKActionSheet *as) {
  2990. // Settings new folder Automatatic upload
  2991. [[NCManageDatabase sharedInstance] setAccountAutoUploadFileName:_metadata.fileName];
  2992. [[NCManageDatabase sharedInstance] setAccountAutoUploadDirectory:serverUrl activeUrl:appDelegate.activeUrl];
  2993. // Clear data (old) Auto Upload
  2994. [[NCManageDatabase sharedInstance] clearDateReadWithServerUrl:_autoUploadDirectory directoryID:nil];
  2995. if (appDelegate.activeAccount.length > 0 && appDelegate.activePhotos)
  2996. [appDelegate.activePhotos reloadDatasourceForced];
  2997. [self readFolder:serverUrl];
  2998. NSLog(@"[LOG] Update Folder Photo");
  2999. NSString *autoUploadPath = [[NCManageDatabase sharedInstance] getAccountAutoUploadPath:appDelegate.activeUrl];
  3000. if ([autoUploadPath length] > 0) {
  3001. [[CCSynchronize sharedSynchronize] readFileForFolder:_metadata.fileName serverUrl:serverUrl selector:selectorReadFileFolder];
  3002. }
  3003. }];
  3004. }
  3005. if (!([_metadata.fileName isEqualToString:_autoUploadFileName] == YES && [serverUrl isEqualToString:_autoUploadDirectory] == YES)) {
  3006. [actionSheet addButtonWithTitle:titoloLock
  3007. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"settingsPasscodeYES"] color:[NCBrandColor sharedInstance].brandElement]
  3008. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3009. height:50.0
  3010. type:AHKActionSheetButtonTypeDefault
  3011. handler:^(AHKActionSheet *as) {
  3012. [self performSelector:@selector(comandoLockPassword) withObject:nil];
  3013. }];
  3014. }
  3015. if (!_metadata.e2eEncrypted) {
  3016. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_set_folder_encrypted_", nil)
  3017. image:[UIImage imageNamed:@"encrypted_empty"]
  3018. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3019. height:50.0
  3020. type:AHKActionSheetButtonTypeEncrypted
  3021. handler:^(AHKActionSheet *as) {
  3022. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3023. NSString *token;
  3024. 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];
  3025. dispatch_async(dispatch_get_main_queue(), ^{
  3026. if (error) {
  3027. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3028. } else {
  3029. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  3030. [self readFolder:self.serverUrl];
  3031. }
  3032. });
  3033. });
  3034. }];
  3035. }
  3036. if (_metadata.e2eEncrypted) {
  3037. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_encrypted_", nil)
  3038. image:[UIImage imageNamed:@"encrypted_empty"]
  3039. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3040. height:50.0
  3041. type:AHKActionSheetButtonTypeEncrypted
  3042. handler:^(AHKActionSheet *as) {
  3043. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3044. NSString *token;
  3045. 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];
  3046. dispatch_async(dispatch_get_main_queue(), ^{
  3047. if (error) {
  3048. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3049. } else {
  3050. [[NCManageDatabase sharedInstance] deleteE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, [NSString stringWithFormat:@"%@/%@", self.serverUrl, _metadata.fileName]]];
  3051. [self readFolder:self.serverUrl];
  3052. }
  3053. });
  3054. });
  3055. }];
  3056. }
  3057. if (directory.e2eTokenLock.length > 0) {
  3058. [actionSheet addButtonWithTitle:NSLocalizedString(@"_e2e_remove_folder_lock_", nil)
  3059. image:[UIImage imageNamed:@"encrypted_empty"]
  3060. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3061. height:50.0
  3062. type:AHKActionSheetButtonTypeEncrypted
  3063. handler:^(AHKActionSheet *as) {
  3064. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
  3065. NSError *error = [[NCNetworkingSync sharedManager] unlockEndToEndFolderEncrypted:appDelegate.activeUser userID:appDelegate.activeUserID password:appDelegate.activePassword url:appDelegate.activeUrl fileID:_metadata.fileID token:directory.e2eTokenLock];
  3066. if (error) {
  3067. dispatch_async(dispatch_get_main_queue(), ^{
  3068. [appDelegate messageNotification:@"_error_" description:[NSString stringWithFormat:@"%@ %d", error.localizedDescription, (int)error.code] visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeError errorCode:0];
  3069. });
  3070. }
  3071. });
  3072. }];
  3073. }
  3074. [actionSheet show];
  3075. }
  3076. // ******************************************* FILE *******************************************
  3077. if (!_metadata.directory) {
  3078. UIImage *iconHeader;
  3079. BOOL isFolderEncrypted = [CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount];
  3080. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3081. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]])
  3082. iconHeader = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, _metadata.fileID]];
  3083. else
  3084. iconHeader = [UIImage imageNamed:_metadata.iconName];
  3085. [actionSheet addButtonWithTitle: _metadata.fileNameView
  3086. image: iconHeader
  3087. backgroundColor: [NCBrandColor sharedInstance].tabBar
  3088. height: 50.0
  3089. type: AHKActionSheetButtonTypeDisabled
  3090. handler: nil
  3091. ];
  3092. if (!isFolderEncrypted) {
  3093. [actionSheet addButtonWithTitle:NSLocalizedString(@"_share_", nil)
  3094. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"]color:[NCBrandColor sharedInstance].brandElement]
  3095. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3096. height: 50.0
  3097. type:AHKActionSheetButtonTypeDefault
  3098. handler:^(AHKActionSheet *as) {
  3099. [self openWindowShare:_metadata];
  3100. }];
  3101. }
  3102. [actionSheet addButtonWithTitle:NSLocalizedString(@"_open_in_", nil)
  3103. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetOpenIn"] color:[NCBrandColor sharedInstance].brandElement]
  3104. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3105. height: 50.0
  3106. type:AHKActionSheetButtonTypeDefault
  3107. handler:^(AHKActionSheet *as) {
  3108. [self performSelector:@selector(openIn:) withObject:_metadata];
  3109. }];
  3110. [actionSheet addButtonWithTitle:NSLocalizedString(@"_rename_", nil)
  3111. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRename"] color:[NCBrandColor sharedInstance].brandElement]
  3112. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3113. height: 50.0
  3114. type:AHKActionSheetButtonTypeDefault
  3115. handler:^(AHKActionSheet *as) {
  3116. UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"_rename_",nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
  3117. [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  3118. textField.text = _metadata.fileNameView;
  3119. [textField addTarget:self action:@selector(minCharTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
  3120. }];
  3121. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_cancel_",nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  3122. NSLog(@"[LOG] Cancel action");
  3123. }];
  3124. UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"_ok_", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  3125. UITextField *fileName = alertController.textFields.firstObject;
  3126. [self performSelectorOnMainThread:@selector(renameFile:) withObject:[NSMutableArray arrayWithObjects:_metadata,fileName.text, nil] waitUntilDone:NO];
  3127. }];
  3128. okAction.enabled = NO;
  3129. [alertController addAction:cancelAction];
  3130. [alertController addAction:okAction];
  3131. [self presentViewController:alertController animated:YES completion:nil];
  3132. }];
  3133. if (!isFolderEncrypted) {
  3134. [actionSheet addButtonWithTitle:NSLocalizedString(@"_move_", nil)
  3135. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetMove"] color:[NCBrandColor sharedInstance].brandElement]
  3136. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3137. height:50.0
  3138. type:AHKActionSheetButtonTypeDefault
  3139. handler:^(AHKActionSheet *as) {
  3140. [self moveOpenWindow:[[NSArray alloc] initWithObjects:indexPath, nil]];
  3141. }];
  3142. }
  3143. if (localFile || [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3144. [actionSheet addButtonWithTitle:NSLocalizedString(@"_remove_local_file_", nil)
  3145. image:[CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetRemoveLocal"] color:[NCBrandColor sharedInstance].brandElement]
  3146. backgroundColor:[NCBrandColor sharedInstance].backgroundView
  3147. height:50.0
  3148. type:AHKActionSheetButtonTypeDefault
  3149. handler:^(AHKActionSheet *as) {
  3150. [self performSelector:@selector(removeLocalFile:) withObject:_metadata];
  3151. }];
  3152. }
  3153. [actionSheet show];
  3154. }
  3155. }
  3156. #pragma --------------------------------------------------------------------------------------------
  3157. #pragma mark - ==== Datasource ====
  3158. #pragma --------------------------------------------------------------------------------------------
  3159. - (void)clearDateReadDataSource:(NSNotification *)notification
  3160. {
  3161. _dateReadDataSource = Nil;
  3162. [self reloadDatasource];
  3163. }
  3164. - (void)reloadDatasource
  3165. {
  3166. [self reloadDatasource:_serverUrl];
  3167. }
  3168. - (void)reloadDatasource:(NSString *)serverUrl
  3169. {
  3170. // test
  3171. if (appDelegate.activeAccount.length == 0 || serverUrl.length == 0 || serverUrl == nil)
  3172. return;
  3173. // Search Mode
  3174. if (_isSearchMode) {
  3175. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:_searchResultMetadatas listProgressMetadata:nil e2eEncryptions:nil groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3176. [self tableViewReloadData];
  3177. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] >= k_minCharsSearch) {
  3178. _noFilesSearchTitle = NSLocalizedString(@"_search_no_record_found_", nil);
  3179. _noFilesSearchDescription = @"";
  3180. }
  3181. if ([_sectionDataSource.allRecordsDataSource count] == 0 && [_searchFileName length] < k_minCharsSearch) {
  3182. _noFilesSearchTitle = @"";
  3183. _noFilesSearchDescription = NSLocalizedString(@"_search_instruction_", nil);
  3184. }
  3185. [self.tableView reloadEmptyDataSet];
  3186. return;
  3187. }
  3188. // Reload -> Self se non siamo nella dir appropriata cercala e se è in memoria reindirizza il reload
  3189. if ([serverUrl isEqualToString:_serverUrl] == NO || _serverUrl == nil) {
  3190. CCMain *main = [appDelegate.listMainVC objectForKey:serverUrl];
  3191. if (main) {
  3192. [main reloadDatasource];
  3193. } else {
  3194. [self tableViewReloadData];
  3195. [appDelegate.activeTransfers reloadDatasource];
  3196. }
  3197. return;
  3198. }
  3199. [appDelegate.activeTransfers reloadDatasource];
  3200. // Settaggio variabili per le ottimizzazioni
  3201. _directoryGroupBy = [CCUtility getGroupBySettings];
  3202. _directoryOrder = [CCUtility getOrderSettings];
  3203. // Remove optimization for encrypted directory
  3204. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount])
  3205. _dateReadDataSource = nil;
  3206. // current directoryID
  3207. NSString *directoryID = [[NCManageDatabase sharedInstance] getDirectoryID:serverUrl];
  3208. // Controllo data lettura Data Source
  3209. tableDirectory *tableDirectory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3210. // Get MetadataFolder
  3211. _metadataFolder = [[NCManageDatabase sharedInstance] getMetadataWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileID = %@", appDelegate.activeAccount, tableDirectory.fileID]];
  3212. NSDate *dateDateRecordDirectory = tableDirectory.dateReadDirectory;
  3213. if ([dateDateRecordDirectory compare:_dateReadDataSource] == NSOrderedDescending || dateDateRecordDirectory == nil || _dateReadDataSource == nil) {
  3214. NSLog(@"[LOG] Rebuild Data Source File : %@", _serverUrl);
  3215. _dateReadDataSource = [NSDate date];
  3216. // Data Source
  3217. NSString *sorted = _directoryOrder;
  3218. if ([sorted isEqualToString:@"fileName"])
  3219. sorted = @"fileName";
  3220. if (directoryID) {
  3221. NSArray *recordsTableMetadata = [[NCManageDatabase sharedInstance] getMetadatasWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND directoryID = %@ AND status = %i", appDelegate.activeAccount, directoryID, k_metadataStatusNormal] sorted:sorted ascending:[CCUtility getAscendingSettings]];
  3222. NSArray *recordsTableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionsWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, serverUrl]];
  3223. _sectionDataSource = [CCSectionDataSourceMetadata new];
  3224. _sectionDataSource = [CCSectionMetadata creataDataSourseSectionMetadata:recordsTableMetadata listProgressMetadata:nil e2eEncryptions:recordsTableE2eEncryption groupByField:_directoryGroupBy activeAccount:appDelegate.activeAccount];
  3225. // get auto upload folder
  3226. _autoUploadFileName = [[NCManageDatabase sharedInstance] getAccountAutoUploadFileName];
  3227. _autoUploadDirectory = [[NCManageDatabase sharedInstance] getAccountAutoUploadDirectory:appDelegate.activeUrl];
  3228. }
  3229. } else {
  3230. NSLog(@"[LOG] [OPTIMIZATION] Rebuild Data Source File : %@ - %@", _serverUrl, _dateReadDataSource);
  3231. }
  3232. [self tableViewReloadData];
  3233. }
  3234. - (NSArray *)getMetadatasFromSelectedRows:(NSArray *)selectedRows
  3235. {
  3236. NSMutableArray *metadatas = [[NSMutableArray alloc] init];
  3237. if (selectedRows.count > 0) {
  3238. for (NSIndexPath *selectionIndex in selectedRows) {
  3239. NSString *fileID = [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:selectionIndex.section]] objectAtIndex:selectionIndex.row];
  3240. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3241. [metadatas addObject:metadata];
  3242. }
  3243. }
  3244. return metadatas;
  3245. }
  3246. - (tableMetadata *)getMetadataFromSectionDataSource:(NSIndexPath *)indexPath
  3247. {
  3248. NSInteger section = indexPath.section + 1;
  3249. NSInteger row = indexPath.row + 1;
  3250. NSInteger totSections = [_sectionDataSource.sections count] ;
  3251. if ((totSections < section) || (section > totSections)) {
  3252. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [0] : error section, totSections = %lu - section = %lu", (long)totSections, (long)section]);
  3253. return nil;
  3254. }
  3255. id valueSection = [_sectionDataSource.sections objectAtIndex:indexPath.section];
  3256. NSArray *fileIDs = [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3257. if (fileIDs) {
  3258. NSInteger totRows =[fileIDs count] ;
  3259. if ((totRows < row) || (row > totRows)) {
  3260. NSLog(@"[LOG] %@", [NSString stringWithFormat:@"DEBUG [1] : error row, totRows = %lu - row = %lu", (long)totRows, (long)row]);
  3261. return nil;
  3262. }
  3263. } else {
  3264. NSLog(@"[LOG] DEBUG [2] : fileIDs is NIL");
  3265. return nil;
  3266. }
  3267. NSString *fileID = [fileIDs objectAtIndex:indexPath.row];
  3268. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3269. return metadata;
  3270. }
  3271. - (NSArray *)getMetadatasFromSectionDataSource:(NSInteger)section
  3272. {
  3273. NSInteger totSections =[_sectionDataSource.sections count] ;
  3274. if ((totSections < (section + 1)) || ((section + 1) > totSections)) {
  3275. return nil;
  3276. }
  3277. id valueSection = [_sectionDataSource.sections objectAtIndex:section];
  3278. return [_sectionDataSource.sectionArrayRow objectForKey:valueSection];
  3279. }
  3280. #pragma --------------------------------------------------------------------------------------------
  3281. #pragma mark - ==== Table ====
  3282. #pragma --------------------------------------------------------------------------------------------
  3283. - (void)tableViewSelect:(BOOL)edit
  3284. {
  3285. // chiudiamo eventuali swipe aperti
  3286. if (edit)
  3287. [self.tableView setEditing:NO animated:NO];
  3288. [self.tableView setAllowsMultipleSelectionDuringEditing:edit];
  3289. [self.tableView setEditing:edit animated:YES];
  3290. _isSelectedMode = edit;
  3291. if (edit)
  3292. [self setUINavigationBarSelected];
  3293. else
  3294. [self setUINavigationBarDefault];
  3295. [_selectedFileIDsMetadatas removeAllObjects];
  3296. [self setTitle];
  3297. }
  3298. - (void)tableViewReloadData
  3299. {
  3300. // store selected cells before relod
  3301. NSArray *indexPaths = [self.tableView indexPathsForSelectedRows];
  3302. //store swipeOffset before relod
  3303. [_statusSwipeCell removeAllObjects];
  3304. for (MGSwipeTableCell *cell in self.tableView.visibleCells) {
  3305. NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
  3306. [_statusSwipeCell setObject:[NSNumber numberWithDouble:cell.swipeOffset] forKey:indexPath];
  3307. }
  3308. // reload table view
  3309. [self.tableView reloadData];
  3310. // selected cells stored
  3311. for (NSIndexPath *path in indexPaths)
  3312. [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
  3313. [self setTableViewFooter];
  3314. if (self.tableView.editing)
  3315. [self setTitle];
  3316. }
  3317. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
  3318. {
  3319. if (tableView.editing == 1) {
  3320. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3321. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3322. return NO;
  3323. if (metadata == nil || metadata.sessionTaskIdentifier != k_taskIdentifierDone)
  3324. return NO;
  3325. else
  3326. return YES;
  3327. } else {
  3328. [_selectedFileIDsMetadatas removeAllObjects];
  3329. }
  3330. return YES;
  3331. }
  3332. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  3333. {
  3334. return 60;
  3335. }
  3336. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  3337. {
  3338. return [[_sectionDataSource.sectionArrayRow allKeys] count];
  3339. }
  3340. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  3341. {
  3342. return [[_sectionDataSource.sectionArrayRow objectForKey:[_sectionDataSource.sections objectAtIndex:section]] count];
  3343. }
  3344. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
  3345. {
  3346. NSArray *sections = [_sectionDataSource.sectionArrayRow allKeys];
  3347. NSString *sectionTitle = [sections objectAtIndex:section];
  3348. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"download"].location != NSNotFound) return 18.f;
  3349. if ([sectionTitle isKindOfClass:[NSString class]] && [sectionTitle rangeOfString:@"upload"].location != NSNotFound) return 18.f;
  3350. if ([_directoryGroupBy isEqualToString:@"none"] && [sections count] <= 1) return 0.0f;
  3351. return 20.f;
  3352. }
  3353. -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
  3354. {
  3355. float shift;
  3356. UIVisualEffectView *visualEffectView;
  3357. NSString *titleSection;
  3358. if (![self indexPathIsValid:[NSIndexPath indexPathForRow:0 inSection:section]])
  3359. return nil;
  3360. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSString class]])
  3361. titleSection = [_sectionDataSource.sections objectAtIndex:section];
  3362. if ([[_sectionDataSource.sections objectAtIndex:section] isKindOfClass:[NSDate class]])
  3363. titleSection = [CCUtility getTitleSectionDate:[_sectionDataSource.sections objectAtIndex:section]];
  3364. if ([titleSection isEqualToString:@"_none_"]) titleSection = @"";
  3365. else if ([titleSection rangeOfString:@"download"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_download_",nil);
  3366. else if ([titleSection rangeOfString:@"upload"].location != NSNotFound) titleSection = NSLocalizedString(@"_title_section_upload_",nil);
  3367. else titleSection = NSLocalizedString(titleSection,nil);
  3368. // Format title
  3369. NSString *currentDevice = [CCUtility currentDevice];
  3370. if ([currentDevice rangeOfString:@"iPad3"].location != NSNotFound) {
  3371. visualEffectView = [[UIVisualEffectView alloc] init];
  3372. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.3];
  3373. } else {
  3374. UIVisualEffect *blurEffect;
  3375. blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
  3376. visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
  3377. visualEffectView.backgroundColor = [[NCBrandColor sharedInstance].brand colorWithAlphaComponent:0.2];
  3378. }
  3379. if ([_directoryGroupBy isEqualToString:@"alphabetic"]) {
  3380. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
  3381. shift = - 35;
  3382. else
  3383. shift = - 20;
  3384. } else shift = - 10;
  3385. // Title
  3386. UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, -12, 0, 44)];
  3387. titleLabel.backgroundColor = [UIColor clearColor];
  3388. titleLabel.textColor = [UIColor blackColor];
  3389. titleLabel.font = [UIFont systemFontOfSize:12];
  3390. titleLabel.textAlignment = NSTextAlignmentLeft;
  3391. titleLabel.text = titleSection;
  3392. titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3393. [visualEffectView.contentView addSubview:titleLabel];
  3394. // Elements
  3395. UILabel *elementLabel= [[UILabel alloc]initWithFrame:CGRectMake(shift, -12, 0, 44)];
  3396. elementLabel.backgroundColor = [UIColor clearColor];
  3397. elementLabel.textColor = [UIColor blackColor];;
  3398. elementLabel.font = [UIFont systemFontOfSize:12];
  3399. elementLabel.textAlignment = NSTextAlignmentRight;
  3400. elementLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
  3401. NSArray *metadatas = [self getMetadatasFromSectionDataSource:section];
  3402. NSUInteger rowsCount = [metadatas count];
  3403. if (rowsCount == 0) return nil;
  3404. if (rowsCount == 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_element_",nil)];
  3405. if (rowsCount > 1) elementLabel.text = [NSString stringWithFormat:@"%lu %@", (unsigned long)rowsCount, NSLocalizedString(@"_elements_",nil)];
  3406. [visualEffectView.contentView addSubview:elementLabel];
  3407. return visualEffectView;
  3408. }
  3409. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
  3410. {
  3411. return [_sectionDataSource.sections indexOfObject:title];
  3412. }
  3413. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
  3414. {
  3415. if ([_directoryGroupBy isEqualToString:@"alphabetic"])
  3416. return [[UILocalizedIndexedCollation currentCollation] sectionIndexTitles];
  3417. else
  3418. return nil;
  3419. }
  3420. /*
  3421. -(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3422. {
  3423. if([indexPath row] == ((NSIndexPath*)[[tableView indexPathsForVisibleRows] lastObject]).row){
  3424. }
  3425. }
  3426. */
  3427. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  3428. {
  3429. NSString *typeCell;
  3430. NSString *dataFile;
  3431. NSString *lunghezzaFile;
  3432. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3433. if (!metadata || [[NCManageDatabase sharedInstance] isTableInvalidated:metadata])
  3434. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3435. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:metadata.directoryID];
  3436. if (!serverUrl)
  3437. return [tableView dequeueReusableCellWithIdentifier:@"CellMain"];
  3438. if ([metadata.session isEqualToString:@""] || metadata.session == nil) typeCell = @"CellMain";
  3439. else typeCell = @"CellMainTransfer";
  3440. CCCellMainTransfer *cell = (CCCellMainTransfer *)[tableView dequeueReusableCellWithIdentifier:typeCell forIndexPath:indexPath];
  3441. // variable base
  3442. cell.delegate = self;
  3443. cell.indexPath = indexPath;
  3444. // separator
  3445. cell.separatorInset = UIEdgeInsetsMake(0.f, 60.f, 0.f, 0.f);
  3446. // change color selection
  3447. UIView *selectionColor = [[UIView alloc] init];
  3448. selectionColor.backgroundColor = [[NCBrandColor sharedInstance] getColorSelectBackgrond];
  3449. cell.selectedBackgroundView = selectionColor;
  3450. // for checkmark color in editing mode
  3451. cell.tintColor = [NCBrandColor sharedInstance].brandElement;
  3452. if ([typeCell isEqualToString:@"CellMain"]) cell.backgroundColor = [NCBrandColor sharedInstance].backgroundView;
  3453. if ([typeCell isEqualToString:@"CellMainTransfer"]) cell.backgroundColor = [NCBrandColor sharedInstance].transferBackground;
  3454. // ----------------------------------------------------------------------------------------------------------
  3455. // DEFAULT
  3456. // ----------------------------------------------------------------------------------------------------------
  3457. cell.file.image = nil;
  3458. cell.status.image = nil;
  3459. cell.favorite.image = nil;
  3460. cell.shared.image = nil;
  3461. cell.local.image = nil;
  3462. cell.labelTitle.enabled = YES;
  3463. cell.labelTitle.text = @"";
  3464. cell.labelInfoFile.enabled = YES;
  3465. cell.labelInfoFile.text = @"";
  3466. cell.progressView.progress = 0.0;
  3467. cell.progressView.hidden = YES;
  3468. cell.cancelTaskButton.hidden = YES;
  3469. cell.reloadTaskButton.hidden = YES;
  3470. cell.stopTaskButton.hidden = YES;
  3471. cell.labelTitle.textColor = [UIColor blackColor];
  3472. // ----------------------------------------------------------------------------------------------------------
  3473. // File Name & Folder
  3474. // ----------------------------------------------------------------------------------------------------------
  3475. // nome del file
  3476. cell.labelTitle.text = metadata.fileNameView;
  3477. // è una directory
  3478. if (metadata.directory) {
  3479. cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
  3480. cell.labelInfoFile.text = [CCUtility dateDiff:metadata.date];
  3481. lunghezzaFile = @" ";
  3482. // ----------------------------------------------------------------------------------------------------------
  3483. // Favorite Folder
  3484. // ----------------------------------------------------------------------------------------------------------
  3485. if (metadata.favorite) {
  3486. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3487. }
  3488. } else {
  3489. // File
  3490. dataFile = [CCUtility dateDiff:metadata.date];
  3491. lunghezzaFile = [CCUtility transformedSize:metadata.size];
  3492. tableLocalFile *localFile = [[NCManageDatabase sharedInstance] getTableLocalFileWithPredicate:[NSPredicate predicateWithFormat:@"fileID = %@", metadata.fileID]];
  3493. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  3494. [dateFormatter setDateStyle:NSDateFormatterShortStyle];
  3495. [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
  3496. if (localFile && [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, metadata.fileID]])
  3497. cell.local.image = [UIImage imageNamed:@"local"];
  3498. else
  3499. cell.local.image = nil;
  3500. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@ %@", dataFile, lunghezzaFile];
  3501. cell.accessoryType = UITableViewCellAccessoryNone;
  3502. }
  3503. // ----------------------------------------------------------------------------------------------------------
  3504. // File Image View
  3505. // ----------------------------------------------------------------------------------------------------------
  3506. // assegnamo l'immagine anteprima se esiste, altrimenti metti quella standars
  3507. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]]) {
  3508. cell.file.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]];
  3509. } else {
  3510. if (metadata.directory) {
  3511. if (metadata.e2eEncrypted)
  3512. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderEncrypted"] color:[NCBrandColor sharedInstance].brandElement];
  3513. else if ([metadata.fileName isEqualToString:_autoUploadFileName] && [self.serverUrl isEqualToString:_autoUploadDirectory])
  3514. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folderphotocamera"] color:[NCBrandColor sharedInstance].brandElement];
  3515. else
  3516. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder"] color:[NCBrandColor sharedInstance].brandElement];
  3517. } else {
  3518. cell.file.image = [UIImage imageNamed:metadata.iconName];
  3519. }
  3520. if (metadata.thumbnailExists && _metadataFolder.e2eEncrypted == NO)
  3521. [[CCActions sharedInstance] downloadTumbnail:metadata delegate:self];
  3522. }
  3523. // ----------------------------------------------------------------------------------------------------------
  3524. // Image Status Lock Passcode
  3525. // ----------------------------------------------------------------------------------------------------------
  3526. // Directory con passcode lock attivato
  3527. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:metadata.fileName];
  3528. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3529. if (metadata.directory && (directory.lock && [[CCUtility getBlockCode] length]))
  3530. cell.status.image = [UIImage imageNamed:@"passcode"];
  3531. // ----------------------------------------------------------------------------------------------------------
  3532. // E2E Image Status Encrypted
  3533. // ----------------------------------------------------------------------------------------------------------
  3534. if (_metadataFolder.e2eEncrypted && !metadata.directory) {
  3535. tableE2eEncryption *tableE2eEncryption = [[NCManageDatabase sharedInstance] getE2eEncryptionWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND fileNameIdentifier = %@", appDelegate.activeAccount, metadata.fileName]];
  3536. if (tableE2eEncryption)
  3537. cell.status.image = [UIImage imageNamed:@"encrypted"];
  3538. }
  3539. // ----------------------------------------------------------------------------------------------------------
  3540. // Favorite
  3541. // ----------------------------------------------------------------------------------------------------------
  3542. if (metadata.favorite) {
  3543. cell.favorite.image = [UIImage imageNamed:@"favorite"];
  3544. }
  3545. // ----------------------------------------------------------------------------------------------------------
  3546. // Share
  3547. // ----------------------------------------------------------------------------------------------------------
  3548. NSString *shareLink = [appDelegate.sharesLink objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3549. NSString *shareUserAndGroup = [appDelegate.sharesUserAndGroup objectForKey:[serverUrl stringByAppendingString:metadata.fileName]];
  3550. BOOL isShare = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_shared].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_shared].location == NSNotFound);
  3551. BOOL isMounted = ([metadata.permissions length] > 0) && ([metadata.permissions rangeOfString:k_permission_mounted].location != NSNotFound) && ([_fatherPermission rangeOfString:k_permission_mounted].location == NSNotFound);
  3552. // Aggiungiamo il Tap per le shared
  3553. if (isShare || [shareLink length] > 0 || [shareUserAndGroup length] > 0 || isMounted) {
  3554. // Shared with you
  3555. if (isShare) {
  3556. if (metadata.directory) {
  3557. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3558. cell.accessoryType = UITableViewCellAccessoryNone;
  3559. }
  3560. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3561. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3562. [tap setNumberOfTapsRequired:1];
  3563. cell.shared.userInteractionEnabled = YES;
  3564. [cell.shared addGestureRecognizer:tap];
  3565. }
  3566. // Mounted with you
  3567. if (isMounted) {
  3568. if (metadata.directory) {
  3569. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_external"] color:[NCBrandColor sharedInstance].brandElement];
  3570. cell.accessoryType = UITableViewCellAccessoryNone;
  3571. }
  3572. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareMounted"] color:[NCBrandColor sharedInstance].brandElement];
  3573. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionConnectionMounted:)];
  3574. [tap setNumberOfTapsRequired:1];
  3575. cell.shared.userInteractionEnabled = YES;
  3576. [cell.shared addGestureRecognizer:tap];
  3577. }
  3578. // You share
  3579. if ([shareLink length] > 0 || [shareUserAndGroup length] > 0) {
  3580. if (metadata.directory) {
  3581. if ([shareLink length] > 0)
  3582. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_public"] color:[NCBrandColor sharedInstance].brandElement];
  3583. if ([shareUserAndGroup length] > 0)
  3584. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"folder_shared_with_me"] color:[NCBrandColor sharedInstance].brandElement];
  3585. cell.shared.userInteractionEnabled = NO;
  3586. } else {
  3587. if ([shareLink length] > 0)
  3588. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"shareLink"] color:[NCBrandColor sharedInstance].brandElement];
  3589. if ([shareUserAndGroup length] > 0)
  3590. cell.shared.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"actionSheetShare"] color:[NCBrandColor sharedInstance].brandElement];
  3591. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapActionShared:)];
  3592. [tap setNumberOfTapsRequired:1];
  3593. cell.shared.userInteractionEnabled = YES;
  3594. [cell.shared addGestureRecognizer:tap];
  3595. }
  3596. }
  3597. } else {
  3598. cell.shared.userInteractionEnabled = NO;
  3599. }
  3600. // ----------------------------------------------------------------------------------------------------------
  3601. // downloadFile
  3602. // ----------------------------------------------------------------------------------------------------------
  3603. if ([metadata.session length] > 0 && [metadata.session containsString:@"download"]) {
  3604. cell.status.image = [UIImage imageNamed:@"statusdownload"];
  3605. // sessionTaskIdentifier : RELOAD + STOP
  3606. if (metadata.sessionTaskIdentifier != k_taskIdentifierDone) {
  3607. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3608. cell.cancelTaskButton.hidden = NO;
  3609. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3610. cell.reloadTaskButton.hidden = NO;
  3611. }
  3612. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3613. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3614. if (progress > 0) {
  3615. cell.progressView.progressTintColor = [UIColor blackColor];
  3616. cell.progressView.progress = progress;
  3617. cell.progressView.hidden = NO;
  3618. }
  3619. // ----------------------------------------------------------------------------------------------------------
  3620. // downloadFile Error
  3621. // ----------------------------------------------------------------------------------------------------------
  3622. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3623. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3624. if ([metadata.sessionError length] == 0) {
  3625. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_downloaded_",nil)];
  3626. } else {
  3627. cell.labelInfoFile.text = metadata.sessionError;
  3628. }
  3629. }
  3630. }
  3631. // ----------------------------------------------------------------------------------------------------------
  3632. // uploadFile
  3633. // ----------------------------------------------------------------------------------------------------------
  3634. if ([metadata.session length] > 0 && [metadata.session rangeOfString:@"upload"].location != NSNotFound) {
  3635. cell.status.image = [UIImage imageNamed:@"statusupload"];
  3636. [cell.cancelTaskButton setBackgroundImage:[UIImage imageNamed:@"removetask"] forState:UIControlStateNormal];
  3637. cell.cancelTaskButton.hidden = NO;
  3638. if (metadata.sessionTaskIdentifier == k_taskIdentifierStop) {
  3639. [cell.reloadTaskButton setBackgroundImage:[UIImage imageNamed:@"reloadtask"] forState:UIControlStateNormal];
  3640. cell.status.image = [UIImage imageNamed:@"statusstop"];
  3641. cell.reloadTaskButton.hidden = NO;
  3642. cell.stopTaskButton.hidden = YES;
  3643. } else {
  3644. [cell.stopTaskButton setBackgroundImage:[UIImage imageNamed:@"stoptask"] forState:UIControlStateNormal];
  3645. cell.stopTaskButton.hidden = NO;
  3646. cell.reloadTaskButton.hidden = YES;
  3647. }
  3648. // se non c'è una preview in bianconero metti l'immagine di default
  3649. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@.ico", appDelegate.directoryUser, metadata.fileID]] == NO)
  3650. cell.file.image = [CCGraphics changeThemingColorImage:[UIImage imageNamed:@"uploaddisable"] color:[NCBrandColor sharedInstance].brandElement];
  3651. cell.labelTitle.enabled = NO;
  3652. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@", lunghezzaFile];
  3653. float progress = [[appDelegate.listProgressMetadata objectForKey:metadata.fileID] floatValue];
  3654. if (progress > 0) {
  3655. cell.progressView.progressTintColor = [UIColor blackColor];
  3656. cell.progressView.progress = progress;
  3657. cell.progressView.hidden = NO;
  3658. }
  3659. // ----------------------------------------------------------------------------------------------------------
  3660. // uploadFileError
  3661. // ----------------------------------------------------------------------------------------------------------
  3662. if (metadata.sessionTaskIdentifier == k_taskIdentifierError) {
  3663. cell.labelTitle.enabled = NO;
  3664. cell.status.image = [UIImage imageNamed:@"statuserror"];
  3665. if ([metadata.sessionError length] == 0) {
  3666. cell.labelInfoFile.text = [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"_error_",nil), NSLocalizedString(@"_file_not_uploaded_",nil)];
  3667. } else {
  3668. cell.labelInfoFile.text = metadata.sessionError;
  3669. }
  3670. }
  3671. }
  3672. [cell.reloadTaskButton addTarget:self action:@selector(reloadTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3673. [cell.cancelTaskButton addTarget:self action:@selector(cancelTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3674. [cell.stopTaskButton addTarget:self action:@selector(stopTaskButton:withEvent:) forControlEvents:UIControlEventTouchUpInside];
  3675. // ======== MGSwipe ========
  3676. if (metadata.favorite)
  3677. 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]];
  3678. else
  3679. 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]];
  3680. cell.leftExpansion.buttonIndex = 0;
  3681. cell.leftExpansion.fillOnTrigger = NO;
  3682. //centerIconOverText
  3683. MGSwipeButton *favoriteButton = (MGSwipeButton *)[cell.leftButtons objectAtIndex:0];
  3684. [favoriteButton centerIconOverText];
  3685. //Right
  3686. cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"swipeDelete"] backgroundColor:[UIColor redColor]], [MGSwipeButton buttonWithTitle:@"" icon:[UIImage imageNamed:@"swipeMore"] backgroundColor:[UIColor lightGrayColor] padding:25]];
  3687. cell.rightSwipeSettings.transition = MGSwipeTransitionBorder;
  3688. //centerIconOverText
  3689. MGSwipeButton *deleteButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:0];
  3690. MGSwipeButton *moreButton = (MGSwipeButton *)[cell.rightButtons objectAtIndex:1];
  3691. [deleteButton centerIconOverText];
  3692. [moreButton centerIconOverText];
  3693. //restore swipeOffset after relod
  3694. CGFloat swipeOffset = [[_statusSwipeCell objectForKey:indexPath] doubleValue];
  3695. if (swipeOffset < 0) {
  3696. [cell showSwipe:MGSwipeDirectionRightToLeft animated:NO];
  3697. [_statusSwipeCell removeObjectForKey:indexPath];
  3698. } else if (swipeOffset > 0) {
  3699. [cell showSwipe:MGSwipeDirectionLeftToRight animated:NO];
  3700. [_statusSwipeCell removeObjectForKey:indexPath];
  3701. }
  3702. return cell;
  3703. }
  3704. - (void)setTableViewFooter
  3705. {
  3706. UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3707. [footerView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3708. UILabel *footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
  3709. [footerLabel setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
  3710. UIFont *appFont = [UIFont systemFontOfSize:12];
  3711. footerLabel.font = appFont;
  3712. footerLabel.textColor = [UIColor grayColor];
  3713. footerLabel.backgroundColor = [UIColor clearColor];
  3714. footerLabel.textAlignment = NSTextAlignmentCenter;
  3715. NSString *folders;
  3716. NSString *files;
  3717. NSString *footerText;
  3718. if (_sectionDataSource.directories > 1) {
  3719. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folders_", nil)];
  3720. } else if (_sectionDataSource.directories == 1){
  3721. folders = [NSString stringWithFormat:@"%ld %@", (long)_sectionDataSource.directories, NSLocalizedString(@"_folder_", nil)];
  3722. } else {
  3723. folders = @"";
  3724. }
  3725. if (_sectionDataSource.files > 1) {
  3726. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_files_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3727. } else if (_sectionDataSource.files == 1){
  3728. files = [NSString stringWithFormat:@"%ld %@ %@", (long)_sectionDataSource.files, NSLocalizedString(@"_file_", nil), [CCUtility transformedSize:_sectionDataSource.totalSize]];
  3729. } else {
  3730. files = @"";
  3731. }
  3732. if ([folders isEqualToString:@""]) {
  3733. footerText = files;
  3734. } else if ([files isEqualToString:@""]) {
  3735. footerText = folders;
  3736. } else {
  3737. footerText = [NSString stringWithFormat:@"%@, %@", folders, files];
  3738. }
  3739. footerLabel.text = footerText;
  3740. [footerView addSubview:footerLabel];
  3741. [self.tableView setTableFooterView:footerView];
  3742. }
  3743. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  3744. {
  3745. UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
  3746. // settiamo il record file.
  3747. _metadata = [self getMetadataFromSectionDataSource:indexPath];
  3748. if (!_metadata)
  3749. return;
  3750. // se non può essere selezionata deseleziona
  3751. if ([cell isEditing] == NO)
  3752. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  3753. // se siamo in modalità editing impostiamo il titolo dei selezioati e usciamo subito
  3754. if (self.tableView.editing) {
  3755. [_selectedFileIDsMetadatas setObject:_metadata forKey:_metadata.fileID];
  3756. [self setTitle];
  3757. return;
  3758. }
  3759. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3760. if (!serverUrl) return;
  3761. // se è in corso una sessione
  3762. if ([_metadata.session length] > 0) return;
  3763. // file
  3764. if (_metadata.directory == NO) {
  3765. // se il file esiste andiamo direttamente al delegato altrimenti carichiamolo
  3766. if ([[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithFormat:@"%@/%@", appDelegate.directoryUser, _metadata.fileID]]) {
  3767. [self downloadFileSuccessFailure:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:@"" errorMessage:@"" errorCode:0];
  3768. } else {
  3769. if ([CCUtility isFolderEncrypted:self.serverUrl account:appDelegate.activeAccount] && ![CCUtility isEndToEndEnabled:appDelegate.activeAccount]) {
  3770. [appDelegate messageNotification:@"_info_" description:@"_e2e_goto_settings_for_enable_" visible:YES delay:k_dismissAfterSecond type:TWMessageBarMessageTypeInfo errorCode:0];
  3771. } else {
  3772. [[CCNetworking sharedNetworking] downloadFile:_metadata.fileName fileID:_metadata.fileID serverUrl:serverUrl selector:selectorLoadFileView selectorPost:nil session:k_download_session taskStatus:k_taskStatusResume delegate:self];
  3773. NSIndexPath *indexPath = [_sectionDataSource.fileIDIndexPath objectForKey:_metadata.fileID];
  3774. if (indexPath) [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
  3775. }
  3776. }
  3777. }
  3778. if (_metadata.directory) [self performSegueDirectoryWithControlPasscode:true];
  3779. }
  3780. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
  3781. {
  3782. tableMetadata *metadata = [self getMetadataFromSectionDataSource:indexPath];
  3783. [_selectedFileIDsMetadatas removeObjectForKey:metadata.fileID];
  3784. [self setTitle];
  3785. }
  3786. - (BOOL)indexPathIsValid:(NSIndexPath *)indexPath
  3787. {
  3788. if (!indexPath)
  3789. return NO;
  3790. NSInteger section = indexPath.section;
  3791. NSInteger row = indexPath.row;
  3792. NSInteger lastSectionIndex = [self numberOfSectionsInTableView:self.tableView] - 1;
  3793. if (section > lastSectionIndex || lastSectionIndex < 0)
  3794. return NO;
  3795. NSInteger rowCount = [self.tableView numberOfRowsInSection:indexPath.section] - 1;
  3796. if (rowCount < 0)
  3797. return NO;
  3798. return row <= rowCount;
  3799. }
  3800. #pragma --------------------------------------------------------------------------------------------
  3801. #pragma mark ===== Navigation ====
  3802. #pragma --------------------------------------------------------------------------------------------
  3803. - (BOOL)shouldPerformSegue
  3804. {
  3805. // if background return
  3806. if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateBackground) return NO;
  3807. if (self.view.window == NO)
  3808. return NO;
  3809. // Collapsed ma siamo già in detail esci
  3810. if (self.splitViewController.isCollapsed)
  3811. if (_detailViewController.isViewLoaded && _detailViewController.view.window) return NO;
  3812. return YES;
  3813. }
  3814. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
  3815. {
  3816. id viewController = segue.destinationViewController;
  3817. NSMutableArray *allRecordsDataSourceImagesVideos = [NSMutableArray new];
  3818. tableMetadata *metadata;
  3819. if ([viewController isKindOfClass:[UINavigationController class]]) {
  3820. UINavigationController *nav = viewController;
  3821. _detailViewController = (CCDetail *)nav.topViewController;
  3822. } else {
  3823. _detailViewController = segue.destinationViewController;
  3824. }
  3825. if ([sender isKindOfClass:[tableMetadata class]]) {
  3826. metadata = sender;
  3827. [allRecordsDataSourceImagesVideos addObject:sender];
  3828. } else {
  3829. metadata = _metadata;
  3830. for (NSString *fileID in _sectionDataSource.allEtag) {
  3831. tableMetadata *metadata = [_sectionDataSource.allRecordsDataSource objectForKey:fileID];
  3832. if ([metadata.typeFile isEqualToString: k_metadataTypeFile_image] || [metadata.typeFile isEqualToString: k_metadataTypeFile_video] || [metadata.typeFile isEqualToString: k_metadataTypeFile_audio])
  3833. [allRecordsDataSourceImagesVideos addObject:metadata];
  3834. }
  3835. }
  3836. _detailViewController.metadataDetail = metadata;
  3837. _detailViewController.dataSourceImagesVideos = allRecordsDataSourceImagesVideos;
  3838. _detailViewController.dateFilterQuery = nil;
  3839. [_detailViewController setTitle:metadata.fileName];
  3840. }
  3841. // can i go to next viewcontroller
  3842. - (void)performSegueDirectoryWithControlPasscode:(BOOL)controlPasscode
  3843. {
  3844. NSString *nomeDir;
  3845. if(self.tableView.editing == NO) {
  3846. NSString *serverUrl = [[NCManageDatabase sharedInstance] getServerUrl:_metadata.directoryID];
  3847. if (!serverUrl) return;
  3848. NSString *lockServerUrl = [CCUtility stringAppendServerUrl:serverUrl addFileName:_metadata.fileName];
  3849. tableDirectory *directory = [[NCManageDatabase sharedInstance] getTableDirectoryWithPredicate:[NSPredicate predicateWithFormat:@"account = %@ AND serverUrl = %@", appDelegate.activeAccount, lockServerUrl]];
  3850. // 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
  3851. if (directory.lock && [[CCUtility getBlockCode] length] && appDelegate.sessionePasscodeLock == nil && controlPasscode) {
  3852. CCBKPasscode *viewController = [[CCBKPasscode alloc] initWithNibName:nil bundle:nil];
  3853. viewController.delegate = self;
  3854. viewController.fromType = CCBKPasscodeFromLockDirectory;
  3855. viewController.type = BKPasscodeViewControllerCheckPasscodeType;
  3856. viewController.inputViewTitlePassword = YES;
  3857. if ([CCUtility getSimplyBlockCode]) {
  3858. viewController.passcodeStyle = BKPasscodeInputViewNumericPasscodeStyle;
  3859. viewController.passcodeInputView.maximumLength = 6;
  3860. } else {
  3861. viewController.passcodeStyle = BKPasscodeInputViewNormalPasscodeStyle;
  3862. viewController.passcodeInputView.maximumLength = 64;
  3863. }
  3864. BKTouchIDManager *touchIDManager = [[BKTouchIDManager alloc] initWithKeychainServiceName:k_serviceShareKeyChain];
  3865. touchIDManager.promptText = NSLocalizedString(@"_scan_fingerprint_", nil);
  3866. viewController.touchIDManager = touchIDManager;
  3867. viewController.title = NSLocalizedString(@"_folder_blocked_", nil);
  3868. viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(passcodeViewCloseButtonPressed:)];
  3869. viewController.navigationItem.leftBarButtonItem.tintColor = [UIColor blackColor];
  3870. UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
  3871. [self presentViewController:navController animated:YES completion:nil];
  3872. return;
  3873. }
  3874. nomeDir = _metadata.fileName;
  3875. NSString *serverUrlPush = [CCUtility stringAppendServerUrl:serverUrl addFileName:nomeDir];
  3876. CCMain *viewController = [appDelegate.listMainVC objectForKey:serverUrlPush];
  3877. if (!viewController) {
  3878. viewController = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"CCMain"];
  3879. viewController.serverUrl = serverUrlPush;
  3880. viewController.titleMain = _metadata.fileName;
  3881. viewController.textBackButton = _titleMain;
  3882. // save self
  3883. [appDelegate.listMainVC setObject:viewController forKey:serverUrlPush];
  3884. [self.navigationController pushViewController:viewController animated:YES];
  3885. } else {
  3886. if (viewController.isViewLoaded) {
  3887. // Fix : Application tried to present modally an active controller
  3888. if ([self.navigationController isBeingPresented]) {
  3889. // being presented
  3890. } else if ([self.navigationController isMovingToParentViewController]) {
  3891. // being pushed
  3892. } else {
  3893. [self.navigationController pushViewController:viewController animated:YES];
  3894. }
  3895. }
  3896. }
  3897. }
  3898. }
  3899. @end