]> git.cworth.org Git - sup/blob - lib/sup/poll.rb
moved evertying to devel
[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     @polling = false
12     @last_poll = nil
13     
14     self.class.i_am_the_instance self
15
16     ::Thread.new do
17       while true
18         sleep DELAY / 2
19         if @last_poll.nil? || (Time.now - @last_poll) >= DELAY
20           mbid = BufferManager.say "Polling for new messages..."
21           num, numi = poll { |s| BufferManager.say s, mbid }
22           BufferManager.clear mbid
23           BufferManager.flash "Loaded #{num} new messages, #{numi} to inbox." if num > 0
24         end
25       end
26     end
27   end
28
29   def poll
30     return [0, 0] if @polling
31     @polling = true
32     found = {}
33     total_num = 0
34     total_numi = 0
35     Index.usual_sources.each do |source|
36       next if source.done?
37       yield "Loading from #{source}... "
38
39       start_offset = nil
40       num = 0
41       num_inbox = 0
42       source.each do |offset, labels|
43         start_offset ||= offset
44
45         begin
46           m = Redwood::Message.new source, offset, labels
47           if found[m.id]
48             yield "Skipping duplicate message #{m.id}"
49             next
50           else
51             found[m.id] = true
52           end
53           
54           if Index.add_message m
55             UpdateManager.relay :add, m
56             num += 1
57             total_num += 1
58             total_numi += 1 if m.labels.include? :inbox
59           end
60         rescue Redwood::MessageFormatError => e
61           yield "Ignoring erroneous message at #{source}##{offset}: #{e.message}"
62         end
63
64         if num % 1000 == 0 && num > 0
65           elapsed = Time.now - start
66           pctdone = (offset.to_f - start_offset) / (source.total.to_f - start_offset)
67           remaining = (source.total.to_f - offset.to_f) * (elapsed.to_f / (offset.to_f - start_offset))
68           yield "## #{num} (#{(pctdone * 100.0)}% done) read; #{elapsed.to_time_s} elapsed; est. #{remaining.to_time_s} remaining"
69         end
70       end
71       yield "Found #{num} messages" unless num == 0
72     end
73     yield "Done polling; loaded #{total_num} new messages total"
74     @last_poll = Time.now
75     @polling = false
76     [total_num, total_numi]
77   end
78 end
79
80 end