CCMain.m 222 KB

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