CCMain.m 221 KB

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