diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0d479d41e31..82a8d9ba6dd 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -408,6 +408,7 @@ jobs:
cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-gpui-kernels
cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-glass
cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-i18n-build
+ cargo +1.95.0 test --manifest-path apps/desktop-gpui/Cargo.toml --locked --target ${{ matrix.settings.target }} -p cap-notes -p cap-calendar -p cap-meetings -p cap-meeting-platform -p cap-notes-ui -p cap-diarize
# Cap only builds gpui's crates as dependencies, so their own tests never run
# in the app jobs above. Run the ones covering Cap's patches against real
diff --git a/.github/workflows/infra-database.yml b/.github/workflows/infra-database.yml
index 6df49f21433..6decf581232 100644
--- a/.github/workflows/infra-database.yml
+++ b/.github/workflows/infra-database.yml
@@ -13,6 +13,7 @@ on:
- "apps/web/app/api/developer/**"
- "apps/web/app/api/cron/developer-storage/**"
- "apps/web/lib/user-preferences-sql.ts"
+ - "apps/web/lib/meetings/trial.ts"
- "apps/web/lib/media-input-policy-strikes.ts"
- "apps/web/lib/organization-member-removal.ts"
- "packages/web-backend/src/Spaces/**"
@@ -44,6 +45,7 @@ on:
- "apps/web/app/api/developer/**"
- "apps/web/app/api/cron/developer-storage/**"
- "apps/web/lib/user-preferences-sql.ts"
+ - "apps/web/lib/meetings/trial.ts"
- "apps/web/lib/media-input-policy-strikes.ts"
- "apps/web/lib/organization-member-removal.ts"
- "packages/web-backend/src/Spaces/**"
@@ -141,4 +143,4 @@ jobs:
CAP_INFRA_TEST_DATABASE_URL: mysql://root@127.0.0.1:3306/cap_infra_tests
CAP_INFRA_ROUND_TRIPS_DATABASE_URL: mysql://root@127.0.0.1:3306/cap_infra_tests
CAP_PASSKEYS_TEST_DATABASE_URL: mysql://root@127.0.0.1:3306/cap_infra_tests
- run: bun run vitest run __tests__/integration/infra-*-database.test.ts __tests__/integration/user-preferences-database.test.ts __tests__/integration/space-creator-membership-database.test.ts __tests__/integration/dashboard-library-database.test.ts __tests__/integration/messenger-poll-database.test.ts __tests__/integration/passkeys-database.test.ts __tests__/integration/email-change-database.test.ts
+ run: bun run vitest run __tests__/integration/infra-*-database.test.ts __tests__/integration/user-preferences-database.test.ts __tests__/integration/space-creator-membership-database.test.ts __tests__/integration/dashboard-library-database.test.ts __tests__/integration/messenger-poll-database.test.ts __tests__/integration/passkeys-database.test.ts __tests__/integration/email-change-database.test.ts __tests__/integration/meetings-trial-database.test.ts
diff --git a/.github/workflows/meetings-reliability.yml b/.github/workflows/meetings-reliability.yml
new file mode 100644
index 00000000000..0a7fe3ea2f2
--- /dev/null
+++ b/.github/workflows/meetings-reliability.yml
@@ -0,0 +1,252 @@
+name: Meetings reliability (real app)
+# Runs a scripted two minute meeting (apps/desktop-gpui/tests/fixtures/meetings) through the real
+# app on Linux and Windows and checks what it made: both sides recorded through the OS audio stack,
+# the transcript against the script, one voice per person with the user as You, notes written, a
+# question answered through the Ask bar, a Cloud meeting's clips, and the live indicator's banner
+# staying on screen. The account is a Pro account against a local stub of the meeting endpoints
+# (scripts/ci/meetings/stub_server.py); nothing reaches a Cap server or an AI provider. On Windows
+# the call's voices must also be named after the call page's tiles, read through UI Automation.
+
+on:
+ pull_request:
+ types: [opened, synchronize, reopened, ready_for_review]
+ paths:
+ - "apps/desktop-gpui/src/meetings.rs"
+ - "apps/desktop-gpui/src/meetings/**"
+ - "apps/desktop-gpui/src/meetings_ui/**"
+ - "apps/desktop-gpui/src/transcription.rs"
+ - "apps/desktop-gpui/src/transcription/**"
+ - "apps/desktop-gpui/meetings/**"
+ - "apps/desktop-gpui/meeting-platform/**"
+ - "apps/desktop-gpui/diarize/**"
+ - "apps/desktop-gpui/tests/fixtures/meetings/**"
+ - "scripts/ci/meetings/**"
+ - ".github/workflows/meetings-reliability.yml"
+ schedule:
+ - cron: "10 5 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: meetings-reliability-${{ github.event.pull_request.number || github.ref }}
+ cancel-in-progress: true
+
+env:
+ # Release speed for live transcription, with the debug assertions the scripted-meeting hooks need.
+ CARGO_PROFILE_RELEASE_DEBUG: "0"
+ CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS: "true"
+
+jobs:
+ linux:
+ name: Meetings on Linux (real app)
+ if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
+ runs-on: blacksmith-8vcpu-ubuntu-2404
+ timeout-minutes: 75
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Install Linux desktop dependencies
+ uses: ./.github/actions/install-desktop-deps
+
+ - name: Install the meeting harness tools
+ run: |
+ sudo apt-get install -y -qq --no-install-recommends xvfb x11-utils xdotool imagemagick dbus \
+ pulseaudio pulseaudio-utils libasound2-plugins ffmpeg openssl openbox > /dev/null
+ if ! command -v google-chrome > /dev/null; then
+ curl -fsSL -o "$RUNNER_TEMP/chrome.deb" https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
+ sudo apt-get install -y -qq "$RUNNER_TEMP/chrome.deb" > /dev/null
+ fi
+ google-chrome --version
+
+ - name: Rust setup
+ uses: dtolnay/rust-toolchain@1.95.0
+ with:
+ targets: x86_64-unknown-linux-gnu
+
+ - uses: ./.github/actions/setup-rust-cache
+ with:
+ target: x86_64-unknown-linux-gnu
+ prefix-key: v1-rust-meetings
+ workspaces: apps/desktop-gpui -> target
+
+ - name: Run setup
+ run: node scripts/setup.js
+ env:
+ RUST_TARGET_TRIPLE: x86_64-unknown-linux-gnu
+
+ - name: Prepare GPUI dependency
+ run: |
+ node scripts/sync-desktop-versions.mjs
+ ./scripts/prepare-gpui-dependency.sh
+
+ - name: Build the app
+ run: cargo +1.95.0 build --manifest-path apps/desktop-gpui/Cargo.toml --locked --release --bin cap-gpui
+
+ - name: Restore the meeting models
+ uses: actions/cache@v4
+ with:
+ path: ${{ runner.temp }}/meeting-models
+ key: meeting-models-v1-${{ hashFiles('scripts/ci/meetings/models.sh') }}
+
+ - name: Download the meeting models
+ run: bash scripts/ci/meetings/models.sh "$RUNNER_TEMP/meeting-models"
+
+ - name: Scripted meetings on Xvfb
+ run: |
+ env -u WAYLAND_DISPLAY XDG_SESSION_TYPE=x11 \
+ LD_LIBRARY_PATH="$GITHUB_WORKSPACE/target/native-deps/lib" \
+ ORT_DYLIB_PATH="$GITHUB_WORKSPACE/target/native-deps/onnxruntime/lib/libonnxruntime.so" \
+ CAP_MEETINGS_MODELS="$RUNNER_TEMP/meeting-models" \
+ dbus-run-session -- bash scripts/ci/meetings/linux.sh \
+ "$GITHUB_WORKSPACE/apps/desktop-gpui/target/release/cap-gpui" "$RUNNER_TEMP/meetings"
+
+ - name: Upload the runs
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: meetings-reliability-linux
+ path: |
+ ${{ runner.temp }}/meetings/*/check.txt
+ ${{ runner.temp }}/meetings/*/score.json
+ ${{ runner.temp }}/meetings/*/stub.jsonl
+ ${{ runner.temp }}/meetings/*/page_started.log
+ ${{ runner.temp }}/meetings/*/app.log
+ ${{ runner.temp }}/meetings/*/shots/*.png
+ ${{ runner.temp }}/meetings/indicator/indicator.png
+ retention-days: 7
+
+ build-windows:
+ name: Build for Windows meetings
+ if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
+ runs-on: blacksmith-8vcpu-windows-2025
+ timeout-minutes: 75
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Rust setup
+ uses: dtolnay/rust-toolchain@1.95.0
+ with:
+ targets: x86_64-pc-windows-msvc
+
+ - uses: ./.github/actions/setup-rust-cache
+ with:
+ target: x86_64-pc-windows-msvc
+ prefix-key: v1-rust-meetings
+ workspaces: apps/desktop-gpui -> target
+
+ - name: Run setup
+ shell: bash
+ run: node scripts/setup.js
+ env:
+ RUST_TARGET_TRIPLE: x86_64-pc-windows-msvc
+
+ - name: Prepare GPUI dependency
+ shell: bash
+ run: |
+ node scripts/sync-desktop-versions.mjs
+ ./scripts/prepare-gpui-dependency.sh
+
+ - name: Build the app
+ shell: bash
+ run: cargo +1.95.0 build --manifest-path apps/desktop-gpui/Cargo.toml --locked --release --bin cap-gpui
+
+ # The build compiles GPUI's shaders at startup from its source tree in ../zed-cap, by
+ # absolute path: the run job puts them back there (as picker-smoke.yml does).
+ - name: Stage the app
+ shell: bash
+ run: |
+ stage="$RUNNER_TEMP/stage"
+ mkdir -p "$stage/gpui-windows-shaders"
+ cp apps/desktop-gpui/target/release/cap-gpui.exe "$stage/"
+ cp ../zed-cap/crates/gpui_windows/src/*.hlsl "$stage/gpui-windows-shaders/"
+ printf '%s' "$GITHUB_WORKSPACE" > "$stage/build-workspace.txt"
+ printf '%s' "$(cd ../zed-cap && pwd -W)" > "$stage/build-zed.txt"
+
+ - uses: actions/upload-artifact@v4
+ with:
+ name: meetings-windows-app
+ path: ${{ runner.temp }}/stage
+ retention-days: 1
+
+ windows:
+ name: Meetings on Windows (real app)
+ needs: build-windows
+ runs-on: windows-2022
+ timeout-minutes: 45
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v4
+ with:
+ name: meetings-windows-app
+ path: ${{ runner.temp }}/app
+
+ - name: Put the build's source files back at its paths
+ shell: pwsh
+ run: |
+ $app = "$env:RUNNER_TEMP\app"
+ $workspace = (Get-Content "$app\build-workspace.txt" -Raw).Trim()
+ if ($workspace -ne $env:GITHUB_WORKSPACE) {
+ New-Item -ItemType Directory -Force (Split-Path $workspace) | Out-Null
+ cmd /c mklink /J "$workspace" "$env:GITHUB_WORKSPACE"
+ if ($LASTEXITCODE -ne 0) { throw "mklink failed" }
+ }
+ $shaders = Join-Path (Get-Content "$app\build-zed.txt" -Raw).Trim() "crates\gpui_windows\src"
+ New-Item -ItemType Directory -Force $shaders | Out-Null
+ Copy-Item "$app\gpui-windows-shaders\*.hlsl" $shaders
+
+ # FFmpeg and ONNX Runtime DLLs, next to the app.
+ - name: Run setup
+ shell: bash
+ run: node scripts/setup.js
+ env:
+ RUST_TARGET_TRIPLE: x86_64-pc-windows-msvc
+
+ - name: Virtual sound card
+ shell: pwsh
+ run: scripts/ci/meetings/setup_audio.ps1
+
+ - name: Harness tools
+ shell: pwsh
+ run: |
+ if (-not (Get-Command ffmpeg -ErrorAction SilentlyContinue)) { choco install ffmpeg -y --no-progress | Out-Null }
+ ffmpeg -version | Select-Object -First 1
+
+ - name: Restore the meeting models
+ uses: actions/cache@v4
+ with:
+ path: ${{ runner.temp }}/meeting-models
+ key: meeting-models-v1-${{ hashFiles('scripts/ci/meetings/models.sh') }}
+
+ - name: Download the meeting models
+ shell: bash
+ run: bash scripts/ci/meetings/models.sh "$RUNNER_TEMP/meeting-models"
+
+ - name: Scripted meetings
+ shell: pwsh
+ run: |
+ $bin = "$env:RUNNER_TEMP\app\cap-gpui.exe"
+ Copy-Item "$env:GITHUB_WORKSPACE\target\release\*.dll" "$env:RUNNER_TEMP\app\"
+ $env:CAP_MEETINGS_MODELS = "$env:RUNNER_TEMP\meeting-models"
+ & scripts/ci/meetings/windows.ps1 -Bin $bin -Work "$env:RUNNER_TEMP\meetings"
+ exit $LASTEXITCODE
+
+ - name: Upload the runs
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: meetings-reliability-windows
+ path: |
+ ${{ runner.temp }}/meetings/*/check.txt
+ ${{ runner.temp }}/meetings/*/score.json
+ ${{ runner.temp }}/meetings/*/stub.jsonl
+ ${{ runner.temp }}/meetings/*/page_started.log
+ ${{ runner.temp }}/meetings/*/app.log
+ ${{ runner.temp }}/meetings/*/shots/*.png
+ ${{ runner.temp }}/meetings/indicator/indicator.png
+ retention-days: 7
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 33ea76a47c0..62f920e18b0 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1412,6 +1412,21 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "cap-calendar"
+version = "0.1.0"
+dependencies = [
+ "base64 0.22.1",
+ "chrono",
+ "chrono-tz",
+ "rrule",
+ "serde",
+ "serde_json",
+ "sha2",
+ "thiserror 2.0.20",
+ "url",
+]
+
[[package]]
name = "cap-camera"
version = "0.1.0"
@@ -1560,10 +1575,12 @@ dependencies = [
"bytes",
"cap-audio",
"cap-automation",
+ "cap-calendar",
"cap-camera",
"cap-camera-effects",
"cap-cli-install",
"cap-cursor-info",
+ "cap-diarize",
"cap-editor",
"cap-enc-ffmpeg",
"cap-export",
@@ -1571,6 +1588,10 @@ dependencies = [
"cap-gpui-kernels",
"cap-i18n-build",
"cap-media-info",
+ "cap-meeting-platform",
+ "cap-meetings",
+ "cap-notes",
+ "cap-notes-ui",
"cap-project",
"cap-recording",
"cap-rendering",
@@ -1590,16 +1611,19 @@ dependencies = [
"ffmpeg-next",
"flume 0.11.1",
"futures-util",
+ "getrandom 0.2.17",
"global-hotkey",
"gpui",
"gpui_platform",
"gpui_tokio",
+ "iana-time-zone",
"image 0.25.10",
"jpeg-decoder",
"jxl-oxide",
"kameo",
"libc",
"lyon_tessellation",
+ "memmap2",
"minisign-verify",
"notify-rust",
"objc2 0.6.5",
@@ -1616,6 +1640,7 @@ dependencies = [
"rodio",
"same-file",
"sanitize-filename",
+ "scap-cpal",
"scap-targets",
"semver",
"serde",
@@ -1640,6 +1665,19 @@ dependencies = [
"x11rb",
]
+[[package]]
+name = "cap-diarize"
+version = "0.1.0"
+dependencies = [
+ "cap-meetings",
+ "ort",
+ "realfft",
+ "serde",
+ "serde_json",
+ "tempfile",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "cap-editor"
version = "0.1.0"
@@ -1869,6 +1907,36 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "cap-meeting-platform"
+version = "0.1.0"
+dependencies = [
+ "block2 0.6.2",
+ "cidre",
+ "flume 0.11.1",
+ "libc",
+ "objc2 0.6.5",
+ "objc2-event-kit",
+ "objc2-foundation 0.3.2",
+ "thiserror 2.0.20",
+ "tracing",
+ "windows 0.61.3",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "cap-meetings"
+version = "0.1.0"
+dependencies = [
+ "cap-diarize",
+ "chrono",
+ "serde",
+ "serde_json",
+ "tempfile",
+ "thiserror 2.0.20",
+ "unicode-segmentation",
+]
+
[[package]]
name = "cap-muxer-protocol"
version = "0.1.0"
@@ -1878,6 +1946,25 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "cap-notes"
+version = "0.1.0"
+dependencies = [
+ "serde",
+ "serde_json",
+ "unicode-segmentation",
+]
+
+[[package]]
+name = "cap-notes-ui"
+version = "0.1.0"
+dependencies = [
+ "cap-notes",
+ "gpui",
+ "gpui_platform",
+ "unicode-segmentation",
+]
+
[[package]]
name = "cap-project"
version = "0.1.0"
@@ -2275,6 +2362,16 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "chrono-tz"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6139a8597ed92cf816dfb33f5dd6cf0bb93a6adc938f11039f371bc5bcd26c3"
+dependencies = [
+ "chrono",
+ "phf 0.12.1",
+]
+
[[package]]
name = "cidre"
version = "0.11.0"
@@ -7503,6 +7600,22 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+[[package]]
+name = "objc2-event-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51bc9ad7325642172110196bacd6af64027ec5549ded7fc6589ea03e0f792bf8"
+dependencies = [
+ "bitflags 2.13.1",
+ "block2 0.6.2",
+ "objc2 0.6.5",
+ "objc2-app-kit 0.3.2",
+ "objc2-core-graphics",
+ "objc2-core-location",
+ "objc2-foundation 0.3.2",
+ "objc2-map-kit",
+]
+
[[package]]
name = "objc2-exception-helper"
version = "0.1.1"
@@ -7569,6 +7682,16 @@ dependencies = [
"objc2-core-foundation",
]
+[[package]]
+name = "objc2-map-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "579edede1c244621cd8229b70ea6e20e6ec3bab5a74afdfd494b446b681e1e64"
+dependencies = [
+ "objc2 0.6.5",
+ "objc2-foundation 0.3.2",
+]
+
[[package]]
name = "objc2-media-toolbox"
version = "0.3.2"
@@ -8137,6 +8260,15 @@ dependencies = [
"phf_shared 0.11.3",
]
+[[package]]
+name = "phf"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "913273894cec178f401a31ec4b656318d95473527be05c0752cc41cdc32be8b7"
+dependencies = [
+ "phf_shared 0.12.1",
+]
+
[[package]]
name = "phf"
version = "0.13.1"
@@ -8262,6 +8394,15 @@ dependencies = [
"siphasher 1.0.3",
]
+[[package]]
+name = "phf_shared"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06005508882fb681fd97892ecff4b7fd0fee13ef1aa569f8695dae7ab9099981"
+dependencies = [
+ "siphasher 1.0.3",
+]
+
[[package]]
name = "phf_shared"
version = "0.13.1"
@@ -9493,6 +9634,19 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "rrule"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "720acfb4980b9d8a6a430f6d7a11933e701ebbeba5eee39cc9d8c5f932aaff74"
+dependencies = [
+ "chrono",
+ "chrono-tz",
+ "log",
+ "regex",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "rustc-demangle"
version = "0.1.28"
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index db0159e9937..e6c2b6a0e14 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -5,7 +5,7 @@
# gpui's tree does not want.
[workspace]
resolver = "2"
-members = [".", "kernels", "i18n-build", "glass"]
+members = [".", "kernels", "i18n-build", "glass", "notes", "notes-ui", "calendar", "meetings", "meeting-platform", "diarize"]
[package]
name = "cap-desktop-gpui"
@@ -24,10 +24,18 @@ name = "studio-finalization-benchmark"
path = "../../crates/recording/examples/studio-finalization-benchmark.rs"
[dependencies]
+memmap2 = "0.9"
cap-audio = { path = "../../crates/audio" }
cap-cli-install = { path = "../../crates/cli-install" }
cap-gpui-kernels = { path = "kernels" }
cap-glass = { path = "glass" }
+cap-meetings = { path = "meetings" }
+cap-meeting-platform = { path = "meeting-platform" }
+cap-calendar = { path = "calendar" }
+cap-diarize = { path = "diarize" }
+cap-notes = { path = "notes" }
+cap-notes-ui = { path = "notes-ui" }
+iana-time-zone = "0.1"
# gpui — the wingleeio/zed fork Comet ships. The pinned rev carries f596cde
# ("destination alpha on transparent windows: Porter-Duff OVER, not additive"),
# which our transparent rounded main-window shell depends on.
@@ -137,6 +145,7 @@ chrono = "0.4"
serde_json = "1"
serde = { version = "1", features = ["derive"] }
sanitize-filename = "0.6.0"
+tempfile = "3"
# Moves media of clips removed from a project to the OS trash, so the user
# can still recover it. Its platform deps (objc2 0.6, windows 0.62) are
# already in the tree.
@@ -177,6 +186,7 @@ reqwest = { version = "0.12", default-features = false, features = [
"rustls-tls",
] }
futures-util = "0.3"
+getrandom = "0.2"
dirs = "6"
dunce = "1.0.5"
# Caption transcription (`src/transcription.rs`): the engine pin 0.6.0
@@ -214,6 +224,7 @@ libc = "0.2"
clipboard-rs = "0.2.4"
raw-window-handle = "0.6"
same-file = "1.0.6"
+scap-cpal = { path = "../../crates/scap-cpal" }
tray-icon = { version = "0.21.1", default-features = false }
windows-sys = { version = "0.59", features = [
"Win32_Foundation",
diff --git a/apps/desktop-gpui/Info.plist b/apps/desktop-gpui/Info.plist
index 4939978f032..d5b34279754 100644
--- a/apps/desktop-gpui/Info.plist
+++ b/apps/desktop-gpui/Info.plist
@@ -37,6 +37,12 @@
Cap uses your camera to record you in your Caps
NSMicrophoneUsageDescription
Cap uses your microphone to record you in your Caps
+ NSAudioCaptureUsageDescription
+ Cap records your computer's audio output during meetings so everyone in the call is transcribed
+ NSCalendarsFullAccessUsageDescription
+ Cap shows your upcoming meetings so it can offer to take notes
+ NSCalendarsUsageDescription
+ Cap shows your upcoming meetings so it can offer to take notes
NSScreenCaptureUsageDescription
Cap captures your screen as part of recording your Caps
NSCameraUseContinuityCameraDeviceType
diff --git a/apps/desktop-gpui/assets/icons/arrow-down.svg b/apps/desktop-gpui/assets/icons/arrow-down.svg
new file mode 100644
index 00000000000..f79668ce02c
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/arrow-down.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/audio-lines.svg b/apps/desktop-gpui/assets/icons/audio-lines.svg
new file mode 100644
index 00000000000..d3af0f1119c
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/audio-lines.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/calendar.svg b/apps/desktop-gpui/assets/icons/calendar.svg
new file mode 100644
index 00000000000..22b18bbd5e9
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/calendar.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/cloud.svg b/apps/desktop-gpui/assets/icons/cloud.svg
new file mode 100644
index 00000000000..5e72c1dadcd
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/cloud.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/corner-down-left.svg b/apps/desktop-gpui/assets/icons/corner-down-left.svg
new file mode 100644
index 00000000000..45b009f1038
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/corner-down-left.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/file-text.svg b/apps/desktop-gpui/assets/icons/file-text.svg
new file mode 100644
index 00000000000..3d2b0a48600
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/file-text.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/folder-plus.svg b/apps/desktop-gpui/assets/icons/folder-plus.svg
new file mode 100644
index 00000000000..c679daec3f1
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/folder-plus.svg
@@ -0,0 +1,4 @@
+
diff --git a/apps/desktop-gpui/assets/icons/google.svg b/apps/desktop-gpui/assets/icons/google.svg
new file mode 100644
index 00000000000..5ea88b48f7c
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/google.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/house.svg b/apps/desktop-gpui/assets/icons/house.svg
new file mode 100644
index 00000000000..b77271bfdd3
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/house.svg
@@ -0,0 +1,4 @@
+
diff --git a/apps/desktop-gpui/assets/icons/languages.svg b/apps/desktop-gpui/assets/icons/languages.svg
new file mode 100644
index 00000000000..7d977bc54f1
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/languages.svg
@@ -0,0 +1,3 @@
+
diff --git a/apps/desktop-gpui/assets/icons/microsoft.svg b/apps/desktop-gpui/assets/icons/microsoft.svg
new file mode 100644
index 00000000000..2c70b1cffd1
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/microsoft.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/notebook.svg b/apps/desktop-gpui/assets/icons/notebook.svg
new file mode 100644
index 00000000000..2efb56522b6
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/notebook.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/panel-left.svg b/apps/desktop-gpui/assets/icons/panel-left.svg
new file mode 100644
index 00000000000..95798a8605f
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/panel-left.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/pin.svg b/apps/desktop-gpui/assets/icons/pin.svg
new file mode 100644
index 00000000000..3b5b2732876
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/pin.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/square-pen.svg b/apps/desktop-gpui/assets/icons/square-pen.svg
new file mode 100644
index 00000000000..56ca1e39bc6
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/square-pen.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/assets/icons/users.svg b/apps/desktop-gpui/assets/icons/users.svg
new file mode 100644
index 00000000000..d652cdeed87
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/users.svg
@@ -0,0 +1 @@
+
diff --git a/apps/desktop-gpui/calendar/Cargo.toml b/apps/desktop-gpui/calendar/Cargo.toml
new file mode 100644
index 00000000000..68c32f6dfc2
--- /dev/null
+++ b/apps/desktop-gpui/calendar/Cargo.toml
@@ -0,0 +1,17 @@
+[package]
+name = "cap-calendar"
+version = "0.1.0"
+edition = "2024"
+license = "AGPL-3.0"
+publish = false
+
+[dependencies]
+base64 = "0.22"
+chrono = { version = "0.4", features = ["serde"] }
+chrono-tz = "0.10.4"
+rrule = "0.14.0"
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+sha2 = "0.10"
+thiserror = "2"
+url = "2.5.8"
diff --git a/apps/desktop-gpui/calendar/src/agenda.rs b/apps/desktop-gpui/calendar/src/agenda.rs
new file mode 100644
index 00000000000..450c04c7275
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/agenda.rs
@@ -0,0 +1,339 @@
+use std::cmp::Ordering;
+use std::collections::{HashMap, HashSet};
+
+use chrono::{DateTime, Duration, NaiveDate, NaiveTime, TimeZone, Utc};
+use chrono_tz::Tz;
+
+use crate::model::{CalendarEvent, SourceKind};
+use crate::text::normalize_title;
+
+pub const DEFAULT_LEAD: Duration = Duration::seconds(60);
+pub const MAX_LEAD: Duration = Duration::minutes(15);
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Filter {
+ pub hide_declined: bool,
+ pub hide_all_day: bool,
+ pub hide_without_participants: bool,
+ pub hidden_calendar_ids: HashSet,
+}
+
+impl Default for Filter {
+ fn default() -> Self {
+ Self {
+ hide_declined: true,
+ hide_all_day: true,
+ hide_without_participants: false,
+ hidden_calendar_ids: HashSet::new(),
+ }
+ }
+}
+
+impl Filter {
+ pub fn allows(&self, event: &CalendarEvent) -> bool {
+ !event.is_cancelled()
+ && !(self.hide_declined && event.is_declined())
+ && !(self.hide_all_day && event.all_day)
+ && !(self.hide_without_participants && !event.has_participants())
+ && !self.hidden_calendar_ids.contains(&event.calendar_id)
+ }
+}
+
+fn source_rank(source: SourceKind) -> u8 {
+ match source {
+ SourceKind::Google | SourceKind::Microsoft => 3,
+ SourceKind::System => 2,
+ SourceKind::Ics => 1,
+ }
+}
+
+fn richness(e: &CalendarEvent) -> (u8, bool, usize, bool) {
+ (
+ source_rank(e.source),
+ e.link.is_some(),
+ e.attendees.len(),
+ e.description.is_some(),
+ )
+}
+
+fn fill_missing(keep: &mut CalendarEvent, other: CalendarEvent) {
+ if keep.link.is_none() {
+ keep.link = other.link;
+ }
+ if keep.location.is_none() {
+ keep.location = other.location;
+ }
+ if keep.description.is_none() {
+ keep.description = other.description;
+ }
+ if keep.web_url.is_none() {
+ keep.web_url = other.web_url;
+ }
+ if keep.attendees.is_empty() {
+ keep.attendees = other.attendees;
+ }
+ if keep.organizer.is_none() {
+ keep.organizer = other.organizer;
+ }
+}
+
+fn dedup_keys(e: &CalendarEvent) -> Vec {
+ let start = e.start.timestamp();
+ let mut keys = Vec::with_capacity(2);
+ if let Some(link) = &e.link
+ && let Some(id) = &link.meeting_id
+ {
+ keys.push(format!(
+ "m|{}|{}|{start}",
+ link.provider.slug(),
+ id.to_ascii_lowercase()
+ ));
+ }
+ let title = normalize_title(&e.title);
+ if !title.is_empty() {
+ keys.push(format!("t|{title}|{start}|{}", e.all_day));
+ }
+ keys
+}
+
+pub fn dedupe(events: Vec) -> Vec {
+ let mut unique: Vec = Vec::with_capacity(events.len());
+ let mut ids: HashMap<(SourceKind, String, String), usize> = HashMap::new();
+ for event in events {
+ let id_key = (event.source, event.calendar_id.clone(), event.id.clone());
+ match ids.get(&id_key) {
+ Some(&i) => unique[i] = event,
+ None => {
+ ids.insert(id_key, unique.len());
+ unique.push(event);
+ }
+ }
+ }
+ let mut parent: Vec = (0..unique.len()).collect();
+ let mut owner: HashMap = HashMap::new();
+ for (i, event) in unique.iter().enumerate() {
+ for key in dedup_keys(event) {
+ match owner.get(&key) {
+ Some(&j) => union(&mut parent, i, j),
+ None => {
+ owner.insert(key, i);
+ }
+ }
+ }
+ }
+ let mut groups: HashMap> = HashMap::new();
+ for (i, event) in unique.into_iter().enumerate() {
+ groups.entry(root(&mut parent, i)).or_default().push(event);
+ }
+ let mut out: Vec = groups.into_values().filter_map(merge_group).collect();
+ out.sort_by(compare_events);
+ out
+}
+
+fn root(parent: &mut [usize], mut i: usize) -> usize {
+ while parent[i] != i {
+ parent[i] = parent[parent[i]];
+ i = parent[i];
+ }
+ i
+}
+
+fn union(parent: &mut [usize], a: usize, b: usize) {
+ let (a, b) = (root(parent, a), root(parent, b));
+ if a != b {
+ parent[a.max(b)] = a.min(b);
+ }
+}
+
+fn source_order(source: SourceKind) -> u8 {
+ match source {
+ SourceKind::Google => 0,
+ SourceKind::Microsoft => 1,
+ SourceKind::System => 2,
+ SourceKind::Ics => 3,
+ }
+}
+
+fn merge_group(mut group: Vec) -> Option {
+ group.sort_by(|a, b| {
+ richness(b)
+ .cmp(&richness(a))
+ .then_with(|| source_order(a.source).cmp(&source_order(b.source)))
+ .then_with(|| a.calendar_id.cmp(&b.calendar_id))
+ .then_with(|| a.id.cmp(&b.id))
+ });
+ let mut members = group.into_iter();
+ let mut keep = members.next()?;
+ for other in members {
+ fill_missing(&mut keep, other);
+ }
+ Some(keep)
+}
+
+fn preference(e: &CalendarEvent) -> (bool, usize) {
+ (e.link.is_some(), e.other_participants())
+}
+
+fn compare_events(a: &CalendarEvent, b: &CalendarEvent) -> Ordering {
+ a.start
+ .cmp(&b.start)
+ .then_with(|| preference(b).cmp(&preference(a)))
+ .then_with(|| a.end.cmp(&b.end))
+ .then_with(|| a.title.cmp(&b.title))
+ .then_with(|| a.id.cmp(&b.id))
+ .then_with(|| a.calendar_id.cmp(&b.calendar_id))
+ .then_with(|| source_order(a.source).cmp(&source_order(b.source)))
+}
+
+fn effective_end(e: &CalendarEvent) -> DateTime {
+ if e.end > e.start {
+ e.end
+ } else {
+ e.start
+ .checked_add_signed(Duration::minutes(1))
+ .unwrap_or(e.start)
+ }
+}
+
+fn fire_time(e: &CalendarEvent, lead: Duration) -> DateTime {
+ e.start.checked_sub_signed(lead).unwrap_or(e.start)
+}
+
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Agenda {
+ events: Vec,
+}
+
+impl Agenda {
+ pub fn new(events: Vec, filter: &Filter) -> Self {
+ let events = dedupe(events)
+ .into_iter()
+ .filter(|e| filter.allows(e))
+ .collect();
+ Self { events }
+ }
+
+ pub fn events(&self) -> &[CalendarEvent] {
+ &self.events
+ }
+
+ fn timed(&self) -> impl Iterator- {
+ self.events.iter().filter(|e| !e.all_day)
+ }
+
+ pub fn current(&self, now: DateTime) -> Vec<&CalendarEvent> {
+ let mut out: Vec<&CalendarEvent> = self
+ .timed()
+ .filter(|e| e.start <= now && now < effective_end(e))
+ .collect();
+ out.sort_by(|a, b| {
+ b.start
+ .cmp(&a.start)
+ .then_with(|| preference(b).cmp(&preference(a)))
+ });
+ out
+ }
+
+ pub fn next(&self, now: DateTime) -> Option<&CalendarEvent> {
+ self.timed().find(|e| e.start > now)
+ }
+
+ pub fn upcoming(&self, now: DateTime, horizon: Duration) -> Vec<&CalendarEvent> {
+ let until = now
+ .checked_add_signed(horizon)
+ .unwrap_or(DateTime::::MAX_UTC);
+ self.timed()
+ .filter(|e| effective_end(e) > now && e.start < until)
+ .collect()
+ }
+
+ pub fn for_day(&self, date: NaiveDate, tz: Tz) -> Vec<&CalendarEvent> {
+ let day_start = local_midnight(date, tz);
+ let day_end = date
+ .succ_opt()
+ .map_or(DateTime::::MAX_UTC, |d| local_midnight(d, tz));
+ self.events
+ .iter()
+ .filter(|e| {
+ if e.all_day {
+ let first = e.start.date_naive();
+ let last = e.end.date_naive();
+ first <= date && (date < last || (first == last && first == date))
+ } else {
+ e.start < day_end && effective_end(e) > day_start
+ }
+ })
+ .collect()
+ }
+}
+
+fn local_midnight(date: NaiveDate, tz: Tz) -> DateTime {
+ let naive = date.and_time(NaiveTime::MIN);
+ tz.from_local_datetime(&naive)
+ .earliest()
+ .map(|d| d.with_timezone(&Utc))
+ .unwrap_or_else(|| crate::tz::Zone::Named(tz).to_utc(naive))
+}
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct Reminder {
+ pub key: String,
+ pub fire_at: DateTime,
+ pub event: CalendarEvent,
+}
+
+pub fn reminder_key(event: &CalendarEvent) -> String {
+ format!(
+ "{}|{}|{}",
+ event.calendar_id,
+ event.id,
+ event.start.timestamp()
+ )
+}
+
+fn remindable(e: &CalendarEvent) -> bool {
+ !e.all_day && !e.is_cancelled() && !e.is_declined()
+}
+
+fn clamp_lead(lead: Duration) -> Duration {
+ lead.clamp(Duration::zero(), MAX_LEAD)
+}
+
+pub fn due_reminders(
+ events: &[CalendarEvent],
+ now: DateTime,
+ lead: Duration,
+ already_notified: &HashSet,
+) -> Vec {
+ let lead = clamp_lead(lead);
+ let mut out: Vec = events
+ .iter()
+ .filter(|e| remindable(e))
+ .filter(|e| fire_time(e, lead) <= now && now < effective_end(e))
+ .filter_map(|e| {
+ let key = reminder_key(e);
+ (!already_notified.contains(&key)).then(|| Reminder {
+ key,
+ fire_at: fire_time(e, lead),
+ event: e.clone(),
+ })
+ })
+ .collect();
+ out.sort_by(|a, b| compare_events(&a.event, &b.event));
+ out.dedup_by(|a, b| a.key == b.key);
+ out
+}
+
+pub fn next_wake(
+ events: &[CalendarEvent],
+ now: DateTime,
+ lead: Duration,
+) -> Option> {
+ let lead = clamp_lead(lead);
+ events
+ .iter()
+ .filter(|e| remindable(e))
+ .map(|e| fire_time(e, lead))
+ .filter(|fire| *fire > now)
+ .min()
+}
diff --git a/apps/desktop-gpui/calendar/src/error.rs b/apps/desktop-gpui/calendar/src/error.rs
new file mode 100644
index 00000000000..3e944e40734
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/error.rs
@@ -0,0 +1,75 @@
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ #[error("invalid JSON: {0}")]
+ Json(String),
+ #[error("unexpected response shape: {0}")]
+ InvalidResponse(String),
+ #[error("provider error {code}: {message}")]
+ Api {
+ status: Option,
+ code: String,
+ message: String,
+ },
+ #[error("refusing to follow a link outside the provider API: {0}")]
+ UntrustedUrl(String),
+ #[error("invalid input: {0}")]
+ InvalidInput(String),
+}
+
+impl Error {
+ pub fn is_unauthorized(&self) -> bool {
+ match self {
+ Error::Api { status, code, .. } => {
+ *status == Some(401)
+ || code.eq_ignore_ascii_case("InvalidAuthenticationToken")
+ || code.eq_ignore_ascii_case("UNAUTHENTICATED")
+ }
+ _ => false,
+ }
+ }
+}
+
+pub(crate) fn api_error_from(value: &serde_json::Value) -> Option {
+ let error = value.get("error")?;
+ if let Some(code) = error.as_str() {
+ return Some(Error::Api {
+ status: None,
+ code: code.to_string(),
+ message: value
+ .get("error_description")
+ .and_then(|v| v.as_str())
+ .unwrap_or_default()
+ .to_string(),
+ });
+ }
+ let status = error
+ .get("code")
+ .and_then(|c| c.as_u64())
+ .and_then(|c| u16::try_from(c).ok());
+ let code = error
+ .get("status")
+ .and_then(|s| s.as_str())
+ .or_else(|| error.get("code").and_then(|c| c.as_str()))
+ .map(str::to_string)
+ .or_else(|| status.map(|s| s.to_string()))
+ .unwrap_or_else(|| "unknown".to_string());
+ let message = error
+ .get("message")
+ .and_then(|m| m.as_str())
+ .unwrap_or_default()
+ .to_string();
+ Some(Error::Api {
+ status,
+ code,
+ message,
+ })
+}
+
+pub(crate) fn parse_json(json: &str) -> Result {
+ let value: serde_json::Value =
+ serde_json::from_str(json).map_err(|e| Error::Json(e.to_string()))?;
+ if let Some(err) = api_error_from(&value) {
+ return Err(err);
+ }
+ Ok(value)
+}
diff --git a/apps/desktop-gpui/calendar/src/google.rs b/apps/desktop-gpui/calendar/src/google.rs
new file mode 100644
index 00000000000..3644fcdda85
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/google.rs
@@ -0,0 +1,361 @@
+use std::ops::Range;
+
+use chrono::{DateTime, NaiveDate, NaiveDateTime, NaiveTime, SecondsFormat, Utc};
+use serde::Deserialize;
+use serde_json::Value;
+
+use crate::error::{Error, parse_json};
+use crate::http::{HttpRequestSpec, api_url};
+use crate::link::{ConferenceEntry, ConferenceKind, event_meeting_link};
+use crate::model::{
+ CalendarEvent, CalendarInfo, EventStatus, Page, Person, Response, SourceKind,
+ derive_self_response, is_self_email,
+};
+use crate::text::non_empty;
+use crate::tz::resolve_tzid;
+
+const API: &str = "https://www.googleapis.com/calendar/v3";
+
+const EVENT_FIELDS: &str = "nextPageToken,timeZone,items(id,status,htmlLink,summary,description,location,start,end,organizer(email,displayName,self),attendees(email,displayName,self,responseStatus,resource),hangoutLink,conferenceData(entryPoints(entryPointType,uri,meetingCode),conferenceSolution(name,key(type)),conferenceId),recurringEventId,originalStartTime,eventType,transparency,iCalUID)";
+
+const CALENDAR_FIELDS: &str = "nextPageToken,items(id,summary,summaryOverride,primary,backgroundColor,selected,accessRole,timeZone,hidden,deleted)";
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GoogleOptions {
+ pub include_status_events: bool,
+ pub include_cancelled: bool,
+ pub self_emails: Vec,
+}
+
+fn rfc3339(dt: DateTime) -> String {
+ dt.to_rfc3339_opts(SecondsFormat::Secs, true)
+}
+
+fn calendar_url(path: &[&str]) -> String {
+ api_url(API, path)
+}
+
+pub fn google_events_request(
+ calendar_id: &str,
+ window: &Range>,
+ page_token: Option<&str>,
+) -> HttpRequestSpec {
+ let mut spec = HttpRequestSpec::get(calendar_url(&["calendars", calendar_id, "events"]))
+ .with_query("singleEvents", "true")
+ .with_query("orderBy", "startTime")
+ .with_query("timeMin", rfc3339(window.start))
+ .with_query("timeMax", rfc3339(window.end))
+ .with_query("maxResults", "250")
+ .with_query("fields", EVENT_FIELDS);
+ if let Some(token) = page_token.filter(|t| !t.is_empty()) {
+ spec = spec.with_query("pageToken", token);
+ }
+ spec
+}
+
+pub fn google_calendar_list_request(page_token: Option<&str>) -> HttpRequestSpec {
+ let mut spec = HttpRequestSpec::get(calendar_url(&["users", "me", "calendarList"]))
+ .with_query("maxResults", "250")
+ .with_query("fields", CALENDAR_FIELDS);
+ if let Some(token) = page_token.filter(|t| !t.is_empty()) {
+ spec = spec.with_query("pageToken", token);
+ }
+ spec
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GTime {
+ date: Option,
+ date_time: Option,
+ time_zone: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GPerson {
+ email: Option,
+ display_name: Option,
+ #[serde(rename = "self")]
+ is_self: bool,
+ response_status: Option,
+ resource: bool,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GEntryPoint {
+ entry_point_type: Option,
+ uri: Option,
+ meeting_code: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GConference {
+ entry_points: Vec,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GEvent {
+ id: Option,
+ status: Option,
+ html_link: Option,
+ summary: Option,
+ description: Option,
+ location: Option,
+ start: Option,
+ end: Option,
+ original_start_time: Option,
+ organizer: Option,
+ attendees: Vec,
+ hangout_link: Option,
+ conference_data: Option,
+ recurring_event_id: Option,
+ event_type: Option,
+ transparency: Option,
+}
+
+enum Resolved {
+ Timed(DateTime),
+ Day(NaiveDate),
+}
+
+fn resolve_time(t: >ime, fallback_zone: Option<&str>) -> Option {
+ if let Some(dt) = t.date_time.as_deref() {
+ if let Ok(parsed) = DateTime::parse_from_rfc3339(dt.trim()) {
+ return Some(Resolved::Timed(parsed.with_timezone(&Utc)));
+ }
+ let naive = NaiveDateTime::parse_from_str(dt.trim(), "%Y-%m-%dT%H:%M:%S%.f").ok()?;
+ let zone = t
+ .time_zone
+ .as_deref()
+ .or(fallback_zone)
+ .and_then(resolve_tzid)?;
+ return Some(Resolved::Timed(zone.to_utc(naive)));
+ }
+ let date = NaiveDate::parse_from_str(t.date.as_deref()?.trim(), "%Y-%m-%d").ok()?;
+ Some(Resolved::Day(date))
+}
+
+fn google_response(value: Option<&str>) -> Response {
+ match value.unwrap_or_default() {
+ "accepted" => Response::Accepted,
+ "declined" => Response::Declined,
+ "tentative" => Response::Tentative,
+ "needsAction" => Response::NeedsAction,
+ _ => Response::Unknown,
+ }
+}
+
+fn person(p: &GPerson, self_emails: &[String]) -> Person {
+ Person {
+ name: non_empty(p.display_name.as_deref()),
+ email: non_empty(p.email.as_deref()),
+ is_self: p.is_self || is_self_email(p.email.as_deref(), self_emails),
+ response: google_response(p.response_status.as_deref()),
+ }
+}
+
+const STATUS_EVENT_TYPES: [&str; 3] = ["workingLocation", "outOfOffice", "focusTime"];
+
+fn map_event(
+ e: GEvent,
+ calendar_id: &str,
+ zone: Option<&str>,
+ opts: &GoogleOptions,
+) -> Option {
+ let status = match e.status.as_deref() {
+ Some("cancelled") => EventStatus::Cancelled,
+ Some("tentative") => EventStatus::Tentative,
+ _ => EventStatus::Confirmed,
+ };
+ if status == EventStatus::Cancelled && !opts.include_cancelled {
+ return None;
+ }
+ if !opts.include_status_events
+ && e.event_type
+ .as_deref()
+ .is_some_and(|t| STATUS_EVENT_TYPES.contains(&t))
+ {
+ return None;
+ }
+ let id = non_empty(e.id.as_deref())?;
+ let start = e
+ .start
+ .as_ref()
+ .or(e.original_start_time.as_ref())
+ .and_then(|t| resolve_time(t, zone))?;
+ let end = e.end.as_ref().and_then(|t| resolve_time(t, zone));
+ let midnight = NaiveTime::MIN;
+ let (start, end, all_day) = match (start, end) {
+ (Resolved::Day(s), end) => {
+ let e_date = match end {
+ Some(Resolved::Day(d)) if d > s => d,
+ _ => s.succ_opt().unwrap_or(s),
+ };
+ (
+ s.and_time(midnight).and_utc(),
+ e_date.and_time(midnight).and_utc(),
+ true,
+ )
+ }
+ (Resolved::Timed(s), Some(Resolved::Timed(end))) if end >= s => (s, end, false),
+ (Resolved::Timed(s), _) => (s, s, false),
+ };
+ let organizer = e.organizer.as_ref().map(|o| person(o, &opts.self_emails));
+ let attendees: Vec = e
+ .attendees
+ .iter()
+ .filter(|a| !a.resource)
+ .map(|a| person(a, &opts.self_emails))
+ .collect();
+ let mut conference: Vec = e
+ .conference_data
+ .as_ref()
+ .map(|c| {
+ c.entry_points
+ .iter()
+ .filter_map(|ep| {
+ Some(ConferenceEntry {
+ kind: ConferenceKind::from_entry_point_type(
+ ep.entry_point_type.as_deref().unwrap_or_default(),
+ ),
+ uri: non_empty(ep.uri.as_deref())?,
+ meeting_code: non_empty(ep.meeting_code.as_deref()),
+ })
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ if let Some(hangout) = non_empty(e.hangout_link.as_deref())
+ && !conference.iter().any(|c| c.kind == ConferenceKind::Video)
+ {
+ conference.push(ConferenceEntry::video(hangout));
+ }
+ let link = event_meeting_link(
+ &conference,
+ e.location.as_deref(),
+ e.description.as_deref(),
+ None,
+ );
+ let self_response = derive_self_response(organizer.as_ref(), &attendees, Response::Unknown);
+ Some(CalendarEvent {
+ id,
+ series_id: non_empty(e.recurring_event_id.as_deref()),
+ calendar_id: calendar_id.to_string(),
+ source: SourceKind::Google,
+ title: e.summary.map(|s| s.trim().to_string()).unwrap_or_default(),
+ start,
+ end,
+ all_day,
+ location: non_empty(e.location.as_deref()),
+ description: non_empty(e.description.as_deref()),
+ organizer,
+ attendees,
+ self_response,
+ link,
+ status,
+ web_url: non_empty(e.html_link.as_deref()),
+ free: e.transparency.as_deref() == Some("transparent"),
+ })
+}
+
+pub(crate) fn array_field<'a>(value: &'a Value, name: &str) -> Result<&'a [Value], Error> {
+ match value.get(name) {
+ None | Some(Value::Null) => Ok(&[]),
+ Some(Value::Array(items)) => Ok(items),
+ Some(_) => Err(Error::InvalidResponse(format!("{name} is not an array"))),
+ }
+}
+
+fn items(value: &Value) -> Result<&[Value], Error> {
+ array_field(value, "items")
+}
+
+fn next_token(value: &Value) -> Option {
+ non_empty(value.get("nextPageToken").and_then(Value::as_str))
+}
+
+pub fn parse_google_events(json: &str, calendar_id: &str) -> Result, Error> {
+ parse_google_events_with(json, calendar_id, &GoogleOptions::default())
+}
+
+pub fn parse_google_events_with(
+ json: &str,
+ calendar_id: &str,
+ opts: &GoogleOptions,
+) -> Result, Error> {
+ let value = parse_json(json)?;
+ if !value.is_object() {
+ return Err(Error::InvalidResponse("expected an object".to_string()));
+ }
+ let zone = value.get("timeZone").and_then(Value::as_str);
+ let mut page = Page {
+ items: Vec::new(),
+ next: next_token(&value),
+ skipped: 0,
+ };
+ for item in items(&value)? {
+ let mapped = serde_json::from_value::(item.clone())
+ .ok()
+ .and_then(|e| map_event(e, calendar_id, zone, opts));
+ match mapped {
+ Some(event) => page.items.push(event),
+ None => page.skipped += 1,
+ }
+ }
+ Ok(page)
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct GCalendar {
+ id: Option,
+ summary: Option,
+ summary_override: Option,
+ primary: bool,
+ background_color: Option,
+ selected: bool,
+ access_role: Option,
+ time_zone: Option,
+ deleted: bool,
+}
+
+pub fn parse_google_calendar_list(json: &str) -> Result, Error> {
+ let value = parse_json(json)?;
+ let mut page = Page {
+ items: Vec::new(),
+ next: next_token(&value),
+ skipped: 0,
+ };
+ for item in items(&value)? {
+ let Some(cal) = serde_json::from_value::(item.clone())
+ .ok()
+ .filter(|c| !c.deleted)
+ else {
+ page.skipped += 1;
+ continue;
+ };
+ let Some(id) = non_empty(cal.id.as_deref()) else {
+ page.skipped += 1;
+ continue;
+ };
+ let name = non_empty(cal.summary_override.as_deref())
+ .or_else(|| non_empty(cal.summary.as_deref()))
+ .unwrap_or_else(|| id.clone());
+ page.items.push(CalendarInfo {
+ owner_email: (cal.primary && id.contains('@')).then(|| id.clone()),
+ id,
+ name,
+ source: SourceKind::Google,
+ primary: cal.primary,
+ color: non_empty(cal.background_color.as_deref()),
+ selected: cal.selected || cal.primary,
+ access_role: non_empty(cal.access_role.as_deref()),
+ time_zone: non_empty(cal.time_zone.as_deref()),
+ });
+ }
+ Ok(page)
+}
diff --git a/apps/desktop-gpui/calendar/src/graph.rs b/apps/desktop-gpui/calendar/src/graph.rs
new file mode 100644
index 00000000000..d299a2ea7e2
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/graph.rs
@@ -0,0 +1,419 @@
+use std::ops::Range;
+
+use chrono::{DateTime, NaiveDateTime, NaiveTime, SecondsFormat, Utc};
+use serde::Deserialize;
+use serde_json::Value;
+
+use crate::error::{Error, parse_json};
+use crate::google::array_field;
+use crate::http::{HttpRequestSpec, api_url};
+use crate::link::{ConferenceEntry, event_meeting_link};
+use crate::model::{
+ CalendarEvent, CalendarInfo, EventStatus, Page, Person, Response, SourceKind,
+ derive_self_response, is_self_email,
+};
+use crate::text::{html_to_text, looks_like_html, non_empty};
+use crate::tz::{Zone, resolve_tzid};
+
+const API: &str = "https://graph.microsoft.com/v1.0";
+const TRUSTED_PREFIX: &str = "https://graph.microsoft.com/";
+
+const EVENT_SELECT: &str = "id,subject,body,bodyPreview,start,end,isAllDay,isCancelled,location,locations,organizer,attendees,responseStatus,onlineMeeting,onlineMeetingUrl,isOnlineMeeting,onlineMeetingProvider,seriesMasterId,type,webLink,showAs";
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct GraphOptions {
+ pub include_cancelled: bool,
+ pub self_emails: Vec,
+}
+
+fn with_common_headers(spec: HttpRequestSpec) -> HttpRequestSpec {
+ spec.with_header("Prefer", "outlook.timezone=\"UTC\"")
+ .with_header("Accept", "application/json")
+}
+
+fn trusted_next_link(next_link: &str) -> Result {
+ let trimmed = next_link.trim();
+ let parsed = url::Url::parse(trimmed).map_err(|_| Error::UntrustedUrl(trimmed.to_string()))?;
+ if !trimmed.starts_with(TRUSTED_PREFIX)
+ || parsed.host_str() != Some("graph.microsoft.com")
+ || parsed.scheme() != "https"
+ || !parsed.username().is_empty()
+ || parsed.port().is_some()
+ {
+ return Err(Error::UntrustedUrl(trimmed.to_string()));
+ }
+ Ok(with_common_headers(HttpRequestSpec::get(
+ parsed.to_string(),
+ )))
+}
+
+pub fn graph_calendar_view_request(
+ calendar_id: Option<&str>,
+ window: &Range>,
+ next_link: Option<&str>,
+) -> Result {
+ if let Some(next) = next_link.filter(|n| !n.trim().is_empty()) {
+ return trusted_next_link(next);
+ }
+ let url = match calendar_id.filter(|c| !c.is_empty()) {
+ Some(id) => api_url(API, &["me", "calendars", id, "calendarView"]),
+ None => api_url(API, &["me", "calendarView"]),
+ };
+ let spec = HttpRequestSpec::get(url)
+ .with_query(
+ "startDateTime",
+ window.start.to_rfc3339_opts(SecondsFormat::Secs, true),
+ )
+ .with_query(
+ "endDateTime",
+ window.end.to_rfc3339_opts(SecondsFormat::Secs, true),
+ )
+ .with_query("$select", EVENT_SELECT)
+ .with_query("$orderby", "start/dateTime")
+ .with_query("$top", "250");
+ Ok(with_common_headers(spec))
+}
+
+pub fn graph_calendars_request(next_link: Option<&str>) -> Result {
+ if let Some(next) = next_link.filter(|n| !n.trim().is_empty()) {
+ return trusted_next_link(next);
+ }
+ Ok(with_common_headers(
+ HttpRequestSpec::get(api_url(API, &["me", "calendars"]))
+ .with_query(
+ "$select",
+ "id,name,color,hexColor,isDefaultCalendar,canEdit,owner",
+ )
+ .with_query("$top", "100"),
+ ))
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MTime {
+ date_time: Option,
+ time_zone: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MEmail {
+ name: Option,
+ address: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MStatus {
+ response: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MAttendee {
+ #[serde(rename = "type")]
+ kind: Option,
+ status: Option,
+ email_address: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MOrganizer {
+ email_address: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MBody {
+ content_type: Option,
+ content: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MLocation {
+ display_name: Option,
+ location_uri: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MOnlineMeeting {
+ join_url: Option,
+ conference_id: Option,
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MEvent {
+ id: Option,
+ subject: Option,
+ body: Option,
+ body_preview: Option,
+ start: Option,
+ end: Option,
+ is_all_day: bool,
+ is_cancelled: bool,
+ location: Option,
+ locations: Vec,
+ organizer: Option,
+ attendees: Vec,
+ response_status: Option,
+ online_meeting: Option,
+ online_meeting_url: Option,
+ series_master_id: Option,
+ web_link: Option,
+ show_as: Option,
+}
+
+fn graph_response(value: Option<&str>) -> Response {
+ match value.unwrap_or_default() {
+ "accepted" | "organizer" => Response::Accepted,
+ "declined" => Response::Declined,
+ "tentativelyAccepted" => Response::Tentative,
+ "notResponded" => Response::NeedsAction,
+ _ => Response::Unknown,
+ }
+}
+
+fn parse_graph_time(t: &MTime) -> Option<(NaiveDateTime, Zone)> {
+ let raw = t.date_time.as_deref()?.trim();
+ let naive = NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S%.f")
+ .or_else(|_| NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M"))
+ .ok()
+ .or_else(|| {
+ DateTime::parse_from_rfc3339(raw)
+ .ok()
+ .map(|d| d.with_timezone(&Utc).naive_utc())
+ })?;
+ let zone = t
+ .time_zone
+ .as_deref()
+ .and_then(resolve_tzid)
+ .unwrap_or(Zone::Utc);
+ Some((naive, zone))
+}
+
+fn email_person(email: &MEmail, self_emails: &[String], response: Response) -> Person {
+ Person {
+ name: non_empty(email.name.as_deref()),
+ email: non_empty(email.address.as_deref()),
+ is_self: is_self_email(email.address.as_deref(), self_emails),
+ response,
+ }
+}
+
+fn map_event(e: MEvent, calendar_id: &str, opts: &GraphOptions) -> Option {
+ let status = if e.is_cancelled {
+ EventStatus::Cancelled
+ } else {
+ EventStatus::Confirmed
+ };
+ if status == EventStatus::Cancelled && !opts.include_cancelled {
+ return None;
+ }
+ let id = non_empty(e.id.as_deref())?;
+ let (start_naive, start_zone) = e.start.as_ref().and_then(parse_graph_time)?;
+ let end = e.end.as_ref().and_then(parse_graph_time);
+ let (start, end) = if e.is_all_day {
+ let start_date = start_naive.date();
+ let end_date = end
+ .map(|(n, _)| n.date())
+ .filter(|d| *d > start_date)
+ .or_else(|| start_date.succ_opt())
+ .unwrap_or(start_date);
+ (
+ start_date.and_time(NaiveTime::MIN).and_utc(),
+ end_date.and_time(NaiveTime::MIN).and_utc(),
+ )
+ } else {
+ let start = start_zone.to_utc(start_naive);
+ let end = end
+ .map(|(n, z)| z.to_utc(n))
+ .filter(|e| *e >= start)
+ .unwrap_or(start);
+ (start, end)
+ };
+ let organizer = e
+ .organizer
+ .as_ref()
+ .and_then(|o| o.email_address.as_ref())
+ .map(|em| email_person(em, &opts.self_emails, Response::Accepted));
+ let attendees: Vec = e
+ .attendees
+ .iter()
+ .filter(|a| {
+ !a.kind
+ .as_deref()
+ .is_some_and(|k| k.eq_ignore_ascii_case("resource"))
+ })
+ .filter_map(|a| {
+ let response = graph_response(a.status.as_ref().and_then(|s| s.response.as_deref()));
+ a.email_address
+ .as_ref()
+ .map(|em| email_person(em, &opts.self_emails, response))
+ })
+ .collect();
+ let fallback = graph_response(
+ e.response_status
+ .as_ref()
+ .and_then(|s| s.response.as_deref()),
+ );
+ let mut organizer = organizer;
+ if e.response_status
+ .as_ref()
+ .and_then(|s| s.response.as_deref())
+ == Some("organizer")
+ && let Some(org) = organizer.as_mut()
+ {
+ org.is_self = true;
+ }
+ let self_response = derive_self_response(organizer.as_ref(), &attendees, fallback);
+
+ let mut conference = Vec::new();
+ if let Some(join) = e
+ .online_meeting
+ .as_ref()
+ .and_then(|m| non_empty(m.join_url.as_deref()))
+ {
+ conference.push(ConferenceEntry {
+ meeting_code: e
+ .online_meeting
+ .as_ref()
+ .and_then(|m| non_empty(m.conference_id.as_deref())),
+ ..ConferenceEntry::video(join)
+ });
+ }
+ if let Some(url) = non_empty(e.online_meeting_url.as_deref()) {
+ conference.push(ConferenceEntry::video(url));
+ }
+ let location = e
+ .location
+ .as_ref()
+ .and_then(|l| non_empty(l.display_name.as_deref()));
+ let location_uris: Vec<&str> = e
+ .location
+ .iter()
+ .chain(e.locations.iter())
+ .filter_map(|l| l.location_uri.as_deref())
+ .collect();
+ let body = e.body.as_ref().and_then(|b| b.content.as_deref());
+ let link = event_meeting_link(&conference, location.as_deref(), body, None).or_else(|| {
+ location_uris
+ .iter()
+ .find_map(|u| crate::link::classify_url(u))
+ });
+ let is_html = e
+ .body
+ .as_ref()
+ .and_then(|b| b.content_type.as_deref())
+ .is_some_and(|t| t.eq_ignore_ascii_case("html"))
+ || body.is_some_and(looks_like_html);
+ let description = body
+ .map(|b| {
+ if is_html {
+ html_to_text(b)
+ } else {
+ b.to_string()
+ }
+ })
+ .and_then(|d| non_empty(Some(&d)))
+ .or_else(|| non_empty(e.body_preview.as_deref()));
+
+ Some(CalendarEvent {
+ id,
+ series_id: non_empty(e.series_master_id.as_deref()),
+ calendar_id: calendar_id.to_string(),
+ source: SourceKind::Microsoft,
+ title: e.subject.map(|s| s.trim().to_string()).unwrap_or_default(),
+ start,
+ end,
+ all_day: e.is_all_day,
+ location,
+ description,
+ organizer,
+ attendees,
+ self_response,
+ link,
+ status,
+ web_url: non_empty(e.web_link.as_deref()),
+ free: e.show_as.as_deref() == Some("free"),
+ })
+}
+
+fn next_link(value: &Value) -> Option {
+ non_empty(value.get("@odata.nextLink").and_then(Value::as_str))
+}
+
+pub fn parse_graph_events(json: &str, calendar_id: &str) -> Result, Error> {
+ parse_graph_events_with(json, calendar_id, &GraphOptions::default())
+}
+
+pub fn parse_graph_events_with(
+ json: &str,
+ calendar_id: &str,
+ opts: &GraphOptions,
+) -> Result, Error> {
+ let value = parse_json(json)?;
+ if !value.is_object() {
+ return Err(Error::InvalidResponse("expected an object".to_string()));
+ }
+ let mut page = Page {
+ items: Vec::new(),
+ next: next_link(&value),
+ skipped: 0,
+ };
+ for item in array_field(&value, "value")? {
+ let mapped = serde_json::from_value::(item.clone())
+ .ok()
+ .and_then(|e| map_event(e, calendar_id, opts));
+ match mapped {
+ Some(event) => page.items.push(event),
+ None => page.skipped += 1,
+ }
+ }
+ Ok(page)
+}
+
+#[derive(Deserialize, Default)]
+#[serde(rename_all = "camelCase", default)]
+struct MCalendar {
+ id: Option,
+ name: Option,
+ hex_color: Option,
+ is_default_calendar: bool,
+ can_edit: bool,
+ owner: Option,
+}
+
+pub fn parse_graph_calendars(json: &str) -> Result, Error> {
+ let value = parse_json(json)?;
+ let mut page = Page {
+ items: Vec::new(),
+ next: next_link(&value),
+ skipped: 0,
+ };
+ for item in array_field(&value, "value")? {
+ let Some(cal) = serde_json::from_value::(item.clone()).ok() else {
+ page.skipped += 1;
+ continue;
+ };
+ let Some(id) = non_empty(cal.id.as_deref()) else {
+ page.skipped += 1;
+ continue;
+ };
+ page.items.push(CalendarInfo {
+ name: non_empty(cal.name.as_deref()).unwrap_or_else(|| id.clone()),
+ id,
+ source: SourceKind::Microsoft,
+ primary: cal.is_default_calendar,
+ color: non_empty(cal.hex_color.as_deref()),
+ selected: true,
+ access_role: Some(if cal.can_edit { "writer" } else { "reader" }.to_string()),
+ owner_email: cal.owner.and_then(|o| non_empty(o.address.as_deref())),
+ time_zone: None,
+ });
+ }
+ Ok(page)
+}
diff --git a/apps/desktop-gpui/calendar/src/http.rs b/apps/desktop-gpui/calendar/src/http.rs
new file mode 100644
index 00000000000..0fdca9eb88e
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/http.rs
@@ -0,0 +1,100 @@
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum HttpMethod {
+ Get,
+ Post,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct HttpRequestSpec {
+ pub method: HttpMethod,
+ pub url: String,
+ pub query: Vec<(String, String)>,
+ pub headers: Vec<(String, String)>,
+ pub form: Vec<(String, String)>,
+}
+
+impl HttpRequestSpec {
+ pub(crate) fn get(url: impl Into) -> Self {
+ Self {
+ method: HttpMethod::Get,
+ url: url.into(),
+ query: Vec::new(),
+ headers: Vec::new(),
+ form: Vec::new(),
+ }
+ }
+
+ pub(crate) fn post_form(url: impl Into, form: Vec<(String, String)>) -> Self {
+ Self {
+ method: HttpMethod::Post,
+ url: url.into(),
+ query: Vec::new(),
+ headers: vec![(
+ "Content-Type".to_string(),
+ "application/x-www-form-urlencoded".to_string(),
+ )],
+ form,
+ }
+ }
+
+ pub(crate) fn with_query(mut self, key: &str, value: impl Into) -> Self {
+ self.query.push((key.to_string(), value.into()));
+ self
+ }
+
+ pub(crate) fn with_header(mut self, key: &str, value: impl Into) -> Self {
+ self.headers.push((key.to_string(), value.into()));
+ self
+ }
+
+ pub fn url_with_query(&self) -> String {
+ if self.query.is_empty() {
+ return self.url.clone();
+ }
+ match url::Url::parse(&self.url) {
+ Ok(mut parsed) => {
+ parsed
+ .query_pairs_mut()
+ .extend_pairs(self.query.iter().map(|(k, v)| (k.as_str(), v.as_str())));
+ parsed.to_string()
+ }
+ Err(_) => {
+ let encoded = encode_pairs(&self.query);
+ let sep = if self.url.contains('?') { '&' } else { '?' };
+ format!("{}{sep}{encoded}", self.url)
+ }
+ }
+ }
+
+ pub fn form_body(&self) -> Option {
+ if self.method != HttpMethod::Post {
+ return None;
+ }
+ Some(encode_pairs(&self.form))
+ }
+
+ pub fn header(&self, name: &str) -> Option<&str> {
+ self.headers
+ .iter()
+ .find(|(k, _)| k.eq_ignore_ascii_case(name))
+ .map(|(_, v)| v.as_str())
+ }
+}
+
+pub(crate) fn encode_pairs(pairs: &[(String, String)]) -> String {
+ url::form_urlencoded::Serializer::new(String::new())
+ .extend_pairs(pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())))
+ .finish()
+}
+
+pub(crate) fn api_url(base: &str, segments: &[&str]) -> String {
+ match url::Url::parse(base) {
+ Ok(mut url) => {
+ if let Ok(mut path) = url.path_segments_mut() {
+ path.pop_if_empty().extend(segments);
+ }
+ url.to_string()
+ }
+ Err(_) => base.to_string(),
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/budget.rs b/apps/desktop-gpui/calendar/src/ics/budget.rs
new file mode 100644
index 00000000000..0954bfa7e37
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/budget.rs
@@ -0,0 +1,25 @@
+pub(crate) const FEED_BUDGET: u64 = 3_000_000;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Budget {
+ left: u64,
+}
+
+impl Budget {
+ pub fn new(left: u64) -> Self {
+ Self { left }
+ }
+
+ #[cfg(test)]
+ pub fn left(&self) -> u64 {
+ self.left
+ }
+
+ pub fn can_afford(&self, cost: u64) -> bool {
+ self.left >= cost
+ }
+
+ pub fn charge(&mut self, cost: u64) {
+ self.left = self.left.saturating_sub(cost);
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/expand.rs b/apps/desktop-gpui/calendar/src/ics/expand.rs
new file mode 100644
index 00000000000..e153b7cfb1f
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/expand.rs
@@ -0,0 +1,274 @@
+use std::collections::{HashMap, HashSet};
+use std::ops::Range;
+
+use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, Utc};
+
+use super::budget::Budget;
+use super::{Exclusion, ParsedCalendar, RawEvent, RawPerson};
+use crate::link::{classify_url, event_meeting_link, find_meeting_link};
+use crate::model::{
+ CalendarEvent, EventStatus, Person, Response, SourceKind, derive_self_response, is_self_email,
+};
+use crate::text::html_to_text;
+
+pub fn expand(
+ cal: &ParsedCalendar,
+ window: Range>,
+ self_emails: &[String],
+) -> Vec {
+ if window.start >= window.end {
+ return Vec::new();
+ }
+ let opts = &cal.options;
+ let mut budget = cal.budget;
+ let mut overrides: HashMap<&str, Vec<&RawEvent>> = HashMap::new();
+ let mut masters: Vec<&RawEvent> = Vec::new();
+ for event in &cal.events {
+ if event.recurrence_id.is_some() {
+ overrides.entry(event.uid.as_str()).or_default().push(event);
+ } else {
+ masters.push(event);
+ }
+ }
+ let builder = Builder {
+ calendar_id: &opts.calendar_id,
+ self_emails,
+ };
+ let keep = |status: EventStatus| status != EventStatus::Cancelled || opts.include_cancelled;
+ let overlaps =
+ |start: DateTime, end: DateTime| start < window.end && end > window.start;
+
+ let mut out: Vec = Vec::new();
+ for master in masters {
+ let room = opts.max_events.saturating_sub(out.len());
+ if room == 0 {
+ break;
+ }
+ if !keep(master.status) {
+ continue;
+ }
+ let replaced: HashSet = overrides
+ .get(master.uid.as_str())
+ .map(|list| {
+ list.iter()
+ .filter_map(|o| o.recurrence_id.map(|r| r.timestamp()))
+ .collect()
+ })
+ .unwrap_or_default();
+ let recurring = master.is_recurring() || !replaced.is_empty();
+ let excluded = Excluded::new(master);
+ let skip = |wall: NaiveDateTime, start: DateTime| {
+ replaced.contains(&start.timestamp()) || excluded.contains(wall, start)
+ };
+ let cap = opts.max_instances_per_series.min(room);
+ for (wall, start) in occurrences(master, &window, cap, &skip, &mut budget) {
+ let end = master.end_for(wall, start);
+ let original = recurring.then_some(start);
+ out.push(builder.build(master, start, end, original));
+ }
+ }
+ let cancelled_series: HashSet<&str> = cal
+ .events
+ .iter()
+ .filter(|e| e.recurrence_id.is_none() && !keep(e.status))
+ .map(|e| e.uid.as_str())
+ .collect();
+ 'overrides: for (uid, list) in overrides {
+ if cancelled_series.contains(uid) {
+ continue;
+ }
+ for event in list {
+ if out.len() >= opts.max_events {
+ break 'overrides;
+ }
+ if !keep(event.status) {
+ continue;
+ }
+ let start = event.start_utc();
+ let end = event.end_for(event.start_wall, start);
+ if overlaps(start, end) {
+ out.push(builder.build(event, start, end, event.recurrence_id));
+ }
+ }
+ }
+ out.sort_by(|a, b| a.start.cmp(&b.start).then_with(|| a.id.cmp(&b.id)));
+ out.truncate(opts.max_events);
+ let mut seen: HashMap = HashMap::new();
+ for event in &mut out {
+ let count = seen.entry(event.id.clone()).or_insert(0);
+ *count += 1;
+ if *count > 1 {
+ event.id = format!("{}#{}", event.id, count);
+ }
+ }
+ out
+}
+
+struct Excluded {
+ instants: HashSet>,
+ days: HashSet,
+}
+
+impl Excluded {
+ fn new(event: &RawEvent) -> Self {
+ let mut instants = HashSet::new();
+ let mut days = HashSet::new();
+ for ex in &event.exdates {
+ match ex {
+ Exclusion::Instant(i) => {
+ instants.insert(*i);
+ }
+ Exclusion::Day(d) => {
+ days.insert(*d);
+ }
+ }
+ }
+ Self { instants, days }
+ }
+
+ fn contains(&self, wall: NaiveDateTime, start: DateTime) -> bool {
+ self.instants.contains(&start) || self.days.contains(&wall.date())
+ }
+}
+
+fn occurrences(
+ event: &RawEvent,
+ window: &Range>,
+ cap: usize,
+ skip: &impl Fn(NaiveDateTime, DateTime) -> bool,
+ budget: &mut Budget,
+) -> Vec<(NaiveDateTime, DateTime)> {
+ let wanted = |wall: NaiveDateTime, utc: DateTime| {
+ !skip(wall, utc) && utc < window.end && event.end_for(wall, utc) > window.start
+ };
+ let start = event.start_utc();
+ let mut found = Vec::new();
+ if wanted(event.start_wall, start) {
+ found.push((event.start_wall, start));
+ }
+ if let Some(rule) = &event.rule {
+ let margin = Duration::days(2);
+ let wall_end = event
+ .zone
+ .from_utc(window.end)
+ .checked_add_signed(margin)
+ .unwrap_or(NaiveDateTime::MAX);
+ let anchor = event
+ .zone
+ .from_utc(window.start)
+ .checked_sub_signed(event.span.upper_bound())
+ .and_then(|a| a.checked_sub_signed(margin))
+ .unwrap_or(event.start_wall);
+ let mut in_window = 0usize;
+ for wall in rule.walls(event.start_wall, anchor, budget) {
+ if wall > wall_end || in_window >= cap {
+ break;
+ }
+ let utc = event.zone.to_utc(wall);
+ if utc == start || !wanted(wall, utc) {
+ continue;
+ }
+ in_window += 1;
+ found.push((wall, utc));
+ }
+ }
+ found.extend(
+ event
+ .rdates
+ .iter()
+ .map(|r| (event.zone.from_utc(*r), *r))
+ .filter(|(wall, utc)| wanted(*wall, *utc)),
+ );
+ found.sort_by_key(|(_, utc)| *utc);
+ found.dedup_by_key(|(_, utc)| *utc);
+ found.truncate(cap);
+ found
+}
+
+fn occurrence_key(start: DateTime, all_day: bool) -> String {
+ if all_day {
+ start.format("%Y%m%d").to_string()
+ } else {
+ start.format("%Y%m%dT%H%M%SZ").to_string()
+ }
+}
+
+struct Builder<'a> {
+ calendar_id: &'a str,
+ self_emails: &'a [String],
+}
+
+impl Builder<'_> {
+ fn person(&self, raw: &RawPerson) -> Person {
+ Person {
+ name: raw.name.clone(),
+ email: raw.email.clone(),
+ is_self: is_self_email(raw.email.as_deref(), self.self_emails),
+ response: raw.response,
+ }
+ }
+
+ fn build(
+ &self,
+ raw: &RawEvent,
+ start: DateTime,
+ end: DateTime,
+ original: Option>,
+ ) -> CalendarEvent {
+ let organizer = raw.organizer.as_ref().map(|o| self.person(o));
+ let mut attendees: Vec = Vec::with_capacity(raw.attendees.len());
+ for person in raw.attendees.iter().map(|a| self.person(a)) {
+ let duplicate = person.email.as_deref().is_some_and(|email| {
+ attendees.iter().any(|p| {
+ p.email
+ .as_deref()
+ .is_some_and(|e| e.eq_ignore_ascii_case(email))
+ })
+ });
+ if !duplicate {
+ attendees.push(person);
+ }
+ }
+ let self_response = derive_self_response(organizer.as_ref(), &attendees, Response::Unknown);
+ let link = event_meeting_link(
+ &raw.conference,
+ raw.location.as_deref(),
+ raw.description.as_deref(),
+ None,
+ )
+ .or_else(|| raw.alt_description.as_deref().and_then(find_meeting_link))
+ .or_else(|| raw.url.as_deref().and_then(classify_url));
+ let description = raw.description.clone().or_else(|| {
+ raw.alt_description
+ .as_deref()
+ .map(html_to_text)
+ .filter(|d| !d.trim().is_empty())
+ });
+ let id = match original {
+ Some(original) => format!("{}_{}", raw.uid, occurrence_key(original, raw.all_day)),
+ None => raw.uid.clone(),
+ };
+ CalendarEvent {
+ id,
+ series_id: original.map(|_| raw.uid.clone()),
+ calendar_id: self.calendar_id.to_string(),
+ source: SourceKind::Ics,
+ title: raw.title.clone(),
+ start,
+ end,
+ all_day: raw.all_day,
+ location: raw.location.clone(),
+ description,
+ organizer,
+ attendees,
+ self_response,
+ link,
+ status: raw.status,
+ web_url: raw
+ .url
+ .clone()
+ .filter(|u| u.starts_with("https://") || u.starts_with("http://")),
+ free: raw.free,
+ }
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/lexer.rs b/apps/desktop-gpui/calendar/src/ics/lexer.rs
new file mode 100644
index 00000000000..5eb366abc0a
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/lexer.rs
@@ -0,0 +1,283 @@
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct Property {
+ pub name: String,
+ pub params: Vec<(String, Vec)>,
+ pub value: String,
+}
+
+impl Property {
+ pub fn param(&self, name: &str) -> Option<&str> {
+ self.params
+ .iter()
+ .find(|(k, _)| k == name)
+ .and_then(|(_, v)| v.first())
+ .map(String::as_str)
+ }
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub(crate) struct Component {
+ pub name: String,
+ pub props: Vec,
+ pub children: Vec,
+}
+
+impl Component {
+ pub fn prop(&self, name: &str) -> Option<&Property> {
+ self.props.iter().find(|p| p.name == name)
+ }
+
+ pub fn props_named<'a>(&'a self, name: &'a str) -> impl Iterator
- + 'a {
+ self.props.iter().filter(move |p| p.name == name)
+ }
+
+ pub fn text(&self, name: &str) -> Option {
+ self.prop(name).map(|p| unescape_text(&p.value))
+ }
+}
+
+pub(crate) struct Lexed {
+ pub root: Component,
+ pub warnings: Vec,
+}
+
+const MAX_DEPTH: usize = 16;
+
+pub(crate) fn unfold(text: &str) -> Vec {
+ let text = text.strip_prefix('\u{feff}').unwrap_or(text);
+ let mut lines: Vec = Vec::new();
+ for raw in text.split('\n') {
+ let line = raw.strip_suffix('\r').unwrap_or(raw);
+ if let Some(rest) = line.strip_prefix([' ', '\t']) {
+ if let Some(last) = lines.last_mut() {
+ last.push_str(rest);
+ continue;
+ }
+ if rest.trim().is_empty() {
+ continue;
+ }
+ lines.push(rest.to_string());
+ continue;
+ }
+ if line.is_empty() {
+ continue;
+ }
+ lines.push(line.to_string());
+ }
+ lines
+}
+
+pub(crate) fn parse_content_line(line: &str) -> Option {
+ let mut name_end = None;
+ for (i, c) in line.char_indices() {
+ if c == ';' || c == ':' {
+ name_end = Some(i);
+ break;
+ }
+ }
+ let name_end = name_end?;
+ let name = line[..name_end].trim().to_ascii_uppercase();
+ if name.is_empty() {
+ return None;
+ }
+ let mut params = Vec::new();
+ let mut rest = &line[name_end..];
+ while let Some(after) = rest.strip_prefix(';') {
+ let eq = after.find(['=', ':', ';'])?;
+ if after.as_bytes()[eq] != b'=' {
+ rest = &after[eq..];
+ continue;
+ }
+ let key = after[..eq].trim().to_ascii_uppercase();
+ let mut values = Vec::new();
+ let mut cursor = &after[eq + 1..];
+ loop {
+ if let Some(quoted) = cursor.strip_prefix('"') {
+ let close = quoted.find('"').unwrap_or(quoted.len());
+ values.push(quoted[..close].to_string());
+ cursor = quoted.get(close + 1..).unwrap_or("");
+ } else {
+ let end = cursor.find([',', ';', ':']).unwrap_or(cursor.len());
+ values.push(cursor[..end].to_string());
+ cursor = &cursor[end..];
+ }
+ match cursor.strip_prefix(',') {
+ Some(next) => cursor = next,
+ None => break,
+ }
+ }
+ params.push((key, values));
+ rest = cursor;
+ if !rest.starts_with(';') && !rest.starts_with(':') {
+ let skip = rest.find([';', ':'])?;
+ rest = &rest[skip..];
+ }
+ }
+ let value = rest.strip_prefix(':')?;
+ Some(Property {
+ name,
+ params,
+ value: value.to_string(),
+ })
+}
+
+pub(crate) fn lex(text: &str) -> Lexed {
+ let mut warnings = Vec::new();
+ let mut stack: Vec = vec![Component {
+ name: "ROOT".to_string(),
+ ..Component::default()
+ }];
+ for line in unfold(text) {
+ let Some(prop) = parse_content_line(&line) else {
+ warnings.push(format!("unparseable line: {}", truncate(&line)));
+ continue;
+ };
+ match prop.name.as_str() {
+ "BEGIN" => {
+ let name = prop.value.trim().to_ascii_uppercase();
+ if stack.len() > MAX_DEPTH {
+ warnings.push(format!("component nesting too deep at {name}"));
+ continue;
+ }
+ stack.push(Component {
+ name,
+ ..Component::default()
+ });
+ }
+ "END" => {
+ let name = prop.value.trim().to_ascii_uppercase();
+ let Some(pos) = stack.iter().skip(1).rposition(|c| c.name == name) else {
+ warnings.push(format!("END:{name} without BEGIN"));
+ continue;
+ };
+ let target = pos + 1;
+ while stack.len() > target {
+ let Some(done) = stack.pop() else { break };
+ if stack.len() > target {
+ warnings.push(format!("component {} not closed", done.name));
+ }
+ if let Some(parent) = stack.last_mut() {
+ parent.children.push(done);
+ }
+ }
+ }
+ _ => {
+ if let Some(current) = stack.last_mut() {
+ current.props.push(prop);
+ }
+ }
+ }
+ }
+ while stack.len() > 1 {
+ let Some(done) = stack.pop() else { break };
+ warnings.push(format!(
+ "component {} not closed at end of input",
+ done.name
+ ));
+ if let Some(parent) = stack.last_mut() {
+ parent.children.push(done);
+ }
+ }
+ let root = stack.pop().unwrap_or_default();
+ Lexed { root, warnings }
+}
+
+fn truncate(line: &str) -> String {
+ line.chars().take(60).collect()
+}
+
+pub(crate) fn unescape_text(value: &str) -> String {
+ let mut out = String::with_capacity(value.len());
+ let mut chars = value.chars();
+ while let Some(c) = chars.next() {
+ if c != '\\' {
+ out.push(c);
+ continue;
+ }
+ match chars.next() {
+ Some('n' | 'N') => out.push('\n'),
+ Some(',') => out.push(','),
+ Some(';') => out.push(';'),
+ Some('\\') => out.push('\\'),
+ Some(':') => out.push(':'),
+ Some(other) => {
+ out.push('\\');
+ out.push(other);
+ }
+ None => out.push('\\'),
+ }
+ }
+ out
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn unfolds_crlf_lf_space_and_tab() {
+ let text =
+ "BEGIN:VEVENT\r\nSUMMARY:Quarterly \r\n planning\r\nDESCRIPTION:a\n\tb\nEND:VEVENT\r\n";
+ let lines = unfold(text);
+ assert_eq!(
+ lines,
+ vec![
+ "BEGIN:VEVENT",
+ "SUMMARY:Quarterly planning",
+ "DESCRIPTION:ab",
+ "END:VEVENT"
+ ]
+ );
+ }
+
+ #[test]
+ fn parses_quoted_params_with_separators() {
+ let prop = parse_content_line(
+ "ATTENDEE;CN=\"Doe, Jane: PM\";PARTSTAT=ACCEPTED;DELEGATED-FROM=\"mailto:a@x.com\",\"mailto:b@x.com\":mailto:jane@x.com",
+ )
+ .unwrap();
+ assert_eq!(prop.name, "ATTENDEE");
+ assert_eq!(prop.param("CN"), Some("Doe, Jane: PM"));
+ assert_eq!(prop.param("PARTSTAT"), Some("ACCEPTED"));
+ assert_eq!(
+ prop.params[2].1,
+ vec!["mailto:a@x.com".to_string(), "mailto:b@x.com".to_string()]
+ );
+ assert_eq!(prop.value, "mailto:jane@x.com");
+ }
+
+ #[test]
+ fn value_keeps_colons() {
+ let prop = parse_content_line("URL;VALUE=URI:https://example.com:8443/a?b=c").unwrap();
+ assert_eq!(prop.value, "https://example.com:8443/a?b=c");
+ assert_eq!(prop.param("VALUE"), Some("URI"));
+ }
+
+ #[test]
+ fn rejects_lines_without_value() {
+ assert!(parse_content_line("JUSTTEXT").is_none());
+ assert!(parse_content_line(":value").is_none());
+ assert!(parse_content_line("X;CN=\"unterminated").is_none());
+ }
+
+ #[test]
+ fn unescapes_text() {
+ assert_eq!(
+ unescape_text("Line one\\nLine two\\, with comma\\; semi \\\\ backslash\\N"),
+ "Line one\nLine two, with comma; semi \\ backslash\n"
+ );
+ assert_eq!(unescape_text("trailing\\"), "trailing\\");
+ }
+
+ #[test]
+ fn lex_recovers_from_mismatched_components() {
+ let lexed = lex(
+ "BEGIN:VCALENDAR\nBEGIN:VEVENT\nUID:1\nBEGIN:VALARM\nEND:VEVENT\nEND:BOGUS\nBEGIN:VEVENT\nUID:2\n",
+ );
+ let cal = &lexed.root.children[0];
+ assert_eq!(cal.children.len(), 2);
+ assert_eq!(cal.children[0].prop("UID").unwrap().value, "1");
+ assert_eq!(cal.children[1].prop("UID").unwrap().value, "2");
+ assert!(lexed.warnings.len() >= 3);
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/mod.rs b/apps/desktop-gpui/calendar/src/ics/mod.rs
new file mode 100644
index 00000000000..caf36a84a1d
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/mod.rs
@@ -0,0 +1,584 @@
+mod budget;
+mod expand;
+mod lexer;
+mod rule;
+mod time;
+mod vtimezone;
+
+use std::collections::{HashMap, HashSet};
+
+use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, Utc};
+use chrono_tz::Tz;
+
+use crate::link::{ConferenceEntry, ConferenceKind};
+use crate::model::{EventStatus, Response, response_from_partstat};
+use crate::text::non_empty;
+use crate::tz::{Zone, resolve_tzid};
+
+pub use expand::expand;
+pub use vtimezone::ZoneResolution;
+
+use budget::{Budget, FEED_BUDGET};
+use lexer::{Component, Property, lex, unescape_text};
+use time::{IcsTime, parse_duration_parts, parse_property};
+
+const MAX_VTIMEZONES: usize = 64;
+
+#[derive(Clone, Debug, PartialEq)]
+pub struct ParseOptions {
+ pub calendar_id: String,
+ pub default_zone: Tz,
+ pub default_duration: Duration,
+ pub max_instances_per_series: usize,
+ pub max_events: usize,
+ pub include_cancelled: bool,
+}
+
+impl Default for ParseOptions {
+ fn default() -> Self {
+ Self {
+ calendar_id: String::new(),
+ default_zone: Tz::UTC,
+ default_duration: Duration::minutes(30),
+ max_instances_per_series: 1_000,
+ max_events: 50_000,
+ include_cancelled: false,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ResolvedZone {
+ pub tzid: String,
+ pub zone_name: String,
+ pub how: ZoneResolution,
+}
+
+#[derive(Clone, Debug)]
+pub struct ParsedCalendar {
+ pub name: Option,
+ pub time_zone: Option,
+ pub warnings: usize,
+ pub warning_messages: Vec,
+ pub zones: Vec,
+ pub(crate) events: Vec,
+ pub(crate) options: ParseOptions,
+ pub(crate) budget: Budget,
+}
+
+impl ParsedCalendar {
+ pub fn component_count(&self) -> usize {
+ self.events.len()
+ }
+
+ fn warn(&mut self, message: impl Into) {
+ self.warnings += 1;
+ if self.warning_messages.len() < 32 {
+ self.warning_messages.push(message.into());
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct Span {
+ pub nominal_days: i64,
+ pub exact: Duration,
+}
+
+impl Span {
+ fn days(days: i64) -> Self {
+ Self {
+ nominal_days: days,
+ exact: Duration::zero(),
+ }
+ }
+
+ fn exact(exact: Duration) -> Self {
+ Self {
+ nominal_days: 0,
+ exact,
+ }
+ }
+
+ pub fn upper_bound(&self) -> Duration {
+ Duration::try_days(self.nominal_days.saturating_add(1))
+ .and_then(|d| d.checked_add(&self.exact))
+ .unwrap_or(Duration::MAX)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) enum Exclusion {
+ Instant(DateTime),
+ Day(NaiveDate),
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct RawPerson {
+ pub name: Option,
+ pub email: Option,
+ pub response: Response,
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct RawEvent {
+ pub uid: String,
+ pub title: String,
+ pub description: Option,
+ pub alt_description: Option,
+ pub location: Option,
+ pub url: Option,
+ pub status: EventStatus,
+ pub free: bool,
+ pub start_wall: NaiveDateTime,
+ pub zone: Zone,
+ pub all_day: bool,
+ pub span: Span,
+ pub organizer: Option,
+ pub attendees: Vec,
+ pub rule: Option,
+ pub exdates: Vec,
+ pub rdates: Vec>,
+ pub recurrence_id: Option>,
+ pub conference: Vec,
+}
+
+impl RawEvent {
+ pub fn start_utc(&self) -> DateTime {
+ self.zone.to_utc(self.start_wall)
+ }
+
+ pub fn end_for(&self, start_wall: NaiveDateTime, start_utc: DateTime) -> DateTime {
+ let Span {
+ nominal_days,
+ exact,
+ } = self.span;
+ let nominal = if nominal_days == 0 {
+ start_utc
+ } else {
+ Duration::try_days(nominal_days)
+ .and_then(|d| start_wall.checked_add_signed(d))
+ .map(|w| self.zone.to_utc(w))
+ .unwrap_or(start_utc)
+ };
+ let end = nominal.checked_add_signed(exact).unwrap_or(nominal);
+ if end > start_utc {
+ end
+ } else {
+ Duration::try_days(nominal_days)
+ .and_then(|d| d.checked_add(&exact))
+ .and_then(|d| start_utc.checked_add_signed(d))
+ .unwrap_or(start_utc)
+ .max(start_utc)
+ }
+ }
+
+ pub fn is_recurring(&self) -> bool {
+ self.rule.is_some() || !self.rdates.is_empty() || self.recurrence_id.is_some()
+ }
+}
+
+struct ZoneContext {
+ zones: HashMap,
+ looked_up: HashMap>,
+ floating: Zone,
+}
+
+impl ZoneContext {
+ fn zone_for(&mut self, tzid: &str, cal: &mut ParsedCalendar) -> Zone {
+ if let Some(zone) = self.zones.get(tzid) {
+ return *zone;
+ }
+ let found = match self.looked_up.get(tzid) {
+ Some(found) => *found,
+ None => {
+ let found = resolve_tzid(tzid);
+ self.looked_up.insert(tzid.to_string(), found);
+ found
+ }
+ };
+ if let Some(zone) = found {
+ return zone;
+ }
+ cal.warn(format!("unknown TZID {tzid}, using the default zone"));
+ self.floating
+ }
+
+ fn wall_and_zone(&mut self, time: &IcsTime, cal: &mut ParsedCalendar) -> (NaiveDateTime, Zone) {
+ match time {
+ IcsTime::Date(d) => (d.and_time(NaiveTime::MIN), Zone::Utc),
+ IcsTime::Utc(n) => (*n, Zone::Utc),
+ IcsTime::Floating(n) => (*n, self.floating),
+ IcsTime::Zoned(n, tzid) => (*n, self.zone_for(tzid, cal)),
+ }
+ }
+
+ fn instant(&mut self, time: &IcsTime, cal: &mut ParsedCalendar) -> DateTime {
+ let (wall, zone) = self.wall_and_zone(time, cal);
+ zone.to_utc(wall)
+ }
+}
+
+pub fn parse_calendar(text: &str, opts: &ParseOptions) -> ParsedCalendar {
+ let lexed = lex(text);
+ let mut cal = ParsedCalendar {
+ name: None,
+ time_zone: None,
+ warnings: 0,
+ warning_messages: Vec::new(),
+ zones: Vec::new(),
+ events: Vec::new(),
+ options: opts.clone(),
+ budget: Budget::new(FEED_BUDGET),
+ };
+ for w in lexed.warnings {
+ cal.warn(w);
+ }
+ let calendars: Vec<&Component> = if lexed.root.children.iter().any(|c| c.name == "VCALENDAR") {
+ lexed
+ .root
+ .children
+ .iter()
+ .filter(|c| c.name == "VCALENDAR")
+ .collect()
+ } else {
+ if !lexed.root.children.is_empty() {
+ cal.warn("no VCALENDAR wrapper");
+ }
+ vec![&lexed.root]
+ };
+ for vcal in calendars {
+ parse_vcalendar(vcal, &mut cal);
+ }
+ cal
+}
+
+pub fn parse_calendar_bytes(bytes: &[u8], opts: &ParseOptions) -> ParsedCalendar {
+ let bytes = bytes.strip_prefix(b"\xef\xbb\xbf").unwrap_or(bytes);
+ let mut joined = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ let fold = match (bytes[i], bytes.get(i + 1), bytes.get(i + 2)) {
+ (b'\r', Some(b'\n'), Some(b' ' | b'\t')) => 3,
+ (b'\n', Some(b' ' | b'\t'), _) => 2,
+ _ => 0,
+ };
+ if fold > 0 {
+ i += fold;
+ continue;
+ }
+ joined.push(bytes[i]);
+ i += 1;
+ }
+ parse_calendar(&String::from_utf8_lossy(&joined), opts)
+}
+
+fn parse_vcalendar(vcal: &Component, cal: &mut ParsedCalendar) {
+ if cal.name.is_none() {
+ cal.name = vcal
+ .text("X-WR-CALNAME")
+ .or_else(|| vcal.text("NAME"))
+ .and_then(|n| non_empty(Some(&n)));
+ }
+ let wr_tz = vcal
+ .prop("X-WR-TIMEZONE")
+ .map(|p| p.value.trim().to_string());
+ if cal.time_zone.is_none() {
+ cal.time_zone = wr_tz.clone().filter(|t| !t.is_empty());
+ }
+ let default_zone = Zone::Named(cal.options.default_zone);
+ let floating = match wr_tz.as_deref().filter(|t| !t.is_empty()) {
+ Some(tz) => resolve_tzid(tz).unwrap_or_else(|| {
+ cal.warn(format!("unknown X-WR-TIMEZONE {tz}"));
+ default_zone
+ }),
+ None => default_zone,
+ };
+ let mut ctx = ZoneContext {
+ zones: HashMap::new(),
+ looked_up: HashMap::new(),
+ floating,
+ };
+ let mut seen_tzids: HashSet = HashSet::new();
+ for (index, comp) in vcal
+ .children
+ .iter()
+ .filter(|c| c.name == "VTIMEZONE")
+ .enumerate()
+ {
+ if index >= MAX_VTIMEZONES {
+ cal.warn("too many VTIMEZONE blocks, ignoring the rest");
+ break;
+ }
+ let tzid = comp
+ .prop("TZID")
+ .map(|p| p.value.trim().to_string())
+ .unwrap_or_default();
+ if !tzid.is_empty() && !seen_tzids.insert(tzid.clone()) {
+ cal.warn(format!("duplicate VTIMEZONE {tzid}"));
+ continue;
+ }
+ match vtimezone::resolve_vtimezone(comp, &mut cal.budget) {
+ Some((tzid, zone, how)) => {
+ let zone_name = match zone {
+ Zone::Utc => "UTC".to_string(),
+ Zone::Named(tz) => tz.name().to_string(),
+ Zone::Fixed(offset) => offset.to_string(),
+ };
+ cal.zones.push(ResolvedZone {
+ tzid: tzid.clone(),
+ zone_name,
+ how,
+ });
+ ctx.zones.insert(tzid, zone);
+ }
+ None => cal.warn("VTIMEZONE without usable TZID or offsets"),
+ }
+ }
+ for comp in vcal.children.iter().filter(|c| c.name == "VEVENT") {
+ if cal.events.len() >= cal.options.max_events {
+ cal.warn("event limit reached, ignoring the rest of the feed");
+ break;
+ }
+ match parse_event(comp, &mut ctx, cal) {
+ Ok(event) => cal.events.push(event),
+ Err(message) => cal.warn(message),
+ }
+ }
+}
+
+fn first_time(prop: &Property) -> Option {
+ parse_property(prop).into_iter().next()
+}
+
+fn parse_person(prop: &Property) -> RawPerson {
+ let value = prop.value.trim();
+ let email = prop
+ .param("EMAIL")
+ .map(str::to_string)
+ .or_else(|| {
+ let lower = value.to_ascii_lowercase();
+ lower
+ .starts_with("mailto:")
+ .then(|| value["mailto:".len()..].to_string())
+ .or_else(|| {
+ (value.contains('@') && !value.contains(':')).then(|| value.to_string())
+ })
+ })
+ .map(|e| e.trim().to_string())
+ .filter(|e| e.contains('@'));
+ RawPerson {
+ name: non_empty(prop.param("CN")),
+ email,
+ response: prop
+ .param("PARTSTAT")
+ .map_or(Response::Unknown, response_from_partstat),
+ }
+}
+
+fn is_resource(prop: &Property) -> bool {
+ prop.param("CUTYPE")
+ .is_some_and(|c| c.eq_ignore_ascii_case("ROOM") || c.eq_ignore_ascii_case("RESOURCE"))
+ || prop
+ .param("ROLE")
+ .is_some_and(|r| r.eq_ignore_ascii_case("NON-PARTICIPANT"))
+}
+
+fn conference_entries(comp: &Component) -> Vec {
+ let mut out = Vec::new();
+ for name in [
+ "X-GOOGLE-CONFERENCE",
+ "X-MICROSOFT-SKYPETEAMSMEETINGURL",
+ "X-MICROSOFT-ONLINEMEETINGEXTERNALLINK",
+ "X-MICROSOFT-ONLINEMEETINGCONFLINK",
+ "CONFERENCE",
+ ] {
+ for prop in comp.props_named(name) {
+ let uri = unescape_text(prop.value.trim());
+ let lower = uri.to_ascii_lowercase();
+ if !(lower.starts_with("https://") || lower.starts_with("http://")) {
+ continue;
+ }
+ let is_video = name != "CONFERENCE"
+ || prop
+ .param("FEATURE")
+ .is_none_or(|f| f.to_ascii_uppercase().contains("VIDEO"));
+ out.push(ConferenceEntry {
+ kind: if is_video {
+ ConferenceKind::Video
+ } else {
+ ConferenceKind::Other
+ },
+ uri,
+ meeting_code: None,
+ });
+ }
+ }
+ out
+}
+
+fn parse_event(
+ comp: &Component,
+ ctx: &mut ZoneContext,
+ cal: &mut ParsedCalendar,
+) -> Result {
+ let start_time = comp
+ .prop("DTSTART")
+ .and_then(first_time)
+ .ok_or_else(|| "VEVENT without a valid DTSTART".to_string())?;
+ let alldayish = comp
+ .prop("X-MICROSOFT-CDO-ALLDAYEVENT")
+ .is_some_and(|p| p.value.trim().eq_ignore_ascii_case("TRUE"));
+ let start_time = match start_time {
+ IcsTime::Floating(n) | IcsTime::Zoned(n, _) if alldayish && n.time() == NaiveTime::MIN => {
+ IcsTime::Date(n.date())
+ }
+ other => other,
+ };
+ let all_day = matches!(start_time, IcsTime::Date(_));
+ let (start_wall, zone) = ctx.wall_and_zone(&start_time, cal);
+ let start_utc = zone.to_utc(start_wall);
+ let default_span = if all_day {
+ Span::days(1)
+ } else {
+ Span::exact(cal.options.default_duration)
+ };
+ let span = if let Some(end_time) = comp.prop("DTEND").and_then(first_time) {
+ let (end_wall, end_zone) = ctx.wall_and_zone(&end_time, cal);
+ if all_day {
+ let days = end_wall
+ .date()
+ .signed_duration_since(start_wall.date())
+ .num_days();
+ if days > 0 {
+ Span::days(days)
+ } else {
+ default_span
+ }
+ } else {
+ let mut exact = end_zone.to_utc(end_wall).signed_duration_since(start_utc);
+ if exact <= Duration::zero() && end_zone == zone {
+ exact = end_wall.signed_duration_since(start_wall);
+ }
+ if exact > Duration::zero() {
+ Span::exact(exact)
+ } else {
+ default_span
+ }
+ }
+ } else if let Some((days, seconds)) = comp
+ .prop("DURATION")
+ .and_then(|p| parse_duration_parts(&p.value))
+ {
+ if days.saturating_mul(86_400).saturating_add(seconds) <= 0 {
+ default_span
+ } else if all_day {
+ Span::days(days.saturating_add(seconds / 86_400).max(1))
+ } else {
+ Span {
+ nominal_days: days,
+ exact: Duration::seconds(seconds),
+ }
+ }
+ } else {
+ default_span
+ };
+
+ let title = comp
+ .text("SUMMARY")
+ .map(|s| s.trim().to_string())
+ .unwrap_or_default();
+ let uid = comp
+ .text("UID")
+ .map(|u| u.trim().to_string())
+ .filter(|u| !u.is_empty())
+ .unwrap_or_else(|| synthetic_uid(&title, start_utc));
+
+ let status = match comp
+ .prop("STATUS")
+ .map(|p| p.value.trim().to_ascii_uppercase())
+ .as_deref()
+ {
+ Some("CANCELLED") => EventStatus::Cancelled,
+ Some("TENTATIVE") => EventStatus::Tentative,
+ _ => EventStatus::Confirmed,
+ };
+ let free = comp
+ .prop("TRANSP")
+ .is_some_and(|p| p.value.trim().eq_ignore_ascii_case("TRANSPARENT"))
+ || comp
+ .prop("X-MICROSOFT-CDO-BUSYSTATUS")
+ .is_some_and(|p| p.value.trim().eq_ignore_ascii_case("FREE"));
+
+ let rule = match comp.prop("RRULE") {
+ Some(prop) => match rule::build_rule(&prop.value, start_wall, zone) {
+ Ok(rule) => Some(rule),
+ Err(e) => {
+ cal.warn(format!("{uid}: ignoring RRULE ({e})"));
+ None
+ }
+ },
+ None => None,
+ };
+
+ let mut exdates = Vec::new();
+ for time in comp.props_named("EXDATE").flat_map(parse_property) {
+ match time {
+ IcsTime::Date(d) => exdates.push(Exclusion::Day(d)),
+ other => exdates.push(Exclusion::Instant(ctx.instant(&other, cal))),
+ }
+ }
+ let mut rdates = Vec::new();
+ for time in comp.props_named("RDATE").flat_map(parse_property) {
+ let instant = match time {
+ IcsTime::Date(d) if !all_day => zone.to_utc(d.and_time(start_wall.time())),
+ other => ctx.instant(&other, cal),
+ };
+ rdates.push(instant);
+ }
+ let recurrence_id = comp
+ .prop("RECURRENCE-ID")
+ .and_then(first_time)
+ .map(|t| match t {
+ IcsTime::Date(d) if !all_day => zone.to_utc(d.and_time(start_wall.time())),
+ other => ctx.instant(&other, cal),
+ });
+
+ let organizer = comp.prop("ORGANIZER").map(parse_person);
+ let attendees = comp
+ .props_named("ATTENDEE")
+ .filter(|p| !is_resource(p))
+ .map(parse_person)
+ .collect();
+
+ Ok(RawEvent {
+ uid,
+ title,
+ description: comp.text("DESCRIPTION").and_then(|d| non_empty(Some(&d))),
+ alt_description: comp.prop("X-ALT-DESC").map(|p| unescape_text(&p.value)),
+ location: comp.text("LOCATION").and_then(|l| non_empty(Some(&l))),
+ url: comp.text("URL").and_then(|u| non_empty(Some(&u))),
+ status,
+ free,
+ start_wall,
+ zone,
+ all_day,
+ span,
+ organizer,
+ attendees,
+ rule,
+ exdates,
+ rdates,
+ recurrence_id,
+ conference: conference_entries(comp),
+ })
+}
+
+fn synthetic_uid(title: &str, start: DateTime) -> String {
+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
+ for byte in title.bytes() {
+ hash ^= u64::from(byte);
+ hash = hash.wrapping_mul(0x0100_0000_01b3);
+ }
+ format!("generated-{hash:016x}-{}", start.timestamp())
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/rule.rs b/apps/desktop-gpui/calendar/src/ics/rule.rs
new file mode 100644
index 00000000000..18d80edb294
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/rule.rs
@@ -0,0 +1,528 @@
+use chrono::{
+ Datelike, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Weekday,
+};
+use rrule::{Frequency, RRule, RRuleSet, RRuleSetIter, Unvalidated};
+
+use super::budget::Budget;
+use super::time::{IcsTime, parse_one};
+use crate::tz::Zone;
+
+const RRULE_LOOP_LIMIT: u64 = 100_000;
+const RRULE_MAX_YEAR: i32 = 10_000;
+const MAX_TIMES_PER_DAY: usize = 96;
+const YIELD_COST: u64 = 8;
+
+const KNOWN_PARTS: [&str; 13] = [
+ "FREQ",
+ "INTERVAL",
+ "COUNT",
+ "BYSECOND",
+ "BYMINUTE",
+ "BYHOUR",
+ "BYDAY",
+ "BYMONTHDAY",
+ "BYYEARDAY",
+ "BYWEEKNO",
+ "BYMONTH",
+ "BYSETPOS",
+ "WKST",
+];
+
+fn as_wall(dt: NaiveDateTime) -> chrono::DateTime {
+ rrule::Tz::UTC.from_utc_datetime(&dt)
+}
+
+#[derive(Clone, Debug)]
+pub(crate) struct Recurrence {
+ rule: RRule,
+ until: Option,
+ count: Option,
+ freq: Frequency,
+ interval: i64,
+ week_start: Weekday,
+ period_cost: u64,
+}
+
+impl Recurrence {
+ fn period_index(&self, wall: NaiveDateTime) -> i64 {
+ match self.freq {
+ Frequency::Yearly => i64::from(wall.year()),
+ Frequency::Monthly => i64::from(wall.year()) * 12 + i64::from(wall.month0()),
+ Frequency::Weekly => week_start_of(wall.date(), self.week_start)
+ .num_days_from_ce()
+ .div_euclid(7)
+ .into(),
+ Frequency::Daily => wall.date().num_days_from_ce().into(),
+ _ => i64::from(wall.date().num_days_from_ce()) * 24 + i64::from(wall.time().hour()),
+ }
+ }
+
+ fn period_start(&self, index: i64) -> Option {
+ let midnight = |date: NaiveDate| date.and_time(NaiveTime::MIN);
+ match self.freq {
+ Frequency::Yearly => {
+ NaiveDate::from_ymd_opt(i32::try_from(index).ok()?, 1, 1).map(midnight)
+ }
+ Frequency::Monthly => {
+ let year = i32::try_from(index.div_euclid(12)).ok()?;
+ let month = u32::try_from(index.rem_euclid(12) + 1).ok()?;
+ NaiveDate::from_ymd_opt(year, month, 1).map(midnight)
+ }
+ Frequency::Weekly => {
+ let last_day = index.checked_mul(7)?.checked_add(6)?;
+ NaiveDate::from_num_days_from_ce_opt(i32::try_from(last_day).ok()?)
+ .map(|d| midnight(week_start_of(d, self.week_start)))
+ }
+ Frequency::Daily => {
+ NaiveDate::from_num_days_from_ce_opt(i32::try_from(index).ok()?).map(midnight)
+ }
+ _ => {
+ let day = i32::try_from(index.div_euclid(24)).ok()?;
+ let hour = u32::try_from(index.rem_euclid(24)).ok()?;
+ NaiveDate::from_num_days_from_ce_opt(day)?.and_hms_opt(hour, 0, 0)
+ }
+ }
+ }
+
+ fn periods_between(&self, from: NaiveDateTime, to: NaiveDateTime) -> u64 {
+ let steps = (self.period_index(to) - self.period_index(from)).max(0) / self.interval;
+ u64::try_from(steps).unwrap_or(0).max(1)
+ }
+
+ fn worst_call(&self, position: NaiveDateTime) -> u64 {
+ let loops = match self.freq {
+ Frequency::Yearly => {
+ let years = i64::from(RRULE_MAX_YEAR - position.year()).max(0) / self.interval;
+ u64::try_from(years + 1).unwrap_or(1).min(RRULE_LOOP_LIMIT)
+ }
+ _ => RRULE_LOOP_LIMIT,
+ };
+ loops.saturating_mul(self.period_cost)
+ }
+
+ fn fast_forward(&self, dtstart_wall: NaiveDateTime, anchor: NaiveDateTime) -> NaiveDateTime {
+ if self.count.is_some() || anchor <= dtstart_wall {
+ return dtstart_wall;
+ }
+ let first = self.period_index(dtstart_wall);
+ let skip = (self.period_index(anchor) - first).div_euclid(self.interval);
+ if skip < 1 {
+ return dtstart_wall;
+ }
+ skip.checked_mul(self.interval)
+ .and_then(|offset| first.checked_add(offset))
+ .and_then(|index| self.period_start(index))
+ .filter(|start| *start > dtstart_wall && *start <= anchor)
+ .unwrap_or(dtstart_wall)
+ }
+
+ pub fn walls<'a>(
+ &'a self,
+ dtstart_wall: NaiveDateTime,
+ anchor: NaiveDateTime,
+ budget: &'a mut Budget,
+ ) -> Walls<'a> {
+ let start = self.fast_forward(dtstart_wall, anchor);
+ let set = RRuleSet::new(as_wall(start))
+ .rrule(self.rule.clone())
+ .limit();
+ Walls {
+ iter: (&set).into_iter(),
+ rec: self,
+ budget,
+ position: start,
+ yielded: 0,
+ done: false,
+ }
+ }
+}
+
+fn week_start_of(date: NaiveDate, week_start: Weekday) -> NaiveDate {
+ let back = (7 + date.weekday().num_days_from_monday() - week_start.num_days_from_monday()) % 7;
+ date.checked_sub_signed(Duration::days(i64::from(back)))
+ .unwrap_or(date)
+}
+
+pub(crate) struct Walls<'a> {
+ iter: RRuleSetIter,
+ rec: &'a Recurrence,
+ budget: &'a mut Budget,
+ position: NaiveDateTime,
+ yielded: u32,
+ done: bool,
+}
+
+impl Iterator for Walls<'_> {
+ type Item = NaiveDateTime;
+
+ fn next(&mut self) -> Option {
+ if self.done {
+ return None;
+ }
+ // rrule scans up to 100,000 empty periods inside one call, so a call is only made when
+ // the budget could pay for that scan; the real cost is charged once the result is known.
+ if !self.budget.can_afford(self.rec.worst_call(self.position)) {
+ self.budget.charge(u64::MAX);
+ self.done = true;
+ return None;
+ }
+ let Some(next) = self.iter.next().map(|dt| dt.naive_utc()) else {
+ let finished_by_count = self.rec.count.is_some_and(|c| self.yielded >= c);
+ self.budget.charge(if finished_by_count {
+ 1
+ } else {
+ self.rec.worst_call(self.position)
+ });
+ self.done = true;
+ return None;
+ };
+ let periods = self.rec.periods_between(self.position, next);
+ self.budget.charge(
+ periods
+ .saturating_mul(self.rec.period_cost)
+ .saturating_add(YIELD_COST),
+ );
+ self.position = next;
+ self.yielded = self.yielded.saturating_add(1);
+ if self.rec.until.is_some_and(|until| next > until) {
+ self.done = true;
+ return None;
+ }
+ Some(next)
+ }
+}
+
+fn times_per_day(rule: &RRule) -> usize {
+ let minutes_seconds = rule.get_by_minute().len().max(1) * rule.get_by_second().len().max(1);
+ match rule.get_freq() {
+ Frequency::Hourly => {
+ let interval = usize::from(rule.get_interval().max(1));
+ let hours = if rule.get_by_hour().is_empty() {
+ 24usize.div_ceil(interval)
+ } else {
+ rule.get_by_hour().len().min(24usize.div_ceil(interval))
+ };
+ hours * minutes_seconds
+ }
+ _ => rule.get_by_hour().len().max(1) * minutes_seconds,
+ }
+}
+
+fn period_cost(freq: Frequency, times_per_day: usize) -> u64 {
+ let (base, days) = match freq {
+ Frequency::Yearly => (16, 366),
+ Frequency::Monthly => (2, 31),
+ Frequency::Weekly => (1, 7),
+ Frequency::Hourly => (2, 1),
+ _ => (1, 1),
+ };
+ base + days * times_per_day as u64 / 32
+}
+
+pub(crate) fn build_rule(
+ value: &str,
+ dtstart_wall: NaiveDateTime,
+ zone: Zone,
+) -> Result {
+ // rrule 0.14 slices BYDAY values by byte offset and panics on non-ASCII input.
+ if !value.is_ascii() {
+ return Err("RRULE contains non-ASCII characters".to_string());
+ }
+ let mut parts: Vec = Vec::new();
+ let mut until = None;
+ let mut has_freq = false;
+ for part in value.split(';') {
+ let Some((key, val)) = part.split_once('=') else {
+ continue;
+ };
+ let key = key.trim().to_ascii_uppercase();
+ let val = val.trim().to_ascii_uppercase();
+ if val.is_empty() {
+ continue;
+ }
+ if key == "UNTIL" {
+ until = Some(val);
+ continue;
+ }
+ if !KNOWN_PARTS.contains(&key.as_str())
+ || parts
+ .iter()
+ .any(|p| p.split('=').next() == Some(key.as_str()))
+ {
+ continue;
+ }
+ if key == "FREQ" {
+ if val == "MINUTELY" || val == "SECONDLY" {
+ return Err(format!("FREQ={val} is not a meeting cadence"));
+ }
+ has_freq = true;
+ }
+ if key == "INTERVAL" && val.parse::().is_ok_and(|n| n == 0) {
+ continue;
+ }
+ if key == "COUNT" && val.parse::().is_ok_and(|n| n == 0) {
+ return Err("COUNT=0".to_string());
+ }
+ parts.push(format!("{key}={val}"));
+ }
+ if !has_freq {
+ return Err(format!("RRULE without FREQ: {value}"));
+ }
+ let rule: RRule = parts
+ .join(";")
+ .parse()
+ .map_err(|e: rrule::RRuleError| e.to_string())?;
+ let until = match until {
+ Some(until) => {
+ let wall = match parse_one(&until, None, false) {
+ Some(IcsTime::Date(date)) => {
+ date.and_time(NaiveTime::from_hms_opt(23, 59, 59).unwrap_or_default())
+ }
+ Some(IcsTime::Utc(naive)) => zone.from_utc(naive.and_utc()),
+ Some(IcsTime::Floating(naive) | IcsTime::Zoned(naive, _)) => naive,
+ None => return Err(format!("bad UNTIL: {until}")),
+ };
+ if wall < dtstart_wall {
+ return Err("UNTIL before DTSTART".to_string());
+ }
+ Some(wall)
+ }
+ None => None,
+ };
+ let rule = rule
+ .validate(as_wall(dtstart_wall))
+ .map_err(|e| e.to_string())?;
+ let times = times_per_day(&rule);
+ if times > MAX_TIMES_PER_DAY {
+ return Err(format!(
+ "{times} occurrences a day is not a meeting cadence"
+ ));
+ }
+ let freq = rule.get_freq();
+ Ok(Recurrence {
+ count: rule.get_count(),
+ interval: i64::from(rule.get_interval().max(1)),
+ week_start: rule.get_week_start(),
+ period_cost: period_cost(freq, times),
+ freq,
+ until,
+ rule,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ics::budget::FEED_BUDGET;
+
+ fn wall(y: i32, m: u32, d: u32, h: u32) -> NaiveDateTime {
+ NaiveDate::from_ymd_opt(y, m, d)
+ .and_then(|d| d.and_hms_opt(h, 0, 0))
+ .unwrap()
+ }
+
+ fn all(rule: &Recurrence, start: NaiveDateTime) -> Vec {
+ let mut budget = Budget::new(FEED_BUDGET);
+ rule.walls(start, start, &mut budget).collect()
+ }
+
+ #[test]
+ fn rebuilds_messy_rules() {
+ let start = wall(2026, 1, 5, 9);
+ let rule = build_rule(
+ "freq=weekly;;byday=MO,WE;X-NAME=foo;INTERVAL=0;WKST=SU;",
+ start,
+ Zone::Utc,
+ )
+ .unwrap();
+ let mut budget = Budget::new(FEED_BUDGET);
+ let got: Vec<_> = rule.walls(start, start, &mut budget).take(3).collect();
+ assert_eq!(got, vec![start, wall(2026, 1, 7, 9), wall(2026, 1, 12, 9)]);
+ }
+
+ #[test]
+ fn until_in_utc_is_converted_to_wall_clock() {
+ let start = wall(2026, 3, 2, 9);
+ let ny = Zone::Named(chrono_tz::Tz::America__New_York);
+ let rule = build_rule("FREQ=DAILY;UNTIL=20260304T140000Z", start, ny).unwrap();
+ assert_eq!(all(&rule, start).len(), 3);
+ }
+
+ #[test]
+ fn rejects_bad_rules() {
+ let start = wall(2026, 1, 5, 9);
+ assert!(build_rule("BYDAY=MO", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=SOMETIMES", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=DAILY;UNTIL=20200101T000000Z", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=DAILY;COUNT=0", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=MONTHLY;BYMONTHDAY=40", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=DAILY;UNTIL=nope", start, Zone::Utc).is_err());
+ }
+
+ #[test]
+ fn sub_hourly_cadences_are_not_rules() {
+ let start = wall(2026, 1, 5, 9);
+ assert!(build_rule("FREQ=SECONDLY", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=MINUTELY;INTERVAL=30", start, Zone::Utc).is_err());
+ assert!(build_rule("FREQ=HOURLY;BYMINUTE=0,5,10,15,20", start, Zone::Utc).is_err());
+ assert!(
+ build_rule(
+ "FREQ=DAILY;BYHOUR=0,1,2,3,4,5,6,7,8,9,10,11;BYMINUTE=0,5,10,15,20,25,30,35,40",
+ start,
+ Zone::Utc
+ )
+ .is_err()
+ );
+ assert!(build_rule("FREQ=HOURLY;INTERVAL=2;BYMINUTE=0,30", start, Zone::Utc).is_ok());
+ assert!(
+ build_rule(
+ "FREQ=DAILY;BYHOUR=9,10,11,12;BYMINUTE=0,15,30,45",
+ start,
+ Zone::Utc
+ )
+ .is_ok()
+ );
+ }
+
+ fn naive_window(
+ rule: &Recurrence,
+ start: NaiveDateTime,
+ from: NaiveDateTime,
+ to: NaiveDateTime,
+ ) -> Vec {
+ let mut budget = Budget::new(u64::MAX / 2);
+ rule.walls(start, start, &mut budget)
+ .skip_while(|w| *w < from)
+ .take_while(|w| *w <= to)
+ .collect()
+ }
+
+ fn fast_window(
+ rule: &Recurrence,
+ start: NaiveDateTime,
+ from: NaiveDateTime,
+ to: NaiveDateTime,
+ ) -> (Vec, u64) {
+ let mut budget = Budget::new(FEED_BUDGET);
+ let got = rule
+ .walls(start, from, &mut budget)
+ .skip_while(|w| *w < from)
+ .take_while(|w| *w <= to)
+ .collect();
+ (got, FEED_BUDGET - budget.left())
+ }
+
+ #[test]
+ fn fast_forward_matches_naive_stepping() {
+ let rules = [
+ "FREQ=YEARLY",
+ "FREQ=YEARLY;INTERVAL=3",
+ "FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=29",
+ "FREQ=YEARLY;BYMONTH=3,11;BYDAY=2SU",
+ "FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU;BYHOUR=1,3",
+ "FREQ=YEARLY;BYWEEKNO=1,20,53;BYDAY=MO",
+ "FREQ=YEARLY;BYYEARDAY=1,100,-1",
+ "FREQ=YEARLY;INTERVAL=2;BYMONTH=1,7;BYDAY=FR;BYSETPOS=-1",
+ "FREQ=MONTHLY",
+ "FREQ=MONTHLY;INTERVAL=5",
+ "FREQ=MONTHLY;BYMONTHDAY=31",
+ "FREQ=MONTHLY;BYMONTHDAY=-1,15",
+ "FREQ=MONTHLY;BYDAY=FR;BYMONTHDAY=13",
+ "FREQ=MONTHLY;INTERVAL=2;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=1,-1",
+ "FREQ=MONTHLY;BYDAY=-2TH;BYMONTH=1,4,7,10",
+ "FREQ=WEEKLY",
+ "FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,TH",
+ "FREQ=WEEKLY;INTERVAL=3;BYDAY=SU,SA;WKST=SU",
+ "FREQ=WEEKLY;INTERVAL=2;BYDAY=TU;WKST=WE",
+ "FREQ=WEEKLY;INTERVAL=4;BYDAY=MO,FR;BYHOUR=9,15;BYMINUTE=0,30",
+ "FREQ=WEEKLY;BYMONTH=6,12;BYDAY=WE",
+ "FREQ=DAILY",
+ "FREQ=DAILY;INTERVAL=3",
+ "FREQ=DAILY;INTERVAL=10;BYDAY=MO,WE,FR",
+ "FREQ=DAILY;BYMONTH=2;BYMONTHDAY=28,29",
+ "FREQ=DAILY;BYHOUR=8,12,17;BYMINUTE=15",
+ "FREQ=DAILY;INTERVAL=2;BYDAY=TU,TH;BYSETPOS=1",
+ "FREQ=HOURLY",
+ "FREQ=HOURLY;INTERVAL=5",
+ "FREQ=HOURLY;INTERVAL=7;BYHOUR=9,10,11,12,13,14,15,16,17",
+ "FREQ=HOURLY;INTERVAL=3;BYDAY=MO,TU,WE,TH,FR;BYMINUTE=0,30",
+ "FREQ=HOURLY;INTERVAL=25",
+ ];
+ let starts = [
+ wall(2019, 1, 1, 0),
+ NaiveDate::from_ymd_opt(2020, 2, 29)
+ .and_then(|d| d.and_hms_opt(23, 45, 10))
+ .unwrap(),
+ wall(2021, 7, 18, 13),
+ wall(2022, 12, 31, 9),
+ ];
+ let anchors = [
+ wall(2026, 1, 1, 0),
+ NaiveDate::from_ymd_opt(2026, 3, 29)
+ .and_then(|d| d.and_hms_opt(5, 17, 0))
+ .unwrap(),
+ wall(2026, 11, 2, 23),
+ ];
+ let mut cases = 0;
+ let mut empty = 0;
+ for text in rules {
+ for start in starts {
+ let rule = build_rule(text, start, Zone::Utc).unwrap();
+ let span = match rule.freq {
+ Frequency::Yearly => Duration::days(366 * 9),
+ Frequency::Monthly => Duration::days(400),
+ Frequency::Weekly => Duration::days(120),
+ _ => Duration::days(21),
+ };
+ for from in anchors {
+ let to = from + span;
+ let naive = naive_window(&rule, start, from, to);
+ let (fast, cost) = fast_window(&rule, start, from, to);
+ assert_eq!(fast, naive, "{text} from {start} window {from}..{to}");
+ empty += usize::from(naive.is_empty());
+ assert!(
+ cost <= 2 * naive.len() as u64 * rule.period_cost + 50_000,
+ "{text} from {start}: cost {cost} for {} walls",
+ naive.len()
+ );
+ cases += 1;
+ }
+ }
+ }
+ assert_eq!(cases, rules.len() * starts.len() * anchors.len());
+ assert!(empty * 10 < cases, "{empty} of {cases} windows were empty");
+ }
+
+ #[test]
+ fn hourly_series_from_years_ago_reaches_the_window() {
+ let start = wall(2015, 1, 1, 9);
+ let rule = build_rule("FREQ=HOURLY", start, Zone::Utc).unwrap();
+ let from = wall(2026, 9, 1, 0);
+ let (got, cost) = fast_window(&rule, start, from, wall(2026, 9, 1, 23));
+ assert_eq!(got.len(), 24);
+ assert_eq!(got[0], from);
+ assert!(cost < 1_000, "{cost}");
+ }
+
+ #[test]
+ fn counted_rules_step_from_the_start_and_stay_exact() {
+ let start = wall(2025, 1, 6, 9);
+ let rule = build_rule("FREQ=WEEKLY;COUNT=60", start, Zone::Utc).unwrap();
+ let (got, _) = fast_window(&rule, start, wall(2026, 2, 1, 0), wall(2026, 12, 31, 0));
+ assert_eq!(got.len(), 4);
+ assert_eq!(got.last(), Some(&wall(2026, 2, 23, 9)));
+ }
+
+ #[test]
+ fn rules_without_occurrences_are_bounded_by_the_budget() {
+ let start = wall(2000, 1, 1, 0);
+ let rule = build_rule("FREQ=YEARLY;BYMONTH=2;BYMONTHDAY=30", start, Zone::Utc).unwrap();
+ let mut budget = Budget::new(FEED_BUDGET);
+ assert_eq!(rule.walls(start, start, &mut budget).count(), 0);
+ assert!(budget.left() < FEED_BUDGET);
+ let mut empty = Budget::new(10);
+ let rule = build_rule("FREQ=DAILY", start, Zone::Utc).unwrap();
+ assert_eq!(rule.walls(start, start, &mut empty).next(), None);
+ assert_eq!(empty.left(), 0);
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/time.rs b/apps/desktop-gpui/calendar/src/ics/time.rs
new file mode 100644
index 00000000000..905afb99610
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/time.rs
@@ -0,0 +1,200 @@
+use chrono::{NaiveDate, NaiveDateTime, NaiveTime};
+
+use super::lexer::Property;
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum IcsTime {
+ Date(NaiveDate),
+ Floating(NaiveDateTime),
+ Utc(NaiveDateTime),
+ Zoned(NaiveDateTime, String),
+}
+
+const MIN_YEAR: i32 = 1000;
+const MAX_YEAR: i32 = 3000;
+
+pub(crate) fn parse_date(value: &str) -> Option {
+ let digits: String = value.chars().filter(|c| *c != '-').collect();
+ if digits.len() != 8 || !digits.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let year: i32 = digits[..4].parse().ok()?;
+ if !(MIN_YEAR..=MAX_YEAR).contains(&year) {
+ return None;
+ }
+ NaiveDate::from_ymd_opt(year, digits[4..6].parse().ok()?, digits[6..8].parse().ok()?)
+}
+
+pub(crate) fn parse_date_time(value: &str) -> Option<(NaiveDateTime, bool)> {
+ let value = value.trim();
+ let (body, utc) = match value.strip_suffix(['Z', 'z']) {
+ Some(body) => (body, true),
+ None => (value, false),
+ };
+ let (date_part, time_part) = body.split_once(['T', 't'])?;
+ let date = parse_date(date_part)?;
+ let time_digits: String = time_part.chars().filter(|c| *c != ':').collect();
+ let time_digits = time_digits.split('.').next().unwrap_or("");
+ if !time_digits.bytes().all(|b| b.is_ascii_digit()) {
+ return None;
+ }
+ let (h, m, s) = match time_digits.len() {
+ 4 => (
+ time_digits[..2].parse().ok()?,
+ time_digits[2..].parse().ok()?,
+ 0,
+ ),
+ 6 => (
+ time_digits[..2].parse().ok()?,
+ time_digits[2..4].parse().ok()?,
+ time_digits[4..].parse::().ok()?.min(59),
+ ),
+ _ => return None,
+ };
+ let time = NaiveTime::from_hms_opt(h, m, s)?;
+ Some((date.and_time(time), utc))
+}
+
+pub(crate) fn parse_one(value: &str, tzid: Option<&str>, is_date: bool) -> Option {
+ let value = value.trim();
+ let looks_like_date = !value.contains(['T', 't']);
+ if is_date || looks_like_date {
+ if let Some(date) = parse_date(value) {
+ return Some(IcsTime::Date(date));
+ }
+ if looks_like_date {
+ return None;
+ }
+ }
+ let (naive, utc) = parse_date_time(value)?;
+ if utc {
+ return Some(IcsTime::Utc(naive));
+ }
+ match tzid.map(str::trim).filter(|t| !t.is_empty()) {
+ Some(tzid) => Some(IcsTime::Zoned(naive, tzid.to_string())),
+ None => Some(IcsTime::Floating(naive)),
+ }
+}
+
+pub(crate) fn parse_property(prop: &Property) -> Vec {
+ let is_date = prop
+ .param("VALUE")
+ .is_some_and(|v| v.eq_ignore_ascii_case("DATE"));
+ let is_period = prop
+ .param("VALUE")
+ .is_some_and(|v| v.eq_ignore_ascii_case("PERIOD"));
+ let tzid = prop.param("TZID");
+ prop.value
+ .split(',')
+ .filter(|v| !v.trim().is_empty())
+ .filter_map(|v| {
+ let v = if is_period || v.contains('/') {
+ v.split('/').next().unwrap_or(v)
+ } else {
+ v
+ };
+ parse_one(v, tzid, is_date)
+ })
+ .collect()
+}
+
+#[cfg(test)]
+pub(crate) fn parse_duration(value: &str) -> Option {
+ let (days, seconds) = parse_duration_parts(value)?;
+ Some(chrono::Duration::seconds(
+ days.checked_mul(86_400)?.checked_add(seconds)?,
+ ))
+}
+
+pub(crate) fn parse_duration_parts(value: &str) -> Option<(i64, i64)> {
+ let value = value.trim();
+ let (negative, rest) = match value.as_bytes().first()? {
+ b'-' => (true, &value[1..]),
+ b'+' => (false, &value[1..]),
+ _ => (false, value),
+ };
+ let rest = rest.strip_prefix(['P', 'p'])?;
+ let mut days: i64 = 0;
+ let mut seconds: i64 = 0;
+ let mut number = String::new();
+ let mut in_time = false;
+ let mut any = false;
+ for c in rest.chars() {
+ match c.to_ascii_uppercase() {
+ d if d.is_ascii_digit() => number.push(d),
+ 'T' => in_time = true,
+ unit => {
+ let n: i64 = number.parse().ok()?;
+ number.clear();
+ match (unit, in_time) {
+ ('W', false) => days = days.checked_add(n.checked_mul(7)?)?,
+ ('D', false) => days = days.checked_add(n)?,
+ ('H', true) => seconds = seconds.checked_add(n.checked_mul(3_600)?)?,
+ ('M', true) => seconds = seconds.checked_add(n.checked_mul(60)?)?,
+ ('S', true) => seconds = seconds.checked_add(n)?,
+ _ => return None,
+ }
+ any = true;
+ }
+ }
+ }
+ let total = days.checked_mul(86_400)?.checked_add(seconds)?;
+ if !any || !number.is_empty() || total > 366 * 86_400 * 10 {
+ return None;
+ }
+ Some(if negative {
+ (-days, -seconds)
+ } else {
+ (days, seconds)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use chrono::Duration;
+
+ #[test]
+ fn parses_all_value_forms() {
+ let d = NaiveDate::from_ymd_opt(2026, 3, 9).unwrap();
+ assert_eq!(parse_one("20260309", None, true), Some(IcsTime::Date(d)));
+ assert_eq!(parse_one("20260309", None, false), Some(IcsTime::Date(d)));
+ let dt = d.and_hms_opt(9, 30, 0).unwrap();
+ assert_eq!(
+ parse_one("20260309T093000Z", None, false),
+ Some(IcsTime::Utc(dt))
+ );
+ assert_eq!(
+ parse_one("20260309T093000", Some("Europe/Paris"), false),
+ Some(IcsTime::Zoned(dt, "Europe/Paris".into()))
+ );
+ assert_eq!(
+ parse_one("20260309T0930", None, false),
+ Some(IcsTime::Floating(dt))
+ );
+ assert_eq!(
+ parse_one("2026-03-09T09:30:00Z", None, false),
+ Some(IcsTime::Utc(dt))
+ );
+ assert_eq!(parse_one("20261309T093000Z", None, false), None);
+ assert_eq!(parse_one("99999999T000000Z", None, false), None);
+ assert_eq!(parse_one("garbage", None, false), None);
+ }
+
+ #[test]
+ fn parses_durations() {
+ assert_eq!(parse_duration("PT1H30M"), Some(Duration::minutes(90)));
+ assert_eq!(parse_duration("P1D"), Some(Duration::days(1)));
+ assert_eq!(parse_duration("P2W"), Some(Duration::weeks(2)));
+ assert_eq!(parse_duration("-PT15M"), Some(Duration::minutes(-15)));
+ assert_eq!(parse_duration("P1DT2H"), Some(Duration::hours(26)));
+ assert_eq!(parse_duration_parts("P1DT2H"), Some((1, 7_200)));
+ assert_eq!(parse_duration_parts("P1W"), Some((7, 0)));
+ assert_eq!(parse_duration_parts("PT24H"), Some((0, 86_400)));
+ assert_eq!(parse_duration_parts("-P1D"), Some((-1, 0)));
+ assert_eq!(parse_duration("PT"), None);
+ assert_eq!(parse_duration("P1H"), None);
+ assert_eq!(parse_duration("P99999999999999999999D"), None);
+ assert_eq!(parse_duration(""), None);
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/ics/vtimezone.rs b/apps/desktop-gpui/calendar/src/ics/vtimezone.rs
new file mode 100644
index 00000000000..7561e788ec3
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/ics/vtimezone.rs
@@ -0,0 +1,241 @@
+use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, NaiveDateTime, Utc};
+
+use super::budget::Budget;
+use super::lexer::Component;
+use super::rule::build_rule;
+use super::time::{IcsTime, parse_property};
+use crate::tz::{Zone, parse_offset, preferred_zones, resolve_tzid};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ZoneResolution {
+ Named,
+ MatchedRules,
+ FixedStandardOffset,
+}
+
+#[derive(Clone, Debug)]
+struct Observance {
+ daylight: bool,
+ start: NaiveDateTime,
+ from: FixedOffset,
+ to: FixedOffset,
+ rule: Option,
+ rdates: Vec,
+}
+
+fn observances(comp: &Component) -> Vec {
+ comp.children
+ .iter()
+ .filter(|c| c.name == "STANDARD" || c.name == "DAYLIGHT")
+ .filter_map(|c| {
+ let to = c.prop("TZOFFSETTO").and_then(|p| parse_offset(&p.value))?;
+ let from = c
+ .prop("TZOFFSETFROM")
+ .and_then(|p| parse_offset(&p.value))
+ .unwrap_or(to);
+ let start = c
+ .prop("DTSTART")
+ .map(parse_property)
+ .and_then(|v| v.into_iter().next())
+ .and_then(|t| match t {
+ IcsTime::Floating(n) | IcsTime::Utc(n) | IcsTime::Zoned(n, _) => Some(n),
+ IcsTime::Date(d) => d.and_hms_opt(0, 0, 0),
+ })?;
+ let rdates = c
+ .props_named("RDATE")
+ .flat_map(parse_property)
+ .filter_map(|t| match t {
+ IcsTime::Floating(n) | IcsTime::Utc(n) | IcsTime::Zoned(n, _) => Some(n),
+ IcsTime::Date(d) => d.and_hms_opt(0, 0, 0),
+ })
+ .collect();
+ Some(Observance {
+ daylight: c.name == "DAYLIGHT",
+ start,
+ from,
+ to,
+ rule: c.prop("RRULE").map(|p| p.value.clone()),
+ rdates,
+ })
+ })
+ .collect()
+}
+
+struct Transition {
+ at: DateTime,
+ from: i32,
+ to: i32,
+}
+
+const ZONE_MATCH_COST: u64 = 5_000;
+
+fn transitions_in(obs: &Observance, year: i32, budget: &mut Budget) -> Vec {
+ let mut walls: Vec = Vec::new();
+ if let Some(rule) = &obs.rule {
+ let year_start = NaiveDate::from_ymd_opt(year, 1, 1).and_then(|d| d.and_hms_opt(0, 0, 0));
+ if let (Ok(rule), Some(year_start)) = (
+ build_rule(rule, obs.start, Zone::Fixed(obs.from)),
+ year_start,
+ ) {
+ walls.extend(
+ rule.walls(obs.start, year_start, budget)
+ .take_while(|w| w.year() <= year)
+ .filter(|w| w.year() == year)
+ .take(64),
+ );
+ }
+ } else {
+ walls.extend(
+ obs.rdates
+ .iter()
+ .chain(std::iter::once(&obs.start))
+ .filter(|w| w.year() == year)
+ .copied(),
+ );
+ }
+ walls
+ .into_iter()
+ .map(|wall| Transition {
+ at: Zone::Fixed(obs.from).to_utc(wall),
+ from: obs.from.local_minus_utc(),
+ to: obs.to.local_minus_utc(),
+ })
+ .collect()
+}
+
+fn latest(obs: &[Observance], daylight: bool) -> Option<&Observance> {
+ obs.iter()
+ .filter(|o| o.daylight == daylight)
+ .max_by_key(|o| o.start)
+}
+
+pub(crate) fn resolve_vtimezone(
+ comp: &Component,
+ budget: &mut Budget,
+) -> Option<(String, Zone, ZoneResolution)> {
+ let tzid = comp.prop("TZID")?.value.trim().to_string();
+ if tzid.is_empty() {
+ return None;
+ }
+ if let Some(zone @ (Zone::Named(_) | Zone::Utc)) = resolve_tzid(&tzid) {
+ return Some((tzid, zone, ZoneResolution::Named));
+ }
+ let obs = observances(comp);
+ let standard = latest(&obs, false).or_else(|| latest(&obs, true))?;
+ let std_offset = standard.to;
+ let daylight = latest(&obs, true).filter(|d| !std::ptr::eq(*d, standard));
+ let base_year = obs
+ .iter()
+ .map(|o| o.start.year())
+ .max()
+ .unwrap_or(2025)
+ .max(2025);
+ let years = [base_year, base_year + 1];
+ let mut transitions = Vec::new();
+ for year in years {
+ transitions.extend(transitions_in(standard, year, budget));
+ if let Some(d) = daylight {
+ transitions.extend(transitions_in(d, year, budget));
+ }
+ }
+ transitions.retain(|t| t.from != t.to);
+ let dst_offset = daylight.map(|d| d.to.local_minus_utc());
+ let samples: Vec> = years
+ .iter()
+ .flat_map(|y| [1, 4, 7, 10].map(|m| (*y, m)))
+ .filter_map(|(y, m)| NaiveDate::from_ymd_opt(y, m, 15)?.and_hms_opt(12, 0, 0))
+ .map(|n| n.and_utc())
+ .collect();
+ let std_secs = std_offset.local_minus_utc();
+ let matches = |zone: Zone| {
+ let ok_transitions = transitions.iter().all(|t| {
+ zone.offset_seconds_at(t.at - Duration::minutes(1)) == t.from
+ && zone.offset_seconds_at(t.at + Duration::minutes(1)) == t.to
+ });
+ let ok_samples = samples.iter().all(|s| {
+ let off = zone.offset_seconds_at(*s);
+ if transitions.is_empty() {
+ off == std_secs
+ } else {
+ off == std_secs || Some(off) == dst_offset
+ }
+ });
+ ok_transitions && ok_samples
+ };
+ if budget.can_afford(ZONE_MATCH_COST) {
+ budget.charge(ZONE_MATCH_COST);
+ if let Some(tz) = preferred_zones().find(|tz| matches(Zone::Named(*tz))) {
+ return Some((tzid, Zone::Named(tz), ZoneResolution::MatchedRules));
+ }
+ }
+ Some((
+ tzid,
+ Zone::Fixed(std_offset),
+ ZoneResolution::FixedStandardOffset,
+ ))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ics::budget::FEED_BUDGET;
+ use crate::ics::lexer::lex;
+ use chrono_tz::Tz;
+
+ fn resolve(text: &str) -> (Zone, ZoneResolution) {
+ let lexed = lex(text);
+ let mut budget = Budget::new(FEED_BUDGET);
+ let (_, zone, how) = resolve_vtimezone(&lexed.root.children[0], &mut budget).unwrap();
+ (zone, how)
+ }
+
+ #[test]
+ fn matches_outlook_custom_eastern() {
+ let (zone, how) = resolve(
+ "BEGIN:VTIMEZONE\nTZID:Customized Time Zone\nBEGIN:STANDARD\nDTSTART:16010101T020000\nTZOFFSETFROM:-0400\nTZOFFSETTO:-0500\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=11\nEND:STANDARD\nBEGIN:DAYLIGHT\nDTSTART:16010101T020000\nTZOFFSETFROM:-0500\nTZOFFSETTO:-0400\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=2SU;BYMONTH=3\nEND:DAYLIGHT\nEND:VTIMEZONE\n",
+ );
+ assert_eq!(how, ZoneResolution::MatchedRules);
+ assert_eq!(zone, Zone::Named(Tz::America__New_York));
+ }
+
+ #[test]
+ fn matches_southern_hemisphere_rules() {
+ let (zone, how) = resolve(
+ "BEGIN:VTIMEZONE\nTZID:(UTC+10:00) Canberra\\, Melbourne\\, Sydney\nBEGIN:STANDARD\nDTSTART:16010101T030000\nTZOFFSETFROM:+1100\nTZOFFSETTO:+1000\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4\nEND:STANDARD\nBEGIN:DAYLIGHT\nDTSTART:16010101T020000\nTZOFFSETFROM:+1000\nTZOFFSETTO:+1100\nRRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10\nEND:DAYLIGHT\nEND:VTIMEZONE\n",
+ );
+ assert_eq!(how, ZoneResolution::MatchedRules);
+ assert_eq!(zone, Zone::Named(Tz::Australia__Sydney));
+ }
+
+ #[test]
+ fn falls_back_to_fixed_standard_offset() {
+ let (zone, how) = resolve(
+ "BEGIN:VTIMEZONE\nTZID:Mars Colony\nBEGIN:STANDARD\nDTSTART:19700101T000000\nTZOFFSETFROM:+0317\nTZOFFSETTO:+0317\nEND:STANDARD\nEND:VTIMEZONE\n",
+ );
+ assert_eq!(how, ZoneResolution::FixedStandardOffset);
+ assert_eq!(
+ zone,
+ FixedOffset::east_opt(3 * 3600 + 17 * 60)
+ .map(Zone::Fixed)
+ .unwrap()
+ );
+ }
+
+ #[test]
+ fn named_tzid_wins_over_rules() {
+ let (zone, how) = resolve(
+ "BEGIN:VTIMEZONE\nTZID:Europe/Berlin\nBEGIN:STANDARD\nDTSTART:19701025T030000\nTZOFFSETFROM:+0200\nTZOFFSETTO:+0100\nEND:STANDARD\nEND:VTIMEZONE\n",
+ );
+ assert_eq!(how, ZoneResolution::Named);
+ assert_eq!(zone, Zone::Named(Tz::Europe__Berlin));
+ }
+
+ #[test]
+ fn matches_zone_without_daylight_saving() {
+ let (zone, how) = resolve(
+ "BEGIN:VTIMEZONE\nTZID:India\nBEGIN:STANDARD\nDTSTART:16010101T000000\nTZOFFSETFROM:+0530\nTZOFFSETTO:+0530\nEND:STANDARD\nEND:VTIMEZONE\n",
+ );
+ assert_eq!(how, ZoneResolution::MatchedRules);
+ assert_eq!(zone, Zone::Named(Tz::Asia__Kolkata));
+ }
+}
diff --git a/apps/desktop-gpui/calendar/src/lib.rs b/apps/desktop-gpui/calendar/src/lib.rs
new file mode 100644
index 00000000000..a2be1214bb5
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/lib.rs
@@ -0,0 +1,22 @@
+pub mod agenda;
+mod error;
+pub mod google;
+pub mod graph;
+mod http;
+pub mod ics;
+pub mod link;
+mod model;
+pub mod oauth;
+pub mod system;
+mod text;
+pub mod tz;
+
+pub use agenda::{Agenda, Filter, Reminder, due_reminders, next_wake};
+pub use chrono_tz::Tz;
+pub use error::Error;
+pub use http::{HttpMethod, HttpRequestSpec};
+pub use link::{
+ ConferenceEntry, ConferenceKind, MeetingLink, Provider, classify_url, event_meeting_link,
+ find_meeting_link,
+};
+pub use model::{CalendarEvent, CalendarInfo, EventStatus, Page, Person, Response, SourceKind};
diff --git a/apps/desktop-gpui/calendar/src/link.rs b/apps/desktop-gpui/calendar/src/link.rs
new file mode 100644
index 00000000000..99b444ecccc
--- /dev/null
+++ b/apps/desktop-gpui/calendar/src/link.rs
@@ -0,0 +1,1233 @@
+use serde::{Deserialize, Serialize};
+use url::Url;
+
+use crate::text::decode_entities;
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub enum Provider {
+ #[serde(rename = "zoom")]
+ Zoom,
+ #[serde(rename = "google-meet")]
+ GoogleMeet,
+ #[serde(rename = "teams")]
+ Teams,
+ #[serde(rename = "webex")]
+ Webex,
+ #[serde(rename = "slack")]
+ Slack,
+ #[serde(rename = "whereby")]
+ Whereby,
+ #[serde(rename = "around")]
+ Around,
+ #[serde(rename = "goto-meeting")]
+ GoToMeeting,
+ #[serde(rename = "goto-webinar")]
+ GoToWebinar,
+ #[serde(rename = "bluejeans")]
+ BlueJeans,
+ #[serde(rename = "jitsi")]
+ Jitsi,
+ #[serde(rename = "discord")]
+ Discord,
+ #[serde(rename = "skype")]
+ Skype,
+ #[serde(rename = "chime")]
+ Chime,
+ #[serde(rename = "ringcentral")]
+ RingCentral,
+ #[serde(rename = "dialpad")]
+ Dialpad,
+ #[serde(rename = "zoho-meeting")]
+ ZohoMeeting,
+ #[serde(rename = "lark")]
+ Lark,
+ #[serde(rename = "tuple")]
+ Tuple,
+ #[serde(rename = "gather")]
+ Gather,
+ #[serde(rename = "riverside")]
+ Riverside,
+ #[serde(rename = "streamyard")]
+ StreamYard,
+ #[serde(rename = "whatsapp")]
+ WhatsApp,
+ #[serde(rename = "facetime")]
+ FaceTime,
+ #[serde(rename = "cal-video")]
+ CalVideo,
+ #[serde(rename = "daily")]
+ Daily,
+ #[serde(rename = "livestorm")]
+ Livestorm,
+ #[serde(rename = "pop")]
+ Pop,
+ #[serde(rename = "tandem")]
+ Tandem,
+ #[serde(rename = "vowel")]
+ Vowel,
+ #[serde(rename = "demio")]
+ Demio,
+ #[serde(rename = "butter")]
+ Butter,
+ #[serde(rename = "other", other)]
+ Other,
+}
+
+impl Provider {
+ pub const ALL: [Provider; 33] = [
+ Provider::Zoom,
+ Provider::GoogleMeet,
+ Provider::Teams,
+ Provider::Webex,
+ Provider::Slack,
+ Provider::Whereby,
+ Provider::Around,
+ Provider::GoToMeeting,
+ Provider::GoToWebinar,
+ Provider::BlueJeans,
+ Provider::Jitsi,
+ Provider::Discord,
+ Provider::Skype,
+ Provider::Chime,
+ Provider::RingCentral,
+ Provider::Dialpad,
+ Provider::ZohoMeeting,
+ Provider::Lark,
+ Provider::Tuple,
+ Provider::Gather,
+ Provider::Riverside,
+ Provider::StreamYard,
+ Provider::WhatsApp,
+ Provider::FaceTime,
+ Provider::CalVideo,
+ Provider::Daily,
+ Provider::Livestorm,
+ Provider::Pop,
+ Provider::Tandem,
+ Provider::Vowel,
+ Provider::Demio,
+ Provider::Butter,
+ Provider::Other,
+ ];
+
+ pub fn display_name(self) -> &'static str {
+ match self {
+ Provider::Zoom => "Zoom",
+ Provider::GoogleMeet => "Google Meet",
+ Provider::Teams => "Microsoft Teams",
+ Provider::Webex => "Webex",
+ Provider::Slack => "Slack Huddle",
+ Provider::Whereby => "Whereby",
+ Provider::Around => "Around",
+ Provider::GoToMeeting => "GoTo Meeting",
+ Provider::GoToWebinar => "GoTo Webinar",
+ Provider::BlueJeans => "BlueJeans",
+ Provider::Jitsi => "Jitsi Meet",
+ Provider::Discord => "Discord",
+ Provider::Skype => "Skype",
+ Provider::Chime => "Amazon Chime",
+ Provider::RingCentral => "RingCentral",
+ Provider::Dialpad => "Dialpad Meetings",
+ Provider::ZohoMeeting => "Zoho Meeting",
+ Provider::Lark => "Lark",
+ Provider::Tuple => "Tuple",
+ Provider::Gather => "Gather",
+ Provider::Riverside => "Riverside",
+ Provider::StreamYard => "StreamYard",
+ Provider::WhatsApp => "WhatsApp",
+ Provider::FaceTime => "FaceTime",
+ Provider::CalVideo => "Cal Video",
+ Provider::Daily => "Daily",
+ Provider::Livestorm => "Livestorm",
+ Provider::Pop => "Pop",
+ Provider::Tandem => "Tandem",
+ Provider::Vowel => "Vowel",
+ Provider::Demio => "Demio",
+ Provider::Butter => "Butter",
+ Provider::Other => "Video call",
+ }
+ }
+
+ pub fn slug(self) -> &'static str {
+ match self {
+ Provider::Zoom => "zoom",
+ Provider::GoogleMeet => "google-meet",
+ Provider::Teams => "teams",
+ Provider::Webex => "webex",
+ Provider::Slack => "slack",
+ Provider::Whereby => "whereby",
+ Provider::Around => "around",
+ Provider::GoToMeeting => "goto-meeting",
+ Provider::GoToWebinar => "goto-webinar",
+ Provider::BlueJeans => "bluejeans",
+ Provider::Jitsi => "jitsi",
+ Provider::Discord => "discord",
+ Provider::Skype => "skype",
+ Provider::Chime => "chime",
+ Provider::RingCentral => "ringcentral",
+ Provider::Dialpad => "dialpad",
+ Provider::ZohoMeeting => "zoho-meeting",
+ Provider::Lark => "lark",
+ Provider::Tuple => "tuple",
+ Provider::Gather => "gather",
+ Provider::Riverside => "riverside",
+ Provider::StreamYard => "streamyard",
+ Provider::WhatsApp => "whatsapp",
+ Provider::FaceTime => "facetime",
+ Provider::CalVideo => "cal-video",
+ Provider::Daily => "daily",
+ Provider::Livestorm => "livestorm",
+ Provider::Pop => "pop",
+ Provider::Tandem => "tandem",
+ Provider::Vowel => "vowel",
+ Provider::Demio => "demio",
+ Provider::Butter => "butter",
+ Provider::Other => "other",
+ }
+ }
+
+ pub fn from_slug(slug: &str) -> Option {
+ Provider::ALL.into_iter().find(|p| p.slug() == slug)
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeetingLink {
+ pub provider: Provider,
+ pub url: String,
+ #[serde(default)]
+ pub meeting_id: Option,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ConferenceKind {
+ Video,
+ Phone,
+ Sip,
+ More,
+ Other,
+}
+
+impl ConferenceKind {
+ pub fn from_entry_point_type(value: &str) -> ConferenceKind {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "video" => ConferenceKind::Video,
+ "phone" => ConferenceKind::Phone,
+ "sip" => ConferenceKind::Sip,
+ "more" => ConferenceKind::More,
+ _ => ConferenceKind::Other,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ConferenceEntry {
+ pub kind: ConferenceKind,
+ pub uri: String,
+ pub meeting_code: Option,
+}
+
+impl ConferenceEntry {
+ pub fn video(uri: impl Into) -> Self {
+ Self {
+ kind: ConferenceKind::Video,
+ uri: uri.into(),
+ meeting_code: None,
+ }
+ }
+}
+
+pub fn event_meeting_link(
+ conference: &[ConferenceEntry],
+ location: Option<&str>,
+ description: Option<&str>,
+ url: Option<&str>,
+) -> Option {
+ conference
+ .iter()
+ .filter(|e| e.kind == ConferenceKind::Video)
+ .find_map(structured_link)
+ .or_else(|| location.and_then(find_meeting_link))
+ .or_else(|| description.and_then(find_meeting_link))
+ .or_else(|| url.and_then(classify_url))
+}
+
+fn structured_link(entry: &ConferenceEntry) -> Option {
+ let code = entry
+ .meeting_code
+ .as_deref()
+ .map(str::trim)
+ .filter(|c| !c.is_empty())
+ .map(str::to_string);
+ if let Some(mut link) = classify_url(&entry.uri) {
+ if link.meeting_id.is_none() {
+ link.meeting_id = code;
+ }
+ return Some(link);
+ }
+ let parsed = Url::parse(entry.uri.trim()).ok()?;
+ if !matches!(parsed.scheme(), "http" | "https") || parsed.host_str().is_none() {
+ return None;
+ }
+ Some(MeetingLink {
+ provider: Provider::Other,
+ url: parsed.to_string(),
+ meeting_id: code,
+ })
+}
+
+pub fn find_meeting_link(text: &str) -> Option {
+ let decoded = decode_entities(text);
+ candidates(&decoded).find_map(|c| classify_url(&c))
+}
+
+pub fn find_all_meeting_links(text: &str) -> Vec {
+ let decoded = decode_entities(text);
+ let mut out: Vec = Vec::new();
+ for link in candidates(&decoded).filter_map(|c| classify_url(&c)) {
+ if !out.iter().any(|l| l.url == link.url) {
+ out.push(link);
+ }
+ }
+ out
+}
+
+pub fn classify_url(url: &str) -> Option {
+ classify_depth(url, 0)
+}
+
+const SCHEMES: [&str; 5] = ["https://", "http://", "zoommtg://", "zoomus://", "msteams:"];
+
+fn is_delimiter(c: char) -> bool {
+ c.is_whitespace()
+ || matches!(
+ c,
+ '<' | '>' | '"' | '\'' | '`' | '|' | '{' | '}' | '\\' | '^'
+ )
+}
+
+fn candidates(text: &str) -> impl Iterator
- + '_ {
+ text.split(is_delimiter)
+ .filter(|t| !t.is_empty())
+ .filter_map(token_candidate)
+}
+
+fn token_candidate(token: &str) -> Option {
+ let lower = token.to_ascii_lowercase();
+ if let Some(idx) = SCHEMES.iter().filter_map(|s| lower.find(s)).min() {
+ return Some(token[idx..].to_string());
+ }
+ let start = token
+ .find(|c: char| c.is_ascii_alphanumeric())
+ .unwrap_or(token.len());
+ let bare = &token[start..];
+ let slash = bare.find('/')?;
+ let host = &bare[..slash];
+ let host_ok = host.contains('.')
+ && host.len() >= 4
+ && host
+ .chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-')
+ && host
+ .rsplit('.')
+ .next()
+ .is_some_and(|tld| tld.len() >= 2 && tld.chars().all(|c| c.is_ascii_alphabetic()));
+ if !host_ok {
+ return None;
+ }
+ Some(format!("https://{bare}"))
+}
+
+fn strip_trailing(s: &str) -> &str {
+ let mut out = s.trim();
+ loop {
+ let Some(last) = out.chars().last() else {
+ return out;
+ };
+ let strip = match last {
+ '.' | ',' | ';' | ':' | '!' | '?' | '*' | ']' | '}' | '\'' | '"' => true,
+ ')' => out.matches(')').count() > out.matches('(').count(),
+ _ => false,
+ };
+ if !strip {
+ return out;
+ }
+ out = &out[..out.len() - last.len_utf8()];
+ }
+}
+
+fn classify_depth(raw: &str, depth: u8) -> Option {
+ if depth > 4 || raw.len() > 8192 {
+ return None;
+ }
+ let trimmed = strip_trailing(raw.trim().trim_start_matches(['<', '(', '[']));
+ if trimmed.is_empty() {
+ return None;
+ }
+ let with_scheme = if trimmed.contains(':') {
+ trimmed.to_string()
+ } else {
+ format!("https://{trimmed}")
+ };
+ let mut url = Url::parse(&with_scheme).ok()?;
+ match url.scheme() {
+ "http" | "https" => {}
+ "zoommtg" | "zoomus" => return zoom_app_link(&url),
+ "msteams" => {
+ let rest = with_scheme.split_once(':')?.1.trim_start_matches('/');
+ return classify_depth(&format!("https://teams.microsoft.com/{rest}"), depth + 1);
+ }
+ _ => return None,
+ }
+ if let Some(inner) = unwrap_redirect(&url, &with_scheme) {
+ return classify_depth(&inner, depth + 1);
+ }
+ let host = url.host_str()?.trim_end_matches('.').to_ascii_lowercase();
+ let segs: Vec = url
+ .path_segments()
+ .map(|s| s.filter(|p| !p.is_empty()).map(percent_decode).collect())
+ .unwrap_or_default();
+ let ctx = Ctx {
+ url: &url,
+ host: &host,
+ segs: &segs,
+ };
+ let (provider, hit) = RULES
+ .iter()
+ .find_map(|(provider, rule)| rule(&ctx).map(|hit| (*provider, hit)))?;
+ if url.scheme() == "http" {
+ url.set_scheme("https").ok()?;
+ }
+ if !hit.keep_fragment {
+ url.set_fragment(None);
+ }
+ strip_tracking(&mut url);
+ Some(MeetingLink {
+ provider,
+ url: url.to_string(),
+ meeting_id: hit.id.filter(|id| !id.is_empty()),
+ })
+}
+
+fn strip_tracking(url: &mut Url) {
+ if url.query().is_none() {
+ return;
+ }
+ let kept: Vec<(String, String)> = url
+ .query_pairs()
+ .filter(|(k, _)| !k.to_ascii_lowercase().starts_with("utm_"))
+ .map(|(k, v)| (k.into_owned(), v.into_owned()))
+ .collect();
+ if kept.is_empty() {
+ url.set_query(None);
+ return;
+ }
+ let original = url.query_pairs().count();
+ if kept.len() != original {
+ url.query_pairs_mut().clear().extend_pairs(kept);
+ }
+}
+
+fn percent_decode(s: &str) -> String {
+ url::form_urlencoded::parse(format!("x={}", s.replace('+', "%2B")).as_bytes())
+ .next()
+ .map(|(_, v)| v.into_owned())
+ .unwrap_or_else(|| s.to_string())
+}
+
+fn query_param(url: &Url, name: &str) -> Option {
+ url.query_pairs()
+ .find(|(k, _)| k.eq_ignore_ascii_case(name))
+ .map(|(_, v)| v.into_owned())
+ .filter(|v| !v.is_empty())
+}
+
+fn unwrap_redirect(url: &Url, raw: &str) -> Option {
+ let host = url.host_str()?.to_ascii_lowercase();
+ let path = url.path();
+ if host.ends_with("safelinks.protection.outlook.com") || path.ends_with("safelinks.html") {
+ return query_param(url, "url");
+ }
+ if (host == "google.com" || host.starts_with("www.google.") || host == "google.co.uk")
+ && path == "/url"
+ {
+ return query_param(url, "q").or_else(|| query_param(url, "url"));
+ }
+ if host == "slack-redir.net" && path == "/link" {
+ return query_param(url, "url");
+ }
+ if host == "urldefense.com" && path.starts_with("/v3/__") {
+ let start = raw.find("/v3/__")? + "/v3/__".len();
+ let rest = &raw[start..];
+ let end = rest.find("__;").unwrap_or(rest.len());
+ return Some(rest[..end].to_string());
+ }
+ if host == "urldefense.proofpoint.com" && path.starts_with("/v2/url") {
+ return query_param(url, "u").map(|u| proofpoint_v2_decode(&u));
+ }
+ None
+}
+
+fn proofpoint_v2_decode(value: &str) -> String {
+ let replaced = value.replace('_', "/");
+ let bytes = replaced.as_bytes();
+ let mut out = Vec::with_capacity(bytes.len());
+ let mut i = 0;
+ while i < bytes.len() {
+ if bytes[i] == b'-'
+ && i + 2 < bytes.len()
+ && let Some(byte) = std::str::from_utf8(&bytes[i + 1..i + 3])
+ .ok()
+ .and_then(|h| u8::from_str_radix(h, 16).ok())
+ {
+ out.push(byte);
+ i += 3;
+ continue;
+ }
+ out.push(bytes[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
+
+fn zoom_app_link(url: &Url) -> Option {
+ let id = query_param(url, "confno").filter(|c| is_digits(c, 9, 12))?;
+ let mut out = format!("https://zoom.us/j/{id}");
+ if let Some(pwd) = query_param(url, "pwd") {
+ out.push_str("?pwd=");
+ out.push_str(&url::form_urlencoded::byte_serialize(pwd.as_bytes()).collect::());
+ }
+ Some(MeetingLink {
+ provider: Provider::Zoom,
+ url: out,
+ meeting_id: Some(id),
+ })
+}
+
+struct Ctx<'a> {
+ url: &'a Url,
+ host: &'a str,
+ segs: &'a [String],
+}
+
+impl Ctx<'_> {
+ fn seg(&self, i: usize) -> Option<&str> {
+ self.segs.get(i).map(String::as_str)
+ }
+
+ fn seg_lower(&self, i: usize) -> Option {
+ self.seg(i).map(str::to_ascii_lowercase)
+ }
+
+ fn host_is(&self, domain: &str) -> bool {
+ self.host == domain
+ }
+
+ fn host_under(&self, domain: &str) -> bool {
+ self.host == domain
+ || (self.host.len() > domain.len()
+ && self.host.ends_with(domain)
+ && self.host.as_bytes()[self.host.len() - domain.len() - 1] == b'.')
+ }
+
+ fn is_root_or_www(&self, domain: &str) -> bool {
+ self.host == domain || self.host.strip_prefix("www.") == Some(domain)
+ }
+
+ fn param(&self, name: &str) -> Option {
+ query_param(self.url, name)
+ }
+}
+
+struct Hit {
+ id: Option,
+ keep_fragment: bool,
+}
+
+fn hit(id: Option) -> Option {
+ Some(Hit {
+ id,
+ keep_fragment: false,
+ })
+}
+
+fn hit_with_fragment(id: Option) -> Option {
+ Some(Hit {
+ id,
+ keep_fragment: true,
+ })
+}
+
+fn is_digits(s: &str, min: usize, max: usize) -> bool {
+ (min..=max).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_digit())
+}
+
+fn digits_of(s: &str) -> String {
+ s.chars().filter(char::is_ascii_digit).collect()
+}
+
+fn is_slug(s: &str) -> bool {
+ !s.is_empty()
+ && s.len() <= 128
+ && s.chars()
+ .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+}
+
+type Rule = fn(&Ctx) -> Option;
+
+const RULES: [(Provider, Rule); 32] = [
+ (Provider::Zoom, zoom),
+ (Provider::GoogleMeet, google_meet),
+ (Provider::Teams, teams),
+ (Provider::Webex, webex),
+ (Provider::Slack, slack),
+ (Provider::Whereby, whereby),
+ (Provider::Around, around),
+ (Provider::GoToMeeting, goto_meeting),
+ (Provider::GoToWebinar, goto_webinar),
+ (Provider::BlueJeans, bluejeans),
+ (Provider::Jitsi, jitsi),
+ (Provider::Discord, discord),
+ (Provider::Skype, skype),
+ (Provider::Chime, chime),
+ (Provider::RingCentral, ringcentral),
+ (Provider::Dialpad, dialpad),
+ (Provider::ZohoMeeting, zoho),
+ (Provider::Lark, lark),
+ (Provider::Tuple, tuple),
+ (Provider::Gather, gather),
+ (Provider::Riverside, riverside),
+ (Provider::StreamYard, streamyard),
+ (Provider::WhatsApp, whatsapp),
+ (Provider::FaceTime, facetime),
+ (Provider::CalVideo, cal_video),
+ (Provider::Daily, daily),
+ (Provider::Livestorm, livestorm),
+ (Provider::Pop, pop),
+ (Provider::Tandem, tandem),
+ (Provider::Vowel, vowel),
+ (Provider::Demio, demio),
+ (Provider::Butter, butter),
+];
+
+fn zoom(c: &Ctx) -> Option {
+ if !(c.host_under("zoom.us") || c.host_under("zoom.com") || c.host_under("zoomgov.com")) {
+ return None;
+ }
+ let numeric = |s: Option<&str>| s.filter(|s| is_digits(s, 9, 12)).map(str::to_string);
+ match c.seg_lower(0)?.as_str() {
+ "j" | "w" | "s" => numeric(c.seg(1)).and_then(|id| hit(Some(id))),
+ "my" => c
+ .seg(1)
+ .filter(|s| is_slug(&s.replace('.', "")))
+ .and_then(|_| hit(None)),
+ "wc" => {
+ let id = match (c.seg(1), c.seg(2)) {
+ (Some("join"), id) => numeric(id),
+ (id, Some("join" | "start")) => numeric(id),
+ _ => None,
+ }?;
+ hit(Some(id))
+ }
+ "meeting" | "webinar" if c.seg(1) == Some("register") && c.seg(2).is_some() => hit(None),
+ "join" => {
+ let id = c.param("confno").filter(|s| is_digits(s, 9, 12))?;
+ hit(Some(id))
+ }
+ _ => None,
+ }
+}
+
+fn is_meet_code(s: &str) -> bool {
+ let parts: Vec<&str> = s.split('-').collect();
+ parts.len() == 3
+ && parts[0].len() == 3
+ && parts[1].len() == 4
+ && parts[2].len() == 3
+ && parts
+ .iter()
+ .all(|p| p.bytes().all(|b| b.is_ascii_alphabetic()))
+}
+
+fn google_meet(c: &Ctx) -> Option {
+ if c.host_is("meet.google.com") {
+ let first = c.seg_lower(0)?;
+ if is_meet_code(&first) {
+ return hit(Some(first));
+ }
+ if first == "lookup" {
+ return c.seg(1).filter(|s| is_slug(s)).and_then(|_| hit(None));
+ }
+ return None;
+ }
+ if (c.host_is("hangouts.google.com") || c.host_is("plus.google.com"))
+ && c.seg(0) == Some("hangouts")
+ && c.seg(1) == Some("_")
+ && c.segs.len() >= 3
+ {
+ return hit(None);
+ }
+ if c.host_is("hangouts.google.com") && c.seg(0) == Some("call") && c.seg(1).is_some() {
+ return hit(c.seg(1).map(str::to_string));
+ }
+ None
+}
+
+const TEAMS_HOSTS: [&str; 6] = [
+ "teams.microsoft.com",
+ "teams.live.com",
+ "teams.cloud.microsoft",
+ "teams.microsoft.us",
+ "gov.teams.microsoft.us",
+ "dod.teams.microsoft.us",
+];
+
+fn teams_path(segs: &[&str]) -> Option