summary refs log tree commit diff stats
path: root/src/main/java/ganarchy/friendcode/sam/I2PSamStreamConnector.java
blob: 95b6a61e4c12fd6fbbcd499d51dc1c2f7a23fa8e (plain) (blame)
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
68
69
70
71
72
73
74
package ganarchy.friendcode.sam;

import com.google.common.collect.ImmutableMap;

import java.io.IOException;
import java.net.*;

public class I2PSamStreamConnector extends I2PSamStateMachine {
    private final String id;
    private final SocketAddress socketAddress;
    private final String friendCode;
    private boolean connected;
    private I2PSamCommand status;

    public I2PSamStreamConnector(SocketAddress socketAddress, String id, String friendCode) {
        this.id = id;
        this.socketAddress = socketAddress;
        this.friendCode = friendCode;
    }

    @Override
    public boolean connect() {
        try {
            Socket samSocket = new Socket();
            samSocket.connect(this.socketAddress, 3000);
            return this.connect(samSocket);
        } catch (IOException e) {
            return false;
        }
    }

    public boolean start() {
        if (!super.start()) {
            return false;
        }
        try {
            this.sendCommand(new I2PSamCommand(
                "STREAM", "CONNECT",
                ImmutableMap.of(
                        "ID", this.id,
                        "DESTINATION", this.friendCode
                )
            ));
            return this.connected = "OK".equals((this.status = this.getCommand("STREAM", "STATUS")).parameters().get("RESULT"));
        } catch (IOException e) {
            return false;
        }
    }

    @Override
    protected void sendCommand(I2PSamCommand command) throws IOException {
        if (this.connected) {
            throw new IllegalStateException("call unwrap() instead");
        }
        super.sendCommand(command);
    }

    @Override
    public void step() throws IOException {
        if (this.connected) {
            throw new IllegalStateException("call unwrap() instead");
        }
        super.step();
    }

    @Override
    public Socket unwrap() {
        return super.unwrap();
    }

    public I2PSamCommand getStatus() {
        return this.status;
    }
}