pikuri-thunderbird 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,203 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'uri'
5
+
6
+ module Pikuri
7
+ module Thunderbird
8
+ # Finds one message's raw RFC 822 bytes in Thunderbird's offline store: an
9
+ # mbox file per folder, under +ImapMail/<server>/+ (IMAP) or +Mail/+ (local
10
+ # folders). Gloda has every message's decoded text but never its bytes, so
11
+ # an attachment can only be read from here:
12
+ #
13
+ # store = MessageStore.new(profile: profile)
14
+ # rec = gloda_mail.read(message_id: id)
15
+ # store.raw_message(message_id: rec[:message_id], folder_uris: rec[:folder_uris])
16
+ # # => "Received: …\r\nMessage-ID: <…>\r\n…" (binary), or nil if no copy is stored
17
+ #
18
+ # +nil+ is the "not stored on this computer" answer: a copy gone from the
19
+ # offline store since Gloda indexed it. A message whose body was never
20
+ # offline doesn't get here: Gloda indexed it from its headers alone, with
21
+ # no attachments to ask for. This class never fetches a message over IMAP.
22
+ #
23
+ # == Implementation details
24
+ #
25
+ # A folder URI maps to its mbox through +prefs.js+, the only file naming
26
+ # which account owns which store directory (a second account on one host
27
+ # gets +imap.gmail-1.com+). Gloda's folder URIs are not valid RFC 3986 —
28
+ # raw +[Gmail]+ brackets and spaces — so they are split by regex. A folder
29
+ # name is mapped verbatim: one with characters the filesystem can't hold,
30
+ # which Thunderbird hashes into its file name (+NS_MsgHashIfNecessary+),
31
+ # isn't found, and its messages answer "not stored". Unhandled until a
32
+ # real folder hits it.
33
+ #
34
+ # Within the mbox the message is found by a linear scan for its
35
+ # +Message-ID:+ header (~0.5 s for a 440 MB +[Gmail]/All Mail+), skipping
36
+ # copies whose +X-Mozilla-Status+ carries the expunged bit. Gloda's
37
+ # +messageKey+ is not used: it is the IMAP UID under +ImapMail/+, and the
38
+ # byte offset is only in the +.msf+ Mork summary.
39
+ #
40
+ # The scan reads the live file, with no snapshot: Thunderbird appends new
41
+ # mail and compacts by renaming a new file over the old one, so the one fd
42
+ # held for the whole scan stays self-consistent.
43
+ #
44
+ # Sharing: +P_stateless+ — every call reads +prefs.js+ and the mbox afresh.
45
+ class MessageStore
46
+ # Raised when a folder can't be mapped to a readable mbox, or the message
47
+ # is too large to open. The message is LLM-presentable.
48
+ Error = Class.new(StandardError)
49
+
50
+ # @return [Integer] largest raw message read into memory. A 25 MB
51
+ # attachment (a typical provider's limit) is ~34 MB as base64.
52
+ MAX_MESSAGE_BYTES = 40 * 1024 * 1024
53
+
54
+ # @return [Integer] scan read size.
55
+ CHUNK = 8 * 1024 * 1024
56
+
57
+ # @return [Integer] bytes kept from the previous chunk, so the separator
58
+ # above a +Message-ID:+ near a chunk start is still in the buffer.
59
+ # Bounds the header length the scan handles.
60
+ OVERLAP = 256 * 1024
61
+
62
+ # @return [Integer] +X-Mozilla-Status+'s deleted-but-not-compacted bit.
63
+ EXPUNGED = 0x0008
64
+
65
+ # @param profile [Profile] the Thunderbird profile whose store to read.
66
+ # @return [MessageStore]
67
+ def initialize(profile:)
68
+ @profile = profile
69
+ end
70
+
71
+ # The first live copy of +message_id+ in any of +folder_uris+, in order.
72
+ #
73
+ # @param message_id [String] the RFC +Message-ID+, without angle brackets
74
+ # (as Gloda stores it).
75
+ # @param folder_uris [Array<String>] Gloda +folderURI+s to try.
76
+ # @return [String, nil] the raw message (binary, CRLF, without the mbox
77
+ # +From - + separator line), or +nil+ when no folder holds a copy.
78
+ # @raise [Error] when a folder's account isn't in +prefs.js+, its store
79
+ # is not mbox, or the message exceeds {MAX_MESSAGE_BYTES}.
80
+ def raw_message(message_id:, folder_uris:)
81
+ servers = read_servers
82
+ folder_uris.each do |uri|
83
+ path = mbox_path(servers, uri)
84
+ next unless File.file?(path)
85
+
86
+ raw = scan(path, message_id)
87
+ return raw if raw
88
+ end
89
+ nil
90
+ end
91
+
92
+ private
93
+
94
+ # @return [Hash{Array(String, String, String) => Hash{String => Object}}]
95
+ # +[scheme, userName, hostname]+ → that server's +mail.server.serverN.*+
96
+ # prefs; the scheme is +imap+ for IMAP and +mailbox+ for local stores.
97
+ def read_servers
98
+ prefs = Hash.new { |h, k| h[k] = {} }
99
+ File.foreach(@profile.prefs_path, encoding: 'UTF-8') do |line|
100
+ m = line.match(/\Auser_pref\("mail\.server\.(server\d+)\.([^"]+)",\s*(.*)\);\s*\z/) or next
101
+ prefs[m[1]][m[2]] = JSON.parse(m[3])
102
+ end
103
+ prefs.each_value.to_h do |s|
104
+ [[s['type'] == 'imap' ? 'imap' : 'mailbox', s['userName'], s['hostname']], s]
105
+ end
106
+ end
107
+
108
+ # @param servers [Hash] from {#read_servers}.
109
+ # @param uri [String] a Gloda +folderURI+, e.g.
110
+ # +"imap://me%40gmail.com@imap.gmail.com/[Gmail]/All Mail"+.
111
+ # @return [String] the folder's mbox path: +a/b/c+ → +<dir>/a.sbd/b.sbd/c+.
112
+ # @raise [Error] when no account owns the URI or its store isn't mbox.
113
+ def mbox_path(servers, uri)
114
+ m = uri.match(%r{\A(\w+)://([^@/]+)@([^/]+)/(.+)\z}) or
115
+ raise Error, "unrecognised Thunderbird folder #{uri.inspect}."
116
+ scheme, user, host, path = m.captures.map { URI.decode_uri_component(_1) }
117
+ server = servers[[scheme, user, host]] or
118
+ raise Error, "no account in Thunderbird's prefs.js owns the folder #{uri.inspect}."
119
+ store = server['storeContractID']
120
+ if store && !store.end_with?('/berkeleystore;1')
121
+ raise Error, "the account behind #{uri.inspect} stores mail as #{store}, which pikuri can't read (only mbox)."
122
+ end
123
+
124
+ dir = server['directory-rel']&.sub('[ProfD]', "#{@profile.dir}/") || server['directory'] or
125
+ raise Error, "Thunderbird's prefs.js names no store directory for the folder #{uri.inspect}."
126
+ *parents, leaf = path.split('/')
127
+ File.join(dir, *parents.map { "#{_1}.sbd" }, leaf)
128
+ end
129
+
130
+ # @param path [String] an mbox file.
131
+ # @param message_id [String]
132
+ # @return [String, nil] the first live copy's raw bytes.
133
+ def scan(path, message_id)
134
+ needle = Regexp.new("^Message-ID:[ \\t]*(?:\\r?\\n[ \\t]+)?<#{Regexp.escape(message_id.b)}>".b,
135
+ Regexp::IGNORECASE)
136
+ File.open(path, 'rb') do |f|
137
+ buf = +''.b
138
+ base = 0 # file offset of buf's first byte
139
+ from = 0 # buf index the next match search starts at
140
+ loop do
141
+ chunk = f.read(CHUNK)
142
+ buf << chunk if chunk
143
+ while (m = needle.match(buf, from))
144
+ from = m.end(0)
145
+ start = buf.rindex(/^From - /, m.begin(0)) or next
146
+ # A blank line between separator and match puts the match in a
147
+ # body: a forwarded mail quoting its own Message-ID header.
148
+ next if buf.byteslice(start, m.begin(0) - start).match?(/\r?\n\r?\n/)
149
+
150
+ raw = message_at(f, base + start)
151
+ return raw unless expunged?(raw)
152
+ end
153
+ return nil unless chunk
154
+
155
+ drop = buf.bytesize - OVERLAP
156
+ next unless drop.positive?
157
+
158
+ buf = buf.byteslice(drop..)
159
+ base += drop
160
+ from = [from - drop, 0].max
161
+ end
162
+ end
163
+ end
164
+
165
+ # Reads with +pread+, so the scan's own file position is untouched should
166
+ # this copy turn out expunged.
167
+ #
168
+ # @param f [File] the open mbox.
169
+ # @param offset [Integer] where the message's +From - + line starts.
170
+ # @return [String] the message, without that line, up to the next one.
171
+ # @raise [Error] past {MAX_MESSAGE_BYTES}.
172
+ def message_at(f, offset)
173
+ out = +''.b
174
+ loop do
175
+ chunk = begin
176
+ f.pread(CHUNK, offset + out.bytesize)
177
+ rescue EOFError
178
+ break
179
+ end
180
+ searched = [out.bytesize - 8, 1].max
181
+ out << chunk
182
+ if (i = out.index("\nFrom - ", searched))
183
+ out = out.byteslice(0, i + 1)
184
+ break
185
+ end
186
+ if out.bytesize > MAX_MESSAGE_BYTES
187
+ raise Error, "this message is over #{MAX_MESSAGE_BYTES / (1024 * 1024)} MB, too large to open here."
188
+ end
189
+ end
190
+ out.byteslice((out.index("\n") || out.bytesize) + 1..) || +''.b
191
+ end
192
+
193
+ # @param raw [String] one message.
194
+ # @return [Boolean] whether Thunderbird marked it deleted but has not
195
+ # compacted it away yet.
196
+ def expunged?(raw)
197
+ header = raw[/\A.*?\r?\n\r?\n/m] || raw
198
+ status = header[/^X-Mozilla-Status:[ \t]*(\h+)/i, 1]
199
+ !status.nil? && status.hex.anybits?(EXPUNGED)
200
+ end
201
+ end
202
+ end
203
+ end
@@ -15,21 +15,33 @@ module Pikuri
15
15
  #
16
16
  # Two install roots are probed, in this order: **snap**
17
17
  # (+~/snap/thunderbird/common/.thunderbird+, confirmed) and **apt**
18
- # (+~/.thunderbird+, recalled). Flatpak is out of scope. If *both* roots
19
- # hold a +profiles.ini+ (a stale apt profile left behind by an apt→snap
20
- # migration is the common case), discovery raises rather than guess
21
- # which is live — the one-time fix (delete the obsolete root) beats a
22
- # liveness heuristic that guesses wrong exactly there. An explicit
23
- # +profile_dir:+ override bypasses all of this.
18
+ # (+~/.thunderbird+, recalled). Flatpak is out of scope. A profile with
19
+ # no mail account (Thunderbird started once, its account wizard closed)
20
+ # doesn't count. If *both* roots hold a profile with an account (a stale
21
+ # apt profile left behind by an apt→snap migration is the common case),
22
+ # discovery raises rather than guess which is live — the one-time fix
23
+ # (delete the obsolete root) beats a liveness heuristic that guesses
24
+ # wrong exactly there. An explicit +profile_dir:+ override bypasses all
25
+ # of this.
24
26
  #
25
27
  # == Implementation details
26
28
  #
29
+ # Roots are compared by +File.realpath+: started while +~/.thunderbird+
30
+ # existed and its own root didn't, the snap launcher links
31
+ # +~/snap/thunderbird/common/.thunderbird -> ~/.thunderbird+, so both
32
+ # roots are one directory and one profile, found as +:snap+.
33
+ #
27
34
  # Within a root, the active profile is the +profiles.ini+ section with
28
35
  # +Default=1+ (or the sole profile when there's exactly one and none is
29
36
  # marked default); +Path+ is resolved relative to the ini's directory
30
37
  # when +IsRelative=1+. The confirmed real-world ini has no +[Install…]+
31
38
  # sections (Firefox's per-install default mechanism), so the plain
32
39
  # +Default=1+ scan suffices.
40
+ #
41
+ # A mail account is a +mail.server.serverN.type+ in +prefs.js+ other
42
+ # than +none+, which is Local Folders: every profile gets those on first
43
+ # start, so a +Mail/+ directory proves nothing. Nor does a missing Gloda
44
+ # index — a real profile has none until its first indexing finishes.
33
45
  class Profile
34
46
  # @return [String] snap install root (confirmed on a live box).
35
47
  SNAP_ROOT = File.expand_path('~/snap/thunderbird/common/.thunderbird')
@@ -55,28 +67,35 @@ module Pikuri
55
67
  # Discover the active profile, or return +nil+ when Thunderbird is not
56
68
  # installed (no +profiles.ini+ under any probed root).
57
69
  #
70
+ # When every found profile lacks a mail account, the first root's wins,
71
+ # so a fresh install is still found.
72
+ #
58
73
  # @param profile_dir [String, nil] explicit override; when given, it is
59
74
  # used verbatim (expanded) and the root scan is skipped.
75
+ # @param roots [Hash{Symbol => String}] install roots to probe, in
76
+ # preference order; the spec points it at temp dirs.
60
77
  # @return [Profile, nil] the resolved profile, or +nil+ if none found.
61
- # @raise [DiscoveryError] if +profile_dir+ isn't a directory, if both
62
- # roots hold a profile, or if a root has several profiles and none
63
- # is marked +Default=1+.
64
- def self.discover(profile_dir: nil)
78
+ # @raise [DiscoveryError] if +profile_dir+ isn't a directory, if two
79
+ # roots hold a profile with a mail account, or if a root has several
80
+ # profiles and none is marked +Default=1+.
81
+ def self.discover(profile_dir: nil, roots: ROOTS)
65
82
  return from_override(profile_dir) if profile_dir
66
83
 
67
- present = ROOTS.select { |_, root| File.file?(File.join(root, 'profiles.ini')) }
84
+ present = roots.select { |_, root| File.file?(File.join(root, 'profiles.ini')) }
85
+ .uniq { |_, root| File.realpath(root) }
86
+ .map { |variant, root| new(dir: resolve_within(root), variant: variant) }
68
87
  return nil if present.empty?
69
88
 
70
- if present.size > 1
71
- paths = present.values.join(' and ')
89
+ live = present.select(&:mail_account?)
90
+ if live.size > 1
91
+ paths = live.map(&:dir).join(' and ')
72
92
  raise DiscoveryError,
73
- "Found Thunderbird profiles under two roots (#{paths}). This usually " \
74
- 'means a stale profile from an old install. Delete the obsolete root, ' \
75
- 'or pass profile_dir: to pick one explicitly.'
93
+ "Found Thunderbird profiles with mail accounts under two roots (#{paths}). " \
94
+ 'This usually means a stale profile from an old install. Delete the ' \
95
+ 'obsolete root, or pass profile_dir: to pick one explicitly.'
76
96
  end
77
97
 
78
- variant, root = present.first
79
- new(dir: resolve_within(root), variant: variant)
98
+ live.first || present.first
80
99
  end
81
100
 
82
101
  # @param dir [String] resolved profile directory (absolute).
@@ -94,6 +113,32 @@ module Pikuri
94
113
  # +available?+ gate).
95
114
  def gloda? = File.file?(gloda_path)
96
115
 
116
+ # @return [Boolean] whether Thunderbird keeps the Gloda index current:
117
+ # +false+ once its *Enable Global Search and Indexer* setting is off,
118
+ # which stops the indexer and leaves the file in place, frozen; +true+
119
+ # when +prefs.js+ is missing or doesn't say (the default is on).
120
+ def gloda_indexing?
121
+ return true unless File.file?(prefs_path)
122
+
123
+ File.foreach(prefs_path, encoding: 'UTF-8').none? do |line|
124
+ line.match?(/\Auser_pref\("mailnews\.database\.global\.indexer\.enabled",\s*false\);/)
125
+ end
126
+ end
127
+
128
+ # @return [String] Thunderbird's preferences, which map each mail
129
+ # account to its store directory (see {MessageStore}).
130
+ def prefs_path = File.join(@dir, 'prefs.js')
131
+
132
+ # @return [Boolean] whether +prefs.js+ names an account beyond Local
133
+ # Folders; +false+ when there is no +prefs.js+.
134
+ def mail_account?
135
+ return false unless File.file?(prefs_path)
136
+
137
+ File.foreach(prefs_path, encoding: 'UTF-8').any? do |line|
138
+ line.match?(/\Auser_pref\("mail\.server\.server\d+\.type",\s*"(?!none")/)
139
+ end
140
+ end
141
+
97
142
  # @return [String] the calendar stores directory.
98
143
  def calendar_dir = File.join(@dir, 'calendar-data')
99
144
 
@@ -113,7 +158,7 @@ module Pikuri
113
158
  # A directory a *snap-confined* Thunderbird can read a hand-off file from,
114
159
  # for the +.ics+ import hand-off ({CalendarCreate}). Snap's +home+
115
160
  # interface blocks hidden +$HOME+ dirs (so the +~/.cache+ snapshot dir is
116
- # unreadable by the confined app — see +DESIGN.md+ § "Platform
161
+ # unreadable by the confined app — see +design/architecture.md+ § "Platform
117
162
  # confinement"); we stage instead in the variant's own readable root: the
118
163
  # snap-owned data area for +:snap+ (readable regardless of the dotfile
119
164
  # rule), the unconfined profile dir for +:apt+/+:override+. The caller
@@ -0,0 +1,207 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'date'
4
+ require 'set'
5
+ require 'ice_cube'
6
+ require 'tzinfo'
7
+
8
+ module Pikuri
9
+ module Thunderbird
10
+ # The start instants of one recurring series inside a search window.
11
+ # Thunderbird stores a series as one master row dated at its *first*
12
+ # occurrence plus its raw +cal_recurrence+ lines, so a date search must
13
+ # expand them:
14
+ #
15
+ # rec = Recurrence.new(start: Time.utc(2026, 11, 9, 7), tz: 'Europe/Helsinki',
16
+ # lines: ['RRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR'], overridden: Set.new)
17
+ # rec.starts(after: Time.utc(2026, 11, 16), before: Time.utc(2026, 11, 20, 22))
18
+ # # => [2026-11-16 07:00 UTC, 2026-11-18 07:00 UTC, 2026-11-20 07:00 UTC] — 09:00 Helsinki each
19
+ #
20
+ # DTSTART is always the first occurrence, even when the rule doesn't
21
+ # match it (libical's reading of RFC 5545, so Thunderbird's). +EXDATE+
22
+ # drops a date, +RDATE+ adds one, and a start in +overridden+ — an edited
23
+ # occurrence Thunderbird stores as its own row — is left to that row.
24
+ #
25
+ # == Implementation details
26
+ #
27
+ # Expansion runs on the event's *wall clock*: its local time rewritten as
28
+ # if it were UTC, where there is no DST, so ice_cube keeps a 09:00 meeting
29
+ # at 09:00 and matches +BYDAY+ on the local weekday. Each date then goes
30
+ # back through the event's zone to an instant. ice_cube's own iCal reader
31
+ # drops +TZID+, so only the RRULE value goes through it; +UNTIL+, +EXDATE+
32
+ # and +RDATE+ are parsed here.
33
+ #
34
+ # A stranger's invitation can write a rule into the calendar, and ice_cube
35
+ # has no loop guard: a +COUNT+ rule walks from DTSTART whatever the window,
36
+ # and an +HOURLY+ or finer one yields a date per step. So only +DAILY+ and
37
+ # coarser rules expand, +COUNT+ stops at {MAX_COUNT}, and the window spans
38
+ # at most {MAX_SPAN}; past those, {Unexpandable}.
39
+ #
40
+ # Immutable.
41
+ class Recurrence
42
+ # Raised for a series this class won't expand: a rule part, zone or date
43
+ # it can't read, or one past the guards. The message names the culprit.
44
+ class Unexpandable < StandardError; end
45
+
46
+ # @return [Array<String>] the +FREQ+ values that expand.
47
+ FREQUENCIES = %w[DAILY WEEKLY MONTHLY YEARLY].freeze
48
+
49
+ # @return [Integer] the largest +COUNT+ that expands; a 0.2 s walk at
50
+ # 100,000, so well below.
51
+ MAX_COUNT = 1000
52
+
53
+ # @return [Integer] seconds: the longest window expanded, two years.
54
+ MAX_SPAN = 731 * 86_400
55
+
56
+ # @return [Integer] seconds of slack each side of the wall-clock window,
57
+ # covering any zone's offset; the exact bounds are applied after.
58
+ SLACK = 86_400
59
+
60
+ # @param start [Time] the master row's start instant (DTSTART).
61
+ # @param tz [String] its +event_start_tz+: an Olson name, +floating+,
62
+ # +UTC+ or +GMT+0300+.
63
+ # @param lines [Array<String>] its +cal_recurrence.icalString+ rows.
64
+ # @param overridden [Set<Integer>] epoch seconds of the occurrences
65
+ # stored as their own rows (their +recurrence_id+).
66
+ # @raise [Unexpandable]
67
+ def initialize(start:, tz:, lines:, overridden:)
68
+ @tz = tz.to_s
69
+ @zone = zone(@tz)
70
+ @start = wall_of(start, @zone)
71
+ @overridden = overridden
72
+ @rules = []
73
+ @exdates = Set.new
74
+ @exdays = Set.new
75
+ @rdates = []
76
+ lines.each { |raw| read_line(raw) }
77
+ end
78
+
79
+ # @param after [Time, nil] inclusive lower bound.
80
+ # @param before [Time, nil] inclusive upper bound; at least one of the two.
81
+ # @return [Array<Time>] UTC start instants, ascending.
82
+ def starts(after:, before:)
83
+ from, to = window(after, before)
84
+ schedule = IceCube::Schedule.new(@start)
85
+ @rules.each { |rule| schedule.add_recurrence_rule(rule) }
86
+ walls = schedule.occurrences_between(wall_of(from, @zone) - SLACK, wall_of(to, @zone) + SLACK)
87
+ .map { |occurrence| Time.at(occurrence.to_i).utc }
88
+ walls = (walls + [@start] + @rdates).uniq.reject { |w| @exdates.include?(w) || @exdays.include?(w.to_date) }
89
+ walls.map { |w| instant_of(w, @zone) }
90
+ .select { |t| t.between?(from, to) && !@overridden.include?(t.to_i) }
91
+ .sort
92
+ end
93
+
94
+ private
95
+
96
+ # @return [Array(Time, Time)]
97
+ def window(after, before)
98
+ raise ArgumentError, 'a window needs after or before' unless after || before
99
+
100
+ from = after || (before - MAX_SPAN)
101
+ [from, [before, from + MAX_SPAN].compact.min]
102
+ end
103
+
104
+ # @param raw [String] one +cal_recurrence+ content line.
105
+ # @return [void]
106
+ def read_line(raw)
107
+ line = IcalLine.parse(raw.to_s.strip)
108
+ case line.name
109
+ when 'RRULE' then @rules << rule(line.value)
110
+ when 'EXDATE'
111
+ dates(line).each { |kind, wall| kind == :date ? @exdays << wall.to_date : @exdates << wall }
112
+ when 'RDATE' then @rdates.concat(dates(line).map(&:last))
113
+ else raise Unexpandable, "unsupported #{line.name} line"
114
+ end
115
+ end
116
+
117
+ # @param value [String] an RRULE value, e.g. +"FREQ=WEEKLY;UNTIL=20270101T000000Z"+.
118
+ # @return [IceCube::Rule]
119
+ def rule(value)
120
+ parts = value.split(';').to_h { |part| part.split('=', 2).then { |k, v| [k.to_s.upcase, v.to_s] } }
121
+ raise Unexpandable, "FREQ=#{parts['FREQ']}" unless FREQUENCIES.include?(parts['FREQ'])
122
+ raise Unexpandable, "COUNT=#{parts['COUNT']}" if parts['COUNT'].to_i > MAX_COUNT
123
+
124
+ until_value = parts.delete('UNTIL')
125
+ rule = IceCube::Rule.from_ical(parts.map { |k, v| "#{k}=#{v}" }.join(';'))
126
+ return rule unless until_value
127
+
128
+ kind, wall = date(until_value, {})
129
+ rule.until(kind == :date ? wall + 86_399 : wall) # a DATE UNTIL includes its whole day
130
+ rescue ArgumentError, NoMethodError => e
131
+ raise Unexpandable, "RRULE #{value}: #{e.message}"
132
+ end
133
+
134
+ # @param line [IcalLine::Parsed] an +EXDATE+ or +RDATE+ line.
135
+ # @return [Array<Array(Symbol, Time)>] +[:date | :time, wall]+ per value.
136
+ def dates(line)
137
+ line.value.split(',').map { |value| date(value.split('/').first.to_s, line.params) } # a PERIOD counts by its start
138
+ end
139
+
140
+ # @param value [String] +20261118+, +20261118T090000+ or +20261118T070000Z+.
141
+ # @param params [Hash{String => String}] the line's params (+TZID+).
142
+ # @return [Array(Symbol, Time)] +:date+ or +:time+, and the wall clock in
143
+ # the event's zone.
144
+ def date(value, params)
145
+ m = value.strip.match(/\A(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z?))?\z/)
146
+ raise Unexpandable, "unreadable date #{value.inspect}" unless m
147
+
148
+ y, mo, d, h, mi, s, utc = m.captures
149
+ return [:date, Time.utc(y.to_i, mo.to_i, d.to_i)] unless h
150
+
151
+ wall = Time.utc(y.to_i, mo.to_i, d.to_i, h.to_i, mi.to_i, s.to_i)
152
+ return [:time, wall_of(wall, @zone)] if utc == 'Z'
153
+
154
+ tzid = params['TZID']
155
+ return [:time, wall] if tzid.nil? || tzid == @tz
156
+
157
+ [:time, wall_of(instant_of(wall, zone(tzid)), @zone)]
158
+ end
159
+
160
+ # @param name [String]
161
+ # @return [TZInfo::Timezone, Integer, nil] an Olson zone, a fixed offset
162
+ # in seconds, or +nil+ for a UTC or floating time (stored as if UTC).
163
+ def zone(name)
164
+ case name
165
+ when '', 'floating', 'UTC', 'Z' then nil
166
+ when /\AGMT([+-])(\d{2})(\d{2})\z/ then (Regexp.last_match(1) == '-' ? -1 : 1) *
167
+ ((Regexp.last_match(2).to_i * 3600) + (Regexp.last_match(3).to_i * 60))
168
+ else TZInfo::Timezone.get(name)
169
+ end
170
+ rescue TZInfo::InvalidTimezoneIdentifier
171
+ raise Unexpandable, "unknown time zone #{name}"
172
+ end
173
+
174
+ # @param instant [Time]
175
+ # @param zone [TZInfo::Timezone, Integer, nil]
176
+ # @return [Time] the local time in +zone+, labelled UTC.
177
+ def wall_of(instant, zone)
178
+ case zone
179
+ when nil then instant.getutc
180
+ when Integer then Time.at(instant.to_i + zone).utc
181
+ else
182
+ local = zone.to_local(instant)
183
+ Time.utc(local.year, local.month, local.day, local.hour, local.min, local.sec)
184
+ end
185
+ end
186
+
187
+ # A local time DST skipped (02:30 on a spring-forward night) moves an
188
+ # hour on, as RFC 5545 says; one that happens twice takes the first.
189
+ #
190
+ # @param wall [Time] the local time in +zone+, labelled UTC.
191
+ # @param zone [TZInfo::Timezone, Integer, nil]
192
+ # @return [Time] the UTC instant.
193
+ def instant_of(wall, zone)
194
+ case zone
195
+ when nil then wall
196
+ when Integer then Time.at(wall.to_i - zone).utc
197
+ else
198
+ begin
199
+ zone.local_to_utc(wall) { |periods| periods.first }.utc
200
+ rescue TZInfo::PeriodNotFound
201
+ zone.local_to_utc(wall + 3600) { |periods| periods.first }.utc
202
+ end
203
+ end
204
+ end
205
+ end
206
+ end
207
+ end
@@ -9,17 +9,17 @@ require 'pikuri-core'
9
9
  # ({Pikuri::Thunderbird::Profile} discovers it) and never touches the
10
10
  # network.
11
11
  #
12
- # The load-bearing posture (v1): search + read are inbound-only, so an
12
+ # The load-bearing posture: search + read are inbound-only, so an
13
13
  # agent wired with only these tools has private data + untrusted content
14
14
  # but *no egress leg* — the lethal trifecta is broken by construction, the
15
- # same model as +bin/pikuri-corpus+. Outbound actions (compose / create
16
- # event) are v2 and are always human-gated hand-offs to Thunderbird's own
17
- # UI. Threat model: +DESIGN.md+; design rationale: +ideas/thunderbird.md+.
15
+ # same model as +pikuri-briefing --with-mail+. Outbound actions (compose / create
16
+ # event) are opt-in and always human-gated hand-offs to Thunderbird's own
17
+ # UI. Threat model: +design/architecture.md+; per-tool rationale: each class's yardoc.
18
18
  Pikuri::PROMPT_DIRS << File.expand_path('../prompts', __dir__)
19
19
 
20
20
  module Pikuri
21
21
  module Thunderbird
22
- # Legs of the five inbound tools: a mailbox and a calendar are private by
22
+ # Legs of the inbound tools: a mailbox and a calendar are private by
23
23
  # *domain*, and their contents are written by whoever mailed you.
24
24
  #
25
25
  # The +private: true+ is the one place the framework declares that leg for