CCMain.m 227 KB

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