Skip to content

Commit b69b54c

Browse files
committed
Committing
1 parent 73db48e commit b69b54c

10 files changed

Lines changed: 197 additions & 31 deletions

File tree

pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,12 @@
8585
<artifactId>twitch4j</artifactId>
8686
<version>1.20.0</version>
8787
</dependency>
88+
<!-- https://mvnrepository.com/artifact/org.json/json -->
89+
<dependency>
90+
<groupId>org.json</groupId>
91+
<artifactId>json</artifactId>
92+
<version>20240303</version>
93+
</dependency>
8894
</dependencies>
8995

9096
</project>

src/main/java/simplexity/Main.java

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,11 @@
88
import simplexity.commands.HelpCommand;
99
import simplexity.commands.ReloadCommand;
1010
import simplexity.config.TTSConfig;
11+
import simplexity.httpserver.AuthServer;
1112
import simplexity.messages.Errors;
13+
import simplexity.messages.Output;
1214
import simplexity.twitch.TwitchClientHandler;
15+
import simplexity.twitch.TwitchSetup;
1316

1417
import java.util.Scanner;
1518

@@ -18,24 +21,28 @@ public class Main {
1821
private static PollyHandler pollyHandler;
1922
private static SpeechHandler speechHandler;
2023
private static TwitchClientHandler twitchClientHandler;
24+
private static TwitchSetup twitchSetup;
25+
public static Scanner scanner;
2126

2227
public static void main(String[] args) {
23-
Scanner scanner = new Scanner(System.in);
28+
scanner = new Scanner(System.in);
2429
commandManager = new CommandManager();
2530
registerCommands(commandManager);
2631
TTSConfig.getInstance().reloadConfig();
2732
pollyHandler = createPollyHandler();
2833
speechHandler = new SpeechHandler();
2934
twitchClientHandler = new TwitchClientHandler();
35+
twitchSetup = new TwitchSetup();
36+
twitchSetup.setup();
3037
twitchClientHandler.setupClient();
3138
twitchClientHandler.getTwitchClient().getChat().joinChannel("RhythmWeHear");
32-
System.out.println(twitchClientHandler.getTwitchClient().getChat().sendMessage("RhythmWeHear", "Test"));
3339
while (true) {
3440
String input = scanner.nextLine();
3541
if (input.equals("--exit")) {
36-
break;
42+
return;
3743
}
3844
if (!commandManager.runCommand(input)) {
45+
twitchClientHandler.getTwitchClient().getChat().sendMessage("RhythmWeHear", input);
3946
speechHandler.processSpeech(input);
4047
} else {
4148
System.out.println("command executed");

src/main/java/simplexity/config/SimplexityFileHandler.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,10 @@ private void createConfigFile(){
4040
}
4141
}
4242

43-
public static void createTwitchFile(String authCode){
43+
public static void createTwitchFile(String accessToken){
4444
File file = new File("twitch-oauth.conf");
4545
try (FileWriter writer = new FileWriter(file)) {
46-
writer.write(ConfigDefaults.TWITCH_OAUTH.replace("%code%", authCode));
46+
writer.write("twitch-oauth=\"" + accessToken + "\"");
4747
} catch (Exception e){
4848
System.out.println(Errors.CAUGHT_EXCEPTION.replace("%error%", e.getMessage()));
4949
}

src/main/java/simplexity/httpserver/AuthHandler.java

Lines changed: 73 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,26 +2,89 @@
22

33
import com.sun.net.httpserver.HttpExchange;
44
import com.sun.net.httpserver.HttpHandler;
5+
import org.json.JSONException;
6+
import org.json.JSONObject;
57
import simplexity.config.SimplexityFileHandler;
68
import simplexity.messages.Errors;
79

10+
import java.io.BufferedReader;
811
import java.io.IOException;
12+
import java.io.InputStreamReader;
913
import java.io.OutputStream;
14+
import java.net.HttpURLConnection;
15+
import java.net.URL;
1016

1117
public class AuthHandler implements HttpHandler {
1218
@Override
1319
public void handle(HttpExchange exchange) {
1420
try {
15-
String twitchCode = exchange.getRequestURI().getQuery().split("=")[1];
16-
twitchCode = twitchCode.split("&")[0];
17-
System.out.println(twitchCode);
18-
SimplexityFileHandler.createTwitchFile(twitchCode);
19-
String response = "<h1>HI</h1>";
20-
exchange.sendResponseHeaders(200, response.length());
21-
OutputStream os = exchange.getResponseBody();
22-
os.write(response.getBytes());
23-
os.close();
24-
} catch (IOException e) {
21+
String query = exchange.getRequestURI().getQuery();
22+
String[] params = query.split("&");
23+
String twitchCode = "";
24+
for (String param : params) {
25+
if (param.startsWith("code=")) {
26+
twitchCode = param.split("=")[1];
27+
}
28+
}
29+
30+
if (!twitchCode.isEmpty()) {
31+
// Exchange the authorization code for an access token
32+
String clientId = "";
33+
String clientSecret = "";
34+
String redirectUri = "http://localhost:3000";
35+
String tokenUrl = "https://id.twitch.tv/oauth2/token";
36+
37+
URL url = new URL(tokenUrl);
38+
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
39+
connection.setRequestMethod("POST");
40+
connection.setDoOutput(true);
41+
String postData = String.format(
42+
"client_id=%s&client_secret=%s&code=%s&grant_type=authorization_code&redirect_uri=%s",
43+
clientId, clientSecret, twitchCode, redirectUri
44+
);
45+
46+
try (OutputStream os = connection.getOutputStream()) {
47+
os.write(postData.getBytes());
48+
os.flush();
49+
}
50+
51+
int responseCode = connection.getResponseCode();
52+
if (responseCode == HttpURLConnection.HTTP_OK) {
53+
try (BufferedReader responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
54+
String responseLine;
55+
StringBuilder responseBuilder = new StringBuilder();
56+
while ((responseLine = responseReader.readLine()) != null) {
57+
responseBuilder.append(responseLine);
58+
}
59+
60+
String response = responseBuilder.toString();
61+
JSONObject json = new JSONObject(response);
62+
String accessToken = json.getString("access_token");
63+
64+
// Save the access token for later use
65+
SimplexityFileHandler.createTwitchFile(accessToken);
66+
67+
String successResponse = "<h1>Authorization successful! You can close this window.</h1>";
68+
exchange.sendResponseHeaders(200, successResponse.length());
69+
OutputStream os = exchange.getResponseBody();
70+
os.write(successResponse.getBytes());
71+
os.close();
72+
}
73+
} else {
74+
String errorResponse = "<h1>Authorization failed!</h1>";
75+
exchange.sendResponseHeaders(500, errorResponse.length());
76+
OutputStream os = exchange.getResponseBody();
77+
os.write(errorResponse.getBytes());
78+
os.close();
79+
}
80+
} else {
81+
String errorResponse = "<h1>No authorization code found!</h1>";
82+
exchange.sendResponseHeaders(400, errorResponse.length());
83+
OutputStream os = exchange.getResponseBody();
84+
os.write(errorResponse.getBytes());
85+
os.close();
86+
}
87+
} catch (IOException | JSONException e) {
2588
System.out.println(Errors.CAUGHT_EXCEPTION.replace("%error%", e.getMessage()));
2689
}
2790
}

src/main/java/simplexity/httpserver/AuthServer.java

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import java.net.InetSocketAddress;
88

99
public class AuthServer {
10-
1110
public static HttpServer server;
1211

1312
public static void run() {
@@ -17,6 +16,7 @@ public static void run() {
1716
System.out.println(Errors.CAUGHT_EXCEPTION.replace("%error%", exception.getMessage()));
1817
}
1918
}
19+
2020
public static void stop() {
2121
server.stop(0);
2222
}
@@ -31,4 +31,6 @@ private static void setupServer() {
3131
System.out.println(Errors.CAUGHT_EXCEPTION.replace("%error%", exception.getMessage()));
3232
}
3333
}
34+
35+
3436
}

src/main/java/simplexity/messages/Errors.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,5 +46,25 @@ public class Errors {
4646
ERROR: %error%
4747
""" + ConsoleColors.RESET;
4848

49+
public static final String TWITCH_AUTH_NULL =
50+
ConsoleColors.RED_BRIGHT + """
51+
ERROR: Twitch auth is null
52+
""" + ConsoleColors.RESET;
53+
54+
public static final String NO_CHANNEL_PROVIDED =
55+
ConsoleColors.RED_BRIGHT + """
56+
ERROR: You have set 'connect-to-twitch' to true but have not provided a channel to connect to.
57+
""" + ConsoleColors.RESET;
58+
59+
public static final String NO_OAUTH_PROVIDED =
60+
ConsoleColors.RED_BRIGHT + """
61+
ERROR: You have set 'connect-to-twitch' to true but have not authorized this application to connect to twitch.
62+
""" + ConsoleColors.RESET;
63+
64+
public static final String INVALID_INPUT =
65+
ConsoleColors.RED_BRIGHT + """
66+
ERROR: Invalid input
67+
""" + ConsoleColors.RESET;
68+
4969

5070
}

src/main/java/simplexity/messages/Output.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,5 +8,10 @@ public class Output {
88
+ ConsoleColors.WHITE + "- " + ConsoleColors.RESET + ConsoleColors.BLUE_BRIGHT + "%command_description%"
99
+ ConsoleColors.RESET;
1010
public static final String RELOAD_MESSAGE = ConsoleColors.GREEN_BOLD_BRIGHT + "Config reloaded" + ConsoleColors.RESET;
11+
public static final String WANT_TO_AUTH_MESSAGE = ConsoleColors.BLUE_BOLD_BRIGHT + "Do you want to authenticate with Twitch? (y/n)" + ConsoleColors.RESET;
12+
public static final String OPEN_LINK_MESSAGE = ConsoleColors.BLUE_BOLD_BRIGHT + "Please open this link in your browser" + ConsoleColors.RESET;
1113
public static final String TWITCH_AUTH_URL = "https://id.twitch.tv/oauth2/authorize?response_type=code&client_id=r0ret1izmdz1alwyq98d2lgjyo0h5r&redirect_uri=http://localhost:3000&scope=chat%3Aread+chat%3Aedit";
14+
public static final String SKIPPING_TWITCH_SETUP = ConsoleColors.YELLOW_BOLD_BRIGHT + "Skipping Twitch setup.." + ConsoleColors.RESET;
15+
public static final String PRESS_ENTER_TO_CONTINUE = ConsoleColors.BLUE_BOLD_BRIGHT + "Press enter to continue" + ConsoleColors.RESET;
16+
public static final String AUTH_SUCCESS = ConsoleColors.GREEN_BOLD_BRIGHT + "Authentication successful" + ConsoleColors.RESET;
1217
}

src/main/java/simplexity/twitch/OAuthLogic.java

Lines changed: 0 additions & 6 deletions
This file was deleted.

src/main/java/simplexity/twitch/TwitchClientHandler.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,28 +4,28 @@
44
import com.github.twitch4j.TwitchClient;
55
import com.github.twitch4j.TwitchClientBuilder;
66
import simplexity.config.TTSConfig;
7+
import simplexity.messages.Errors;
78

89
public class TwitchClientHandler {
910

1011
OAuth2Credential oAuth2Credential;
1112
TwitchClient twitchClient;
1213

13-
public boolean setupClient(){
14+
public boolean setupClient() {
1415
String twitchOAuth = TTSConfig.getInstance().getTwitchOAuth();
15-
if (twitchOAuth == null) {
16-
System.out.println("TWITCH OAUTH IS NULL");
16+
if (twitchOAuth == null || twitchOAuth.isEmpty()) {
17+
System.out.println(Errors.NO_OAUTH_PROVIDED);
1718
return false;
1819
}
19-
oAuth2Credential = new OAuth2Credential("twitch", TTSConfig.getInstance().getTwitchOAuth());
20-
twitchClient = TwitchClientBuilder.builder().withEnableChat(true).withChatAccount(oAuth2Credential).build();
20+
oAuth2Credential = new OAuth2Credential("twitch", twitchOAuth);
21+
twitchClient = TwitchClientBuilder.builder()
22+
.withEnableChat(true)
23+
.withChatAccount(oAuth2Credential)
24+
.build();
2125
return true;
2226
}
2327

2428
public TwitchClient getTwitchClient() {
2529
return twitchClient;
2630
}
27-
28-
29-
30-
3131
}
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package simplexity.twitch;
2+
3+
import simplexity.Main;
4+
import simplexity.config.TTSConfig;
5+
import simplexity.httpserver.AuthServer;
6+
import simplexity.messages.Errors;
7+
import simplexity.messages.Output;
8+
9+
import java.util.concurrent.CountDownLatch;
10+
11+
public class TwitchSetup {
12+
13+
private static final CountDownLatch latch = new CountDownLatch(1);
14+
15+
public void setup() {
16+
if (!checkConfig()) return;
17+
if (!checkAuth()){
18+
if (!requestAuth()) return;
19+
if (!checkAuth()) {
20+
System.out.println(Output.PRESS_ENTER_TO_CONTINUE);
21+
Main.scanner.nextLine();
22+
TTSConfig.getInstance().reloadConfig();
23+
AuthServer.stop();
24+
}
25+
if (checkAuth()) {
26+
System.out.println(Output.AUTH_SUCCESS);
27+
}
28+
}
29+
}
30+
31+
public boolean checkConfig() {
32+
String twitchChannel = TTSConfig.getInstance().getTwitchChannel();
33+
boolean useTwitch = TTSConfig.getInstance().isConnectToTwitch();
34+
if (!useTwitch) return false;
35+
if (twitchChannel.isEmpty()) {
36+
System.out.println(Errors.NO_CHANNEL_PROVIDED);
37+
return false;
38+
}
39+
return true;
40+
}
41+
42+
public boolean checkAuth() {
43+
String twitchOAuth = TTSConfig.getInstance().getTwitchOAuth();
44+
if (twitchOAuth == null || twitchOAuth.isEmpty()) {
45+
return false;
46+
}
47+
return true;
48+
}
49+
50+
public boolean requestAuth() {
51+
System.out.println(Errors.NO_OAUTH_PROVIDED);
52+
System.out.println(Output.WANT_TO_AUTH_MESSAGE);
53+
String input = Main.scanner.nextLine();
54+
while (true) {
55+
switch (input.toLowerCase()) {
56+
case "y":
57+
System.out.println(Output.OPEN_LINK_MESSAGE);
58+
System.out.println(Output.TWITCH_AUTH_URL);
59+
AuthServer.run();
60+
return true;
61+
case "n":
62+
System.out.println(Output.SKIPPING_TWITCH_SETUP);
63+
return false;
64+
default:
65+
System.out.println(Errors.INVALID_INPUT);
66+
}
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)