summaryrefslogtreecommitdiff
path: root/sunshine
diff options
context:
space:
mode:
authorKrzysztof Klinikowski <kkszysiu@gmail.com>2010-05-24 12:52:10 +0200
committerKrzysztof Klinikowski <kkszysiu@gmail.com>2010-05-24 12:52:10 +0200
commit1e4f45afdbee9edcc9cc39de33b8120c1aa9b4f6 (patch)
tree5517c2ae7fe334d478fcb4da43a0b6d603753be2 /sunshine
parent32ee26f5fe79b7d03c21da46653b316eafbda93f (diff)
GaduApi class refactoring and ContactInfo interface implementation.
Diffstat (limited to 'sunshine')
-rw-r--r--sunshine/Connection_Interface_Contact_Info.py78
-rw-r--r--sunshine/avatars.py18
-rw-r--r--sunshine/connection.py17
-rw-r--r--sunshine/contacts.py9
-rw-r--r--sunshine/contacts_info.py88
-rw-r--r--sunshine/lqsoft/gaduapi.py269
6 files changed, 323 insertions, 156 deletions
diff --git a/sunshine/Connection_Interface_Contact_Info.py b/sunshine/Connection_Interface_Contact_Info.py
new file mode 100644
index 0000000..9872d98
--- /dev/null
+++ b/sunshine/Connection_Interface_Contact_Info.py
@@ -0,0 +1,78 @@
+# -*- coding: utf-8 -*-
+# Generated from the Telepathy spec
+""" Copyright (C) 2008 Collabora Limited
+ Copyright (C) 2008 Nokia Corporation
+
+ This library is free software; you can redistribute it and/or
+modify it under the terms of the GNU Lesser General Public
+License as published by the Free Software Foundation; either
+version 2.1 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
+Lesser General Public License for more details.
+
+You should have received a copy of the GNU Lesser General Public
+License along with this library; if not, write to the Free Software
+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
+
+"""
+
+import dbus.service
+
+
+class ConnectionInterfaceContactInfo(dbus.service.Interface):
+ """\
+ An interface for requesting information about a contact on a given
+ connection. Information is represented as a list of
+ Contact_Info_Fields forming a
+ structured representation of a vCard (as defined by RFC 2426), using
+ field names and semantics defined therein.
+ """
+
+ def __init__(self):
+ self._interfaces.add('org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT')
+
+ @dbus.service.method('org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT', in_signature='au', out_signature='a{ua(sasas)}')
+ def GetContactInfo(self, Contacts):
+ """
+ Request information on several contacts at once. This SHOULD only
+ return cached information, omitting handles for which no information is
+ cached from the returned map. For contacts without cached information,
+ the information SHOULD be requested from the network, with the result
+ signalled later by ContactInfoChanged.
+
+ """
+ raise NotImplementedError
+
+ @dbus.service.method('org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT', in_signature='u', out_signature='a(sasas)')
+ def RequestContactInfo(self, Contact):
+ """
+ Retrieve information for a contact, requesting it from the network if
+ it is not cached locally.
+
+ """
+ raise NotImplementedError
+
+ @dbus.service.method('org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT', in_signature='a(sasas)', out_signature='')
+ def SetContactInfo(self, ContactInfo):
+ """
+ Set new contact information for this connection, replacing existing
+ information. This method is only suppported if
+ ContactInfoFlags contains
+ Can_Set, and may only be passed fields conforming to
+ SupportedFields.
+
+ """
+ raise NotImplementedError
+
+ @dbus.service.signal('org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT', signature='ua(sasas)')
+ def ContactInfoChanged(self, Contact, ContactInfo):
+ """
+ Emitted when a contact's information has changed or been received for
+ the first time on this connection.
+
+ """
+ pass
+ \ No newline at end of file
diff --git a/sunshine/avatars.py b/sunshine/avatars.py
index 6a16073..83920e8 100644
--- a/sunshine/avatars.py
+++ b/sunshine/avatars.py
@@ -106,23 +106,9 @@ class SunshineAvatars(telepathy.server.ConnectionInterfaceAvatars):
if not isinstance(avatar, str):
avatar = "".join([chr(b) for b in avatar])
data = StringIO.StringIO(avatar).getvalue()
- gg = GG_Oauth(self.profile.uin, self.password)
- ext = gg.getExtByType(mime_type)
- gg.uploadAvatar(data, ext)
+ ext = self.ggapi.getExtByType(mime_type)
+ self.ggapi.uploadAvatar(data, ext)
return str(self.profile.uin).encode("hex")
-# self._avatar_known = True
-# if not isinstance(avatar, str):
-# avatar = "".join([chr(b) for b in avatar])
-# msn_object = papyon.p2p.MSNObject(self.msn_client.profile,
-# len(avatar),
-# papyon.p2p.MSNObjectType.DISPLAY_PICTURE,
-# hashlib.sha1(avatar).hexdigest() + '.tmp',
-# "",
-# data=StringIO.StringIO(avatar))
-# self.msn_client.profile.msn_object = msn_object
-# avatar_token = msn_object._data_sha.encode("hex")
-# logger.info("Setting self avatar to %s" % avatar_token)
-# return avatar_token
def ClearAvatar(self):
pass
diff --git a/sunshine/connection.py b/sunshine/connection.py
index 3f6059e..1670c82 100644
--- a/sunshine/connection.py
+++ b/sunshine/connection.py
@@ -29,6 +29,8 @@ from sunshine.util.config import SunshineConfig
from sunshine.lqsoft.pygadu.twisted_protocol import GaduClient
from sunshine.lqsoft.pygadu.models import GaduProfile, GaduContact, GaduContactGroup
+from sunshine.lqsoft.gaduapi import *
+
from twisted.internet import reactor, protocol
from twisted.web.client import getPage
from twisted.internet import task
@@ -43,6 +45,7 @@ from sunshine.avatars import SunshineAvatars
from sunshine.handle import SunshineHandleFactory
from sunshine.capabilities import SunshineCapabilities
from sunshine.contacts import SunshineContacts
+from sunshine.contacts_info import SunshineContactInfo
from sunshine.channel_manager import SunshineChannelManager
from sunshine.util.decorator import async, stripHTML, unescape
@@ -112,7 +115,8 @@ class SunshineConnection(telepathy.server.Connection,
SunshineAliasing,
SunshineAvatars,
SunshineCapabilities,
- SunshineContacts
+ SunshineContacts,
+ SunshineContactInfo
):
_secret_parameters = set([
@@ -164,8 +168,6 @@ class SunshineConnection(telepathy.server.Connection,
self.profile.onXmlEvent = self.onXmlEvent
self.profile.onUserData = self.onUserData
- self.password = str(parameters['password'])
-
#lets try to make file with contacts etc ^^
self.configfile = SunshineConfig(int(parameters['account']))
self.configfile.check_dirs()
@@ -188,6 +190,8 @@ class SunshineConnection(telepathy.server.Connection,
logger.info("We have %s contacts in file." % (self.configfile.get_contacts_count()))
self.factory = GaduClientFactory(self.profile)
+ self.ggapi = GG_Oauth(self.profile.uin, parameters['password'])
+
self._channel_manager = SunshineChannelManager(self)
self._recv_id = 0
@@ -203,6 +207,7 @@ class SunshineConnection(telepathy.server.Connection,
SunshineAvatars.__init__(self)
SunshineContacts.__init__(self)
SunshineCapabilities.__init__(self)
+ SunshineContactInfo.__init__(self)
self.updateCapabilitiesCalls()
@@ -382,7 +387,7 @@ class SunshineConnection(telepathy.server.Connection,
def getServerAdress(self, uin):
logger.info("Fetching GG server adress.")
- url = 'http://appmsg.gadu-gadu.pl/appsvc/appmsg_ver10.asp?fmnumber=%s&lastmsg=0&version=10.0.0.10784' % (str(uin))
+ url = 'http://appmsg.gadu-gadu.pl/appsvc/appmsg_ver10.asp?fmnumber=%s&lastmsg=0&version=10.1.1.11119' % (str(uin))
d = getPage(url, timeout=10)
d.addCallback(self.on_server_adress_fetched, uin)
d.addErrback(self.on_server_adress_fetched_failed, uin)
@@ -637,3 +642,7 @@ class SunshineConnection(telepathy.server.Connection,
def onUserData(self, data):
logger.info("UserData: %s" % str(data))
+ #for user in data.users:
+ # print user.uin
+ # for attr in user.attr:
+ # print "%s - %s" % (attr.name, attr.value)
diff --git a/sunshine/contacts.py b/sunshine/contacts.py
index cdd5fa8..f6da095 100644
--- a/sunshine/contacts.py
+++ b/sunshine/contacts.py
@@ -29,6 +29,8 @@ __all__ = ['SunshineContacts']
logger = logging.getLogger('Sunshine.Contacts')
+CONNECTION_INTERFACE_CONTACT_INFO = 'org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT'
+
class SunshineContacts(telepathy.server.ConnectionInterfaceContacts):
attributes = {
@@ -37,7 +39,8 @@ class SunshineContacts(telepathy.server.ConnectionInterfaceContacts):
telepathy.CONNECTION_INTERFACE_ALIASING : 'alias',
telepathy.CONNECTION_INTERFACE_AVATARS : 'token',
telepathy.CONNECTION_INTERFACE_CAPABILITIES : 'caps',
- telepathy.CONNECTION_INTERFACE_CONTACT_CAPABILITIES : 'capabilities'
+ telepathy.CONNECTION_INTERFACE_CONTACT_CAPABILITIES : 'capabilities',
+ CONNECTION_INTERFACE_CONTACT_INFO : 'contact-info'
}
def __init__(self):
@@ -77,7 +80,9 @@ class SunshineContacts(telepathy.server.ConnectionInterfaceContacts):
telepathy.CONNECTION_INTERFACE_CAPABILITIES:
lambda x: self.GetCapabilities(x).items(),
telepathy.CONNECTION_INTERFACE_CONTACT_CAPABILITIES:
- lambda x: self.GetContactCapabilities(x).items()
+ lambda x: self.GetContactCapabilities(x).items(),
+ CONNECTION_INTERFACE_CONTACT_INFO:
+ lambda x: self.GetContactInfo(x).items()
}
#Hold handles if needed
diff --git a/sunshine/contacts_info.py b/sunshine/contacts_info.py
new file mode 100644
index 0000000..9591340
--- /dev/null
+++ b/sunshine/contacts_info.py
@@ -0,0 +1,88 @@
+# telepathy-sunshine is the GaduGadu connection manager for Telepathy
+#
+# Copyright (C) 2010 Krzysztof Klinikowski <kkszysiu@gmail.com>
+#
+# 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.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+import logging
+import dbus
+import dbus.service
+
+from sunshine.Connection_Interface_Contact_Info import ConnectionInterfaceContactInfo
+
+import telepathy
+import telepathy.constants
+import telepathy.errors
+
+from sunshine.handle import SunshineHandleFactory
+from sunshine.util.decorator import async
+
+__all__ = ['SunshineContactInfo']
+
+logger = logging.getLogger('Sunshine.ContactInfo')
+
+CONNECTION_INTERFACE_CONTACT_INFO = 'org.freedesktop.Telepathy.Connection.Interface.ContactInfo.DRAFT'
+
+# Contact_Info_Flag
+CONTACT_INFO_FLAG_CAN_SET = 1
+CONTACT_INFO_FLAG_PUSH = 2
+LAST_CONTACT_INFO_FLAG = 2
+# Contact_Info_Field_Flags (bitfield/set of flags, 0 for none)
+CONTACT_INFO_FIELD_FLAG_PARAMETERS_MANDATORY = 1
+
+class SunshineContactInfo(telepathy.server.DBusProperties, ConnectionInterfaceContactInfo):
+ def __init__(self):
+ logger.info('SunshineContactInfo called.')
+ telepathy.server.DBusProperties.__init__(self)
+ ConnectionInterfaceContactInfo.__init__(self)
+ #self._interfaces.remove(CONNECTION_INTERFACE_CONTACT_INFO)
+
+ self._implement_property_get(CONNECTION_INTERFACE_CONTACT_INFO, {
+ 'ContactInfoFlags': lambda: self.contact_info_flags,
+ 'SupportedFields': lambda: self.contact_info_supported_fields,
+ })
+
+ @property
+ def contact_info_flags(self):
+ return CONTACT_INFO_FLAG_CAN_SET | CONTACT_INFO_FLAG_PUSH
+
+ @property
+ def contact_info_supported_fields(self):
+ return [
+ ('nickname', [], 0, 1),
+ ('fn', [], 0, 1),
+ ('label', [], 0, 1),
+ ('bday', [], 0, 1),
+ ('url', [], 0, 1),
+ ('url', [], 0, 1),
+ ]
+
+ def GetContactInfo(self, contacts):
+ logger.info("GetContactInfo")
+ for contact in contacts:
+ print contact
+ return []
+
+ def RefreshContactInfo(self, contacts):
+ logger.info('RefreshContactInfo')
+ pass
+
+ def RequestContactInfo(self, contact):
+ logger.info('RequestContactInfo')
+ pass
+
+ def SetContactInfo(self, contactinfo):
+ logger.info('SetContactInfo')
+ pass
diff --git a/sunshine/lqsoft/gaduapi.py b/sunshine/lqsoft/gaduapi.py
index 7cfa6eb..b258560 100644
--- a/sunshine/lqsoft/gaduapi.py
+++ b/sunshine/lqsoft/gaduapi.py
@@ -6,6 +6,8 @@ from twisted.internet.protocol import Protocol
from twisted.web.http_headers import Headers
from twisted.internet.defer import succeed
+#from twisted.python import log
+
from twisted.internet import task
from twisted.web.client import getPage
@@ -45,6 +47,7 @@ REQUEST_TOKEN_URL = 'http://api.gadu-gadu.pl/request_token'
ACCESS_TOKEN_URL = 'http://api.gadu-gadu.pl/access_token'
AUTHORIZE_TOKEN_URL = 'http://login.gadu-gadu.pl/authorize'
PUT_AVATAR_URL = 'http://api.gadu-gadu.pl/avatars/%s/0.xml'
+GET_INFO_URL = 'http://api.gadu-gadu.pl/users/%s.json'
def check_requirements():
if proper_twisted == True and oauth_loaded == True:
@@ -104,7 +107,100 @@ class GG_Oauth(object):
self.consumer = oauth.OAuthConsumer(self.uin, self.password)
self._signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
+
+ #
+ # REQUESTING TOKEN
+ #
+
+ def requestToken(self):
+ oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_method='POST', http_url=REQUEST_TOKEN_URL) # create an oauth request
+ oauth_request.sign_request(self._signature_method, self.consumer, None) # the request knows how to generate a signature
+ auth_header = oauth_request.to_header()
+ headers = {}
+ headers['Authorization'] = [auth_header['Authorization']]
+ headers['Accept'] = ['application/json']
+ headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
+ headers['Host'] = ['api.gadu-gadu.pl']
+ headers['Content-Length'] = [0]
+ headers = Headers(headers)
+
+ url = REQUEST_TOKEN_URL
+ d = self.agent.request(
+ 'POST',
+ REQUEST_TOKEN_URL,
+ headers,
+ None)
+
+ d.addCallback(self.cbRequestToken)
+ d.addErrback(self.cbShutdown)
+
+ def cbRequestToken(self, response):
+ finished = Deferred()
+ response.deliverBody(BeginningPrinter(finished))
+ finished.addCallback(self.cbRequestTokenSuccess)
+ finished.addErrback(self.cbShutdown)
+ return finished
+
+ def cbRequestTokenSuccess(self, result):
+ content = json.loads(result)['result']
+
+ oauth_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
+
+ postvars = 'callback_url=http://www.mojageneracja.pl&request_token=%s&uin=%s&password=%s' % (oauth_token.key, self.uin, self.password)
+
+ headers = {}
+ headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
+ headers['Accept'] = ['*/*']
+ headers['Content-Type'] = ['application/x-www-form-urlencoded']
+
+ headers = Headers(headers)
+
+ body = StringProducer(str(postvars))
+
+ d = self.agent.request(
+ 'POST',
+ AUTHORIZE_TOKEN_URL,
+ headers,
+ body)
+
+ d.addCallback(self.cbTokenAuthorised, oauth_token)
+ d.addErrback(self.cbShutdown)
+
+ def cbTokenAuthorised(self, result, oauth_token):
+ oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=oauth_token, http_method='POST', http_url=ACCESS_TOKEN_URL) # create an oauth request
+ oauth_request.sign_request(self._signature_method, self.consumer, oauth_token) # the request knows how to generate a signature
+ auth_header = oauth_request.to_header()
+
+ headers = {}
+ headers['Authorization'] = [auth_header['Authorization']]
+ headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
+ headers['Accept'] = ['application/json']
+ headers['Content-Length'] = [0]
+ headers = Headers(headers)
+
+ d = self.agent.request(
+ 'POST',
+ ACCESS_TOKEN_URL,
+ headers,
+ None)
+
+ d.addCallback(self.requestAccessToken, oauth_token)
+ d.addErrback(self.cbShutdown)
+
+ def requestAccessToken(self, response, oauth_token):
+ finished = Deferred()
+ response.deliverBody(BeginningPrinter(finished))
+ finished.addCallback(self.accessTokenReceived, oauth_token)
+ finished.addErrback(self.cbShutdown)
+ return finished
+
+ def accessTokenReceived(self, result, oauth_token):
+ content = json.loads(result)['result']
+
+ self.access_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
+ self.expire_token = time.time()+36000
+
def getContentType(self, filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
@@ -140,8 +236,7 @@ class GG_Oauth(object):
def putAvatar(self, data, ext):
url = str(PUT_AVATAR_URL % self.uin)
- #print url
-
+
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=self.access_token, http_method='PUT', http_url=url) # create an oauth request
oauth_request.sign_request(self._signature_method, self.consumer, self.access_token) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
@@ -169,165 +264,60 @@ class GG_Oauth(object):
d.addErrback(self.cbShutdown)
def putAvatarSuccess(self, response):
- #print 'putAvatarSuccess: ', response
- #print 'Response version:', response.version
- #print 'Response code:', response.code
- #print 'Response phrase:', response.phrase
- #print 'Response headers:'
- #print pformat(list(response.headers.getAllRawHeaders()))
logger.info("New avatar should be uploaded now.")
+
+ def fetchUserInfo(self, uin):
+ url = str(GET_INFO_URL % self.uin)
- """
- def accessTokenReceived(self, result, oauth_token):
- print 'accessTokenReceived: ', result
- content = json.loads(result)['result']
- oauth_access_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
-
- #url = str(PUT_AVATAR_URL % content['uin'])
- url = 'http://api.gadu-gadu.pl/users/5120225.xml'
- print url
-
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=oauth_access_token, http_method='GET', http_url=url) # create an oauth request
- oauth_request.sign_request(self._signature_method, self.consumer, oauth_access_token) # the request knows how to generate a signature
- auth_header = oauth_request.to_header()
-
- headers = {}
- headers['Authorization'] = [auth_header['Authorization']]
- headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
- headers['Accept'] = ['*/*']
- headers['Host'] = ['api.gadu-gadu.pl']
- #headers['Content-Type'] = ['multipart/form-data; boundary=%s' % boundary]
- headers['Content-Length'] = [0]
- headers = Headers(headers)
- d = self.agent.request(
- 'GET',
- 'http://api.gadu-gadu.pl/users/5120225.xml',
- headers,
- None)
-
- d.addCallback(self.putAvatarSuccess)
- d.addErrback(self.cbShutdown)
- """
-
- def accessTokenReceived(self, result, oauth_token):
- #print 'accessTokenReceived: ', result
- content = json.loads(result)['result']
-
- self.access_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
- self.expire_token = time.time()+36000
-
- def requestAccessToken(self, response, oauth_token):
- #print 'Response version:', response.version
- #print 'Response code:', response.code
- #print 'Response phrase:', response.phrase
- #print 'Response headers:'
- #print pformat(list(response.headers.getAllRawHeaders()))
- finished = Deferred()
- response.deliverBody(BeginningPrinter(finished))
- finished.addCallback(self.accessTokenReceived, oauth_token)
- finished.addErrback(self.cbShutdown)
- return finished
-
- def cbTokenAuthorised(self, result, oauth_token):
- #print 'tokenAuthorised: ', result
- #print 'Response version:', result.version
- #print 'Response code:', result.code
- #print 'Response phrase:', result.phrase
- #print 'Response headers:'
- #print pformat(list(result.headers.getAllRawHeaders()))
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=oauth_token, http_method='POST', http_url=ACCESS_TOKEN_URL) # create an oauth request
- oauth_request.sign_request(self._signature_method, self.consumer, oauth_token) # the request knows how to generate a signature
+ oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, token=self.access_token, http_method='GET', http_url=url) # create an oauth request
+ oauth_request.sign_request(self._signature_method, self.consumer, self.access_token) # the request knows how to generate a signature
auth_header = oauth_request.to_header()
headers = {}
+ #headers['Connection'] = ['keep-alive']
headers['Authorization'] = [auth_header['Authorization']]
headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
- headers['Accept'] = ['application/json']
- #headers['Content-Type'] = ['application/x-www-form-urlencoded']
- headers['Content-Length'] = [0]
+ headers['Accept'] = ['*/*']
headers = Headers(headers)
d = self.agent.request(
- 'POST',
- ACCESS_TOKEN_URL,
+ 'GET',
+ url,
headers,
None)
- d.addCallback(self.requestAccessToken, oauth_token)
+ d.addCallback(self.fetchUserInfoSuccess, uin)
d.addErrback(self.cbShutdown)
- def cbRequestToken(self, response):
- #print 'Response version:', response.version
- #print 'Response code:', response.code
- #print 'Response phrase:', response.phrase
- #print 'Response headers:'
- #print pformat(list(response.headers.getAllRawHeaders()))
+ def fetchUserInfoSuccess(self, response, uin):
finished = Deferred()
response.deliverBody(BeginningPrinter(finished))
- finished.addCallback(self.cbRequestTokenSuccess)
+ finished.addCallback(self.onUserInfoRecv, uin)
finished.addErrback(self.cbShutdown)
return finished
-
- def cbRequestTokenSuccess(self, result):
+
+ def onUserInfoRecv(self, result, uin):
content = json.loads(result)['result']
+ self.onUserInfo(uin, content)
- oauth_token = oauth.OAuthToken(content['oauth_token'], content['oauth_token_secret'])
-
- postvars = 'callback_url=http://www.mojageneracja.pl&request_token=%s&uin=%s&password=%s' % (oauth_token.key, self.uin, self.password)
-
- headers = {}
- headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
- headers['Accept'] = ['*/*']
- headers['Content-Type'] = ['application/x-www-form-urlencoded']
+ def onUserInfo(self, uin, result):
+ pass
- headers = Headers(headers)
-
- body = StringProducer(str(postvars))
-
- d = self.agent.request(
- 'POST',
- AUTHORIZE_TOKEN_URL,
- headers,
- body)
-
- d.addCallback(self.cbTokenAuthorised, oauth_token)
- d.addErrback(self.cbShutdown)
-
def cbShutdown(self, ignored):
- #reactor.stop()
logger.info("Something went wrong.")
#print 'cbShutdown: ', ignored
- def requestToken(self):
- oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.consumer, http_method='POST', http_url=REQUEST_TOKEN_URL) # create an oauth request
- #oauth_request.set_parameter('oauth_timestamp', int(time.time())-3600)
- oauth_request.sign_request(self._signature_method, self.consumer, None) # the request knows how to generate a signature
- auth_header = oauth_request.to_header()
- headers = {}
- headers['Authorization'] = [auth_header['Authorization']]
- headers['Accept'] = ['application/json']
- headers['User-Agent'] = ['Gadu-Gadu Client, build 8,0,0,4881']
- headers['Host'] = ['api.gadu-gadu.pl']
- headers['Content-Length'] = [0]
- headers = Headers(headers)
-
- url = REQUEST_TOKEN_URL
-
- d = self.agent.request(
- 'POST',
- REQUEST_TOKEN_URL,
- headers,
- None)
-
- d.addCallback(self.cbRequestToken)
- d.addErrback(self.cbShutdown)
-
def checkTokenForAvatar(self, data, ext):
#print 'checkTokenForAvatar'
if int(time.time()) <= self.expire_token and self.access_token != None:
self.putAvatar(data, ext)
self.__loopingcall.stop()
-
+
+ def checkTokenForUserInfo(self, uin):
+ if int(time.time()) <= self.expire_token and self.access_token != None:
+ self.fetchUserInfo(uin)
+ self.__loopingcall.stop()
+
def getToken(self):
self.requestToken()
@@ -338,12 +328,23 @@ class GG_Oauth(object):
self.requestToken()
self.__loopingcall = task.LoopingCall(self.checkTokenForAvatar, data, ext)
self.__loopingcall.start(5.0)
-
+
+ def getUserInfo(self, uin):
+ if int(time.time()) <= self.expire_token and self.access_token != None:
+ self.fetchUserInfo(uin)
+ else:
+ self.requestToken()
+ self.__loopingcall = task.LoopingCall(self.checkTokenForUserInfo, uin)
+ self.__loopingcall.start(5.0)
+
#if check_requirements() == True:
# gg = GG_Oauth(4634020, 'xxxxxx')
-# data = open('avatar.png', 'r').read()
-# ext = mimetypes.guess_extension(mimetypes.guess_type('avatar.png')[0])
-# gg.uploadAvatar(data, ext)
+ #data = open('avatar.png', 'r').read()
+ #ext = mimetypes.guess_extension(mimetypes.guess_type('avatar.png')[0])
+ #gg.uploadAvatar(data, ext)
+# gg.getUserInfo('5120225')
#else:
# print 'GG_oAuth_API: Requirements related with Gadu-Gadu oAuth API support not fullfilled. You need twisted-core, twisted-web in version 9.0.0 or greater and python-oauth.'
+
+#log.startLogging(sys.stdout)
#reactor.run()