summaryrefslogtreecommitdiffstats
path: root/kmymoney2/plugins/ofximport/ofxpartner.cpp
blob: 711bff5b2f085f3171e990c71265b89b6639f4cf (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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/***************************************************************************
                             ofxpartner.cpp
                             ----------
    begin                : Fri Jan 23 2009
    copyright            : (C) 2009 by Thomas Baumgart
    email                : Thomas Baumgart <ipwizard@users.sourceforge.net>
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program 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.                                   *
 *                                                                         *
 ***************************************************************************/


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

// ----------------------------------------------------------------------------
// QT Includes

#include <tqdatetime.h>
#include <tqeventloop.h>
#include <tqfileinfo.h>
#include <tqvaluelist.h>
#include <tqapplication.h>
#include <tqdom.h>
#include <tqregexp.h>
#include <tqdir.h>
#include <tqtextstream.h>

// ----------------------------------------------------------------------------
// KDE Includes


#include <kio/job.h>
#include <klocale.h>
#include <kmessagebox.h>

// ----------------------------------------------------------------------------
// Project Includes

#include "ofxpartner.h"

namespace OfxPartner
{
bool post(const TQString& request, const TQMap<TQString, TQString>& attr, const KURL& url, const KURL& filename);
bool get(const TQString& request, const TQMap<TQString, TQString>& attr, const KURL& url, const KURL& filename);

const TQString kBankFilename = "ofx-bank-index.xml";
const TQString kCcFilename = "ofx-cc-index.xml";
const TQString kInvFilename = "ofx-inv-index.xml";

#define VER "9"

static TQString directory;

void setDirectory(const TQString& dir)
{
  directory = dir;
}

bool needReload(const TQFileInfo& i)
{
  return ((!i.isReadable())
  || (i.lastModified().addDays(7) < TQDateTime::currentDateTime())
  || (i.size() < 1024));
}

void ValidateIndexCache(void)
{
  // TODO (Ace) Check whether these files exist and are recent enough before getting them again

  struct stat filestats;
  KURL fname;

  TQMap<TQString, TQString> attr;
  attr["content-type"] = "application/x-www-form-urlencoded";
  attr["accept"] = "*/*";

  fname = directory + kBankFilename;
  TQFileInfo i(fname.path());
  if(needReload(i))
    post("T=1&S=*&R=1&O=0&TEST=0", attr, KURL("http://moneycentral.msn.com/money/2005/mnynet/service/ols/filist.aspx?SKU=3&VER=" VER), fname);

  fname = directory + kCcFilename;
  i = TQFileInfo(fname.path());
  if(needReload(i))
    post("T=2&S=*&R=1&O=0&TEST=0", attr, KURL("http://moneycentral.msn.com/money/2005/mnynet/service/ols/filist.aspx?SKU=3&VER=" VER) ,fname);

  fname = directory + kInvFilename;
  i = TQFileInfo(fname.path());
  if(needReload(i))
    post("T=3&S=*&R=1&O=0&TEST=0", attr, KURL("http://moneycentral.msn.com/money/2005/mnynet/service/ols/filist.aspx?SKU=3&VER=" VER), fname);
}

static void ParseFile(TQMap<TQString, TQString>& result, const TQString& fileName, const TQString& bankName)
{
  TQFile f(fileName);
  if(f.open(IO_ReadOnly)) {
    TQTextStream stream(&f);
    stream.setEncoding(TQTextStream::Unicode);
    TQString msg;
    int errl, errc;
    TQDomDocument doc;
    if(doc.setContent(stream.read(), &msg, &errl, &errc)) {
      TQDomNodeList olist = doc.elementsByTagName("prov");
      for(int i = 0; i < olist.count(); ++i) {
        TQDomNode onode = olist.item(i);
        if(onode.isElement()) {
          bool collectGuid = false;
          TQDomElement elo = onode.toElement();
          TQDomNodeList ilist = onode.childNodes();
          for(int j = 0; j < ilist.count(); ++j) {
            TQDomNode inode = ilist.item(j);
            TQDomElement el = inode.toElement();
            if(el.tagName() == "name") {
              if(bankName.isEmpty())
                result[el.text()] = TQString();
              else if(el.text() == bankName) {
                collectGuid = true;
              }
            }
            if(el.tagName() == "guid" && collectGuid) {
              result[el.text()] = TQString();
            }
          }
        }
      }
    }
    f.close();
  }
}

TQValueList<TQString> BankNames(void)
{
  TQMap<TQString, TQString> result;

  // Make sure the index files are up to date
  ValidateIndexCache();

  ParseFile(result, directory + kBankFilename, TQString());
  ParseFile(result, directory + kCcFilename, TQString());
  ParseFile(result, directory + kInvFilename, TQString());

  // Add Innovision
  result["Innovision"] = TQString();

  return result.keys();
}

TQValueList<TQString> FipidForBank(const TQString& bank)
{
  TQMap<TQString, TQString> result;

  ParseFile(result, directory + kBankFilename, bank);
  ParseFile(result, directory + kCcFilename, bank);
  ParseFile(result, directory + kInvFilename, bank);

  // the fipid for Innovision is 1.
  if ( bank == "Innovision" )
    result["1"] = TQString();

  return result.keys();
}

TQString extractNodeText(TQDomElement& node, const TQString& name)
{
  TQString res;
  TQRegExp exp("([^/]+)/?([^/].*)?");
  if(exp.search(name) != -1) {
    TQDomNodeList olist = node.elementsByTagName(exp.cap(1));
    if(olist.count()) {
      TQDomNode onode = olist.item(0);
      if(onode.isElement()) {
        TQDomElement elo = onode.toElement();
        if(exp.cap(2).isEmpty()) {
          res = elo.text();
        } else {
          res = extractNodeText(elo, exp.cap(2));
        }
      }
    }
  }
  return res;
}

TQString extractNodeText(TQDomDocument& doc, const TQString& name)
{
  TQString res;
  TQRegExp exp("([^/]+)/?([^/].*)?");
  if(exp.search(name) != -1) {
    TQDomNodeList olist = doc.elementsByTagName(exp.cap(1));
    if(olist.count()) {
      TQDomNode onode = olist.item(0);
      if(onode.isElement()) {
        TQDomElement elo = onode.toElement();
        if(exp.cap(2).isEmpty()) {
          res = elo.text();
        } else {
          res = extractNodeText(elo, exp.cap(2));
        }
      }
    }
  }
  return res;
}

OfxFiServiceInfo ServiceInfo(const TQString& fipid)
{
  OfxFiServiceInfo result;
  memset(&result, 0, sizeof(OfxFiServiceInfo));

  // Hard-coded values for Innovision test server
  if ( fipid == "1" )
  {
    strncpy(result.fid,"00000",OFX_FID_LENGTH-1);
    strncpy(result.org,"ReferenceFI",OFX_ORG_LENGTH-1);
    strncpy(result.url,"http://ofx.innovision.com",OFX_URL_LENGTH-1);
    result.accountlist = 1;
    result.statements = 1;
    result.billpay = 1;
    result.investments = 1;

    return result;
  }

  TQMap<TQString, TQString> attr;
  attr["content-type"] = "application/x-www-form-urlencoded";
  attr["accept"] = "*/*";

  KURL guidFile(TQString("%1fipid-%2.xml").arg(directory).arg(fipid));

  // Apparently at some point in time, for VER=6 msn returned an online URL
  // to a static error page (http://moneycentral.msn.com/cust404.htm).
  // Increasing to VER=9 solved the problem. This may happen again in the
  // future.
  TQFileInfo i(guidFile.path());
  if(!i.isReadable() || i.lastModified().addDays(7) < TQDateTime::currentDateTime())
    get("", attr, KURL(TQString("http://moneycentral.msn.com/money/2005/mnynet/service/olsvcupd/OnlSvcBrandInfo.aspx?MSNGUID=&GUID=%1&SKU=3&VER=" VER).arg(fipid)), guidFile);

  TQFile f(guidFile.path());
  if(f.open(IO_ReadOnly)) {
    TQTextStream stream(&f);
    stream.setEncoding(TQTextStream::Unicode);
    TQString msg;
    int errl, errc;
    TQDomDocument doc;
    if(doc.setContent(stream.read(), &msg, &errl, &errc)) {
      TQString fid = extractNodeText(doc, "ProviderSettings/FID");
      TQString org = extractNodeText(doc, "ProviderSettings/Org");
      TQString url = extractNodeText(doc, "ProviderSettings/ProviderURL");
      strncpy(result.fid, fid.latin1(), OFX_FID_LENGTH-1);
      strncpy(result.org, org.latin1(), OFX_ORG_LENGTH-1);
      strncpy(result.url, url.latin1(), OFX_URL_LENGTH-1);
      result.accountlist = (extractNodeText(doc, "ProviderSettings/AcctListAvail") == "1");
      result.statements = (extractNodeText(doc, "BankingCapabilities/Bank") == "1");
      result.billpay= (extractNodeText(doc, "BillPayCapabilities/Pay") == "1");
      result.investments= (extractNodeText(doc, "InvestmentCapabilities/BrkStmt") == "1");
    }
  }

  return result;
}

bool get(const TQString& request, const TQMap<TQString, TQString>& attr, const KURL& url, const KURL& filename)
{
  TQByteArray req(0);
  OfxHttpRequest job("GET", url, req, attr, filename, true);

  return job.error() == TQHttp::NoError;
}

bool post(const TQString& request, const TQMap<TQString, TQString>& attr, const KURL& url, const KURL& filename)
{
  TQByteArray req;
  req.fill(0, request.length()+1);
  req.duplicate(request.ascii(), request.length());

  OfxHttpRequest job("POST", url, req, attr, filename, true);
  return job.error() == TQHttp::NoError;
}

} // namespace OfxPartner

class OfxHttpsRequest::Private
{
public:
  TQFile		m_fpTrace;
};

OfxHttpsRequest::OfxHttpsRequest(const TQString& type, const KURL &url, const TQByteArray &postData, const TQMap<TQString, TQString>& metaData, const KURL& dst, bool showProgressInfo) :
  d(new Private),
  m_dst(dst)
{
  TQDir homeDir(TQDir::home());
  if(homeDir.exists("ofxlog.txt")) {
    d->m_fpTrace.setName(TQString("%1/ofxlog.txt").arg(TQDir::homeDirPath()));
    d->m_fpTrace.open(IO_WriteOnly | IO_Append);
  }

  m_job = KIO::http_post(url, postData, showProgressInfo);
  m_job->addMetaData("content-type", "Content-type: application/x-ofx" );

  if(d->m_fpTrace.isOpen()) {
    TQTextStream ts(&d->m_fpTrace);
    ts << "url: " << url.prettyURL() << "\n";
    ts << "request:\n" << TQString(postData) << "\n" << "response:\n";
  }

  connect(m_job,TQT_SIGNAL(result(KIO::Job*)),this,TQT_SLOT(slotOfxFinished(KIO::Job*)));
  connect(m_job,TQT_SIGNAL(data(KIO::Job*, const TQByteArray&)),this,TQT_SLOT(slotOfxData(KIO::Job*,const TQByteArray&)));
  connect(m_job,TQT_SIGNAL(connected(KIO::Job*)),this,TQT_SLOT(slotOfxConnected(KIO::Job*)));

  tqApp->enter_loop();
}

OfxHttpsRequest::~OfxHttpsRequest()
{
  if(d->m_fpTrace.isOpen()) {
    d->m_fpTrace.close();
  }
}

void OfxHttpsRequest::slotOfxConnected(KIO::Job*)
{
  m_file.setName(m_dst.path());
  m_file.open(IO_WriteOnly);
}

void OfxHttpsRequest::slotOfxData(KIO::Job*,const TQByteArray& _ba)
{
  if(m_file.isOpen()) {
    TQTextStream ts(&m_file);
    ts << TQString(_ba);

    if(d->m_fpTrace.isOpen()) {
      d->m_fpTrace.writeBlock(_ba, _ba.size());
    }


  }
}

void OfxHttpsRequest::slotOfxFinished(KIO::Job* /* e */)
{
  if(m_file.isOpen()) {
    m_file.close();
    if(d->m_fpTrace.isOpen()) {
      d->m_fpTrace.writeBlock("\nCompleted\n\n\n\n", 14);
    }
  }

  int error = m_job->error();
  if ( error ) {
    m_job->showErrorDialog();
    unlink(m_dst.path());

  } else if ( m_job->isErrorPage() ) {
    TQString details;
    TQFile f( m_dst.path() );
    if ( f.open( IO_ReadOnly ) ) {
      TQTextStream stream( &f );
      TQString line;
      while ( !stream.atEnd() ) {
        details += stream.readLine(); // line of text excluding '\n'
      }
      f.close();
    }
    KMessageBox::detailedSorry( 0, i18n("The HTTP request failed."), details, i18n("Failed") );
    unlink(m_dst.path());
  }

  tqApp->exit_loop();
}



OfxHttpRequest::OfxHttpRequest(const TQString& type, const KURL &url, const TQByteArray &postData, const TQMap<TQString, TQString>& metaData, const KURL& dst, bool showProgressInfo)
{
  TQFile f(dst.path());
  m_error = TQHttp::NoError;
  TQString errorMsg;
  if(f.open(IO_WriteOnly)) {
    m_job = new TQHttp(url.host());
    TQHttpRequestHeader header(type, url.encodedPathAndQuery());
    header.setValue("Host", url.host());
    TQMap<TQString, TQString>::const_iterator it;
    for(it = metaData.begin(); it != metaData.end(); ++it) {
      header.setValue(it.key(), *it);
    }

    m_job->request(header, postData, TQT_TQIODEVICE(&f));

    connect(m_job, TQT_SIGNAL(requestFinished(int, bool)),
            this, TQT_SLOT(slotOfxFinished(int, bool)));

    tqApp->enter_loop();

    if(m_error != TQHttp::NoError)
      errorMsg = m_job->errorString();

    delete m_job;
  } else {
    m_error = TQHttp::Aborted;
    errorMsg = i18n("Cannot open file %1 for writing").arg(dst.path());
  }

  if(m_error != TQHttp::NoError) {
    KMessageBox::error(0, errorMsg, i18n("OFX setup error"));
    unlink(dst.path());
  }
}

void OfxHttpRequest::slotOfxFinished(int, bool rc)
{
  if(rc) {
    m_error = m_job->error();
  }
  tqApp->exit_loop();
}

#include "ofxpartner.moc"

// vim:cin:si:ai:et:ts=2:sw=2: