summaryrefslogtreecommitdiffstats
path: root/src/z3950connection.cpp
blob: ada2a1d39bf8018922e1c60777c895ecf47a8052 (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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
/***************************************************************************
    copyright            : (C) 2005-2006 by Robby Stephenson
    email                : $EMAIL
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This file has been modified to match the requirements of KBibTeX.     *
 *   In case of problems or bugs arising from this implementation, please  *
 *   contact the KBibTeX team first.                                       *
 *                             Thomas Fischer <fischer@unix-ag.uni-kl.de>  *
 *                                                                         *
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 "z3950connection.h"
// #include "z3950fetcher.h"
#include "messagehandler.h"
#include "latin1literal.h"
#include <kdebug.h>
#include "iso5426converter.h"
#include "iso6937converter.h"

#include <qapplication.h>

#include <config.h>

#ifdef HAVE_YAZ
extern "C"
{
#include <yaz/zoom.h>
#include <yaz/marcdisp.h>
#include <yaz/yaz-version.h>
}
#endif

#include <klocale.h>

#include <qfile.h>

namespace
{
    static const size_t Z3950_DEFAULT_MAX_RECORDS = 20;
}

using KBibTeX::Z3950ResultFound;
using KBibTeX::Z3950Connection;

Z3950ResultFound::Z3950ResultFound( const QString& s ) : QCustomEvent( uid() )
        , m_result( QDeepCopy<QString>( s ) )
{
    ++Z3950Connection::resultsLeft;
}

Z3950ResultFound::~Z3950ResultFound()
{
    --Z3950Connection::resultsLeft;
}

class Z3950Connection::Private
{
public:
    Private() {}
#ifdef HAVE_YAZ
    ~Private()
    {
        ZOOM_options_destroy( conn_opt );
        ZOOM_connection_destroy( conn );
    };

    ZOOM_options conn_opt;
    ZOOM_connection conn;
#endif
};

int Z3950Connection::resultsLeft = 0;

// since the character set goes into a yaz api call
// I'm paranoid about user insertions, so just grab 64
// characters at most
Z3950Connection::Z3950Connection( QObject* fetcher,
                                  const QString& host,
                                  uint port,
                                  const QString& dbname,
                                  const QString& sourceCharSet,
                                  const QString& syntax,
                                  const QString& esn )
        : QThread()
        , d( new Private() )
        , m_connected( false )
        , m_aborted( false )
        , m_fetcher( fetcher )
        , m_host( QDeepCopy<QString>( host ) )
        , m_port( port )
        , m_dbname( QDeepCopy<QString>( dbname ) )
        , m_sourceCharSet( QDeepCopy<QString>( sourceCharSet.left( 64 ) ) )
        , m_syntax( QDeepCopy<QString>( syntax ) )
        , m_esn( QDeepCopy<QString>( esn ) )
        , m_start( 0 )
        , m_limit( Z3950_DEFAULT_MAX_RECORDS )
        , m_hasMore( false )
{
}

Z3950Connection::~Z3950Connection()
{
    m_connected = false;
    delete d;
    d = 0;
}

void Z3950Connection::reset()
{
    m_start = 0;
    m_limit = Z3950_DEFAULT_MAX_RECORDS;
}

void Z3950Connection::setQuery( const QString& query_, unsigned int numHits )
{
    m_pqn = QDeepCopy<QString>( query_ );
    m_limit = Z3950_DEFAULT_MAX_RECORDS < numHits ? Z3950_DEFAULT_MAX_RECORDS : numHits;
}

void Z3950Connection::setUserPassword( const QString& user_, const QString& pword_ )
{
    m_user = QDeepCopy<QString>( user_ );
    m_password = QDeepCopy<QString>( pword_ );
}

void Z3950Connection::run()
{
//  kdDebug() << "Z3950Connection::run() - " << m_fetcher->source() << endl;
    m_aborted = false;
    m_hasMore = false;
    resultsLeft = 0;
#ifdef HAVE_YAZ

    if ( !makeConnection() )
    {
        done();
        return;
    }

    ZOOM_query query = ZOOM_query_create();
    kdDebug() << "Z3950Connection::run() - pqn = " << toCString( m_pqn ) << endl;
    int errcode = ZOOM_query_prefix( query, toCString( m_pqn ) );
    if ( errcode != 0 )
    {
        kdDebug() << "Z3950Connection::run() - query error: " << m_pqn << endl;
        ZOOM_query_destroy( query );
        QString s = i18n( "Query error!" );
        s += ' ' + m_pqn;
        done( s, MessageHandler::Error );
        return;
    }

    ZOOM_resultset resultSet = ZOOM_connection_search( d->conn, query );

    // check abort status
    if ( m_aborted )
    {
        done();
        return;
    }

    // I know the LOC wants the syntax = "xml" and esn = "mods"
    // to get MODS data, that seems a bit odd...
    // esn only makes sense for marc and grs-1
    // if syntax is mods, set esn to mods too
    QCString type = "raw";
    if ( m_syntax == Latin1Literal( "mods" ) )
    {
        m_syntax = QString::fromLatin1( "xml" );
        ZOOM_resultset_option_set( resultSet, "elementSetName", "mods" );
        type = "xml";
    }
    else
    {
        ZOOM_resultset_option_set( resultSet, "elementSetName", m_esn.latin1() );
    }
    ZOOM_resultset_option_set( resultSet, "start", QCString().setNum( m_start ) );
    ZOOM_resultset_option_set( resultSet, "count", QCString().setNum( m_limit - m_start ) );
    // search in default syntax, unless syntax is already set
    if ( !m_syntax.isEmpty() )
    {
        ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", m_syntax.latin1() );
    }

    const char* errmsg;
    const char* addinfo;
    errcode = ZOOM_connection_error( d->conn, &errmsg, &addinfo );
    if ( errcode != 0 )
    {
        ZOOM_resultset_destroy( resultSet );
        ZOOM_query_destroy( query );
        m_connected = false;

        QString s = i18n( "Connection search error %1: %2" ).arg( errcode ).arg( toString( errmsg ) );
        if ( !QCString( addinfo ).isEmpty() )
        {
            s += " (" + toString( addinfo ) + ")";
        }
        kdDebug() << "Z3950Connection::run() - " << s << endl;
        done( s, MessageHandler::Error );
        return;
    }

    const size_t numResults = ZOOM_resultset_size( resultSet );

    QString newSyntax = m_syntax;
    if ( numResults > 0 )
    {
        kdDebug() << "Z3950Connection::run() - current syntax is " << m_syntax << " (" << numResults << " results)" << endl;
        // so now we know that results exist, might have to check syntax
        int len;
        ZOOM_record rec = ZOOM_resultset_record( resultSet, 0 );
        // want raw unless it's mods
        ZOOM_record_get( rec, type, &len );
        if ( len > 0 && m_syntax.isEmpty() )
        {
            newSyntax = QString::fromLatin1( ZOOM_record_get( rec, "syntax", &len ) ).lower();
            kdDebug() << "Z3950Connection::run() - syntax guess is " << newSyntax << endl;
            if ( newSyntax == Latin1Literal( "mods" ) || newSyntax == Latin1Literal( "xml" ) )
            {
                m_syntax = QString::fromLatin1( "xml" );
                ZOOM_resultset_option_set( resultSet, "elementSetName", "mods" );
            }
            else if ( newSyntax == Latin1Literal( "grs-1" ) )
            {
                // if it's defaulting to grs-1, go ahead and change it to try to get a marc
                // record since grs-1 is a last resort for us
                newSyntax.truncate( 0 );
            }
        }
        // right now, we just understand mods, unimarc, marc21/usmarc, and grs-1
        if ( newSyntax != Latin1Literal( "xml" ) &&
                newSyntax != Latin1Literal( "usmarc" ) &&
                newSyntax != Latin1Literal( "marc21" ) &&
                newSyntax != Latin1Literal( "unimarc" ) &&
                newSyntax != Latin1Literal( "grs-1" ) )
        {
            kdDebug() << "Z3950Connection::run() - changing z39.50 syntax to MODS" << endl;
            newSyntax = QString::fromLatin1( "xml" );
            ZOOM_resultset_option_set( resultSet, "elementSetName", "mods" );
            ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", newSyntax.latin1() );
            rec = ZOOM_resultset_record( resultSet, 0 );
            ZOOM_record_get( rec, "xml", &len );
            if ( len == 0 )
            {
                // change set name back
                ZOOM_resultset_option_set( resultSet, "elementSetName", m_esn.latin1() );
                newSyntax = QString::fromLatin1( "usmarc" ); // try usmarc
                kdDebug() << "Z3950Connection::run() - changing z39.50 syntax to USMARC" << endl;
                ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", newSyntax.latin1() );
                rec = ZOOM_resultset_record( resultSet, 0 );
                ZOOM_record_get( rec, "raw", &len );
            }
            if ( len == 0 )
            {
                newSyntax = QString::fromLatin1( "marc21" ); // try marc21
                kdDebug() << "Z3950Connection::run() - changing z39.50 syntax to MARC21" << endl;
                ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", newSyntax.latin1() );
                rec = ZOOM_resultset_record( resultSet, 0 );
                ZOOM_record_get( rec, "raw", &len );
            }
            if ( len == 0 )
            {
                newSyntax = QString::fromLatin1( "unimarc" ); // try unimarc
                kdDebug() << "Z3950Connection::run() - changing z39.50 syntax to UNIMARC" << endl;
                ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", newSyntax.latin1() );
                rec = ZOOM_resultset_record( resultSet, 0 );
                ZOOM_record_get( rec, "raw", &len );
            }
            if ( len == 0 )
            {
                newSyntax = QString::fromLatin1( "grs-1" ); // try grs-1
                kdDebug() << "Z3950Connection::run() - changing z39.50 syntax to GRS-1" << endl;
                ZOOM_resultset_option_set( resultSet, "preferredRecordSyntax", newSyntax.latin1() );
                rec = ZOOM_resultset_record( resultSet, 0 );
                ZOOM_record_get( rec, "raw", &len );
            }
            if ( len == 0 )
            {
                kdDebug() << "Z3950Connection::run() - giving up" << endl;
                ZOOM_resultset_destroy( resultSet );
                ZOOM_query_destroy( query );
                done( i18n( "Record syntax error" ), MessageHandler::Error );
                return;
            }
            kdDebug() << "Z3950Connection::run() - final syntax is " << newSyntax << endl;
        }
    }

    // go back to fooling ourselves and calling it mods
    if ( m_syntax == Latin1Literal( "xml" ) )
    {
        m_syntax = QString::fromLatin1( "mods" );
    }
    if ( newSyntax == Latin1Literal( "xml" ) )
    {
        newSyntax = QString::fromLatin1( "mods" );
    }
    // save syntax change for next time
    if ( m_syntax != newSyntax )
    {
        qApp->postEvent( m_fetcher, new Z3950SyntaxChange( newSyntax ) );
        m_syntax = newSyntax;
    }

    if ( m_sourceCharSet.isEmpty() )
    {
        m_sourceCharSet = QString::fromLatin1( "marc-8" );
    }

    const size_t realLimit = QMIN( numResults, m_limit );

    for ( size_t i = m_start; i < realLimit && !m_aborted; ++i )
    {
        kdDebug() << "Z3950Connection::run() - grabbing index " << i << endl;
        ZOOM_record rec = ZOOM_resultset_record( resultSet, i );
        if ( !rec )
        {
            kdDebug() << "Z3950Connection::run() - no record returned for index " << i << endl;
            continue;
        }
        int len;
        QString data;
        if ( m_syntax == Latin1Literal( "mods" ) )
        {
            data = toString( ZOOM_record_get( rec, "xml", &len ) );
        }
        else if ( m_syntax == Latin1Literal( "grs-1" ) )   // grs-1
        {
            // we're going to parse the rendered data, very ugly...
            data = toString( ZOOM_record_get( rec, "render", &len ) );
        }
        else
        {
#if 0
            kdWarning() << "Remove debug from z3950connection.cpp" << endl;
            {
                QFile f1( QString::fromLatin1( "/tmp/z3950.raw" ) );
                if ( f1.open( IO_WriteOnly ) )
                {
                    QDataStream t( &f1 );
                    t << ZOOM_record_get( rec, "raw", &len );
                }
                f1.close();
            }
#endif
            data = toXML( ZOOM_record_get( rec, "raw", &len ), m_sourceCharSet );
        }
        Z3950ResultFound* ev = new Z3950ResultFound( data );
        QApplication::postEvent( m_fetcher, ev );
    }

    ZOOM_resultset_destroy( resultSet );
    ZOOM_query_destroy( query );

    m_hasMore = m_limit < numResults;
    if ( m_hasMore )
    {
        m_start = m_limit;
        m_limit += Z3950_DEFAULT_MAX_RECORDS;
    }
#endif
    done();
}

bool Z3950Connection::makeConnection()
{
    if ( m_connected )
    {
        return true;
    }
//  kdDebug() << "Z3950Connection::makeConnection() - " << m_fetcher->source() << endl;
// I don't know what to do except assume database, user, and password are in locale encoding
#ifdef HAVE_YAZ
    d->conn_opt = ZOOM_options_create();
    ZOOM_options_set( d->conn_opt, "implementationName", "KBibTeX" );
    ZOOM_options_set( d->conn_opt, "databaseName",       toCString( m_dbname ) );
    ZOOM_options_set( d->conn_opt, "user",               toCString( m_user ) );
    ZOOM_options_set( d->conn_opt, "password",           toCString( m_password ) );

    d->conn = ZOOM_connection_create( d->conn_opt );
    ZOOM_connection_connect( d->conn, m_host.latin1(), m_port );

    int errcode;
    const char* errmsg; // unused: carries same info as 'errcode'
    const char* addinfo;
    errcode = ZOOM_connection_error( d->conn, &errmsg, &addinfo );
    if ( errcode != 0 )
    {
        ZOOM_options_destroy( d->conn_opt );
        ZOOM_connection_destroy( d->conn );
        m_connected = false;

        QString s = i18n( "Connection error %1: %2" ).arg( errcode ).arg( toString( errmsg ) );
        if ( !QCString( addinfo ).isEmpty() )
        {
            s += " (" + toString( addinfo ) + ")";
        }
        kdDebug() << "Z3950Connection::makeConnection() - " << s << endl;
        done( s, MessageHandler::Error );
        return false;
    }
#endif
    m_connected = true;
    return true;
}

void Z3950Connection::done()
{
    checkPendingEvents();
    qApp->postEvent( m_fetcher, new Z3950ConnectionDone( m_hasMore ) );
}

void Z3950Connection::done( const QString& msg_, int type_ )
{
    checkPendingEvents();
    if ( m_aborted )
    {
        qApp->postEvent( m_fetcher, new Z3950ConnectionDone( m_hasMore ) );
    }
    else
    {
        qApp->postEvent( m_fetcher, new Z3950ConnectionDone( m_hasMore, msg_, type_ ) );
    }
}

void Z3950Connection::checkPendingEvents()
{
    // if there's still some pending result events, go ahead and just wait 1 second
    if ( resultsLeft > 0 )
    {
        sleep( 1 );
    }
}

inline
QCString Z3950Connection::toCString( const QString& text_ )
{
    return iconvRun( text_.utf8(), QString::fromLatin1( "utf-8" ), m_sourceCharSet );
}

inline
QString Z3950Connection::toString( const QCString& text_ )
{
    return QString::fromUtf8( iconvRun( text_, m_sourceCharSet, QString::fromLatin1( "utf-8" ) ) );
}

// static
QCString Z3950Connection::iconvRun( const QCString& text_, const QString& fromCharSet_, const QString& toCharSet_ )
{
#ifdef HAVE_YAZ
    if ( text_.isEmpty() )
    {
        return text_;
    }

    if ( fromCharSet_ == toCharSet_ )
    {
        return text_;
    }

    yaz_iconv_t cd = yaz_iconv_open( toCharSet_.latin1(), fromCharSet_.latin1() );
    if ( !cd )
    {
        // maybe it's iso 5426, which we sorta support
        QString charSetLower = fromCharSet_.lower();
        charSetLower.remove( '-' ).remove( ' ' );
        if ( charSetLower == Latin1Literal( "iso5426" ) )
        {
            return iconvRun( Iso5426Converter::toUtf8( text_ ).utf8(), QString::fromLatin1( "utf-8" ), toCharSet_ );
        }
        else if ( charSetLower == Latin1Literal( "iso6937" ) )
        {
            return iconvRun( Iso6937Converter::toUtf8( text_ ).utf8(), QString::fromLatin1( "utf-8" ), toCharSet_ );
        }
        kdWarning() << "Z3950Connection::iconvRun() - conversion from " << fromCharSet_
        << " to " << toCharSet_ << " is unsupported" << endl;
        return text_;
    }

    const char* input = text_;
    size_t inlen = text_.length();

    size_t outlen = 2 * inlen;  // this is enough, right?
    QMemArray<char> result0( outlen );
    char* result = result0.data();

    int r = yaz_iconv( cd, const_cast<char**>( &input ), &inlen, &result, &outlen );
    if ( r <= 0 )
    {
        kdDebug() << "Z3950Connection::iconvRun() - can't decode buffer" << endl;
        return text_;
    }
    // bug in yaz, need to flush buffer to catch last character
    yaz_iconv( cd, 0, 0, &result, &outlen );

    // length is pointer difference
    size_t len = result - result0;

    QCString output = QCString( result0, len + 1 );
//  kdDebug() << "-------------------------------------------" << endl;
//  kdDebug() << output << endl;
//  kdDebug() << "-------------------------------------------" << endl;
    yaz_iconv_close( cd );
    return output;
#endif
    return text_;
}

QString Z3950Connection::toXML( const QCString& marc_, const QString& charSet_ )
{
#ifdef HAVE_YAZ
    if ( marc_.isEmpty() )
    {
        kdDebug() << "Z3950Connection::toXML() - empty string" << endl;
        return QString::null;
    }

    yaz_iconv_t cd = yaz_iconv_open( "utf-8", charSet_.latin1() );
    if ( !cd )
    {
        // maybe it's iso 5426, which we sorta support
        QString charSetLower = charSet_.lower();
        charSetLower.remove( '-' ).remove( ' ' );
        if ( charSetLower == Latin1Literal( "iso5426" ) )
        {
            return toXML( Iso5426Converter::toUtf8( marc_ ).utf8(), QString::fromLatin1( "utf-8" ) );
        }
        else if ( charSetLower == Latin1Literal( "iso6937" ) )
        {
            return toXML( Iso6937Converter::toUtf8( marc_ ).utf8(), QString::fromLatin1( "utf-8" ) );
        }
        kdWarning() << "Z3950Connection::toXML() - conversion from " << charSet_ << " is unsupported" << endl;
        return QString::null;
    }

    yaz_marc_t mt = yaz_marc_create();
    yaz_marc_iconv( mt, cd );
    yaz_marc_xml( mt, YAZ_MARC_MARCXML );

    // first 5 bytes are length
    bool ok;
#if YAZ_VERSIONL < 0x030000
    int len = marc_.left( 5 ).toInt( &ok );
#else
    size_t len = marc_.left( 5 ).toInt( &ok );
#endif
    if ( ok && ( len < 25 || len > 100000 ) )
    {
        kdDebug() << "Z3950Connection::toXML() - bad length: " << ( ok ? len : -1 ) << endl;
        return QString::null;
    }

#if YAZ_VERSIONL < 0x030000
    char* result;
#else
    const char* result;
#endif
    int r = yaz_marc_decode_buf( mt, marc_, -1, &result, &len );
    if ( r <= 0 )
    {
        kdDebug() << "Z3950Connection::toXML() - can't decode buffer" << endl;
        return QString::null;
    }

    QString output = QString::fromLatin1( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" );
    output += QString::fromUtf8( QCString( result, len + 1 ), len + 1 );
//  kdDebug() << QCString(result) << endl;
//  kdDebug() << "-------------------------------------------" << endl;
//  kdDebug() << output << endl;
    yaz_iconv_close( cd );
    yaz_marc_destroy( mt );

    return output;
#else // no yaz
    return QString::null;
#endif
}