-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathevent.rb
More file actions
579 lines (499 loc) · 19.2 KB
/
event.rb
File metadata and controls
579 lines (499 loc) · 19.2 KB
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
# == Schema Information
# Schema version: 20111110144520
#
# Table name: events
#
# id :integer not null, primary key
# title :string(255)
# description :text
# start_time :datetime
# url :string(255)
# created_at :datetime
# updated_at :datetime
# venue_id :integer
# source_id :integer
# duplicate_of_id :integer
# end_time :datetime
# version :integer
# rrule :string(255)
# venue_details :text
# organization_id :integer
#
# == Event
#
# A model representing a calendar event.
class Event < ActiveRecord::Base
include SearchEngine
include AssociatedVenues
include UrlValidator
# Treat any event with a duration of at least this many hours as a multiday
# event. This constant is used by the #multiday? method and is primarily
# meant to make iCalendar exports display this event as covering a range of
# days, rather than hours.
MIN_MULTIDAY_DURATION = 20.hours
has_paper_trail :meta => { :site_id => :site_id }
acts_as_taggable
xss_foliate :strip => [:title], :sanitize => [:description, :venue_details]
include DecodeHtmlEntitiesHack
# Associations
scope_to_current_site
belongs_to :site
belongs_to :venue, :counter_cache => true
belongs_to :source
belongs_to :organization
has_and_belongs_to_many :types
has_and_belongs_to_many :topics
before_create :associate_source_topics_types, :if => :source
# Validations
validates_presence_of :title, :start_time
validate :end_time_later_than_start_time
before_validation :normalize_url!
validates_format_of :url,
:with => WEBSITE_FORMAT,
:allow_blank => true,
:allow_nil => true
include ValidatesBlacklistOnMixin
validates_blacklist_on :title, :description, :url
include UpdateUpdatedAtMixin
include VersionDiff
# Duplicates
include DuplicateChecking
duplicate_checking_ignores_attributes :source_id, :version, :venue_id, :description, :url, :rrule, :venue_details, :organization_id
duplicate_squashing_ignores_associations :tags, :base_tags, :taggings
after_save :inherit_organizations_venue
# Named scopes
scope :on_or_after_date, lambda { |date|
time = date.beginning_of_day
where("(start_time >= :time) OR (end_time IS NOT NULL AND end_time > :time)",
:time => time).order(:start_time)
}
scope :before_date, lambda { |date|
time = date.beginning_of_day
where("start_time < :time", :time => time).order(:start_time)
}
scope :future, lambda { on_or_after_date(Time.zone.today) }
scope :past, lambda { before_date(Time.zone.today) }
scope :within_dates, lambda { |start_date, end_date|
if start_date == end_date
end_date = end_date + 1.day
end
on_or_after_date(start_date).before_date(end_date)
}
# Expand the simple sort order names from the URL into more intelligent SQL order strings
scope :ordered_by_ui_field, lambda{|ui_field|
case ui_field
when 'name'
order('lower(events.title), start_time')
when 'venue'
includes(:venue).order('lower(venues.title), start_time')
else # when 'date', nil
order('start_time')
end
}
def inherit_organizations_venue
if organization.present? && organization.venue && (venue.nil? || !venue.valid?)
self.venue = Venue.where(id: organization.venue_id).first
self.save!
end
end
#---[ Overrides ]-------------------------------------------------------
# Return the title but strip out any whitespace.
def title
# TODO Generalize this code so we can use it on other attributes in the different model classes. The solution should use an #alias_method_chain to make sure it's not breaking any explicit overrides for an attribute.
return read_attribute(:title).try {|t| t.to_s.strip }
end
def title=(title)
super(title.try {|t| t.strip[0,255] })
end
# Return description without those pesky carriage-returns.
def description
# TODO Generalize this code so we can reuse it on other attributes.
return read_attribute(:description).try {|d| d.to_s.gsub("\r\n", "\n").gsub("\r", "\n") }
end
if (table_exists? rescue nil)
# XXX Horrible hack to materialize the #start_time= and #end_time= methods so they can be aliased by #start_time_with_smarter_setter= and #end_time_with_smarter_setter=.
Event.new(:start_time => Time.zone.now, :end_time => Time.zone.now)
# Set the start_time from one of a number of time values, a string, or an
# array of strings.
def start_time_with_smarter_setter=(value)
return self.class.set_time_on(self, :start_time, value)
end
alias_method_chain :start_time=, :smarter_setter
# Set the end_time to the given +value+, which could be a Time, Date,
# DateTime, String, Array of Strings, etc.
def end_time_with_smarter_setter=(value)
return self.class.set_time_on(self, :end_time, value)
end
alias_method_chain :end_time=, :smarter_setter
end
# Sets record's attribute to time value. If time is invalid, marks record as invalid.
#
# @param [ActiveRecord::Base] record The record to modify.
# @param [String, Symbol] attribute The attribute to set, e.g. :start_time.
# @param [ActiveSupport::TimeWithZone] value The time.
#
# @return [ActiveSupport::TimeWithZone]
def self.set_time_on(record, attribute, value)
begin
result = self.time_for(value)
rescue Exception => e
record.errors.add(attribute, "is invalid")
return record.send("#{attribute}_without_smarter_setter=", nil)
end
return record.send("#{attribute}_without_smarter_setter=", result)
end
# Returns time for the value, which can be a Time, Date, DateTime, String,
# Array of Strings, nil, etc.
#
# @param [nil, String, Date, DateTime, ActiveSupport::TimeWithZone, Time] value The time to parse.
#
# @return [ActiveSupport::TimeWithZone]
#
# @raise TypeError Thrown if given an unknown type.
# @raise Exception Thrown if value can't be parsed.
def self.time_for(value)
value = value.join(' ') if value.kind_of?(Array)
case value
when NilClass
return nil
when String
# This can throw an exception
return value.present? ?
Time.zone.parse(value) :
nil
when Date, DateTime, Time
return value.to_time.in_time_zone
when Time
when ActiveSupport::TimeWithZone
return value # Accept as-is.
else
raise TypeError, "Unknown type #{value.class.to_s.inspect} with value #{value.inspect}"
end
end
def self.find_event(search)
if search
Event.find(:all, :conditions => ['title LIKE ?', "%#{search}%"])
end
end
#---[ Queries ]---------------------------------------------------------
# Returns groups of records for the site overview screen in the following format:
#
# {
# :today => [...], # Events happening today or empty array
# :tomorrow => [...], # Events happening tomorrow or empty array
# :later => [...], # Events happening within two weeks or empty array
# :more => ..., # First event after the two week window or nil
# }
def self.select_for_overview
today = Time.zone.now.beginning_of_day
tomorrow = today + 1.day
after_tomorrow = tomorrow + 1.day
future_cutoff = today + 2.weeks
times_to_events = {
:today => [],
:tomorrow => [],
:later => [],
:more => nil,
}
# Find all events between today and future_cutoff, sorted by start_time
# includes events any part of which occurs on or after today through on or after future_cutoff
overview_events = self.non_duplicates.within_dates(today, future_cutoff)
overview_events.each do |event|
if event.start_time < tomorrow
times_to_events[:today] << event
elsif event.start_time >= tomorrow && event.start_time < after_tomorrow
times_to_events[:tomorrow] << event
else
times_to_events[:later] << event
end
end
# Find next item beyond the future_cuttoff for use in making links to it:
times_to_events[:more] = Event.first(:conditions => ["start_time >= ?", future_cutoff], :order => 'start_time asc')
return times_to_events
end
# Return Hash of Events grouped by the +type+.
def self.find_duplicates_by_type(type='na')
case type.to_s.strip
when 'na', ''
return { [] => self.future }
else
kind = %w[all any].include?(type) ? type.to_sym : type.split(',')
return self.find_duplicates_by(kind,
:grouped => true,
:where => "a.start_time >= #{self.connection.quote(Time.zone.now - 1.day)}")
end
end
#---[ Sort labels ]-------------------------------------------
# Labels displayed for sorting options:
SORTING_LABELS = {
'name' => 'Event Name',
'venue' => 'Location',
'score' => 'Relevance',
'date' => 'Date',
}
# Return the label for the +sorting_key+ (e.g. 'score'). Optionally set the
# +is_searching_by_tag+, to constrain options available for tag searches.
def self.sorting_label_for(sorting_key=nil, is_searching_by_tag=false)
sorting_key = sorting_key.to_s
if sorting_key.present? and SORTING_LABELS.has_key?(sorting_key)
SORTING_LABELS[sorting_key]
elsif is_searching_by_tag
SORTING_LABELS['date']
else
SORTING_LABELS['score']
end
end
#---[ Searching ]-------------------------------------------------------
# NOTE: The `Event.search` method is implemented elsewhere! For example, it's
# added by SearchEngine::ActsAsSolr if you're using that search engine.
# Return events matching the given +tag+ are grouped by their currentness,
# see ::group_by_currentness for data structure details.
#
# Will also set :error key if there was a non-fatal problem, e.g. invalid
# sort order.
#
# Options:
# * :current => Limit results to only current events? Defaults to false.
def self.search_tag_grouped_by_currentness(tag, opts={})
error = nil
tagged_with_opts = {}
case opts[:order]
when 'date', '', nil
tagged_with_opts[:order] = 'events.start_time'
when 'name', 'title'
tagged_with_opts[:order] = 'events.title'
when 'venue'
tagged_with_opts[:order] = 'venues.title'
tagged_with_opts[:include] = :venue
else
tagged_with_opts[:order] = 'events.start_time'
error = "Unknown ordering option #{opts[:order].inspect}, sorting by date instead."
end
result = self.group_by_currentness(self.includes(:venue).tagged_with(tag, tagged_with_opts))
# TODO Avoid searching for :past results. Currently finding them and discarding them when not wanted.
result[:past] = [] if opts[:current]
result[:error] = error
return result
end
# Return events grouped by their currentness. Accepts the same +args+ as
# #search. The results hash is keyed by whether the event is current
# (true/false) and the values are arrays of events.
def self.search_keywords_grouped_by_currentness(query, opts={})
events = self.group_by_currentness(self.search(query, opts))
if events[:past] && opts[:order].to_s == "date"
events[:past].reverse!
end
return events
end
# Return +events+ grouped by currentness using a data structure like:
#
# {
# :current => [ my_current_event, my_other_current_event ],
# :past => [ my_past_event ],
# }
def self.group_by_currentness(events)
grouped = events.group_by(&:current?)
return {:current => grouped[true] || [], :past => grouped[false] || []}
end
#---[ Transformations ]-------------------------------------------------
# Returns an Event created from an AbstractEvent.
def self.from_abstract_event(abstract_event, source=nil)
event = Event.new
event.source = source
event.organization = source.organization if source
event.title = abstract_event.title
event.description = abstract_event.description
event.start_time = abstract_event.start_time.blank? ? nil : Time.zone.parse(abstract_event.start_time.to_s)
event.end_time = abstract_event.end_time.blank? ? nil : Time.zone.parse(abstract_event.end_time.to_s)
event.url = abstract_event.url
event.venue = Venue.from_abstract_location(abstract_event.abstract_location, source) if abstract_event.abstract_location
event.tag_list = abstract_event.tags.join(',')
duplicates = event.find_exact_duplicates
event = duplicates.first.progenitor if duplicates
return event
end
# Returns an hCalendar string representing this Event.
def to_hcal
<<-EOF
<div class="vevent">
<a class="url" href="#{url}">#{url}</a>
<span class="summary">#{title}</span>:
<abbr class="dtstart" title="#{start_time.to_s(:yyyymmdd)}">#{start_time.to_s(:long_date).gsub(/\b[0](\d)/, '\1')}</abbr>,
at the <span class="location">#{venue && venue.title}</span>
</div>
EOF
end
# Returns an iCalendar string representing this Event.
#
# Options:
# * :url_helper - Lambda that accepts an Event instance and generates a URL
# for it if it doesn't have a URL already. (See Event::to_ical for example)
def to_ical(opts={})
self.class.to_ical(self, opts)
end
# Return an iCalendar string representing an Array of Event instances.
#
# Arguments:
# * :events - Event instance or array of them.
#
# Options:
# * :url_helper - Lambda that accepts an Event instance and generates a URL
# for it if it doesn't have a URL already.
#
# Example:
# ics1 = Event.to_ical(myevent)
# ics2 = Event.to_ical(myevents, :url_helper => lambda{|event| event_url(event)})
def self.to_ical(events, opts={})
events = [events].flatten
icalendar = RiCal.Calendar do |calendar|
calendar.prodid = "-//Calagator//EN"
for item in events
calendar.event do |entry|
entry.summary(item.title || 'Untitled Event')
desc = String.new.tap do |d|
if item.multiday?
d << "This event runs from #{TimeRange.new(item.start_time, item.end_time, :format => :text).to_s}."
d << "\n\n Description:\n"
end
d << Loofah::Helpers::strip_tags(item.description) if item.description.present?
d << "\n\nTags: #{item.tag_list}" unless item.tag_list.blank?
d << "\n\nImported from: #{opts[:url_helper].call(item)}" if opts[:url_helper]
end
entry.description(desc) unless desc.blank?
entry.created item.created_at if item.created_at
entry.last_modified item.updated_at if item.updated_at
# Set the iCalendar SEQUENCE, which should be increased each time an
# event is updated. If an admin needs to forcefully increment the
# SEQUENCE for all events, they can edit the "config/secrets.yml"
# file and set the "icalendar_sequence_offset" value to something
# greater than 0.
entry.sequence((SECRETS.icalendar_sequence_offset || 0) + item.versions.count)
if item.multiday?
entry.dtstart item.dates.first
entry.dtend item.dates.last + 1.day
else
entry.dtstart item.start_time
entry.dtend item[:end_time] || item.start_time + 1.hour
end
if item.url.present?
entry.url item.url
end
if item.venue
entry.location [item.venue.title, item.venue.full_address].compact.join(": ")
end
# dtstamp and uid added because of a bug in Outlook;
# Outlook 2003 will not import an .ics file unless it has DTSTAMP, UID, and METHOD
# use created_at for DTSTAMP; if there's no created_at, use event.start_time;
entry.dtstamp item.created_at || item.start_time
entry.uid "#{opts[:url_helper].call(item)}" if opts[:url_helper]
end
end
end
# Add the calendar name, normalize line-endings to UNIX LF, then replace them with DOS CF-LF.
return icalendar.
export.
sub(/(CALSCALE:\w+)/i, "\\1\nX-WR-CALNAME:#{SETTINGS.name}\nMETHOD:PUBLISH").
gsub(/\r\n/,"\n").
gsub(/\n/,"\r\n")
end
def location
venue && venue.location
end
# Array of attributes that should be cloned by #to_clone.
CLONE_ATTRIBUTES = [:title, :description, :venue_id, :url, :tag_list, :venue_details]
# Return a new record with fields selectively copied from the original, and
# the start_time and end_time adjusted so that their date is set to today and
# their time-of-day is set to the original record's time-of-day.
def to_clone
clone = self.class.new
for attribute in CLONE_ATTRIBUTES
clone.send("#{attribute}=", self.send(attribute))
end
if self.start_time
clone.start_time = self.class._clone_time_for_today(self.start_time)
end
if self.end_time
clone.end_time = self.class._clone_time_for_today(self.end_time)
end
return clone
end
# Return a time that's today but has the time-of-day component from the
# +source+ time argument.
def self._clone_time_for_today(source)
today = Time.zone.today
return Time.zone.local(today.year, today.mon, today.day, source.hour, source.min, source.sec, source.usec)
end
#---[ Date related ]----------------------------------------------------
# Returns a range of time spanned by the event.
def time_range
if self.start_time && self.end_time
self.start_time..self.end_time
elsif self.start_time
self.start_time..(self.start_time + 1.hour)
else
raise ArgumentError, "can't get a time range for an event with no start time"
end
end
# Returns an array of the dates spanned by the event.
def dates
if self.start_time && self.end_time
return (self.start_time.to_date..self.end_time.to_date).to_a
elsif self.start_time
return [self.start_time.to_date]
else
raise ArgumentError, "can't get dates for an event with no start time"
end
end
# Is this event current? Default cutoff is today
def current?(cutoff=nil)
cutoff ||= Time.zone.today.beginning_of_day
return (self.end_time || self.start_time) >= cutoff
end
# Is this event old? Default cutoff is yesterday
def old?(cutoff=nil)
cutoff ||= Time.zone.now.midnight # midnight today is the end of yesterday
return (self.end_time || self.start_time + 1.hour) <= cutoff
end
# Did this event start before today but ends today or later?
def ongoing?
today = Time.zone.today.beginning_of_day
self.start_time < today && self.end_time && self.end_time >= today
end
def multiday?
( self.dates.size > 1 ) && ( self.duration.seconds > MIN_MULTIDAY_DURATION )
end
def duration
if self.end_time && self.start_time
return (self.end_time - self.start_time)
else
return 0
end
end
def start_date
@start_date ||= start_time.to_date
end
def end_time
self[:end_time] || start_time
end
def end_date
@end_date ||= begin
# subtract a second from end time to prevent ending on midnight
end_time = self.end_time ? self.end_time - 1.second : self.start_time
end_time.to_date
end
end
def days(start_date = nil)
# FIXME: what is end_date is at midnight?
(end_date - (start_date || self.start_date)).to_i + 1
end
protected
def end_time_later_than_start_time
if start_time && end_time && end_time < start_time
errors.add(:end_time, "cannot be before start")
end
end
def associate_source_topics_types
self.topic_ids = source.topic_ids
self.type_ids = source.type_ids
end
end