CCMain.m 230 KB

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