Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
asmejkal committed Apr 15, 2022
1 parent 5ea9238 commit 3690862
Show file tree
Hide file tree
Showing 51 changed files with 6,152 additions and 0 deletions.
66 changes: 66 additions & 0 deletions DiscordFoobarStatus.Client/DiscordClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
using System;
using Discord;
using DiscordFoobarStatus.Core.Models;
using Microsoft.Extensions.Logging;

namespace DiscordFoobarStatus.Client
{
internal class DiscordClient : IDisposable, IDiscordClient
{
private readonly Discord.Discord _client;
private readonly ILogger<DiscordClient> _logger;

public DiscordClient(ILogger<DiscordClient> logger)
{
_client = new Discord.Discord(DiscordConstants.ClientId, (ulong)CreateFlags.NoRequireDiscord);
_logger = logger;
}

public void Dispose()
{
((IDisposable)_client).Dispose();
}

public void RunCallbacks() => _client.RunCallbacks();

public void UpdateActivity(ActivitySetDto data)
{
var activity = new Activity()
{
State = data.State!,
Details = data.Details!
};

if (data.Thumbnail != null)
{
activity.Assets = new() { LargeImage = data.Thumbnail };
if (data.ThumbnailText != null)
activity.Assets.LargeText = data.ThumbnailText;
}

if (data.StartTimestamp != null)
activity.Timestamps = new() { Start = data.StartTimestamp.Value };
else if (data.EndTimestamp != null)
activity.Timestamps = new() { End = data.EndTimestamp.Value };

_client.GetActivityManager().UpdateActivity(activity, x =>
{
if (x == Result.Ok)
_logger.LogInformation("Updated activity to {Activity}", data);
else
_logger.LogError("Failed to update activity with error {Error}", x);
});
}

public void ClearActivity()
{
_client.GetActivityManager().ClearActivity(x =>
{
if (x == Result.Ok)
_logger.LogInformation("Cleared activity");
else
_logger.LogError("Failed to clear activity with error {Error}", x);
});
}
}
}
7 changes: 7 additions & 0 deletions DiscordFoobarStatus.Client/DiscordConstants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace DiscordFoobarStatus.Client
{
internal static class DiscordConstants
{
public const long ClientId = 962359979371802686;
}
}
33 changes: 33 additions & 0 deletions DiscordFoobarStatus.Client/DiscordFoobarStatus.Client.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net5.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<Platforms>x86</Platforms>
</PropertyGroup>

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

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x86'">
<Optimize>False</Optimize>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.EventSource" Version="6.0.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="4.2.0" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\DiscordFoobarStatus.Core\DiscordFoobarStatus.Core.csproj" />
<ProjectReference Include="..\DiscordFoobarStatus.DiscordSdk\DiscordFoobarStatus.DiscordSdk.csproj" />
</ItemGroup>

</Project>
11 changes: 11 additions & 0 deletions DiscordFoobarStatus.Client/IDiscordClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using DiscordFoobarStatus.Core.Models;

namespace DiscordFoobarStatus.Client
{
public interface IDiscordClient
{
void ClearActivity();
void RunCallbacks();
void UpdateActivity(ActivitySetDto data);
}
}
56 changes: 56 additions & 0 deletions DiscordFoobarStatus.Client/Music.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

89 changes: 89 additions & 0 deletions DiscordFoobarStatus.Client/Music.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
using System;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Windows.Forms;
using DiscordFoobarStatus.Core.Interop;
using DiscordFoobarStatus.Core.Models;
using Microsoft.Extensions.Logging;

namespace DiscordFoobarStatus.Client
{
public partial class Music : Form
{
private readonly IDiscordClient _discordClient;
private readonly ILogger<Music> _logger;

private readonly MessageIds _messageIds = new();

protected override bool ShowWithoutActivation => true;

public Music(IDiscordClient discordClient, ILogger<Music> logger)
{
_discordClient = discordClient;
_logger = logger;

InitializeComponent();

FormBorderStyle = FormBorderStyle.FixedToolWindow;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
Location = new(-2000, -2000);
Size = new(1, 1);
}

protected override void WndProc(ref Message m)
{
try
{
if (m.Msg == User32.WM_COPYDATA)
HandleCopyData(ref m);
else if (m.Msg == _messageIds.Shutdown)
HandleShutdown();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to handle message {MessageType}", m.Msg);
}

base.WndProc(ref m);
}

private void HandleCopyData(ref Message m)
{
var copyData = Marshal.PtrToStructure<CopyData>(m.LParam);
var raw = copyData.AsUnicodeString;
if (raw == null)
throw new ArgumentException("Missing payload", nameof(m));

if (copyData.dwData == (IntPtr)_messageIds.UpdateActivity)
{
_logger.LogInformation("Received UpdateActivity message");
var dto = JsonSerializer.Deserialize<ActivitySetDto>(raw) ?? throw new JsonException("Null payload");
_discordClient.UpdateActivity(dto);
}
else
{
throw new ArgumentOutOfRangeException(nameof(m), copyData.dwData, "Unknown message type");
}
}

private void HandleShutdown()
{
_logger.LogInformation("Received Shutdown message");
_discordClient.ClearActivity();
Close();
}

private void CallbackLoopTimer_Tick(object sender, EventArgs e)
{
try
{
_discordClient.RunCallbacks();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to run Discord callbacks");
}
}
}
}
66 changes: 66 additions & 0 deletions DiscordFoobarStatus.Client/Music.resx
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="CallbackLoopTimer.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>139</value>
</metadata>
</root>
56 changes: 56 additions & 0 deletions DiscordFoobarStatus.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace DiscordFoobarStatus.Client
{
internal class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
using var host = CreateHostBuilder().Build();
var logger = host.Services.GetRequiredService<ILoggerFactory>().CreateLogger<Program>();
try
{
logger.LogInformation("Starting process {ProcessId}", Process.GetCurrentProcess().Id);

Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(host.Services.GetRequiredService<Music>());

logger.LogInformation("Shutting down process {ProcessId}", Process.GetCurrentProcess().Id);
}
catch (Exception ex)
{
logger.LogError(ex, "Fatal error");
throw;
}
}

private static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices(services => services.AddClientServices())
.UseSerilog((_, config) =>
{
config.WriteTo.RollingFile(
"logs/log-{Date}.txt",
LogEventLevel.Information,
fileSizeLimitBytes: 1024 * 1024 * 10,
retainedFileCountLimit: 3);
});
}
}
}
Loading

0 comments on commit 3690862

Please sign in to comment.