summaryrefslogtreecommitdiffstats
path: root/kopete/plugins/addbookmarks/addbookmarksplugin.cpp
blob: 65e808f4b6f68fbdbbc1d934f31a2fc976707248 (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
//
// C++ Implementation: %{MODULE}
//
// Description:
//
//
// Author: Roie Kerstein <sf_kersteinroie@bezeqint.net>, (C) 2004
//
// Copyright: See COPYING file that comes with this distribution
//
//

#include <kdebug.h>
#include <kbookmark.h>
#include <tqvariant.h>
#include <tqtextcodec.h>
#include <tqregexp.h>

#include "addbookmarksplugin.moc"
#include "addbookmarksplugin.h"
#include "kopetecontact.h"
#include "kopetechatsessionmanager.h"
#include "kopeteglobal.h"
#include "kopetemetacontact.h"


K_EXPORT_COMPONENT_FACTORY( kopete_addbookmarks, BookmarksPluginFactory( "kopete_addbookmarks" )  )


static bool isURLInGroup(const KURL& url, const KBookmarkGroup& group)
{
	KBookmark bookmark = group.first();
	
	for( ; !bookmark.isNull() ; bookmark = group.next(bookmark) ){
		if( !bookmark.isGroup() && !bookmark.isSeparator() )
			if( url == bookmark.url() )
				return true;
	}
	return false;
}

BookmarksPlugin::BookmarksPlugin(TQObject *parent, const char *name, const TQStringList &/*args*/)
 : Kopete::Plugin(BookmarksPluginFactory::instance(), parent, name)
{
	//kdDebug(14501) << "plugin loading" << endl;
	connect( Kopete::ChatSessionManager::self(), TQT_SIGNAL( aboutToDisplay( Kopete::Message & ) ), this, TQT_SLOT( slotBookmarkURLsInMessage( Kopete::Message & ) ) );
}

/*!
    \fn BookmarksPlugin::slotBookmarkURLsInMessage(KopeteMessage & msg)
 */
void BookmarksPlugin::slotBookmarkURLsInMessage(Kopete::Message & msg)
{
	//kdDebug(14501) << "recieved message:" << endl << msg.parsedBody() << endl;
	if(msg.direction() != Kopete::Message::Inbound)
		return;
	KURL::List *URLsList;
	KURL::List::iterator it;
	URLsList = extractURLsFromString( msg.parsedBody() );
	if (!URLsList->empty()) {
		for( it = URLsList->begin() ; it != URLsList->end() ; ++it){
			if ( m_settings.addBookmarksFromUnknownContacts() || !msg.from()->metaContact()->isTemporary() )
			{
				if ( msg.from()->metaContact() ) {
					addKopeteBookmark(*it, msg.from()->metaContact()->displayName() );
					//kdDebug (14501) << "name:" << msg.from()->metaContact()->displayName() << endl;
				}
				else {
					addKopeteBookmark(*it, msg.from()->property(Kopete::Global::Properties::self()->nickName()).value().toString() );
					//kdDebug (14501) << "name:" << msg.from()->property(Kopete::Global::Properties::self()->nickName()).value().toString() << endl;
				}
			}
		}
	}
	delete URLsList;
}

void BookmarksPlugin::slotAddKopeteBookmark( KIO::Job *transfer, const TQByteArray &data )
{
	TQTextCodec *codec = getPageEncoding( data );
	TQString htmlpage = codec->toUnicode( data );
	TQRegExp rx("<title>([^<]*){1,96}</title>");
	rx.setCaseSensitive(false);
	int pos = rx.search( htmlpage );
	KBookmarkManager *mgr = KBookmarkManager::userBookmarksManager();
	KBookmarkGroup group = getKopeteFolder();
	TQString sender = m_map[(KIO::TransferJob*)transfer].sender;
	
	if ( m_settings.useSubfolderForContact( sender ) )
		group = getFolder( group, sender );

	if( pos == -1 ){
		group.addBookmark( mgr, m_map[(KIO::TransferJob*)transfer].url.prettyURL(), m_map[(KIO::TransferJob*)transfer].url.url() );
		kdDebug( 14501 ) << "failed to extract title from first data chunk" << endl;
	}else {
		group.addBookmark( mgr, rx.cap( 1 ).simplifyWhiteSpace(),
						   m_map[(KIO::TransferJob*)transfer].url.url() );
	}
	mgr->save();
	mgr->emitChanged( group );
	m_map.remove( (KIO::TransferJob*)transfer );
	transfer->kill();
}

KURL::List* BookmarksPlugin::extractURLsFromString( const TQString& text )
{
	KURL::List *list = new KURL::List;
	TQRegExp rx("<a href=\"[^\\s\"]+\"");
	int pos=0;
	KURL url;
	
	for(; (pos=rx.search(text, pos))!=-1; pos+=rx.matchedLength()){
	 //as long as there is a matching URL in text
		url = text.mid(pos+9, rx.matchedLength()-10);
		// assuming that in formatted messages links appear as <a href="link"
		if(url.isValid())
			list->append(url);
	}
	return list;
}

void BookmarksPlugin::addKopeteBookmark( const KURL& url, const TQString& sender )
{
	KBookmarkGroup group = getKopeteFolder();

	if ( m_settings.useSubfolderForContact( sender ) ) {
		group = getFolder( group, sender );
	}
	// either restrict to http(s) or to KProtocolInfo::protocolClass() == :internet
	if( !isURLInGroup( url, group )
		&& url.isValid() && url.protocol().startsWith("http") ) {
		KIO::TransferJob *transfer;
		// make asynchronous transfer to avoid GUI freezing due to overloaded web servers
		transfer = KIO::get(url, false, false);
		transfer->setInteractive(false);
		connect ( transfer, TQT_SIGNAL ( data( KIO::Job *, const TQByteArray & ) ),
		this, TQT_SLOT ( slotAddKopeteBookmark( KIO::Job *, const TQByteArray & ) ) );
		m_map[transfer].url = url;
		m_map[transfer].sender = sender;
	}
}

KBookmarkGroup BookmarksPlugin::getKopeteFolder()
{
	KBookmarkManager *mgr = KBookmarkManager::userBookmarksManager();

	return getFolder( mgr->root(), TQString::tqfromLatin1("kopete") );
}

KBookmarkGroup BookmarksPlugin::getFolder( KBookmarkGroup group, const TQString& folder )
{
	KBookmark bookmark;


	for( bookmark=group.first(); !bookmark.isNull() && !(bookmark.isGroup() && !bookmark.fullText().compare( folder )); bookmark = group.next(bookmark));
	if( bookmark.isNull() ){
		KBookmarkManager *mgr = KBookmarkManager::userBookmarksManager();
		//kdDebug (14501) << "GetFolder:" << folder << endl;
		group = group.createNewFolder( mgr, folder, true);
	}else {
		group = bookmark.toGroup();
	}
	return group;
}

TQTextCodec* BookmarksPlugin::getPageEncoding( const TQByteArray& data )
{
	TQString temp = TQString::tqfromLatin1(data);
	TQRegExp rx("<meta[^>]*(charset|CHARSET)\\s*=\\s*[^>]*>");
	int pos = rx.search( temp );
	TQTextCodec *codec;
	
	if( pos == -1 ){
		kdDebug( 14501 ) << "charset not found in first data chunk" << endl;
		return TQTextCodec::codecForName("iso8859-1");
	}
	//kdDebug(14501) << temp.mid(pos, rx.matchedLength()) << endl;
	temp = temp.mid(pos, rx.matchedLength()-1);
	temp = temp.mid( temp.find("charset", 0, false)+7);
	temp = temp.remove('=').simplifyWhiteSpace();
	for( pos = 0 ; temp[pos].isLetterOrNumber() || temp[pos] == '-' ; pos++ );
	temp = temp.left( pos );
	//kdDebug(14501) << "encoding: " << temp << endl;
	codec = TQTextCodec::codecForName( temp.latin1() );
	if( !codec ){
		return TQTextCodec::codecForName("iso8859-1");
	}
	return codec;
}

void BookmarksPlugin::slotReloadSettings()
{
	m_settings.load();
}