CCMain.m 223 KB

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