HistoryRequest.java 8.9 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile: HistoryRequest.java,v $
 * $Revision: 2899 $
 * $Date: 2005-09-28 15:30:42 -0300 (Wed, 28 Sep 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
19 20
 */

21
package org.jivesoftware.openfire.muc;
22

23 24 25 26 27 28
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

29 30
import org.dom4j.Element;
import org.jivesoftware.openfire.muc.spi.LocalMUCRole;
31
import org.jivesoftware.util.XMPPDateTimeFormat;
32 33
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
34 35
import org.xmpp.packet.Message;

36 37 38 39 40 41 42 43 44 45 46 47 48 49
/**
 * Represents the amount of history requested by an occupant while joining a room. There are 
 * basically four ways to control the amount of history that a user may receive. Those are: limit
 * by the maximum limit of characters to receive, limit by a maximum number of stanzas to receive,
 * limit to receive only the messages before a given date or of the last X seconds.<p>
 * 
 * A user may combine any of these four methods. The idea is that the user will receive the smallest 
 * amount of traffic so the amount of history to collect will stop as soon as any of the requested 
 * method has reached its limit.
 * 
 * @author Gaston Dombiak
 */
public class HistoryRequest {

50
	private static final Logger Log = LoggerFactory.getLogger(HistoryRequest.class);
51
	private static final XMPPDateTimeFormat xmppDateTime = new XMPPDateTimeFormat();
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

    private int maxChars = -1;
    private int maxStanzas = -1;
    private int seconds = -1;
    private Date since;

    public HistoryRequest(Element userFragment) {
        Element history = userFragment.element("history");
        if (history != null) {
            if (history.attribute("maxchars") != null) {
                this.maxChars = Integer.parseInt(history.attributeValue("maxchars"));
            }
            if (history.attribute("maxstanzas") != null) {
                this.maxStanzas = Integer.parseInt(history.attributeValue("maxstanzas"));
            }
            if (history.attribute("seconds") != null) {
                this.seconds = Integer.parseInt(history.attributeValue("seconds"));
            }
            if (history.attribute("since") != null) {
                try {
72 73
                    // parse since String into Date
                    this.since = xmppDateTime.parseString(history.attributeValue("since"));
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
                }
                catch(ParseException pe) {
                    Log.error("Error parsing date from history management", pe);
                    this.since = null;
                }
            }
        }
    }
    
    /**
     * Returns the total number of characters to receive in the history.
     * 
     * @return total number of characters to receive in the history.
     */
    public int getMaxChars() {
        return maxChars;
    }

    /**
     * Returns the total number of messages to receive in the history.
     * 
     * @return the total number of messages to receive in the history.
     */
    public int getMaxStanzas() {
        return maxStanzas;
    }

    /**
     * Returns the number of seconds to use to filter the messages received during that time. 
     * In other words, only the messages received in the last "X" seconds will be included in 
     * the history.
     * 
     * @return the number of seconds to use to filter the messages received during that time.
     */
    public int getSeconds() {
        return seconds;
    }

    /**
     * Returns the since date to use to filter the messages received during that time. 
     * In other words, only the messages received since the datetime specified will be 
     * included in the history.
     * 
     * @return the since date to use to filter the messages received during that time.
     */
    public Date getSince() {
        return since;
    }

    /**
     * Returns true if the history has been configured with some values.
     * 
     * @return true if the history has been configured with some values.
     */
    private boolean isConfigured() {
        return maxChars > -1 || maxStanzas > -1 || seconds > -1 || since != null;
    }

    /**
     * Sends the smallest amount of traffic that meets any combination of the requested criteria.
     * 
     * @param joinRole the user that will receive the history.
     * @param roomHistory the history of the room.
     */
138
    public void sendHistory(LocalMUCRole joinRole, MUCRoomHistory roomHistory) {
139
        if (!isConfigured()) {
140
            Iterator<Message> history = roomHistory.getMessageHistory();
141
            while (history.hasNext()) {
142
                joinRole.send(history.next());
143 144 145
            }
        }
        else {
146 147
            Message changedSubject = roomHistory.getChangedSubject();
            boolean addChangedSubject = (changedSubject != null) ? true : false;
148 149
            if (getMaxChars() == 0) {
                // The user requested to receive no history
150 151 152
                if (addChangedSubject) {
                    joinRole.send(changedSubject);
                }
153 154 155 156 157
                return;
            }
            int accumulatedChars = 0;
            int accumulatedStanzas = 0;
            Element delayInformation;
158
            LinkedList<Message> historyToSend = new LinkedList<Message>();
159
            ListIterator<Message> iterator = roomHistory.getReverseMessageHistory();
160
            while (iterator.hasPrevious()) {
161
                Message message = iterator.previous();
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
                // Update number of characters to send
                String text = message.getBody() == null ? message.getSubject() : message.getBody();
                if (text == null) {
                    // Skip this message since it has no body and no subject  
                    continue;
                }
                accumulatedChars += text.length();
                if (getMaxChars() > -1 && accumulatedChars > getMaxChars()) {
                    // Stop collecting history since we have exceded a limit
                    break;
                }
                // Update number of messages to send
                accumulatedStanzas ++;
                if (getMaxStanzas() > -1 && accumulatedStanzas > getMaxStanzas()) {
                    // Stop collecting history since we have exceded a limit
                    break;
                }

                if (getSeconds() > -1 || getSince() != null) {
                    delayInformation = message.getChildElement("x", "jabber:x:delay");
                    try {
                        // Get the date when the historic message was sent
184
                        Date delayedDate = xmppDateTime.parseString(delayInformation.attributeValue("stamp"));
185
                        if (getSince() != null && delayedDate != null && delayedDate.before(getSince())) {
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
                            // Stop collecting history since we have exceded a limit
                            break;
                        }
                        if (getSeconds() > -1) {
                            Date current = new Date();
                            long diff = (current.getTime() - delayedDate.getTime()) / 1000;
                            if (getSeconds() <= diff) {
                                // Stop collecting history since we have exceded a limit
                                break;
                            }
                        }
                    }
                    catch (Exception e) {
                        Log.error("Error parsing date from historic message", e);
                    }

                }

204 205 206 207 208 209 210
                // Don't add the latest subject change if it's already in the history.
                if (addChangedSubject) {
                    if (changedSubject != null && changedSubject.equals(message)) {
                        addChangedSubject = false;
                    }
                }

211 212
                historyToSend.addFirst(message);
            }
213 214 215 216
            // Check if we should add the latest subject change.
            if (addChangedSubject) {
                historyToSend.addFirst(changedSubject);
            }
217
            // Send the smallest amount of traffic to the user
218 219
            for (Object aHistoryToSend : historyToSend) {
                joinRole.send((Message) aHistoryToSend);
220 221 222 223
            }
        }
    }
}