summaryrefslogtreecommitdiff
path: root/lib/feed2imap/html2text-parser.rb
blob: a6bf4004fecd3001d271d1aac16f3a16870b6d7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
=begin
Feed2Imap - RSS/Atom Aggregator uploading to an IMAP Server
Copyright (c) 2005 Lucas Nussbaum <lucas@lucas-nussbaum.net>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
=end

require 'feed2imap/sgml-parser.rb'

# this class provides a simple SGML parser that removes HTML tags
class HTML2TextParser < SGMLParser

  attr_reader :savedata

  def initialize(verbose = false)
    @savedata = ''
    @pre = false
    @href = nil
    @links = []
    super(verbose)
  end

  def handle_data(data)
    # let's remove all CR
    data.gsub!(/\n/, '') if not @pre
 
    @savedata << data
  end

  def unknown_starttag(tag, attrs)
    case tag
    when 'p'
      @savedata << "\n\n"
    when 'br'
      @savedata << "\n"
    when 'b'
      @savedata << '*'
    when 'u'
      @savedata << '_'
    when 'i'
      @savedata << '/'
    when 'pre'
      @savedata << "\n\n"
      @pre = true
    when 'a'
      # find href in args
      @href = nil
      attrs.each do |a|
        if a[0] == 'href'
          @href = a[1]
        end
      end
      @links << @href.gsub(/^("|'|)(.*)("|')$/,'\2')
    end
  end

  def close
    super
    if @links.length > 0
      @savedata << "\n\n"
      @links.each_index do |i|
        @savedata << "[#{i+1}] #{@links[i]}\n"
      end
    end
  end

  def unknown_endtag(tag)
    case tag
    when 'b'
      @savedata << '*'
    when 'u'
      @savedata << '_'
    when 'i'
      @savedata << '/'
    when 'pre'
      @savedata << "\n\n"
      @pre = false
    when 'a'
      if @href
        @savedata << "[#{@links.length}]"
        @href = nil
      end
    end
  end
end