CCMain.m 220 KB

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