Made working dir customizable by options
[fourmizzz.git] / members.py
index f3af288435cbf1b84a2e68229f10c80e160a0953..404e3049958a7566d4cc59b702dea72fc44408f6 100755 (executable)
@@ -13,15 +13,31 @@ from http.cookiejar import CookieJar
 from html_parser import *
 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
+
+Exemples:
+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² 
+LOSS,Nirgal,Passeur 806,553624,442900,,,,,110724,20.00,Nirgal a perdu 110 724 cm² (20.00%) 
+FLOOD,filoux,Passeur 003,55813865,74225093,yosemite,Passeur 004,51142304,32731076,18411228,36.00,filoux a pris 18 411 228 cm² à yosemite (36.00%)
+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%)
+
+Note that in last 2 lines exemple, NewField1 is 102 that is different from 100+1 because of multiple floods.
+"""
+
+# globals:
+#BASE_DIRECTORY
 #SERVER
 #LOGIN
 #PASSWORD
 #BASE_URL
-HOME = os.environ['HOME']
-ARCHIVE = HOME + '/.fourmizzz/archive.py'
-RESULT = HOME + '/.fourmizzz/results.log'
 
-def read_config():
+def read_config(config_dir):
     '''
     That function will read config.py in .fourmizzz directory
     and set up globals SERVER, LOGIN, PASSWORD, and BASE_URL.
@@ -34,13 +50,13 @@ LOGIN = 'MonIdentifiant'
 PASSWORD = 'MonMotDePasse'
     '''
 
-    sys.path.append(HOME+'/.fourmizzz')
+    sys.path.append(config_dir)
     try:
         import config
     except ImportError:
-        CONFIG = HOME+'/.fourmizzz/config.py'
-        logging.fatal("No configuration file. Creating %s", CONFIG)
-        f = open(CONFIG, mode='w+', encoding='utf-8')
+        config_filename = os.path.join(config_dir, 'config.py')
+        logging.fatal("No configuration file. Creating %s", config_filename)
+        f = open(config_filename, mode='w+', encoding='utf-8')
         f.write(CONFIG_TEMPLATE)
         f.close()
         logging.fatal("Please update this file with your details.")
@@ -83,7 +99,7 @@ def number_format(i):
             result = ' ' + result
         d3 = i % 1000
         i = i//1000
-        if i:
+        if i: # there will be something else left of that
             result = ('%03d' % d3) + result
         else:
             result = ('%d' % d3) + result
@@ -131,30 +147,65 @@ def tdc_get(alliance_tag=None):
         #print('-'*80)
         #print_idented_tree(table)
 
-    summary = {}
+    members = {} # NEW
     for tr in get_elem(table, 'tr'):
         row = get_elem(tr, 'td')
-        if not alliance_tag and len(row) != 10:
-            continue
-        if alliance_tag and len(row) != 6:
-            continue
         #print('-'*10)
         #print_idented_tree(tr)
         if not alliance_tag:
+            if len(row) != 10:
+                continue
+            grade = get_merged_leaf_content(row[2])
             nick = get_merged_leaf_content(row[3])
-            tdc = get_merged_leaf_content(row[4]).replace(' ', '')
+            field = int(get_merged_leaf_content(row[4]).replace(' ', ''))
+            techno = int(get_merged_leaf_content(row[5]))
+            anthill = int(get_merged_leaf_content(row[6]))
+            active = get_elem(row[7], 'img')[0].attributes['alt']
+            colonized = len(get_elem(row[8], 'img')) == 1
+            #print(nick, grade, field, techno, anthill, active, colonized)
+
         else:
+            if len(row) != 6:
+                continue
+            grade = get_merged_leaf_content(row[1])
             nick = get_merged_leaf_content(row[2])
-            tdc = get_merged_leaf_content(row[3]).replace(' ', '')
+            field = int(get_merged_leaf_content(row[3]).replace(' ', ''))
+            techno = int(get_merged_leaf_content(row[4]))
+            anthill = int(get_merged_leaf_content(row[5]))
+            active = None
+            colonized = None
+            #print(nick, grade, field, techno, anthill)
+
+        members[nick] = {
+            'grade': grade,
+            'field': field,
+            'techno': techno,
+            'anthill': anthill,
+            'active': active,
+            'colonized': colonized,
+        }
+        #print(members[nick])
+
+    logging.debug('%s members - total field = %s cm²', len(members), number_format(sum([x['field'] for x in members.values()])))
+    return members
 
-        tdc = int(tdc)
-        #print(nick, tdc)
-        summary[nick] = tdc
-    logging.debug('%s members - total tdc = %s cm²', len(summary), number_format(sum(summary.values())))
-    return summary
 
+def members_to_field(members):
+    """
+    Takes a full information dict "members"
+    Returns a simple dict with nick->field
+    """
+    fields  = {}
+    for nick, data in members.items():
+        fields[nick] = data['field']
+    return fields
+
+
+def field_compare(oldmembers, newmembers):
+    
+    oldtdc = members_to_field(oldmembers)
+    newtdc = members_to_field(newmembers)
 
-def tdc_compare(oldtdc, newtdc):
     changes = {}
     txtchanges = []
     for nick in newtdc.keys():
@@ -222,6 +273,11 @@ if __name__ == '__main__':
     parser.add_option('-a', '--alliance',
         dest='alliance',
         help="alliance tag. default is to process player own alliance.")
+    parser.add_option('--dir',
+        dest='directory', default='.fourmizzz',
+        help="Working directory, including config.py, archives and results. "
+             "Relative to HOME unless it starts with /. "
+             "Default is '%default'.")
     parser.add_option('--dry-run',
         action='store_true', dest='dryrun', default=False,
         help="don't store result in archives.")
@@ -231,30 +287,40 @@ if __name__ == '__main__':
         loglevel = logging.DEBUG
     elif options.quiet:
         loglevel = logging.WARNING
-    else
+    else:
         loglevel = logging.INFO
-    logging.basicConfig(filename=RESULT, level=loglevel, format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S %Z')
+    
+    HOME = os.environ['HOME']
+    if options.directory[0] == '/':
+        BASE_DIRECTORY = options.directory
+    else:
+        BASE_DIRECTORY = os.path.join(HOME, options.directory)
 
-    read_config()
+    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')
 
-    oldtdc = None
+    read_config(BASE_DIRECTORY)
+
+    members_filename = os.path.join(BASE_DIRECTORY, 'archive.py')
+    oldmembers = None
     try:
-        f = open(ARCHIVE, mode='r+', encoding='utf-8')
+        f = open(members_filename, mode='r+', encoding='utf-8')
     except IOError as err:
         if err.errno == 2: # No such file or directory
             logging.warning("No archive file, creating one.")
-            f = open(ARCHIVE, mode='w+', encoding='utf-8')
+            f = open(members_filename, mode='w+', encoding='utf-8')
         else:
             raise
     else:
-        oldtdc = eval(f.read())
+        oldmembers = eval(f.read())
     
-    newtdc = tdc_get(options.alliance)
-    if oldtdc is not None:
-        tdc_compare(oldtdc, newtdc)
+    newmembers = tdc_get(options.alliance)
+
+    if oldmembers is not None:
+        field_compare(oldmembers, newmembers)
     
     # Save archive only after processing, just in case it crashes
     if not options.dryrun:
         f.seek(0)
-        f.write(repr(newtdc))
+        f.write(repr(newmembers))
         f.truncate()