summaryrefslogtreecommitdiffstats
blob: c634555784deb70c283fd0065109d628f8ebc63a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2010-2015, Isode Limited, London, England.
 * All rights reserved.
 */
package com.isode.stroke.presence;

import com.isode.stroke.elements.Payload;
import com.isode.stroke.elements.Presence;

/**
 * This presence sender adds payloads to outgoing presences.
 *
 * This class isn't meant to be used with directed presence.
 */
public class PayloadAddingPresenceSender implements PresenceSender {
    private Presence lastSentPresence;
    private final PresenceSender sender;
    private Payload payload;

    public PayloadAddingPresenceSender(PresenceSender sender) {
        this.sender = sender;
    }
    
    public void sendPresence(Presence presence) {
        if (presence.isAvailable()) {
            if (presence.getTo() != null && !presence.getTo().isValid()) {
                lastSentPresence = presence;
            }
        } else {
            lastSentPresence = null;
        }
        if (payload != null) {
            Presence sentPresence = new Presence(presence);
            sentPresence.updatePayload(payload);
            sender.sendPresence(sentPresence);
        } else {
            sender.sendPresence(presence);
        }
    }

    public boolean isAvailable() {
        return sender.isAvailable();
    }

    /**
     * Sets the payload to be added to outgoing presences. If initial presence
     * has been sent, this will resend the last sent presence with an updated
     * payload. Initial presence is reset when unavailable presence is sent, or
     * when reset() is called.
     */
    public void setPayload(Payload payload) {
        this.payload = payload;
        if (lastSentPresence != null) {
            sendPresence(lastSentPresence);
        }
    }

    /**
     * Resets the presence sender. This puts the presence sender back in the
     * initial state (before initial presence has been sent). This also resets
     * the chained sender.
     */
    public void reset() {
        lastSentPresence = null;
    }

}