summaryrefslogtreecommitdiffstats
path: root/libmail/smapaddmessage.C
blob: 2224eb839410a8b033b8dbd1cfbc9c0aaed5abff (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
71
72
73
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
/*
** Copyright 2003-2008, Double Precision Inc.
**
** See COPYING for distribution information.
*/
#include "smapaddmessage.H"
#include "smapadd.H"
#include "rfc822/rfc822.h"
#include <errno.h>
#include <sstream>
#include <cstring>

using namespace std;

mail::smapAddMessage::smapAddMessage(mail::imap &imapAccountArg,
				     mail::callback &callbackArg)
	: addMessage(&imapAccountArg),
	  imapAccount(imapAccountArg),
	  callback(&callbackArg),
	  tfile(tmpfile())
{
}

mail::smapAddMessage::~smapAddMessage()
{
	if (tfile)
		fclose(tfile);
	if (callback)
		callback->fail("Operation aborted.");
}

void mail::smapAddMessage::saveMessageContents(std::string contents)
{
	size_t n;

	while ((n=contents.find('\r')) != std::string::npos)
		contents.erase(contents.begin()+n,
			       contents.begin()+n+1);

	if (tfile)
		if (fwrite(&contents[0], contents.size(), 1, tfile) != 1)
			; // Ignore gcc warning
}

void mail::smapAddMessage::go()
{
	if (!tfile || ferror(tfile) || fflush(tfile) ||
	    fseek(tfile, 0L, SEEK_SET) < 0)
	{
		fail(strerror(errno));
		return;
	}

	if (!checkServer())
		return;

	{
		string flags;

#define FLAG
#define NOTFLAG !
#define DOFLAG(NOT, field, name) \
		if (NOT messageInfo.field) flags += "," name

		LIBMAIL_SMAPFLAGS;
#undef DOFLAG
#undef NOTFLAG
#undef FLAG

		if (flags.size() > 0)
			flags=flags.substr(1);

		ostringstream o;

		o << "ADD FLAGS=" << flags;

		if (messageDate)
		{
			char buf[80];

			rfc822_mkdate_buf(messageDate, buf);

			o << " \"INTERNALDATE=" << buf << "\"";
		}

		o << "\n";

		cmds.push_back(o.str());
	}

	smapAdd *add=new smapAdd(cmds, *callback);

	if (add)
	{
		callback=NULL;
		add->tfile=tfile;
		tfile=NULL;
	}

	try {
		imapAccount.installForegroundTask(add);
	} catch (...) {
		if (add)
			delete add;
		delete this;
		LIBMAIL_THROW(LIBMAIL_THROW_EMPTY);
	}

	delete this;
}

void mail::smapAddMessage::fail(std::string errmsg)
{
	mail::callback *c=callback;

	callback=NULL;
	delete this;

	if (c)
		c->fail(errmsg);
}