Skip to content

Commit

Permalink
Reimplemented globals (broadcasts) tracking.
Browse files Browse the repository at this point in the history
Now tMediator makes API request and gets info from json instead of parsing forum.
  • Loading branch information
al-arz committed Aug 2, 2016
1 parent 5dad6e7 commit eccfd4c
Show file tree
Hide file tree
Showing 10 changed files with 99 additions and 76 deletions.
Binary file added tMediator/libs/gson-2.7.jar
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.seroperson.mediator.parsing;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateDeserializer implements JsonDeserializer<Date>{
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
return format.parse(json.getAsString());
} catch (ParseException e) {
System.err.println(e.getMessage());
}
return new Date();
}
}
72 changes: 26 additions & 46 deletions tMediator/src/com/seroperson/mediator/parsing/Parser.java
Original file line number Diff line number Diff line change
@@ -1,35 +1,29 @@
package com.seroperson.mediator.parsing;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.seroperson.mediator.tori.stuff.Global;
import com.seroperson.mediator.tori.stuff.Player;
import com.seroperson.mediator.tori.stuff.Server;
import com.seroperson.mediator.tori.stuff.*;
import com.seroperson.mediator.utils.ThrowHandler;

public class Parser {

private final static DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
private final static String TORIBASH = "TORIBASH";
private final static String REGEXP_SERVER = "([\\d{1,3}\\.]+):(\\d{1,})\\s(\\p{ASCII}+)";
private final static String REGEXP_CLIENT = "[^\\s]+\\w";
private final static String REGEXP_MOD = "[^\\s]+\\.tbm";
private final static String REGEXP_COLORS = "\\^\\d{2}+";
private final static String REGEXP_JOIN_CMD = "[\\\\\\/][jJ][oO]\\s(\\w+)";
private final static char[][] limiters = new char[][] { new char[] { '[', ']' }, new char[] { '(', ')' } };
private static String prevGlobal = "";
public final static String CNONE = "none";

public static Server[] getServers(final ThrowHandler th, final String npservers) {
Expand All @@ -52,36 +46,24 @@ public static Server[] getServers(final ThrowHandler th, final String npservers)
}

public static Global getGlobal(String npglobal) throws Throwable {
if(!npglobal.contains("latest_broadcast"))
//ToDo: probly there is more elegant solution but I'm dumb and lazy
if (npglobal.equals(prevGlobal))
return null;

/* message may contain incorrect attribute for xml :c */
npglobal = npglobal.replaceAll("~<a href=\"member.php\\?u=\\d{0,9}\">+\\p{ASCII}+", "</div>");

final long date;
final DocumentBuilder docbuilder = factory.newDocumentBuilder();
final InputStream stream = new ByteArrayInputStream(npglobal.getBytes());
final String message;
final String player;
final String server;
final Document doc;

try {
doc = docbuilder.parse(stream);
}
finally {
stream.close();
}

final NodeList div = doc.getElementsByTagName("div");
final Node node = div.item(0);

message = node.getTextContent().trim();
player = node.getAttributes().getNamedItem("data-username").getTextContent().trim();
server = node.getAttributes().getNamedItem("data-room").getTextContent().trim();
date = System.currentTimeMillis();
prevGlobal = npglobal;

final GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(Date.class, new DateDeserializer());
final Gson gson = gsonb.create();

return new Global(message, date, server, player);
final Broadcast bc = gson.fromJson(npglobal, Broadcast.class);
final BroadcastedMessage global = bc.broadcasts[0];
final Matcher roomMatcher = Pattern.compile(REGEXP_JOIN_CMD).matcher(global.message);
final String room;
if (roomMatcher.find())
room = roomMatcher.group(1);
else
room = "unknown room";
return new Global(global.message.trim().replaceAll(REGEXP_COLORS, ""), global.post_time.getTime(), room, global.username);
}

@SuppressWarnings("unused")
Expand Down Expand Up @@ -148,14 +130,12 @@ private static Object[] handleString(final String fullStr, final StringTokenizer
mod = "classic";
break NEWGAME;
}
/*if (currentStr.contains(" beginnerlobby ")) {
mod = "classic";
break NEWGAME;
}*/
final Pattern pattern = Pattern.compile(REGEXP_MOD);
final Matcher matcher = pattern.matcher(currentStr);
matcher.find();
mod = "classic";//matcher.group().trim();
if (matcher.find())
mod = matcher.group().trim();
else
mod = "undefined mod";
}

if(st.hasMoreTokens())
Expand Down
33 changes: 12 additions & 21 deletions tMediator/src/com/seroperson/mediator/refresh/Refresher.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,42 +25,33 @@ public class Refresher extends ServerHandler {

private Socket socket;
private final ServerViewerContainer container;
private final URL forum;
private final URL broadcasts;

public Refresher(final RefreshHandler handler, ServerViewerContainer con) throws MalformedURLException {
super(handler);
container = con;
forum = new URL(Mediator.getMediator().getSettings().getForumURI());
broadcasts = new URL(Mediator.getMediator().getSettings().getBroadcastURL());
}

protected Global getGlobal() throws Throwable {
if(!Mediator.getMediator().getSettings().isGlobalsTracking())
return null;

final URLConnection connection = forum.openConnection();
final URLConnection connection = broadcasts.openConnection();
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64)");
connection.connect();
//final Scanner reader = new Scanner(new InputStreamReader(connection.getInputStream()));
//ToDo: check server response
final Scanner reader = new Scanner(new InputStreamReader(connection.getInputStream()));
final StringBuilder builder = new StringBuilder();
/*try {
while(reader.hasNextLine()) {
final String str = reader.nextLine();
if(str.contains("<!-- latest ingame broadcast -->")) {
while(true) {
final String string = reader.nextLine();
if(string.contains("<!-- / latest ingame broadcast -->"))
break;
builder.append(string);
}
break;
}
if(str.contains("<!-- nav buttons bar -->")) // too late
break;
}
try {
builder.append(reader.nextLine());
}
catch (Exception ex) {
System.err.println(ex.getMessage());
}
finally {
reader.close();
}*/
builder.append("No globals");
}
return Parser.getGlobal(builder.toString());
}

Expand Down
11 changes: 6 additions & 5 deletions tMediator/src/com/seroperson/mediator/settings/Settings.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public class Settings {
static {
final SettingsDef def = new SettingsDef();
def.rooms = new String[1];
//ToDo: should definitely update this :)
def.names = new String[] { "hampa", "nirs", "korvin", "slipanc" };
def.clans = new String[] { "Aliens", "Impro", "Imba", "Abyss" };
defaultsettings = new Settings(def);
Expand All @@ -18,7 +19,7 @@ public class Settings {
private final int port;
private final int sort;
private final String server;
private final String forum_uri;
private final String broadcast_url;

private final String[] names;
private final String[] clans;
Expand All @@ -38,7 +39,7 @@ public Settings() {
period = defaultsettings.period;
port = defaultsettings.port;
sort = defaultsettings.sort;
forum_uri = defaultsettings.forum_uri;
broadcast_url = defaultsettings.broadcast_url;
server = defaultsettings.server;
names = defaultsettings.names;
clans = defaultsettings.clans;
Expand All @@ -63,7 +64,7 @@ public Settings(final SettingsDef def) {
padLeft = def.padLeft;
padBottom = def.padBottom;
globals = def.globals == null ? defaultsettings.globals : def.globals;
forum_uri = def.uri == null ? defaultsettings.forum_uri : def.uri;
broadcast_url = def.broadcastURL == null ? defaultsettings.broadcast_url : def.broadcastURL;
showlogo = def.showlogo == null ? defaultsettings.showlogo : def.showlogo;
unminimizeonnewplayer = def.unminimizeonnewplayer == null ? defaultsettings.unminimizeonnewplayer : def.unminimizeonnewplayer;
round = def.round == null ? defaultsettings.round : def.round;
Expand All @@ -86,8 +87,8 @@ public String getServer() {
return server;
}

public String getForumURI() {
return forum_uri;
public String getBroadcastURL() {
return broadcast_url;
}

public String[] getRooms() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class SettingsDef {
public int period = 30000;
public int port = 22000;
public String server = "144.76.163.135";
public String uri = "http://forum.toribash.com/forumdisplay.php?f=35";
public String broadcastURL = "http://forum.toribash.com/tori_broadcast.php?format=json&per_page=1";

public String[] names;
public String[] clans;
Expand All @@ -18,7 +18,7 @@ public class SettingsDef {
public int sort = 0;

public Boolean showlogo = false;
public Boolean globals = false;
public Boolean globals = true;
public Boolean unminimizeonnewplayer = true;
public Float[] round = new Float[] { 15f, 0f, 0f, 15f };

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ private void save() {
def.port = current.getPort();
def.rooms = current.getRooms();
def.sort = sort;
def.uri = current.getForumURI();
def.broadcastURL = current.getBroadcastURL();
def.round = current.getShapeSettings();
def.position = current.getPosition();
final Settings settings = new Settings(def);
Expand Down
14 changes: 14 additions & 0 deletions tMediator/src/com/seroperson/mediator/tori/stuff/Broadcast.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.seroperson.mediator.tori.stuff;

//http://forum.toribash.com/tori_broadcast.php?format=json&explain
public class Broadcast {
public BroadcastedMessage[] broadcasts;

@Override
public String toString() {
if (broadcasts != null && broadcasts[0] != null)
return broadcasts[0].toString();
else
return "No broadcast";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.seroperson.mediator.tori.stuff;

import java.util.Date;

public class BroadcastedMessage {
public Date post_time;
public String message;
public String username;

@Override
public String toString() {
return post_time.toString() + ": " + message + " by " + username;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ private void replace(int cindex, final ObjectMap<Player, Integer> oldorder, fina
private void push(int cindex, int nindex, final Actor actor, final Actor nactor) {

int multi = Math.abs(nindex-cindex);
float amount = actor.getHeight()*multi;
float amount = actor.getHeight()*multi; //ToDo: investigate why does it throw a NullPointerException

if(cindex < nindex)
amount *= -1;
Expand Down

0 comments on commit eccfd4c

Please sign in to comment.