Now also monitor active/inactive status change
[fourmizzz.git] / members.py
index 0fbaa79e0193eaf49ced8d843d7749e9ed41724e..7192c28907cae1cdc9ebe169770fc6cea0a97268 100755 (executable)
@@ -10,6 +10,7 @@ import re
 import logging
 from datetime import datetime
 import calendar
+import random
 import urllib.request
 from http.cookiejar import CookieJar
 
@@ -19,9 +20,10 @@ import htmlentities
 """
 csv file format:
 DateTime,Action,Nick1,Grade1,OldField1,NewField1,Nick2,Grade2,OldField2,NewField2,FloodField,FieldLossPercent,Text
-Action is one of: JOIN, QUIT, WIN, LOSS, FLOOD
+Action is one of: JOIN, QUIT, WIN, LOSS, FLOOD, NOOP, ACT
 
 Exemples:
+NOOP,,,,,,,,,,,No changes
 JOIN,Nirgal,Recrue,0,571628,,,,,,,Nirgal a rejoint l'alliance avec 571 628 cm² 
 QUIT,oncleblu,Chasseur,9940181,0,,,,,,,oncleblu a quité l'alliance avec 9 940 181 cm² 
 WIN,Nirgal,Chasseur,200000,257900,,,,,,,Nirgal a gagné 57 900 cm² 
@@ -30,6 +32,8 @@ FLOOD,filoux,Passeur 003,55813865,74225093,yosemite,Passeur 004,51142304,3273107
 FLOOD,Nick1,Grade1,100,102,Nick2,Grade2,100,99,1,1.00,Nick1 a pris 1 cm² à Nick2 (1.00%)
 FLOOD,Nick1,Grade1,100,102,Nick3,Grade3,100,99,1,1.00,Nick1 a pris 1 cm² à Nick3 (1.00%)
 
+ACT,Nick1,Grade1,100,100,,,,,,,Nick1 est en vacances
+
 Note that in last 2 lines exemple, NewField1 is 102 that is different from 100+1 because of multiple floods.
 """
 
@@ -39,6 +43,7 @@ Note that in last 2 lines exemple, NewField1 is 102 that is different from 100+1
 #LOGIN
 #PASSWORD
 #BASE_URL
+DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z'
 
 def read_config(config_dir):
     '''
@@ -204,13 +209,15 @@ def members_to_field(members):
     return fields
 
 
-def field_compare(oldmembers, newmembers):
+def field_compare(oldmembers, newmembers, csvfile):
     
     oldfield = members_to_field(oldmembers)
     newfield = members_to_field(newmembers)
 
     changes = {}
     txtchanges = []
+    txtchanges2 = []
+
     for nick in newfield.keys():
         told = oldfield.get(nick, 0)
         tnew = newfield[nick]
@@ -228,8 +235,8 @@ def field_compare(oldmembers, newmembers):
     #print
 
     if not len(changes):
-        logging.info('No changes')
-        return
+        txtchanges.append('No changes')
+        txtchanges2.append('NOOP,,,,,,,,,,,No changes')
  
     for nick in changes.keys():
         delta = changes[nick]['delta']
@@ -242,6 +249,19 @@ def field_compare(oldmembers, newmembers):
                 continue # not the good one
             percent = float(oldfield[nick2] - newfield[nick2]) / oldfield[nick2] * 100.
             txtchanges.append('%s a pris %s cm² à %s (%.2f%%)' % (nick, number_format(delta), nick2, percent))
+            txtchanges2.append('FLOOD,{nick1},{grade1},{oldfield1},{newfield1},{nick2},{grade2},{oldfield2},{newfield2},{deltafield},{percent},{nick1} a pris {nicedeltafield} cm² à {nick2} ({percent:.2f}%)'.format(
+                nick1=nick,
+                grade1=newmembers[nick].get('grade', ''),
+                oldfield1=oldfield[nick],
+                newfield1=newfield[nick],
+                nick2=nick2,
+                grade2=newmembers[nick2].get('grade', ''),
+                oldfield2=oldfield[nick2],
+                newfield2=newfield[nick2],
+                deltafield=delta,
+                nicedeltafield= number_format(delta),
+                percent=percent,
+                ))
             changes[nick]['delta'] = 0
             changes[nick2]['delta'] = 0
 
@@ -251,17 +271,68 @@ def field_compare(oldmembers, newmembers):
             if nick in newfield:
                 percent = float(-delta) / oldfield[nick] * 100.
                 txtchanges.append('%s a perdu %s cm² (%.2f%%)' % (nick, number_format(-delta), percent))
+                txtchanges2.append('LOSS,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},{percent},{nick1} a perdu {nicedeltafield} cm² ({percent:.2f}%)'.format(
+                    nick1=nick,
+                    grade1=newmembers[nick].get('grade', ''),
+                    oldfield1=oldfield[nick],
+                    newfield1=newfield[nick],
+                    deltafield=-delta,
+                    nicedeltafield=number_format(-delta),
+                    percent=percent,
+                    ))
             else:
                 txtchanges.append("%s a quité l'alliance avec %s cm²" % (nick, number_format(-delta)))
+                txtchanges2.append('QUIT,{nick1},{grade1},{oldfield1},0,,,,,{deltafield},,{nick1} a quité l\'alliance avec {nicedeltafield} cm²'.format(
+                    nick1=nick,
+                    grade1=oldmembers[nick].get('grade', ''),
+                    oldfield1=oldfield[nick],
+                    deltafield=-delta,
+                    nicedeltafield=number_format(-delta),
+                    ))
         elif delta > 0:
             if nick in oldfield:
                 txtchanges.append('%s a gagné %s cm²' % (nick, number_format(delta)))
+                txtchanges2.append('WIN,{nick1},{grade1},{oldfield1},{newfield1},,,,,{deltafield},,{nick1} a gagné {nicedeltafield} cm²'.format(
+                    nick1=nick,
+                    grade1=newmembers[nick].get('grade', ''),
+                    oldfield1=oldfield[nick],
+                    newfield1=newfield[nick],
+                    deltafield=delta,
+                    nicedeltafield=number_format(delta),
+                    ))
             else:
                 txtchanges.append("%s a rejoint l'alliance avec %s cm²" % (nick, number_format(delta)))
+                txtchanges2.append('JOIN,{nick1},{grade1},0,{newfield1},,,,,{deltafield},,{nick1} a rejoint l\'alliance avec {nicedeltafield} cm²'.format(
+                    nick1=nick,
+                    grade1=newmembers[nick].get('grade', ''),
+                    newfield1=newfield[nick],
+                    deltafield=delta,
+                    nicedeltafield=number_format(delta),
+                    ))
 
     for txtchange in txtchanges:
         logging.info(txtchange)
 
+    for txtchange in txtchanges2:
+        csvfile.write(time.strftime(DATETIME_FORMAT)+','+txtchange+'\n')
+
+def activity_compare(oldmembers, newmembers, csvfile):
+    txtchanges2 = []
+    for nick, data in newmembers.items():
+        newa = data.get('active', None)
+        olda = oldmembers.get(nick, {}).get('active', None)
+        if newa and olda and newa != olda:
+            txtchanges2.append('ACT,{nick1},{grade1},{olddata1},{newdata1},,,,,,,{nick1} est maintenant {lowernewdata1}'.format(
+                nick1=nick,
+                grade1=newmembers[nick]['grade'],
+                olddata1=olda,
+                newdata1=newa,
+                lowernewdata1=newa.lower(),
+                ))
+
+    for txtchange in txtchanges2:
+        logging.info(txtchange.split(',')[-1])
+        csvfile.write(time.strftime(DATETIME_FORMAT)+','+txtchange+'\n')
 
 if __name__ == '__main__':
     from optparse import OptionParser
@@ -280,6 +351,11 @@ if __name__ == '__main__':
         help="Working directory, including config.py, archives and results. "
              "Relative to HOME unless it starts with /. "
              "Default is '%default'.")
+    parser.add_option('--quick',
+        action='store_true', dest='quick', default=False,
+        help="Don't sleep a random delay before hiting the server. "
+             "The programme usually wait between 0 and 59s, so that "
+             "there is no pick usage on a round minute")
     parser.add_option('--members-name',
         dest='archive_filename', metavar='FILENAME', default="archive.py",
         help="Override filename containing old data. "
@@ -292,9 +368,6 @@ if __name__ == '__main__':
     parser.add_option('--dry-run',
         action='store_true', dest='dryrun', default=False,
         help="don't store result in archives.")
-    parser.add_option('--stdout',
-        action='store_true', dest='stdout', default=False,
-        help="Print result on stdout rather that in results.log")
     options, args = parser.parse_args()
 
     if options.debug:
@@ -305,16 +378,15 @@ if __name__ == '__main__':
         loglevel = logging.INFO
     
     HOME = os.environ['HOME']
-    if options.directory[0] == '/':
+    if options.directory[0] == os.path.sep: # '/' on linux
         BASE_DIRECTORY = options.directory
     else:
         BASE_DIRECTORY = os.path.join(HOME, options.directory)
+    logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt=DATETIME_FORMAT)
 
-    if options.stdout:
-        logging.basicConfig(level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z')
-    else:
-        result_filename = os.path.join(BASE_DIRECTORY, 'results.log')
-        logging.basicConfig(filename=result_filename, level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z')
+    if not options.quick:
+        delay = random.randint(0,59)
+        sleep(delay)
 
     read_config(BASE_DIRECTORY)
 
@@ -339,7 +411,10 @@ if __name__ == '__main__':
         newmembers = members_fetch(options.alliance)
 
     if oldmembers is not None:
-        field_compare(oldmembers, newmembers)
+        csvfilename = os.path.join(BASE_DIRECTORY, 'results.csv')
+        csvfile = open(csvfilename, mode='a', encoding='utf-8')
+        field_compare(oldmembers, newmembers, csvfile)
+        activity_compare(oldmembers, newmembers, csvfile)
     
     # Save archive only after processing, just in case it crashes
     if not options.dryrun: