CCMain.m 233 KB

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