PlanOpticon

planopticon / video_processor / sources / teams_recording_source.py
Source Blame History 375 lines
0981a08… noreply 1 """Microsoft Teams meeting recording source using the m365 CLI.
0981a08… noreply 2
0981a08… noreply 3 Fetches Teams meeting recordings and transcripts via the Microsoft Graph API
0981a08… noreply 4 through the `m365` CLI tool.
0981a08… noreply 5
0981a08… noreply 6 Requires: npm install -g @pnp/cli-microsoft365
0981a08… noreply 7 Auth: m365 login (interactive)
0981a08… noreply 8 Docs: https://pnp.github.io/cli-microsoft365/
0981a08… noreply 9 """
0981a08… noreply 10
0981a08… noreply 11 import logging
0981a08… noreply 12 import re
0981a08… noreply 13 import shutil
0981a08… noreply 14 import subprocess
0981a08… noreply 15 from pathlib import Path
0981a08… noreply 16 from typing import List, Optional
0981a08… noreply 17
0981a08… noreply 18 from video_processor.sources.base import BaseSource, SourceFile
0981a08… noreply 19 from video_processor.sources.m365_source import _run_m365
0981a08… noreply 20
0981a08… noreply 21 logger = logging.getLogger(__name__)
0981a08… noreply 22
0981a08… noreply 23
0981a08… noreply 24 def _vtt_to_text(vtt: str) -> str:
0981a08… noreply 25 """Strip VTT timing metadata and return plain text.
0981a08… noreply 26
0981a08… noreply 27 Removes WEBVTT headers, timestamps (00:00:00.000 --> 00:00:05.000),
0981a08… noreply 28 cue identifiers, and deduplicates consecutive identical lines.
0981a08… noreply 29 """
0981a08… noreply 30 lines = vtt.splitlines()
0981a08… noreply 31 text_lines: list[str] = []
0981a08… noreply 32 prev_line = ""
0981a08… noreply 33
0981a08… noreply 34 for line in lines:
0981a08… noreply 35 stripped = line.strip()
0981a08… noreply 36 # Skip WEBVTT header and NOTE blocks
0981a08… noreply 37 if stripped.startswith("WEBVTT") or stripped.startswith("NOTE"):
0981a08… noreply 38 continue
0981a08… noreply 39 # Skip timestamp lines (e.g. 00:00:01.000 --> 00:00:05.000)
0981a08… noreply 40 if re.match(r"\d{2}:\d{2}[:\.][\d.]+ --> \d{2}:\d{2}[:\.][\d.]+", stripped):
0981a08… noreply 41 continue
0981a08… noreply 42 # Skip numeric cue identifiers
0981a08… noreply 43 if re.match(r"^\d+$", stripped):
0981a08… noreply 44 continue
0981a08… noreply 45 # Skip blank lines
0981a08… noreply 46 if not stripped:
0981a08… noreply 47 continue
0981a08… noreply 48 # Strip inline VTT tags like <v Speaker>
0981a08… noreply 49 cleaned = re.sub(r"<[^>]+>", "", stripped).strip()
0981a08… noreply 50 if cleaned and cleaned != prev_line:
0981a08… noreply 51 text_lines.append(cleaned)
0981a08… noreply 52 prev_line = cleaned
0981a08… noreply 53
0981a08… noreply 54 return "\n".join(text_lines)
0981a08… noreply 55
0981a08… noreply 56
0981a08… noreply 57 class TeamsRecordingSource(BaseSource):
0981a08… noreply 58 """
0981a08… noreply 59 Fetch Teams meeting recordings and transcripts via the m365 CLI / Graph API.
0981a08… noreply 60
0981a08… noreply 61 Usage:
0981a08… noreply 62 source = TeamsRecordingSource(user_id="me")
0981a08… noreply 63 source.authenticate()
0981a08… noreply 64 recordings = source.list_videos()
0981a08… noreply 65 source.download_all(recordings, Path("./recordings"))
0981a08… noreply 66
0981a08… noreply 67 # Fetch transcript for a specific meeting
0981a08… noreply 68 transcript = source.fetch_transcript(meeting_id)
0981a08… noreply 69 """
0981a08… noreply 70
0981a08… noreply 71 def __init__(self, user_id: str = "me"):
0981a08… noreply 72 self.user_id = user_id
0981a08… noreply 73
0981a08… noreply 74 def authenticate(self) -> bool:
0981a08… noreply 75 """Check if m365 CLI is installed and logged in."""
0981a08… noreply 76 if not shutil.which("m365"):
0981a08… noreply 77 logger.error("m365 CLI not found. Install with: npm install -g @pnp/cli-microsoft365")
0981a08… noreply 78 return False
0981a08… noreply 79 try:
0981a08… noreply 80 result = _run_m365(["status"], timeout=10)
0981a08… noreply 81 if isinstance(result, dict) and result.get("connectedAs"):
0981a08… noreply 82 return True
0981a08… noreply 83 if isinstance(result, str) and "Logged in" in result:
0981a08… noreply 84 return True
0981a08… noreply 85 logger.error("m365 not logged in. Run: m365 login")
0981a08… noreply 86 return False
0981a08… noreply 87 except (RuntimeError, subprocess.TimeoutExpired):
0981a08… noreply 88 logger.error("m365 not logged in. Run: m365 login")
0981a08… noreply 89 return False
0981a08… noreply 90
0981a08… noreply 91 def list_videos(
0981a08… noreply 92 self,
0981a08… noreply 93 folder_id: Optional[str] = None,
0981a08… noreply 94 folder_path: Optional[str] = None,
0981a08… noreply 95 patterns: Optional[List[str]] = None,
0981a08… noreply 96 ) -> List[SourceFile]:
0981a08… noreply 97 """List Teams meeting recordings available for the user.
0981a08… noreply 98
0981a08… noreply 99 Tries multiple approaches:
0981a08… noreply 100 1. Graph API onlineMeetings endpoint
0981a08… noreply 101 2. m365 teams meeting list command
0981a08… noreply 102 3. Fallback: search chat messages for recording links
0981a08… noreply 103 """
0981a08… noreply 104 files: List[SourceFile] = []
0981a08… noreply 105
0981a08… noreply 106 # Approach 1: Graph API — list online meetings
0981a08… noreply 107 try:
0981a08… noreply 108 result = _run_m365(
0981a08… noreply 109 [
0981a08… noreply 110 "request",
0981a08… noreply 111 "--url",
0981a08… noreply 112 f"https://graph.microsoft.com/v1.0/{self.user_id}/onlineMeetings",
0981a08… noreply 113 "--method",
0981a08… noreply 114 "get",
0981a08… noreply 115 ],
0981a08… noreply 116 timeout=60,
0981a08… noreply 117 )
0981a08… noreply 118 meetings = self._extract_meetings_list(result)
0981a08… noreply 119 for meeting in meetings:
0981a08… noreply 120 recording_files = self._get_meeting_recordings(meeting)
0981a08… noreply 121 files.extend(recording_files)
0981a08… noreply 122
0981a08… noreply 123 if files:
0981a08… noreply 124 logger.info(f"Found {len(files)} recording(s) via Graph API onlineMeetings")
0981a08… noreply 125 return files
0981a08… noreply 126 except RuntimeError as e:
0981a08… noreply 127 logger.debug(f"onlineMeetings endpoint failed: {e}")
0981a08… noreply 128
0981a08… noreply 129 # Approach 2: m365 teams meeting list
0981a08… noreply 130 try:
0981a08… noreply 131 result = _run_m365(["teams", "meeting", "list"], timeout=60)
0981a08… noreply 132 meetings = result if isinstance(result, list) else []
0981a08… noreply 133 for meeting in meetings:
0981a08… noreply 134 recording_files = self._get_meeting_recordings(meeting)
0981a08… noreply 135 files.extend(recording_files)
0981a08… noreply 136
0981a08… noreply 137 if files:
0981a08… noreply 138 logger.info(f"Found {len(files)} recording(s) via m365 teams meeting list")
0981a08… noreply 139 return files
0981a08… noreply 140 except RuntimeError as e:
0981a08… noreply 141 logger.debug(f"teams meeting list failed: {e}")
0981a08… noreply 142
0981a08… noreply 143 # Approach 3: Fallback — search chat messages for recording links
0981a08… noreply 144 try:
0981a08… noreply 145 result = _run_m365(
0981a08… noreply 146 [
0981a08… noreply 147 "request",
0981a08… noreply 148 "--url",
0981a08… noreply 149 (
0981a08… noreply 150 f"https://graph.microsoft.com/v1.0/{self.user_id}/chats"
0981a08… noreply 151 "?$expand=messages($top=50)"
0981a08… noreply 152 "&$filter=chatType eq 'meeting'"
0981a08… noreply 153 "&$top=25"
0981a08… noreply 154 ),
0981a08… noreply 155 "--method",
0981a08… noreply 156 "get",
0981a08… noreply 157 ],
0981a08… noreply 158 timeout=60,
0981a08… noreply 159 )
0981a08… noreply 160 chats = self._extract_value_list(result)
0981a08… noreply 161 for chat in chats:
0981a08… noreply 162 messages = chat.get("messages", [])
0981a08… noreply 163 for msg in messages:
0981a08… noreply 164 body = msg.get("body", {}).get("content", "")
0981a08… noreply 165 if "recording" in body.lower() or ".mp4" in body.lower():
0981a08… noreply 166 topic = chat.get("topic", "Meeting Recording")
0981a08… noreply 167 chat_id = chat.get("id", "")
0981a08… noreply 168 msg_id = msg.get("id", "")
0981a08… noreply 169 files.append(
0981a08… noreply 170 SourceFile(
0981a08… noreply 171 name=f"{topic}.mp4",
0981a08… noreply 172 id=f"{chat_id}:{msg_id}",
0981a08… noreply 173 mime_type="video/mp4",
0981a08… noreply 174 modified_at=msg.get("createdDateTime"),
0981a08… noreply 175 )
0981a08… noreply 176 )
0981a08… noreply 177 if files:
0981a08… noreply 178 logger.info(f"Found {len(files)} recording link(s) in meeting chats")
0981a08… noreply 179 except RuntimeError as e:
0981a08… noreply 180 logger.debug(f"Chat message fallback failed: {e}")
0981a08… noreply 181
0981a08… noreply 182 if not files:
0981a08… noreply 183 logger.warning("No Teams meeting recordings found")
0981a08… noreply 184
0981a08… noreply 185 return files
0981a08… noreply 186
0981a08… noreply 187 def download(self, file: SourceFile, destination: Path) -> Path:
0981a08… noreply 188 """Download a recording via its Graph API download URL."""
0981a08… noreply 189 destination = Path(destination)
0981a08… noreply 190 destination.parent.mkdir(parents=True, exist_ok=True)
0981a08… noreply 191
0981a08… noreply 192 download_url = file.path
0981a08… noreply 193 if download_url:
0981a08… noreply 194 # Use the direct download URL from contentUrl / @microsoft.graph.downloadUrl
0981a08… noreply 195 _run_m365(
0981a08… noreply 196 [
0981a08… noreply 197 "request",
0981a08… noreply 198 "--url",
0981a08… noreply 199 download_url,
0981a08… noreply 200 "--method",
0981a08… noreply 201 "get",
0981a08… noreply 202 "--filePath",
0981a08… noreply 203 str(destination),
0981a08… noreply 204 ],
0981a08… noreply 205 timeout=300,
0981a08… noreply 206 )
0981a08… noreply 207 else:
0981a08… noreply 208 # Try to get download URL from the recording ID
0981a08… noreply 209 meeting_id, _, recording_id = file.id.partition(":")
0981a08… noreply 210 if recording_id:
0981a08… noreply 211 url = (
0981a08… noreply 212 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 213 f"/onlineMeetings/{meeting_id}"
0981a08… noreply 214 f"/recordings/{recording_id}/content"
0981a08… noreply 215 )
0981a08… noreply 216 else:
0981a08… noreply 217 url = (
0981a08… noreply 218 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 219 f"/onlineMeetings/{meeting_id}/recordings"
0981a08… noreply 220 )
0981a08… noreply 221 # Fetch recording list to find the content URL
0981a08… noreply 222 result = _run_m365(
0981a08… noreply 223 ["request", "--url", url, "--method", "get"],
0981a08… noreply 224 timeout=60,
0981a08… noreply 225 )
0981a08… noreply 226 recordings = self._extract_value_list(result)
0981a08… noreply 227 if recordings:
0981a08… noreply 228 url = (
0981a08… noreply 229 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 230 f"/onlineMeetings/{meeting_id}"
0981a08… noreply 231 f"/recordings/{recordings[0].get('id', '')}/content"
0981a08… noreply 232 )
0981a08… noreply 233
0981a08… noreply 234 _run_m365(
0981a08… noreply 235 [
0981a08… noreply 236 "request",
0981a08… noreply 237 "--url",
0981a08… noreply 238 url,
0981a08… noreply 239 "--method",
0981a08… noreply 240 "get",
0981a08… noreply 241 "--filePath",
0981a08… noreply 242 str(destination),
0981a08… noreply 243 ],
0981a08… noreply 244 timeout=300,
0981a08… noreply 245 )
0981a08… noreply 246
0981a08… noreply 247 logger.info(f"Downloaded {file.name} to {destination}")
0981a08… noreply 248 return destination
0981a08… noreply 249
0981a08… noreply 250 def fetch_transcript(self, meeting_id: str) -> Optional[str]:
0981a08… noreply 251 """Fetch the transcript for a Teams meeting.
0981a08… noreply 252
0981a08… noreply 253 Queries the Graph API transcripts endpoint, downloads the transcript
0981a08… noreply 254 content, and converts VTT format to plain text.
0981a08… noreply 255 """
0981a08… noreply 256 try:
0981a08… noreply 257 result = _run_m365(
0981a08… noreply 258 [
0981a08… noreply 259 "request",
0981a08… noreply 260 "--url",
0981a08… noreply 261 (
0981a08… noreply 262 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 263 f"/onlineMeetings/{meeting_id}/transcripts"
0981a08… noreply 264 ),
0981a08… noreply 265 "--method",
0981a08… noreply 266 "get",
0981a08… noreply 267 ],
0981a08… noreply 268 timeout=60,
0981a08… noreply 269 )
0981a08… noreply 270 except RuntimeError as e:
0981a08… noreply 271 logger.warning(f"Failed to list transcripts for meeting {meeting_id}: {e}")
0981a08… noreply 272 return None
0981a08… noreply 273
0981a08… noreply 274 transcripts = self._extract_value_list(result)
0981a08… noreply 275 if not transcripts:
0981a08… noreply 276 logger.info(f"No transcripts found for meeting {meeting_id}")
0981a08… noreply 277 return None
0981a08… noreply 278
0981a08… noreply 279 # Download the first available transcript
0981a08… noreply 280 transcript_id = transcripts[0].get("id", "")
0981a08… noreply 281 try:
0981a08… noreply 282 content_result = _run_m365(
0981a08… noreply 283 [
0981a08… noreply 284 "request",
0981a08… noreply 285 "--url",
0981a08… noreply 286 (
0981a08… noreply 287 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 288 f"/onlineMeetings/{meeting_id}"
0981a08… noreply 289 f"/transcripts/{transcript_id}/content"
0981a08… noreply 290 ),
0981a08… noreply 291 "--method",
0981a08… noreply 292 "get",
0981a08… noreply 293 "--accept",
0981a08… noreply 294 "text/vtt",
0981a08… noreply 295 ],
0981a08… noreply 296 timeout=60,
0981a08… noreply 297 )
0981a08… noreply 298 except RuntimeError as e:
0981a08… noreply 299 logger.warning(f"Failed to download transcript {transcript_id}: {e}")
0981a08… noreply 300 return None
0981a08… noreply 301
0981a08… noreply 302 # content_result may be raw VTT text or a dict with raw key
0981a08… noreply 303 if isinstance(content_result, dict):
0981a08… noreply 304 raw = content_result.get("raw", "")
0981a08… noreply 305 else:
0981a08… noreply 306 raw = str(content_result)
0981a08… noreply 307
0981a08… noreply 308 if not raw:
0981a08… noreply 309 logger.warning(f"Empty transcript content for meeting {meeting_id}")
0981a08… noreply 310 return None
0981a08… noreply 311
0981a08… noreply 312 return _vtt_to_text(raw)
0981a08… noreply 313
0981a08… noreply 314 # ------------------------------------------------------------------
0981a08… noreply 315 # Internal helpers
0981a08… noreply 316 # ------------------------------------------------------------------
0981a08… noreply 317
0981a08… noreply 318 def _extract_meetings_list(self, result) -> list:
0981a08… noreply 319 """Extract meetings list from Graph API response."""
0981a08… noreply 320 if isinstance(result, list):
0981a08… noreply 321 return result
0981a08… noreply 322 if isinstance(result, dict):
0981a08… noreply 323 return result.get("value", [])
0981a08… noreply 324 return []
0981a08… noreply 325
0981a08… noreply 326 def _extract_value_list(self, result) -> list:
0981a08… noreply 327 """Extract value list from a Graph API response."""
0981a08… noreply 328 if isinstance(result, list):
0981a08… noreply 329 return result
0981a08… noreply 330 if isinstance(result, dict):
0981a08… noreply 331 return result.get("value", [])
0981a08… noreply 332 return []
0981a08… noreply 333
0981a08… noreply 334 def _get_meeting_recordings(self, meeting: dict) -> List[SourceFile]:
0981a08… noreply 335 """Fetch recordings for a single meeting and return SourceFile entries."""
0981a08… noreply 336 meeting_id = meeting.get("id", "")
0981a08… noreply 337 subject = meeting.get("subject", meeting.get("topic", "Teams Meeting"))
0981a08… noreply 338 start_time = meeting.get("startDateTime", meeting.get("createdDateTime"))
0981a08… noreply 339
0981a08… noreply 340 if not meeting_id:
0981a08… noreply 341 return []
0981a08… noreply 342
0981a08… noreply 343 try:
0981a08… noreply 344 result = _run_m365(
0981a08… noreply 345 [
0981a08… noreply 346 "request",
0981a08… noreply 347 "--url",
0981a08… noreply 348 (
0981a08… noreply 349 f"https://graph.microsoft.com/v1.0/{self.user_id}"
0981a08… noreply 350 f"/onlineMeetings/{meeting_id}/recordings"
0981a08… noreply 351 ),
0981a08… noreply 352 "--method",
0981a08… noreply 353 "get",
0981a08… noreply 354 ],
0981a08… noreply 355 timeout=60,
0981a08… noreply 356 )
0981a08… noreply 357 except RuntimeError:
0981a08… noreply 358 return []
0981a08… noreply 359
0981a08… noreply 360 recordings = self._extract_value_list(result)
0981a08… noreply 361 files: List[SourceFile] = []
0981a08… noreply 362 for rec in recordings:
0981a08… noreply 363 rec_id = rec.get("id", "")
0981a08… noreply 364 download_url = rec.get("content.downloadUrl", rec.get("contentUrl"))
0981a08… noreply 365 files.append(
0981a08… noreply 366 SourceFile(
0981a08… noreply 367 name=f"{subject}.mp4",
0981a08… noreply 368 id=f"{meeting_id}:{rec_id}",
0981a08… noreply 369 mime_type="video/mp4",
0981a08… noreply 370 modified_at=start_time,
0981a08… noreply 371 path=download_url,
0981a08… noreply 372 )
0981a08… noreply 373 )
0981a08… noreply 374
0981a08… noreply 375 return files

Keyboard Shortcuts

Open search /
Next entry (timeline) j
Previous entry (timeline) k
Open focused entry Enter
Show this help ?
Toggle theme Top nav button