first release
[groupsms] / sms / tpsession / tpsessionaccount.cpp
1 /*
2  * This file is part of TpSession
3  *
4  * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
5  * Contact Kate Alhola  kate.alholanokia.com
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21 #include "tpsessionaccount.h"
22 #include <TelepathyQt4/Message>
23
24 /**
25  * \class TpSessionAccount
26  * \headerfile <tpsessionaccount.h>
27  *
28  * TpSessionAccount class represents every account you have. As example account for “Ring” connection manager represents your cellular
29  * account and you may send and receive SMS with it. Gabble represents your GoogleTalk account if you have defined them.
30  * TpSessionAccounts are created by TpSession class,they are not intended to be created stand-alone
31
32  */
33 /**
34  * \fn void TpSessionAccount::accountReady(TpSessionAccount *);
35  *
36  * Emitted when the account becomes ready
37  *
38  * \param  TpSessionAccount  pointer to account become ready
39  */
40 /**
41  * \fn void TpSessionAccount::channelReady(TpSessionAccount *);
42  *
43  * Emitted when the account Manager becomes ready
44  *
45  * \param  TpSession  pointer to TpSession class
46  */
47 /**
48  * \fn void TpSessionAccount::messageReceived(const Tp::ReceivedMessage &,TpSessionAccount *);
49  *
50  * Emitted when any of Account Managers recived message
51  *
52  * \param  Tp::ReceivedMessage  Message received
53  * \param  TpSessionAccount  pointer to account received message
54  */
55
56 /**
57  * \fn void TpSessionAccount::newChannel(TpSessionAccount *,QString CjhannelType,QString peerId,const Tp::ChannelDetails &);
58  * \param  TpSession  pointer to TpSession class
59  * \param  ChannelType type of Channel, TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT for text channel, TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA for steram media, as exmple for incoming call
60  * \param  peedId PeerId, as example caller telephone number
61  * \param channeDetails needed if you would like to create a channel. For text chanels TpSession creates channel automatically. For calls, Maemo Call UI handles callcreation
62  */
63
64 /**
65  * Construct a new TpSessionAccount object. This constructor is called by TpSession class when new account is created or fetched from account manager. It is not inended to be used stand alone
66  *
67  * \param am          Telepathy-Qt4 account manager for this account
68  * \param objectPath  Dbus object path tonew account
69  */
70 TpSessionAccount::TpSessionAccount(Tp::AccountManagerPtr am,const QString &objectPath):
71         mAcc(Tp::Account::create(am->dbusConnection(),am->busName(), objectPath))
72
73 {
74     connect(mAcc->becomeReady(),SIGNAL(finished(Tp::PendingOperation *)),SLOT(onReady(Tp::PendingOperation *)));
75     ready=false;
76     //  qDebug() << "TpSessionAccount::TpSessionAccount objectPath=" << objectPath;
77 };
78
79
80 void TpSessionAccount::onReady(Tp::PendingOperation *op)
81 {
82
83     acc = mAcc.data();
84     qDebug() << "TpSessionAccount::onReady cmName=" << acc->cmName() << "haveConnection=" <<
85         (acc->haveConnection()? ( acc->connection()->isReady() ? "Ready":"notReady"):"no");
86
87     if(acc->haveConnection())
88     {
89
90         connect(acc->connection()->becomeReady(Tp::Connection::FeatureRoster | Tp::Connection::FeatureSelfContact ),
91                 SIGNAL(finished(Tp::PendingOperation *)),
92                 SLOT(onContactsConnectionReady(Tp::PendingOperation *)));
93         if (acc->connection()->isReady() && acc->connection()->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS))
94         {
95             qDebug() << "TpSessionAccount::onReady: connecting to Connection.Interface.NewChannels";
96             connect(acc->connection()->requestsInterface(),
97                     SIGNAL(NewChannels(const Tp::ChannelDetailsList&)),
98                     SLOT(onNewChannels(const Tp::ChannelDetailsList&)));
99         }
100     }
101     else
102     { // If there is no connection, we are ready now, else we are ready when contacts connection is ready
103         qDebug() << "If there is no connection, we are ready now, else we are ready when contacts connection is ready";
104         ready=true;
105         Q_EMIT accountReady(this);
106     }
107 }
108
109 void TpSessionAccount::onContactsConnectionReady(Tp::PendingOperation *op)
110 {
111     if (op->isError()) {
112         qWarning() << "Connection cannot become ready" << acc->cmName();
113         return;
114     }
115
116     if (acc->connection()->interfaces().contains(TELEPATHY_INTERFACE_CONNECTION_INTERFACE_REQUESTS)) {
117         qDebug() << "TpSessionAccount::onContactsConectionReady: connecting to Connection.Interface.NewChannels";
118         connect(acc->connection()->requestsInterface(),
119                 SIGNAL(NewChannels(const Tp::ChannelDetailsList&)),
120                 SLOT(onNewChannels(const Tp::ChannelDetailsList&)));
121     } else qDebug() << "TpSessionAccount::onectionReady: does NO have CONNECTION_INTERFACE_REQUESTS";
122     Tp::PendingReady *pr = qobject_cast<Tp::PendingReady *>(op);
123     contactsConn = Tp::ConnectionPtr(qobject_cast<Tp::Connection *>(pr->object()));
124 #if 0
125     connect(contactsConn->contactManager(),
126             SIGNAL(presencePublicationRequested(const Tp::Contacts &)),
127             SLOT(onPresencePublicationRequested(const Tp::Contacts &)));
128 #endif
129     qDebug() << "TpSessionAccount::onContactsConnectionReady "<< acc->cmName() ;
130     //    RosterItem *item;
131     bool exists;
132     myContacts=contactsConn->contactManager()->allKnownContacts();
133     Q_FOREACH (const Tp::ContactPtr &contact, myContacts) {
134         qDebug() << "id=" <<contact->id() << " alias=" << contact->alias() << " presence=" << contact->presenceStatus()  ;
135         if(contact->id()==reqContact) {
136             addOutgoingChannel(contact);
137             reqContact="";
138         }
139     };
140     if(!reqContact.isEmpty() ) makeContactFromAddress(reqContact);
141     ready=true;
142     Q_EMIT accountReady(this);
143 }
144
145
146 /**
147  * Fetch Tp::ContactPtr for contact with given address. Contact is searched among contacts returned by contact manager for ths account.
148  * All connecions managers does not return contacts, as example Ring telephony contact manager does not. Gabble for Googletalk or Spirit for Skype does
149  * return contacts-
150  *
151  * \param id            Contact address/id, as example email address, telephone number etc. Only exact matches
152  * \return      TpContactPtr, if nontact is not returned TpContactPtr.isNull() is true
153  */
154
155 Tp::ContactPtr TpSessionAccount::getContactFromAddress(QString id)
156 {
157     Tp::ContactPtr p;
158     Q_FOREACH (const Tp::ContactPtr &contact, myContacts) {
159         if(contact->id()==reqContact) return p=contact;
160     }
161     return p;
162 }
163 /**
164  * Fetch TpSessionChannel for with given address. Contact is searched among active channels for this account.
165  *
166  *
167  * \param id            Contact address/id, as example email address, telephone number etc. Only exact matches
168  * \return          Pointer to TpSessionChannel or NULL if nit found
169  */
170
171 TpSessionChannel* TpSessionAccount::getChannelFromPeerAddress(QString id)
172 {
173     TpSessionChannel* p=NULL;
174     Q_FOREACH (TpSessionChannel* channel, myChannels) {
175         if(channel->peerId()==id) return p=channel;
176     }
177     return p;
178 }
179 /**
180  * Creates new contact with given address. This function is Acynchronous, it sends request to contact manager for contact creation,
181  *
182  * \param address           Contact address/id, as example email address, telephone number etc.
183  */
184
185 void TpSessionAccount::makeContactFromAddress(QString address)
186 {
187     qDebug() << "TpSessionAccount::makeContactFromAddress(QString address)";
188     reqContact=address;  // When we get retrieved signal, we check if it is this one
189     Tp::PendingContacts *pc = contactsConn->contactManager()->contactsForIdentifiers( QStringList(address) );
190     qDebug() << "111111111111111111";
191     connect(pc,SIGNAL(finished(Tp::PendingOperation *)),SLOT(onNewContactRetrieved(Tp::PendingOperation *)));
192 }
193
194 void TpSessionAccount::onNewContactRetrieved(Tp::PendingOperation *op)
195 {
196     Tp::PendingContacts *pcontacts = qobject_cast<Tp::PendingContacts *>(op);
197     QList<Tp::ContactPtr> contacts = pcontacts->contacts();
198     QString username = pcontacts->identifiers().first();
199     if (contacts.size() != 1 || !contacts.first()) {
200         qDebug() << "Unable to add contact " <<reqContact;
201         return;
202     }
203
204     Tp::ContactPtr contact = contacts.first();
205     //    qDebug() << "TpSessionAccount::onContactRetrieved" << reqContact;
206     if(!reqContact.isEmpty()) addOutgoingChannel(contacts.first());
207 }
208 /**
209  * Send message to given address. This function is compled Acynchronous function that may produce multiple state transitions beforecomletion.
210  * If there is already existing TpSessionChannel for this contact, it simply queues message for sending and no forther transitions are needed
211  * If there are no hannel, it first check is there contact for this address, if is, it requests new channel to be created for ths channel and message
212  * is left waiting untill channel is created. If there is no contact, it sends request fr contact creation and when contact is created state machine
213  * proceeds to channel creation.
214  *
215  * MessageSent() signal is emitted when completed
216  *
217  * \param address           Contact address/id, as example email address, telephone number etc.
218  * \param message           Message string
219  */
220
221 void TpSessionAccount::sendMessageToAddress(QString address,QString message)
222 {
223     qDebug() << "TpSessionAccount::sendMessageToAddress(QString address,QString message)";
224
225     Tp::ContactPtr p;
226     TpSessionChannel* channel = getChannelFromPeerAddress(address);
227     if(channel) {
228         channel->sendMessage(message); // We have already channel
229         Q_EMIT messageQueued(this);
230     }
231     else {        
232         reqMessage=message;
233         p=getContactFromAddress(address); // Do we have contact ready ?
234         if(p.isNull())  // If not, create it
235         {
236             makeContactFromAddress(address); // Create and after created, send
237         }else
238         {
239             addOutgoingChannel(p); // Create channel and when ready, send
240         }
241     };
242 }
243
244 void TpSessionAccount::addOutgoingChannel(const Tp::ContactPtr &contact)
245 {
246
247
248     //    qDebug() << "TpSessionAccount::addOutgoingChannel";
249
250     TpSessionChannel* newChannel=new TpSessionChannel(contact->manager()->connection(),contact);
251     connect(newChannel,SIGNAL(messageReceived(const Tp::ReceivedMessage &,TpSessionChannel *)),
252             SLOT(onMessageReceived(const Tp::ReceivedMessage &,TpSessionChannel *)));
253     connect(newChannel,SIGNAL(channelReady(TpSessionChannel *)),
254             SLOT(onOutgoingChannelReady(TpSessionChannel*)));
255     myChannels+=newChannel;
256
257 }
258
259 void TpSessionAccount::onOutgoingChannelReady(TpSessionChannel *ch)
260 {
261     // qDebug() << "TpSessionAccoiunt::onOutgoingChannelReady";
262     Q_EMIT channelReady(this);
263     if(!reqMessage.isEmpty()) {
264         ch->sendMessage(reqMessage);
265         Q_EMIT messageQueued(this);
266     };
267     reqMessage.clear();
268 }
269
270
271 void TpSessionAccount::onMessageSent(const Tp::Message &msg,Tp::MessageSendingFlags, const QString &flags)
272 {
273     //    qDebug() << "TpSessionAccount::onMessageSent";
274     Q_EMIT messageSent(msg,this);
275 };
276
277 void TpSessionAccount::onMessageReceived(const Tp::ReceivedMessage &msg,TpSessionChannel *ch)
278 {
279     //    qDebug() << "TpSessionAccount::onMessageReceived " << msg.text();
280     Q_EMIT messageReceived(msg,this);
281 };
282
283 void TpSessionAccount::onNewChannels(const Tp::ChannelDetailsList &channels)
284 {
285
286     Tp::TextChannelPtr myIngoingTextChannel;
287     //    qDebug() << "TpSessionAccount::onNewChannels";
288     Q_FOREACH (const Tp::ChannelDetails &details, channels) {
289         QString channelType = details.properties.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".ChannelType")).toString();
290         QString targetId = details.properties.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".TargetID")).toString();
291         bool requested = details.properties.value(QLatin1String(TELEPATHY_INTERFACE_CHANNEL ".Requested")).toBool();
292         //        qDebug() << " channelType:" << channelType <<" requested  :" << requested << " targetId" << targetId;
293
294         Q_EMIT newChannel(this,channelType,targetId,details);
295         if (channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_TEXT && !requested) {
296
297             myIngoingTextChannel = Tp::TextChannel::create(acc->connection(),details.channel.path(),details.properties);
298             //            qDebug() << "TpSessionAccount::onNewChannels path=" <<"path " << myIngoingTextChannel->objectPath();
299
300             TpSessionChannel* newChannel=new TpSessionChannel( myIngoingTextChannel);
301             connect(newChannel,SIGNAL(messageReceived(const Tp::ReceivedMessage &,TpSessionChannel *)),
302                     SLOT(onMessageReceived(const Tp::ReceivedMessage &,TpSessionChannel *)));
303             myChannels+=newChannel;
304         }
305         if (channelType == TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA && !requested) {
306             //            qDebug() << "Incoming call" ;
307         }
308     }
309 }