This repository has moved! Please check out the latest version at the new location https://git.exmods.org/NGnius/GameSDKcraft
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

184 lines
7.8KB

  1. using System;
  2. using System.Reflection;
  3. //using Microsoft.Win32;
  4. using IllusionPlugin;
  5. using GamecraftModdingAPI.Events;
  6. using GamecraftModdingAPI.Commands;
  7. using Discord;
  8. namespace GamecraftRPC
  9. {
  10. public class Plugin : IPlugin // the Illusion Plugin Architecture (IPA) will ignore classes that don't implement IPlugin'
  11. {
  12. public string Name { get; } = Assembly.GetExecutingAssembly().GetName().Name;
  13. public string Version { get; } = Assembly.GetExecutingAssembly().GetName().Version.ToString();
  14. private static readonly long CLIENT_ID =
  15. #if DEBUG
  16. 692733325902872619;
  17. #else
  18. 696732441012076605;
  19. #endif
  20. private Discord.Discord discordRPC;
  21. // called when Gamecraft shuts down
  22. public void OnApplicationQuit()
  23. {
  24. // Shutdown this mod
  25. if (discordRPC != null)
  26. {
  27. discordRPC.GetActivityManager().ClearActivity((result) => { GamecraftModdingAPI.Utility.Logging.LogDebug($"Cleared status: {result}"); });
  28. discordRPC.Dispose();
  29. }
  30. GamecraftModdingAPI.Utility.Logging.LogDebug($"{Name} has shutdown");
  31. // Shutdown the Gamecraft modding API last
  32. GamecraftModdingAPI.Main.Shutdown();
  33. }
  34. // called when Gamecraft starts up
  35. public void OnApplicationStart()
  36. {
  37. // Initialize the Gamecraft modding API first
  38. GamecraftModdingAPI.Main.Init();
  39. // detect Wine (maybe?)
  40. bool isWineDetected = false;
  41. foreach (var key in Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software").GetSubKeyNames())
  42. {
  43. if (key == "Wine")
  44. {
  45. isWineDetected = true;
  46. break;
  47. }
  48. }
  49. if (isWineDetected)
  50. {
  51. // check for or install fake Discord
  52. GamecraftModdingAPI.Utility.Logging.MetaLog("\n--------------------------------\n\nIt looks like you may be using Wine/Proton, cool!\nPlease install https://github.com/0e4ef622/wine-discord-ipc-bridge to get this to work.\n\n--------------------------------");
  53. }
  54. // Initialize this mod
  55. discordRPC = new Discord.Discord(CLIENT_ID, (UInt64)Discord.CreateFlags.Default);
  56. discordRPC.SetLogHook(LogLevel.Debug, (_, msg) => { GamecraftModdingAPI.Utility.Logging.MetaLog(msg); });
  57. discordRPC.GetRelationshipManager().OnRefresh += () =>
  58. {
  59. discordRPC.GetRelationshipManager().Filter((ref Relationship r) => { return r.Presence.Status == Status.Online && r.Type == RelationshipType.Friend; });
  60. PresenceUtility.Users = new Relationship[discordRPC.GetRelationshipManager().Count()];
  61. for (uint i = 0; i < discordRPC.GetRelationshipManager().Count(); i++)
  62. {
  63. PresenceUtility.Users[i] = discordRPC.GetRelationshipManager().GetAt(i);
  64. }
  65. };
  66. SetDiscordActivity(discordRPC, state: "Loading...", details: "Initializing Gamecraft", start: (int)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds);
  67. EventManager.AddEventHandler(new Events.GamePresenceHandler(discordRPC));
  68. EventManager.AddEventHandler(new Events.MenuPresenceHandler(discordRPC));
  69. EventManager.AddEventHandler(new Events.EditPresenceHandler(discordRPC));
  70. EventManager.AddEventHandler(new Events.SimulatePresenceHandler(discordRPC));
  71. SimpleCustomCommandEngine<string> rpcCommand = new SimpleCustomCommandEngine<string>(
  72. (s) => { SetDiscordActivity(discordRPC, state: s); }, // TODO: command action
  73. "SetRichPresence", // command name (used to invoke it in the console)
  74. "Set Discord status (experimental)" // command description (displayed when help command is executed)
  75. ); // this command can also be executed using the Command Computer
  76. SimpleCustomCommandEngine listDiscordUsersCommand = new SimpleCustomCommandEngine(
  77. () =>
  78. {
  79. string result = "Online Friends\n";
  80. for (int i = 0; i < PresenceUtility.Users.Length; i++)
  81. {
  82. result += $"{PresenceUtility.Users[i].User.Username} ({PresenceUtility.Users[i].User.Id})\n";
  83. }
  84. GamecraftModdingAPI.Utility.Logging.CommandLog(result);
  85. },
  86. "ListDiscordUsers",
  87. "List online Discord friends");
  88. // register the command so the modding API knows about it
  89. CommandManager.AddCommand(rpcCommand);
  90. CommandManager.AddCommand(listDiscordUsersCommand);
  91. GamecraftModdingAPI.Utility.GameEngineManager.AddGameEngine(new Engines.PlayerCountEngine(discordRPC));
  92. GamecraftModdingAPI.Utility.Logging.LogDebug($"{Name} has started up");
  93. }
  94. // unused methods
  95. public void OnFixedUpdate() { } // called once per physics update
  96. public void OnLevelWasInitialized(int level) { } // called after a level is initialized
  97. public void OnLevelWasLoaded(int level) { } // called after a level is loaded
  98. public void OnUpdate() // called once per rendered frame (frame update)
  99. {
  100. if (discordRPC != null ) discordRPC.RunCallbacks();
  101. }
  102. public static void SetDiscordActivity(Discord.Discord discordRPC, string state = null, string details = null, int start = 0, int end = 0, string largeImg = "gamecraft-logo-g", string largeTxt = "Gamecraft", string smallImg = "exmods-logo-xm2", string smallTxt = "Exmods", string partyId = null, int partyCurrentSize = 0, int partyMaxSize = 0, string matchSecret = null, string joinSecret = null, string spectateSecret = null, bool instance = true, string debug = "")
  103. {
  104. if (discordRPC == null) return;
  105. ref Activity activity = ref PresenceUtility.Activity;
  106. activity.Instance = instance;
  107. if (state != null) activity.State = state;
  108. if (details != null) activity.Details = details;
  109. if (start != 0) activity.Timestamps.Start = start;
  110. if (end != 0) activity.Timestamps.End = end;
  111. if (!string.IsNullOrEmpty(largeImg))
  112. {
  113. activity.Assets.LargeImage = largeImg;
  114. activity.Assets.LargeText = largeTxt;
  115. }
  116. if (!string.IsNullOrEmpty(smallImg))
  117. {
  118. activity.Assets.SmallImage = smallImg;
  119. activity.Assets.SmallText = smallTxt;
  120. }
  121. if (!string.IsNullOrEmpty(partyId))
  122. {
  123. activity.Party.Id = partyId;
  124. activity.Party.Size.CurrentSize = partyCurrentSize;
  125. activity.Party.Size.MaxSize = partyMaxSize;
  126. }
  127. if (!string.IsNullOrEmpty(matchSecret) || !string.IsNullOrEmpty(joinSecret) || !string.IsNullOrEmpty(spectateSecret))
  128. {
  129. activity.Secrets.Match = matchSecret;
  130. activity.Secrets.Join = joinSecret;
  131. activity.Secrets.Spectate = spectateSecret;
  132. }
  133. discordRPC.GetActivityManager().UpdateActivity(activity, result =>
  134. {
  135. GamecraftModdingAPI.Utility.Logging.MetaLog($"Update Activity Result: {result} {debug}");
  136. });
  137. }
  138. public static void SetDiscordActivity(Discord.Discord discordRPC, Discord.Activity activity, string debug = "")
  139. {
  140. PresenceUtility.Activity = activity;
  141. discordRPC.GetActivityManager().UpdateActivity(PresenceUtility.Activity, result =>
  142. {
  143. GamecraftModdingAPI.Utility.Logging.MetaLog($"Update Activity Result: {result} {debug}");
  144. });
  145. }
  146. public static void SetDiscordActivity(Discord.Discord discordRPC, string debug = "")
  147. {
  148. discordRPC.GetActivityManager().UpdateActivity(PresenceUtility.Activity, result =>
  149. {
  150. GamecraftModdingAPI.Utility.Logging.MetaLog($"Update Activity Result: {result} {debug}");
  151. });
  152. }
  153. }
  154. }