CCMain.m 218 KB

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