Skip to content

Commit

Permalink
Add returnvalues
Browse files Browse the repository at this point in the history
  • Loading branch information
littlecodersh committed Nov 11, 2016
1 parent 7593582 commit 6cd5ae4
Show file tree
Hide file tree
Showing 8 changed files with 256 additions and 114 deletions.
47 changes: 45 additions & 2 deletions itchat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,49 @@ def new_instance():

# I really want to use sys.modules[__name__] = originInstance
# but it makes auto-fill a real mess, so forgive me for my following **
# actually it toke me less than 30 seconds, god bless Uganda

import sys
sys.modules[__name__] = originInstance
# components.login
login = originInstance.login
get_QRuuid = originInstance.get_QRuuid
get_QR = originInstance.get_QR
check_login = originInstance.check_login
web_init = originInstance.web_init
show_mobile_login = originInstance.show_mobile_login
start_receiving = originInstance.start_receiving
get_msg = originInstance.get_msg
logout = originInstance.logout
# components.contact
update_chatroom = originInstance.update_chatroom
get_contact = originInstance.get_contact
get_friends = originInstance.get_friends
get_chatrooms = originInstance.get_chatrooms
get_mps = originInstance.get_mps
set_alias = originInstance.set_alias
add_friend = originInstance.add_friend
get_head_img = originInstance.get_head_img
create_chatroom = originInstance.create_chatroom
set_chatroom_name = originInstance.set_chatroom_name
delete_member_from_chatroom = originInstance.delete_member_from_chatroom
add_member_into_chatroom = originInstance.add_member_into_chatroom
# components.messages
send_raw_msg = originInstance.send_raw_msg
send_msg = originInstance.send_msg
upload_file = originInstance.upload_file
send_file = originInstance.send_file
send_image = originInstance.send_image
send_video = originInstance.send_video
send = originInstance.send
# components.hotreload
dump_login_status = originInstance.dump_login_status
load_login_status = originInstance.load_login_status
# components.register
auto_login = originInstance.auto_login
configured_reply = originInstance.configured_reply
msg_register = originInstance.msg_register
run = originInstance.run
# other functions
set_logging = originInstance.set_logging
search_friends = originInstance.search_friends
search_chatrooms = originInstance.search_chatrooms
search_mps = originInstance.search_mps
53 changes: 36 additions & 17 deletions itchat/components/contact.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import requests

from .. import config, utils
from ..returnvalues import ReturnValue

logger = logging.getLogger('itchat')

Expand Down Expand Up @@ -34,8 +35,14 @@ def update_chatroom(self, userName, detailedMember=False):
'List': [{
'UserName': userName,
'ChatRoomId': '', }], }
j = json.loads(self.s.post(url, data=json.dumps(data), headers=headers
).content.decode('utf8', 'replace'))['ContactList'][0]
contactList = json.loads(self.s.post(url, data=json.dumps(data), headers=headers
).content.decode('utf8', 'replace')).get('ContactList')
if not contactList:
return ReturnValue({'BaseResponse': {
'ErrMsg': 'No chatroom found',
'Ret': -1001, }})
else:
j = contactList[0]

if detailedMember:
def get_detailed_member_info(encryChatroomId, memberList):
Expand All @@ -60,7 +67,7 @@ def get_detailed_member_info(encryChatroomId, memberList):
totalMemberList += get_detailed_member_info(j['EncryChatRoomId'], memberList)
j['MemberList'] = totalMemberList

update_local_chatrooms(core, [j])
update_local_chatrooms(self, [j])
return self.storageClass.search_chatrooms(userName=j['UserName'])

def update_local_chatrooms(core, l):
Expand All @@ -86,7 +93,7 @@ def update_local_chatrooms(core, l):
oldMemberList, 'UserName', member['UserName'])
if oldMember is not None:
for k in oldMember:
member[k] = member[k] or oldMember[k]
member[k] = member.get(k) or oldMember[k]
else:
chatroom['MemberList'] = oldMemberList
# update other info
Expand Down Expand Up @@ -149,7 +156,7 @@ def get_contact(self, update=False):
self.memberList.append(m)
else:
self.mpList.append(m)
if chatroomList: update_local_chatrooms(core, chatroomList)
if chatroomList: update_local_chatrooms(self, chatroomList)
return copy.deepcopy(chatroomList)

def get_friends(self, update=False):
Expand All @@ -176,9 +183,9 @@ def set_alias(self, userName, alias):
'RemarkName' : alias,
'BaseRequest' : self.loginInfo['BaseRequest'], }
headers = { 'User-Agent' : config.USER_AGENT }
j = self.s.post(url, json.dumps(data, ensure_ascii=False).encode('utf8'),
headers=headers).json()
return j['BaseResponse']['Ret'] == 0
r = self.s.post(url, json.dumps(data, ensure_ascii=False).encode('utf8'),
headers=headers)
return ReturnValue(rawResponse=r)

def add_friend(self, userName, status=2, ticket='', userInfo={}):
''' Add a friend or accept a friend
Expand All @@ -204,7 +211,7 @@ def add_friend(self, userName, status=2, ticket='', userInfo={}):
r = self.s.post(url, data=json.dumps(data), headers=headers)
if userInfo: # add user to storage
self.memberList.append(utils.struct_friend_info(userInfo))
return r.json()
return ReturnValue(rawResponse=r)

def get_head_img(self, userName=None, chatroomUserName=None, picDir=None):
''' get head image
Expand All @@ -218,13 +225,19 @@ def get_head_img(self, userName=None, chatroomUserName=None, picDir=None):
url = '%s/webwxgeticon' % self.loginInfo['url']
if chatroomUserName is None:
infoDict = self.storageClass.search_friends(userName=userName)
if infoDict is None: return None
if infoDict is None:
return ReturnValue({'BaseResponse': {
'ErrMsg': 'No friend found',
'Ret': -1001, }})
else:
if userName is None:
url = '%s/webwxgetheadimg' % self.loginInfo['url']
else:
chatroom = self.storageClass.search_chatrooms(userName=chatroomUserName)
if chatroomUserName is None: return None
if chatroomUserName is None:
return ReturnValue({'BaseResponse': {
'ErrMsg': 'No chatroom found',
'Ret': -1001, }})
if chatroom['EncryChatRoomId'] == '':
chatroom = self.update_chatroom(chatroomUserName)
params['chatroomid'] = chatroom['EncryChatRoomId']
Expand All @@ -233,10 +246,14 @@ def get_head_img(self, userName=None, chatroomUserName=None, picDir=None):
tempStorage = io.BytesIO()
for block in r.iter_content(1024):
tempStorage.write(block)
if picDir is None: return tempStorage.getvalue()
if picDir is None:
return tempStorage.getvalue()
with open(picDir, 'wb') as f: f.write(tempStorage.getvalue())
return ReturnValue({'BaseResponse': {
'ErrMsg': 'Successfully downloaded',
'Ret': 0, }})

def create_chatroom(self, memberList, topic = ''):
def create_chatroom(self, memberList, topic=''):
url = '%s/webwxcreatechatroom?pass_ticket=%s&r=%s' % (
self.loginInfo['url'], self.loginInfo['pass_ticket'], int(time.time()))
data = {
Expand All @@ -249,7 +266,7 @@ def create_chatroom(self, memberList, topic = ''):
'User-Agent' : config.USER_AGENT }
r = self.s.post(url, headers=headers,
data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore'))
return r.json()
return ReturnValue(rawResponse=r)

def set_chatroom_name(self, chatroomUserName, name):
url = '%s/webwxupdatechatroom?fun=modtopic&pass_ticket=%s' % (
Expand All @@ -263,7 +280,7 @@ def set_chatroom_name(self, chatroomUserName, name):
'User-Agent' : config.USER_AGENT }
r = self.s.post(url, headers=headers,
data=json.dumps(data, ensure_ascii=False).encode('utf8', 'ignore'))
return r.json()
return ReturnValue(rawResponse=r)

def delete_member_from_chatroom(self, chatroomUserName, memberList):
url = '%s/webwxupdatechatroom?fun=delmember&pass_ticket=%s' % (
Expand All @@ -275,7 +292,8 @@ def delete_member_from_chatroom(self, chatroomUserName, memberList):
headers = {
'content-type': 'application/json; charset=UTF-8',
'User-Agent' : config.USER_AGENT}
return self.s.post(url, data=json.dumps(data),headers=headers).json()
r = self.s.post(url, data=json.dumps(data),headers=headers)
return ReturnValue(rawResponse=r)

def add_member_into_chatroom(self, chatroomUserName, memberList,
useInvitation=False):
Expand All @@ -302,4 +320,5 @@ def add_member_into_chatroom(self, chatroomUserName, memberList,
headers = {
'content-type': 'application/json; charset=UTF-8',
'User-Agent' : config.USER_AGENT}
return self.s.post(url, data=json.dumps(params),headers=headers).json()
r = self.s.post(url, data=json.dumps(params),headers=headers)
return ReturnValue(rawResponse=r)
14 changes: 11 additions & 3 deletions itchat/components/hotreload.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import requests

from ..returnvalues import ReturnValue
from .contact import update_local_chatrooms
from .messages import produce_msg

Expand Down Expand Up @@ -34,15 +35,20 @@ def load_login_status(self, fileDir, callback=None):
j = pickle.load(f)
except Exception as e:
logger.debug('No such file, loading login status failed.')
return False
return ReturnValue({'BaseResponse': {
'ErrMsg': 'No such file, loading login status failed.',
'Ret': -1002, }})

self.loginInfo = j['loginInfo']
self.s.cookies = requests.utils.cookiejar_from_dict(j['cookies'])
self.storageClass.loads(j['storage'])
msgList, contactList = self.get_msg()
if (msgList or contactList) is None:
self.logout()
logger.debug('server refused, loading login status failed.')
return False
return ReturnValue({'BaseResponse': {
'ErrMsg': 'server refused, loading login status failed.',
'Ret': -1003, }})
else:
if contactList:
update_local_chatrooms(self, contactList)
Expand All @@ -53,4 +59,6 @@ def load_login_status(self, fileDir, callback=None):
logger.debug('loading login status succeeded.')
if hasattr(callback, '__call__'):
callback()
return True
return ReturnValue({'BaseResponse': {
'ErrMsg': 'loading login status succeeded.',
'Ret': 0, }})
20 changes: 11 additions & 9 deletions itchat/components/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import requests

from .. import config, utils
from ..returnvalues import ReturnValue
from .contact import update_local_chatrooms
from .messages import produce_msg

Expand All @@ -23,8 +24,8 @@ def load_login(core):
core.get_msg = get_msg
core.logout = logout

def login(self, enableCmdQR=False, picDir=None, callback=None,
finishCallback=None):
def login(self, enableCmdQR=False, picDir=None,
callback=None, finishCallback=None):
while 1:
for getCount in range(10):
logger.info('Getting uuid of QR code.')
Expand Down Expand Up @@ -170,17 +171,17 @@ def show_mobile_login(self):
'ContentType': 'application/json; charset=UTF-8',
'User-Agent' : config.USER_AGENT, }
r = self.s.post(url, data=json.dumps(data), headers=headers)
return r
return ReturnValue(rawResponse=r)

def start_receiving(self, finishCallback=None):
self.alive = True
def maintain_loop():
retryCount = 0
while 1:
while self.alive:
try:
i = sync_check(self)
if i is None:
break
self.alive = False
elif i == '0':
continue
else:
Expand All @@ -195,10 +196,9 @@ def maintain_loop():
retryCount += 1
logger.debug(traceback.format_exc())
if self.receivingRetryCount < retryCount:
break
self.alive = False
else:
time.sleep(1)
self.alive = False
self.logout()
if hasattr(finishCallback, '__call__'):
finishCallback()
Expand Down Expand Up @@ -248,7 +248,7 @@ def get_msg(self):

def logout(self):
if self.alive:
url = '%s/webwxlogout'
url = '%s/webwxlogout' % self.loginInfo['url']
params = {
'redirect' : 1,
'type' : 1,
Expand All @@ -259,4 +259,6 @@ def logout(self):
self.s.cookies.clear()
del self.chatroomList[:]
# other info will be automatically cleared
return True
return ReturnValue({'BaseResponse': {
'ErrMsg': 'logout successfully.',
'Ret': 0, }})
Loading

0 comments on commit 6cd5ae4

Please sign in to comment.