Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

League of Legends integration! #77

Merged
merged 6 commits into from
Feb 3, 2023
Merged
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
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions Classes/Integrations/Integration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RePlays.Integrations
{
public abstract class Integration
{
public abstract Task Start();
public abstract Task Shutdown();
}
}
106 changes: 106 additions & 0 deletions Classes/Integrations/LeagueOfLegendsIntegration.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using RePlays.Classes.Services;
using RePlays.Services;
using RePlays.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata.Ecma335;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using System.Timers;

namespace RePlays.Integrations
{
internal class LeagueOfLegendsIntegration : Integration
{
Timer timer = new Timer()
{
Interval = 250,
};

public override async Task Start()
{
Logger.WriteLine("Starting League Of Legends integration");
int lastKills = 0;
string username = await GetCurrentPlayerName();

if (username == null)
{
Logger.WriteLine("Could not get the current player name");
return;
}

timer.Elapsed += async (sender, e) =>
{
using (var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
})
using (HttpClient client = new HttpClient(handler))
{
try
{
string result = await client.GetStringAsync("https://127.0.0.1:2999/liveclientdata/playerscores?summonerName=" + username);
JsonDocument doc = JsonDocument.Parse(result);
JsonElement root = doc.RootElement;

int currentKills = root.GetProperty("kills").GetInt32();
if (currentKills != lastKills)
{
BookmarkService.AddBookmark(new Bookmark { type = Bookmark.BookmarkType.Kill });
Console.WriteLine("Kills changed to: " + currentKills);
lastKills = currentKills;
}
}
catch
{
if(!RecordingService.IsRecording || RecordingService.GetTotalRecordingTimeInSeconds() > 180)
{
timer.Stop();
await Shutdown();
}
}
}
};
timer.Start();
Logger.WriteLine("Successfully started League Of Legends integration");
}

public async override Task Shutdown()
{
Logger.WriteLine("Shutting down League Of Legends integration");
timer.Stop();
}

private async Task<string> GetCurrentPlayerName()
{
using (var handler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true
})
using (HttpClient client = new HttpClient(handler))
{
while (true)
{
try
{
return (await client.GetStringAsync("https://127.0.0.1:2999/liveclientdata/activeplayername")).Trim('\"');
}
catch (Exception ex)
{
if (RecordingService.IsRecording && RecordingService.GetTotalRecordingTimeInSeconds() > 180)
{
Logger.WriteLine("Could not get player name, error: " + ex.Message);
return null;
}
await Task.Delay(5000);
}
}
}
}

}
}
2 changes: 2 additions & 0 deletions Classes/Recorders/LibObsRecorder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public override void Start() {
}
else if (formattedMsg == "[game-capture: 'gameplay'] capture stopped") {
signalGCHookSuccess = false;
IntegrationService.Shutdown();
}
}
}
Expand Down Expand Up @@ -300,6 +301,7 @@ public override async Task<bool> StartRecording() {
Logger.WriteLine($"LibObs started recording [{session.Pid}] [{session.GameTitle}] [{windowClassNameId}]");
}

IntegrationService.Start(session.GameTitle);
return true;
}

Expand Down
36 changes: 25 additions & 11 deletions Classes/Services/BookmarkService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,30 @@
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace RePlays.Classes.Services
namespace RePlays.Services
{
internal static class BookmarkService
{
static List<int> bookmarks = new();
static List<Bookmark> bookmarks = new();
static int latestBookmarkKeyPress;

public static void AddBookmark()
public static void AddBookmark(Bookmark bookmark)
{
TimeSpan t = DateTime.UtcNow - new DateTime(1970, 1, 1);
int secondsSinceEpoch = (int)t.TotalSeconds;
int secondsSinceEpoch = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;

if (secondsSinceEpoch - latestBookmarkKeyPress >= 2)
if ((secondsSinceEpoch - latestBookmarkKeyPress >= 2) || !bookmark.type.Equals(Bookmark.BookmarkType.Manual))
{
latestBookmarkKeyPress = secondsSinceEpoch;
Logger.WriteLine("Adding bookmark: " + RecordingService.recordingElapsed);
bookmarks.Add(RecordingService.recordingElapsed);
double bookmarkTimestamp = RecordingService.GetTotalRecordingTimeInSecondsWithDecimals();
Logger.WriteLine("Adding bookmark: " + bookmarkTimestamp);
bookmark.time = bookmarkTimestamp;
bookmarks.Add(bookmark);

System.IO.Stream soundStream = Properties.Resources.bookmark;
System.Media.SoundPlayer bookmarkSound = new System.Media.SoundPlayer(soundStream);
bookmarkSound.Play();
if(bookmark.type.Equals(Bookmark.BookmarkType.Manual)){
System.IO.Stream soundStream = Properties.Resources.bookmark;
System.Media.SoundPlayer bookmarkSound = new System.Media.SoundPlayer(soundStream);
bookmarkSound.Play();
}
}
}

Expand All @@ -44,4 +47,15 @@ public static void ApplyBookmarkToSavedVideo(string videoName)
}
}
}

public class Bookmark
{
public enum BookmarkType
{
Manual,
Kill
}
public BookmarkType type { get; set; }
public double time { get; set; }
}
}
9 changes: 7 additions & 2 deletions Classes/Services/DetectionService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,14 +239,19 @@ public static async void AutoDetectGame(int processId, bool autoRecord = true)
var windowHandle = ActiveRecorder.GetWindowHandleByProcessId(processId, true);
var className = ActiveRecorder.GetClassName(windowHandle);
string gameTitle = GetGameTitle(executablePath);

string fileName = Path.GetFileName(executablePath);
try
{
FileVersionInfo fileInformation = FileVersionInfo.GetVersionInfo(executablePath);
bool hasBadWordInDescription = fileInformation.FileDescription != null ? blacklistList.Where(bannedWord => fileInformation.FileDescription.ToLower().Contains(bannedWord)).Any() : false;
bool hasBadWordInClassName = blacklistList.Where(bannedWord => className.ToLower().Contains(bannedWord)).Any() || blacklistList.Where(bannedWord => className.ToLower().Replace(" ", "").Contains(bannedWord)).Any();
bool hasBadWordInGameTitle = blacklistList.Where(bannedWord => gameTitle.ToLower().Contains(bannedWord)).Any() || blacklistList.Where(bannedWord => gameTitle.ToLower().Replace(" ", "").Contains(bannedWord)).Any();
if (hasBadWordInDescription || hasBadWordInClassName || hasBadWordInGameTitle) return;
bool hasBadWordInFileName = blacklistList.Where(bannedWord => fileName.ToLower().Contains(bannedWord)).Any() || blacklistList.Where(bannedWord => fileName.ToLower().Replace(" ", "").Contains(bannedWord)).Any();

bool isBlocked = hasBadWordInDescription || hasBadWordInClassName || hasBadWordInGameTitle || hasBadWordInFileName;
Logger.WriteLine($"{gameTitle}: hasBadWordInDescription: {hasBadWordInDescription}, hasBadWordInClassName: {hasBadWordInClassName}, hasBadWordInGameTitle: {hasBadWordInGameTitle}, hasBadWordInFileName: {hasBadWordInFileName}");
if (isBlocked) return;

}
catch(Exception e)
{
Expand Down
2 changes: 1 addition & 1 deletion Classes/Services/Hotkeys/BookmarkHotkey.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class BookmarkHotkey : Hotkey
private readonly string key = "CreateBookmark";
public override void Action()
{
if (RecordingService.IsRecording) BookmarkService.AddBookmark();
if (RecordingService.IsRecording) BookmarkService.AddBookmark(new Bookmark {type = Bookmark.BookmarkType.Manual});
}

protected override void SetKeybind()
Expand Down
35 changes: 35 additions & 0 deletions Classes/Services/IntegrationService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using RePlays.Integrations;
using System;
using System.Threading.Tasks;

namespace RePlays.Services
{
public static class IntegrationService
{
private static readonly String LEAGUE_OF_LEGENDS = "League of Legends";
public static Integration ActiveGameIntegration;
public static async void Start(String gameName)
{
if(gameName == LEAGUE_OF_LEGENDS)
{
ActiveGameIntegration = new LeagueOfLegendsIntegration();
}
else
{
ActiveGameIntegration = null;
}

if (ActiveGameIntegration == null)
return;

await Task.Run(() => ActiveGameIntegration.Start());
}

public static async void Shutdown()
{
if (ActiveGameIntegration == null)
return;
await Task.Run(() => ActiveGameIntegration.Shutdown());
}
}
}
23 changes: 16 additions & 7 deletions Classes/Services/RecordingService.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
using RePlays.Recorders;
using RePlays.Utils;
using System.Timers;
using System;
using System.Threading.Tasks;
using System.Timers;

namespace RePlays.Services {
namespace RePlays.Services
{
public static class RecordingService {
public static BaseRecorder ActiveRecorder;

private static Timer recordingTimer = new Timer(1000);
public static int recordingElapsed = 0;
private static Timer recordingTimer = new Timer(100);
public static DateTime startTime;
public static double lastVideoDuration = 0;
private static Session currentSession = new(0, "Game Unknown");
public static bool IsRecording { get; internal set; }
Expand Down Expand Up @@ -67,6 +68,7 @@ public static async void StartRecording() {
if (!IsRecording && result) {
Logger.WriteLine("Current Session PID: " + currentSession.Pid.ToString());
if (currentSession.Pid != 0) {
startTime = DateTime.Now;
recordingTimer.Elapsed += OnTimedEvent;
recordingTimer.Start();

Expand All @@ -87,8 +89,7 @@ public static async void StartRecording() {
}

private static void OnTimedEvent(object source, ElapsedEventArgs e) {
recordingElapsed++;
WebMessage.DisplayToast("Recording", currentSession.GameTitle, "🔴 Recording", "none", recordingElapsed);
WebMessage.DisplayToast("Recording", currentSession.GameTitle, "🔴 Recording", "none", GetTotalRecordingTimeInSeconds());
}

public static async void StopRecording() {
Expand All @@ -98,7 +99,6 @@ public static async void StopRecording() {

if (IsRecording && result) {
if(currentSession.Pid != 0) {
recordingElapsed = 0;
recordingTimer.Elapsed -= OnTimedEvent;
recordingTimer.Stop();
Logger.WriteLine(string.Format("Stop Recording: {0}, {1}", currentSession.Pid, currentSession.GameTitle));
Expand Down Expand Up @@ -138,5 +138,14 @@ public static void GainedFocus()
GameInFocus = true;
ActiveRecorder.GainedFocus();
}

public static int GetTotalRecordingTimeInSeconds()
{
return (int)(DateTime.Now - startTime).TotalSeconds;
}
public static double GetTotalRecordingTimeInSecondsWithDecimals()
{
return (DateTime.Now - startTime).TotalMilliseconds/1000;
}
}
}
5 changes: 1 addition & 4 deletions Classes/Utils/Messages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@
using RePlays.Services;
using static RePlays.Utils.Functions;
using static RePlays.Services.SettingsService;
using static RePlays.Utils.CaptureSettings;
using static RePlays.Utils.Compression;
using System.Globalization;
using System.IO.Pipes;

namespace RePlays.Utils {
public class RetrieveVideos {
Expand Down Expand Up @@ -375,7 +372,7 @@ public static void DestroyToast(string id) {
SendMessage(JsonSerializer.Serialize(webMessage));
}

public static void SetBookmarks(string videoName, List<int> bookmarks, double elapsed)
public static void SetBookmarks(string videoName, List<Bookmark> bookmarks, double elapsed)
{

WebMessage webMessage = new();
Expand Down
8 changes: 5 additions & 3 deletions ClientApp/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useRef } from 'react';
import Settings from './pages/Settings';
import Modal from './components/Modal';
import Toast from './components/Toast';
import {BookmarkType} from './index';

export const ContextMenuContext = createContext<ContextMenuOptions | null>(null);
export const ModalContext = createContext<ModalOptions | null>(null);
Expand Down Expand Up @@ -94,11 +95,12 @@ function App() {
let videoMetadata = JSON.parse(localStorage.getItem("videoMetadataBookmarks")!);


let bookmarks: { id: number, time: number }[] = [];
let bookmarks: { id: number, type: BookmarkType, time: number }[] = [];
const map = [BookmarkType.Manual, BookmarkType.Kill];

data.bookmarks.forEach(function (bookmark: any) {
let time = bookmark / (data.elapsed) * 100;
bookmarks.push({ id: Date.now(), time: time });
let timeToSet = bookmark.time / (data.elapsed) * 100;
bookmarks.push({ id: Date.now(), type: map[bookmark.type], time: timeToSet });
});

videoMetadata[data.videoname] = { bookmarks };
Expand Down
Loading