Ejemplo n.º 1
0
def generate_type_badges(type_):
    ''' Check if cache type has a badge and set status if yes. '''
    if type_ in Pers.typeCount.keys():
        keys = [key for key in Pers.typeCount.keys()
                    if type_[:5].lower() in key.lower()]
        if len(keys) == 1:
            try:
                badgeManager.setStatus(type_[:5].lower(), 
                                        Pers.typeCount[keys[0]])
                print type_ + ' ' + str(Pers.typeCount[keys[0]])
            except NameError('BadgeName'):
                print("No Match for Cachetype %s found. Nothing was set."%
                        type_)
        elif len(keys) > 1:
            print("Ambiquious type name '" + type_ + "', found (gpx: " + 
                    str(keys) + ") aborting...")
        else: 
            raise LookupError(type_[:5].lower() + " not in badge names.")
    else:
        try:
            badgeManager.setStatus(type_[:5].lower(), 0)
            print type_ + ' ' + str(0)
        except NameError('BadgeName'):
            print("No Match for Cachetype %s found. Nothing was set."% 
                    type_)
Ejemplo n.º 2
0
def create_badges(gpx_inst, con_mngr, cache_mngr, force_tb_update,
                  force_owned_update):
    ''' Generate the badges from statistical data.
    
    Use the statistical data from the parser runs and the badge definitions to
    create badges and set their status.
    
    '''
    all = gpx_inst.all_caches
    ##### LOGS ####
    if Pers.ownfoundlogcount > 0:
        avgwordcount = Pers.wordcount / Pers.ownfoundlogcount
    else:
        avgwordcount = 0
    print "Average  word count: " + str(avgwordcount)
    badgeManager.setStatus('Author', avgwordcount)
   
    #### OVERALL COUNT #####
    badgeManager.setStatus('Geocacher', Pers.ownfoundlogcount)
    print "Geocaches " + str(Pers.ownfoundlogcount)
   
    ##### TYPES #####
    print '\n'
    types = ['Traditional Cache', 'Multi-cache', 'Unknown Cache', 
             'Letterbox Hybrid', 'Earthcache', 'Wherigo Cache', 
             'CITO Event Cache','Event Cache','Virtual Cache',
             'Mega Social Event Cache','Benchmark','Waymark','Webcam Cache',
             'Project Ape Cache']
   
    for type_ in types:
        generate_type_badges(type_)
    lostn = len([a for a in all if 'Lost and Found' in a.desc])
    badgeManager.setStatus('Lost', lostn)
    print '10 Years! Cache ' + str(lostn)
    
    ##### CONTAINERS #####
    print '\n',
    types = [u'Not chosen', u'Large', u'Micro', u'Regular', u'Small', u'Other']
    found_types = [a.cache.container for a in all]
    container_hist = {}
    for con in found_types:
        container_hist[con] = container_hist.get(con,0) + 1
    
    for key in types:
        try:
            badgeManager.setStatus(key[:5], container_hist.get(key,0))
            print key + ' ' + str(container_hist.get(key,0))
        except NameError:
            print key + " No Match"      

    ######### D/T Matrix #############
    print '\n\t',

    dtm = [(float(a.cache.difficulty), float(a.cache.terrain))
           for a in all]
    matrix = defaultdict(lambda: defaultdict(lambda: 0))
    for pair in dtm:
        matrix[pair[0]][pair[1]] = matrix[pair[0]].get(pair[1],0) + 1
    difficult = terrain = [1.0, 1.5 , 2.0 , 2.5 , 3.0, 3.5, 4.0, 4.5, 5.0]
    mcount = 0
    for dif in difficult:
        for ter in terrain:
            amount = matrix[dif][ter]
            print("%3d" % amount),
            if amount > 0: 
                mcount += 1 
        print "\n\n\t",
    print "Found %d of 81 D/T combinations"% mcount
   
    badgeManager.setStatus('Matrix', mcount)
   
    ####### OTHERS #####
    print '\n',
    try:
        hccs = [wpt.cache for wpt in all
                if wpt.cache.terrain == u'5' and wpt.cache.difficulty == u'5']
    except AttributeError:
        return all
    badgeManager.setStatus('Adventur', len(hccs))
    print('HCC Caches: ' + str(len(hccs)) +
          " (" + str([a.name for a in hccs]) + ")")
    
    ftfs = [a.cache for a in all if 'FTF' in a.cache.logs[0].text]
    badgeManager.setStatus('FTF', len(ftfs))
    print('FTF Caches: ' + str(len(ftfs)) +
          " (" + str([a.name for a in ftfs]) + ")")

    print('\n'),
    if(not force_owned_update):
            try:
                owned = int(cache_mngr.get('OWNCACHES', 'caches_hidden'))
                ownedcaches = cache_mngr.get('OWNCACHES','caches')
                owned_events = int(cache_mngr.get('OWNCACHES', 'owned_events'))
            except NoOptionError:
                print "Cached data incomplete, please redownload with -o"
                owned = 0
                ownedcaches = []
                owned_events = 0
    else:
        print 'No list of hidden caches cached, retrieving new data ...'
        ownlist = con_mngr.get_owner_list()
        ownlist = re.compile("<script([^>]*)>.*?</script>",
                              re.DOTALL).sub("", ownlist)
        ownlist = re.compile("<span([^>]*)>.*?</span>",
                              re.DOTALL).sub("", ownlist)
        ownparser = OwnParser()
        ownparser.feed(ownlist)
        owned = ownparser.owncount
        owned_events = ownparser.own_event_count
        ownedcaches = ownparser.owncaches
        cache_mngr.set('OWNCACHES', 'caches_hidden', str(owned))
        cache_mngr.set('OWNCACHES', 'owned_events', str(owned_events))
        cache_mngr.set('OWNCACHES', 'caches', str(ownedcaches))
        with open('cache.dat', 'ab') as cachefile:
            cache_mngr.write(cachefile)
   
    badgeManager.setStatus('Owner', owned)
    print "Owner of " + str(owned) + ' Caches: ' + str(ownedcaches)

    badgeManager.setStatus('Host', owned_events)
    print "Hosted " + str(owned_events) + ' Events.'
    
    scuba = [a.name for a in all
             if (5,1) in [(b.id, b.inc) for b in a.cache.attributes]]
    badgeManager.setStatus('Scuba', len(scuba))
    
   
    ##### COUNTRIES #######
    print '\n',
    travel = [a.cache.country for a in all]
    travel_hist = {}
    for country in travel:
        travel_hist[country] = travel_hist.get(country, 0) + 1
    badgeManager.setStatus('Travelling', len(travel_hist))
    print 'Countries traveled ' + str(len(travel_hist)) + ': '+ str(travel_hist)
   
    try:
        with open("statelist.txt",'r') as filehandle:
            statelist = filehandle.read()
    except IOError:
        # Couldn't read file, download new.
        try:
            statelist = con_mngr.getcountrylist()
        except Exception:
            # Failed, abort.
            print "Not able to retrieve country list"
            raise
        else:
            # New statelist downloaded, saving for further use.
            try: 
                with open("statelist.txt",'w') as filehandle:
                    filehandle.write(statelist)
            except IOError:
                print("Could not write 'statelist.txt' file.\n"
                      "Continuing without saving")
    if statelist:
        # Only generate with valid statelist, else skip
        badgeManager.setCountryList(statelist)
        for country in travel_hist.keys():
            cbadge = stateBadge(country)
            cbadge.setStatus(len(Pers.stateList[country]))
            badgeManager.addBadge(cbadge)      
            print('Visited ' + str(len(Pers.stateList[country])) +
                  ' state(s) in ' + country + "\n\t" + 
                  str(Pers.stateList[country].keys()))
   
    ##### GEOGRAPHY #######
    print('\n'),
    badgeManager.setStatus('Clouds', Pers.hMax)
    print("Found cache above " + str(Pers.hMax) + "m N.N.")
    badgeManager.setStatus('Gound', Pers.hMin)
    print("Found cache below " + str(Pers.hMin) + "m N.N.")
    badgeManager.setStatus('Distance', Pers.max_distance[1])
    print("Found cache " + str(Pers.max_distance[0]) + " in " +
          str(Pers.max_distance[1]) + "km distance")
       
    #### COINS ##########
    print('\n'),
    if(cache_mngr.has_option('TRAVELITEMS', 'coins') and 
       cache_mngr.has_option('TRAVELITEMS', 'travelbugs') and 
       not force_tb_update):
        coins = int(cache_mngr.get('TRAVELITEMS', 'coins'))
        tbs   = int(cache_mngr.get('TRAVELITEMS', 'travelbugs'))
    else:
        print 'No Coin list cached, retrieving new data ...'
        coinlist = con_mngr.getmycoinlist()
        coinlist = re.compile("<script([^>]*)>.*?</script>", 
                              re.DOTALL).sub("", coinlist)
        coinlist = re.compile("<span([^>]*)>.*?</span>", 
                              re.DOTALL).sub("", coinlist)
        coinparser = CoinParser()
        coinparser.feed(coinlist)
        coins = coinparser.CoinCount
        tbs = coinparser.TBCount
        cache_mngr.set('TRAVELITEMS', 'travelbugs', str(tbs))
        cache_mngr.set('TRAVELITEMS', 'coins', str(coins))
        with open('cache.dat', 'wb') as cachefile:
            cache_mngr.write(cachefile)
   
    badgeManager.setStatus('Coin', coins)
    print "Coins " + str(coins)
    badgeManager.setStatus('Travelbug', tbs)
    print "Travelbugs " + str(tbs)
    
    #### DATE ##########
    print('\n'),
    cachebyday = defaultdict(lambda: 0)
    cachebydate = defaultdict(lambda: 0)
    for wpt in all:
        if 'Z' not in wpt.cache.logs[0].date:
            wpt.cache.logs[0].date += 'Z'
        found = wpt.cache.logs[0].date
        cachebyday[str(parse_datetime(found).date())] += 1
        cachebydate[parse_datetime(found).date().strftime('%m-%d')] += 1
    maxfind = 43 #max(cachebyday.values())
    for (key, value) in zip(cachebyday.keys(), cachebyday.values()):
        if value == maxfind:
            maxfinddate = key
    badgeManager.setStatus('Busy', maxfind)
    # print("Found %i caches on %s"% (maxfind, maxfinddate))
    badgeManager.setStatus('Calendar', len(cachebydate))
    print("Found caches on %d dates"% (len(cachebydate)))
    days = cachebyday.keys()
    days.sort()
    maxdays = dayscount = 1
    prev = "0000-00-00"
    for date in days:
        if int(date[-2:]) == int(prev[-2:]) + 1:            
            dayscount += 1
        elif (int(date[-2:]) == 1 and 
             int(prev[-2:]) == monthrange(int(prev[:4]) , int(prev[5:7]))[1]):
            dayscount += 1
        else:
            maxdays = max(dayscount, maxdays)
            dayscount = 1
        prev = date
    badgeManager.setStatus('Daily', maxdays)
    print "Found caches on %i consecutive days"% maxdays