summaryrefslogtreecommitdiffstats
path: root/src/fetch/srufetcher.cpp
blob: 38bf62a00a57cf86def961d6c16944cdb9e252bb (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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/***************************************************************************
    copyright            : (C) 2003-2006 by Robby Stephenson
    email                : robby@periapsis.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of version 2 of the GNU General Public License as  *
 *   published by the Free Software Foundation;                            *
 *                                                                         *
 ***************************************************************************/

#include "srufetcher.h"
#include "messagehandler.h"
#include "../field.h"
#include "../collection.h"
#include "../translators/tellico_xml.h"
#include "../translators/xslthandler.h"
#include "../translators/tellicoimporter.h"
#include "../translators/dcimporter.h"
#include "../tellico_kernel.h"
#include "../tellico_debug.h"
#include "../gui/lineedit.h"
#include "../gui/combobox.h"
#include "../latin1literal.h"
#include "../tellico_utils.h"
#include "../lccnvalidator.h"

#include <klocale.h>
#include <tdeio/job.h>
#include <kstandarddirs.h>
#include <tdeconfig.h>
#include <kcombobox.h>
#include <kaccelmanager.h>
#include <knuminput.h>

#include <tqlabel.h>
#include <tqlayout.h>
#include <tqwhatsthis.h>

//#define SRU_DEBUG

namespace {
  // 7090 was the old default port, but that wa sjust because LoC used it
  // let's use default HTTP port of 80 now
  static const int SRU_DEFAULT_PORT = 80;
  static const int SRU_MAX_RECORDS = 25;
}

using Tellico::Fetch::SRUFetcher;
using Tellico::Fetch::SRUConfigWidget;

SRUFetcher::SRUFetcher(TQObject* parent_, const char* name_)
    : Fetcher(parent_, name_), m_job(0), m_MARCXMLHandler(0), m_MODSHandler(0), m_started(false) {
}

SRUFetcher::SRUFetcher(const TQString& name_, const TQString& host_, uint port_, const TQString& path_,
                       TQObject* parent_) : Fetcher(parent_),
      m_host(host_), m_port(port_), m_path(path_),
      m_job(0), m_MARCXMLHandler(0), m_MODSHandler(0), m_started(false) {
  m_name = name_; // m_name is protected in super class
}

SRUFetcher::~SRUFetcher() {
  delete m_MARCXMLHandler;
  m_MARCXMLHandler = 0;
  delete m_MODSHandler;
  m_MODSHandler = 0;
}

TQString SRUFetcher::defaultName() {
  return i18n("SRU Server");
}

TQString SRUFetcher::source() const {
  return m_name.isEmpty() ? defaultName() : m_name;
}

bool SRUFetcher::canFetch(int type) const {
  return type == Data::Collection::Book || type == Data::Collection::Bibtex;
}

void SRUFetcher::readConfigHook(const TDEConfigGroup& config_) {
  m_host = config_.readEntry("Host");
  int p = config_.readNumEntry("Port", SRU_DEFAULT_PORT);
  if(p > 0) {
    m_port = p;
  }
  m_path = config_.readEntry("Path");
  // used to be called Database
  if(m_path.isEmpty()) {
    m_path = config_.readEntry("Database");
  }
  if(!m_path.startsWith(TQChar('/'))) {
    m_path.prepend('/');
  }
  m_format = config_.readEntry("Format", TQString::fromLatin1("mods"));
  m_fields = config_.readListEntry("Custom Fields");
}

void SRUFetcher::search(FetchKey key_, const TQString& value_) {
  if(m_host.isEmpty() || m_path.isEmpty()) {
    myDebug() << "SRUFetcher::search() - settings are not set!" << endl;
    stop();
    return;
  }

  m_started = true;

#ifdef SRU_DEBUG
  KURL u = KURL::fromPathOrURL(TQString::fromLatin1("/home/robby/sru.xml"));
#else
  KURL u;
  u.setProtocol(TQString::fromLatin1("http"));
  u.setHost(m_host);
  u.setPort(m_port);
  u.setPath(m_path);

  u.addQueryItem(TQString::fromLatin1("operation"), TQString::fromLatin1("searchRetrieve"));
  u.addQueryItem(TQString::fromLatin1("version"), TQString::fromLatin1("1.1"));
  u.addQueryItem(TQString::fromLatin1("maximumRecords"), TQString::number(SRU_MAX_RECORDS));
  u.addQueryItem(TQString::fromLatin1("recordSchema"), m_format);

  const int type = Kernel::self()->collectionType();
  TQString str = TQChar('"') + value_ + TQChar('"');
  switch(key_) {
    case Title:
      u.addQueryItem(TQString::fromLatin1("query"), TQString::fromLatin1("dc.title=") + str);
      break;

    case Person:
      {
        TQString s;
        if(type == Data::Collection::Book || type == Data::Collection::Bibtex) {
          s = TQString::fromLatin1("author=") + str + TQString::fromLatin1(" or dc.author=") + str;
        } else {
          s = TQString::fromLatin1("dc.creator=") + str + TQString::fromLatin1(" or dc.editor=") + str;
        }
        u.addQueryItem(TQString::fromLatin1("query"), s);
      }
      break;

    case ISBN:
      // no validation here
      str.remove('-');
      // limit to first isbn
      str = str.section(';', 0, 0);
      u.addQueryItem(TQString::fromLatin1("query"), TQString::fromLatin1("bath.isbn=") + str);
      break;

    case LCCN:
      {
        // limit to first lccn
        str.remove('-');
        str = str.section(';', 0, 0);
        // also try formalized lccn
        TQString lccn = LCCNValidator::formalize(str);
        u.addQueryItem(TQString::fromLatin1("query"),
                       TQString::fromLatin1("bath.lccn=") + str +
                       TQString::fromLatin1(" or bath.lccn=") + lccn
                       );
      }
      break;

    case Keyword:
      u.addQueryItem(TQString::fromLatin1("query"), str);
      break;

    case Raw:
      {
        TQString key = value_.section('=', 0, 0).stripWhiteSpace();
        TQString str = value_.section('=', 1).stripWhiteSpace();
        u.addQueryItem(key, str);
      }
      break;

    default:
      kdWarning() << "SRUFetcher::search() - key not recognized: " << key_ << endl;
      stop();
      break;
  }
#endif
//  myDebug() << u.prettyURL() << endl;

  m_job = TDEIO::get(u, false, false);
  connect(m_job, TQT_SIGNAL(data(TDEIO::Job*, const TQByteArray&)),
          TQT_SLOT(slotData(TDEIO::Job*, const TQByteArray&)));
  connect(m_job, TQT_SIGNAL(result(TDEIO::Job*)),
          TQT_SLOT(slotComplete(TDEIO::Job*)));
}

void SRUFetcher::stop() {
  if(!m_started) {
    return;
  }
  if(m_job) {
    m_job->kill();
    m_job = 0;
  }
  m_data.truncate(0);
  m_started = false;
  emit signalDone(this);
}

void SRUFetcher::slotData(TDEIO::Job*, const TQByteArray& data_) {
  TQDataStream stream(m_data, IO_WriteOnly | IO_Append);
  stream.writeRawBytes(data_.data(), data_.size());
}

void SRUFetcher::slotComplete(TDEIO::Job* job_) {
  // since the fetch is done, don't worry about holding the job pointer
  m_job = 0;

  if(job_->error()) {
    job_->showErrorDialog(Kernel::self()->widget());
    stop();
    return;
  }

  if(m_data.isEmpty()) {
    stop();
    return;
  }

  Data::CollPtr coll;
  TQString msg;

  const TQString result = TQString::fromUtf8(m_data, m_data.size());

  // first check for SRU errors
  const TQString& diag = XML::nsZingDiag;
  Import::XMLImporter xmlImporter(result);
  TQDomDocument dom = xmlImporter.domDocument();

  TQDomNodeList diagList = dom.elementsByTagNameNS(diag, TQString::fromLatin1("diagnostic"));
  for(uint i = 0; i < diagList.count(); ++i) {
    TQDomElement elem = diagList.item(i).toElement();
    TQDomNodeList nodeList1 = elem.elementsByTagNameNS(diag, TQString::fromLatin1("message"));
    TQDomNodeList nodeList2 = elem.elementsByTagNameNS(diag, TQString::fromLatin1("details"));
    for(uint j = 0; j < nodeList1.count(); ++j) {
      TQString d = nodeList1.item(j).toElement().text();
      if(!d.isEmpty()) {
        TQString d2 = nodeList2.item(j).toElement().text();
        if(!d2.isEmpty()) {
          d += " (" + d2 + ')';
        }
        myDebug() << "SRUFetcher::slotComplete() - " << d << endl;
        if(!msg.isEmpty()) msg += '\n';
        msg += d;
      }
    }
  }

  TQString modsResult;
  if(m_format == Latin1Literal("mods")) {
    modsResult = result;
  } else if(m_format == Latin1Literal("marcxml") && initMARCXMLHandler()) {
    modsResult = m_MARCXMLHandler->applyStylesheet(result);
  }
  if(!modsResult.isEmpty() && initMODSHandler()) {
    Import::TellicoImporter imp(m_MODSHandler->applyStylesheet(modsResult));
    coll = imp.collection();
    if(!msg.isEmpty()) msg += '\n';
    msg += imp.statusMessage();
  } else if(m_format == Latin1Literal("dc")) {
    Import::DCImporter imp(dom);
    coll = imp.collection();
    if(!msg.isEmpty()) msg += '\n';
    msg += imp.statusMessage();
  } else {
    myDebug() << "SRUFetcher::slotComplete() - unrecognized format: " << m_format << endl;
    stop();
    return;
  }

  if(coll && !msg.isEmpty()) {
    message(msg, coll->entryCount() == 0 ? MessageHandler::Warning : MessageHandler::Status);
  }

  if(!coll) {
    myDebug() << "SRUFetcher::slotComplete() - no collection pointer" << endl;
    if(!msg.isEmpty()) {
      message(msg, MessageHandler::Error);
    }
    stop();
    return;
  }

  const StringMap customFields = SRUFetcher::customFields();
  for(StringMap::ConstIterator it = customFields.begin(); it != customFields.end(); ++it) {
    if(!m_fields.contains(it.key())) {
      coll->removeField(it.key());
    }
  }

  Data::EntryVec entries = coll->entries();
  for(Data::EntryVec::Iterator entry = entries.begin(); entry != entries.end(); ++entry) {
    TQString desc;
    switch(coll->type()) {
      case Data::Collection::Book:
        desc = entry->field(TQString::fromLatin1("author"))
               + TQChar('/')
               + entry->field(TQString::fromLatin1("publisher"));
        if(!entry->field(TQString::fromLatin1("cr_year")).isEmpty()) {
          desc += TQChar('/') + entry->field(TQString::fromLatin1("cr_year"));
        } else if(!entry->field(TQString::fromLatin1("pub_year")).isEmpty()){
          desc += TQChar('/') + entry->field(TQString::fromLatin1("pub_year"));
        }
        break;

      case Data::Collection::Video:
        desc = entry->field(TQString::fromLatin1("studio"))
               + TQChar('/')
               + entry->field(TQString::fromLatin1("director"))
               + TQChar('/')
               + entry->field(TQString::fromLatin1("year"));
        break;

      case Data::Collection::Album:
        desc = entry->field(TQString::fromLatin1("artist"))
               + TQChar('/')
               + entry->field(TQString::fromLatin1("label"))
               + TQChar('/')
               + entry->field(TQString::fromLatin1("year"));
        break;

      default:
        break;
    }
    SearchResult* r = new SearchResult(this, entry->title(), desc, entry->field(TQString::fromLatin1("isbn")));
    m_entries.insert(r->uid, entry);
    emit signalResultFound(r);
  }
  stop();
}

Tellico::Data::EntryPtr SRUFetcher::fetchEntry(uint uid_) {
  return m_entries[uid_];
}

void SRUFetcher::updateEntry(Data::EntryPtr entry_) {
//  myDebug() << "SRUFetcher::updateEntry() - " << source() << ": " << entry_->title() << endl;
  TQString isbn = entry_->field(TQString::fromLatin1("isbn"));
  if(!isbn.isEmpty()) {
    search(Fetch::ISBN, isbn);
    return;
  }

  TQString lccn = entry_->field(TQString::fromLatin1("lccn"));
  if(!lccn.isEmpty()) {
    search(Fetch::LCCN, lccn);
    return;
  }

  // optimistically try searching for title and rely on Collection::sameEntry() to figure things out
  TQString t = entry_->field(TQString::fromLatin1("title"));
  if(!t.isEmpty()) {
    search(Fetch::Title, t);
    return;
  }

  myDebug() << "SRUFetcher::updateEntry() - insufficient info to search" << endl;
  emit signalDone(this); // always need to emit this if not continuing with the search
}

bool SRUFetcher::initMARCXMLHandler() {
  if(m_MARCXMLHandler) {
    return true;
  }

  TQString xsltfile = locate("appdata", TQString::fromLatin1("MARC21slim2MODS3.xsl"));
  if(xsltfile.isEmpty()) {
    kdWarning() << "SRUFetcher::initHandlers() - can not locate MARC21slim2MODS3.xsl." << endl;
    return false;
  }

  KURL u;
  u.setPath(xsltfile);

  m_MARCXMLHandler = new XSLTHandler(u);
  if(!m_MARCXMLHandler->isValid()) {
    kdWarning() << "SRUFetcher::initHandlers() - error in MARC21slim2MODS3.xsl." << endl;
    delete m_MARCXMLHandler;
    m_MARCXMLHandler = 0;
    return false;
  }
  return true;
}

bool SRUFetcher::initMODSHandler() {
  if(m_MODSHandler) {
    return true;
  }

  TQString xsltfile = locate("appdata", TQString::fromLatin1("mods2tellico.xsl"));
  if(xsltfile.isEmpty()) {
    kdWarning() << "SRUFetcher::initHandlers() - can not locate mods2tellico.xsl." << endl;
    return false;
  }

  KURL u;
  u.setPath(xsltfile);

  m_MODSHandler = new XSLTHandler(u);
  if(!m_MODSHandler->isValid()) {
    kdWarning() << "SRUFetcher::initHandlers() - error in mods2tellico.xsl." << endl;
    delete m_MODSHandler;
    m_MODSHandler = 0;
    return false;
  }
  return true;
}

Tellico::Fetch::Fetcher::Ptr SRUFetcher::libraryOfCongress(TQObject* parent_) {
  return new SRUFetcher(i18n("Library of Congress (US)"), TQString::fromLatin1("z3950.loc.gov"), 7090,
                        TQString::fromLatin1("voyager"), parent_);
}

// static
Tellico::StringMap SRUFetcher::customFields() {
  StringMap map;
  map[TQString::fromLatin1("address")]  = i18n("Address");
  map[TQString::fromLatin1("abstract")] = i18n("Abstract");
  return map;
}

Tellico::Fetch::ConfigWidget* SRUFetcher::configWidget(TQWidget* parent_) const {
  return new SRUConfigWidget(parent_, this);
}

SRUConfigWidget::SRUConfigWidget(TQWidget* parent_, const SRUFetcher* fetcher_ /*=0*/)
    : ConfigWidget(parent_) {
  TQGridLayout* l = new TQGridLayout(optionsWidget(), 4, 2);
  l->setSpacing(4);
  l->setColStretch(1, 10);

  int row = -1;
  TQLabel* label = new TQLabel(i18n("Hos&t: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_hostEdit = new GUI::LineEdit(optionsWidget());
  connect(m_hostEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  connect(m_hostEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SIGNAL(signalName(const TQString&)));
  connect(m_hostEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotCheckHost()));
  l->addWidget(m_hostEdit, row, 1);
  TQString w = i18n("Enter the host name of the server.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_hostEdit, w);
  label->setBuddy(m_hostEdit);

  label = new TQLabel(i18n("&Port: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_portSpinBox = new KIntSpinBox(0, 999999, 1, SRU_DEFAULT_PORT, 10, optionsWidget());
  connect(m_portSpinBox, TQT_SIGNAL(valueChanged(int)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_portSpinBox, row, 1);
  w = i18n("Enter the port number of the server. The default is %1.").arg(SRU_DEFAULT_PORT);
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_portSpinBox, w);
  label->setBuddy(m_portSpinBox);

  label = new TQLabel(i18n("Path: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_pathEdit = new GUI::LineEdit(optionsWidget());
  connect(m_pathEdit, TQT_SIGNAL(textChanged(const TQString&)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_pathEdit, row, 1);
  w = i18n("Enter the path to the database used by the server.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_pathEdit, w);
  label->setBuddy(m_pathEdit);

  label = new TQLabel(i18n("Format: "), optionsWidget());
  l->addWidget(label, ++row, 0);
  m_formatCombo = new GUI::ComboBox(optionsWidget());
  m_formatCombo->insertItem(TQString::fromLatin1("MODS"), TQString::fromLatin1("mods"));
  m_formatCombo->insertItem(TQString::fromLatin1("MARCXML"), TQString::fromLatin1("marcxml"));
  m_formatCombo->insertItem(TQString::fromLatin1("Dublin Core"), TQString::fromLatin1("dc"));
  connect(m_formatCombo, TQT_SIGNAL(activated(int)), TQT_SLOT(slotSetModified()));
  l->addWidget(m_formatCombo, row, 1);
  w = i18n("Enter the result format used by the server.");
  TQWhatsThis::add(label, w);
  TQWhatsThis::add(m_formatCombo, w);
  label->setBuddy(m_formatCombo);

  l->setRowStretch(++row, 1);

  // now add additional fields widget
  addFieldsWidget(SRUFetcher::customFields(), fetcher_ ? fetcher_->m_fields : TQStringList());

  if(fetcher_) {
    m_hostEdit->setText(fetcher_->m_host);
    m_portSpinBox->setValue(fetcher_->m_port);
    m_pathEdit->setText(fetcher_->m_path);
    m_formatCombo->setCurrentData(fetcher_->m_format);
  }
  KAcceleratorManager::manage(optionsWidget());
}

void SRUConfigWidget::saveConfig(TDEConfigGroup& config_) {
  TQString s = m_hostEdit->text().stripWhiteSpace();
  if(!s.isEmpty()) {
    config_.writeEntry("Host", s);
  }
  int port = m_portSpinBox->value();
  if(port > 0) {
    config_.writeEntry("Port", port);
  }
  s = m_pathEdit->text().stripWhiteSpace();
  if(!s.isEmpty()) {
    config_.writeEntry("Path", s);
  }
  s = m_formatCombo->currentData().toString();
  if(!s.isEmpty()) {
    config_.writeEntry("Format", s);
  }
  saveFieldsConfig(config_);
  slotSetModified(false);
}

TQString SRUConfigWidget::preferredName() const {
  TQString s = m_hostEdit->text();
  return s.isEmpty() ? SRUFetcher::defaultName() : s;
}

void SRUConfigWidget::slotCheckHost() {
  TQString s = m_hostEdit->text();
  // someone might be pasting a full URL, check that
  if(s.find(':') > -1 || s.find('/') > -1) {
    KURL u(s);
    if(u.isValid()) {
      m_hostEdit->setText(u.host());
      if(u.port() > 0) {
        m_portSpinBox->setValue(u.port());
      }
      if(!u.path().isEmpty()) {
        m_pathEdit->setText(u.path());
      }
    }
  }
}

#include "srufetcher.moc"