ea8fef029bd9277b5e2e6435532502727b452d93
[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 members_to_field(members):
209     """
210     Takes a full information dict "members"
211     Returns a simple dict with nick->field
212     """
213     fields  = {}
214     for nick, data in members.items():
215         fields[nick] = data['field']
216     return fields
217
218
219 def publish_line(csvfile, text, **args):
220     csvline = text.format(**args)
221     logging.info(csvline.split(',')[-1])
222     if not options.dryrun:
223         csvfile.write(time.strftime(DATETIME_FORMAT)+','+csvline+'\n')
224
225 def field_compare(oldmembers, newmembers, csvfile):
226     
227     oldfield = members_to_field(oldmembers)
228     newfield = members_to_field(newmembers)
229
230     changes = {}
231
232     for nick in newfield.keys():
233         told = oldfield.get(nick, 0)
234         tnew = newfield[nick]
235         if told == tnew:
236             continue
237         changes[nick] = { 'old': told, 'new': tnew, 'delta': tnew-told }
238     
239     for nick in oldfield.keys():
240         if nick not in newfield:
241             told = oldfield[nick]
242             tnew = 0
243             changes[nick] = { 'old': told, 'new': 0, 'delta': -told }
244     #for nick, change in changes.items():
245     #    print(nick, ' - ', change['old'], ' - ', change['new'], ' - ', change['delta'])
246     #print
247
248     if not len(changes):
249         publish_line(csvfile, 'NOOP,,,,,,,,,,,No changes')
250  
251     for nick in changes.keys():
252         delta = changes[nick]['delta']
253         if delta <= 0:
254             continue # 0 is already process, <0 will be processed when nick swaps with nick2
255         for nick2 in changes.keys():
256             if changes[nick2]['delta'] == 0:
257                 continue # already done
258             if changes[nick2]['delta'] != -delta:
259                 continue # not the good one
260             percent = float(oldfield[nick2] - newfield[nick2]) / oldfield[nick2] * 100.
261             publish_line(csvfile, 
262                 'FLOOD,{nick1},{grade1},{oldfield1},{newfield1},{nick2},{grade2},{oldfield2},{newfield2},{deltafield},{percent},{nick1} a pris {nicedeltafield} cm² à {nick2} ({percent:.2f}%)',
263                 nick1=nick,
264                 grade1=newmembers[nick].get('grade', ''),
265                 oldfield1=oldfield[nick],
266                 newfield1=newfield[nick],
267                 nick2=nick2,
268                 grade2=newmembers[nick2].get('grade', ''),
269                 oldfield2=oldfield[nick2],
270                 newfield2=newfield[nick2],
271                 deltafield=delta,
272                 nicedeltafield= number_format(delta),
273                 percent=percent,
274                 )
275             changes[nick]['delta'] = 0
276             changes[nick2]['delta'] = 0
277
278     for nick, change in changes.items():
279         delta = change['delta']
280         if delta < 0:
281             if nick in newfield:
282                 percent = float(-delta) / oldfield[nick] * 100.
283                 publish_line(csvfile, 
284                     'LOSS,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},{percent},{nick1} a perdu {nicedeltafield} cm² ({percent:.2f}%)',
285                     nick1=nick,
286                     grade1=newmembers[nick].get('grade', ''),
287                     oldfield1=oldfield[nick],
288                     newfield1=newfield[nick],
289                     deltafield=-delta,
290                     nicedeltafield=number_format(-delta),
291                     percent=percent,
292                     )
293             else:
294                 publish_line(csvfile, 
295                     'QUIT,{nick1},{grade1},{oldfield1},0,,,,,{deltafield},,{nick1} a quité l\'alliance avec {nicedeltafield} cm²',
296                     nick1=nick,
297                     grade1=oldmembers[nick].get('grade', ''),
298                     oldfield1=oldfield[nick],
299                     deltafield=-delta,
300                     nicedeltafield=number_format(-delta),
301                     )
302         elif delta > 0:
303             if nick in oldfield:
304                 publish_line(csvfile, 
305                     'WIN,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},,{nick1} a gagné {nicedeltafield} cm²',
306                     nick1=nick,
307                     grade1=newmembers[nick].get('grade', ''),
308                     oldfield1=oldfield[nick],
309                     newfield1=newfield[nick],
310                     deltafield=delta,
311                     nicedeltafield=number_format(delta),
312                     )
313             else:
314                 publish_line(csvfile, 
315                     'JOIN,{nick1},{grade1},0,{newfield1},,,,,{deltafield},,{nick1} a rejoint l\'alliance avec {nicedeltafield} cm²',
316                     nick1=nick,
317                     grade1=newmembers[nick].get('grade', ''),
318                     newfield1=newfield[nick],
319                     deltafield=delta,
320                     nicedeltafield=number_format(delta),
321                     )
322
323 def activity_compare(oldmembers, newmembers, csvfile):
324     for nick, data in newmembers.items():
325         newa = data.get('active', None)
326         olda = oldmembers.get(nick, {}).get('active', None)
327         if newa and olda and newa != olda:
328             publish_line(csvfile, 
329                 'ACT,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} est maintenant {lowernewdata1}',
330                 nick1=nick,
331                 grade1=newmembers[nick]['grade'],
332                 olddata1=olda,
333                 newdata1=newa,
334                 lowernewdata1=newa.lower(),
335                 )
336
337 def grade_compare(oldmembers, newmembers, csvfile):
338     for nick, data in newmembers.items():
339         newdata = data.get('grade', None)
340         olddata = oldmembers.get(nick, {}).get('grade', None)
341         if newdata is not None and olddata is not None and newdata != olddata:
342             publish_line(csvfile, 
343                 'GRADE,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} est désormais {grade1}',
344                 nick1=nick,
345                 grade1=newmembers[nick]['grade'],
346                 olddata1=olddata,
347                 newdata1=newdata,
348                 )
349
350 def colonized_compare(oldmembers, newmembers, csvfile):
351     for nick, data in newmembers.items():
352         newc = data.get('colonized', None)
353         oldc = oldmembers.get(nick, {}).get('colonized', None)
354         if newc is not None and oldc is not None and newc != oldc:
355             if newc:
356                 txt = "s'est fait colonisé"
357             else:
358                 txt = "n'est plus colonisé"
359             publish_line(csvfile, 
360                 'COLON,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} {txt}',
361                 nick1=nick,
362                 grade1=newmembers[nick]['grade'],
363                 olddata1=str(oldc),
364                 newdata1=str(newc),
365                 txt=txt,
366                 )
367
368 def evolution_compare(oldmembers, newmembers, csvfile):
369     for nick, data in newmembers.items():
370         newdata = data['anthill']
371         olddata = oldmembers.get(nick, {}).get('anthill', None)
372         if newdata is not None and olddata is not None and newdata != olddata:
373             publish_line(csvfile, 
374                 'ANTHILL,{nick1},{grade1},{olddata1},{newdata1},,,,,,,La fourmilière de {nick1} a atteint le niveau {newdata1}',
375                 nick1=nick,
376                 grade1=newmembers[nick]['grade'],
377                 olddata1=olddata,
378                 newdata1=newdata,
379                 )
380         newdata = data['techno']
381         olddata = oldmembers.get(nick, {}).get('techno', None)
382         if newdata is not None and olddata is not None and newdata != olddata:
383             publish_line(csvfile, 
384                 'TECHNO,{nick1},{grade1},{olddata1},{newdata1},,,,,,,La technologie de {nick1} a atteint le niveau {newdata1}',
385                 nick1=nick,
386                 grade1=newmembers[nick]['grade'],
387                 olddata1=olddata,
388                 newdata1=newdata,
389                 )
390
391 if __name__ == '__main__':
392     from optparse import OptionParser
393     parser = OptionParser()
394     parser.add_option('-d', '-v', '--debug', '--verbose',
395         action='store_true', dest='debug', default=False,
396         help="debug mode")
397     parser.add_option('-q', '--quiet',
398         action='store_true', dest='quiet', default=False,
399         help="quiet mode")
400     parser.add_option('-a', '--alliance',
401         dest='alliance', metavar="TAG",
402         help="Default is to process player own alliance.")
403     parser.add_option('--dir',
404         dest='directory', default='.fourmizzz',
405         help="Working directory, including config.py, archives and results. "
406              "Relative to HOME unless it starts with /. "
407              "Default is '%default'.")
408     parser.add_option('--quick',
409         action='store_true', dest='quick', default=False,
410         help="Don't sleep a random delay before hiting the server. "
411              "The programme usually wait between 0 and 59s, so that "
412              "there is no pick usage on a round minute")
413     parser.add_option('--members-name',
414         dest='archive_filename', metavar='FILENAME', default="archive.py",
415         help="Override filename containing old data. "
416         "Default is '%default' in Working directory. "
417         "See --dir.")
418     parser.add_option('--new-members-name',
419         dest='new_archive_filename', metavar='FILENAME',
420         help="Read new members data from a file. "
421         "Default is to fetch data from antzzz server.")
422     parser.add_option('--dry-run',
423         action='store_true', dest='dryrun', default=False,
424         help="don't store result in archives.")
425     options, args = parser.parse_args()
426
427     if options.debug:
428         loglevel = logging.DEBUG
429     elif options.quiet:
430         loglevel = logging.WARNING
431     else:
432         loglevel = logging.INFO
433     
434     HOME = os.environ['HOME']
435     if options.directory[0] == os.path.sep: # '/' on linux
436         BASE_DIRECTORY = options.directory
437     else:
438         BASE_DIRECTORY = os.path.join(HOME, options.directory)
439     logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt=DATETIME_FORMAT)
440
441     if not options.quick:
442         delay = random.randint(0,59)
443         sleep(delay)
444
445     read_config(BASE_DIRECTORY)
446
447     members_filename = os.path.join(BASE_DIRECTORY, options.archive_filename)
448     oldmembers = None
449     try:
450         f = open(members_filename, mode='r+', encoding='utf-8')
451     except IOError as err:
452         if err.errno == 2: # No such file or directory
453             logging.warning("No archive file, creating one.")
454             f = open(members_filename, mode='w+', encoding='utf-8')
455         else:
456             raise
457     else:
458         oldmembers = eval(f.read())
459     
460     if options.new_archive_filename:
461         new_archive_filename = os.path.join(BASE_DIRECTORY, options.new_archive_filename)
462         newf = open(new_archive_filename, mode='r', encoding='utf8')
463         newmembers = eval(newf.read())
464     else:
465         newmembers = members_fetch(options.alliance)
466
467     if oldmembers is not None:
468         csvfilename = os.path.join(BASE_DIRECTORY, 'results.csv')
469         csvfile = open(csvfilename, mode='a', encoding='utf-8')
470         field_compare(oldmembers, newmembers, csvfile)
471         grade_compare(oldmembers, newmembers, csvfile)
472         activity_compare(oldmembers, newmembers, csvfile)
473         colonized_compare(oldmembers, newmembers, csvfile)
474         evolution_compare(oldmembers, newmembers, csvfile)
475     
476     # Save archive only after processing, just in case it crashes
477     if not options.dryrun:
478         f.seek(0)
479         f.write(repr(newmembers))
480         f.truncate()
481         f.close()
482
483         # We work in members.csv.new file then rename it
484         # In the unlikely event that some script is reading it
485         # while we updated it
486         members_csvfilename = os.path.join(BASE_DIRECTORY, "members.csv")
487         members_csvfilename_new = members_csvfilename + '.new'
488         f = open(members_csvfilename_new, mode='w', encoding='utf-8')
489         f.write('grade,nick,field,techno,anthill,active,colonized\n')
490         for nick, data in newmembers.items():
491             data = [
492                 data['grade'],
493                 nick,
494                 data['field'],
495                 data['techno'],
496                 data['anthill'],
497                 data['active'],
498                 data['colonized'],
499                 ]
500             data = [ str(x) for x in data ]
501             f.write(','.join(data) + '\n')
502         f.close()
503         os.rename(members_csvfilename_new, members_csvfilename)