summaryrefslogtreecommitdiffstats
path: root/src/stationlist.cpp
blob: 6dc86437225300a927c5c66f39882d8e0c9930da (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
/***************************************************************************
                          stationlist.cpp  -  description
                             -------------------
    begin                : Sat March 29 2003
    copyright            : (C) 2003 by Klas Kalass, Ernst Martin Witte
    email                : klas@kde.org, witte@kawo1.rwth-aachen.de
 ***************************************************************************/

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

#include "include/radiostation.h"
#include "include/errorlog-interfaces.h"
#include "include/utils.h"
#include "include/stationlist.h"
#include "include/stationlistxmlhandler.h"
#include "include/tderadioversion.h"

#include <tqstring.h>
#include <tqfile.h>
#include <tqiodevice.h>
#include <tqmessagebox.h>
#include <tdeio/netaccess.h>
#include <tdetempfile.h>
#include <tdelocale.h>

//////////////////////////////////////////////////////////////////////////////

const KDE_EXPORT StationList emptyStationList;

//////////////////////////////////////////////////////////////////////////////

RawStationList::RawStationList ()
{
    setAutoDelete(true);
}


RawStationList::RawStationList (const RawStationList &sl)
    : TQPtrList<RadioStation>(sl)
{
    setAutoDelete(true);
}


RawStationList::~RawStationList ()
{
    clear();
}


TQPtrCollection::Item RawStationList::newItem (TQPtrCollection::Item s)
{
    if (s)
        return ((RadioStation*)s)->copy();
    else
        return NULL;
}


void  RawStationList::deleteItem (TQPtrCollection::Item s)
{
    if (autoDelete())
        delete (RadioStation*)s;
}


int RawStationList::compareItems(TQPtrCollection::Item a, TQPtrCollection::Item b)
{
    if (!a && !b)
        return 0;

    if (!a)
        return -1;

    if (!b)
        return 1;

    return ((RadioStation*)a)->compare(*(RadioStation*)b);
}


bool RawStationList::insert (uint index, const RadioStation * item )
{
    if (!item) return false;
    RadioStation *rs = &stationWithID(item->stationID());
    bool r = true;
    if (rs != item) {
        r = BaseClass::insert(index, item);
        removeRef(rs);
    }
    return r;
}


bool RawStationList::insert (const RadioStation * item )
{
    if (!item) return false;
    int idx = idxWithID(item->stationID());
    if (idx >= 0) {
        return replace(idx, item);
    } else {
        append(item);
        return true;
    }
}


void RawStationList::inSort ( const RadioStation * item )
{
    if (!item) return;
    RadioStation *rs = &stationWithID(item->stationID());
    if (rs != item) {
        removeRef(rs);
    }
    BaseClass::inSort(item);
}


void RawStationList::prepend ( const RadioStation * item )
{
    if (!item) return;
    RadioStation *rs = &stationWithID(item->stationID());
    if (rs != item) {
        removeRef(rs);
    }
    BaseClass::prepend(item);
}


void RawStationList::append ( const RadioStation * item )
{
    if (!item) return;
    RadioStation *rs = &stationWithID(item->stationID());
    if (rs != item) {
        removeRef(rs);
    }
    BaseClass::append(item);
}


bool RawStationList::replace ( uint index, const RadioStation * item )
{
    bool r = true;
    RadioStation *rs = &stationWithID(item->stationID());
    r = BaseClass::replace(index, item);
    if (rs != item) {
        BaseClass::removeRef(rs);
    }
    return r;
}


const RadioStation &RawStationList::stationWithID(const TQString &sid) const
{
    Iterator it(*this);
    for (; const RadioStation *s = it.current(); ++it) {
        if (s->stationID() == sid)
            return *s;
    }
    return (RadioStation &) undefinedRadioStation;
}


RadioStation &RawStationList::stationWithID(const TQString &sid)
{
    Iterator it(*this);
    for (; RadioStation *s = it.current(); ++it) {
        if (s->stationID() == sid)
            return *s;
    }
    return (RadioStation &) undefinedRadioStation;
}



int RawStationList::idxWithID(const TQString &sid) const
{
    int i = 0;
    Iterator it(*this);
    for (; const RadioStation *s = it.current(); ++it, ++i) {
        if (s->stationID() == sid)
            return i;
    }
    return -1;
}


bool RawStationList::operator == (const RawStationList &l) const
{
    TQPtrListIterator<RadioStation> it1(*this);
    TQPtrListIterator<RadioStation> it2(l);
    if (count() != l.count())
        return false;
    for (; it1.current() && it2.current(); ++it1, ++it2) {
        if (**it1 != **it2)
            return false;
    }
    return true;
}


//////////////////////////////////////////////////////////////////////////////

StationList::StationList()
{
    m_all.setAutoDelete(true);
}

StationList::StationList(const StationList &sl)
    : m_all      (sl.m_all),
      m_metaData (sl.m_metaData)
{
    m_all.setAutoDelete(true);
}


StationList::~StationList()
{
}


void StationList::merge(const StationList & other)
{
    // merge meta information: honor merge in comment

    StationListMetaData const & metaData = other.metaData();

    if (! m_metaData.comment.isEmpty())
        m_metaData.comment += "\n";

    m_metaData.lastChange = TQDateTime::currentDateTime();

    if (!metaData.maintainer.isEmpty())
        m_metaData.maintainer += (count() ? TQString(" / ") : TQString()) + metaData.maintainer;

    if (!metaData.country.isEmpty())
        m_metaData.country += (count() ? TQString(" / ") : TQString()) + metaData.country;

    if (!metaData.city.isEmpty())
        m_metaData.city = (count()     ? TQString(" / ") : TQString()) + metaData.city;

    if (!metaData.media.isEmpty())
        m_metaData.media += (count()   ? TQString(" / ") : TQString()) + metaData.media;

    if (!metaData.comment.isEmpty())
        m_metaData.comment += (count() ? TQString(" / ") : TQString()) + metaData.comment;
    if (count() && other.count())
        m_metaData.comment += " " + i18n("Contains merged Data");


    // merge stations

    TQPtrListIterator<RadioStation> it(other.all());
    for (RadioStation *s = it.current(); s; s = ++it) {
        m_all.insert(s);
    }
}



StationList &StationList::operator = (const StationList &other)
{
    m_metaData = other.metaData();
    m_all      = other.all();
    return *this;
}


const RadioStation &StationList::at(int idx) const
{
    RawStationList::Iterator it(m_all);
    it += idx;
    return it.current() ? *it.current() : (const RadioStation &) undefinedRadioStation;
}


RadioStation &StationList::at(int idx)
{
    RawStationList::Iterator it(m_all);
    it += idx;
    return it.current() ? *it.current() : (RadioStation &) undefinedRadioStation;
}


const RadioStation &StationList::stationWithID(const TQString &sid) const
{
    return m_all.stationWithID(sid);
}


RadioStation &StationList::stationWithID(const TQString &sid)
{
    return m_all.stationWithID(sid);
}


bool StationList::readXML (const TQString &dat, const IErrorLogClient &logger, bool enableMessageBox)
{
    // FIXME: TODO: error handling
    TQXmlInputSource source;
    source.setData(dat);
    TQXmlSimpleReader      reader;
    StationListXmlHandler handler(logger);
    reader.setContentHandler (&handler);
    if (reader.parse(source)) {
        if (handler.wasCompatMode() && enableMessageBox) {
            TQMessageBox::information(NULL, "TDERadio",
                                     i18n("Probably an old station preset file was read.\n"
                                     "You have to rebuild your station selections for "
                                     "the quickbar and the docking menu.")
                                     );
        }

        m_all      = handler.getStations();
        m_metaData = handler.getMetaData();
        return true;
    } else {
        logger.logError("StationList::readXML: " + i18n("parsing failed"));

        if (enableMessageBox) {
            TQMessageBox::warning(NULL, "TDERadio",
                                 i18n("Parsing the station preset file failed.\n"
                                      "See console output for more details."));
        }
        return false;
    }
}


bool StationList::readXML (const KURL &url, const IErrorLogClient &logger, bool enableMessageBox)
{
    TQString tmpfile;
    if (!TDEIO::NetAccess::download(url, tmpfile, NULL)) {
        if (enableMessageBox) {
            logger.logError("StationList::readXML: " +
                            i18n("error downloading preset file %1").arg(url.url()));
            TQMessageBox::warning(NULL, "TDERadio",
                                 i18n("Download of the station preset file at %1 failed.")
                                 .arg(url.url()));
        } else {
            logger.logWarning("StationList::readXML: " +
                              i18n("error downloading preset file %1").arg(url.url()));
        }
        return false;
    }

    logger.logDebug("StationList::readXML: " +
             i18n("temporary file: ") + tmpfile);

    TQFile presetFile (tmpfile);

    if (! presetFile.open(IO_ReadOnly)) {
        logger.logError("StationList::readXML: " +
                 i18n("error opening preset file %1").arg(tmpfile));
        if (enableMessageBox) {
            TQMessageBox::warning(NULL, "TDERadio",
                                 i18n("Opening of the station preset file at %1 failed.")
                                 .arg(tmpfile));
        }
        return false;
    }

    TQString xmlData;

    // make sure that qtextstream is gone when we close presetFile
    TQString tmp;
    {
        TQTextStream ins(&presetFile);
        tmp = ins.read();
    }

    presetFile.reset();

    // preset file written with tderadio <= 0.2.x
    if (tmp.find("<format>") < 0) {
        logger.logInfo(i18n("Old Preset File Format detected"));
        TQTextStream ins(&presetFile);
        ins.setEncoding(TQTextStream::Locale);
        xmlData = ins.read();
    }
    // preset file written with tderadio >= 0.3.0
    else {
        TQXmlInputSource tmp(&presetFile);
        xmlData = tmp.data();
    }

    presetFile.close();

    TDEIO::NetAccess::removeTempFile(tmpfile);

    return readXML(xmlData, logger, enableMessageBox);
}


TQString StationList::writeXML (const IErrorLogClient &/*logger*/) const
{
    TQString data = TQString();

    // write station list

    TQString t   = "\t";
    TQString tt  = "\t\t";
    TQString ttt = "\t\t\t";

    data +=       xmlOpenTag(TDERadioConfigElement) +
            t   + xmlOpenTag(StationListElement) +
            tt  + xmlTag(StationListFormat, STATION_LIST_FORMAT) +
            tt  + xmlOpenTag(StationListInfo) +
            ttt + xmlTag(StationListInfoCreator,    "tderadio-" TDERADIO_VERSION) +
            ttt + xmlTag(StationListInfoMaintainer, m_metaData.maintainer) +
            ttt + xmlTag(StationListInfoChanged,    m_metaData.lastChange.toString(TQt::ISODate)) +
            ttt + xmlTag(StationListInfoCountry,    m_metaData.country) +
            ttt + xmlTag(StationListInfoCity,       m_metaData.city) +
            ttt + xmlTag(StationListInfoMedia,      m_metaData.media) +
            ttt + xmlTag(StationListInfoComments,   m_metaData.comment) +
            tt  + xmlCloseTag (StationListInfo);

    for (RawStationList::Iterator it(m_all); it.current(); ++it) {
        RadioStation *s = it.current();

        data += tt + xmlOpenTag (s->getClassName());

        TQStringList properties = s->getPropertyNames();
        TQStringList::iterator end = properties.end();
        for (TQStringList::iterator sit = properties.begin(); sit != end; ++sit) {
            data += ttt + xmlTag (*sit, s->getProperty(*sit));
        }
        data += tt + xmlCloseTag(s->getClassName());

    }

    data += t + xmlCloseTag(StationListElement) +
                xmlCloseTag(TDERadioConfigElement);

    return data;
}


bool StationList::writeXML (const KURL &url, const IErrorLogClient &logger, bool enableMessageBox) const
{
    KTempFile tmpFile;
    tmpFile.setAutoDelete(true);
    TQFile *outf = tmpFile.file();

    TQTextStream outs(outf);
    outs.setEncoding(TQTextStream::UnicodeUTF8);
    outs << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" << endl;

    TQString output = writeXML(logger);

    outs << output;
    if (outf->status() != IO_Ok) {
        logger.logError("StationList::writeXML: " +
                 i18n("error writing to tempfile %1").arg(tmpFile.name()));
        if (enableMessageBox) {
            TQMessageBox::warning(NULL, "TDERadio",
                                 i18n("Writing station preset file %1 failed.")
                                 .arg(tmpFile.name()));
        }
        return false;
    }

    // close hopefully flushes buffers ;)
    outf->close();

    if (count() <= 1) {
        logger.logWarning("StationList::writeXML: " +
                 i18n("uploading preset file %1: ").arg(url.url()));
        logger.logWarning("StationList::writeXML: " +
                 i18n("something strange happend, station list has only %1 entries. Writing station preset file skipped").arg(count()));
    } else {

        if (!TDEIO::NetAccess::upload(tmpFile.name(), url, NULL)) {
            logger.logError("StationList::writeXML: " +
                    i18n("error uploading preset file %1").arg(url.url()));

            if (enableMessageBox) {
                TQMessageBox::warning(NULL, "TDERadio",
                                    i18n("Upload of station preset file to %1 failed.")
                                    .arg(url.url()));
            }
            return false;
        }
    }

    return true;
}