Browse Source

send calendar list

master
amki 5 years ago
parent
commit
baad11c9fa
  1. BIN
      DiscoBot/98293701175955456-calendar.db
  2. BIN
      DiscoBot/98293701175955456-rss.db
  3. 7
      DiscoBot/ClientApp/src/app/calendar/calendar.component.html
  4. 46
      DiscoBot/ClientApp/src/app/calendar/calendar.component.ts
  5. 3
      DiscoBot/ClientApp/src/app/home/home.component.html
  6. 31
      DiscoBot/DisBot.cs
  7. 2
      DiscoBot/IModule.cs
  8. 1
      DiscoBot/Program.cs
  9. 8
      DiscoBot/Startup.cs
  10. 10
      DiscoBot/appsettings.json
  11. 6
      DiscoBot/calendar/CalController.cs
  12. 49
      DiscoBot/calendar/Calendar.cs
  13. 12
      DiscoBot/calendar/CalendarContext.cs
  14. 29
      DiscoBot/calendar/JSONObjects.cs
  15. 7
      DiscoBot/rss/Rss.cs

BIN
DiscoBot/98293701175955456-calendar.db

Binary file not shown.

BIN
DiscoBot/98293701175955456-rss.db

Binary file not shown.

7
DiscoBot/ClientApp/src/app/calendar/calendar.component.html

@ -1,7 +1,10 @@
<h1>Calendar</h1> <h1>Calendar</h1>
<p>This component demonstrates fetching data from the server.</p> <div class="calendars" *ngIf="calendars">
<p *ngIf="!forecasts"><em>Loading...</em></p> <div class="calendar" *ngFor="let calendar of calendars">
<a (click)="getCalendar(calendar.ChannelId)">{{calendar.Id}} ||{{calendar.ChannelId}}</a>
</div>
</div>
<table class='table table-striped' *ngIf="forecasts"> <table class='table table-striped' *ngIf="forecasts">
<thead> <thead>

46
DiscoBot/ClientApp/src/app/calendar/calendar.component.ts

@ -7,25 +7,47 @@ import { HttpClient } from '@angular/common/http';
}) })
export class CalendarComponent { export class CalendarComponent {
public forecasts: CalendarForecast[]; public forecasts: CalendarForecast[];
public webSocket;
public calendars;
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) { getCalendar(id) {
console.log("ws connecting to ws" + baseUrl.substring(4, baseUrl.length) + "ws/calendar"); console.log("getCalendar: ", id);
var ws = new WebSocket("ws" + baseUrl.substring(4, baseUrl.length) + "ws/calendar"); this.webSocket.send('{Op: "calget", ChannelId: ' + id + '}');
}
ws.onopen = function () {
// Web Socket is connected, send data using send() handleCalendarList(cList) {
ws.send('{op:"connect", gid: 98293701175955456, module:"calendar"}'); console.log("Setting calendars: ", cList);
alert("Message is sent..."); this.calendars = cList;
};
constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
var self = this;
console.log("ws connecting to ws" + baseUrl.substring(4, baseUrl.length) + "ws/calendar");
this.webSocket = new WebSocket("ws" + baseUrl.substring(4, baseUrl.length) + "ws/calendar");
this.webSocket.onopen = function () {
// TODO: Stop hardcoding gid, get this from url?
self.webSocket.send('{Op:"connect", GId: 98293701175955456, Module:"calendar"}');
setInterval(() => {
self.webSocket.send('{Op:"ping"}');
},120000);
}; };
ws.onmessage = function (evt) { this.webSocket.onmessage = function (evt) {
var received_msg = evt.data; console.log("evt: ", evt);
alert(received_msg); var msg = JSON.parse(evt.data);
console.log(msg);
switch (msg.Op) {
case "CalendarList":
self.handleCalendarList(msg.Calendars);
break;
default:
console.log("Unknown opcode: ", msg);
}
}; };
ws.onclose = function () { this.webSocket.onclose = function () {
// websocket is closed. // websocket is closed.
alert("Connection is closed..."); alert("Connection is closed...");

3
DiscoBot/ClientApp/src/app/home/home.component.html

@ -11,5 +11,6 @@
<li><strong>Angular CLI integration</strong>. In development mode, there's no need to run <code>ng serve</code>. It runs in the background automatically, so your client-side resources are dynamically built on demand and the page refreshes when you modify any file.</li> <li><strong>Angular CLI integration</strong>. In development mode, there's no need to run <code>ng serve</code>. It runs in the background automatically, so your client-side resources are dynamically built on demand and the page refreshes when you modify any file.</li>
<li><strong>Efficient production builds</strong>. In production mode, development-time features are disabled, and your <code>dotnet publish</code> configuration automatically invokes <code>ng build</code> to produce minified, ahead-of-time compiled JavaScript files.</li> <li><strong>Efficient production builds</strong>. In production mode, development-time features are disabled, and your <code>dotnet publish</code> configuration automatically invokes <code>ng build</code> to produce minified, ahead-of-time compiled JavaScript files.</li>
</ul> </ul>
Dübbel Kalenderio
<app-calendar></app-calendar> <app-calendar></app-calendar>
<p>The <code>ClientApp</code> subdirectory is a standard Angular CLI application. If you open a command prompt in that directory, you can run any <code>ng</code> command (e.g., <code>ng test</code>), or use <code>npm</code> to install extra packages into it.</p>

31
DiscoBot/DisBot.cs

@ -30,25 +30,7 @@ namespace DiscoBot
this.wsC = wsC; this.wsC = wsC;
} }
private async Task Echo(HttpContext context, WebSocket webSocket) public async Task HandleWebsocket(HttpContext context, TaskCompletionSource<object> tcs)
{
var buffer = new byte[1024 * 4];
WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
// Clientpaket handlen
// WebSocket an richtiges module zustellen
while (!result.CloseStatus.HasValue)
{
var msgBytes = Encoding.UTF8.GetBytes("penis");
Console.WriteLine(msgBytes);
await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
}
//await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
}
public async Task HandleWebsocket(HttpContext context)
{ {
Console.WriteLine("Handling Websocket to "+ context.Request.Path); Console.WriteLine("Handling Websocket to "+ context.Request.Path);
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
@ -59,7 +41,9 @@ namespace DiscoBot
{ {
if (m.Name == login.Module) if (m.Name == login.Module)
{ {
m.OnNewWebSocket(webSocket); #pragma warning disable CS4014 // Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt.
m.OnNewWebSocketAsync(webSocket, tcs);
#pragma warning restore CS4014 // Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt.
} }
} }
} }
@ -74,6 +58,13 @@ namespace DiscoBot
return line; return line;
} }
public static async void SendStringViaWebSocket(WebSocket ws, string str)
{
var msgBytes = Encoding.UTF8.GetBytes(str);
Console.WriteLine("Sending: "+str);
await ws.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, true, CancellationToken.None);
}
public async void Initialize() public async void Initialize()
{ {
Console.WriteLine("In init!"); Console.WriteLine("In init!");

2
DiscoBot/IModule.cs

@ -12,6 +12,6 @@ namespace DiscoBot
Dictionary<string,Func<SocketMessage, string[], Task>> Commands { get; set; } Dictionary<string,Func<SocketMessage, string[], Task>> Commands { get; set; }
string Name { get; set; } string Name { get; set; }
void Initialize(); void Initialize();
void OnNewWebSocket(WebSocket ws); Task OnNewWebSocketAsync(WebSocket ws, TaskCompletionSource<object> tcs);
} }
} }

1
DiscoBot/Program.cs

@ -7,6 +7,7 @@ using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace DiscoBot namespace DiscoBot
{ {

8
DiscoBot/Startup.cs

@ -6,6 +6,7 @@ using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.WebSockets; using System.Net.WebSockets;
@ -31,6 +32,7 @@ namespace DiscoBot
services.AddMvc() services.AddMvc()
.AddNewtonsoftJson(); .AddNewtonsoftJson();
// In production, the Angular files will be served from this directory // In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration => services.AddSpaStaticFiles(configuration =>
{ {
@ -75,7 +77,9 @@ namespace DiscoBot
{ {
if (context.WebSockets.IsWebSocketRequest) if (context.WebSockets.IsWebSocketRequest)
{ {
await diBot.HandleWebsocket(context); var socketFinishedTcs = new TaskCompletionSource<object>();
await diBot.HandleWebsocket(context, socketFinishedTcs);
await socketFinishedTcs.Task;
} }
else else
{ {
@ -107,7 +111,7 @@ namespace DiscoBot
if (env.IsDevelopment()) if (env.IsDevelopment())
{ {
spa.UseAngularCliServer(npmScript: "start"); spa.UseProxyToSpaDevelopmentServer("http://localhost:4200");
} }
}); });
} }

10
DiscoBot/appsettings.json

@ -1,8 +1,12 @@
{ {
"Logging": { "Logging": {
"LogLevel": { "LogLevel": {
"Default": "Warning" "Default": "Information",
} "Microsoft.AspNetCore": "Warning"
}, },
"Console": {
"IncludeScopes": true
}
},
"AllowedHosts": "*" "AllowedHosts": "*"
} }

6
DiscoBot/calendar/CalController.cs

@ -15,10 +15,8 @@ namespace DiscoBot.calendar
// GET: api/Cal // GET: api/Cal
[HttpGet("{guild}", Name = "Get")] [HttpGet("{guild}", Name = "Get")]
public JsonResult Get(ulong guild) public JsonResult Get(ulong guild)
{ {
CalendarContext calendarContext = new CalendarContext(guild); return Json("");
List<CalendarItem> items = calendarContext.CalendarItems.Include(i => i.Attendance).ToList();
return Json(items);
} }
// POST: api/Cal // POST: api/Cal

49
DiscoBot/calendar/Calendar.cs

@ -5,6 +5,8 @@ using System.Net.WebSockets;
using System.Threading.Tasks; using System.Threading.Tasks;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace DiscoBot.calendar namespace DiscoBot.calendar
{ {
@ -32,10 +34,44 @@ namespace DiscoBot.calendar
Console.WriteLine("Initializing calendar..."); Console.WriteLine("Initializing calendar...");
} }
public void OnNewWebSocket(WebSocket ws) public async Task OnNewWebSocketAsync(WebSocket ws, TaskCompletionSource<object> tcs)
{ {
Console.WriteLine("Calendar " + guild.Id + " has a new websocket."); Console.WriteLine("Calendar " + guild.Id + " has a new websocket.");
webSockets.Add(ws); webSockets.Add(ws);
// Send list of calendars(channels)
//var calendar = calendarContext.ChannelCalendar.Include(cal => cal.Items).ToList();
var cList = new CalendarList();
cList.Calendars = calendarContext.ChannelCalendar.ToList();
string str = JsonConvert.SerializeObject(cList);
Console.WriteLine(str);
DisBot.SendStringViaWebSocket(ws, str);
#pragma warning disable CS4014 // Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt.
Task.Run(async () =>
{
Console.WriteLine("Starting websocket handling...");
while (ws.State != WebSocketState.Closed)
{
string msg = await DisBot.ReadOneStringFromWebSocket(ws);
var op = JsonConvert.DeserializeObject<Opcode>(msg);
switch (op.Op)
{
case "calget":
var calGet = JsonConvert.DeserializeObject<CalGet>(msg);
Console.WriteLine("ChannelID:" + calGet.ChannelId);
var calendarWS = new CalendarWS();
var temp = calendarContext.ChannelCalendar.FirstOrDefault();
calendarWS.Op = calGet.Op;
DisBot.SendStringViaWebSocket(ws, JsonConvert.SerializeObject(calendarWS));
break;
default:
Console.WriteLine("Unknown opcode: " + op.Op);
break;
}
}
Console.WriteLine("Websocket handling stopped...");
tcs.TrySetResult(new object());
});
#pragma warning restore CS4014 // Da auf diesen Aufruf nicht gewartet wird, wird die Ausführung der aktuellen Methode vor Abschluss des Aufrufs fortgesetzt.
} }
private Task HandleTestCommand(SocketMessage msg, string[] parameters) private Task HandleTestCommand(SocketMessage msg, string[] parameters)
@ -56,6 +92,14 @@ namespace DiscoBot.calendar
try try
{ {
var gchan = msg.Channel as IGuildChannel; var gchan = msg.Channel as IGuildChannel;
var calendar = calendarContext.ChannelCalendar.FirstOrDefault(cal => cal.ChannelId == gchan.Id);
if(calendar == null)
{
calendar = new ChannelCalendar();
calendar.ChannelId = gchan.Id;
calendar.Moderated = false;
calendarContext.Add(calendar);
}
string name = parameters[1]; string name = parameters[1];
string date = parameters[2]; string date = parameters[2];
string comment = parameters[3]; string comment = parameters[3];
@ -70,8 +114,9 @@ namespace DiscoBot.calendar
attendance.Attendee = msg.Author.Id; attendance.Attendee = msg.Author.Id;
attendance.Attending = Attendance.Attending; attendance.Attending = Attendance.Attending;
calItem.Attendance.Add(attendance); calItem.Attendance.Add(attendance);
calendarContext.CalendarItems.Add(calItem); calendar.Items.Add(calItem);
calendarContext.SaveChanges(); calendarContext.SaveChanges();
msg.Channel.SendMessageAsync("Event "+ calItem.Name + " has been added.");
} }
catch(FormatException) catch(FormatException)
{ {

12
DiscoBot/calendar/CalendarContext.cs

@ -11,8 +11,7 @@ namespace DiscoBot.calendar
public class CalendarContext : DbContext public class CalendarContext : DbContext
{ {
private ulong guildId; private ulong guildId;
public DbSet<CalendarItem> CalendarItems { get; set; } public DbSet<ChannelCalendar> ChannelCalendar { get; set; }
public CalendarContext(ulong guildId) public CalendarContext(ulong guildId)
{ {
this.guildId = guildId; this.guildId = guildId;
@ -24,6 +23,15 @@ namespace DiscoBot.calendar
} }
} }
public class ChannelCalendar
{
[Key]
public ulong Id { get; set; }
public ulong ChannelId { get; set; }
public List<CalendarItem> Items { get; set; } = new List<CalendarItem>();
public bool Moderated { get; set; }
}
public class CalendarItemAttendance public class CalendarItemAttendance
{ {
[Key] [Key]

29
DiscoBot/calendar/JSONObjects.cs

@ -5,10 +5,37 @@ using System.Threading.Tasks;
namespace DiscoBot.calendar namespace DiscoBot.calendar
{ {
public class Opcode
{
public string Op { get; set; }
}
public class Login { public class Login {
// {op:"connect", gid: 324984732895, module:"calendar"} // {Op:"connect", GId: 324984732895, Module:"calendar"}
public string Op { get; set; } public string Op { get; set; }
public ulong Gid { get; set; } public ulong Gid { get; set; }
public string Module { get; set; } public string Module { get; set; }
} }
public class CalendarList
{
// {Op: "CalendarList, Calendars: []}
public string Op { get; set; }
public List<ChannelCalendar> Calendars { get; set; }
public CalendarList()
{
this.Op = "CalendarList";
}
}
public class CalendarWS
{
public string Op { get; set; }
public ChannelCalendar Calendar { get; set; }
}
public class CalGet
{
// {Op:"calget", ChannelId: 239180890231}
public string Op { get; set; }
public ulong ChannelId { get; set; }
}
} }

7
DiscoBot/rss/Rss.cs

@ -43,7 +43,10 @@ namespace DiscoBot.rss
Console.WriteLine("Found feed " + feed.Name); Console.WriteLine("Found feed " + feed.Name);
Timer timer = new Timer(feed.CheckInterval.TotalMilliseconds); Timer timer = new Timer(feed.CheckInterval.TotalMilliseconds);
timer.AutoReset = true; timer.AutoReset = true;
timer.Elapsed += async (sender, e) => await HandleFeedCheck(feed); timer.Elapsed += async (sender, e) =>
{
await Task.Run(() => HandleFeedCheck(feed));
};
timer.Start(); timer.Start();
timers.Add(feed.Name, timer); timers.Add(feed.Name, timer);
return Task.CompletedTask; return Task.CompletedTask;
@ -208,7 +211,7 @@ namespace DiscoBot.rss
Console.WriteLine("Initializing rss..."); Console.WriteLine("Initializing rss...");
} }
public void OnNewWebSocket(WebSocket ws) public async Task OnNewWebSocketAsync(WebSocket ws, TaskCompletionSource<object> tcs)
{ {
Console.WriteLine("Calendar " + guild.Id + " has a new websocket."); Console.WriteLine("Calendar " + guild.Id + " has a new websocket.");
webSockets.Add(ws); webSockets.Add(ws);

Loading…
Cancel
Save