forked from evenevan/export-ms-teams-chats
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGet-MicrosoftTeamsChat.ps1
More file actions
229 lines (173 loc) · 10.2 KB
/
Get-MicrosoftTeamsChat.ps1
File metadata and controls
229 lines (173 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
#Requires -Version 5.1
<#
.SYNOPSIS
Exports Microsoft Chat History
.DESCRIPTION
This script reads the Microsoft Graph API and exports of chat history into HTML files in a location you specify.
.PARAMETER exportFolder
Export location of where the HTML files will be saved. For example, "D:\ExportedHTML\"
.PARAMETER toExport
If specified, only group chats this string (exact match) will be exported
.PARAMETER avoidOverwrite
If a chat with the same file name already exists, this will create the new file with a number at the end instead (such as (1))
.PARAMETER clientId
The client id of the Azure AD App Registration.
.PARAMETER tenantId
The tenant id. See https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc#find-your-apps-openid-configuration-document-uri for possible tenants.
.EXAMPLE
.\Get-MicrosoftTeamsChat.ps1 -exportFolder "D:\ExportedHTML" -clientId "31359c7f-bd7e-475c-86db-fdb8c937548e" -tenantId "contoso.onmicrosoft.com" -skipIds '19:c968a252f5dc4310bd6714883389dcfe@thread.v2'
.NOTES
Original Author: Trent Steenholdt
Pre-requisites: An app registration with delegated User.Read, Chat.Read and User.ReadBasic. All permissions is needed in the Azure AD tenant you're connecting to.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory = $false, HelpMessage = "Export location of where the HTML files will be saved.")] [string] $exportFolder = "out",
[Parameter(Mandatory = $false, HelpMessage = "If specified, only chats named (exact match) will be exported")] [string[]] $toExport = $null,
[Parameter(Mandatory = $false, HelpMessage = "Any chat IDs specified will be skipped")] [string[]] $skipIds = @(),
[Parameter(Mandatory = $false, HelpMessage = "If a chat with the same file name already exists, this will create the new file with a number at the end instead (such as (1))")] [switch] $avoidOverwrite,
[Parameter(Mandatory = $false, HelpMessage = "The client id of the Azure AD App Registration")] [string] $clientId = "7f586887-37d3-4d1f-89cf-153c7d1bbe54",
[Parameter(Mandatory = $false, HelpMessage = "The tenant id of the Azure AD environment the user logs into")] [string] $tenantId = "organizations"
)
#################################
## Import Modules ##
#################################
Set-Location $PSScriptRoot
$verbose = $PSBoundParameters["verbose"]
Get-ChildItem "$PSScriptRoot/functions/chat/*.psm1" | ForEach-Object { Import-Module $_.FullName -Force -ArgumentList $verbose }
Get-ChildItem "$PSScriptRoot/functions/message/*.psm1" | ForEach-Object { Import-Module $_.FullName -Force -ArgumentList $verbose }
Get-ChildItem "$PSScriptRoot/functions/user/*.psm1" | ForEach-Object { Import-Module $_.FullName -Force -ArgumentList $verbose }
Get-ChildItem "$PSScriptRoot/functions/util/*.psm1" | ForEach-Object { Import-Module $_.FullName -Force -Global -ArgumentList $verbose }
####################################
## HTML ##
####################################
$chatHTMLTemplate = Get-Content -Raw ./assets/chat.html
$messageHTMLTemplate = Get-Content -Raw ./assets/message.html
$stylesheetCSS = Get-Content -Raw ./assets/stylesheet.css
#Script
$start = Get-Date
Write-Host -ForegroundColor Cyan "Starting script..."
$assetsFolder = Join-Path -Path $exportFolder -ChildPath "assets"
if (-not(Test-Path -Path $assetsFolder)) { New-Item -ItemType Directory -Path $assetsFolder | Out-Null }
$exportFolder = (Resolve-Path -Path $exportFolder).ToString()
Write-Host "Your chats will be exported to $exportFolder."
$me = Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/me" -Headers @{
"Authorization" = "Bearer $(Get-GraphAccessToken $clientId $tenantId)"
}
Write-Host ("Getting all chats, please wait... This may take some time.")
$chats = Get-Chats $clientId $tenantId
Write-Host ("" + $chats.count + " possible chat chats found.")
$chatIndex = 0
foreach ($chat in $chats) {
Write-Progress -Activity "Exporting Chats" -Status "Chat $($chatIndex) of $($chats.count)" -PercentComplete $(($chatIndex / $chats.count) * 100)
$chatIndex += 1
Write-Verbose "Exporting $($chat.id)"
try {
$members = Get-Members $chat $clientId $tenantId
}
catch {
Write-Host ("Members could not resolved, continue...")
continue
}
$name = ConvertTo-ChatName $chat $members $me $clientId $tenantId
if ($null -ne $toExport -and $toExport -notcontains $name) {
Write-Host ("$name is not in chats to export ($($toExport -join ", ")), skipping...")
continue
}
if ($skipIds -contains $chat.id) {
Write-Host ("$name ($($chat.id)) is in the skip list, skipping...")
continue
}
$messages = Get-Messages $chat $clientId $tenantId
$messagesHTML = $null
if (($messages.count -gt 0) -and (-not([string]::isNullorEmpty($name)))) {
Write-Host -ForegroundColor White ("`r`n$name :: $($messages.count) messages.")
# download profile pictures for use later
if ($members.Count -le 10) {
Write-Host "Downloading profile pictures..."
foreach ($member in $members) {
Get-ProfilePicture $member.userId $assetsFolder $clientId $tenantId | Out-Null
}
} else {
Write-Host "Skipping profile picture download (more than 10 members)..."
}
Write-Host "Processing messages..."
foreach ($message in $messages) {
$profilePicture = Get-ProfilePicture $message.from.user.id $assetsFolder $clientId $tenantId
$time = ConvertTo-CleanDateTime $message.createdDateTime
switch ($message.messageType) {
"message" {
$messageBody = $message.body.content
$imageTagMatches = [Regex]::Matches($messageBody, "<img.+?src=[\`"']https:\/\/graph.microsoft.com(.+?)[\`"'].*?>")
foreach ($imageTagMatch in $imageTagMatches) {
Write-Verbose "Downloading embedded image in message..."
$imagePath = Get-Image $imageTagMatch $assetsFolder $clientId $tenantId
$messageBody = $messageBody.Replace($imageTagMatch.Groups[0], "<img src=`"$imagePath`" style=`"width: 100%;`" >")
}
$messageHTML = $messageHTMLTemplate
$messageHTML = $messageHTML.Replace("###ATTACHMENTS###", (ConvertTo-HTMLAttachments $message.attachments))
$messageHTML = $messageHTML.Replace("###CONVERSATION###", $messageBody)
$messageHTML = $messageHTML.Replace("###DATE###", $time)
$messageHTML = $messageHTML.Replace("###DELETED###", "$($null -ne $message.deletedDateTime)".ToLower())
$messageHTML = $messageHTML.Replace("###EDITED###", "$($null -ne $message.lastEditedDateTime)".ToLower())
$messageHTML = $messageHTML.Replace("###IMAGE###", $profilePicture)
$messageHTML = $messageHTML.Replace("###ME###", "$($message.from.user.displayName -eq $me.displayName)".ToLower())
$messageHTML = $messageHTML.Replace("###NAME###", (Get-Initiator $message.from clientId $tenantId))
$messageHTML = $messageHTML.Replace("###PRIORITY###", $message.importance)
$messagesHTML += $messageHTML
Break
}
"systemEventMessage" {
$messageHTML = $messageHTMLTemplate
$messageHTML = $messageHTML.Replace("###ATTACHMENTS###", $null)
$messageHTML = $messageHTML.Replace("###CONVERSATION###", (ConvertTo-SystemEventMessage $message.eventDetail $clientId $tenantId))
$messageHTML = $messageHTML.Replace("###DATE###", $time)
$messageHTML = $messageHTML.Replace("###DELETED###", $null)
$messageHTML = $messageHTML.Replace("###EDITED###", $null)
$messageHTML = $messageHTML.Replace("###IMAGE###", $profilePicture)
$messageHTML = $messageHTML.Replace("###ME###", "false")
$messageHTML = $messageHTML.Replace("###NAME###", "System Event")
$messageHTML = $messageHTML.Replace("###PRIORITY###", $message.importance)
$messagesHTML += $messageHTML
Break
}
Default {
Write-Warning "Unhandled message type: $($message.messageType)"
}
}
}
$chatHTML = $chatHTMLTemplate
$chatHTML = $chatHTML.Replace("###MESSAGES###", $messagesHTML)
$chatHTML = $chatHTML.Replace("###CHATNAME###", $name)
$chatHTML = $chatHTML.Replace("###STYLE###", $stylesheetCSS)
$name = $name.Split([IO.Path]::GetInvalidFileNameChars()) -join "_"
if ($name.length -gt 64) {
$name = $name.Substring(0, 64)
}
$file = Join-Path -Path $exportFolder -ChildPath "$name.html"
if ($chat.chatType -ne "oneOnOne") {
Write-Verbose "Chat is not oneOnOne, appending hash to end"
# add hash of chatId in case multiple chats have the same name or members
$chatIdStream = [IO.MemoryStream]::new([byte[]][char[]]$chat.id)
$chatIdShortHash = (Get-FileHash -InputStream $chatIdStream -Algorithm SHA256).Hash.Substring(0,8)
$file = $file.Replace(".html", ( " ($chatIdShortHash).html"))
}
if ($avoidOverwrite -eq $true) {
Write-Verbose "Avoid overwrite enabled, appending counter if file path is not unique"
$uniqueFile = $file
$counter = 1
while (Test-Path $uniqueFile) {
$uniqueFile = $file.Replace(".html", ( " ($counter).html"))
$counter++
}
$file = $uniqueFile
}
Write-Host -ForegroundColor Green "Exporting $file..."
$chatHTML | Out-File -LiteralPath $file
}
else {
Write-Host ("`r`n$name :: No messages found.")
Write-Host -ForegroundColor Yellow "Skipping..."
}
}
Write-Host -ForegroundColor Cyan "`r`nScript completed after $(((Get-Date) - $start).TotalSeconds)s... Bye!"