Fix client side timestamp problem

Added Support for standalone webchat by reading a json file
Fix for jsonfile-interval in code
Added working php script with spam prevention, for webchat
This commit is contained in:
Jason Booth 2011-03-10 00:11:43 -06:00
parent 965686d44c
commit d296724755
5 changed files with 102 additions and 13 deletions

View File

@ -134,9 +134,7 @@ public class DynmapPlugin extends JavaPlugin {
messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() { messageHandler.onMessageReceived.addListener(new Listener<SendMessageHandler.Message>() {
@Override @Override
public void triggered(Message t) { public void triggered(Message t) {
mapManager.pushUpdate(new Client.WebChatMessage(t.name, t.message)); webChat(t.name, t.message);
log.info("[WEB]" + t.name + ": " + t.message);
getServer().broadcastMessage("[WEB]" + t.name + ": " + t.message);
} }
}); });
webServer.handlers.put("/up/sendmessage", messageHandler); webServer.handlers.put("/up/sendmessage", messageHandler);
@ -345,7 +343,7 @@ public class DynmapPlugin extends JavaPlugin {
private void jsonConfig() { private void jsonConfig() {
File outputFile; File outputFile;
Map<?, ?> clientConfig = (Map<?, ?>) configuration.getProperty("web"); Map<?, ?> clientConfig = (Map<?, ?>) configuration.getProperty("web");
File webpath = new File(configuration.getString("webpath", "web"), "dynmap_config.json"); File webpath = new File(configuration.getString("webpath", "web"), "standalone/dynmap_config.json");
if (webpath.isAbsolute()) if (webpath.isAbsolute())
outputFile = webpath; outputFile = webpath;
else else
@ -361,4 +359,11 @@ public class DynmapPlugin extends JavaPlugin {
log.log(Level.SEVERE, "Exception while writing JSON-configuration-file.", ioe); log.log(Level.SEVERE, "Exception while writing JSON-configuration-file.", ioe);
} }
} }
public void webChat(String name, String message)
{
mapManager.pushUpdate(new Client.WebChatMessage(name, message));
log.info("[WEB]" + name + ": " + message);
getServer().broadcastMessage("[WEB]" + name + ": " + message);
}
} }

View File

@ -3,7 +3,9 @@ package org.dynmap;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException; import java.io.IOException;
import java.util.Iterator;
import java.util.TimerTask; import java.util.TimerTask;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -13,7 +15,12 @@ import org.bukkit.Server;
import org.bukkit.World; import org.bukkit.World;
import org.bukkit.entity.Player; import org.bukkit.entity.Player;
import org.bukkit.util.config.Configuration; import org.bukkit.util.config.Configuration;
import org.dynmap.Event;
import org.dynmap.web.Json; import org.dynmap.web.Json;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
class JsonTimerTask extends TimerTask { class JsonTimerTask extends TimerTask {
protected static final Logger log = Logger.getLogger("Minecraft"); protected static final Logger log = Logger.getLogger("Minecraft");
@ -22,6 +29,8 @@ class JsonTimerTask extends TimerTask {
private Server server; private Server server;
private MapManager mapManager; private MapManager mapManager;
private Configuration configuration; private Configuration configuration;
private static final JSONParser parser = new JSONParser();
private long lastTimestamp = 0;
public JsonTimerTask(DynmapPlugin instance, Configuration config) { public JsonTimerTask(DynmapPlugin instance, Configuration config) {
this.plugin = instance; this.plugin = instance;
@ -31,8 +40,48 @@ class JsonTimerTask extends TimerTask {
} }
public void run() { public void run() {
long jsonInterval = configuration.getInt("jsonfile-interval", 1) * 1000;
long current = System.currentTimeMillis();
File outputFile;
//Handles Reading WebChat
if(configuration.getNode("web").getBoolean("allowwebchat", false))
{
File webChatPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_webchat.json");
if (webChatPath.isAbsolute())
outputFile = webChatPath;
else {
outputFile = new File(plugin.getDataFolder(), webChatPath.toString());
}
if(webChatPath.exists() && lastTimestamp != 0)
{
JSONArray jsonMsgs = null;
try {
FileReader inputFileReader = new FileReader(webChatPath);
jsonMsgs = (JSONArray) parser.parse(inputFileReader);
inputFileReader.close();
} catch(IOException ex){
log.log(Level.SEVERE, "Exception while reading JSON-file.", ex);
} catch(ParseException ex) {
log.log(Level.SEVERE, "Exception while parsing JSON-file.", ex);
}
if(jsonMsgs != null) {
Iterator iter = jsonMsgs.iterator();
while(iter.hasNext()) {
JSONObject o = (JSONObject)iter.next();
if(Long.parseLong(String.valueOf(o.get("timestamp"))) >= (lastTimestamp))
{
plugin.webChat(String.valueOf(o.get("name")), String.valueOf(o.get("message")));
}
}
}
}
}
//Handles Updates
for (World world : this.server.getWorlds()) { for (World world : this.server.getWorlds()) {
long current = System.currentTimeMillis(); current = System.currentTimeMillis();
Client.Update update = new Client.Update(); Client.Update update = new Client.Update();
@ -47,14 +96,13 @@ class JsonTimerTask extends TimerTask {
update.players[i] = new Client.Player(p.getName(), pl.getWorld().getName(), pl.getX(), pl.getY(), pl.getZ()); update.players[i] = new Client.Player(p.getName(), pl.getWorld().getName(), pl.getX(), pl.getY(), pl.getZ());
} }
update.updates = mapManager.getWorldUpdates(world.getName(), current - (configuration.getInt("jsonfile-interval", 1) + 10000)); update.updates = mapManager.getWorldUpdates(world.getName(), current - (jsonInterval + 10000));
File webpath = new File(this.configuration.getString("webpath", "web"), "dynmap_" + world.getName() + ".json"); File webWorldPath = new File(this.configuration.getString("webpath", "web"), "standalone/dynmap_" + world.getName() + ".json");
File outputFile; if (webWorldPath.isAbsolute())
if (webpath.isAbsolute()) outputFile = webWorldPath;
outputFile = webpath;
else { else {
outputFile = new File(plugin.getDataFolder(), webpath.toString()); outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
} }
try { try {
FileOutputStream fos = new FileOutputStream(outputFile); FileOutputStream fos = new FileOutputStream(outputFile);
@ -66,5 +114,6 @@ class JsonTimerTask extends TimerTask {
log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe); log.log(Level.SEVERE, "Exception while writing JSON-file.", ioe);
} }
} }
lastTimestamp = System.currentTimeMillis();
} }
} }

View File

@ -1,4 +1,4 @@
function sendChat(message) { function sendChat(me, message) {
var ip; var ip;
$.ajax({ $.ajax({
type: "GET", type: "GET",
@ -13,6 +13,8 @@ function sendChat(message) {
dataType: 'json', dataType: 'json',
success: function(response) { success: function(response) {
//handle response //handle response
if(response)
me.onPlayerChat('', response);
} }
}); });
} }

View File

@ -213,7 +213,7 @@ DynMap.prototype = {
.keydown(function(event) { .keydown(function(event) {
if (event.keyCode == '13') { if (event.keyCode == '13') {
event.preventDefault(); event.preventDefault();
sendChat(chatinput.val()); sendChat(me, chatinput.val());
chatinput.val(''); chatinput.val('');
} }
}) })
@ -329,6 +329,7 @@ DynMap.prototype = {
//var divs = $('div[rel]'); //var divs = $('div[rel]');
//divs.filter(function(i){return parseInt(divs[i].attr('rel')) > timestamp+me.options.messagettl;}).remove(); //divs.filter(function(i){return parseInt(divs[i].attr('rel')) > timestamp+me.options.messagettl;}).remove();
}); });
me.lasttimestamp = update.timestamp;
setTimeout(function() { me.update(); }, me.options.updaterate); setTimeout(function() { me.update(); }, me.options.updaterate);
}, function(status, statusText, request) { }, function(status, statusText, request) {
me.alertbox me.alertbox

View File

@ -0,0 +1,32 @@
<?php
$msginterval = 5; //In seconds - add this to dynmap web config??
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['lastchat'] < time())
{
$config = json_decode(file_get_contents('dynmap_config.json'), true);
$micro = explode(' ', microtime());
$timestamp = $micro[1].round($micro[0]*1000);
$data = json_decode(trim(file_get_contents('php://input')));
$data->timestamp = $timestamp;
$old_messages = json_decode(file_get_contents('dynmap_webchat.json'), true);
if(!empty($old_messages))
{
foreach($old_messages as $message)
{
if(($timestamp - $config['updaterate'] - 10000) < $message['timestamp'])
$new_messages[] = $message;
}
}
$new_messages[] = $data;
file_put_contents('dynmap_webchat.json', json_encode($new_messages));
$_SESSION['lastchat'] = time()+$msginterval;
}
elseif($_SERVER['REQUEST_METHOD'] == 'POST' && $_SESSION['lastchat'] > time())
{
echo json_encode('You may only chat once every '.$msginterval.' seconds.');
}
?>