CCMain.m 222 KB

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