CCMain.m 221 KB

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