private void _bCountMessage_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); // Get a news group on the server NewsGroup group = nntp.SelectGroup(_tbNewsgroup.Text); // Display the message count. string.Format("Message Count: {0}", group.ArticleCount.ToString()); } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private void btnRetreive_Click(object sender, EventArgs e) { //Retrieve newsgroup entries btnRetreive.Enabled = false; try { NntpClient nntp = new NntpClient(); nntp.Connect(txtServer.Text); NewsGroup group = nntp.SelectGroup(txtnews.Text); //Display the listView1 of entries received for (int i = 0; i < 10; i++) { try { listView1.Items.Add(new ListViewItem(group.RetrieveHeaderObject().Subject)); group.Next(); } catch { } } nntp.Disconnect(); } finally { btnRetreive.Enabled = true; } }
public bool Execute(NntpClient context) { using (var response = context.PerformRequest(new NntpRequest(NntpCommand.ModeReader, false))) { return response.ResponseCode == NntpResponseCode.ServerReadyPostingAllowed || response.ResponseCode == NntpResponseCode.ServerReadyNoPostingAllowed; } }
private static void TestNewGroups(NntpClient client) { // get new groups foreach (NntpGroup g in client.NewGroups(DateTimeOffset.Now.AddYears(-10)).Groups) { Console.WriteLine($"{g.Name} {g.LowWaterMark} {g.HighWaterMark} {g.ArticleCount}"); } }
private static void TestListCounts(NntpClient client) { // list counts foreach (NntpGroup g in client.ListCounts("*.recovery").Groups) { Console.WriteLine($"{g.Name} {g.LowWaterMark} {g.HighWaterMark} {g.ArticleCount} {g.PostingStatus}"); } }
internal NewsGroup(string name, int firstArticle, int lastArticle, bool postingAllowed, NntpClient nntp) { Name = name; FirstArticle = firstArticle; LastArticle = lastArticle; PostingAllowed = postingAllowed; _nntp = nntp; }
public bool Execute(NntpClient context) { using (var response = context.PerformRequest(new NntpRequest(NntpCommand.Group, false, _group))) { var success = response.ResponseCode == NntpResponseCode.NflsGroupSelected; if (success) Group = new Group(response); return success; } }
public bool Execute(NntpClient context) { using (var response = context.PerformRequest(new NntpRequest(NntpCommand.Stat, false, _articleId.ToString()))) { var success = response.ResponseCode == NntpResponseCode.ArticleRetrievedRequestTextSeparately; if (success) Stat = new Stat(response); return success; } }
private void _bRetrieveSpecificMessage_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); // Get a news group on the server NewsGroup group = nntp.SelectGroup(_tbNewsgroup.Text); if (group.ArticleCount > 0) { for (int i = 1; i < group.ArticleCount + 1; i++) { ActiveUp.Net.Mail.Message message = group.RetrieveArticleObject(i); ListViewItem lvi = new ListViewItem(); lvi.Text = i.ToString("0000"); lvi.SubItems.AddRange(new string[] { message.Subject }); lvi.Tag = message; _lvMessages.Items.Add(lvi); this.AddLogEntry(string.Format("{1} Subject: {0}" , message.Subject, i.ToString("0000"))); } } else { this.AddLogEntry("There is no message in the newsgroup."); } } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private static void TestArticle(NntpClient client, NntpGroup @group) { // get article by message id ShowArticle(client.Article("<*****@*****.**>").Article); // select group alt.test.clienttest with article numbers ShowGroup(client.ListGroup("alt.test.clienttest").Group); // get first article in group ShowArticle(client.Article().Article); // get last article in group ShowArticle(client.Article(@group.HighWaterMark).Article); }
private static void TestListActiveTimes(NntpClient client) { // list active.times with wildmat foreach (NntpGroupOrigin groupOrigin in client.ListActiveTimes("*.recovery").GroupOrigins) { Console.WriteLine($"{groupOrigin.Name} {groupOrigin.CreatedAt} {groupOrigin.CreatedBy}"); } // list active.times foreach (NntpGroupOrigin groupOrigin in client.ListActiveTimes().GroupOrigins) { Console.WriteLine($"{groupOrigin.Name} {groupOrigin.CreatedAt} {groupOrigin.CreatedBy}"); } }
private static void TestDownloadNzbStreaming(NntpClient client, string nzbFileName) { string fullPath = Path.Combine(nzbFileName); string nzbData = File.ReadAllText(fullPath, UsenetEncoding.Default); NzbDocument nzbDocument = NzbParser.Parse(nzbData); string downloadDir = Path.Combine("downloads", nzbFileName); Directory.CreateDirectory(downloadDir); var sw = new Stopwatch(); sw.Restart(); log.LogInformation("Downloading nzb {nzbFileName}", nzbFileName); foreach (NzbFile file in nzbDocument.Files) { log.LogInformation("Downloading file {subject}", file.Subject); foreach (NzbSegment segment in file.Segments) { log.LogInformation("Downloading article {messageId}", segment.MessageId); NntpArticleResponse response = client.Article(segment.MessageId); using (YencStream yencStream = YencStreamDecoder.Decode(response.Article.Body)) { YencHeader header = yencStream.Header; string fileName = Path.Combine(downloadDir, header.FileName); if (!File.Exists(fileName)) { log.LogInformation("Creating file {fileName}", fileName); // create file and pre-allocate disk space for it using (FileStream stream = File.Create(fileName)) { stream.SetLength(header.FileSize); } } log.LogInformation("Writing {size} bytes to file {fileName} at offset {offset}", header.PartSize, fileName, header.PartOffset); using (FileStream stream = File.Open( fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite)) { stream.Seek(header.PartOffset, SeekOrigin.Begin); yencStream.CopyTo(stream); } } } } log.LogInformation("Nzb downloaded in {elapsed}", sw.Elapsed); }
private static void TestDecompression(NntpClient client, NntpGroup @group) { // enable gzip client.XfeatureCompressGzip(false); // xzhdr ShowLines(client.Xzhdr("Subject", @group.LowWaterMark, @group.HighWaterMark).Lines); // xzver ShowLines(client.Xzver(@group.HighWaterMark, @group.HighWaterMark).Lines); //TestListDistributions(client); TestListActive(client); //TestNewGroups(client); }
public bool Execute(NntpClient context) { using (var authUserResponse = context.PerformRequest(new NntpRequest(NntpCommand.AuthUser, false, _username))) { if (authUserResponse.ResponseCode != NntpResponseCode.MoreAuthenticationInformationRequired) return false; using (var authPassResponse = context.PerformRequest(new NntpRequest(NntpCommand.AuthPass, false, _password))) { if (authPassResponse.ResponseCode != NntpResponseCode.AuthenticationAccepted) return false; return true; } } }
private static void TestListActive(NntpClient client) { Console.WriteLine("Number of groups: " + client.ListActive().Groups.Count()); //// list active //foreach (NntpGroup g in client.ListActive2().Groups) //{ // Console.WriteLine($"{g.Name} {g.LowWaterMark} {g.HighWaterMark} {g.ArticleCount}"); //} //// list active with wildmat //foreach (NntpGroup g in client.ListActive("*.recovery").Groups) //{ // Console.WriteLine($"{g.Name} {g.LowWaterMark} {g.HighWaterMark} {g.ArticleCount}"); //} }
private void _bRetrieveMessageList_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); // Get a news group on the server NewsGroup group = nntp.SelectGroup(_tbNewsgroup.Text); //Retrive the article and display the subject MessageCollection mc = new MessageCollection(); for (int n = 0; n < group.ArticleCount; n++) { ActiveUp.Net.Mail.Message message = group.RetrieveArticleObject(n); mc.Add(message); this.AddLogEntry(string.Format("Subject : {0}", message.Subject)); } //mc will contain the list of messages } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private void btnRetreive_Click(object sender, EventArgs e) { NntpClient nntp = new NntpClient(); nntp.Connect(txtServer.Text); NewsGroup group = nntp.SelectGroup(txtnews.Text); for (int i = 0; i < 10; i++) { try { listView1.Items.Add(new ListViewItem(group.RetrieveHeaderObject().Subject)); group.Next(); } catch { } } nntp.Disconnect(); }
private void _bNewMessages_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); // Get a news group on the server // Gets article ids that belong to the "myhost.info" newsgroup and have been added less than one month ago. string[] newids = nntp.GetNewArticleIds(_tbNewsgroup.Text, System.DateTime.Now.AddMonths(-1)); // We get each article as an object. foreach (string articleId in newids) { ActiveUp.Net.Mail.Message message = nntp.RetrieveArticleObject(articleId); //Display the subject. this.AddLogEntry(string.Format("Subject : {0}", message.Subject)); } } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private static async Task<NntpClient> ConnectAsync(Server server) { // connect to nntp server var client = new NntpClient(new NntpConnection()); //var client = new NntpClient(new Usenet.Nntp.Experimental.NntpConnection()); if (!await client.ConnectAsync(server.Hostname, server.Port, server.UseSsl)) { Console.WriteLine("Failed to connect."); return null; } // authenticate if (!server.NeedsAuthentication || Authenticate(client, server.Username, server.Password)) { return client; } Console.WriteLine("Login failed, bye."); client.Quit(); return null; }
private static bool Authenticate(NntpClient client, string username, string password) { // try to authenticate with username and password from options if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(password) && client.Authenticate(username, password)) { return true; } // get password and username if not provided in options for (var tries = 3; tries > 0; tries--) { // get username string defaultUsername = string.IsNullOrWhiteSpace(username) ? null : $"[default = {username}]"; Console.Write($"Username{defaultUsername}: "); string userName = Console.ReadLine(); if (!string.IsNullOrWhiteSpace(userName)) { username = userName; } if (string.IsNullOrWhiteSpace(username)) { return false; } // get password Console.Write("Password: "******"Invalid credentials."); } return false; }
public bool Execute(NntpClient context) { using (var response = context.PerformRequest(new NntpRequest(NntpCommand.Quit, false))) { var success = response.ResponseCode == NntpResponseCode.ClosingConnection; if (success) { try { var statusLine = response.StatusLine; var parts = statusLine.Split(new[] { ' ' }, 2); Message = parts[1]; } catch (Exception) { //Ignore parse errors, server is what matters } } return success; } }
private static string TestPost(NntpClient client) { string messageId = $"cucumber_{Guid.NewGuid()}@hhh.net"; NntpArticle newArticle = new NntpArticleBuilder() .SetMessageId(messageId) .SetFrom("Superuser <*****@*****.**>") .SetSubject(messageId) .AddGroup("alt.test.clienttest") .AddGroup("alt.test") .AddLine("This is a message with id " + messageId) .AddLine("bla bla bla") .Build(); // post client.Post(newArticle); // read back and show ShowArticle(client.Article(messageId).Article); return messageId; }
private void _bRetrieveAllNewsgroup_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); //Get the news group on the server NewsGroupCollection groups = nntp.GetNewsGroups(); foreach (NewsGroup group in groups) { this.AddLogEntry(string.Format("Group name : {0}", group.Name)); } } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private void _bPostMessage_Click(object sender, EventArgs e) { // We create nntp client object. NntpClient nntp = new NntpClient(); try { // We connect to the nntp server. nntp.Connect(_tbNntpServer.Text); // We create the message to post. ActiveUp.Net.Mail.Message msg = new ActiveUp.Net.Mail.Message(); msg.Subject = _tbSubject.Text; msg.BodyText.Text = _tbBody.Text; msg.To.Add(_tbNewsgroup.Text); nntp.Post(msg); } catch (NntpException pexp) { this.AddLogEntry(string.Format("Nntp Error: {0}", pexp.Message)); } catch (Exception ex) { this.AddLogEntry(string.Format("Failed: {0}", ex.Message)); } finally { if (nntp.IsConnected) { nntp.Disconnect();; } } }
private static void TestXhdr(NntpClient client, NntpGroup group) { // xhdr ShowLines(client.Xhdr("Subject", NntpArticleRange.Range(group.HighWaterMark, group.HighWaterMark)).Lines); }
private static void TestXover(NntpClient client, NntpGroup group) { // xover ShowLines(client.Xover(NntpArticleRange.Range(group.HighWaterMark, group.HighWaterMark)).Lines); }
private static void TestListHeaders(NntpClient client) { // list headers ShowLines(client.ListHeaders().Lines); }
private static void TestListDistribPats(NntpClient client) { // list distrib.pats ShowLines(client.ListDistribPats().Lines); }
static void Main(string[] args) { var host = args.Length > 0 ? args[0] : "news.fysh.org"; Console.WriteLine("Hello World!"); var cts = new CancellationTokenSource(); var client = new NntpClient(); try { Console.WriteLine($"Connecting to {host}..."); var connectTask = client.ConnectAsync(host).Result; if (connectTask.IsCommandError || connectTask.IsServerError) { // Following a 400 or 502 response, the server MUST immediately close the connection. var quitAbortiveResult = client.DisconnectAsync().Result; Console.Out.WriteLine($"Closed connection: {quitAbortiveResult}"); return; } Console.WriteLine($"Connected to {host}"); Console.WriteLine($"\r\nRetrieving server capabilities"); var caps = client.GetCapabilitiesAsync(cts.Token).Result; foreach (var cap in caps) { Console.WriteLine($"\t{cap}"); } var sasl = client.AuthenticateSaslPlainAsync("john", "doe", cts.Token).Result; var date = client.DateAsync(cts.Token).Result; Console.WriteLine($"Server date: {date.DateTime}"); var newsgroups = client.GetNewsgroupsListAsync(cts.Token).Result; Console.WriteLine($"\r\nGroups count={newsgroups.Count}"); foreach (var ng in newsgroups) { Console.WriteLine($"\t{ng}"); } Console.WriteLine($"\r\nRetrieving news..."); foreach (var ng in newsgroups) { Console.WriteLine($"\tGroup summary for {ng}"); var group = client.GetGroupAsync(ng, cts.Token).Result; Console.WriteLine($"\t\tEstimated article count: {group.EstimatedArticleCount}"); Console.WriteLine($"\t\tLow watermark: {group.LowWatermark}"); Console.WriteLine($"\t\tHigh watermark: {group.HighWatermark}"); if (group.HighWatermark == group.LowWatermark - 1) { Console.WriteLine("\t\t--- EMPTY GROUP WITH NO ARTICLES ---"); } else { var groupList = client.GetGroupListAsync(ng, null, null, cts.Token).Result; Console.WriteLine($"\t\tLISTGROUP also called low {groupList.LowWatermark}~={group.LowWatermark}"); Console.WriteLine($"\tNews for {ng}"); var overResponse = client.OverAsync(group.LowWatermark, group.HighWatermark, cts.Token).Result; Console.Write($"\t\tArticle count={overResponse.Count}"); foreach (var over in overResponse.Take(2)) { Console.WriteLine($"\t\t#{over.ArticleNumber}: {over.Subject}"); var articleByNumber = client.ArticleAsync(over.ArticleNumber, cts.Token).Result; Console.WriteLine($"\t\t\t({articleByNumber.Code}) ARTICLE:\r\n{articleByNumber.Lines.Take(50).Aggregate((c, n) => c + "\r\n\t\t\t" + n)}"); var headers = articleByNumber.GetHeaders(); var messageId = articleByNumber.GetHeaderValues("Message-ID").FirstOrDefault(); var articleByMessageId = client.ArticleAsync(messageId, cts.Token).Result; Console.WriteLine($"\t\t\t\t({articleByMessageId.Code}) ARTICLE: {articleByNumber.Lines.Take(5).Aggregate((c, n) => c + "\r\n\t\t\t" + n)}"); var articleCurrent = client.ArticleAsync(cts.Token).Result; var messageIdCurrent = articleCurrent.GetHeaderValues("Message-ID").FirstOrDefault(); var stat = client.StatAsync(over.ArticleNumber, cts.Token).Result; Console.WriteLine($"\t\t\t\tArticle-Num={messageId} ~= Article-Current={messageIdCurrent} ~= Stat={stat.MessageId}"); } // Test some other commands for groups var next = client.LastAsync(cts.Token).Result; Console.WriteLine($"\t\tNEXT ({next.Code}) article={next.ArticleNumber}, messageId={next.MessageId}"); var last = client.LastAsync(cts.Token).Result; Console.WriteLine($"\t\tLAST ({last.Code}) article={last.ArticleNumber}, messageId={last.MessageId}"); } } // Test some other commands globally { var newGroups = client.NewGroupsAsync(DateTime.Now.AddYears(-30), cts.Token).Result; Console.WriteLine($"\r\nChecking for new groups in the past 30 years..."); foreach (var ng in newGroups.Groups.Take(20)) { Console.WriteLine($"\t{ng.Group} {ng.LowWatermark}-{ng.HighWatermark} {ng.Status}"); } var newNews = client.NewNewsAsync("*", DateTime.Now.AddYears(-30), cts.Token).Result; Console.WriteLine($"\r\nChecking for new messages in the past 30 years..."); foreach (var msg in newNews.MessageIds.Take(20)) { Console.WriteLine($"\t{msg}"); } var activeGroups = client.ListActiveAsync(cts.Token).Result; Console.WriteLine($"\r\nLIST ACTIVE Groups count={activeGroups.Groups.Count}"); var activeTimesGroups = client.ListActiveTimesAsync(cts.Token).Result; Console.WriteLine($"\r\nLIST ACTIVE.TIMES Groups count={activeGroups.Groups.Count}"); var newsgroupsList = client.ListNewsgroupsAsync(cts.Token).Result; Console.WriteLine($"\r\nLIST NEWSGROUPS Groups count={newsgroupsList.Groups.Count}"); } } catch (ArgumentException aex) { Console.Error.WriteLine($"Caught ArgumentException: {aex.Message}\r\n{aex}"); return; } catch (AggregateException agg) { Console.Error.WriteLine($"Caught AggregateException: {agg.Message}"); foreach (var ex in agg.InnerExceptions) { Console.Error.WriteLine($"...InnerException: {ex.Message}: {ex}"); } return; } var quitResponse = client.DisconnectAsync().Result; if (quitResponse == null) { Console.Out.WriteLine($"Connection is already closed"); } else { Console.Out.WriteLine($"Closed connection: {quitResponse}"); } }
private static void TestListNewsGroups(NntpClient client) { // list newsgroups ShowLines(client.ListNewsgroups("*.recovery").Lines); }
private static void TestListOverviewFormat(NntpClient client) { // list overview.fmt ShowLines(client.ListOverviewFormat().Lines); }
private static async Task MainAsync(string[] args) { // init logging LibraryLogging.Factory = ApplicationLogging.Factory; log.LogInformation("Program started with {Arguments}.", (object)args); // init config IConfigurationBuilder configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json"); config = configBuilder.Build(); // setup DI IServiceProvider serviceProvider = new ServiceCollection() .AddOptions() .Configure<Nntp>(config.GetSection(nameof(Nntp))) .AddSingleton(ApplicationLogging.Factory) .BuildServiceProvider(); // read config Nntp nntpOptions = serviceProvider.GetService<IOptions<Nntp>>().Value; Server server; bool streaming = args.Length > 0 && args[0] == "stream"; log.LogInformation("Decode streaming: {streaming}", streaming); while ((server = ChooseServer(nntpOptions.Servers)) != null) { try { NntpClient client = await ConnectAsync(server); if (client == null) { continue; } TestDownloadNzb(client, @"Testfile.nzb"); //TestDownloadNzbStreaming(client, @"Testfile.nzb"); //TestDate(client); //TestCapabilities(client); //TestHelp(client); //TestListActiveTimes(client); //NntpGroup group = client.Group("alt.test.clienttest").Group; //ShowGroup(group); //TestArticle(client, @group); //TestPost(client); //TestListCounts(client); //TestListOverviewFormat(client); //TestListNewsGroups(client); //TestListDistribPats(client); //TestListHeaders(client); //TestXover(client, group); //TestXhdr(client, group); //TestListDistributions(client); //sw.Restart(); //TestListActive(client); //Console.WriteLine(sw.Elapsed); //TestNewGroups(client); //TestDecompression(client, @group); // quit - close connection client.Quit(); } catch (Exception exception) { log.LogError("Exception: {exception}", exception); } } }
private static void TestDate(NntpClient client) { // get server date Console.WriteLine($"Server date: {client.Date()}"); }
private static void TestCapabilities(NntpClient client) { // get capabilities ShowLines(client.Capabilities().Lines); }
private static void TestHelp(NntpClient client) { // get help ShowLines(client.Help().Lines); }