2 * This file Copyright (C) Mnemosyne LLC
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2
6 * as published by the Free Software Foundation.
8 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10 * $Id: watchdir.cc 14150 2013-07-27 21:58:14Z jordan $
16 #include <QFileSystemWatcher>
19 #include <libtransmission/transmission.h>
22 #include "torrent-model.h"
29 WatchDir :: WatchDir( const TorrentModel
& model
):
35 WatchDir :: ~WatchDir( )
44 WatchDir :: metainfoTest( const QString
& filename
) const
48 tr_ctor
* ctor
= tr_ctorNew( 0 );
51 tr_ctorSetMetainfoFromFile( ctor
, filename
.toUtf8().constData() );
52 const int err
= tr_torrentParse( ctor
, &inf
);
55 else if( myModel
.hasTorrent( QString::fromUtf8( inf
.hashString
) ) )
62 tr_metainfoFree( &inf
);
68 WatchDir :: onTimeout( )
70 QTimer
* t
= qobject_cast
<QTimer
*>(sender());
71 const QString filename
= t
->objectName( );
72 if( metainfoTest( filename
) == OK
)
73 emit
torrentFileAdded( filename
);
78 WatchDir :: setPath( const QString
& path
, bool isEnabled
)
80 // clear out any remnants of the previous watcher, if any
81 myWatchDirFiles
.clear( );
87 // maybe create a new watcher
89 myWatcher
= new QFileSystemWatcher( );
90 myWatcher
->addPath( path
);
91 connect( myWatcher
, SIGNAL(directoryChanged(const QString
&)), this, SLOT(watcherActivated(const QString
&)));
92 //std::cerr << "watching " << qPrintable(path) << " for new .torrent files" << std::endl;
93 watcherActivated( path
); // trigger the watchdir for .torrent files in there already
98 WatchDir :: watcherActivated( const QString
& path
)
100 const QDir
dir(path
);
102 // get the list of files currently in the watch directory
104 foreach( QString str
, dir
.entryList( QDir::Readable
|QDir::Files
) )
107 // try to add any new files which end in .torrent
108 const QSet
<QString
> newFiles( files
- myWatchDirFiles
);
109 const QString torrentSuffix
= QString::fromUtf8( ".torrent" );
110 foreach( QString name
, newFiles
) {
111 if( name
.endsWith( torrentSuffix
, Qt::CaseInsensitive
) ) {
112 const QString filename
= dir
.absoluteFilePath( name
);
113 switch( metainfoTest( filename
) ) {
115 emit
torrentFileAdded( filename
);
120 // give the .torrent a few seconds to finish downloading
121 QTimer
* t
= new QTimer( this );
122 t
->setObjectName( dir
.absoluteFilePath( name
) );
123 t
->setSingleShot( true );
124 connect( t
, SIGNAL(timeout()), this, SLOT(onTimeout()));
131 // update our file list so that we can use it
132 // for comparison the next time around
133 myWatchDirFiles
= files
;