CCMain.m 233 KB

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