CCMain.m 231 KB

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