]> git.cworth.org Git - sup/blob - lib/sup/poll.rb
todo: added attach messages
[sup] / lib / sup / poll.rb
1 require 'thread'
2
3 module Redwood
4
5 class PollManager
6   include Singleton
7
8   DELAY = 300
9
10   def initialize
11     @mutex = Mutex.new
12     @last_poll = nil
13     
14     self.class.i_am_the_instance self
15   end
16
17   def buffer
18     BufferManager.spawn_unless_exists("<poll for new messages>", :hidden => true) { PollMode.new }
19   end
20
21   def poll
22     BufferManager.flash "Polling for new messages..."
23     num, numi = buffer.mode.poll
24     if num > 0
25       BufferManager.flash "Loaded #{num} new messages, #{numi} to inbox." 
26     else
27       BufferManager.flash "No new messages." 
28     end
29     [num, numi]
30   end
31
32   def start_thread
33     Redwood::reporting_thread do
34       while true
35         sleep DELAY / 2
36         poll if @last_poll.nil? || (Time.now - @last_poll) >= DELAY
37       end
38     end
39   end
40
41   def do_poll
42     total_num = total_numi = 0
43     @mutex.synchronize do
44       found = {}
45       Index.usual_sources.each do |source|
46         yield "Loading from #{source}... " unless source.done? || source.broken?
47         num = 0
48         numi = 0
49         Index.add_new_messages_from source do |m, offset, source_labels, entry|
50           yield "Found message at #{offset} with labels #{m.labels * ', '}"
51           num += 1
52           numi += 1 if m.labels.include? :inbox
53           m
54         end
55         yield "Found #{num} messages, #{numi} to inbox" unless num == 0
56         total_num += num
57         total_numi += numi
58       end
59
60       yield "Done polling; loaded #{total_num} new messages total"
61       @last_poll = Time.now
62       @polling = false
63     end
64     [total_num, total_numi]
65   end
66 end
67
68 end