Repository navigation
Expand file tree
/
Copy pathModel.js
More file actions
383 lines (345 loc) · 14.3 KB
/
Copy pathModel.js
File metadata and controls
383 lines (345 loc) · 14.3 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
function parseCliVersion(raw) {
var text = String(raw || "").trim()
var match = text.match(/^basecamp version v?(\d+)\.(\d+)\.(\d+)(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$/)
if (!match) return { ok: false, error: "Could not determine the Basecamp CLI version", version: "", supported: false }
var major = parseInt(match[1], 10)
var minor = parseInt(match[2], 10)
var patch = parseInt(match[3], 10)
var prerelease = String(match[4] || "")
var buildMetadata = String(match[5] || "")
var newerThanMinimum = major > 0 || minor > 9 || (minor === 9 && patch > 0)
var minimumRelease = major === 0 && minor === 9 && patch === 0 && prerelease === ""
return {
ok: true,
error: "",
version: major + "." + minor + "." + patch + prerelease + buildMetadata,
supported: newerThanMinimum || minimumRelease
}
}
// One place for the setup-state UI contract: which state wins (missing CLI
// beats outdated beats signed-out), the user-facing strings, and the exact
// shell command the panel launches in a floating terminal. The launch
// command preserves the fix's exit status through the IPC refresh so the
// terminal presentation can honor Ctrl-C (exit 130) from the fix itself.
var setupLockFilename = "37signals.basecamp.setup.lock"
function setupLockPath(runtimeDir) {
return String(runtimeDir || "/tmp").replace(/\/+$/, "") + "/" + setupLockFilename
}
function shellQuote(value) {
return "'" + String(value || "").replace(/'/g, "'\\''") + "'"
}
function setupLaunchCommand(fix, ipcTarget) {
var target = shellQuote(ipcTarget)
var completion = "omarchy-shell -q \"$target\" setupFinished"
return "target=" + target + "; lock=\"${XDG_RUNTIME_DIR:-/tmp}/" + setupLockFilename + "\"; "
+ "( flock -n 9 || { printf '%s\\n' 'Basecamp setup is already running.'; exit 75; }; "
+ "trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM; "
+ "trap 'rc=$?; trap - EXIT; flock -u 9; " + completion + "; exit $rc' EXIT; "
+ String(fix || "") + " ) 9>\"$lock\""
}
function setupPlan(installed, supported, authenticated, ipcTarget) {
var plan = {
needed: installed !== true || supported !== true || authenticated !== true,
title: "Please sign in",
command: "basecamp auth login",
buttonLabel: "Sign in to Basecamp…",
fix: "basecamp auth login"
}
if (installed !== true) {
plan.title = ""
plan.command = ""
plan.buttonLabel = "Install Basecamp CLI…"
plan.fix = "omarchy-pkg-add basecamp-cli && basecamp auth login"
} else if (supported !== true) {
plan.title = "Basecamp CLI 0.9 or newer is required"
plan.command = "omarchy update"
plan.buttonLabel = "Update Omarchy…"
plan.fix = "omarchy update"
}
plan.launchCommand = setupLaunchCommand(plan.fix, ipcTarget)
return plan
}
function parseJson(raw) {
var text = String(raw || "").trim()
if (text === "") return { ok: false, error: "The Basecamp CLI returned no data", code: "" }
try {
var parsed = JSON.parse(text)
if (!parsed || typeof parsed !== "object") return { ok: false, error: "The Basecamp CLI returned invalid data", code: "" }
if (parsed.ok === false) {
return {
ok: false,
error: cleanText(parsed.error || parsed.message || "The Basecamp CLI request failed"),
code: String(parsed.code || ""),
hint: cleanText(parsed.hint || "")
}
}
return { ok: true, value: parsed }
} catch (error) {
return { ok: false, error: "Could not parse the Basecamp CLI response", code: "" }
}
}
function parseAccounts(raw) {
var result = parseJson(raw)
if (!result.ok) return { ok: false, error: result.error, accounts: [] }
var data = Array.isArray(result.value.data) ? result.value.data : []
var accounts = []
for (var i = 0; i < data.length; i++) {
var account = data[i] || {}
var id = String(account.id || "").trim()
if (id === "") continue
accounts.push({
id: id,
name: cleanText(account.name || ("Account " + id)),
order: accounts.length
})
}
return { ok: true, error: "", accounts: accounts }
}
// Each response key maps to exactly one tab. Everything else — Basecamp 5's
// always-empty `memories` placeholder, `scheduled_bubble_ups` that have not
// returned yet, and keys added later — stays out of the feed instead of
// leaking into Previous notifications.
var NOTIFICATION_SECTIONS = {
unreads: { unread: true, bubbledUp: false },
unread: { unread: true, bubbledUp: false },
reads: { unread: false, bubbledUp: false },
read: { unread: false, bubbledUp: false },
bubble_ups: { unread: false, bubbledUp: true }
}
function parseNotifications(raw, account, limit) {
var result = parseJson(raw)
if (!result.ok) return { ok: false, error: result.error, items: [] }
var data = result.value.data
var sections = []
if (Array.isArray(data)) {
sections.push({ items: data, unread: false, bubbledUp: false })
} else if (data && typeof data === "object") {
for (var key in NOTIFICATION_SECTIONS) {
if (!Array.isArray(data[key])) continue
var kind = NOTIFICATION_SECTIONS[key]
sections.push({ items: data[key], unread: kind.unread, bubbledUp: kind.bubbledUp })
}
}
var notifications = []
var bubbleUps = []
for (var s = 0; s < sections.length; s++) {
var section = sections[s]
var target = section.bubbledUp ? bubbleUps : notifications
for (var n = 0; n < section.items.length; n++) {
var item = normalizeNotification(section.items[n], account, section.unread, section.bubbledUp)
if (item) target.push(item)
}
}
// Cap each group separately so bubble-ups never crowd out notifications.
var count = positiveInteger(limit, 20)
notifications.sort(compareWithinAccount)
bubbleUps.sort(compareWithinAccount)
return {
ok: true,
error: "",
items: notifications.slice(0, count).concat(bubbleUps.slice(0, count))
}
}
function joinNames(names) {
if (names.length <= 1) return names.join("")
return names.slice(0, -1).join(", ") + " & " + names[names.length - 1]
}
function pingTitle(item) {
var names = []
var list = Array.isArray(item.participants) ? item.participants : []
for (var i = 0; i < list.length; i++) {
var name = cleanText(list[i] && list[i].name ? list[i].name : "")
if (name !== "") names.push(name)
}
if (names.length === 0) return ""
return "Ping with " + joinNames(names)
}
// Workaround for Basecamp CLI/API: the /my/notifications.json endpoint returns
// REST API endpoint URLs (e.g. https://3.basecampapi.com/...) in app_url for
// certain notification types (such as BoostReport and Reminder question answers).
// Convert them to web application URLs (https://app.basecamp.com/...) so opening
// them in a browser renders the Basecamp web UI instead of raw JSON / 401 API responses.
function normalizeAppUrl(rawUrl) {
var url = String(rawUrl || "").trim()
return url.replace("https://3.basecampapi.com/", "https://app.basecamp.com/")
}
function normalizeNotification(value, account, unread, bubbledUp) {
var item = value || {}
var id = String(item.id || "").trim()
if (id === "") return null
var timestamp = String(item.updated_at || item.created_at || "")
var parsedTime = Date.parse(timestamp)
if (!isFinite(parsedTime)) parsedTime = 0
var title = cleanText(item.title || item.readable_identifier || "Basecamp notification")
if (String(item.section || "") === "pings" && item.named !== true) {
title = pingTitle(item) || title
}
return {
id: id,
accountId: String(account.id || ""),
accountName: cleanText(account.name || "Basecamp"),
accountOrder: Number(account.order || 0),
title: title,
creator: cleanText(item.creator && item.creator.name ? item.creator.name : ""),
excerpt: cleanText(item.content_excerpt || ""),
project: cleanText(item.bucket_name || item.section || ""),
type: cleanText(item.type || ""),
timestamp: timestamp,
timestampMs: parsedTime,
url: normalizeAppUrl(item.app_url),
unread: unread === true,
unreadCount: positiveInteger(item.unread_count, 0),
bubbledUp: bubbledUp === true,
bubbleUpUrl: String(item.bubble_up_url || "").trim()
}
}
function compareWithinAccount(a, b) {
if (a.unread !== b.unread) return a.unread ? -1 : 1
return Number(b.timestampMs || 0) - Number(a.timestampMs || 0)
}
function sortNotifications(items) {
var sorted = Array.isArray(items) ? items.slice() : []
sorted.sort(function(a, b) {
var timeDifference = Number(b.timestampMs || 0) - Number(a.timestampMs || 0)
if (timeDifference !== 0) return timeDifference
var accountDifference = Number(a.accountOrder || 0) - Number(b.accountOrder || 0)
if (accountDifference !== 0) return accountDifference
return String(a.id || "").localeCompare(String(b.id || ""))
})
return sorted
}
function filterNotifications(items, accountId, state) {
var source = Array.isArray(items) ? items : []
var selectedAccount = String(accountId || "")
var selectedState = String(state || "all")
return source.filter(function(item) {
if (selectedAccount !== "" && String(item.accountId || "") !== selectedAccount) return false
if (selectedState === "unread") return item.unread === true && item.bubbledUp !== true
if (selectedState === "previous") return item.unread !== true && item.bubbledUp !== true
if (selectedState === "bubbled") return item.bubbledUp === true
return true
})
}
function visibleNotifications(items, accountId, state) {
var rows = filterNotifications(items, accountId, state)
if (state !== "unread") return rows
return filterNotifications(items, accountId, "bubbled").slice(0, 2).concat(rows)
}
function unreadCount(items, accountId) {
var source = Array.isArray(items) ? items : []
var selectedAccount = String(accountId || "")
var count = 0
for (var i = 0; i < source.length; i++) {
var item = source[i]
if (selectedAccount !== "" && String(item.accountId || "") !== selectedAccount) continue
if (item.unread === true) count++
}
return count
}
function accountFilterOptions(accounts) {
var options = [{ value: "", label: "All accounts" }]
var source = Array.isArray(accounts) ? accounts.slice() : []
source.sort(function(a, b) {
return cleanText(a.name || "Basecamp").toLowerCase().localeCompare(
cleanText(b.name || "Basecamp").toLowerCase())
})
for (var i = 0; i < source.length; i++) {
options.push({ value: String(source[i].id || ""), label: cleanText(source[i].name || "Basecamp") })
}
return options
}
function notificationTypeIcon(type) {
var value = String(type || "").toLowerCase()
if (value === "mention") return "" // md-at
if (value === "comment") return "" // md-comment_text_outline
if (value === "chat") return "" // md-chat
if (value === "completion") return "" // md-check
if (value === "event") return "" // md-bell
if (value === "bulletin") return "" // md-bullhorn
if (value === "document") return "" // md-file_document
if (value === "hill") return "" // md-chart_bell_curve
if (value === "boostreport") return "" // md-rocket
return "" // md-message
}
function notificationBadgeText(item, hovered) {
if (hovered) return "" // md-close
if (item && item.bubbledUp === true) return "" // md-arrow_up_bold
return String(Math.max(1, (item && item.unreadCount) || 0))
}
// Decode entities BEFORE stripping tags, so encoded markup (<img …>)
// becomes real markup and is then removed — never the reverse, which lets
// it survive into the UI. `&` decodes last so double-encoded entities
// (&lt;) re-form as inert text instead of live angle brackets.
function cleanText(value) {
var text = String(value || "")
.replace(/\\[nrt]/g, " ")
.replace(/ /gi, " ")
.replace(/</gi, "<")
.replace(/>/gi, ">")
.replace(/"/gi, "\"")
.replace(/'|'/gi, "'")
.replace(/&/gi, "&")
return text
.replace(/<br\s*\/?\s*>/gi, " ")
.replace(/<[^>]*>/g, " ")
.replace(/\s+/g, " ")
.trim()
}
function positiveInteger(value, fallback) {
var number = parseInt(String(value), 10)
return isFinite(number) && number > 0 ? number : fallback
}
var MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
function notificationTime(timestampMs, nowMs) {
var value = Number(timestampMs || 0)
if (!isFinite(value) || value <= 0) return ""
var now = nowMs === undefined ? Date.now() : Number(nowMs)
var date = new Date(value)
var ref = new Date(now)
if (date.getFullYear() === ref.getFullYear() && date.getMonth() === ref.getMonth() && date.getDate() === ref.getDate()) {
var hours = date.getHours()
var hour12 = hours % 12 === 0 ? 12 : hours % 12
var minutes = date.getMinutes()
return hour12 + ":" + (minutes < 10 ? "0" + minutes : minutes) + (hours >= 12 ? "pm" : "am")
}
var label = MONTH_NAMES[date.getMonth()] + " " + date.getDate()
if (date.getFullYear() !== ref.getFullYear()) label += ", " + date.getFullYear()
return label
}
function notificationMeta(item, nowMs, showAccount) {
if (!item) return ""
var parts = []
var age = notificationTime(item.timestampMs, nowMs)
var creator = cleanText(item.creator || "")
var project = cleanText(item.project || "")
var account = cleanText(item.accountName || "")
if (age !== "") parts.push(age)
if (creator !== "") parts.push(creator)
if (project !== "") {
parts.push(showAccount === true && account !== "" ? project + " (" + account + ")" : project)
} else if (showAccount === true && account !== "") {
parts.push(account)
}
return parts.join(" • ")
}
if (typeof module !== "undefined") {
module.exports = {
setupLockPath: setupLockPath,
setupLaunchCommand: setupLaunchCommand,
setupPlan: setupPlan,
parseCliVersion: parseCliVersion,
parseAccounts: parseAccounts,
parseNotifications: parseNotifications,
normalizeAppUrl: normalizeAppUrl,
sortNotifications: sortNotifications,
filterNotifications: filterNotifications,
visibleNotifications: visibleNotifications,
unreadCount: unreadCount,
accountFilterOptions: accountFilterOptions,
notificationTypeIcon: notificationTypeIcon,
notificationBadgeText: notificationBadgeText,
cleanText: cleanText,
notificationTime: notificationTime,
notificationMeta: notificationMeta
}
}