File indexing completed on 2024-04-14 04:49:14

0001 /*
0002     SPDX-FileCopyrightText: 2004 Richard Lärkäng <nouseforaname@home.se>
0003 
0004     SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "sites.h"
0008 
0009 #include <KIO/TransferJob>
0010 #include <QDebug>
0011 #include <QRegExp>
0012 #include <QTextStream>
0013 #include <QUrl>
0014 #include <QUrlQuery>
0015 
0016 namespace KCDDB
0017 {
0018   Sites::Sites()
0019   {
0020 
0021   }
0022 
0023     QList<Mirror>
0024   Sites::siteList()
0025   {
0026     QUrl url;
0027     url.setScheme( QLatin1String( "http" ) );
0028     url.setHost( QLatin1String( "gnudb.gnudb.org" ) );
0029     url.setPort( 80 );
0030     url.setPath( QLatin1String( "/~cddb/cddb.cgi" ) );
0031 
0032     QString hello = QString::fromLatin1("%1 %2 %3 %4")
0033         .arg(QLatin1String( "libkcddb-user" ), QLatin1String( "localHost" ), CDDB::clientName(), CDDB::clientVersion());
0034 
0035     QUrlQuery query;
0036     query.addQueryItem( QLatin1String( "cmd" ), QLatin1String( "sites" ) );
0037     query.addQueryItem( QLatin1String( "hello" ), hello );
0038     query.addQueryItem( QLatin1String( "proto" ), QLatin1String( "5" ) );
0039     url.setQuery( query );
0040 
0041     QList<Mirror> result;
0042 
0043     KIO::TransferJob* job = KIO::get( url, KIO::NoReload, KIO::HideProgressInfo );
0044     QByteArray data;
0045     QObject::connect( job, &KIO::TransferJob::data, [&data](KIO::Job *, const QByteArray &d){ data += d; } );
0046     if( job->exec() )
0047     {
0048       result = readData( data );
0049     }
0050 
0051     return result;
0052   }
0053 
0054     QList<Mirror>
0055   Sites::readData(const QByteArray& data)
0056   {
0057     QList<Mirror> result;
0058 
0059     QTextStream ts(data);
0060 
0061     if (CDDB::statusCode(ts.readLine()) != 210)
0062       return result;
0063 
0064     while (!ts.atEnd())
0065     {
0066       QString line = ts.readLine();
0067       if (line == QLatin1String( "." ))
0068         break;
0069       result << parseLine(line);
0070     }
0071 
0072     return result;
0073   }
0074 
0075     Mirror
0076   Sites::parseLine(const QString& line)
0077   {
0078     Mirror m;
0079 
0080     QRegExp rexp(QLatin1String( "([^ ]+) (cddbp|http) (\\d+) ([^ ]+) [N|S]\\d{3}.\\d{2} [E|W]\\d{3}.\\d{2} (.*)" ));
0081 
0082     if (rexp.indexIn(line) != -1)
0083     {
0084       m.address = rexp.cap(1);
0085 
0086       if (rexp.cap(2) == QLatin1String( "cddbp" ))
0087         m.transport = Lookup::CDDBP;
0088       else
0089         m.transport = Lookup::HTTP;
0090 
0091       m.port = rexp.cap(3).toUInt();
0092 
0093       if (m.transport == Lookup::HTTP && rexp.cap(4) != QLatin1String( "/~cddb/cddb.cgi" ))
0094         qWarning() << "Non default urls are not supported for http";
0095 
0096       m.description = rexp.cap(5);
0097     }
0098 
0099     return m;
0100   }
0101 }