summaryrefslogtreecommitdiffstats
path: root/tdeabc/plugins/file/resourcefile.cpp
blob: b29cf33c3c184a66a65b0da35b3f3dccc3019533 (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
/*
    This file is part of libkabc.

    Copyright (c) 2001,2003 Cornelius Schumacher <schumacher@kde.org>
    Copyright (c) 2006 Tom Abers <tomalbers@kde.nl>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

#include <tqfile.h>
#include <tqfileinfo.h>
#include <tqtimer.h>

#include <tdeapplication.h>
#include <tdeconfig.h>
#include <kdebug.h>
#include <tdeio/scheduler.h>
#include <tdelocale.h>
#include <ksavefile.h>
#include <kstandarddirs.h>

#include "formatfactory.h"
#include "resourcefileconfig.h"
#include "stdaddressbook.h"
#include "lock.h"

#include "resourcefile.h"

using namespace KABC;

ResourceFile::ResourceFile( const TDEConfig *config )
  : Resource( config ), mFormat( 0 ),
    mAsynchronous( false )
{
  TQString fileName, formatName;

  if ( config ) {
    fileName = config->readPathEntry( "FileName", StdAddressBook::fileName() );
    formatName = config->readEntry( "FileFormat", "vcard" );
  } else {
    fileName = StdAddressBook::fileName();
    formatName = "vcard";
  }

  init( fileName, formatName );
}

ResourceFile::ResourceFile( const TQString &fileName,
                            const TQString &formatName )
  : Resource( 0 ), mFormat( 0 ),
    mAsynchronous( false )
{
  init( fileName, formatName );
}

void ResourceFile::init( const TQString &fileName, const TQString &formatName )
{
  mFormatName = formatName;

  FormatFactory *factory = FormatFactory::self();
  mFormat = factory->format( mFormatName );

  if ( !mFormat ) {
    mFormatName = "vcard";
    mFormat = factory->format( mFormatName );
  }

  connect( &mDirWatch, TQT_SIGNAL( dirty(const TQString&) ), TQT_SLOT( fileChanged() ) );
  connect( &mDirWatch, TQT_SIGNAL( created(const TQString&) ), TQT_SLOT( fileChanged() ) );
  connect( &mDirWatch, TQT_SIGNAL( deleted(const TQString&) ), TQT_SLOT( fileChanged() ) );

  setFileName( fileName );

  mLock = 0;
}

ResourceFile::~ResourceFile()
{
  delete mFormat;
  mFormat = 0;
}

void ResourceFile::writeConfig( TDEConfig *config )
{
  Resource::writeConfig( config );

  if ( mFileName == StdAddressBook::fileName() )
    config->deleteEntry( "FileName" );
  else
    config->writePathEntry( "FileName", mFileName );

  config->writeEntry( "FileFormat", mFormatName );
}

Ticket *ResourceFile::requestSaveTicket()
{
  kdDebug(5700) << "ResourceFile::requestSaveTicket()" << endl;

  if ( !addressBook() ) return 0;

  delete mLock;
  mLock = new Lock( mFileName );

  if ( mLock->lock() ) {
    addressBook()->emitAddressBookLocked();
  } else {
    addressBook()->error( mLock->error() );
    kdDebug(5700) << "ResourceFile::requestSaveTicket(): Unable to lock file '"
                  << mFileName << "': " << mLock->error() << endl;
    return 0;
  }

  return createTicket( this );
}

void ResourceFile::releaseSaveTicket( Ticket *ticket )
{
  delete ticket;

  delete mLock;
  mLock = 0;

  addressBook()->emitAddressBookUnlocked();
}

bool ResourceFile::doOpen()
{
  TQFile file( mFileName );

  if ( !file.exists() ) {
    // try to create the file
    bool ok = file.open( IO_WriteOnly );
    if ( ok )
      file.close();

    return ok;
  } else {
    TQFileInfo fileInfo( mFileName );
    if ( readOnly() || !fileInfo.isWritable() ) {
      if ( !file.open( IO_ReadOnly ) )
        return false;
    } else {
      if ( !file.open( IO_ReadWrite ) )
        return false;
    }

    if ( file.size() == 0 ) {
      file.close();
      kdDebug() << "File size is zero. Evaluating backups" << endl;
      for (int i=0; i!=20; i++)
      {
        TQFile backup( mFileName + "__" + TQString::number(i) );
        kdDebug() << "Evaluating" << backup.name() << " size: " << backup.size() << endl;
        if ( backup.size() != 0 )
        {
          kdDebug() << "Restoring backup " << i << endl;
          const TQString src = mFileName + "__" + TQString::number(i);
          const TQString dest = mFileName;

          // remove dest
          TQFile::remove( dest );

          // copy src to dest
          if ( backup.open( IO_ReadOnly ) ) {
            const TQByteArray data = backup.readAll();

            TQFile out( dest );
            if ( out.open( IO_WriteOnly ) ) {
              out.writeBlock( data );
              out.close();
            }

            backup.close();
          }
          return true; 
        }
      }
      return true;
    }

    bool ok = mFormat->checkFormat( &file );
    file.close();

    return ok;
  }
}

void ResourceFile::doClose()
{
}

bool ResourceFile::load()
{
  kdDebug(5700) << "ResourceFile::load(): '" << mFileName << "'" << endl;

  mAsynchronous = false;

  TQFile file( mFileName );
  if ( !file.open( IO_ReadOnly ) ) {
    addressBook()->error( i18n( "Unable to open file '%1'." ).arg( mFileName ) );
    return false;
  }

  clear();

  return mFormat->loadAll( addressBook(), this, &file );
}

bool ResourceFile::asyncLoad()
{
  kdDebug(5700) << "ResourceFile::asyncLoad()" << endl;

  mAsynchronous = true;

  bool ok = load();

  if ( !ok )
    emitLoadingError();
  else
    emitLoadingFinished();

  return true;
}

bool ResourceFile::save( Ticket * )
{
  kdDebug(5700) << "ResourceFile::save()" << endl;

  // Only do the logrotate dance when the __0 file is not 0 bytes.
  TQFile file( mFileName + "__0" );
  if ( file.size() != 0 ) {
    const TQString last = mFileName + "__20";
    kdDebug() << "deleting " << last << endl;

    TQFile::remove( last );

    for (int i=19; i>=0; i--)
    {
      const TQString src = mFileName + "__" + TQString::number(i);
      const TQString dest = mFileName + "__" + TQString::number(i+1);
      kdDebug() << "moving " << src << " -> " << dest << endl;

      // copy src to dest
      TQFile in( src );
      if ( in.open( IO_ReadOnly ) ) {
        const TQByteArray data = in.readAll();

        TQFile out( dest );
        if ( out.open( IO_WriteOnly ) ) {
          out.writeBlock( data );
          out.close();
        }

        in.close();
      }

      // remove src
      TQFile::remove( src );
    }
  } else
    kdDebug() << "Not starting logrotate __0 is 0 bytes." << endl;

  TQString extension = "__0";
  (void) KSaveFile::backupFile( mFileName, TQString::null /*directory*/,
                                extension );

  mDirWatch.stopScan();

  KSaveFile saveFile( mFileName );
  bool ok = false;

  if ( saveFile.status() == 0 && saveFile.file() ) {
    mFormat->saveAll( addressBook(), this, saveFile.file() );
    ok = saveFile.close();
  }

  if ( !ok ) {
    saveFile.abort();
    addressBook()->error( i18n( "Unable to save file '%1'." ).arg( mFileName ) );
  }

  mDirWatch.startScan();

  return ok;
}

bool ResourceFile::asyncSave( Ticket *ticket )
{
  kdDebug(5700) << "ResourceFile::asyncSave()" << endl;

  bool ok = save( ticket );

  if ( !ok )
    TQTimer::singleShot( 0, this, TQT_SLOT( emitSavingError() ) );
  else
    TQTimer::singleShot( 0, this, TQT_SLOT( emitSavingFinished() ) );

  return ok;
}

void ResourceFile::setFileName( const TQString &fileName )
{
  mDirWatch.stopScan();
  if ( mDirWatch.contains( mFileName ) )
    mDirWatch.removeFile( mFileName );

  mFileName = fileName;

  mDirWatch.addFile( mFileName );
  mDirWatch.startScan();
}

TQString ResourceFile::fileName() const
{
  return mFileName;
}

void ResourceFile::setFormat( const TQString &format )
{
  mFormatName = format;
  delete mFormat;

  FormatFactory *factory = FormatFactory::self();
  mFormat = factory->format( mFormatName );
}

TQString ResourceFile::format() const
{
  return mFormatName;
}

void ResourceFile::fileChanged()
{
    kdDebug(5700) << "ResourceFile::fileChanged(): " << mFileName << endl;

  if ( !addressBook() )
    return;

  if ( mAsynchronous )
    asyncLoad();
  else {
    load();
    kdDebug() << "addressBookChanged() " << endl;
    addressBook()->emitAddressBookChanged();
  }
}

void ResourceFile::removeAddressee( const Addressee &addr )
{
  TQFile::remove( TQFile::encodeName( locateLocal( "data", "tdeabc/photos/" ) + addr.uid() ) );
  TQFile::remove( TQFile::encodeName( locateLocal( "data", "tdeabc/logos/" ) + addr.uid() ) );
  TQFile::remove( TQFile::encodeName( locateLocal( "data", "tdeabc/sounds/" ) + addr.uid() ) );

  mAddrMap.erase( addr.uid() );
}

void ResourceFile::emitSavingFinished()
{
  emit savingFinished( this );
}

void ResourceFile::emitSavingError()
{
  emit savingError( this, i18n( "Unable to save file '%1'." ).arg( mFileName ) );
}

void ResourceFile::emitLoadingFinished()
{
  emit loadingFinished( this );
}

void ResourceFile::emitLoadingError()
{
  emit loadingError( this, i18n( "Problems during parsing file '%1'." ).arg( mFileName ) );
}

#include "resourcefile.moc"