CCMain.m 222 KB

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