Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
11 changes: 11 additions & 0 deletions .NET core/DiscordSharp.Commands/DiscordSharp.Commands.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\DiscordSharp\DiscordSharp.csproj" />
</ItemGroup>

</Project>
31 changes: 31 additions & 0 deletions .NET core/DiscordSharp.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2010
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordSharp", "DiscordSharp\DiscordSharp.csproj", "{83B812D1-C6A7-4378-825F-F7B21575ADDA}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DiscordSharp.Commands", "DiscordSharp.Commands\DiscordSharp.Commands.csproj", "{D0A7320C-33CA-455D-886B-86088C083903}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{83B812D1-C6A7-4378-825F-F7B21575ADDA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{83B812D1-C6A7-4378-825F-F7B21575ADDA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{83B812D1-C6A7-4378-825F-F7B21575ADDA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{83B812D1-C6A7-4378-825F-F7B21575ADDA}.Release|Any CPU.Build.0 = Release|Any CPU
{D0A7320C-33CA-455D-886B-86088C083903}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D0A7320C-33CA-455D-886B-86088C083903}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D0A7320C-33CA-455D-886B-86088C083903}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D0A7320C-33CA-455D-886B-86088C083903}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {4076345A-687A-4117-890D-F43D786881E1}
EndGlobalSection
EndGlobal
File renamed without changes.
654 changes: 373 additions & 281 deletions DiscordSharp/DiscordClient.cs → .NET core/DiscordSharp/DiscordClient.cs

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions .NET core/DiscordSharp/DiscordSharp.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Optimize>true</Optimize>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CaptchaGen.NetCore" Version="1.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.1" />
<PackageReference Include="WebSocket4Net" Version="0.15.2" />
</ItemGroup>

</Project>
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using DiscordSharp.Objects;
using System;
using System.Collections.Generic;
using System.Text;

namespace DiscordSharp.Events
{
public class DiscordGuildMembersLoadedEventArgs : EventArgs
{
public DiscordServer Server { get; internal set; }
public int MemberSize { get; internal set; }
}
}
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ namespace DiscordSharp.Objects
{
public enum Status
{
Online, Idle, Offline
Online,
Idle,
Offline,
DoNotDisturb
}
public class DiscordMember
{
Expand Down Expand Up @@ -52,12 +55,23 @@ Voice only
internal void SetPresence(string status)
{
string checkAgainst = status.ToLower().Trim();
if (checkAgainst == "online")
Status = Status.Online;
else if (checkAgainst == "idle")
Status = Status.Idle;
else
Status = Status.Offline;
switch (checkAgainst)
{
case "dnd":
Status = Status.DoNotDisturb;
break;
case "online":
Status = Status.Online;
break;
case "idle":
Status = Status.Idle;
break;
case "offline":
Status = Status.Offline;
break;
default:
throw new Exception("New presence status type found: " + status);
}
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,33 +79,34 @@ internal DiscordServer()
Members = new Dictionary<ID, DiscordMember>();
}


internal void AddMember(DiscordMember member)
{
if (member == null)
return;
if(Members.ContainsKey(member.ID)) //then replace

lock (Members)
{
Members.Remove(member.ID);
if (Members.ContainsKey(member.ID)) //then replace
Members.Remove(member.ID);

Members.Add(member.ID, member);
}
Members.Add(member.ID, member);
}

internal int ClearOfflineMembers()
{
int count = 0;
foreach(var member in Members)
{
if (member.Value.Status == Status.Offline)
return count;
}
return count;
return Members.Count(mem => mem.Value.Status == Status.Offline);
}
internal bool RemoveMember(ID key)
{
if(Members.ContainsKey(key))
if (Members.ContainsKey(key))
{
Members.Remove(key);
lock (Members)
{
Members.Remove(key);
}
return true;
}
return false;
}
Expand All @@ -114,14 +115,11 @@ public DiscordMember GetMemberByKey(ID key)
if (Unavailable)
throw new Exception("Server is currently unavailable!");

try
{
return Members.First(x => x.Key == key).Value;
}
catch
if (Members.ContainsKey(key))
{
return null; //because instead of just returning null by default, it has to do this shit.
return Members[key];
}
return null;
}
public DiscordMember GetMemberByUsername(string username, bool caseSensitive = false)
{
Expand Down Expand Up @@ -273,7 +271,8 @@ public DiscordChannel CreateChannel(string ChannelName, bool voice)
var result = JObject.Parse(WebWrapper.Post(url, DiscordClient.token, reqJson));
if (result != null)
{
DiscordChannel dc = new DiscordChannel {
DiscordChannel dc = new DiscordChannel
{
Name = result["name"].ToString(),
ID = result["id"].ToString(),
Type = result["type"].ToObject<ChannelType>(),
Expand Down
File renamed without changes.
188 changes: 188 additions & 0 deletions .NET core/DiscordSharp/Sockets/BuiltIn/NetWebSocketWrapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DiscordSharp.Sockets.BuiltIn
{
public class NetWebSocketWrapper
{
private const int ReceiveChunkSize = 4096;

private string _URL;
public string URL
{
get { return _URL; }
private set { }
}

private readonly ClientWebSocket _ws;
private readonly Uri _uri;
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
private readonly CancellationToken _cancellationToken;

/// <summary>
/// Create an instance
/// </summary>
/// <param name="uri"></param>
public NetWebSocketWrapper(string uri)
{
this._URL = uri;

_ws = new ClientWebSocket();
_ws.Options.KeepAliveInterval = TimeSpan.FromSeconds(20);
_uri = new Uri(uri);
_cancellationToken = _cancellationTokenSource.Token;

//_ws.CloseStatusDescription
//_ws.CloseStatus.Value.ToString();
}

#region Public methods
public event EventHandler<SocketMessageEventArgs> MessageReceived;
public event EventHandler<SocketClosedEventArgs> SocketClosed;
public event EventHandler<SocketErrorEventArgs> SocketError;
public event EventHandler<EventArgs> SocketOpened;

public bool IsAlive
{
get
{
return _ws != null;
}
}

/// <summary>
/// Connects to the WebSocket server.
/// </summary>
public void Connect()
{
//await _ws.ConnectAsync(_uri, _cancellationToken);
_ws.ConnectAsync(_uri, _cancellationToken).Wait();

SocketOpened?.Invoke(this, null);

StartListen();
}

/// <summary>
/// Close socket
/// </summary>
public void Close()
{
CallOnDisconnected("User requested to exit.");
}

/// <summary>
/// Send a message to the WebSocket server.
/// </summary>
/// <param name="message">The message to send</param>
/// <returns>success</returns>
public async Task<bool> SendMessage(string message)
{
byte[] messageBuffer = Encoding.UTF8.GetBytes(message);
return await SendMessage(messageBuffer);
}

/// <summary>
/// Sends a byte array to the connected socket
/// </summary>
/// <param name="buffer"></param>
/// <returns>success</returns>
public async Task<bool> SendMessage(byte[] buffer)
{
if (_ws.State != WebSocketState.Open)
{
throw new Exception("Connection is not open.");
}
try
{
await _ws.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
return true;
}
catch (Exception exp)
{
CallOnDisconnected(exp.Message);
}
return false;
}
#endregion

private async void StartListen()
{
try
{
while (_ws != null && _ws.State == WebSocketState.Open)
{
byte[] Sharedbuffer = new byte[ReceiveChunkSize];


using (var ms = new MemoryStream()) // auto release memory
{
WebSocketReceiveResult res;
do
{
res = await _ws.ReceiveAsync(Sharedbuffer, CancellationToken.None);
if (res.MessageType == WebSocketMessageType.Close)
{
CallOnDisconnected(null);
return;
}
ms.Write(Sharedbuffer, 0, res.Count);
// ms.Write(segment.Array, segment.Offset, res.Count);
}
while (!res.EndOfMessage);

ms.Seek(0, SeekOrigin.Begin);

// Return data
byte[] returnBuffer = new byte[ms.Length];
Buffer.BlockCopy(ms.ToArray(), 0, returnBuffer, 0, (int)ms.Length);

string msg = Encoding.UTF8.GetString(returnBuffer);

// Fires the return packet in a new thread
ThreadPool.QueueUserWorkItem(state =>
{
SocketMessageEventArgs args = new SocketMessageEventArgs
{
Message = msg
};
MessageReceived?.Invoke(this, args);
});
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
CallOnDisconnected(ex.Message);
}
finally
{
_ws.Dispose();
}
}

private void CallOnDisconnected(string messageOverride)
{
try
{
_ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait();
}
catch { }

SocketClosedEventArgs args = new SocketClosedEventArgs
{
Reason = messageOverride != null ? messageOverride : _ws.CloseStatusDescription,
WasClean = false,
Code = _ws.CloseStatus != null ? (int)_ws.CloseStatus.Value : -1
};
SocketClosed?.Invoke(this, args);
}
}
}
Loading