CCMain.m 232 KB

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