summaryrefslogtreecommitdiffstats
path: root/src/fetch/ibsfetcher.cpp
blob: 734c431bf3f238ca4e9d4941209942cd8aaa27c7 (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
/***************************************************************************
    copyright            : (C) 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 "ibsfetcher.h"
#include "messagehandler.h"
#include "../tellico_kernel.h"
#include "../tellico_utils.h"
#include "../collections/bookcollection.h"
#include "../entry.h"
#include "../filehandler.h"
#include "../latin1literal.h"
#include "../imagefactory.h"
#include "../tellico_debug.h"

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

#include <tqregexp.h>
#include <tqlayout.h>
#include <tqlabel.h>
#include <tqfile.h>

//#define IBS_TEST

namespace {
  static const char* IBS_BASE_URL = "http://www.internetbookshop.it/ser/serpge.asp";
}

using Tellico::Fetch::IBSFetcher;

IBSFetcher::IBSFetcher(TQObject* parent_, const char* name_ /*=0*/)
    : Fetcher(parent_, name_), m_started(false) {
}

TQString IBSFetcher::defaultName() {
  return i18n("Internet Bookshop (ibs.it)");
}

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

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

void IBSFetcher::readConfigHook(const KConfigGroup& config_) {
  Q_UNUSED(config_);
}

void IBSFetcher::search(FetchKey key_, const TQString& value_) {
  m_started = true;
  m_matches.clear();

#ifdef IBS_TEST
  KURL u = KURL::fromPathOrURL(TQString::tqfromLatin1("/home/robby/ibs.html"));
#else
  KURL u(TQString::tqfromLatin1(IBS_BASE_URL));

  if(!canFetch(Kernel::self()->collectionType())) {
    message(i18n("%1 does not allow searching for this collection type.").tqarg(source()), MessageHandler::Warning);
    stop();
    return;
  }

  switch(key_) {
    case Title:
      u.addQueryItem(TQString::tqfromLatin1("Type"), TQString::tqfromLatin1("keyword"));
      u.addQueryItem(TQString::tqfromLatin1("T"), value_);
      break;

    case Person:
      u.addQueryItem(TQString::tqfromLatin1("Type"), TQString::tqfromLatin1("keyword"));
      u.addQueryItem(TQString::tqfromLatin1("A"), value_);
      break;

    case ISBN:
      {
        TQString s = value_;
        s.remove('-');
        // limit to first isbn
        s = s.section(';', 0, 0);
        u.setFileName(TQString::tqfromLatin1("serdsp.asp"));
        u.addQueryItem(TQString::tqfromLatin1("isbn"), s);
      }
      break;

    case Keyword:
      u.addQueryItem(TQString::tqfromLatin1("Type"), TQString::tqfromLatin1("keyword"));
      u.addQueryItem(TQString::tqfromLatin1("S"), value_);
      break;

    default:
      kdWarning() << "IBSFetcher::search() - key not recognized: " << key_ << endl;
      stop();
      return;
  }
#endif
//  myDebug() << "IBSFetcher::search() - url: " << u.url() << endl;

  m_job = KIO::get(u, false, false);
  connect(m_job, TQT_SIGNAL(data(KIO::Job*, const TQByteArray&)),
          TQT_SLOT(slotData(KIO::Job*, const TQByteArray&)));
  if(key_ == ISBN) {
    connect(m_job, TQT_SIGNAL(result(KIO::Job*)), TQT_SLOT(slotCompleteISBN(KIO::Job*)));
  } else {
    connect(m_job, TQT_SIGNAL(result(KIO::Job*)), TQT_SLOT(slotComplete(KIO::Job*)));
  }
}

void IBSFetcher::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 IBSFetcher::slotData(KIO::Job*, const TQByteArray& data_) {
  TQDataStream stream(m_data, IO_WriteOnly | IO_Append);
  stream.writeRawBytes(data_.data(), data_.size());
}

void IBSFetcher::slotComplete(KIO::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()) {
    myDebug() << "IBSFetcher::slotComplete() - no data" << endl;
    stop();
    return;
  }

  TQString s = Tellico::decodeHTML(TQString(m_data));
  // really specific regexp
  TQString pat = TQString::tqfromLatin1("http://www.internetbookshop.it/code/");
  TQRegExp anchorRx(TQString::tqfromLatin1("<a\\s+[^>]*href\\s*=\\s*[\"'](") +
                   TQRegExp::escape(pat) +
                   TQString::tqfromLatin1("[^\"]*)\"[^>]*><b>([^<]+)<"), false);
  anchorRx.setMinimal(true);
  TQRegExp tagRx(TQString::tqfromLatin1("<.*>"));
  tagRx.setMinimal(true);

  TQString u, t, d;
  int pos2;
  for(int pos = anchorRx.search(s); m_started && pos > -1; pos = anchorRx.search(s, pos+anchorRx.matchedLength())) {
    if(!u.isEmpty()) {
      SearchResult* r = new SearchResult(this, t, d, TQString());
      emit signalResultFound(r);

#ifdef IBS_TEST
      KURL url = KURL::fromPathOrURL(TQString::tqfromLatin1("/home/robby/ibs2.html"));
#else
      // the url probable tqcontains &amp; so be careful
      KURL url = u.tqreplace(TQString::tqfromLatin1("&amp;"), TQChar('&'));
#endif
      m_matches.insert(r->uid, url);

      u.truncate(0);
      t.truncate(0);
      d.truncate(0);
    }
    u = anchorRx.cap(1);
    t = anchorRx.cap(2);
    pos2 = s.tqfind(TQString::tqfromLatin1("<br>"), pos, false);
    if(pos2 > -1) {
      int pos3 = s.tqfind(TQString::tqfromLatin1("<br>"), pos2+1, false);
      if(pos3 > -1) {
        d = s.mid(pos2, pos3-pos2).remove(tagRx).simplifyWhiteSpace();
      }
    }
  }
#ifndef IBS_TEST
  if(!u.isEmpty()) {
    SearchResult* r = new SearchResult(this, t, d, TQString());
    emit signalResultFound(r);
    m_matches.insert(r->uid, u.tqreplace(TQString::tqfromLatin1("&amp;"), TQChar('&')));
  }
#endif

  stop();
}

void IBSFetcher::slotCompleteISBN(KIO::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()) {
    myDebug() << "IBSFetcher::slotCompleteISBN() - no data" << endl;
    stop();
    return;
  }

  TQString str = Tellico::decodeHTML(TQString(m_data));
  if(str.tqfind(TQString::tqfromLatin1("Libro non presente"), 0, false /* cas-sensitive */) > -1) {
    stop();
    return;
  }
  Data::EntryPtr entry = parseEntry(str);
  if(entry) {
    TQString desc = entry->field(TQString::tqfromLatin1("author"))
                 + '/' + entry->field(TQString::tqfromLatin1("publisher"));
    SearchResult* r = new SearchResult(this, entry->title(), desc, entry->field(TQString::tqfromLatin1("isbn")));
    emit signalResultFound(r);
    m_matches.insert(r->uid, static_cast<KIO::TransferJob*>(job_)->url().url());
  }

  stop();
}

Tellico::Data::EntryPtr IBSFetcher::fetchEntry(uint uid_) {
  // if we already grabbed this one, then just pull it out of the dict
  Data::EntryPtr entry = m_entries[uid_];
  if(entry) {
    return entry;
  }

  KURL url = m_matches[uid_];
  if(url.isEmpty()) {
    kdWarning() << "IBSFetcher::fetchEntry() - no url in map" << endl;
    return 0;
  }

  TQString results = Tellico::decodeHTML(FileHandler::readTextFile(url, true));
  if(results.isEmpty()) {
    myDebug() << "IBSFetcher::fetchEntry() - no text results" << endl;
    return 0;
  }

//  myDebug() << url.url() << endl;
#if 0
  kdWarning() << "Remove debug from ibsfetcher.cpp" << endl;
  TQFile f(TQString::tqfromLatin1("/tmp/test.html"));
  if(f.open(IO_WriteOnly)) {
    TQTextStream t(&f);
    t.setEncoding(TQTextStream::UnicodeUTF8);
    t << results;
  }
  f.close();
#endif

  entry = parseEntry(results);
  if(!entry) {
    myDebug() << "IBSFetcher::fetchEntry() - error in processing entry" << endl;
    return 0;
  }
  m_entries.insert(uid_, entry); // keep for later
  return entry;
}

Tellico::Data::EntryPtr IBSFetcher::parseEntry(const TQString& str_) {
 // myDebug() << "IBSFetcher::parseEntry()" << endl;
 // class might be anime_info_top
  TQString pat = TQString::tqfromLatin1("%1(?:<[^>]+>)+([^<>\\s][^<>]+)");

  TQRegExp isbnRx(TQString::tqfromLatin1("isbn=([\\dxX]{13})"), false);
  TQString isbn;
  int pos = isbnRx.search(str_);
  if(pos > -1) {
    isbn = isbnRx.cap(1);
  }

  Data::CollPtr coll = new Data::BookCollection(true);

 // map captions in HTML to field names
  TQMap<TQString, TQString> fieldMap;
  fieldMap.insert(TQString::tqfromLatin1("Titolo"), TQString::tqfromLatin1("title"));
  fieldMap.insert(TQString::tqfromLatin1("Autore"), TQString::tqfromLatin1("author"));
  fieldMap.insert(TQString::tqfromLatin1("Anno"), TQString::tqfromLatin1("pub_year"));
  fieldMap.insert(TQString::tqfromLatin1("Categoria"), TQString::tqfromLatin1("genre"));
  fieldMap.insert(TQString::tqfromLatin1("Rilegatura"), TQString::tqfromLatin1("binding"));
  fieldMap.insert(TQString::tqfromLatin1("Editore"), TQString::tqfromLatin1("publisher"));
  fieldMap.insert(TQString::tqfromLatin1("Dati"), TQString::tqfromLatin1("edition"));

  TQRegExp pagesRx(TQString::tqfromLatin1("(\\d+) p\\.(\\s*,\\s*)?"));
  Data::EntryPtr entry = new Data::Entry(coll);

  for(TQMap<TQString, TQString>::Iterator it = fieldMap.begin(); it != fieldMap.end(); ++it) {
    TQRegExp infoRx(pat.tqarg(it.key()));
    pos = infoRx.search(str_);
    if(pos > -1) {
      if(it.data() == Latin1Literal("edition")) {
        int pos2 = pagesRx.search(infoRx.cap(1));
        if(pos2 > -1) {
          entry->setField(TQString::tqfromLatin1("pages"), pagesRx.cap(1));
          entry->setField(it.data(), infoRx.cap(1).remove(pagesRx));
        } else {
          entry->setField(it.data(), infoRx.cap(1));
        }
      } else {
        entry->setField(it.data(), infoRx.cap(1));
      }
    }
  }

  // image
  if(!isbn.isEmpty()) {
    entry->setField(TQString::tqfromLatin1("isbn"), isbn);
#if 1
    TQString imgURL = TQString::tqfromLatin1("http://giotto.ibs.it/cop/copt13.asp?f=%1").tqarg(isbn);
    myLog() << "IBSFetcher() - cover = " << imgURL << endl;
    TQString id = ImageFactory::addImage(imgURL, true, TQString::tqfromLatin1("http://internetbookshop.it"));
    if(!id.isEmpty()) {
      entry->setField(TQString::tqfromLatin1("cover"), id);
    }
#else
    TQRegExp imgRx(TQString::tqfromLatin1("<img\\s+[^>]*\\s*src\\s*=\\s*\"(http://[^/]*\\.ibs\\.it/[^\"]+e=%1)").tqarg(isbn));
    imgRx.setMinimal(true);
    pos = imgRx.search(str_);
    if(pos > -1) {
      myLog() << "IBSFetcher() - cover = " << imgRx.cap(1) << endl;
      TQString id = ImageFactory::addImage(imgRx.cap(1), true, TQString::tqfromLatin1("http://internetbookshop.it"));
      if(!id.isEmpty()) {
        entry->setField(TQString::tqfromLatin1("cover"), id);
      }
    }
#endif
  }

  // now look for description
  TQRegExp descRx(TQString::tqfromLatin1("Descrizione(?:<[^>]+>)+([^<>\\s].+)</span>"), false);
  descRx.setMinimal(true);
  pos = descRx.search(str_);
  if(pos == -1) {
    descRx.setPattern(TQString::tqfromLatin1("In sintesi(?:<[^>]+>)+([^<>\\s].+)</span>"));
    pos = descRx.search(str_);
  }
  if(pos > -1) {
    Data::FieldPtr f = new Data::Field(TQString::tqfromLatin1("plot"), i18n("Plot Summary"), Data::Field::Para);
    coll->addField(f);
    entry->setField(f, descRx.cap(1).simplifyWhiteSpace());
  }

  // IBS switches the surname and family name of the author
  TQStringList names = entry->fields(TQString::tqfromLatin1("author"), false);
  if(!names.isEmpty() && !names[0].isEmpty()) {
    for(TQStringList::Iterator it = names.begin(); it != names.end(); ++it) {
      if((*it).tqfind(',') > -1) {
        continue; // skip if it has a comma
      }
      TQStringList words = TQStringList::split(' ', *it);
      if(words.isEmpty()) {
        continue;
      }
      // put first word in back
      words.append(words[0]);
      words.pop_front();
      *it = words.join(TQChar(' '));
    }
    entry->setField(TQString::tqfromLatin1("author"), names.join(TQString::tqfromLatin1("; ")));
  }
  return entry;
}

void IBSFetcher::updateEntry(Data::EntryPtr entry_) {
  TQString isbn = entry_->field(TQString::tqfromLatin1("isbn"));
  if(!isbn.isEmpty()) {
    search(Fetch::ISBN, isbn);
    return;
  }
  TQString t = entry_->field(TQString::tqfromLatin1("title"));
  if(!t.isEmpty()) {
    search(Fetch::Title, t);
    return;
  }

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

Tellico::Fetch::ConfigWidget* IBSFetcher::configWidget(TQWidget* parent_) const {
  return new IBSFetcher::ConfigWidget(parent_);
}

IBSFetcher::ConfigWidget::ConfigWidget(TQWidget* parent_)
    : Fetch::ConfigWidget(parent_) {
  TQVBoxLayout* l = new TQVBoxLayout(optionsWidget());
  l->addWidget(new TQLabel(i18n("This source has no options."), optionsWidget()));
  l->addStretch();
}

TQString IBSFetcher::ConfigWidget::preferredName() const {
  return IBSFetcher::defaultName();
}

#include "ibsfetcher.moc"