Skip to content

Commit

Permalink
Add oop compacity
Browse files Browse the repository at this point in the history
  • Loading branch information
littlecodersh committed Mar 17, 2017
1 parent d87da68 commit 834e638
Show file tree
Hide file tree
Showing 7 changed files with 299 additions and 20 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
build/*
dist/*
test/*
tests/*
itchat.egg-info/*
*.pyc
*.swp
Expand Down
20 changes: 11 additions & 9 deletions itchat/components/contact.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from .. import config, utils
from ..returnvalues import ReturnValue
from ..storage import contact_change
from ..storage import contact_change, templates

logger = logging.getLogger('itchat')

Expand Down Expand Up @@ -99,8 +99,8 @@ def update_friend(self, userName):
return r if len(r) != 1 else r[0]

def update_info_dict(oldInfoDict, newInfoDict):
'''
only normal values will be updated here
''' only normal values will be updated here
because newInfoDict is normal dict, so it's not necessary to consider templates
'''
for k, v in newInfoDict.items():
if any((isinstance(v, t) for t in (tuple, list, dict))):
Expand All @@ -126,8 +126,8 @@ def update_local_chatrooms(core, l):
if oldChatroom:
update_info_dict(oldChatroom, chatroom)
# - update other values
memberList, oldMemberList = (c.get('MemberList', [])
for c in (chatroom, oldChatroom))
memberList = chatroom.get('MemberList', [])
oldMemberList = oldChatroom.memberList
if memberList:
for member in memberList:
oldMember = utils.search_dict_list(
Expand All @@ -137,17 +137,19 @@ def update_local_chatrooms(core, l):
else:
oldMemberList.append(member)
else:
oldChatroom = chatroom
core.chatroomList.append(chatroom)
oldChatroom = templates.wrap_user_dict(chatroom)
core.chatroomList.append(oldChatroom)
# delete useless members
if len(chatroom['MemberList']) != len(oldChatroom['MemberList']) and \
chatroom['MemberList']:
existsUserNames = [member['UserName'] for member in chatroom['MemberList']]
delList = []
for i, member in enumerate(oldChatroom['MemberList']):
if member['UserName'] not in existsUserNames: delList.append(i)
if member['UserName'] not in existsUserNames:
delList.append(i)
delList.sort(reverse=True)
for i in delList: del oldChatroom['MemberList'][i]
for i in delList:
del oldChatroom['MemberList'][i]
# - update OwnerUin
if oldChatroom.get('ChatRoomOwner') and oldChatroom.get('MemberList'):
oldChatroom['OwnerUin'] = utils.search_dict_list(oldChatroom['MemberList'],
Expand Down
3 changes: 2 additions & 1 deletion itchat/components/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

from .. import config, utils
from ..returnvalues import ReturnValue
from ..storage.templates import wrap_user_dict
from .contact import update_local_chatrooms, update_local_friends
from .messages import produce_msg

Expand Down Expand Up @@ -182,7 +183,7 @@ def web_init(self):
# deal with login info
utils.emoji_formatter(dic['User'], 'NickName')
self.loginInfo['InviteStartCount'] = int(dic['InviteStartCount'])
self.loginInfo['User'] = utils.struct_friend_info(dic['User'])
self.loginInfo['User'] = wrap_user_dict(utils.struct_friend_info(dic['User']))
self.memberList.append(self.loginInfo['User'])
self.loginInfo['SyncKey'] = dic['SyncKey']
self.loginInfo['synckey'] = '|'.join(['%s_%s' % (item['Key'], item['Val'])
Expand Down
2 changes: 1 addition & 1 deletion itchat/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __init__(self):
- failing is failing
'''
self.alive, self.isLogging = False, False
self.storageClass = storage.Storage()
self.storageClass = storage.Storage(self)
self.memberList = self.storageClass.memberList
self.mpList = self.storageClass.mpList
self.chatroomList = self.storageClass.chatroomList
Expand Down
21 changes: 20 additions & 1 deletion itchat/returnvalues.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,23 @@
TRANSLATE = 'Chinese'

class ReturnValue(dict):
''' turn return value of itchat into a boolean value
for requests:
..code::python
import requests
r = requests.get('http://httpbin.org/get')
print(ReturnValue(rawResponse=r)
for normal dict:
..code::python
returnDict = {
'BaseResponse': {
'Ret': 0,
'ErrMsg': 'My error msg', }, }
print(ReturnValue(returnDict))
'''
def __init__(self, returnValueDict={}, rawResponse=None):
if rawResponse:
try:
Expand All @@ -14,7 +31,8 @@ def __init__(self, returnValueDict={}, rawResponse=None):
'Ret': -1004,
'ErrMsg': 'Unexpected return value', },
'Data': rawResponse.content, }
for k, v in returnValueDict.items(): self[k] = v
for k, v in returnValueDict.items():
self[k] = v
if not 'BaseResponse' in self:
self['BaseResponse'] = {
'ErrMsg': 'no BaseResponse in raw response',
Expand Down Expand Up @@ -45,6 +63,7 @@ def __repr__(self):
-1003: u'服务器拒绝连接',
-1004: u'服务器返回异常值',
-1005: u'参数错误',
-1006: u'无效操作',
0: u'请求成功',
},
}
27 changes: 20 additions & 7 deletions itchat/storage.py → itchat/storage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,32 @@
import queue as Queue
from threading import Lock

from .templates import (
ContactList, AbstractUserDict, User,
MassivePlatform, Chatroom, ChatroomMember)

def contact_change(fn):
def _contact_change(core, *args, **kwargs):
with core.storageClass.updateLock:
return fn(core, *args, **kwargs)
return _contact_change

class Storage(object):
def __init__(self):
def __init__(self, core):
self.userName = None
self.nickName = None
self.updateLock = Lock()
self.memberList = []
self.mpList = []
self.chatroomList = []
self.memberList = ContactList()
self.mpList = ContactList()
self.chatroomList = ContactList()
self.msgList = Queue.Queue(-1)
self.lastInputUserName = None
self.memberList.set_default_value(contactClass=User)
self.memberList.core = core
self.mpList.set_default_value(contactClass=MassivePlatform)
self.mpList.core = core
self.chatroomList.set_default_value(contactClass=Chatroom)
self.chatroomList.core = core
def dumps(self):
return {
'userName' : self.userName,
Expand All @@ -33,11 +43,14 @@ def loads(self, j):
self.userName = j.get('userName', None)
self.nickName = j.get('nickName', None)
del self.memberList[:]
for i in j.get('memberList', []): self.memberList.append(i)
for i in j.get('memberList', []):
self.memberList.append(i)
del self.mpList[:]
for i in j.get('mpList', []): self.mpList.append(i)
for i in j.get('mpList', []):
self.mpList.append(i)
del self.chatroomList[:]
for i in j.get('chatroomList', []): self.chatroomList.append(i)
for i in j.get('chatroomList', []):
self.chatroomList.append(i)
self.lastInputUserName = j.get('lastInputUserName', None)
def search_friends(self, name=None, userName=None, remarkName=None, nickName=None,
wechatAccount=None):
Expand Down
Loading

0 comments on commit 834e638

Please sign in to comment.