diff --git a/db/item.tw.txt b/db/item.tw.txt index 6655ca5..44402c2 100644 --- a/db/item.tw.txt +++ b/db/item.tw.txt @@ -2,7 +2,9 @@ 2,BC回復藥,回復所有BC 3,假卡,如果對沒有被搶走的碎片使用假卡,可以阻止一次碎片被搶走。 20,卑彌呼醬印記,大量收集的話・・・ +24,戰鬥點數,大量收集的話・・・ 31,JOB:學生會長,請期待騎士團的實際安裝 +33,戰鬥點數,大量收集的話・・・ 38,不列顛糖果,大量收集的話・・・ 42,音符,大量收集的話・・・ 43,能量核心,大量收集的話・・・ @@ -10,6 +12,7 @@ 45,貓耳魔戒,大量收集的話・・・ 46,機密文件,大量收集的話・・・ 47,黃色小鴨,大量收集的話・・・ +50,商城商品,商城用 51,十香的好感度,提升十香的好感度的話・・・ 52,狂三的好感度,提升狂三的好感度的話・・・ 53,四糸乃的好感度,提升四糸乃的好感度的話・・・ @@ -20,4 +23,4 @@ 58,古之書碎片,據說收集到一定數量的話就會得到神秘的東西・・・ 59,月和藏寶圖,據說收集到明鏡月和島所有的藏寶圖的話・・・ 60,不列顛校徽,大量收集的話・・・ -63,四葉幸運草,據說找到的話會得到好運・・・ +63,四葉幸運草,據說找到的話會得到好運・・・ \ No newline at end of file diff --git a/db/revision.txt b/db/revision.txt index 9a8116e..50240af 100644 --- a/db/revision.txt +++ b/db/revision.txt @@ -1 +1,2 @@ -180,173 \ No newline at end of file +cn,180,179 +tw,173,157 \ No newline at end of file diff --git a/maclient.py b/maclient.py index b5ccbf8..09f8306 100644 --- a/maclient.py +++ b/maclient.py @@ -23,7 +23,7 @@ import maclient_player import maclient_network import maclient_logging -__version__=1.47 +__version__=1.48 #CONSTS: EXPLORE_BATTLE,NORMAL_BATTLE,WAKE_BATTLE=0,1,2 GACHA_FRIENNSHIP_POINT,GACHA_GACHA_TICKET,GACHA_11=1,2,4 @@ -146,7 +146,8 @@ def load_config(self): self.cfg_save_traffic=not self._read_config('system','save_traffic')=='0' self.cfg_greet_words=self._read_config('tactic','greet_words') or ( self.loc=='tw' and random.choice(['大家好.','問好']) or random.choice(['你好!','你好!请多指教!'])) - self.cfg_factor_getnew=not self._read_config('tactic','factor_getnew') == '0' + self.cfg_factor_getnew=not self._read_config('tactic','factor_getnew') == '0' + self.cfg_auto_update= not self._read_config('tactic','factor_getnew') == '0' logging.basicConfig(level=self._read_config('system','loglevel')) logging.setlogfile('events_%s.log'%self.loc) self.cfg_delay=float(self._read_config('system','delay')) @@ -216,6 +217,20 @@ def _dopost(self,urikey,postdata='',usecookie=True,setcookie=True,extraheader={' logging.error(du8('由于以上↑的原因,无法继续执行!')) self._exit(1) update_dt=self.player.update_all(dec) + #check revision update + if self.player.need_update[0] or self.player.need_update[1]: + if self.cfg_auto_update: + logging.info(du8('更新%s%s数据……'%( + ' 卡片' if self.player.need_update[0] else '', + ' 道具' if self.player.need_update[1] else '') )) + import maclient_update + crev,irev=maclient_update.update_master(self.loc,self.player.need_update,self.poster) + logging.info(du8('%s%s'%( + '卡片数据更新为rev.%s'%crev if crev else '', + '道具数据更新为rev.%s'%irev if irev else '') )) + self.player.need_update=False,False + else: + logging.warning(du8('检测到服务器游戏数据与游戏数据不一致,请手动更新数据库')) #update profile if not resp['error']: self.remoteHdl(method='PROFILE') @@ -679,9 +694,9 @@ def _explore_floor(self,area,floor=None): self._fairy_battle(info.fairy,type=EXPLORE_BATTLE) time.sleep(5.5) #回到秘境界面 - param='area_id=%s&check=1&floor_id=%s'%(area.id,floor.id) - if self._dopost('exploration/get_floor',postdata=param)[0]['error']: - return None,EXPLORE_ERROR + # param='area_id=%s&check=1&floor_id=%s'%(area.id,floor.id) + # if self._dopost('exploration/get_floor',postdata=param)[0]['error']: + # return None,EXPLORE_ERROR elif info.event_type=='2': logging.info(du8('碰到个傻X:'+info.encounter.name+' -> '+info.message)) time.sleep(1.5) diff --git a/maclient_cli.py b/maclient_cli.py index 38e53e6..d86d874 100644 --- a/maclient_cli.py +++ b/maclient_cli.py @@ -15,7 +15,7 @@ import maclient_network import maclient_remote import getpass -__version__=1.47 +__version__=1.48 du8=lambda str:str.decode('utf-8') def iter_printer(l,sep='\n'): cnt=1 @@ -225,31 +225,38 @@ def macs(uri,header={},body='',method='GET'): print(du8('已保存~')) maclient1.load_config() elif ch =='6': - getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ - and sys.path[0].decode(sys.getfilesystemencoding()) \ - or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build - rev=open(opath.join(getPATH0(),'db/revision.txt'),'r').read().strip('\n').split(',') - h={'User-Agent':'maclient/%f'%__version__} - upd=macs('/db/revision.txt')[1].strip('\n').split(',') - if upd[0]!=rev[0] or upd[1]!=rev[1]: - if upd[1]!=rev[1]: - print(du8('正在更新台服数据……')) - c=macs('/db/card.tw.txt')[1] - open(opath.join(getPATH0(),'db/card.tw.txt'),'w').write(c) - print(du8('卡组更新成功XD')) - c=macs('/db/item.tw.txt')[1] - open(opath.join(getPATH0(),'db/item.tw.txt'),'w').write(c) - if upd[0]!=rev[0]: - print(du8('正在更新国服数据……')) - c=macs('/db/card.cn.txt')[1] - open(opath.join(getPATH0(),'db/card.cn.txt'),'w').write(c) - print(du8('卡组更新成功XD')) - c=macs('/db/item.cn.txt')[1] - open(opath.join(getPATH0(),'db/item.cn.txt'),'w').write(c) - print(du8('道具更新成功XD')) - open(opath.join(getPATH0(),'db/revision.txt'),'w').write(','.join(upd)) - else: - print(du8('木有更新www')) + logging.info(du8('将强制重新从服务器下载数据……')) + import maclient_update + crev,irev=maclient_update.update_master(maclient1.loc,(True,True),maclient1.poster) + logging.info(du8('%s%s'%( + '卡片数据更新为rev.%s'%crev if crev else '', + '道具数据更新为rev.%s'%irev if irev else '') )) + # the following is deprecated + # getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ + # and sys.path[0].decode(sys.getfilesystemencoding()) \ + # or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build + # rev=open(opath.join(getPATH0(),'db/revision.txt'),'r').read().strip('\n').split(',') + # h={'User-Agent':'maclient/%f'%__version__} + # upd=macs('/db/revision.txt')[1].strip('\n').split(',') + # if upd[0]!=rev[0] or upd[1]!=rev[1]: + # if upd[1]!=rev[1]: + # print(du8('正在更新台服数据……')) + # c=macs('/db/card.tw.txt')[1] + # open(opath.join(getPATH0(),'db/card.tw.txt'),'w').write(c) + # print(du8('卡组更新成功XD')) + # c=macs('/db/item.tw.txt')[1] + # open(opath.join(getPATH0(),'db/item.tw.txt'),'w').write(c) + # if upd[0]!=rev[0]: + # print(du8('正在更新国服数据……')) + # c=macs('/db/card.cn.txt')[1] + # open(opath.join(getPATH0(),'db/card.cn.txt'),'w').write(c) + # print(du8('卡组更新成功XD')) + # c=macs('/db/item.cn.txt')[1] + # open(opath.join(getPATH0(),'db/item.cn.txt'),'w').write(c) + # print(du8('道具更新成功XD')) + # open(opath.join(getPATH0(),'db/revision.txt'),'w').write(','.join(upd)) + # else: + # print(du8('木有更新www')) elif ch =='7': sys.exit(0) diff --git a/maclient_logging.py b/maclient_logging.py index 9a66388..2fa2037 100644 --- a/maclient_logging.py +++ b/maclient_logging.py @@ -44,6 +44,7 @@ def __init__(self, *args, **kwargs): self.__set_sleep_color = lambda: __write('\033[36m') self.__set_bright_color = lambda: __write('\033[32m') self.__reset_color = lambda: __write('\033[0m') + self.logfile=None def setlogfile(self,f): self.logfile=open(f,'a') @classmethod @@ -64,7 +65,8 @@ def debug(self, fmt, *args, **kwargs): self.__reset_color() def info(self, fmt, *args, **kwargs): puretext=self.log('INFO', fmt, *args) - self.logfile.write(puretext) + if self.logfile: + self.logfile.write(puretext) def sleep(self, fmt, *args, **kwargs): self.__set_sleep_color() self.log('SLEEP', fmt, *args, **kwargs) diff --git a/maclient_player.py b/maclient_player.py index 11c3093..06aa10b 100644 --- a/maclient_player.py +++ b/maclient_player.py @@ -12,162 +12,175 @@ from xml2dict import XML2Dict class player(object): - def __init__(self,login_xml,loc): - #[:2]可以让cn2变成cn以使用同一个卡组/道具数据 - self.card=card(loc[:2]) - self.item=item(loc[:2]) - self.update_all(login_xml) - self.loc=loc - self.fairy={'id':0,'alive':False} - self.id='0' - object.__init__(self) + def __init__(self,login_xml,loc): + #[:2]可以让cn2变成cn以使用同一个卡组/道具数据 + self.card=card(loc[:2]) + self.item=item(loc[:2]) + self.loc=loc + self.fairy={'id':0,'alive':False} + self.id='0' + self.checked_update=False + self.need_update=False,False + self.update_all(login_xml) + object.__init__(self) - def update_all(self,xmldata): - if xmldata=='': - return '',False - else: - res=[self._update_data(xmldata),self._update_card(xmldata),self._update_item(xmldata)] - return '%s %s %s'%(res[0][0],res[1][0],res[2][0]),res[1][1] + def update_all(self,xmldata): + if xmldata=='': + return '',False + else: + res=[self._update_data(xmldata),self._update_card(xmldata),self._update_item(xmldata)] - def calc_ap_bc(self): - #正常计算AP BC 变动 - for key in ['ap','bc']: - if self.hasattr(key): - getattr(self,key)['current']+=(time.time()-int(getattr(self,key)['current_time']))/int(getattr(self,key)['interval_time']) - if getattr(self,key)['current']>=getattr(self,key)['max']: - getattr(self,key)['current']=getattr(self,key)['max'] + return '%s %s %s'%(res[0][0],res[1][0],res[2][0]),res[1][1] - def _update_data(self,xmldata): - self.calc_ap_bc() - try: - xmlresp = XML2Dict().fromstring(xmldata).response - if 'login' in xmlresp.body: - self.id=xmlresp.body.login.user_id - self.playerdata=xmlresp.header.your_data - except: - return 'Profile no update',False - try: - for key in ['ap','bc']: - if not self.hasattr(key): - self.__setattr__(key,{}) - for attr in self.playerdata[key]: - getattr(self,key)[attr]=int(self.playerdata[key][attr].value) - for key in ['gold','friendship_point']: - self.__setattr__(key,int(self.playerdata[key].value)) - self.lv=self.playerdata['town_level'].value - self.leader_sid=self.playerdata['leader_serial_id'].value - self.name=self.playerdata['name'].value - except KeyError: - pass - #print self.ap.current,self.bc.current - return 'AP:%d/%d BC:%d/%d G:%d FP:%d'%(self.ap['current'],self.ap['max'],self.bc['current'],self.bc['max'],self.gold,self.friendship_point),True + def calc_ap_bc(self): + #正常计算AP BC 变动 + for key in ['ap','bc']: + if self.hasattr(key): + getattr(self,key)['current']+=(time.time()-int(getattr(self,key)['current_time']))/int(getattr(self,key)['interval_time']) + if getattr(self,key)['current']>=getattr(self,key)['max']: + getattr(self,key)['current']=getattr(self,key)['max'] - def _update_card(self,xmldata): - try: - xml = XML2Dict().fromstring(xmldata) - self.card.update(xml.response.header.your_data.owner_card_list.user_card) - return 'CARDs:%d'%self.card.count,True - except : - return '',False + def _update_data(self,xmldata): + self.calc_ap_bc() + try: + xmlresp = XML2Dict().fromstring(xmldata).response + if 'login' in xmlresp.body: + self.id=xmlresp.body.login.user_id + self.playerdata=xmlresp.header.your_data + except: + return 'Profile no update',False + try: + for key in ['ap','bc']: + if not self.hasattr(key): + self.__setattr__(key,{}) + for attr in self.playerdata[key]: + getattr(self,key)[attr]=int(self.playerdata[key][attr].value) + for key in ['gold','friendship_point']: + self.__setattr__(key,int(self.playerdata[key].value)) + self.lv=self.playerdata['town_level'].value + self.leader_sid=self.playerdata['leader_serial_id'].value + self.name=self.playerdata['name'].value + except KeyError: + pass + if not self.checked_update: + # try: + cardrev=int(xmlresp.header.revision.card_rev) + itemrev=int(xmlresp.header.revision.item_rev) + # except KeyError: + # pass + # else: + import maclient_update + self.need_update=maclient_update.check_revision(self.loc,(cardrev,itemrev)) + self.checked_update=True#只检查一次 + #print self.ap.current,self.bc.current + return 'AP:%d/%d BC:%d/%d G:%d FP:%d'%(self.ap['current'],self.ap['max'],self.bc['current'],self.bc['max'],self.gold,self.friendship_point),True - def _update_item(self,xmldata): - try: - xml = XML2Dict().fromstring(xmldata) - self.item.update(xml.response.header.your_data.itemlist) - return 'Items updated',True - except: - return '',False - def hasattr(self,key): - try: - getattr(self,key) - except AttributeError: - return False - else: - return True - def __setattr__(self,key,val): - return object.__setattr__(self,key,val) + def _update_card(self,xmldata): + try: + xml = XML2Dict().fromstring(xmldata) + self.card.update(xml.response.header.your_data.owner_card_list.user_card) + return 'CARDs:%d'%self.card.count,True + except : + return '',False + + def _update_item(self,xmldata): + try: + xml = XML2Dict().fromstring(xmldata) + self.item.update(xml.response.header.your_data.itemlist) + return 'Items updated',True + except: + return '',False + def hasattr(self,key): + try: + getattr(self,key) + except AttributeError: + return False + else: + return True + def __setattr__(self,key,val): + return object.__setattr__(self,key,val) class item(object): - def __init__(self,loc): - self.getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ - and sys.path[0].decode(sys.getfilesystemencoding()) \ - or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build - self.name={} - for c in open(opath.join(self.getPATH0(),'db/item.%s.txt'%loc)).read().split('\n'): - c=c.split(',') - if c!=['']: - self.name[int(c[0])]=c[1] - self.count={} - def update(self,itemdict): - for it in itemdict: - try: - self.count[int(it.item_id)]=it.num - except KeyError: - self.count[int(it.item_id)]='0' + def __init__(self,loc): + self.getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ + and sys.path[0].decode(sys.getfilesystemencoding()) \ + or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build + self.name={} + for c in open(opath.join(self.getPATH0(),'db/item.%s.txt'%loc)).read().split('\n'): + c=c.split(',') + if c!=['']: + self.name[int(c[0])]=c[1] + self.count={} + def update(self,itemdict): + for it in itemdict: + try: + self.count[int(it.item_id)]=it.num + except KeyError: + self.count[int(it.item_id)]='0' class card(object): - def __init__(self,loc): - self.getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ - and sys.path[0].decode(sys.getfilesystemencoding()) \ - or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build - self.db={} - for c in open(opath.join(self.getPATH0(),'db/card.%s.txt'%loc)).read().split('\n'): - c=c.split(',') - if c!=['']: - self.db[int(c[0])]=[c[1],int(c[2]),int(c[3])] - self.count=0 - - def update(self,carddict): - self.cards=carddict - self.count=len(self.cards) - #print self.cid('124') - def _found_card_by_value(self,key,value): - res=[] - for i in self.cards: - if i[key].value==value: - res.append(i) - return res - def sid(self,sid): - return self._found_card_by_value('serial_id',sid)[0] - def cid(self,cid): - return self._found_card_by_value('master_card_id',cid) + def __init__(self,loc): + self.getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ + and sys.path[0].decode(sys.getfilesystemencoding()) \ + or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build + self.db={} + for c in open(opath.join(self.getPATH0(),'db/card.%s.txt'%loc)).read().split('\n'): + c=c.split(',') + if c!=['']: + self.db[int(c[0])]=[c[1],int(c[2]),int(c[3])] + self.count=0 + + def update(self,carddict): + self.cards=carddict + self.count=len(self.cards) + #print self.cid('124') + def _found_card_by_value(self,key,value): + res=[] + for i in self.cards: + if i[key].value==value: + res.append(i) + return res + def sid(self,sid): + return self._found_card_by_value('serial_id',sid)[0] + def cid(self,cid): + return self._found_card_by_value('master_card_id',cid) if __name__=='__main__': - if len(sys.argv)>2: - input_path=sys.argv[1]#.replace("\\","\\\\") - output_dir=sys.argv[2]#.replace("\\","\\\\") - else: - input_path=r'E:\ACG\GameArchive\MA\com.square_enix.million_tw\files\save\download' - output_dir-r'E:\ACG\GameArchive\MA\com.square_enix.million_tw\files\save\decrypt' - filelist=[] - if os.path.isdir(input_path): - for root,dirs,files in os.walk(input_path): - for f in files: - filelist.append(os.path.join(root,f)) - else: - filelist=[input_path] - for i in filelist: - if not os.path.isdir(i): - save=i.replace(os.path.split(input_path)[0],output_dir) - decrypt_file(i,save) - # #import binascii - # #hexlify=lambda x: binascii.hexlify(x) - # print decode_param('S=tAS5lPt7ftw8HlSUflkJFA%3D%3D%0A&login_id=8lIlKXItI6T3p7zAORJJSw%3D%3D%0A&password=v%2FCxxyFKqD5NahTXKACSkg%3D%3D%0A&app=dpa7%2FriPmmGftWfXGdEv2Q%3D%3D%0A&token=fRqY08WorSorOWR8188aGceoMhi1v5NUjKV9Vu4SspgVyyotBRSo%2Bj%2FpYH3NxSS5p96kBK2%2FQz2N%0AGmf0rHmspgT9DiDBH4wkSvpAJdbRExFM8yxS41SPimTpl99QmVCv0fhSOV8Kztx9eseMD4jbWbcU%0AXthkY4ALLLFdZ3xpnJbpOxFiQku6Ovyw0MnSG4dxDsy4n6ybmIrPin3W%2BSU%2FLr7Wk0s5RXJF3iTI%0AQDTmN1SGmmZM1kqReNhMdx74EiYxvRXr51EsPJEvDSPfu%2F542DM2By584uiANhpify5iFRXZisI7%0AyGZp8QGNr1NIego5aBG8KsXmX%2BgzcaAx3wL8nw%3D%3D%0A') - # #print decode_param('notice_id=bfOK21o6f0flO9OlO1dRkByUK8bPymhd4cjvNVkto3Q%3D%0A') - # #area_id=90115 - # #area_id=90115%0A&check=1%0A&floor_id=3 - # #area_id=90115%0A&auto_build=1%0A&floor_id=3 - # import random - # p='invitation_id=8204a&login_id=%s¶m=&password=%s¶m=%s'%('goodevening','zcn19920492','35'+(''.join([str(random.randint(0,10)+i-i) for i in range(10)]))) - # print encode_param(p),len(encode_param(p)) - # #Million/100 (Samsung; Gallaxy S; 4.2) generic/Gallaxy S/Gallaxy S:4.2/stock/com.littlewithe.20130402.good/stable-keys - # #print c.db['cn']['72'] - # #knight_id=0%0A&move=1%0A&parts_id=0 - # #S=nosessionid&login_id=zzh930916&password=19930917&app=and&token=BubYIgiyDYTFUifydHIoIOGBiujgRzrEFUIbIKOHniHIoihoiHasbdhasbdUIUBujhbjhjBJKJBb - # #59247865 - # #xmld=open(r'D:\Dev\Python\Workspace\maClient\login','r').read() - # #pl=player(xmld) - # #print pl.card.cid('9999') - + if len(sys.argv)>2: + input_path=sys.argv[1]#.replace("\\","\\\\") + output_dir=sys.argv[2]#.replace("\\","\\\\") + else: + input_path=r'E:\ACG\GameArchive\MA\com.square_enix.million_tw\files\save\download' + output_dir-r'E:\ACG\GameArchive\MA\com.square_enix.million_tw\files\save\decrypt' + filelist=[] + if os.path.isdir(input_path): + for root,dirs,files in os.walk(input_path): + for f in files: + filelist.append(os.path.join(root,f)) + else: + filelist=[input_path] + for i in filelist: + if not os.path.isdir(i): + save=i.replace(os.path.split(input_path)[0],output_dir) + decrypt_file(i,save) + # #import binascii + # #hexlify=lambda x: binascii.hexlify(x) + # print decode_param('S=tAS5lPt7ftw8HlSUflkJFA%3D%3D%0A&login_id=8lIlKXItI6T3p7zAORJJSw%3D%3D%0A&password=v%2FCxxyFKqD5NahTXKACSkg%3D%3D%0A&app=dpa7%2FriPmmGftWfXGdEv2Q%3D%3D%0A&token=fRqY08WorSorOWR8188aGceoMhi1v5NUjKV9Vu4SspgVyyotBRSo%2Bj%2FpYH3NxSS5p96kBK2%2FQz2N%0AGmf0rHmspgT9DiDBH4wkSvpAJdbRExFM8yxS41SPimTpl99QmVCv0fhSOV8Kztx9eseMD4jbWbcU%0AXthkY4ALLLFdZ3xpnJbpOxFiQku6Ovyw0MnSG4dxDsy4n6ybmIrPin3W%2BSU%2FLr7Wk0s5RXJF3iTI%0AQDTmN1SGmmZM1kqReNhMdx74EiYxvRXr51EsPJEvDSPfu%2F542DM2By584uiANhpify5iFRXZisI7%0AyGZp8QGNr1NIego5aBG8KsXmX%2BgzcaAx3wL8nw%3D%3D%0A') + # #print decode_param('notice_id=bfOK21o6f0flO9OlO1dRkByUK8bPymhd4cjvNVkto3Q%3D%0A') + # #area_id=90115 + # #area_id=90115%0A&check=1%0A&floor_id=3 + # #area_id=90115%0A&auto_build=1%0A&floor_id=3 + # import random + # p='invitation_id=8204a&login_id=%s¶m=&password=%s¶m=%s'%('goodevening','zcn19920492','35'+(''.join([str(random.randint(0,10)+i-i) for i in range(10)]))) + # print encode_param(p),len(encode_param(p)) + # #Million/100 (Samsung; Gallaxy S; 4.2) generic/Gallaxy S/Gallaxy S:4.2/stock/com.littlewithe.20130402.good/stable-keys + # #print c.db['cn']['72'] + # #knight_id=0%0A&move=1%0A&parts_id=0 + # #S=nosessionid&login_id=zzh930916&password=19930917&app=and&token=BubYIgiyDYTFUifydHIoIOGBiujgRzrEFUIbIKOHniHIoihoiHasbdhasbdUIUBujhbjhjBJKJBb + # #59247865 + # #xmld=open(r'D:\Dev\Python\Workspace\maClient\login','r').read() + # #pl=player(xmld) + # #print pl.card.cid('9999') + diff --git a/maclient_update.py b/maclient_update.py new file mode 100644 index 0000000..5f2efac --- /dev/null +++ b/maclient_update.py @@ -0,0 +1,86 @@ +#!/usr/bin/env python +# coding:utf-8 +# maclient master data updater +# Contributor: +# fffonion +import os +import os.path as opath +import sys +from xml2dict import XML2Dict + +getPATH0=lambda:opath.split(sys.argv[0])[1].find('py') != -1\ + and sys.path[0].decode(sys.getfilesystemencoding()) \ + or sys.path[1].decode(sys.getfilesystemencoding())#pyinstaller build + +def get_revision(loc): + local_revs=open(opath.join(getPATH0(),'db/revision.txt')).read().split('\n') + rev=None + for r in local_revs: + r=r.split(',') + if r[0]==loc: + rev=r + break + if not rev: + raise KeyError('No server revision data found for "%s"'%loc) + return rev + +def save_revision(loc,cardrev=None,itemrev=None): + rev_str=open(opath.join(getPATH0(),'db/revision.txt')).read() + local_revs=rev_str.split('\n') + rev=None + for r in local_revs: + rl=r.split(',') + if rl[0]==loc: + rev=rl + break + if not rev: + raise KeyError('No server revision data found for "%s"'%loc) + if cardrev: + rev[1]=str(cardrev) + if itemrev: + rev[2]=str(itemrev) + rev_str=rev_str.replace(r,','.join(rev)) + open(opath.join(getPATH0(),'db/revision.txt'),'w').write(rev_str) + +def check_revision(loc,rev_tuple): + rev=get_revision(loc) + if rev: + return rev_tuple[0]>float(rev[1]),rev_tuple[1]>float(rev[2]) + else: + return False,False + +def update_master(loc,need_update,poster): + new_rev=[None,None] + if need_update[0]: + a,b=poster.post('masterdata/card/update',postdata='%s&revision=0'%poster.cookie,noencrypt=True) + resp=XML2Dict().fromstring(b.replace('&','--').replace('--#','&#')).response + cards=resp.body.master_data.master_card_data.card + strs=[] + for c in cards: + strs.append('%s,%s,%s,%s,%s,%s,%s,%s'%( + c.master_card_id, + c.name, + c.rarity, + c.cost, + str(c.char_description).strip('\n').strip(' ').replace('\n','\\n'), + c.skill_kana, + c.skill_name, + str(c.skill_description).replace('\n','\\n'))) + open(opath.join(getPATH0(),'db/card.%s.txt'%loc),'w').write('\n'.join(strs)) + new_rev[0]=resp.header.revision.card_rev + save_revision(loc,cardrev=new_rev[0]) + if need_update[1]: + a,b=poster.post('masterdata/item/update',postdata='%s&revision=0'%poster.cookie,noencrypt=True) + resp=XML2Dict().fromstring(b).response + itmes=resp.body.master_data.master_item_data.item_info + strs=[] + for c in itmes: + strs.append('%s,%s,%s'%( + c.item_id, + c.name, + c.explanation + )) + open(opath.join(getPATH0(),'db/item.%s.txt'%loc),'w').write('\n'.join(strs)) + new_rev[1]=resp.header.revision.item_rev + save_revision(loc,itemrev=new_rev[1]) + return new_rev \ No newline at end of file