CCMain.m 222 KB

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