10 class chooser(object):
11 """Base class of a thing that chooses pages"""
12 def get_page_list(self):
14 valid_filename = re.compile("([^_]+)_(\d+)_([^\.]+)\.html")
16 pages = [ f for f in os.listdir(constants.pages_dir)
17 if os.path.isfile(os.path.join(constants.pages_dir, f))]
19 result = re.match(valid_filename, page)
21 print(('chooser: candidate page: "%s"' % page))
22 if (result.group(3) != "none"):
23 freshness_requirement = int(result.group(3))
24 last_modified = int(os.path.getmtime(
25 os.path.join(constants.pages_dir, page)))
26 age = (now - last_modified)
27 if (age > freshness_requirement):
28 print(('"%s" is too old.' % page))
30 filenames.append(page)
33 def choose_next_page(self):
36 class weighted_random_chooser(chooser):
37 """Chooser that does it via weighted RNG"""
40 self.valid_filename = re.compile("([^_]+)_(\d+)_([^\.]+)\.html")
44 def choose_next_page(self):
45 if (self.pages == None or
46 self.count % 100 == 0):
47 self.pages = self.get_page_list()
51 for page in self.pages:
52 result = re.match(self.valid_filename, page)
54 weight = int(result.group(2))
55 weights.append(weight)
56 total_weight += weight
58 if (total_weight <= 0):
62 pick = random.randrange(0, total_weight - 1)
64 for x in range(0, len(weights)):
67 self.pages[x] != self.last_choice):
68 self.last_choice = self.pages[x]
72 class weighted_random_chooser_with_triggers(weighted_random_chooser):
73 """Same as WRC but has trigger events"""
74 def __init__(self, trigger_list):
75 weighted_random_chooser.__init__(self)
76 self.trigger_list = trigger_list
77 self.page_queue = set(())
79 def check_for_triggers(self):
81 for t in self.trigger_list:
82 x = t.get_triggered_page_list()
83 if x != None and len(x) > 0:
85 self.page_queue.add(y)
89 def choose_next_page(self):
90 if (self.pages == None or
91 self.count % 100 == 0):
92 self.pages = self.get_page_list()
94 triggered = self.check_for_triggers()
96 # First try to satisfy from the page queue
97 if (len(self.page_queue) > 0):
98 print("Pulling page from queue")
101 for t in self.page_queue:
102 if priority == None or t[1] > priority:
105 self.page_queue.remove((page, priority))
106 return page, triggered
108 # Fall back on weighted random choice.
110 return weighted_random_chooser.choose_next_page(self), False
112 class rotating_chooser(chooser):
113 """Chooser that does it in a rotation"""
115 self.valid_filename = re.compile("([^_]+)_(\d+)_([^\.]+)\.html")
120 def choose_next_page(self):
121 if (self.pages == None or
122 self.count % 100 == 0):
123 self.pages = self.get_page_list()
125 if len(self.pages) == 0:
128 if (self.current >= len(self.pages)):
131 page = self.pages[self.current]
136 #x = weighted_random_chooser_with_triggers(None)