Skip to content

Commit

Permalink
Merge pull request #3 from Georglider/master
Browse files Browse the repository at this point in the history
1.1.0
  • Loading branch information
Georglider authored Jan 10, 2023
2 parents c7a71cc + ba369a4 commit 58d0f39
Show file tree
Hide file tree
Showing 10 changed files with 234 additions and 160 deletions.
1 change: 1 addition & 0 deletions .idea/gradle.xml

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

10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@

## Start
1. Go to [Twitch Dev Console](https://dev.twitch.tv/console/apps) and create an app (As a category you can choose Game Integration)
2. Set OAuth redirect to your server ip with port like this: http://localhost:3000, don't forget to set this port to plugin's config.yml
1. If your server hosting does not allow you to open other ports, you can install this server to your computer and as address set http://localhost:{port} with your preferred port
2. Download VirtualTwitchServer and open it. (You can also open it via CLI if you pass any argument to startup script (java -jar VirtualTwitchServer.jar -cli))
1. Go to the Twitch Dev Console of your app and set OAuth Redirect URL like this: http://localhost:{PORT}/
2. Over here you need to put port which you have selected in the previous step
3. Click on Login with Twitch button and then paste your generated token into your config
3. Set your broadcaster_name in config as you have it on twitch
4. Copy Client ID and Client Secret to plugin's config.yml
5. Set how much time player can spend on your server after buying reward
1. 10 = 10 seconds
2. 5M = 5 minutes
3. 10H = 10 hours
4. 30D = 30 days
6. Start server and go to link from 2nd point
7. Here you need to click login and authorize through your Twitch account
8. Now you can change reward settings created by bot in [Twitch Dashboard](https://dashboard.twitch.tv/)
6. Now you can change reward settings created by bot in [Twitch Dashboard](https://dashboard.twitch.tv/)

### Please **do not** change app_access_token, user_access_token, reward_id and broadcaster_id if you don't know what you're doing

Expand Down
27 changes: 27 additions & 0 deletions VirtualTwitchServer/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
plugins {
id 'java'
}

group 'georglider'
version '1.1.0'

jar {
manifest {
attributes(
'Main-Class': 'georglider.twitch.Application'
)
}
}

repositories {
mavenCentral()
}

dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1'
}

test {
useJUnitPlatform()
}
153 changes: 153 additions & 0 deletions VirtualTwitchServer/src/main/java/georglider/twitch/Application.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
package georglider.twitch;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Scanner;

/**
* @author Georglider (Georglider#3660)
* <p> Main creation on 10.01.2023 at 20:46
**/

public class Application {

static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException, InterruptedException, URISyntaxException {
boolean cli = args.length > 0;

int port = Integer.parseInt(dialog("Please provide port which would be used for current session", cli));
String clientId = dialog("Please paste your clientId from Twitch here!", cli);

String token = startServer(port, clientId, cli);
System.out.println("\n" + token);
if (!cli) {
int a = JOptionPane.showConfirmDialog(null,
String.format("Here's your token %s, would you like to copy it?", token),
"Would you like to copy your token?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null);
if (a == 0) {
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(new StringSelection(token), null);
}
}
}

public static String startServer(int port, String clientId, Boolean cli) throws IOException, InterruptedException, URISyntaxException {
HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
String s = new InetSocketAddress(port).toString();
LoggedInHandler loggedInHandler = new LoggedInHandler();
StartHandler startHandler = new StartHandler(s, clientId);
server.createContext("/", startHandler);
server.createContext("/token", loggedInHandler);
server.setExecutor(null); // creates a default executor
server.start();

if (!cli && Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("http://localhost:" + port));
} else {
System.out.printf("Go to the http://localhost:%d", port);
}

while (loggedInHandler.token.equals("")) {
Thread.sleep(1000);
}
server.stop(10);
return loggedInHandler.token;
}

static class LoggedInHandler implements HttpHandler {
String token = "";

public LoggedInHandler() {
}

@Override
public void handle(HttpExchange t) throws IOException {
if (t.getRequestURI().toString().length() < 50) {
String response = """
<html>
<body>
<h1>Something went wrong, please try again!</h1>
</body>
</html>""";
t.sendResponseHeaders(401, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
} else {
this.token = t.getRequestURI().toString().substring(20, 50);

String response = String.format("""
<html>
<body>
<h1>Authenticated!</h1>
<h2>This is your token -> %s</h2>
</body>
</html>""", this.token);
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}

static class StartHandler implements HttpHandler {
private final String clientId;
private final String server;

public StartHandler(String server, String clientId) {
this.server = new StringBuilder(server.replace("0.0.0.0/0.0.0.0", "localhost")).insert(0, "http://").toString();
this.clientId = clientId;
}

@Override
public void handle(HttpExchange t) throws IOException {
String response = String.format("""
<html>
<body>
<a href=%s>Login with Twitch</a>
</body>
<script>
if (location.href.indexOf('#') != -1) {location.replace(location.href.replace('#', "token/"))}</script>
</html>""", ("https://id.twitch.tv/oauth2/authorize?client_id=" + clientId +
"&redirect_uri=" + server + "&response_type=token" +
"&scope=channel:manage:redemptions channel:read:redemptions"));
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}

public static String dialog(String message, Boolean cliMode) {
if (cliMode) {
System.out.println(message);

return scanner.nextLine();
}
return JOptionPane.showInputDialog(message);
}

}
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ plugins {
}

group = 'georglider'
version = '1.0.1'
version = '1.1.0'

repositories {
mavenCentral()
Expand Down
2 changes: 2 additions & 0 deletions settings.gradle
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
rootProject.name = 'twitch'
include 'VirtualTwitchServer'

71 changes: 35 additions & 36 deletions src/main/java/georglider/twitch/IntegrationApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,21 @@

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import georglider.twitch.api.TwitchAPIServer;
import georglider.twitch.data.ConfigManager;
import georglider.twitch.data.WhitelistManager;
import georglider.twitch.listeners.JoinLeaveListener;
import georglider.twitch.listeners.TwitchListenerAPI;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandException;
import org.bukkit.ChatColor;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import java.util.Objects;

public final class IntegrationApplication extends JavaPlugin {

Expand All @@ -30,45 +29,45 @@ public void onEnable() {
this.config = new ConfigManager(this);
this.whitelist = new WhitelistManager(this);

if (this.config.getConfig().get("user_access_token") == null || this.config.getConfig().getInt("user_access_token") != 0) {
System.out.println(this.config.getConfig().getInt("user_access_token"));
new BukkitRunnable() {
@Override
public void run() {
ConsoleCommandSender console = Bukkit.getConsoleSender();

console.sendMessage(String.valueOf(this.config.getConfig().getInt("app_access_token")));
console.sendMessage(Objects.requireNonNull(this.config.getConfig().getString("app_access_token")));

if (this.config.getConfig().getInt("app_access_token") == 8) {
if (this.config.getConfig().getInt("client_id") != 8) {
if (this.config.getConfig().getInt("client_secret") != 8) {
try {
ConfigManager setupConfig = IntegrationApplication.getPlugin(IntegrationApplication.class).config;
setupConfig.getConfig().set("user_access_token", TwitchAPIServer.startServer(config.getConfig().getInt("port"), config.getConfig().getString("client_id")));
setupConfig.saveConfig();
} catch (IOException | InterruptedException e) {
URL url = new URL("https://id.twitch.tv/oauth2/token?client_id="+ this.config.getConfig().getString("client_id")+"&client_secret="+this.config.getConfig().getString("client_secret")+"&grant_type=client_credentials&scope=channel:manage:redemptions%20channel:read:redemptions");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject json = new JsonParser().parse(reader).getAsJsonObject();

this.config.getConfig().set("app_access_token", json.get("access_token").getAsString());
this.config.saveConfig();
} catch (IOException e) {
console.sendMessage(ChatColor.DARK_RED + "Either client_id or client_secret is wrong. Please check your config file");
e.printStackTrace();
}
this.config.reloadConfig();
} else {
console.sendMessage(ChatColor.DARK_RED + "Please provide your client_secret into config file!");
}
}.runTask(this);
this.config.reloadConfig();
}
if (this.config.getConfig().get("app_access_token") == null || this.config.getConfig().getInt("app_access_token") != 0) {
try {
URL url = new URL("https://id.twitch.tv/oauth2/token?client_id="+ this.config.getConfig().getString("client_id")+"&client_secret="+this.config.getConfig().getString("client_secret")+"&grant_type=client_credentials&scope=channel:manage:redemptions%20channel:read:redemptions");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
JsonObject json = new JsonParser().parse(reader).getAsJsonObject();

this.config.getConfig().set("app_access_token", json.get("access_token").getAsString());
this.config.saveConfig();
} catch (IOException e) {
e.printStackTrace();
} else {
console.sendMessage(ChatColor.DARK_RED + "Please provide your client_id into config file!");
}
this.config.reloadConfig();
}


this.twitch = new TwitchListenerAPI();
getServer().getPluginManager().registerEvents(new JoinLeaveListener(), this);


console.sendMessage(String.valueOf(this.config.getConfig().getInt("user_access_token")));
if (this.config.getConfig().getInt("user_access_token") != 8) {
this.twitch = new TwitchListenerAPI();
getServer().getPluginManager().registerEvents(new JoinLeaveListener(), this);
} else {
console.sendMessage(ChatColor.DARK_RED + "Please provide your user_access_token into config file! You can get it via special jar");
}

//twitchClient.getEventManager().onEvent(UpdateRedemptionProgressEvent.class, System.out::println);
}
Expand Down
Loading

0 comments on commit 58d0f39

Please sign in to comment.