-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathGet-MicrosoftTeamsChat.ps1
320 lines (263 loc) · 16.6 KB
/
Get-MicrosoftTeamsChat.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
#Requires -Version 7.0
<#
.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 clientId
The client id of the Azure AD App Registration.
.PARAMETER tenantId
The domain name of the UPNs for users in your tenant. E.g. contoso.com.
.PARAMETER domain
The heritage tenant, Readify or Kloud.
.EXAMPLE
.\Get-MicrosoftTeamChat.ps1 -ExportFolder "D:\ExportedHTML" -clientId "ClientIDforAzureADAppRegistration" -tenantId "TenantIdoftheAADOrg" -domain "contoso.com"
.NOTES
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 = $true, HelpMessage = "Export location of where the HTML files will be saved.")] [string] $ExportFolder,
[Parameter(Mandatory = $true, HelpMessage = "The client id of the Azure AD App Registration")] [string] $clientId,
[Parameter(Mandatory = $true, HelpMessage = "The tenant id of the Azure AD environment the user logs into")] [string] $tenantId,
[Parameter(Mandatory = $true, HelpMessage = "The domain name of the UPNs for users in your tenant. E.g. contoso.com")] [string] $domain
)
#################################
## Import Modules ##
#################################
Set-Location $PSScriptRoot
Import-Module ($PSScriptRoot + "/functions/TelstraPurpleFunctions") -Force
Get-TPASCII
####################################
## HTML ##
####################################
$HTML = Get-Content -Raw ./files/chat.html
$HTMLMessagesBlock_them = @"
<div class="message-container">
<div class="message">
<div style="display:flex; margin-top:10px">
<div style="flex:none; overflow:hidden; border-radius:50%; height:42px; width:42px; margin:10px">
<img height="42" src="###IMAGE###" style="vertical-align:top; width:42px; height:42px;" width="42">
</div>
<div class="them" style="flex:1; overflow:hidden;">
<div style="font-size:1.2rem; white-space:nowrap; text-overflow:ellipsis; overflow:hidden;">
<span style="font-weight:700;">###NAME###</span><span style="margin-left:1rem;">###DATE###</span>
</div>
<div>
###CONVERSATION###
</div>
###ATTACHMENT###
</div>
</div>
</div>
</div>
"@
$HTMLMessagesBlock_me = @"
<div class="message-container">
<div class="message">
<div style="display:flex; margin-top:10px">
<div class="me" style="flex:1; overflow:hidden;">
<div style="font-size:1.2rem; white-space:nowrap; text-overflow:ellipsis; overflow:hidden;">
<span style="font-weight:700;">###NAME###</span><span style="margin-left:1rem;">###DATE###</span>
</div>
<div>
###CONVERSATION###
</div>
###ATTACHMENT###
</div>
<div style="flex:none; overflow:hidden; border-radius:50%; height:42px; width:42px; margin:10px">
<img height="42" src="###IMAGE###" style="vertical-align:top; width:42px; height:42px;" width="42">
</div>
</div>
</div>
</div>
"@
$HTMLAttachmentBlock = @"
<div class="attachment">
<a href="###ATTACHEMENTURL###" target="_blank">###ATTACHEMENTNAME###</a>
</div>
"@
#Script
Write-Host -ForegroundColor Cyan "`r`nStarting script..."
Write-Host -ForegroundColor White "`r`nSign in with the Device Code to the app registration:"
$tokenOutput = Connect-DeviceCodeAPI $clientId $tenantId $null
$token = $tokenOutput.access_token
$refresh_token = $tokenOutput.refresh_token
$ImagesFolder = Join-Path -Path $ExportFolder -ChildPath 'images'
if (-not(Test-Path -Path $ImagesFolder)) { New-Item -ItemType Directory -Path $ImagesFolder | Out-Null }
$ExportFolder = (Resolve-Path -Path $ExportFolder).ToString()
$accessToken = ConvertTo-SecureString $token -AsPlainText -Force
$me = Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/me" -Authentication OAuth -Token $accessToken
$allChats = @();
$firstChat = Invoke-RestMethod -Method Get -Uri "https://graph.microsoft.com/v1.0/me/chats" -Authentication OAuth -Token $accessToken
$allChats += $firstChat
$allChatsCount = $firstChat.'@odata.count'
Write-Host ("`r`nGetting all chats, please wait... This may take some time.`r`n")
if ($null -ne $firstChat.'@odata.nextLink') {
$chatNextLink = $firstChat.'@odata.nextLink'
do {
$chatsToAdd = Invoke-RestMethod -Method Get -Uri $chatNextLink -Authentication OAuth -Token $accessToken
$allChats += $chatsToAdd
$chatNextLink = $chatsToAdd.'@odata.nextLink'
$allChatsCount = $allChatsCount + $chatsToAdd.'@odata.count'
} until ($null -eq $chatsToAdd.'@odata.nextLink' )
}
$chats = $allChats.value | Sort-Object createdDateTime -Descending
Write-Host ("`r`n" + $chats.count + " possible chat threads found.`r`n")
$threadCount = 0
$StartTime = Get-Date
foreach ($thread in $chats) {
#50 is the maximum allowed with the beta api
$conversationUri = "https://graph.microsoft.com/v1.0/me/chats/" + $thread.id + "/messages?top=50"
$elapsedTime = (Get-Date) - $StartTime
Write-Verbose ("Script running for " + $elapsedTime.TotalSeconds + " seconds.")
if ($elapsedTime.TotalMinutes -gt 30) {
Write-Host -ForegroundColor Cyan "Reauthenticating with refresh token..."
$tokenOutput = Connect-DeviceCodeAPI $clientId $tenantId $refresh_token
$token = $tokenOutput.access_token
$refresh_token = $tokenOutput.refresh_token
$accessToken = ConvertTo-SecureString $token -AsPlainText -Force
$StartTime = $(Get-Date)
Start-Sleep 5
}
$name = Get-Random;
if ($null -ne $thread.topic) {
$name = $thread.topic
}
else {
$membersUri = "https://graph.microsoft.com/v1.0/me/chats/" + $thread.id + "/members"
$members = Invoke-RestMethod -Method Get -Uri $membersUri -Authentication OAuth -Token $accessToken
$members = $members.value.displayName | Where-Object { $_ -notlike "*@purple.telstra.com" }
$name = ($members | Where-Object { $_ -notmatch $me.displayName } | Select-Object -Unique) -join ", "
}
$allConversations = @();
try {
$firstConversation = Invoke-RestMethod -Method Get -Uri $conversationUri -Authentication OAuth -Token $accessToken
$allConversations += $firstConversation
$allConversationsCount = $firstConversation.'@odata.count'
}
catch {
Write-Host ($name + " :: Could not download historical messages.")
Write-Host -ForegroundColor Yellow "Skipping...`r`n"
}
if ($null -ne $firstConversation.'@odata.nextLink') {
$conversationNextLink = $firstConversation.'@odata.nextLink'
do {
$conversationToAdd = Invoke-RestMethod -Method Get -Uri $conversationNextLink -Authentication OAuth -Token $accessToken
$allConversations += $conversationToAdd
$conversationNextLink = $conversationToAdd.'@odata.nextLink'
$allConversationsCount = $allConversationsCount + $conversationToAdd.'@odata.count'
} until ($null -eq $conversationToAdd.'@odata.nextLink')
}
$conversation = $allConversations.value | Sort-Object createdDateTime
$threadCount++
$messagesHTML = $null
if (($conversation.count -gt 0) -and (-not([string]::isNullorEmpty($name)))) {
Write-Host -ForegroundColor White ($name + " :: " + $allConversationsCount + " messages.")
Write-Verbose $conversationUri
foreach ($message in $conversation) {
$userPhotoUPN = ($message.from.user.displayName -replace " ", ".") + "@" + $domain
$profilefile = Join-Path -Path $ImagesFolder -ChildPath "$userPhotoUPN.jpg"
if (-not(Test-Path $profilefile)) {
$profilePhotoUri = "https://graph.microsoft.com/v1.0/users/" + $userPhotoUPN + "/photos/96x96/`$value"
$pictureURL = ("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCADIAMgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD8qqKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACii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j9FAH1L/w8/8A2m/+inP/AOCTTf8A5Go/4ef/ALTf/RTn/wDBJpv/AMjV8tUUAfUv/Dz/APab/wCinP8A+CTTf/kaj/h5/wDtN/8ARTn/APBJpv8A8jV8tUUAewfGr9rr4tftEaLYaT8QvFreIdPsJzc28J0+1t9khXaWzDEhPHYkivH6KKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//2Q==")
try {
Invoke-WebRequest -Uri $profilePhotoUri -Authentication OAuth -Token $accessToken -OutFile $profilefile
$pictureURL = Get-EncodedImage $profilefile
}
catch {
}
}
else {
$pictureURL = Get-EncodedImage $profilefile
}
$messageBody = $message.body.content
if ($messageBody -match "<img.+?src=[\`"']https:\/\/graph.microsoft.com(.+?)[\`"'].*?>") {
$imagecount = 0
foreach ($imgMatch in $Matches) {
$imagecount++
$threadidIO = $thread.id.Split([IO.Path]::GetInvalidFileNameChars()) -join '_'
$imagefile = Join-Path -Path $ImagesFolder -ChildPath "$threadidIO$imagecount.jpg"
$imageUri = "https://graph.microsoft.com" + $imgMatch[1]
Write-Host "Downloading embedded image in message..."
Write-Verbose $imageUri
$retries = 0
$limit = 5
$completed = $false
while (-not $completed) {
try {
$response = Invoke-WebRequest -Uri $imageUri -Authentication OAuth -Token $accessToken
Set-Content -Path $imagefile -AsByteStream -Value $response.Content
$imageencoded = Get-EncodedImage $imagefile
$messageBody = $messageBody.Replace($imgMatch[0], ("<a href=`"" + $imageencoded + "`" download>" + $imgMatch[0] + "</a>"))
$messageBody = $messageBody.Replace($imageUri, $imageencoded)
if ($response.StatusCode -ne 200) {
throw "Expecting reponse code 200, was: $($response.StatusCode)"
}
$completed = $true
}
catch {
if ($retries -ge $limit) {
Write-Warning "Request to $imageUri failed the maximum number of $limit times."
$completed = $true
}
else {
Write-Warning "Request to $imageUri failed. Retrying in 5 seconds."
Start-Sleep 5
$retries++
}
}
}
}
}
$time = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date ($message.createdDateTime)), (Get-TimeZone).Id)
$time = Get-Date $time -Format "dd MMMM yyyy, hh:mm tt"
if ($message.from.user.displayName -eq $me.displayName) {
$HTMLMessagesBlock = $HTMLMessagesBlock_me
}
else {
$HTMLMessagesBlock = $HTMLMessagesBlock_them
}
if ($null -ne $message.attachment) {
$attachmentHTML = $HTMLAttachmentBlock `
-Replace "###ATTACHEMENTURL###", $message.attachment.name`
-Replace "###ATTACHEMENTNAME###", $message.attachment.contentURL`
-Replace "###IMAGE###", $pictureURL
$messagesHTML += $HTMLMessagesBlock `
-Replace "###NAME###", $message.from.user.displayName`
-Replace "###CONVERSATION###", $messageBody`
-Replace "###DATE###", $time`
-Replace "###ATTACHMENT###", $attachmentHTML`
-Replace "###IMAGE###", $pictureURL
}
else {
$messagesHTML += $HTMLMessagesBlock `
-Replace "###NAME###", $message.from.user.displayName`
-Replace "###CONVERSATION###", $messageBody`
-Replace "###DATE###", $time`
-Replace "###ATTACHMENT###", $null`
-Replace "###IMAGE###", $pictureURL
}
}
$HTMLfile = $HTML `
-Replace "###MESSAGES###", $messagesHTML`
-Replace "###CHATNAME###", $name`
$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 (Test-Path $file) { $file = ($file -Replace ".html", ( "(" + $threadCount + ")" + ".html")) }
Write-Host -ForegroundColor Green "Exporting $file... `r`n"
$HTMLfile | Out-File -FilePath $file
}
else {
Write-Host ($name + " :: No messages found.")
Write-Host -ForegroundColor Yellow "Skipping...`r`n"
}
}
Remove-Item -Path $ImagesFolder -Recurse
Write-Host -ForegroundColor Cyan "`r`nScript completed... Bye!"