package org.dynmap.web.handlers;

import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.logging.Logger;

import org.dynmap.Event;
import org.dynmap.web.HttpField;
import org.dynmap.web.HttpHandler;
import org.dynmap.web.HttpMethod;
import org.dynmap.web.HttpRequest;
import org.dynmap.web.HttpResponse;
import org.dynmap.web.HttpStatus;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class SendMessageHandler implements HttpHandler {
    protected static final Logger log = Logger.getLogger("Minecraft");
    protected static final String LOG_PREFIX = "[dynmap] ";

    private static final JSONParser parser = new JSONParser();
    public Event<Message> onMessageReceived = new Event<SendMessageHandler.Message>();
    private Charset cs_utf8 = Charset.forName("UTF-8");
    public int maximumMessageInterval = 1000;
    public String spamMessage = "\"You may only chat once every %interval% seconds.\"";
    private HashMap<String, WebUser> disallowedUsers = new HashMap<String, WebUser>();
    private LinkedList<WebUser> disallowedUserQueue = new LinkedList<WebUser>();
    private Object disallowedUsersLock = new Object();

    @Override
    public void handle(String path, HttpRequest request, HttpResponse response) throws Exception {
        if (!request.method.equals(HttpMethod.Post)) {
            response.status = HttpStatus.MethodNotAllowed;
            response.fields.put(HttpField.Accept, HttpMethod.Post);
            return;
        }

        InputStreamReader reader = new InputStreamReader(request.body, cs_utf8);

        JSONObject o = (JSONObject)parser.parse(reader);
        final Message message = new Message();
        //message.name = String.valueOf(o.get("name")); //Can't trust client....we don't need to on internal web server
        message.name = request.rmtaddr.getAddress().getHostAddress();
        message.message = String.valueOf(o.get("message"));

        final long now = System.currentTimeMillis();

        synchronized(disallowedUsersLock) {
            // Allow users that  user that are now allowed to send messages.
            while (!disallowedUserQueue.isEmpty()) {
                WebUser wu = disallowedUserQueue.getFirst();
                if (now >= wu.nextMessageTime) {
                    disallowedUserQueue.remove();
                    disallowedUsers.remove(wu.name);
                } else {
                    break;
                }
            }

            WebUser user = disallowedUsers.get(message.name);
            if (user == null) {
                user = new WebUser() {{
                    name = message.name;
                    nextMessageTime = now+maximumMessageInterval;
                }};
                disallowedUsers.put(user.name, user);
                disallowedUserQueue.add(user);
            } else {
                response.fields.put("Content-Length", "0");
                response.status = HttpStatus.Forbidden;
                response.getBody();
                return;
            }
        }

        onMessageReceived.trigger(message);

        response.fields.put(HttpField.ContentLength, "0");
        response.status = HttpStatus.OK;
        response.getBody();
    }

    public static class Message {
        public String name;
        public String message;
    }
    public static class WebUser {
        public long nextMessageTime;
        public String name;
    }
}

@@ -1771,119 +1771,407 @@
    /
-/message.name = String.valueOf(o.get(%22name%22)); //Can't trust client....we don't need to on internal web server%0A
+* If proxied client address, get original */%0A        if(request.fields.containsKey(%22X-Forwarded-For%22))%0A            message.name = request.fields.get(%22X-Forwarded-For%22);%0A        /* If from loopback, we're probably getting from proxy - need to trust client */%0A        else if(request.rmtaddr.getAddress().isLoopbackAddress())%0A            message.name = String.valueOf(o.get(%22name%22));%0A        else%0A    
     

Add support for using X-Forwarded-From for better proxy IP handling on webchat