summaryrefslogtreecommitdiffstats
blob: f980c47ce78d370340a4c282d2cb66fcc55ce244 (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
68
69
70
/*
 * Copyright (c) 2010 Remko Tronçon
 * Licensed under the GNU General Public License v3.
 * See Documentation/Licenses/GPLv3.txt for more information.
 */

#include "Swiften/FileTransfer/IBBReceiveSession.h"

#include <boost/bind.hpp>
#include <iostream>

#include "Swiften/Queries/IQRouter.h"
#include "Swiften/FileTransfer/IBBRequest.h"
#include "Swiften/FileTransfer/BytestreamException.h"

namespace Swift {

IBBReceiveSession::IBBReceiveSession(const std::string& id, const JID& from, size_t size, WriteBytestream::ref bytestream, IQRouter* router) : SetResponder<IBB>(router), id(id), from(from), size(size), bytestream(bytestream), router(router), sequenceNumber(0), active(false), receivedSize(0) {
}

IBBReceiveSession::~IBBReceiveSession() {
}

void IBBReceiveSession::start() {
	active = true;
}

void IBBReceiveSession::stop() {
	if (active && router->isAvailable()) {
		IBBRequest::create(from, IBB::createIBBClose(id), router)->send();
	}
	finish(boost::optional<FileTransferError>());
}

void IBBReceiveSession::finish(boost::optional<FileTransferError> error) {
	active = false;
	onFinished(error);
}

bool IBBReceiveSession::handleSetRequest(const JID& from, const JID&, const std::string& id, IBB::ref ibb) {
	if (from == this->from && ibb->getStreamID() == id) {
		if (ibb->getAction() == IBB::Data) {
			if (sequenceNumber == ibb->getSequenceNumber()) {
				bytestream->write(ibb->getData());
				receivedSize += ibb->getData().getSize();
				if (receivedSize >= size) {
					if (receivedSize > size) {
						std::cerr << "Warning: Received more data than expected" << std::endl;
					}
					finish(boost::optional<FileTransferError>());
				}
			}
			else {
				sendError(from, id, ErrorPayload::NotAcceptable, ErrorPayload::Cancel);
				finish(FileTransferError(FileTransferError::ClosedError));
			}
		}
		else if (ibb->getAction() == IBB::Open) {
			sendResponse(from, id, IBB::ref());
		}
		else if (ibb->getAction() == IBB::Close) {
			sendResponse(from, id, IBB::ref());
			finish(FileTransferError(FileTransferError::ClosedError));
		}
		return true;
	}
	return false;
}

}