summaryrefslogtreecommitdiff
path: root/server/src/journal_commit.cc
blob: 21d40c30292a93bdff65cb236d21b913c0c4f3de (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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/***************************************************************************
 *            journal_commit.cc
 *
 *  Tue Mar 18 11:10:00 CET 2008
 *  Copyright 2008 Bent Bisballe Nyeng and Peter Skaarup
 *  deva@aasimon.org and piparum@piparum.dk
 ****************************************************************************/

/*
 *  This file is part of Pracro.
 *
 *  Pracro is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  Pracro is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Pracro; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
 */
#include "journal_commit.h"

#include <config.h>

#include "debug.h"

#include <string>

// for gethostbyname
#include <netdb.h>

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <endian.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdarg.h>
#include <fcntl.h>
#include <time.h>
#include <errno.h>

#include "template.h"
#include "templateparser.h"

static inline bool iswhitespace(char c)
{
  return c == ' ' || c == '\n' || c == '\t';
}

/**
 * Remove all spaces, tabs and newline trailing the string.
 */
static std::string stripTrailingWhitepace(std::string str)
{
  if(str == "") return str;

  ssize_t end = str.size() - 1;

  while(end && iswhitespace(str[end]) 
        && (end>0 && str[end-1] & 0x80) == false // Make sure we are not in a utf8 character.
        ) {
    end--;
  }
  end++;

  return str.substr(0, end);
}

/**
 * Find all lines longer than 'width', and insert a newline in the
 * first backward occurring space.
 */
static std::string addNewlines(std::string str, size_t width)
{
  std::string output;

  std::string fraction;
  size_t linelen = 0;
  for(size_t i = 0; i < str.size(); i++) {

    fraction += str[i];

    if(iswhitespace(str[i]) 
       && (i>0 && str[i-1] & 0x80) == false // Make sure we are not in a utf8 character.
       ) {
      if(linelen + fraction.size() > width) {
        output[output.size() - 1] = '\n';
        linelen = 0;
      }
      output += fraction;
      linelen += fraction.size();
      fraction = "";
    }

    if(str[i] == '\n') linelen = 0;

  }
  output += fraction;

  return output;
}

static int mwrite(int sock, const char *fmt, ...)
{
  int l = 0;
  va_list args;
  char *buffer;

  buffer = (char*)calloc(64*1024, 1);

  va_start(args, fmt);
  l = vsnprintf(buffer, 64*1024, fmt, args);
  va_end(args);
  
  if(sock != -1 && write(sock, buffer, l) != l) {
    PRACRO_ERR_LOG(journal, "write did not write all the bytes in the buffer.\n");
  }
 
  PRACRO_DEBUG(journal, "%s", buffer);
  free(buffer);

  return l;
}

int journal_commit(const char *cpr, const char *user,
                   const char *addr, unsigned short int port,
                   const char *buf, size_t size)
{
  int sock = -1;

#ifndef WITHOUT_UPLOADSERVER
  struct sockaddr_in sin;

  // Do DNS lookup
  char *ip;
  struct in_addr **addr_list;
  struct hostent *he;
  he = gethostbyname(addr);
  if(!he || !he->h_length) {
    PRACRO_ERR_LOG(journal, "gethostbyname(%s) failed (errno=%d)!\n", addr, errno);
    return -1;
  }

  addr_list = (struct in_addr **)he->h_addr_list;
  //  Get first value. We know for sure that there are at least one.
  ip = inet_ntoa(*addr_list[0]);

  // open socket
  memset(&sin, 0, sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = inet_addr(ip);
  sin.sin_port = htons(port);
  
  if( (sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
    PRACRO_ERR_LOG(journal, "Socket() failed!\n");
    return -1;
  }
  
  if(connect(sock, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
    PRACRO_ERR_LOG(journal, "Connect() failed!\n");
    perror(":");
    return -1;
  }
#endif/*WITHOUT_UPLOADSERVER*/

  // send header
  mwrite(sock, "PUT JOURNAL PROTO1.0 \r\n");  
  mwrite(sock, "size : %i\r\n", size);  
  mwrite(sock, "user: %s\r\n", user);
  mwrite(sock, "generator: pracro\r\n");
  //  mwrite(sock, "password: 1234\r\n");
  mwrite(sock, "cpr: %s\r\n", cpr);
  mwrite(sock, "date: %i\r\n", time(NULL));
  mwrite(sock, "charset: utf8\r\n");
  mwrite(sock, "\r\n");

  std::string resume = stripTrailingWhitepace(addNewlines(buf, 60));

  // send body
  if(sock != -1 && write(sock, resume.c_str(), resume.size()) != (ssize_t)resume.size()) {
    PRACRO_ERR_LOG(journal, "write did not write all the bytes in the buffer.\n");
  }
  PRACRO_DEBUG(journal, "%s", buf);

#ifndef WITHOUT_UPLOADSERVER
  // close socket
  close(sock);
#endif/*WITHOUT_UPLOADSERVER*/

  return 0;
}

JournalWriter::JournalWriter(std::string host, unsigned short int port)
{
  this->host = host;
  this->port = port;
}

void JournalWriter::addEntry(Transaction &transaction, Commit &commit,
                             std::string resume, std::string templname)
{
  TemplateParser tp(templname);
  tp.parse();
  Template *templ = tp.getTemplate();
  
  size_t index = 0;
  std::vector< Macro >::iterator i = templ->macros.begin();
  while(i != templ->macros.end()) {
    Macro &m = *i;
    if(commit.macro == m.attributes["name"]) break;
    index++;
    i++;
  }

  if(index >= templ->macros.size()) {
    PRACRO_ERR(journal, "Could not find macro %s in template %s\n",
                 commit.macro.c_str(), templname.c_str());
    //      return;
  } else {
    PRACRO_DEBUG(journal, "Found macro %s as index %u in template %s\n",
                 commit.macro.c_str(), index, templname.c_str());
  }

  // First run - initialize username and cpr.
  if(currentuser == "" && entrylist.size() == 0) currentuser = transaction.user;
  if(currentcpr == "" && entrylist.size() == 0) currentcpr = transaction.cpr;

  PRACRO_DEBUG(journal, "addEntry: template(%s)\n", templname.c_str());

  // Add the template resume as the header (ie. first entry) of the journal entry.
  if(entrylist.size() == 0 && templname != "") {
    std::string template_resume = templ->attributes["resume"];
    
    PRACRO_DEBUG(journal, "TemplateResume: %s\n", template_resume.c_str());
    
    if(template_resume != "") {
      ResumeEntry re;
      re.resume = template_resume;
      re.macro = "template_header"; 
      entrylist[-1] = re; // Make sure it comes first.
    }
  }

  // Test if the username or the cpr has changed... if so, commit and clear the list.
  if(currentuser != transaction.user || currentcpr != transaction.cpr) {
    this->commit();
    entrylist.clear();
  }

  // Strip trailing whitespace, and add newlines.
  std::string r = stripTrailingWhitepace(addNewlines(resume, 60));
  std::string m = commit.macro;

  /*
  // If macro already exists, overwrite with this entry, otherwise, just add it
  int idx = -1;
  std::vector< ResumeEntry >::iterator i = entrylist.begin();
  int cnt = 0;
  while(i != entrylist.end()) {
    if(i->macro == m) idx = cnt;
    cnt++;
    i++;
  }

  if(idx != -1) {
    entrylist[idx].resume = r;
    entrylist[idx].macro = m;
  } else {
    ResumeEntry re;
    re.resume = r;
    re.macro = m;
    entrylist.push_back(re);
  }
  */

  ResumeEntry re;
  re.resume = r;
  re.macro = m;
  entrylist[index] = re;
}

void JournalWriter::commit()
{
  std::string resume;
  
  // Iterate through all resumes, and create a string containing them all.
  std::map< int, ResumeEntry >::iterator i = entrylist.begin();
  while(i != entrylist.end()) {
    if(resume != "") resume += "\n\n";
    //    resume += i->macro + "\n";
    resume += i->second.resume;
    i++;
  }

  if(resume == "") return;

  // Connect to praxisuploadserver and commit all resumes in one bulk.
  journal_commit(currentcpr.c_str(), currentuser.c_str(),
                 host.c_str(), port,
                 resume.c_str(), resume.size());
}


#ifdef TEST_JOURNAL_COMMIT

int main()
{
  std::string text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do\neiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.           \n\n    \t";

  std::string resume = stripTrailingWhitepace(addNewlines(text, 60));
  printf("[%s]\n", resume.c_str());

  resume = stripTrailingWhitepace(addNewlines("", 60));
  printf("[%s]\n", resume.c_str());

  return 0;
}

#endif/*TEST_JOURNAL_COMMIT*/