]> git.cworth.org Git - sup/blob - lib/sup/index.rb
remove out-of-date comments about the hook system
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'fileutils'
4 require 'ferret'
5
6 begin
7   require 'chronic'
8   $have_chronic = true
9 rescue LoadError => e
10   Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
11   $have_chronic = false
12 end
13
14 module Redwood
15
16 class Index
17   class LockError < StandardError
18     def initialize h
19       @h = h
20     end
21
22     def method_missing m; @h[m.to_s] end
23   end
24
25   include Singleton
26
27   HookManager.register "custom-search", <<EOS
28 Executes before a string search is applied to the index,
29 returning a new search string.
30 Variables:
31   subs: The string being searched.
32 EOS
33
34   ## these two accessors should ONLY be used by single-threaded programs.
35   ## otherwise you will have a naughty ferret on your hands.
36   attr_reader :index
37   alias ferret index
38
39   def initialize dir=BASE_DIR
40     @index_mutex = Monitor.new
41
42     @dir = dir
43     @sources = {}
44     @sources_dirty = false
45     @source_mutex = Monitor.new
46
47     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
48     sa = Ferret::Analysis::StandardAnalyzer.new [], true
49     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
50     @analyzer[:body] = sa
51     @analyzer[:subject] = sa
52     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
53     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
54
55     self.class.i_am_the_instance self
56   end
57
58   def lockfile; File.join @dir, "lock" end
59
60   def lock
61     Redwood::log "locking #{lockfile}..."
62     begin
63       @lock.lock
64     rescue Lockfile::MaxTriesLockError
65       raise LockError, @lock.lockinfo_on_disk
66     end
67   end
68
69   def start_lock_update_thread
70     @lock_update_thread = Redwood::reporting_thread("lock update") do
71       while true
72         sleep 30
73         @lock.touch_yourself
74       end
75     end
76   end
77
78   def stop_lock_update_thread
79     @lock_update_thread.kill if @lock_update_thread
80     @lock_update_thread = nil
81   end
82
83   def possibly_pluralize number_of, kind
84     "#{number_of} #{kind}" +
85         if number_of == 1 then "" else "s" end
86   end
87
88   def fancy_lock_error_message_for e
89     secs = (Time.now - e.mtime).to_i
90     mins = secs / 60
91     time =
92       if mins == 0
93         possibly_pluralize secs , "second"
94       else
95         possibly_pluralize mins, "minute"
96       end
97
98     <<EOS
99 Error: the sup index is locked by another process! User '#{e.user}' on
100 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
101 as of #{time} ago.
102 EOS
103   end
104
105   def lock_or_die
106     begin
107       lock
108     rescue LockError => e
109       $stderr.puts fancy_lock_error_message_for(e)
110       $stderr.puts <<EOS
111
112 You can wait for the process to finish, or, if it crashed and left a
113 stale lock file behind, you can manually delete #{@lock.path}.
114 EOS
115       exit
116     end
117   end
118
119   def unlock
120     if @lock && @lock.locked?
121       Redwood::log "unlocking #{lockfile}..."
122       @lock.unlock
123     end
124   end
125
126   def load
127     load_sources
128     load_index
129   end
130
131   def save
132     Redwood::log "saving index and sources..."
133     FileUtils.mkdir_p @dir unless File.exists? @dir
134     save_sources
135     save_index
136   end
137
138   def add_source source
139     @source_mutex.synchronize do
140       raise "duplicate source!" if @sources.include? source
141       @sources_dirty = true
142       max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
143       source.id ||= (max || 0) + 1
144       ##source.id += 1 while @sources.member? source.id
145       @sources[source.id] = source
146     end
147   end
148
149   def sources
150     ## favour the inbox by listing non-archived sources first
151     @source_mutex.synchronize { @sources.values }.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
152   end
153
154   def source_for uri; sources.find { |s| s.is_source_for? uri }; end
155   def usual_sources; sources.find_all { |s| s.usual? }; end
156
157   def load_index dir=File.join(@dir, "ferret")
158     if File.exists? dir
159       Redwood::log "loading index..."
160       @index_mutex.synchronize do
161         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
162         Redwood::log "loaded index of #{@index.size} messages"
163       end
164     else
165       Redwood::log "creating index..."
166       @index_mutex.synchronize do
167         field_infos = Ferret::Index::FieldInfos.new :store => :yes
168         field_infos.add_field :message_id, :index => :untokenized
169         field_infos.add_field :source_id
170         field_infos.add_field :source_info
171         field_infos.add_field :date, :index => :untokenized
172         field_infos.add_field :body
173         field_infos.add_field :label
174         field_infos.add_field :attachments
175         field_infos.add_field :subject
176         field_infos.add_field :from
177         field_infos.add_field :to
178         field_infos.add_field :refs
179         field_infos.add_field :snippet, :index => :no, :term_vector => :no
180         field_infos.create_index dir
181         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
182       end
183     end
184   end
185
186   ## Syncs the message to the index, replacing any previous version.  adding
187   ## either way. Index state will be determined by the message's #labels
188   ## accessor.
189   ##
190   ## if need_load is false, docid and entry are assumed to be set to the
191   ## result of load_entry_for_id (which can be nil).
192   def sync_message m, need_load=true, docid=nil, entry=nil, opts={}
193     docid, entry = load_entry_for_id m.id if need_load
194
195     raise "no source info for message #{m.id}" unless m.source && m.source_info
196     @index_mutex.synchronize do
197       raise "trying to delete non-corresponding entry #{docid} with index message-id #{@index[docid][:message_id].inspect} and parameter message id #{m.id.inspect}" if docid && @index[docid][:message_id] != m.id
198     end
199
200     source_id = if m.source.is_a? Integer
201       m.source
202     else
203       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
204     end
205
206     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
207       ""
208     else
209       m.snippet
210     end
211
212     ## write the new document to the index. if the entry already exists in the
213     ## index, reuse it (which avoids having to reload the entry from the source,
214     ## which can be quite expensive for e.g. large threads of IMAP actions.)
215     ##
216     ## exception: if the index entry belongs to an earlier version of the
217     ## message, use everything from the new message instead, but union the
218     ## flags. this allows messages sent to mailing lists to have their header
219     ## updated and to have flags set properly.
220     ##
221     ## minor hack: messages in sources with lower ids have priority over
222     ## messages in sources with higher ids. so messages in the inbox will
223     ## override everyone, and messages in the sent box will be overridden
224     ## by everyone else.
225     ##
226     ## written in this manner to support previous versions of the index which
227     ## did not keep around the entry body. upgrading is thus seamless.
228     entry ||= {}
229     labels = m.labels.uniq # override because this is the new state, unless...
230
231     ## if we are a later version of a message, ignore what's in the index,
232     ## but merge in the labels.
233     if entry[:source_id] && entry[:source_info] && entry[:label] &&
234       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
235       labels = (entry[:label].symbolistize + m.labels).uniq
236       #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
237       #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
238       #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
239       entry = {}
240     end
241
242     ## if force_overwite is true, ignore what's in the index. this is used
243     ## primarily by sup-sync to force index updates.
244     entry = {} if opts[:force_overwrite]
245
246     d = {
247       :message_id => m.id,
248       :source_id => source_id,
249       :source_info => m.source_info,
250       :date => (entry[:date] || m.date.to_indexable_s),
251       :body => (entry[:body] || m.indexable_content),
252       :snippet => snippet, # always override
253       :label => labels.uniq.join(" "),
254       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
255
256       ## always override :from and :to.
257       ## older versions of Sup would often store the wrong thing in the index
258       ## (because they were canonicalizing email addresses, resulting in the
259       ## wrong name associated with each.) the correct address is read from
260       ## the original header when these messages are opened in thread-view-mode,
261       ## so this allows people to forcibly update the address in the index by
262       ## marking those threads for saving.
263       :from => (m.from ? m.from.indexable_content : ""),
264       :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
265
266       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
267       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
268     }
269
270     @index_mutex.synchronize do
271       @index.delete docid if docid
272       @index.add_document d
273     end
274
275     ## this hasn't been triggered in a long time.
276     ## docid, entry = load_entry_for_id m.id
277     ## raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
278   end
279
280   def save_index fn=File.join(@dir, "ferret")
281     # don't have to do anything, apparently
282   end
283
284   def contains_id? id
285     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
286   end
287   def contains? m; contains_id? m.id end
288   def size; @index_mutex.synchronize { @index.size } end
289   def empty?; size == 0 end
290
291   ## you should probably not call this on a block that doesn't break
292   ## rather quickly because the results can be very large.
293   EACH_BY_DATE_NUM = 100
294   def each_id_by_date opts={}
295     return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
296     query = build_query opts
297     offset = 0
298     while true
299       limit = (opts[:limit])? [EACH_BY_DATE_NUM, opts[:limit] - offset].min : EACH_BY_DATE_NUM
300       results = @index_mutex.synchronize { @index.search query, :sort => "date DESC", :limit => limit, :offset => offset }
301       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
302       results.hits.each do |hit|
303         yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
304       end
305       break if opts[:limit] and offset >= opts[:limit] - limit
306       break if offset >= results.total_hits - limit
307       offset += limit
308     end
309   end
310
311   def num_results_for opts={}
312     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
313
314     q = build_query opts
315     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits }
316   end
317
318   ## yield all messages in the thread containing 'm' by repeatedly
319   ## querying the index. yields pairs of message ids and
320   ## message-building lambdas, so that building an unwanted message
321   ## can be skipped in the block if desired.
322   ##
323   ## only two options, :limit and :skip_killed. if :skip_killed is
324   ## true, stops loading any thread if a message with a :killed flag
325   ## is found.
326   SAME_SUBJECT_DATE_LIMIT = 7
327   MAX_CLAUSES = 1000
328   def each_message_in_thread_for m, opts={}
329     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
330     messages = {}
331     searched = {}
332     num_queries = 0
333
334     pending = [m.id]
335     if $config[:thread_by_subject] # do subject queries
336       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
337       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
338
339       q = Ferret::Search::BooleanQuery.new true
340       sq = Ferret::Search::PhraseQuery.new(:subject)
341       wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
342         sq.add_term t
343       end
344       q.add_query sq, :must
345       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
346
347       q = build_query :qobj => q
348
349       p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
350       Redwood::log "found #{p1.size} results for subject query #{q}"
351
352       p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
353       Redwood::log "found #{p2.size} results in string form"
354
355       pending = (pending + p1 + p2).uniq
356     end
357
358     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
359       q = Ferret::Search::BooleanQuery.new true
360       # this disappeared in newer ferrets... wtf.
361       # q.max_clause_count = 2048
362
363       lim = [MAX_CLAUSES / 2, pending.length].min
364       pending[0 ... lim].each do |id|
365         searched[id] = true
366         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
367         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
368       end
369       pending = pending[lim .. -1]
370
371       q = build_query :qobj => q
372
373       num_queries += 1
374       killed = false
375       @index_mutex.synchronize do
376         @index.search_each(q, :limit => :all) do |docid, score|
377           break if opts[:limit] && messages.size >= opts[:limit]
378           if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
379             killed = true
380             break
381           end
382           mid = @index[docid][:message_id]
383           unless messages.member?(mid)
384             #Redwood::log "got #{mid} as a child of #{id}"
385             messages[mid] ||= lambda { build_message docid }
386             refs = @index[docid][:refs].split
387             pending += refs.select { |id| !searched[id] }
388           end
389         end
390       end
391     end
392
393     if killed
394       Redwood::log "thread for #{m.id} is killed, ignoring"
395       false
396     else
397       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
398       messages.each { |mid, builder| yield mid, builder }
399       true
400     end
401   end
402
403   ## builds a message object from a ferret result
404   def build_message docid
405     @index_mutex.synchronize do
406       doc = @index[docid]
407
408       source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
409       raise "invalid source #{doc[:source_id]}" unless source
410
411       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
412
413       fake_header = {
414         "date" => Time.at(doc[:date].to_i),
415         "subject" => unwrap_subj(doc[:subject]),
416         "from" => doc[:from],
417         "to" => doc[:to].split.join(", "), # reformat
418         "message-id" => doc[:message_id],
419         "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
420       }
421
422       m = Message.new :source => source, :source_info => doc[:source_info].to_i,
423                   :labels => doc[:label].symbolistize,
424                   :snippet => doc[:snippet]
425       m.parse_header fake_header
426       m
427     end
428   end
429
430   def fresh_thread_id; @next_thread_id += 1; end
431   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
432   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
433
434   def drop_entry docno; @index_mutex.synchronize { @index.delete docno } end
435
436   def load_entry_for_id mid
437     @index_mutex.synchronize do
438       results = @index.search Ferret::Search::TermQuery.new(:message_id, mid)
439       return if results.total_hits == 0
440       docid = results.hits[0].doc
441       entry = @index[docid]
442       entry_dup = entry.fields.inject({}) { |h, f| h[f] = entry[f]; h }
443       [docid, entry_dup]
444     end
445   end
446
447   def load_contacts emails, h={}
448     q = Ferret::Search::BooleanQuery.new true
449     emails.each do |e|
450       qq = Ferret::Search::BooleanQuery.new true
451       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
452       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
453       q.add_query qq
454     end
455     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
456     
457     Redwood::log "contact search: #{q}"
458     contacts = {}
459     num = h[:num] || 20
460     @index_mutex.synchronize do
461       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
462         break if contacts.size >= num
463         #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
464         f = @index[docid][:from]
465         t = @index[docid][:to]
466
467         if AccountManager.is_account_email? f
468           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
469         else
470           contacts[Person.from_address(f)] = true
471         end
472       end
473     end
474
475     contacts.keys.compact
476   end
477
478   def load_sources fn=Redwood::SOURCE_FN
479     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
480     @source_mutex.synchronize do
481       @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
482       @sources_dirty = false
483     end
484   end
485
486   def has_any_from_source_with_label? source, label
487     q = Ferret::Search::BooleanQuery.new
488     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
489     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
490     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
491   end
492
493   ## takes a user query string and returns the list of docids for messages
494   ## that match the query.
495   ##
496   ## messages can then be loaded from the index with #build_message.
497   ##
498   ## raises a ParseError if the parsing failed.
499   def run_query query
500     qobj, opts = Redwood::Index.parse_user_query_string query
501     query = Redwood::Index.build_query opts.merge(:qobj => qobj)
502     results = @index.search query, :limit => (opts[:limit] || :all)
503     results.hits.map { |hit| hit.doc }
504   end
505
506 protected
507
508   class ParseError < StandardError; end
509
510   ## parse a query string from the user. returns a query object and a set of
511   ## extra flags; both of these are meant to be passed to #build_query.
512   ##
513   ## raises a ParseError if something went wrong.
514   def parse_user_query_string s
515     extraopts = {}
516
517     subs = HookManager.run("custom-search", :subs => s) || s
518
519     subs = subs.gsub(/\b(to|from):(\S+)\b/) do
520       field, name = $1, $2
521       if(p = ContactManager.contact_for(name))
522         [field, p.email]
523       elsif name == "me"
524         [field, "(" + AccountManager.user_emails.join("||") + ")"]
525       else
526         [field, name]
527       end.join(":")
528     end
529
530     ## if we see a label:deleted or a label:spam term anywhere in the query
531     ## string, we set the extra load_spam or load_deleted options to true.
532     ## bizarre? well, because the query allows arbitrary parenthesized boolean
533     ## expressions, without fully parsing the query, we can't tell whether
534     ## the user is explicitly directing us to search spam messages or not.
535     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
536     ## search spam messages or not?
537     ##
538     ## so, we rely on the fact that turning these extra options ON turns OFF
539     ## the adding of "-label:deleted" or "-label:spam" terms at the very
540     ## final stage of query processing. if the user wants to search spam
541     ## messages, not adding that is the right thing; if he doesn't want to
542     ## search spam messages, then not adding it won't have any effect.
543     extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
544     extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
545
546     ## gmail style "is" operator
547     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
548       field, label = $1, $2
549       case label
550       when "read"
551         "-label:unread"
552       when "spam"
553         extraopts[:load_spam] = true
554         "label:spam"
555       when "deleted"
556         extraopts[:load_deleted] = true
557         "label:deleted"
558       else
559         "label:#{$2}"
560       end
561     end
562
563     ## gmail style attachments "filename" and "filetype" searches
564     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
565       field, name = $1, ($3 || $4)
566       case field
567       when "filename"
568         Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
569         "attachments:(#{name.downcase})"
570       when "filetype"
571         Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
572         "attachments:(*.#{name.downcase})"
573       end
574     end
575
576     if $have_chronic
577       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
578         field, datestr = $1, ($3 || $4)
579         realdate = Chronic.parse datestr, :guess => false, :context => :past
580         if realdate
581           case field
582           when "after"
583             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
584             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
585           when "before"
586             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
587             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
588           else
589             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
590             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
591           end
592         else
593           raise ParseError, "can't understand date #{datestr.inspect}"
594         end
595       end
596     end
597
598     ## limit:42 restrict the search to 42 results
599     subs = subs.gsub(/\blimit:(\S+)\b/) do
600       lim = $1
601       if lim =~ /^\d+$/
602         extraopts[:limit] = lim.to_i
603         ''
604       else
605         raise ParseError, "non-numeric limit #{lim.inspect}"
606       end
607     end
608     
609     begin
610       [@qparser.parse(subs), extraopts]
611     rescue Ferret::QueryParser::QueryParseException => e
612       raise ParseError, e.message
613     end
614   end
615
616   def build_query opts
617     query = Ferret::Search::BooleanQuery.new
618     query.add_query opts[:qobj], :must if opts[:qobj]
619     labels = ([opts[:label]] + (opts[:labels] || [])).compact
620     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
621     if opts[:participants]
622       q2 = Ferret::Search::BooleanQuery.new
623       opts[:participants].each do |p|
624         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
625         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
626       end
627       query.add_query q2, :must
628     end
629         
630     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
631     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
632     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
633     query
634   end
635
636   def save_sources fn=Redwood::SOURCE_FN
637     @source_mutex.synchronize do
638       if @sources_dirty || @sources.any? { |id, s| s.dirty? }
639         bakfn = fn + ".bak"
640         if File.exists? fn
641           File.chmod 0600, fn
642           FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
643         end
644         Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
645         File.chmod 0600, fn
646       end
647       @sources_dirty = false
648     end
649   end
650 end
651
652 end