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