2 # -*- coding: utf-8 -*-
8 from datetime import datetime
11 from http.cookiejar import CookieJar
13 from html_parser import *
18 DateTime,Action,Nick1,Grade1,OldField1,NewField1,Nick2,Grade2,OldField2,NewField2,FloodField,FieldLossPercent,Text
19 Action is one of: JOIN, QUIT, WIN, LOSS, FLOOD
21 JOIN,Nirgal,Recrue,0,571628,,,,,,,Nirgal a rejoint l'alliance avec 571 628 cm²
22 QUIT,oncleblu,Chasseur,9940181,0,,,,,,,oncleblu a quité l'alliance avec 9 940 181 cm²
23 WIN,Nirgal,Chasseur,200000,257900,,,,,,,Nirgal a gagné 57 900 cm²
24 LOSS,Nirgal,Passeur 806,553624,442900,,,,,110724,20.00,Nirgal a perdu 110 724 cm² (20.00%)
25 FLOOD,filoux,Passeur 003,55813865,74225093,yosemite,Passeur 004,51142304,32731076,18411228,36.00,filoux a pris 18 411 228 cm² à yosemite (36.00%)
34 HOME = os.environ['HOME']
35 ARCHIVE = HOME + '/.fourmizzz/archive.py'
36 RESULT = HOME + '/.fourmizzz/results.log'
40 That function will read config.py in .fourmizzz directory
41 and set up globals SERVER, LOGIN, PASSWORD, and BASE_URL.
43 global SERVER, LOGIN, PASSWORD
45 CONFIG_TEMPLATE='''# Veuillez modifier les lignes ci dessous avec vos paramètres:
46 SERVER = 's1.fourmizzz.fr'
47 LOGIN = 'MonIdentifiant'
48 PASSWORD = 'MonMotDePasse'
51 sys.path.append(HOME+'/.fourmizzz')
55 CONFIG = HOME+'/.fourmizzz/config.py'
56 logging.fatal("No configuration file. Creating %s", CONFIG)
57 f = open(CONFIG, mode='w+', encoding='utf-8')
58 f.write(CONFIG_TEMPLATE)
60 logging.fatal("Please update this file with your details.")
62 SERVER = config.SERVER
64 PASSWORD = config.PASSWORD
65 BASE_URL = 'http://%s' % SERVER
67 def hide_password_from_log(txt):
68 return re.sub('mot_passe=.*', 'mot_passe=********', txt)
71 def httpopen(url, post_data=None):
73 log_post_data = hide_password_from_log(post_data)
74 post_data = post_data.encode('utf-8') # str->bytes
75 logging.debug('HTTP POST %s %s', url, log_post_data)
77 logging.debug('HTTP GET %s', url)
79 if __opener__ is None:
80 cookiejar = CookieJar()
81 __opener__ = urllib.request.build_opener()
82 __opener__.add_handler(urllib.request.HTTPCookieProcessor(cookiejar))
83 http_response = __opener__.open(url, post_data)
87 logging.debug('Waiting %s seconds', seconds)
91 return calendar.timegm(datetime.now().timetuple())
101 result = ('%03d' % d3) + result
103 result = ('%d' % d3) + result
107 def tdc_get(alliance_tag=None):
108 #httpresponse = httpopen(BASE_URL + '/')
109 #html = httpresponse.read().decode('utf-8')
112 httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s' % (SERVER, LOGIN, PASSWORD))
113 #httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s&connexion=Connexion' % (SERVER, LOGIN, PASSWORD))
114 html = httpresponse.read().decode('utf-8')
115 if "redirectReine" not in html:
116 logging.fatal("Impossible de s'authentifier. Vérifiez vos paramètres dans config.py")
121 #httpresponse = httpopen(BASE_URL + '/alliance.php?Membres')
122 #html = httpresponse.read().decode('utf-8')
127 httpresponse = httpopen(BASE_URL + '/alliance.php?Membres',
128 'xajax=membre&xajaxr='+str(timestamp()))
129 html = httpresponse.read().decode('utf-8')
133 root = html_parse(html)
134 table = get_elem(root, 'table')[0]
135 td = get_elem(table, 'td')[3]
136 table = get_elem(td, 'table')[0]
138 #print_idented_tree(table)
140 httpresponse = httpopen(BASE_URL + '/classementAlliance.php?alliance=%s' % alliance_tag)
141 html = httpresponse.read().decode('utf-8')
143 root = html_parse(html)
144 table = get_elem(root, 'table')[2]
146 #print_idented_tree(table)
149 for tr in get_elem(table, 'tr'):
150 row = get_elem(tr, 'td')
151 if not alliance_tag and len(row) != 10:
153 if alliance_tag and len(row) != 6:
156 #print_idented_tree(tr)
158 nick = get_merged_leaf_content(row[3])
159 tdc = get_merged_leaf_content(row[4]).replace(' ', '')
161 nick = get_merged_leaf_content(row[2])
162 tdc = get_merged_leaf_content(row[3]).replace(' ', '')
167 logging.debug('%s members - total tdc = %s cm²', len(summary), number_format(sum(summary.values())))
171 def tdc_compare(oldtdc, newtdc):
174 for nick in newtdc.keys():
175 told = oldtdc.get(nick, 0)
179 changes[nick] = { 'old': told, 'new': tnew, 'delta': tnew-told }
181 for nick in oldtdc.keys():
182 if nick not in newtdc:
185 changes[nick] = { 'old': told, 'new': 0, 'delta': -told }
186 #for nick, change in changes.items():
187 # print(nick, ' - ', change['old'], ' - ', change['new'], ' - ', change['delta'])
191 logging.info('No changes')
194 for nick in changes.keys():
195 delta = changes[nick]['delta']
197 continue # 0 is already process, <0 will be processed when nick swaps with nick2
198 for nick2 in changes.keys():
199 if changes[nick2]['delta'] == 0:
200 continue # already done
201 if changes[nick2]['delta'] != -delta:
202 continue # not the good one
203 percent = float(oldtdc[nick2] - newtdc[nick2]) / oldtdc[nick2] * 100.
204 txtchanges.append('%s a pris %s cm² à %s (%.2f%%)' % (nick, number_format(delta), nick2, percent))
205 changes[nick]['delta'] = 0
206 changes[nick2]['delta'] = 0
209 for nick, change in changes.items():
210 delta = change['delta']
213 percent = float(-delta) / oldtdc[nick] * 100.
214 txtchanges.append('%s a perdu %s cm² (%.2f%%)' % (nick, number_format(-delta), percent))
216 txtchanges.append("%s a quité l'alliance avec %s cm²" % (nick, number_format(-delta)))
219 txtchanges.append('%s a gagné %s cm²' % (nick, number_format(delta)))
221 txtchanges.append("%s a rejoint l'alliance avec %s cm²" % (nick, number_format(delta)))
223 for txtchange in txtchanges:
224 logging.info(txtchange)
227 if __name__ == '__main__':
228 from optparse import OptionParser
229 parser = OptionParser()
230 parser.add_option('-d', '-v', '--debug', '--verbose',
231 action='store_true', dest='debug', default=False,
233 parser.add_option('-q', '--quiet',
234 action='store_true', dest='quiet', default=False,
236 parser.add_option('-a', '--alliance',
238 help="alliance tag. default is to process player own alliance.")
239 parser.add_option('--dry-run',
240 action='store_true', dest='dryrun', default=False,
241 help="don't store result in archives.")
242 options, args = parser.parse_args()
245 loglevel = logging.DEBUG
247 loglevel = logging.WARNING
249 loglevel = logging.INFO
250 logging.basicConfig(filename=RESULT, level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z')
256 f = open(ARCHIVE, mode='r+', encoding='utf-8')
257 except IOError as err:
258 if err.errno == 2: # No such file or directory
259 logging.warning("No archive file, creating one.")
260 f = open(ARCHIVE, mode='w+', encoding='utf-8')
264 oldtdc = eval(f.read())
266 newtdc = tdc_get(options.alliance)
267 if oldtdc is not None:
268 tdc_compare(oldtdc, newtdc)
270 # Save archive only after processing, just in case it crashes
271 if not options.dryrun:
273 f.write(repr(newtdc))