Skip to content
This repository has been archived by the owner on Jun 20, 2019. It is now read-only.

Commit

Permalink
Update to new Twitch API stuffs
Browse files Browse the repository at this point in the history
  • Loading branch information
dries007 committed Jun 3, 2015
1 parent 2fc5f28 commit 08ca443
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 39 deletions.
5 changes: 4 additions & 1 deletion build.gradle
Expand Up @@ -28,7 +28,7 @@ apply plugin: "maven"
apply plugin: "idea-utils"

group = "net.doubledoordev.ftsw"
version = "1.1.0"
version = "1.2.0"

targetCompatibility = 1.7
sourceCompatibility = 1.7
Expand Down Expand Up @@ -88,6 +88,9 @@ task deobfJar(type: Jar) {
jar {
from "LICENSE.txt"
appendix = project.minecraft.version
manifest {
attributes 'ModSide': 'SERVER'
}
}

artifacts {
Expand Down
126 changes: 98 additions & 28 deletions src/main/java/net/doubledoordev/ftsw/ForgeTwitchSubWhitelist.java
Expand Up @@ -31,6 +31,8 @@
package net.doubledoordev.ftsw;

import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
Expand All @@ -41,12 +43,18 @@
import cpw.mods.fml.relauncher.Side;
import net.minecraft.network.NetHandlerPlayServer;
import net.minecraft.server.management.ServerConfigurationManager;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.config.Configuration;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.lwjgl.Sys;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
* @author Dries007
Expand All @@ -55,24 +63,58 @@
public class ForgeTwitchSubWhitelist
{
public static final String MODID = "ForgeTwitchSubWhitelist";
public static final String CHECK_TWITCH_URL = "http://www.twitch.tv/api/channels/%s/subscriptions/%s?oauth_token=%s";
public static final String GET_TWITCH_NAME_URL = "http://doubledoordev.net/getTwitchName.php?uuid=%s";
// check that a user is subbed
public static final String CHECK_TWITCH_URL = "https://api.twitch.tv/kraken/channels/$CHANNEL$/subscriptions/$USER$?oauth_token=$TOKEN$";
// verify that the token works
public static final String VERIFY_TWITCH_URL = "https://api.twitch.tv/kraken/channels/$CHANNEL$/subscriptions?limit=1&oauth_token=$TOKEN$";
public static final String GET_TWITCH_NAME_URL = "http://doubledoordev.net/getTwitchName.php?uuid=$UUID$";
public static final String NOT_LINKED = "You need to link your MC and Twitch accounts! Go to http://www.doubledoordev.net/?p=twitch";

public static final Gson GSON = new Gson();
public static final Map<String, Long> SUB_END_DATE_MAP = new HashMap<>();

@Mod.Instance(MODID)
public static ForgeTwitchSubWhitelist instance;
private Configuration configuration;

private String kickMsg = "You must be subscribed to $CHANNEL$ to join this server. http://www.twitch.tv/$CHANNEL$";
private String twitchToken;
private String channel;
private File jsonFile;

@Mod.EventHandler
public void init(FMLPreInitializationEvent event)
public void init(FMLPreInitializationEvent event) throws IOException
{
configuration = new Configuration(event.getSuggestedConfigurationFile());
syncConfig();

FMLCommonHandler.instance().bus().register(this);

configuration = new Configuration(event.getSuggestedConfigurationFile());
jsonFile = new File(event.getModConfigurationDirectory(), MODID.concat(".json"));
if (jsonFile.exists())
{
SUB_END_DATE_MAP.putAll(GSON.<Map<? extends String, ? extends Long>>fromJson(FileUtils.readFileToString(jsonFile), new TypeToken<Map<String, Long>>()
{
}.getType()));
}

syncConfig();
if (Strings.isNullOrEmpty(twitchToken) || Strings.isNullOrEmpty(channel))
{
RuntimeException e = new RuntimeException("\n\nYour TwitchToken or Channel are missing from the " + MODID + " config.\n\n");
e.setStackTrace(new StackTraceElement[0]);
throw e;
}

event.getModLog().info("Trying out the channel & twitchtoken. This could take a couple of seconds.");
try
{
//noinspection ResultOfMethodCallIgnored
IOUtils.toString(new URL(VERIFY_TWITCH_URL.replace("$CHANNEL$", channel).replace("$TOKEN$", twitchToken)));
}
catch (IOException ex)
{
RuntimeException e = new RuntimeException("\n\nYour TwitchToken or Channel are wrong or expired, or you are not partnered. Update them in the " + MODID + " config.\n\nDO NOT POST THIS LOG ANYWHERE ONLINE WITHOUT REMOVING THE URL IN THE LINE BELOW!\n", ex);
e.setStackTrace(new StackTraceElement[0]);
throw e;
}
}

@NetworkCheckHandler
Expand All @@ -84,6 +126,7 @@ public boolean networkCheckHandler(Map<String, String> map, Side side)
@Mod.EventHandler
public void init(FMLServerStartingEvent event)
{
if (event.getSide().isServer()) return;
event.registerServerCommand(new InfoCommand());
}

Expand All @@ -99,40 +142,67 @@ public void run()
ServerConfigurationManager scm = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager();
scm.setWhiteListEnabled(true);

NetHandlerPlayServer handler = ((NetHandlerPlayServer) event.handler);

if (scm.func_152607_e(handler.playerEntity.getGameProfile())) return; // op or whitelisted

String twitchName;
try
{
twitchName = IOUtils.toString(new URL(String.format(GET_TWITCH_NAME_URL, handler.playerEntity.getUniqueID().toString()))).trim();
}
catch (IOException e)
{
twitchName = handler.playerEntity.getCommandSenderName();
NetHandlerPlayServer handler = ((NetHandlerPlayServer) event.handler);

if (scm.func_152607_e(handler.playerEntity.getGameProfile())) return; // op or whitelisted

String twitchName = lookupUsername(handler.playerEntity.getGameProfile().getId());
if (Strings.isNullOrEmpty(twitchName))
{
handler.kickPlayerFromServer(NOT_LINKED);
return;
}
System.out.println(twitchName);
if (!SUB_END_DATE_MAP.containsKey(twitchName) || SUB_END_DATE_MAP.get(twitchName) - System.currentTimeMillis() > 0) // Not yet known or cache expired
{
try
{
//noinspection ResultOfMethodCallIgnored
IOUtils.toString(new URL(CHECK_TWITCH_URL.replace("$CHANNEL$", channel).replace("$TOKEN$", twitchToken).replace("$USER$", twitchName))); // this is what fails if not subbed
SUB_END_DATE_MAP.put(twitchName, System.currentTimeMillis() + (1000 * 60 * 60 * 24)); // 24h cache period
FileUtils.writeStringToFile(jsonFile, GSON.toJson(SUB_END_DATE_MAP));
}
catch (IOException e)
{
handler.kickPlayerFromServer(kickMsg.replace("$CHANNEL$", channel));
}
}
}
if (Strings.isNullOrEmpty(twitchName)) handler.kickPlayerFromServer("You need to link you MC and Twitch on:\nhttp://www.doubledoordev.net/?p=twitch");
try
finally
{
//noinspection ResultOfMethodCallIgnored
IOUtils.toString(new URL(String.format(CHECK_TWITCH_URL, channel, twitchName, twitchToken)));
scm.setWhiteListEnabled(false);
}
catch (IOException e)
{
handler.kickPlayerFromServer(String.format("You must be subscribed to %s to join this server.", channel));
}

scm.setWhiteListEnabled(false);
}
}).start();
}

public void syncConfig()
{
configuration.addCustomCategoryComment(MODID, "This information is required for server side operation.");

twitchToken = configuration.getString("twitchToken", MODID, "", "Get it from http://www.doubledoordev.net/?p=twitch");
channel = configuration.getString("channel", MODID, "", "Cap sensitive!");
channel = configuration.getString("channel", MODID, "", "");
kickMsg = configuration.getString("kickMsg", MODID, kickMsg, "You can use $CHANNEL$ to insert the channel name.");

if (configuration.hasChanged()) configuration.save();
}

public static String lookupUsername(UUID uuid)
{
String twitchName = null;
try
{
twitchName = IOUtils.toString(new URL(GET_TWITCH_NAME_URL.replace("$UUID$", uuid.toString())));
int firstLineEnd = twitchName.indexOf('\n');
if (firstLineEnd != -1) twitchName = twitchName.substring(0, firstLineEnd);
twitchName = twitchName.trim();
}
catch (IOException e)
{
e.printStackTrace();
}
return twitchName;
}
}
11 changes: 1 addition & 10 deletions src/main/java/net/doubledoordev/ftsw/InfoCommand.java
Expand Up @@ -79,16 +79,7 @@ public void run()
for (String arg : args)
{
GameProfile profile = MinecraftServer.getServer().func_152358_ax().func_152655_a(arg);
String twitchName = null;
try
{
twitchName = IOUtils.toString(new URL(String.format(ForgeTwitchSubWhitelist.GET_TWITCH_NAME_URL, profile.getId().toString()))).trim();
}
catch (IOException e)
{

}
if (Strings.isNullOrEmpty(twitchName)) twitchName = "???";
String twitchName = ForgeTwitchSubWhitelist.lookupUsername(profile.getId());
sender.addChatMessage(new ChatComponentText(arg).appendText(" -> ").appendSibling(new ChatComponentText(twitchName).setChatStyle(new ChatStyle().setColor(EnumChatFormatting.GOLD))));
}
}
Expand Down

0 comments on commit 08ca443

Please sign in to comment.