759b614b550f7136d1a7c1833c5363051f6e7f38
[fourmizzz.git] / members.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 #
4 # Last version is available at svn://svn.nirgal.com/kod/fourmizzz/
5 # Licensed under GPL
6
7 import os
8 import time
9 import re
10 import logging
11 from datetime import datetime
12 import calendar
13 import random
14 import urllib.request
15 from http.cookiejar import CookieJar
16
17 from html_parser import *
18 import htmlentities
19
20 """
21 csv file format:
22 DateTime,Action,Nick1,Grade1,OldField1,NewField1,Nick2,Grade2,OldField2,NewField2,FloodField,FieldLossPercent,Text
23 Action is one of: JOIN, QUIT, WIN, LOSS, FLOOD, NOOP, ACT, ANTHILL, TECHNO, GRADE
24
25 Exemples:
26 NOOP,,,,,,,,,,,Pas de changement dans le TdC
27 JOIN,Nirgal,Recrue,0,571628,,,,,,,Nirgal a rejoint l'alliance avec 571 628 cm² 
28 QUIT,oncleblu,Chasseur,9940181,0,,,,,,,oncleblu a quité l'alliance avec 9 940 181 cm² 
29 WIN,Nirgal,Chasseur,200000,257900,,,,,,,Nirgal a gagné 57 900 cm² 
30 LOSS,Nirgal,Passeur 806,553624,442900,,,,,110724,20.00,Nirgal a perdu 110 724 cm² (20.00%) 
31 FLOOD,filoux,Passeur 003,55813865,74225093,yosemite,Passeur 004,51142304,32731076,18411228,36.00,filoux a pris 18 411 228 cm² à yosemite (36.00%)
32 FLOOD,Nick1,Grade1,100,102,Nick2,Grade2,100,99,1,1.00,Nick1 a pris 1 cm² à Nick2 (1.00%)
33 FLOOD,Nick1,Grade1,100,102,Nick3,Grade3,100,99,1,1.00,Nick1 a pris 1 cm² à Nick3 (1.00%)
34
35 ACT,Nick1,Grade1,Actif,En vacances,,,,,,,Nick1 est maintenant en vacances
36 COLON,Nick1,Grade1,False,True,,,,,,,Nick1 s'est fait colonisé
37 COLON,Nick1,Grade1,True,False,,,,,,,Nick1 n'est plus colonisé
38
39 ANTHILL,Nick1,Grade1,199,200,,,,,,,La fourmilière de Nick1 a atteint le niveau 200
40 TECHNO,Nick1,Grade1,199,200,,,,,,,La technologie Nick1 a atteint le niveau 200
41
42 GRADE,Nick1,Recrue,Recrue,Passer 806,,,,,,,Nick1 est maintenant Passeur 806
43
44 Note that in last 2 FLOOD lines exemple, NewField1 is 102 that is different from 100+1 because of multiple floods.
45 """
46
47 # globals:
48 #BASE_DIRECTORY
49 #SERVER
50 #LOGIN
51 #PASSWORD
52 #BASE_URL
53 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
54
55 def read_config(config_dir):
56     '''
57     That function will read config.py in .fourmizzz directory
58     and set up globals SERVER, LOGIN, PASSWORD, and BASE_URL.
59     '''
60     global SERVER, LOGIN, PASSWORD
61     global BASE_URL
62     CONFIG_TEMPLATE='''# Veuillez modifier les lignes ci dessous avec vos paramètres:
63 SERVER = 's1.fourmizzz.fr'
64 LOGIN = 'MonIdentifiant'
65 PASSWORD = 'MonMotDePasse'
66     '''
67
68     sys.path.append(config_dir)
69     try:
70         import config
71     except ImportError:
72         config_filename = os.path.join(config_dir, 'config.py')
73         logging.fatal("No configuration file. Creating %s", config_filename)
74         f = open(config_filename, mode='w+', encoding='utf-8')
75         f.write(CONFIG_TEMPLATE)
76         f.close()
77         logging.fatal("Please update this file with your details.")
78         sys.exit(1)
79     SERVER = config.SERVER
80     LOGIN = config.LOGIN
81     PASSWORD = config.PASSWORD
82     BASE_URL = 'http://%s' % SERVER
83
84 def hide_password_from_log(txt):
85     return re.sub('mot_passe=.*', 'mot_passe=********', txt)
86
87 __opener__ = None
88 def httpopen(url, post_data=None):
89     if post_data:
90         log_post_data = hide_password_from_log(post_data)
91         post_data = post_data.encode('utf-8') # str->bytes
92         logging.debug('HTTP POST %s %s', url, log_post_data)
93     else:
94         logging.debug('HTTP GET %s', url)
95     global __opener__
96     if __opener__ is None:
97         cookiejar = CookieJar()
98         __opener__ = urllib.request.build_opener()
99         __opener__.add_handler(urllib.request.HTTPCookieProcessor(cookiejar))
100     http_response = __opener__.open(url, post_data)
101     return http_response
102
103 def sleep(seconds):
104     logging.debug('Waiting %s seconds', seconds)
105     time.sleep(seconds)
106
107 def timestamp():
108     return calendar.timegm(datetime.now().timetuple())
109
110 def number_format(i):
111     result = ''
112     while i:
113         if result:
114             result = ' ' + result
115         d3 = i % 1000
116         i = i//1000
117         if i: # there will be something else left of that
118             result = ('%03d' % d3) + result
119         else:
120             result = ('%d' % d3) + result
121     return result
122
123
124 def members_fetch(alliance_tag=None):
125     #httpresponse = httpopen(BASE_URL + '/')
126     #html = httpresponse.read().decode('utf-8')
127     #print(html)
128    
129     httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s' % (SERVER, LOGIN, PASSWORD))
130     #httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s&connexion=Connexion' % (SERVER, LOGIN, PASSWORD))
131     html = httpresponse.read().decode('utf-8')
132     if "redirectReine" not in html:
133         logging.fatal("Impossible de s'authentifier. Vérifiez vos paramètres dans config.py")
134         sys.exit(1)
135     #print('-'*80)
136     #print(html)
137     
138     #httpresponse = httpopen(BASE_URL + '/alliance.php?Membres')
139     #html = httpresponse.read().decode('utf-8')
140     #print('-'*80)
141     #print(html)
142
143     if not alliance_tag:
144         httpresponse = httpopen(BASE_URL + '/alliance.php?Membres',
145             'xajax=membre&xajaxr='+str(timestamp()))
146         html = httpresponse.read().decode('utf-8')
147         #print('-'*80)
148         #print(html)
149
150         root = html_parse(html)
151         table = get_elem(root, 'table')[0]
152         td = get_elem(table, 'td')[3]
153         table = get_elem(td, 'table')[0]
154         #print('-'*80)
155         #print_idented_tree(table)
156     else:
157         httpresponse = httpopen(BASE_URL + '/classementAlliance.php?alliance=%s' % alliance_tag)
158         html = httpresponse.read().decode('utf-8')
159         
160         root = html_parse(html)
161         table = get_elem(root, 'table')[2]
162         #print('-'*80)
163         #print_idented_tree(table)
164
165     members = {} # NEW
166     for tr in get_elem(table, 'tr'):
167         row = get_elem(tr, 'td')
168         #print('-'*10)
169         #print_idented_tree(tr)
170         if not alliance_tag:
171             if len(row) != 10:
172                 continue
173             grade = get_merged_leaf_content(row[2])
174             nick = get_merged_leaf_content(row[3])
175             field = int(get_merged_leaf_content(row[4]).replace(' ', ''))
176             techno = int(get_merged_leaf_content(row[5]))
177             anthill = int(get_merged_leaf_content(row[6]))
178             active = get_elem(row[7], 'img')[0].attributes['alt']
179             colonized = len(get_elem(row[8], 'img')) == 1
180             #print(nick, grade, field, techno, anthill, active, colonized)
181
182         else:
183             if len(row) != 6:
184                 continue
185             grade = get_merged_leaf_content(row[1])
186             nick = get_merged_leaf_content(row[2])
187             field = int(get_merged_leaf_content(row[3]).replace(' ', ''))
188             techno = int(get_merged_leaf_content(row[4]))
189             anthill = int(get_merged_leaf_content(row[5]))
190             active = None
191             colonized = None
192             #print(nick, grade, field, techno, anthill)
193
194         members[nick] = {
195             'grade': grade,
196             'field': field,
197             'techno': techno,
198             'anthill': anthill,
199             'active': active,
200             'colonized': colonized,
201         }
202         #print(members[nick])
203
204     logging.debug('%s members - total field = %s cm²', len(members), number_format(sum([x['field'] for x in members.values()])))
205     return members
206
207
208 def copy_existing_data(oldmembers, newmembers):
209     '''
210     Check if newmembers contains some keys and if missing, copy them from
211     oldmembers:
212     colonized, active: if alliance is forced, these keys are not fetched
213     x, y: only fetch them when neded.
214     '''
215     for nick, data in newmembers.items():
216         for key in ['colonized', 'active', 'x', 'y' ]:
217             if data.get(key, None) is None:
218                 # missing or None
219                 value = oldmembers.get(nick, {}).get(key, None)
220                 newmembers[nick][key] = value
221
222 def members_to_field(members):
223     """
224     Takes a full information dict "members"
225     Returns a simple dict with nick->field
226     """
227     fields  = {}
228     for nick, data in members.items():
229         fields[nick] = data['field']
230     return fields
231
232
233 def publish_line(csvfile, text, **args):
234     csvline = text.format(**args)
235     logging.info(csvline.split(',')[-1])
236     if not options.dryrun:
237         csvfile.write(time.strftime(DATETIME_FORMAT)+','+csvline+'\n')
238
239 def field_compare(oldmembers, newmembers, csvfile):
240     
241     oldfield = members_to_field(oldmembers)
242     newfield = members_to_field(newmembers)
243
244     changes = {}
245
246     for nick in newfield.keys():
247         told = oldfield.get(nick, 0)
248         tnew = newfield[nick]
249         if told == tnew:
250             continue
251         changes[nick] = { 'old': told, 'new': tnew, 'delta': tnew-told }
252     
253     for nick in oldfield.keys():
254         if nick not in newfield:
255             told = oldfield[nick]
256             tnew = 0
257             changes[nick] = { 'old': told, 'new': 0, 'delta': -told }
258     #for nick, change in changes.items():
259     #    print(nick, ' - ', change['old'], ' - ', change['new'], ' - ', change['delta'])
260     #print
261
262     if not len(changes):
263         publish_line(csvfile, 'NOOP,,,,,,,,,,,No changes')
264  
265     for nick in changes.keys():
266         delta = changes[nick]['delta']
267         if delta <= 0:
268             continue # 0 is already process, <0 will be processed when nick swaps with nick2
269         for nick2 in changes.keys():
270             if changes[nick2]['delta'] == 0:
271                 continue # already done
272             if changes[nick2]['delta'] != -delta:
273                 continue # not the good one
274             percent = float(oldfield[nick2] - newfield[nick2]) / oldfield[nick2] * 100.
275             publish_line(csvfile, 
276                 'FLOOD,{nick1},{grade1},{oldfield1},{newfield1},{nick2},{grade2},{oldfield2},{newfield2},{deltafield},{percent},{nick1} a pris {nicedeltafield} cm² à {nick2} ({percent:.2f}%)',
277                 nick1=nick,
278                 grade1=newmembers[nick].get('grade', ''),
279                 oldfield1=oldfield[nick],
280                 newfield1=newfield[nick],
281                 nick2=nick2,
282                 grade2=newmembers[nick2].get('grade', ''),
283                 oldfield2=oldfield[nick2],
284                 newfield2=newfield[nick2],
285                 deltafield=delta,
286                 nicedeltafield= number_format(delta),
287                 percent=percent,
288                 )
289             changes[nick]['delta'] = 0
290             changes[nick2]['delta'] = 0
291
292     for nick, change in changes.items():
293         delta = change['delta']
294         if delta < 0:
295             if nick in newfield:
296                 percent = float(-delta) / oldfield[nick] * 100.
297                 publish_line(csvfile, 
298                     'LOSS,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},{percent},{nick1} a perdu {nicedeltafield} cm² ({percent:.2f}%)',
299                     nick1=nick,
300                     grade1=newmembers[nick].get('grade', ''),
301                     oldfield1=oldfield[nick],
302                     newfield1=newfield[nick],
303                     deltafield=-delta,
304                     nicedeltafield=number_format(-delta),
305                     percent=percent,
306                     )
307             else:
308                 publish_line(csvfile, 
309                     'QUIT,{nick1},{grade1},{oldfield1},0,,,,,{deltafield},,{nick1} a quité l\'alliance avec {nicedeltafield} cm²',
310                     nick1=nick,
311                     grade1=oldmembers[nick].get('grade', ''),
312                     oldfield1=oldfield[nick],
313                     deltafield=-delta,
314                     nicedeltafield=number_format(-delta),
315                     )
316         elif delta > 0:
317             if nick in oldfield:
318                 publish_line(csvfile, 
319                     'WIN,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},,{nick1} a gagné {nicedeltafield} cm²',
320                     nick1=nick,
321                     grade1=newmembers[nick].get('grade', ''),
322                     oldfield1=oldfield[nick],
323                     newfield1=newfield[nick],
324                     deltafield=delta,
325                     nicedeltafield=number_format(delta),
326                     )
327             else:
328                 publish_line(csvfile, 
329                     'JOIN,{nick1},{grade1},0,{newfield1},,,,,{deltafield},,{nick1} a rejoint l\'alliance avec {nicedeltafield} cm²',
330                     nick1=nick,
331                     grade1=newmembers[nick].get('grade', ''),
332                     newfield1=newfield[nick],
333                     deltafield=delta,
334                     nicedeltafield=number_format(delta),
335                     )
336
337 def activity_compare(oldmembers, newmembers, csvfile):
338     for nick, data in newmembers.items():
339         newa = data.get('active', None)
340         olda = oldmembers.get(nick, {}).get('active', None)
341         if newa and olda and newa != olda:
342             publish_line(csvfile, 
343                 'ACT,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} est maintenant {lowernewdata1}',
344                 nick1=nick,
345                 grade1=newmembers[nick]['grade'],
346                 olddata1=olda,
347                 newdata1=newa,
348                 lowernewdata1=newa.lower(),
349                 )
350
351 def grade_compare(oldmembers, newmembers, csvfile):
352     for nick, data in newmembers.items():
353         newdata = data.get('grade', None)
354         olddata = oldmembers.get(nick, {}).get('grade', None)
355         if newdata is not None and olddata is not None and newdata != olddata:
356             publish_line(csvfile, 
357                 'GRADE,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} est désormais {grade1}',
358                 nick1=nick,
359                 grade1=newmembers[nick]['grade'],
360                 olddata1=olddata,
361                 newdata1=newdata,
362                 )
363
364 def colonized_compare(oldmembers, newmembers, csvfile):
365     for nick, data in newmembers.items():
366         newc = data.get('colonized', None)
367         oldc = oldmembers.get(nick, {}).get('colonized', None)
368         if newc is not None and oldc is not None and newc != oldc:
369             if newc:
370                 txt = "s'est fait colonisé"
371             else:
372                 txt = "n'est plus colonisé"
373             publish_line(csvfile, 
374                 'COLON,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} {txt}',
375                 nick1=nick,
376                 grade1=newmembers[nick]['grade'],
377                 olddata1=str(oldc),
378                 newdata1=str(newc),
379                 txt=txt,
380                 )
381
382 def evolution_compare(oldmembers, newmembers, csvfile):
383     for nick, data in newmembers.items():
384         newdata = data['anthill']
385         olddata = oldmembers.get(nick, {}).get('anthill', None)
386         if newdata is not None and olddata is not None and newdata != olddata:
387             publish_line(csvfile, 
388                 'ANTHILL,{nick1},{grade1},{olddata1},{newdata1},,,,,,,La fourmilière de {nick1} a atteint le niveau {newdata1}',
389                 nick1=nick,
390                 grade1=newmembers[nick]['grade'],
391                 olddata1=olddata,
392                 newdata1=newdata,
393                 )
394         newdata = data['techno']
395         olddata = oldmembers.get(nick, {}).get('techno', None)
396         if newdata is not None and olddata is not None and newdata != olddata:
397             publish_line(csvfile, 
398                 'TECHNO,{nick1},{grade1},{olddata1},{newdata1},,,,,,,La technologie de {nick1} a atteint le niveau {newdata1}',
399                 nick1=nick,
400                 grade1=newmembers[nick]['grade'],
401                 olddata1=olddata,
402                 newdata1=newdata,
403                 )
404
405 if __name__ == '__main__':
406     from optparse import OptionParser
407     parser = OptionParser()
408     parser.add_option('-d', '-v', '--debug', '--verbose',
409         action='store_true', dest='debug', default=False,
410         help="debug mode")
411     parser.add_option('-q', '--quiet',
412         action='store_true', dest='quiet', default=False,
413         help="quiet mode")
414     parser.add_option('-a', '--alliance',
415         dest='alliance', metavar="TAG",
416         help="Default is to process player own alliance.")
417     parser.add_option('--dir',
418         dest='directory', default='.fourmizzz',
419         help="Working directory, including config.py, archives and results. "
420              "Relative to HOME unless it starts with /. "
421              "Default is '%default'.")
422     parser.add_option('--quick',
423         action='store_true', dest='quick', default=False,
424         help="Don't sleep a random delay before hiting the server. "
425              "The programme usually wait between 0 and 59s, so that "
426              "there is no pick usage on a round minute")
427     parser.add_option('--members-name',
428         dest='archive_filename', metavar='FILENAME', default="archive.py",
429         help="Override filename containing old data. "
430         "Default is '%default' in Working directory. "
431         "See --dir.")
432     parser.add_option('--new-members-name',
433         dest='new_archive_filename', metavar='FILENAME',
434         help="Read new members data from a file. "
435         "Default is to fetch data from antzzz server.")
436     parser.add_option('--dry-run',
437         action='store_true', dest='dryrun', default=False,
438         help="don't store result in archives.")
439     options, args = parser.parse_args()
440
441     if options.debug:
442         loglevel = logging.DEBUG
443     elif options.quiet:
444         loglevel = logging.WARNING
445     else:
446         loglevel = logging.INFO
447     
448     HOME = os.environ['HOME']
449     if options.directory[0] == os.path.sep: # '/' on linux
450         BASE_DIRECTORY = options.directory
451     else:
452         BASE_DIRECTORY = os.path.join(HOME, options.directory)
453     logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt=DATETIME_FORMAT)
454
455     if not options.quick:
456         delay = random.randint(0,59)
457         sleep(delay)
458
459     read_config(BASE_DIRECTORY)
460
461     members_filename = os.path.join(BASE_DIRECTORY, options.archive_filename)
462     oldmembers = None
463     try:
464         f = open(members_filename, mode='r+', encoding='utf-8')
465     except IOError as err:
466         if err.errno == 2: # No such file or directory
467             logging.warning("No archive file, creating one.")
468             f = open(members_filename, mode='w+', encoding='utf-8')
469         else:
470             raise
471     else:
472         oldmembers = eval(f.read())
473     
474     if options.new_archive_filename:
475         new_archive_filename = os.path.join(BASE_DIRECTORY, options.new_archive_filename)
476         newf = open(new_archive_filename, mode='r', encoding='utf8')
477         newmembers = eval(newf.read())
478     else:
479         newmembers = members_fetch(options.alliance)
480
481     if oldmembers is not None:
482         copy_existing_data(oldmembers, newmembers)
483         csvfilename = os.path.join(BASE_DIRECTORY, 'results.csv')
484         csvfile = open(csvfilename, mode='a', encoding='utf-8')
485         field_compare(oldmembers, newmembers, csvfile)
486         grade_compare(oldmembers, newmembers, csvfile)
487         activity_compare(oldmembers, newmembers, csvfile)
488         colonized_compare(oldmembers, newmembers, csvfile)
489         evolution_compare(oldmembers, newmembers, csvfile)
490     
491     # Save archive only after processing, just in case it crashes
492     if not options.dryrun:
493         f.seek(0)
494         f.write(repr(newmembers))
495         f.truncate()
496         f.close()
497
498         # We work in members.csv.new file then rename it
499         # In the unlikely event that some script is reading it
500         # while we updated it
501         members_csvfilename = os.path.join(BASE_DIRECTORY, "members.csv")
502         members_csvfilename_new = members_csvfilename + '.new'
503         f = open(members_csvfilename_new, mode='w', encoding='utf-8')
504         f.write('grade,nick,field,techno,anthill,active,colonized,x,y\n')
505         for nick, data in newmembers.items():
506             data = [
507                 data['grade'],
508                 nick,
509                 data['field'],
510                 data['techno'],
511                 data['anthill'],
512                 data['active'],
513                 data['colonized'],
514                 data['x'],
515                 data['y'],
516                 ]
517             data = [ str(x) for x in data ]
518             f.write(','.join(data) + '\n')
519         f.close()
520         os.rename(members_csvfilename_new, members_csvfilename)