Added delay to spread server hits within minutes
[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
24
25 Exemples:
26 NOOP,,,,,,,,,,,No changes
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 Note that in last 2 lines exemple, NewField1 is 102 that is different from 100+1 because of multiple floods.
36 """
37
38 # globals:
39 #BASE_DIRECTORY
40 #SERVER
41 #LOGIN
42 #PASSWORD
43 #BASE_URL
44 DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
45
46 def read_config(config_dir):
47     '''
48     That function will read config.py in .fourmizzz directory
49     and set up globals SERVER, LOGIN, PASSWORD, and BASE_URL.
50     '''
51     global SERVER, LOGIN, PASSWORD
52     global BASE_URL
53     CONFIG_TEMPLATE='''# Veuillez modifier les lignes ci dessous avec vos paramètres:
54 SERVER = 's1.fourmizzz.fr'
55 LOGIN = 'MonIdentifiant'
56 PASSWORD = 'MonMotDePasse'
57     '''
58
59     sys.path.append(config_dir)
60     try:
61         import config
62     except ImportError:
63         config_filename = os.path.join(config_dir, 'config.py')
64         logging.fatal("No configuration file. Creating %s", config_filename)
65         f = open(config_filename, mode='w+', encoding='utf-8')
66         f.write(CONFIG_TEMPLATE)
67         f.close()
68         logging.fatal("Please update this file with your details.")
69         sys.exit(1)
70     SERVER = config.SERVER
71     LOGIN = config.LOGIN
72     PASSWORD = config.PASSWORD
73     BASE_URL = 'http://%s' % SERVER
74
75 def hide_password_from_log(txt):
76     return re.sub('mot_passe=.*', 'mot_passe=********', txt)
77
78 __opener__ = None
79 def httpopen(url, post_data=None):
80     if post_data:
81         log_post_data = hide_password_from_log(post_data)
82         post_data = post_data.encode('utf-8') # str->bytes
83         logging.debug('HTTP POST %s %s', url, log_post_data)
84     else:
85         logging.debug('HTTP GET %s', url)
86     global __opener__
87     if __opener__ is None:
88         cookiejar = CookieJar()
89         __opener__ = urllib.request.build_opener()
90         __opener__.add_handler(urllib.request.HTTPCookieProcessor(cookiejar))
91     http_response = __opener__.open(url, post_data)
92     return http_response
93
94 def sleep(seconds):
95     logging.debug('Waiting %s seconds', seconds)
96     time.sleep(seconds)
97
98 def timestamp():
99     return calendar.timegm(datetime.now().timetuple())
100
101 def number_format(i):
102     result = ''
103     while i:
104         if result:
105             result = ' ' + result
106         d3 = i % 1000
107         i = i//1000
108         if i: # there will be something else left of that
109             result = ('%03d' % d3) + result
110         else:
111             result = ('%d' % d3) + result
112     return result
113
114
115 def members_fetch(alliance_tag=None):
116     #httpresponse = httpopen(BASE_URL + '/')
117     #html = httpresponse.read().decode('utf-8')
118     #print(html)
119    
120     httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s' % (SERVER, LOGIN, PASSWORD))
121     #httpresponse = httpopen(BASE_URL + '/index.php?connexion=1', 'serveur=%s&pseudo=%s&mot_passe=%s&connexion=Connexion' % (SERVER, LOGIN, PASSWORD))
122     html = httpresponse.read().decode('utf-8')
123     if "redirectReine" not in html:
124         logging.fatal("Impossible de s'authentifier. Vérifiez vos paramètres dans config.py")
125         sys.exit(1)
126     #print('-'*80)
127     #print(html)
128     
129     #httpresponse = httpopen(BASE_URL + '/alliance.php?Membres')
130     #html = httpresponse.read().decode('utf-8')
131     #print('-'*80)
132     #print(html)
133
134     if not alliance_tag:
135         httpresponse = httpopen(BASE_URL + '/alliance.php?Membres',
136             'xajax=membre&xajaxr='+str(timestamp()))
137         html = httpresponse.read().decode('utf-8')
138         #print('-'*80)
139         #print(html)
140
141         root = html_parse(html)
142         table = get_elem(root, 'table')[0]
143         td = get_elem(table, 'td')[3]
144         table = get_elem(td, 'table')[0]
145         #print('-'*80)
146         #print_idented_tree(table)
147     else:
148         httpresponse = httpopen(BASE_URL + '/classementAlliance.php?alliance=%s' % alliance_tag)
149         html = httpresponse.read().decode('utf-8')
150         
151         root = html_parse(html)
152         table = get_elem(root, 'table')[2]
153         #print('-'*80)
154         #print_idented_tree(table)
155
156     members = {} # NEW
157     for tr in get_elem(table, 'tr'):
158         row = get_elem(tr, 'td')
159         #print('-'*10)
160         #print_idented_tree(tr)
161         if not alliance_tag:
162             if len(row) != 10:
163                 continue
164             grade = get_merged_leaf_content(row[2])
165             nick = get_merged_leaf_content(row[3])
166             field = int(get_merged_leaf_content(row[4]).replace(' ', ''))
167             techno = int(get_merged_leaf_content(row[5]))
168             anthill = int(get_merged_leaf_content(row[6]))
169             active = get_elem(row[7], 'img')[0].attributes['alt']
170             colonized = len(get_elem(row[8], 'img')) == 1
171             #print(nick, grade, field, techno, anthill, active, colonized)
172
173         else:
174             if len(row) != 6:
175                 continue
176             grade = get_merged_leaf_content(row[1])
177             nick = get_merged_leaf_content(row[2])
178             field = int(get_merged_leaf_content(row[3]).replace(' ', ''))
179             techno = int(get_merged_leaf_content(row[4]))
180             anthill = int(get_merged_leaf_content(row[5]))
181             active = None
182             colonized = None
183             #print(nick, grade, field, techno, anthill)
184
185         members[nick] = {
186             'grade': grade,
187             'field': field,
188             'techno': techno,
189             'anthill': anthill,
190             'active': active,
191             'colonized': colonized,
192         }
193         #print(members[nick])
194
195     logging.debug('%s members - total field = %s cm²', len(members), number_format(sum([x['field'] for x in members.values()])))
196     return members
197
198
199 def members_to_field(members):
200     """
201     Takes a full information dict "members"
202     Returns a simple dict with nick->field
203     """
204     fields  = {}
205     for nick, data in members.items():
206         fields[nick] = data['field']
207     return fields
208
209
210 def field_compare(oldmembers, newmembers, csvfile):
211     
212     oldfield = members_to_field(oldmembers)
213     newfield = members_to_field(newmembers)
214
215     changes = {}
216     txtchanges = []
217     txtchanges2 = []
218
219     for nick in newfield.keys():
220         told = oldfield.get(nick, 0)
221         tnew = newfield[nick]
222         if told == tnew:
223             continue
224         changes[nick] = { 'old': told, 'new': tnew, 'delta': tnew-told }
225     
226     for nick in oldfield.keys():
227         if nick not in newfield:
228             told = oldfield[nick]
229             tnew = 0
230             changes[nick] = { 'old': told, 'new': 0, 'delta': -told }
231     #for nick, change in changes.items():
232     #    print(nick, ' - ', change['old'], ' - ', change['new'], ' - ', change['delta'])
233     #print
234
235     if not len(changes):
236         txtchanges.append('No changes')
237         txtchanges2.append('NOOP,,,,,,,,,,,No changes')
238  
239     for nick in changes.keys():
240         delta = changes[nick]['delta']
241         if delta <= 0:
242             continue # 0 is already process, <0 will be processed when nick swaps with nick2
243         for nick2 in changes.keys():
244             if changes[nick2]['delta'] == 0:
245                 continue # already done
246             if changes[nick2]['delta'] != -delta:
247                 continue # not the good one
248             percent = float(oldfield[nick2] - newfield[nick2]) / oldfield[nick2] * 100.
249             txtchanges.append('%s a pris %s cm² à %s (%.2f%%)' % (nick, number_format(delta), nick2, percent))
250             txtchanges2.append('FLOOD,{nick1},{grade1},{oldfield1},{newfield1},{nick2},{grade2},{oldfield2},{newfield2},{deltafield},{percent},{nick1} a pris {nicedeltafield} cm² à {nick2} ({percent:.2f}%)'.format(
251                 nick1=nick,
252                 grade1=newmembers[nick].get('grade', ''),
253                 oldfield1=oldfield[nick],
254                 newfield1=newfield[nick],
255                 nick2=nick2,
256                 grade2=newmembers[nick2].get('grade', ''),
257                 oldfield2=oldfield[nick2],
258                 newfield2=newfield[nick2],
259                 deltafield=delta,
260                 nicedeltafield= number_format(delta),
261                 percent=percent,
262                 ))
263             changes[nick]['delta'] = 0
264             changes[nick2]['delta'] = 0
265
266     for nick, change in changes.items():
267         delta = change['delta']
268         if delta < 0:
269             if nick in newfield:
270                 percent = float(-delta) / oldfield[nick] * 100.
271                 txtchanges.append('%s a perdu %s cm² (%.2f%%)' % (nick, number_format(-delta), percent))
272                 txtchanges2.append('LOSS,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},{percent},{nick1} a perdu {nicedeltafield} cm² ({percent:.2f}%)'.format(
273                     nick1=nick,
274                     grade1=newmembers[nick].get('grade', ''),
275                     oldfield1=oldfield[nick],
276                     newfield1=newfield[nick],
277                     deltafield=-delta,
278                     nicedeltafield=number_format(-delta),
279                     percent=percent,
280                     ))
281             else:
282                 txtchanges.append("%s a quité l'alliance avec %s cm²" % (nick, number_format(-delta)))
283                 txtchanges2.append('QUIT,{nick1},{grade1},{oldfield1},0,,,,,{deltafield},,{nick1} a quité l\'alliance avec {nicedeltafield} cm²'.format(
284                     nick1=nick,
285                     grade1=oldmembers[nick].get('grade', ''),
286                     oldfield1=oldfield[nick],
287                     deltafield=-delta,
288                     nicedeltafield=number_format(-delta),
289                     ))
290         elif delta > 0:
291             if nick in oldfield:
292                 txtchanges.append('%s a gagné %s cm²' % (nick, number_format(delta)))
293                 txtchanges2.append('WIN,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},,{nick1} a gagné {nicedeltafield} cm²'.format(
294                     nick1=nick,
295                     grade1=newmembers[nick].get('grade', ''),
296                     oldfield1=oldfield[nick],
297                     newfield1=newfield[nick],
298                     deltafield=delta,
299                     nicedeltafield=number_format(delta),
300                     ))
301             else:
302                 txtchanges.append("%s a rejoint l'alliance avec %s cm²" % (nick, number_format(delta)))
303                 txtchanges2.append('JOIN,{nick1},{grade1},0,{newfield1},,,,,{deltafield},,{nick1} a rejoint l\'alliance avec {nicedeltafield} cm²'.format(
304                     nick1=nick,
305                     grade1=newmembers[nick].get('grade', ''),
306                     newfield1=newfield[nick],
307                     deltafield=delta,
308                     nicedeltafield=number_format(delta),
309                     ))
310
311     for txtchange in txtchanges:
312         logging.info(txtchange)
313
314     for txtchange in txtchanges2:
315         csvfile.write(time.strftime(DATETIME_FORMAT)+','+txtchange+'\n')
316
317 if __name__ == '__main__':
318     from optparse import OptionParser
319     parser = OptionParser()
320     parser.add_option('-d', '-v', '--debug', '--verbose',
321         action='store_true', dest='debug', default=False,
322         help="debug mode")
323     parser.add_option('-q', '--quiet',
324         action='store_true', dest='quiet', default=False,
325         help="quiet mode")
326     parser.add_option('-a', '--alliance',
327         dest='alliance', metavar="TAG",
328         help="Default is to process player own alliance.")
329     parser.add_option('--dir',
330         dest='directory', default='.fourmizzz',
331         help="Working directory, including config.py, archives and results. "
332              "Relative to HOME unless it starts with /. "
333              "Default is '%default'.")
334     parser.add_option('--quick',
335         action='store_true', dest='quick', default=False,
336         help="Don't sleep a random delay before hiting the server. "
337              "The programme usually wait between 0 and 59s, so that "
338              "there is no pick usage on a round minute")
339     parser.add_option('--members-name',
340         dest='archive_filename', metavar='FILENAME', default="archive.py",
341         help="Override filename containing old data. "
342         "Default is '%default' in Working directory. "
343         "See --dir.")
344     parser.add_option('--new-members-name',
345         dest='new_archive_filename', metavar='FILENAME',
346         help="Read new members data from a file. "
347         "Default is to fetch data from antzzz server.")
348     parser.add_option('--dry-run',
349         action='store_true', dest='dryrun', default=False,
350         help="don't store result in archives.")
351     options, args = parser.parse_args()
352
353     if options.debug:
354         loglevel = logging.DEBUG
355     elif options.quiet:
356         loglevel = logging.WARNING
357     else:
358         loglevel = logging.INFO
359     
360     HOME = os.environ['HOME']
361     if options.directory[0] == os.path.sep: # '/' on linux
362         BASE_DIRECTORY = options.directory
363     else:
364         BASE_DIRECTORY = os.path.join(HOME, options.directory)
365     logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt=DATETIME_FORMAT)
366
367     if not options.quick:
368         delay = random.randint(0,59)
369         sleep(delay)
370
371     read_config(BASE_DIRECTORY)
372
373     members_filename = os.path.join(BASE_DIRECTORY, options.archive_filename)
374     oldmembers = None
375     try:
376         f = open(members_filename, mode='r+', encoding='utf-8')
377     except IOError as err:
378         if err.errno == 2: # No such file or directory
379             logging.warning("No archive file, creating one.")
380             f = open(members_filename, mode='w+', encoding='utf-8')
381         else:
382             raise
383     else:
384         oldmembers = eval(f.read())
385     
386     if options.new_archive_filename:
387         new_archive_filename = os.path.join(BASE_DIRECTORY, options.new_archive_filename)
388         newf = open(new_archive_filename, mode='r', encoding='utf8')
389         newmembers = eval(newf.read())
390     else:
391         newmembers = members_fetch(options.alliance)
392
393     if oldmembers is not None:
394         csvfilename = os.path.join(BASE_DIRECTORY, 'results.csv')
395         csvfile = open(csvfilename, mode='a', encoding='utf-8')
396         field_compare(oldmembers, newmembers, csvfile)
397     
398     # Save archive only after processing, just in case it crashes
399     if not options.dryrun:
400         f.seek(0)
401         f.write(repr(newmembers))
402         f.truncate()