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