Class: ICalPal::Event

Inherits:
Object
  • Object
show all
Includes:
ICalPal
Defined in:
lib/event.rb

Overview

Class representing items from the CalendarItem table

Constant Summary collapse

QUERY =
<<~SQL
SELECT DISTINCT

Store.name AS account,
Store.type,

Calendar.color,
Calendar.title AS calendar,
Calendar.subcal_url,
Calendar.symbolic_color_name,

CAST(CalendarItem.end_date AS INT) AS end_date,
CAST(CalendarItem.orig_date AS INT) AS orig_date,
CAST(CalendarItem.start_date AS INT) AS start_date,
CAST(CalendarItem.end_date - CalendarItem.start_date AS INT) AS duration,
CalendarItem.all_day,
CalendarItem.availability,
CalendarItem.conference_url_detected,
CalendarItem.description AS notes,
CalendarItem.has_recurrences,
CalendarItem.invitation_status,
CalendarItem.orig_item_id,
CalendarItem.rowid,
CalendarItem.start_tz,
CalendarItem.status,
CalendarItem.summary AS title,
CalendarItem.unique_identifier,
CalendarItem.url,
CalendarItem.uuid,

json_group_array(DISTINCT CAST(ExceptionDate.date AS INT)) AS xdate,

json_group_array(DISTINCT Identity.display_name) AS attendees,

Location.address AS address,
Location.title AS location,

Recurrence.count,
CAST(Recurrence.end_date AS INT) AS rend_date,
Recurrence.frequency,
Recurrence.interval,
Recurrence.specifier,

min(Alarm.trigger_interval) AS trigger_interval

FROM Store

JOIN Calendar ON Calendar.store_id = Store.rowid
JOIN CalendarItem ON CalendarItem.calendar_id = Calendar.rowid

LEFT OUTER JOIN Location ON Location.rowid = CalendarItem.location_id
LEFT OUTER JOIN Recurrence ON Recurrence.owner_id = CalendarItem.rowid
LEFT OUTER JOIN ExceptionDate ON ExceptionDate.owner_id = CalendarItem.rowid
LEFT OUTER JOIN Alarm ON Alarm.calendaritem_owner_id = CalendarItem.rowid
LEFT OUTER JOIN Participant ON Participant.owner_id = CalendarItem.rowid
LEFT OUTER JOIN Identity ON Identity.rowid = Participant.identity_id

WHERE Store.disabled IS NOT 1

GROUP BY CalendarItem.rowid

ORDER BY CalendarItem.unique_identifier
SQL

Constants included from ICalPal

DOW, ITIME, VERSION

Instance Attribute Summary

Attributes included from ICalPal

#self

Instance Method Summary collapse

Methods included from ICalPal

call, #keys, load_data, nth, #to_csv, #to_xml, #values, #xmlify

Constructor Details

#initialize(obj) ⇒ Event #initialize(obj<DateTime>) ⇒ Event

Returns a new instance of Event.

Overloads:

  • #initialize(obj) ⇒ Event

    Parameters:

    • obj (SQLite3::ResultSet::HashWithTypesAndFields)
  • #initialize(obj<DateTime>) ⇒ Event

    Create a placeholder event for days with no events when using –sed

    Parameters:

    • obj (DateTime)


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
# File 'lib/event.rb', line 70

def initialize(obj)
  # Placeholder for days with no events
  return @self = {
           $opts[:sep] => obj,
           'sdate' => obj,
           'placeholder' => true,
           'title' => 'Nothing.',
         } if DateTime === obj

  @self = {}
  obj.keys.each { |k| @self[k] = obj[k] }

  # Convert JSON arrays to Arrays
  @self['attendees'] = JSON.parse(obj['attendees'])
  @self['xdate'] = JSON.parse(obj['xdate']).map do |k|
    k = RDT.new(*Time.at(k + ITIME).to_a.reverse[4..]) if k
  end

  # Convert iCal dates to normal dates
  obj.keys.select { |i| i.end_with? '_date' }.each do |k|
    t = Time.at(obj[k] + ITIME) if obj[k]
    @self["#{k[0]}date"] = RDT.new(*t.to_a.reverse[4..], t.zone) if t
  end

  if @self['start_tz'] == '_float'
    @self['sdate'] = RDT.new(*(@self['sdate'].to_time - Time.zone_offset($now.zone())).to_a.reverse[4..], $now.zone)
    @self['edate'] = RDT.new(*(@self['edate'].to_time - Time.zone_offset($now.zone())).to_a.reverse[4..], $now.zone)
  end

  # Type of calendar event is from
  obj['type'] = EventKit::EKSourceType.find_index { |i| i[:name] == 'Subscribed' } if obj['subcal_url']
  type = EventKit::EKSourceType[obj['type']]

  @self['symbolic_color_name'] ||= @self['color']
  @self['type'] = type[:name]
end

Instance Method Details

#[](k) ⇒ Object

Standard accessor with special handling for age, availability, datetime, location, notes, status, title, and uid

Parameters:

  • k (String)

    Key/property name



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
# File 'lib/event.rb', line 21

def [](k)
  case k
  when 'age' then           # pseudo-property
    @self['sdate'].year - @self['edate'].year

  when 'availability' then  # Integer -> String
    EventKit::EKEventAvailability.select { |k, v| v == @self['availability'] }.keys

  when 'datetime' then      # date[ at time[ - time]]
    unless $opts[:sd] || $opts[:days] == 1
      t = @self['sdate'].to_s
      t += ' at ' unless @self['all_day'].positive?
    end

    unless @self['all_day'] && @self['all_day'].positive? || @self['placeholder']
      t ||= ''
      t += "#{@self['sdate'].strftime($opts[:tf])}" if @self['sdate']
      t += " - #{@self['edate'].strftime($opts[:tf])}" unless $opts[:eed] || !@self['edate']
    end
    t

  when 'location' then      # location[ address]
    @self['location']? [ @self['location'], @self['address'] ].join(' ').chop : nil

  when 'notes' then         # \n -> :nnr
    @self['notes']? @self['notes'].strip.gsub(/\n/, $opts[:nnr]) : nil

  when 'sday' then        # pseudo-property
    ICalPal::RDT.new(*@self['sdate'].to_a[0..2])

  when 'status' then        # Integer -> String
    EventKit::EKEventStatus.select { |k, v| v == @self['status'] }.keys[0]

  when 'title' then         # title[ (age N)]
    @self['title'] + ((@self['calendar'] == 'Birthdays')? " (age #{self['age']})" : "")

  when 'uid' then           # for icalBuddy
    @self['UUID']

  else @self[k]
  end
end

#[]=(k, v) ⇒ Object

Standard accessor with special handling for sdate. Setting sdate will also set sday.

Parameters:

  • k (String)

    Key/property name

  • v (Object)

    Key/property value



11
12
13
14
# File 'lib/event.rb', line 11

def []=(k, v)
  @self[k] = v
  @self['sday'] = ICalPal::RDT.new(*self['sdate'].to_a[0..2]) if k == 'sdate'
end

#apply_frequency!Object

Apply frequency and interval



235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/event.rb', line 235

def apply_frequency!
  # Leave edate alone for birthdays to compute age
  dates = [ 'sdate' ]
  dates << 'edate' unless self['calendar'].include?('Birthday')

  dates.each do |d|
    case EventKit::EKRecurrenceFrequency[self['frequency'] - 1]
    when 'daily'   then self[d] +=  self['interval']
    when 'weekly'  then self[d] +=  self['interval'] * 7
    when 'monthly' then self[d] >>= self['interval']
    when 'yearly'  then self[d] >>= self['interval'] * 12
    end
  end if self['frequency'] && self['interval']
end

#cloneObject

Returns a deep clone of self.

Returns:

  • a deep clone of self



170
171
172
173
174
175
# File 'lib/event.rb', line 170

def clone()
  self['stime'] = @self['sdate'].to_i
  self['etime'] = @self['edate'].to_i

  Marshal.load(Marshal.dump(self))
end

#get_occurrences(changes) ⇒ Array<IcalPal::Event>

Get next occurences of a recurring event

Parameters:

  • changes (Array)

    Recurrence changes for the event

Returns:

  • (Array<IcalPal::Event>)


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
# File 'lib/event.rb', line 181

def get_occurrences(changes)
  ndate = self['sdate']
  odays = []
  retval = []

  # Deconstruct specifier(s)
  if self['specifier']
    self['specifier'].split(';').each do |k|
      j = k.split('=')

      # M=Day of the month, O=Month of the year, S=Nth
      case j[0]
      when 'M' then ndate = RDT.new(ndate.year, ndate.month, j[1].to_i)
      when 'O' then ndate = RDT.new(ndate.year, j[1].to_i, ndate.day)
      when 'S' then @self['specifier'].sub!(/D=0/, "D=+#{j[1].to_i}")
      end

      # No time travel!
      ndate = self['sdate'] if ndate <= self['sdate']
    end

    # D=Day of the week
    self['specifier'].split(';').each do |k|
      j = k.split('=')

      odays = j[1].split(',') if j[0] == 'D'
    end
  end

  # Deconstruct occurence day(s)
  odays.each do |n|
    dow = DOW[n[-2..-1].to_sym]
    ndate += 1 until ndate.wday == dow
    ndate = ICalPal.nth(Integer(n[0..1]), n[-2..-1], ndate) unless (n[0] == '0')

    # Check for changes
    changes.detect(
      proc {
        self['sdate'] = RDT.new(*ndate.to_a[0..2], *self['sdate'].to_a[3..])
        self['edate'] = RDT.new(*ndate.to_a[0..2], *self['edate'].to_a[3..])
        retval.push(clone)
      }) { |i| @self['sday'] == i['sday'] }
  end

  # Check for changes
  changes.detect(
    proc {
      retval.push(clone)
    }) { |i| @self['sday'] == i['sday'] } unless retval.count.positive?

  retval
end

#in_window?(s, e = s) ⇒ Boolean

Check if an event starts or ends between from and to, or if it’s running now (for -n)

Parameters:

  • s (RDT)

    Event start

  • e (RDT) (defaults to: s)

    Event end

Returns:

  • (Boolean)


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/event.rb', line 256

def in_window?(s, e = s)
  if $opts[:n] then
    if ($now >= s && $now < e) then
      $log.debug("now: #{s} to #{e} vs. #{$now}")
      return(true)
    else
      $log.debug("not now: #{s} to #{e} vs. #{$now}")
      return(false)
    end
  else
    if ([ s, e ].max >= $opts[:from] && s < $opts[:to]) then
      $log.debug("in window: #{s} to #{e} vs. #{$opts[:from]} to #{$opts[:to]}")
      return(true)
    else
      $log.debug("not in window: #{s} to #{e} vs. #{$opts[:from]} to #{$opts[:to]}")
      return(false)
    end
  end
end

#non_recurringArray<Event>

Check non-recurring events

Returns:

  • (Array<Event>)

    If an event spans multiple days, the return value will contain a unique ICalPal::Event for each day that falls within our window



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/event.rb', line 112

def non_recurring
  retval = []

  # Repeat for multi-day events
  ((self['duration'] / 86400).to_i + 1).times do |i|
    break if self['sdate'] > $opts[:to]

    $log.debug("multi-day event #{i + 1}") if (i > 0)
    self['daynum'] = i + 1
    retval.push(clone) if in_window?(self['sdate'])
    self['sdate'] += 1
    self['edate'] += 1
  end

  retval
end

#recurringArray<Event>

Check recurring events

Returns:

  • (Array<Event>)

    All occurrences of a recurring event that are within our window



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
# File 'lib/event.rb', line 133

def recurring
  retval = []

  # See if event ends before we start
  stop = [ $opts[:to], (self['rdate'] || $opts[:to]) ].min
  if stop < $opts[:from] then
    $log.debug("#{stop} < #{$opts[:from]}")
    return(retval)
  end

  # Get changes to series
  changes = $rows.select { |r| r['orig_item_id'] == self['ROWID'] }

  i = 1
  while self['sdate'] <= stop
    if self['count'].positive? && i > self['count'] then
      $log.debug("count exceeded: #{i} > #{self['count']}")
      return(retval)
    end
    i += 1

    unless @self['xdate'].any?(@self['sdate']) # Exceptions?
      o = get_occurrences(changes)
      o.each { |r| retval.push(r) if in_window?(r['sdate'], r['edate']) }
    end

    apply_frequency!
  end

  retval
end