summaryrefslogtreecommitdiff
path: root/lib/rss/rss.rb
blob: 9c616238febed49e021ee75adb8e4e514fd1b681 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# Copyright (c) 2003-2004 Kouhei Sutou.  You can redistribute it and/or
# modify it under the same terms as Ruby.
#
# Author:: Kouhei Sutou <kou@cozmixng.org>

require "time"

class Time
	class << self
		unless respond_to?(:w3cdtf)
			def w3cdtf(date)
				if /\A\s*
				    (-?\d+)-(\d\d)-(\d\d)
				    (?:T
				    (\d\d):(\d\d)(?::(\d\d))?
				    (\.\d+)?
				    (Z|[+-]\d\d:\d\d)?)?
				    \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8))
					datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i] 
					datetime << $7.to_f * 1000000 if $7
					if $8
						Time.utc(*datetime) - zone_offset($8)
					else
						Time.local(*datetime)
					end
				else
					raise ArgumentError.new("invalid date: #{date.inspect}")
				end
			end
		end
	end

	unless instance_methods.include?("w3cdtf")
		alias w3cdtf iso8601
	end
end

require "English"
require "rss/utils"
require "rss/converter"
require "rss/xml-stylesheet"

module RSS

	VERSION = "0.0.8"

	DEBUG = false

	class Error < StandardError; end

	class OverlappedPrefixError < Error
		attr_reader :prefix
		def initialize(prefix)
			@prefix = prefix
		end
	end

	class InvalidRSSError < Error; end

	class MissingTagError < InvalidRSSError
		attr_reader :tag, :parent
		def initialize(tag, parent)
			@tag, @parent = tag, parent
			super("tag <#{tag}> is missing in tag <#{parent}>")
		end
	end

	class TooMuchTagError < InvalidRSSError
		attr_reader :tag, :parent
		def initialize(tag, parent)
			@tag, @parent = tag, parent
			super("tag <#{tag}> is too much in tag <#{parent}>")
		end
	end

	class MissingAttributeError < InvalidRSSError
		attr_reader :tag, :attribute
		def initialize(tag, attribute)
			@tag, @attribute = tag, attribute
			super("attribute <#{attribute}> is missing in tag <#{tag}>")
		end
	end

	class UnknownTagError < InvalidRSSError
		attr_reader :tag, :uri
		def initialize(tag, uri)
			@tag, @uri = tag, uri
			super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>")
		end
	end

	class NotExceptedTagError < InvalidRSSError
		attr_reader :tag, :parent
		def initialize(tag, parent)
			@tag, @parent = tag, parent
			super("tag <#{tag}> is not expected in tag <#{parent}>")
		end
	end

	class NotAvailableValueError < InvalidRSSError
		attr_reader :tag, :value
		def initialize(tag, value)
			@tag, @value = tag, value
			super("value <#{value}> of tag <#{tag}> is not available.")
		end
	end

	class UnknownConversionMethodError < Error
		attr_reader :to, :from
		def initialize(to, from)
			@to = to
			@from = from
			super("can't convert to #{to} from #{from}.")
		end
	end
	# for backward compatibility
	UnknownConvertMethod = UnknownConversionMethodError

	class ConversionError < Error
		attr_reader :string, :to, :from
		def initialize(string, to, from)
			@string = string
			@to = to
			@from = from
			super("can't convert #{@string} to #{to} from #{from}.")
		end
	end

	module BaseModel

		include Utils

		def install_have_child_element(name)
			add_need_initialize_variable(name)

			attr_accessor name
			install_element(name) do |n, elem_name|
				<<-EOC
				if @#{n}
					"\#{indent}\#{@#{n}.to_s(convert)}"
				else
					''
				end
EOC
			end
		end
		alias_method(:install_have_attribute_element, :install_have_child_element)

		def install_have_children_element(name, postfix="s")
			add_have_children_element(name)

			def_children_accessor(name, postfix)
			install_element(name, postfix) do |n, elem_name|
				<<-EOC
				rv = ''
				@#{n}.each do |x|
					rv << "\#{indent}\#{x.to_s(convert)}"
				end
				rv
EOC
			end
		end

		def install_text_element(name)
			self::ELEMENTS << name
			add_need_initialize_variable(name)

			attr_writer name
			convert_attr_reader name
			install_element(name) do |n, elem_name|
				<<-EOC
				if @#{n}
					rv = "\#{indent}<#{elem_name}>"
					value = html_escape(@#{n})
					if convert and @converter
						rv << @converter.convert(value)
					else
						rv << value
					end
	  	    rv << "</#{elem_name}>"
					rv
				else
					''
				end
EOC
			end
		end

		def install_date_element(name, type, disp_name=name)
			self::ELEMENTS << name
			add_need_initialize_variable(name)

			# accessor
			convert_attr_reader name
			module_eval(<<-EOC, *get_file_and_line_from_caller(2))
			def #{name}=(new_value)
				if new_value.kind_of?(Time)
					@#{name} = new_value
				else
					if @do_validate
						begin
							@#{name} = Time.send('#{type}', new_value)
						rescue ArgumentError
							raise NotAvailableValueError.new('#{disp_name}', new_value)
						end
					else
						@#{name} = nil
						if /\\A\\s*\\z/ !~ new_value.to_s
							begin
								@#{name} = Time.parse(new_value)
							rescue ArgumentError
							end
						end
					end
				end

				# Is it need?
				if @#{name}
					class << @#{name}
						alias_method(:_to_s, :to_s) unless respond_to?(:_to_s)
						alias_method(:to_s, :#{type})
					end
				end

			end
EOC
			
			install_element(name) do |n, elem_name|
				<<-EOC
				if @#{n}
					rv = "\#{indent}<#{elem_name}>"
					value = html_escape(@#{n}.#{type})
					if convert and @converter
						rv << @converter.convert(value)
					else
						rv << value
					end
	  	    rv << "</#{elem_name}>"
					rv
				else
					''
				end
EOC
			end

		end

		private
		def install_element(name, postfix="")
			elem_name = name.sub('_', ':')
			module_eval(<<-EOC, *get_file_and_line_from_caller(2))
			def #{name}_element#{postfix}(convert=true, indent='')
				#{yield(name, elem_name)}
			end
			private :#{name}_element#{postfix}
EOC
		end

		def convert_attr_reader(*attrs)
			attrs.each do |attr|
				attr = attr.id2name if attr.kind_of?(Integer)
				module_eval(<<-EOC, *get_file_and_line_from_caller(2))
				def #{attr}
					if @converter
						@converter.convert(@#{attr})
					else
						@#{attr}
					end
				end
EOC
			end
		end

		def def_children_accessor(accessor_name, postfix="s")
			module_eval(<<-EOC, *get_file_and_line_from_caller(2))
			def #{accessor_name}#{postfix}
				@#{accessor_name}
			end

			def #{accessor_name}(*args)
				if args.empty?
					@#{accessor_name}.first
				else
					@#{accessor_name}.send("[]", *args)
				end
			end
				
			def #{accessor_name}=(*args)
				if args.size == 1
					@#{accessor_name}.push(args[0])
				else
					@#{accessor_name}.send("[]=", *args)
				end
			end
			alias_method(:set_#{accessor_name}, :#{accessor_name}=)
EOC
		end

	end

	URI = "http://purl.org/rss/1.0/"

	class Element

		extend BaseModel
		include Utils

		class << self

			def inherited(klass)
				klass.module_eval(<<-EOC)
				public
				
				TAG_NAME = name.split('::').last.downcase


				@@must_call_validators = {::RSS::URI => ''}

				def self.must_call_validators
					@@must_call_validators
				end

				def self.install_must_call_validator(prefix, uri)
					@@must_call_validators[uri] = prefix
				end
				
				@@model = []

				def self.model
					@@model
				end

				def self.install_model(tag, occurs=nil)
					if m = @@model.find {|t, o| t == tag}
						m[1] = occurs
					else
						@@model << [tag, occurs]
					end
				end

				@@get_attributes = []
				
				def self.get_attributes()
					@@get_attributes
				end

				def self.install_get_attribute(name, uri, required=true)
					attr_writer name
					convert_attr_reader name
					@@get_attributes << [name, uri, required]
				end

				@@have_content = false

				def self.content_setup
					attr_writer :content
					convert_attr_reader :content
					@@have_content = true
				end

				def self.have_content?
					@@have_content
				end

				@@have_children_elements = []

				def self.have_children_elements
					@@have_children_elements
				end

				def self.add_have_children_element(variable_name)
					@@have_children_elements << variable_name
				end
				
				@@need_initialize_variables = []
				
				def self.add_need_initialize_variable(variable_name)
					@@need_initialize_variables << variable_name
				end
				
				def self.need_initialize_variables
					@@need_initialize_variables
				end

				EOC
			end

			def required_prefix
				nil
			end

			def required_uri
				nil
			end
			
			def install_ns(prefix, uri)
				if self::NSPOOL.has_key?(prefix)
					raise OverlappedPrefixError.new(prefix)
				end
				self::NSPOOL[prefix] = uri
			end

		end

		attr_accessor :do_validate

		def initialize(do_validate=true)
			@converter = nil
			@do_validate = do_validate
			initialize_variables
		end

		def tag_name
			self.class::TAG_NAME
		end

		def converter=(converter)
			@converter = converter
			children.each do |child|
				child.converter = converter unless child.nil?
			end
		end
		
		def validate
			validate_attribute
			__validate
		end
		
		def validate_for_stream(tags)
			__validate(tags, false)
		end

    private
		def initialize_variables
			self.class.need_initialize_variables.each do |variable_name|
				instance_eval("@#{variable_name} = nil")
			end
			initialize_have_children_elements
			@content = "" if self.class.have_content?
		end

		def initialize_have_children_elements
			self.class.have_children_elements.each do |variable_name|
				instance_eval("@#{variable_name} = []")
			end
		end

		# not String class children.
		def children
			[]
		end

		# default #validate() argument.
		def _tags
			[]
		end

		def _attrs
			[]
		end

		def __validate(tags=_tags, recursive=true)
			if recursive
				children.compact.each do |child|
					child.validate
				end
			end
			must_call_validators = self.class.must_call_validators
			tags = tag_filter(tags.dup)
			p tags if DEBUG
			self.class::NSPOOL.each do |prefix, uri|
				if tags.has_key?(uri) and !must_call_validators.has_key?(uri)
					meth = "#{prefix}_validate"
					send(meth, tags[uri]) if respond_to?(meth, true)
				end
			end
			must_call_validators.each do |uri, prefix|
				send("#{prefix}_validate", tags[uri])
			end
		end

		def validate_attribute
			_attrs.each do |a_name, required|
				if required and send(a_name).nil?
					raise MissingAttributeError.new(self.class::TAG_NAME, a_name)
				end
			end
		end

		def other_element(convert, indent='')
			rv = ''
			private_methods.each do |meth|
				if /\A([^_]+)_[^_]+_elements?\z/ =~ meth and
						self.class::NSPOOL.has_key?($1)
					res = send(meth, convert)
					rv << "#{indent}#{res}\n" if /\A\s*\z/ !~ res
				end
			end
			rv
		end

		def _validate(tags, model=self.class.model)
			count = 1
			do_redo = false
			not_shift = false
			tag = nil

			model.each_with_index do |elem, i|

				if DEBUG
					p "before" 
					p tags
					p elem
				end

				if not_shift
					not_shift = false
				elsif tags
					tag = tags.shift
				end

				if DEBUG
					p "mid"
					p count
				end

				case elem[1]
				when '?'
					if count > 2
						raise TooMuchTagError.new(elem[0], tag_name)
					else
						if elem[0] == tag
							do_redo = true
						else
							not_shift = true
						end
					end
				when '*'
					if elem[0] == tag
						do_redo = true
					else
						not_shift = true
					end
				when '+'
					if elem[0] == tag
						do_redo = true
					else
						if count > 1
							not_shift = true
						else
							raise MissingTagError.new(elem[0], tag_name)
						end
					end
				else
					if elem[0] == tag
						if model[i+1] and model[i+1][0] != elem[0] and
								tags and tags.first == elem[0]
							raise TooMuchTagError.new(elem[0], tag_name)
						end
					else
						raise MissingTagError.new(elem[0], tag_name)
					end
				end

				if DEBUG
					p "after"
					p not_shift
					p do_redo
					p tag
				end

				if do_redo
					do_redo = false
					count += 1
					redo
				else
					count = 1
				end

			end

			if !tags.nil? and !tags.empty?
				raise NotExceptedTagError.new(tag, tag_name)
			end

		end

		def tag_filter(tags)
			rv = {}
			tags.each do |tag|
				rv[tag[0]] = [] unless rv.has_key?(tag[0])
				rv[tag[0]].push(tag[1])
			end
			rv
		end

	end

	module RootElementMixin

		attr_reader :output_encoding

		def initialize(rss_version, version=nil, encoding=nil, standalone=nil)
			super()
			@rss_version = rss_version
			@version = version || '1.0'
			@encoding = encoding
			@standalone = standalone
			@output_encoding = nil
		end

		def output_encoding=(enc)
			@output_encoding = enc
			self.converter = Converter.new(@output_encoding, @encoding)
		end

		private
		def xmldecl
			rv = %Q[<?xml version="#{@version}"]
			if @output_encoding or @encoding
				rv << %Q[ encoding="#{@output_encoding or @encoding}"]
			end
			rv << %Q[ standalone="#{@standalone}"] if @standalone
			rv << '?>'
			rv
		end
		
		def ns_declaration
			rv = ''
			self.class::NSPOOL.each do |prefix, uri|
				prefix = ":#{prefix}" unless prefix.empty?
				rv << %Q|\n\txmlns#{prefix}="#{html_escape(uri)}"|
			end
			rv
		end
		
	end

end