Public/export-ibCourse.ps1

function Export-ibMarkdown {
    [CmdletBinding()]param([Parameter(Mandatory)][string]$CourseCode,[Parameter(Mandatory)][string]$CacheFolder, [ValidateSet('Lecture','Complet')][string]$ExportProfile = 'Lecture')
    $StructureFile = Join-Path $CacheFolder "$CourseCode\structure.json"
    $CourseStructure = Get-Content $StructureFile -Raw -Encoding UTF8 | ConvertFrom-Json
    if ($ExportProfile -eq 'Lecture') {
        $KeepIntroduction = $false
        $KeepSummary = $false
        $KeepExercises = $false}
    else {
        $KeepIntroduction = $true
        $KeepSummary = $true
        $KeepExercises = $true}
    $OutputMarkdown = Join-Path $CacheFolder "$CourseCode-$ExportProfile.md"
    Write-Host "$($CourseStructure.LearningPaths.Count) Learning Paths trouvés"
    $AllContent = @()
    $FirstLearningPath = $true
    foreach ($LearningPath in $CourseStructure.LearningPaths) {
        Write-Host "[LP] $($LearningPath.Title)"
        if (-not $FirstLearningPath) {$AllContent += "`r`n`r`n\newpage`r`n`r`n"}
        $FirstLearningPath = $false
        $AllContent += "# $($LearningPath.Title)`r`n"
        $FirstModule = $true
        foreach ($Module in $LearningPath.Modules) {
            Write-Host " [MODULE] $($Module.Title)"
            if (-not $FirstModule) {$AllContent += "`r`n`r`n\newpage`r`n`r`n"}
            $FirstModule = $false
            $AllContent += "## $($Module.Title)`r`n"
            foreach ($Unit in $Module.Units) {
                $UnitTitle = $Unit.Title
                if (!$KeepIntroduction -and $UnitTitle.ToLower() -eq 'introduction') {
                    Write-Host " [Introduction ignorée]"
                    continue}
                if (!$KeepSummary -and $UnitTitle.ToLower() -eq 'summary') {
                    Write-Host " [Summary ignoré]"
                    continue}
                if (!$KeepExercises -and $UnitTitle.ToLower().StartsWith('exercise')) {
                    Write-Host " [Exercise ignoré]"
                    continue}
                Write-Host " $UnitTitle"
                try {
                    $UnitContent = Get-Content $Unit.File -Raw -Encoding UTF8
                    $Patterns = @('Completed\s*<br><br>\s*~\s*\d+\s*minutes?', 'Completed\s*<br><br>\s*~\s*\d+\s*minute', 'Completed')
                    foreach ($Pattern in $Patterns) {
                    $UnitContent = [regex]::Replace($UnitContent, $Pattern, '', 'IgnoreCase')}
                    $UnitContent = [regex]::Replace($UnitContent, '-\s*\d+\s*minutes?', '', 'IgnoreCase')
                    $AllContent += $UnitContent.Trim()}
                catch {Write-Warning ("Erreur unité : $($_.Exception.Message)")}}}}
    Set-Content -Path $OutputMarkdown -Value ($AllContent -join "`r`n`r`n") -Encoding UTF8
    Write-Host "Markdown créé : $OutputMarkdown"
    return $OutputMarkdown}
function Get-ibWebCache {
    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$SourceUrl, [Parameter(Mandatory)][string]$DestinationFolder, [string]$Extension = "html")
    $Uri = [uri]$SourceUrl
    $FileName = ($Uri.AbsolutePath.TrimEnd('/') -split '/')[-1]
    if (-not (Test-Path $DestinationFolder)) {New-Item -ItemType Directory -Path $DestinationFolder | Out-Null}
    if ($FileName.EndsWith(".$Extension")) {$DestinationFile = Join-Path $DestinationFolder $FileName}
    else {$DestinationFile = Join-Path $DestinationFolder "$FileName.$Extension"}
    if (-not (Test-Path $DestinationFile)) {
        Write-Debug "Téléchargement de '$SourceUrl'"
        Invoke-WebRequest -Uri $SourceUrl -OutFile $DestinationFile -ErrorAction Stop}
    return $DestinationFile}

function Convert-ibKnowledgeCheckToMarkdown {
    [CmdletBinding()]param([Parameter(Mandatory)]$KnowledgeCheckFile)
    $KnowledgeCheck = Get-Content $KnowledgeCheckFile -Raw | ConvertFrom-Yaml
    $Markdown = @('## Module assessment','')
    $QuestionIndex = 1
    foreach ($Question in $KnowledgeCheck.quiz.questions) {
        $Markdown += "### Question $QuestionIndex",'',$Question.content,''
        foreach ($Choice in $Question.choices) {
            if ($Choice.isCorrect) {
                $Markdown += "- **$($Choice.content)**"
                if ($Choice.explanation) {$Markdown += " - *$($Choice.explanation)*"}}
            else { $Markdown += "- $($Choice.content)" }}
        $Markdown += ''
        $QuestionIndex++}
    return ($Markdown -join "`r`n")}
function get-ibGlobalCache {
    [CmdletBinding()]param([Parameter(Mandatory)][string]$CourseCode, [Parameter(Mandatory)][string]$CacheFolder, [Parameter(Mandatory)][string]$ExportProfile)
    $learnPath = "https://learn.microsoft.com/$language/training"
    $KnowledgeCheckRepos = @('learn','learn-m365-pr')
    $KnownFiles = [System.Collections.Generic.HashSet[string]]::new()
    $LearningPathFolder = Join-Path $CacheFolder $CourseCode
    $ImagesFolder = Join-Path $LearningPathFolder "images"
    $CourseUrl = "$learnPath/courses/$CourseCode"
    $CourseFile = Get-ibWebCache -SourceUrl $CourseUrl -DestinationFolder $CacheFolder
    $CourseContent = Get-Content $CourseFile -Raw -Encoding UTF8
    #Analyse de l'accueil pour trouver les Learning Path
    $LPMatches = [regex]::Matches($CourseContent, '<meta[^>]*name="learn_item"[^>]*content="([^"]+)"')
    $lpStructure = @()
    foreach ($LPMatch in $LPMatches)  {
        $Content = $LPMatch.Groups[1].Value
        if ($Content -notlike 'learn.wwl.*') {continue}
        $LpUrl = "$learnPath/paths/$($Content -replace '^learn\.wwl\.', '')/"
        $LpFile = Get-ibWebCache -SourceUrl $LpUrl -DestinationFolder $LearningPathFolder
        if (-not $KnownFiles.Add($LPFile)) {continue}
        $LpContent = Get-Content $LpFile -Raw -Encoding UTF8
        if ($LpContent -match 'property="og:title"[^\>]*content="([^"]+)"') {
            $LpTitle = $Matches[1] -replace '\s*-\s*Training$'}
        #Analyse du Learning Path pour trouver les modules
        $ModuleMatches = [regex]::Matches($LpContent,'href="\.\./\.\./modules/([^/]+)/"')
        $ModuleStructure = @()
        foreach ($ModuleMatch in $ModuleMatches) {
            $ModuleUrl = "$learnPath/modules/$($ModuleMatch.Groups[1].Value)/"
            $ModuleFolder = join-path $LearningPathFolder ([System.IO.Path]::GetFileNameWithoutExtension($lpFile))
            $ModuleFile = Get-ibWebCache -SourceUrl $ModuleUrl -DestinationFolder $ModuleFolder
            if (-not $KnownFiles.Add($ModuleFile)) {continue}
            $ModuleContent = Get-Content $ModuleFile -Raw -Encoding UTF8
            if ($ModuleContent -match 'property="og:title"[^\>]*content="([^"]+)"') {
            $ModuleTitle = $Matches[1] -replace '\s*-\s*Training$'}
            #Récupération des informations pour les urls
            if ($ModuleContent -match 'name="source_path"[^"]*content="([^"]+)"') {$SourcePath = $Matches[1]}
            #Analyse du module pour trouver les unités
            $UnitStructure = @()
            $UnitLines = $ModuleContent -split "`n" | Where-Object { $_ -like '*unit-title*' }
            $firstUnit = $true
            foreach ($Line in $UnitLines) {
                if ($Line -match 'href="([^"]+)"') {
                    $UnitUrl = "$ModuleUrl$($Matches[1])?accept=text/markdown"
                    $UnitsFolder = Join-Path $ModuleFolder ([System.IO.Path]::GetFileNameWithoutExtension($ModuleFile))
                    $UnitFile = Get-ibWebCache -SourceUrl $UnitUrl -DestinationFolder $UnitsFolder -Extension "md"
                    if (-not $KnownFiles.Add($UnitFile)) {continue}
                    $UnitContent = Get-Content $UnitFile -Raw -Encoding UTF8
                    #Suppression du FrontMatter YAML
                    $IsKnowledgeCheck = $false
                    $KnowledgeCheckYaml = $null
                    if ($UnitContent -match '(?s)^---\s*\r?\n.*?\r?\n---\s*\r?\n') {
                        $UnitContent = "`r`n`r`n" + $UnitContent.Substring($Matches[0].Length)
                        $UnitYaml = $Matches[0]
                        # Détection Knowledge Check
                        if ($UnitYaml -match 'module_assessment:\s*true') {
                            if ($UnitYaml -match 'source_path:\s*(.+)') {
                                $SourcePath = $Matches[1].Trim()
                                $KnowledgeCheckYaml = $null
                                $KnowledgeCheckSourcePath = $Matches[1].Trim()
                                foreach ($KnowledgeCheckRepo in $KnowledgeCheckRepos) {
                                    $LocalSourcePath = $KnowledgeCheckSourcePath
                                    $RepoPrefix = "$KnowledgeCheckRepo/"
                                    if ($LocalSourcePath.StartsWith($RepoPrefix)) {
                                    $LocalSourcePath = $LocalSourcePath.Substring($RepoPrefix.Length)}
                                    $KnowledgeCheckYamlUrl ="https://raw.githubusercontent.com/MicrosoftDocs/$KnowledgeCheckRepo/main/$LocalSourcePath"
                                    try {
                                        $KnowledgeCheckYaml = Get-ibWebCache -SourceUrl $KnowledgeCheckYamlUrl -DestinationFolder $UnitsFolder -Extension 'yml'
                                        if (-not (Test-Path $KnowledgeCheckYaml)) {throw "Téléchargement échoué"}
                                        $UnitContent = Convert-ibKnowledgeCheckToMarkdown -KnowledgeCheckFile $KnowledgeCheckYaml
                                        $IsKnowledgeCheck = $true
                                        break}
                                    catch {}}
                            if (-not $KnowledgeCheckYaml) {Write-Warning "Knowledge Check introuvable : $SourcePath"}}}}
                    if (-not $FirstUnit) {$UnitContent = "`r`n`r`n\newpage`r`n`r`n" + $UnitContent}
                    $FirstUnit = $false
                    $UnitTitle = ($UnitContent -split "`n" | Where-Object { $_ -like '## *' } | Select-Object -First 1)
                    $UnitTitle = $UnitTitle -replace '^##\s+', ''
                    #Récupération éventuelle des images de l'unité
                    $ImageMatches = [regex]::Matches($UnitContent, '\(([^)]*/media/[^)]+)\)')
                    foreach ($ImageMatch in $ImageMatches) {
                        $OriginalImagePath = $ImageMatch.Groups[1].Value
                        $ImageFile = (Split-Path $OriginalImagePath -Leaf) -replace '#.*$'
                        $RawUrl = "https://learn.microsoft.com/$language/training/" + ($OriginalImagePath -replace '^\.\./\.\./','' -replace '#.*$','')
                        $Extension = [System.IO.Path]::GetExtension($ImageFile).TrimStart('.')
                        Get-ibWebCache -SourceUrl $RawUrl -DestinationFolder $ImagesFolder -Extension $Extension
                        $PublishedImagePath = "$CourseCode-$ExportProfile/$ImageFile"
                        $UnitContent = $UnitContent.Replace($OriginalImagePath, $PublishedImagePath)}
                    # Conversion des urls Learn relatives en urls absolues
                    $UnitContent = $UnitContent -replace '\]\(/', '](https://learn.microsoft.com/'
                    Set-Content -Path $UnitFile -Value $UnitContent -Encoding UTF8 -Force
                    $UnitStructure += @{Title = $UnitTitle; File = $UnitFile; IsKnowledgeCheck = $IsKnowledgeCheck;}}}
            $ModuleStructure += @{File = $ModuleFile;Title = $ModuleTitle; Units = $UnitStructure}}
        $lpStructure += @{File = $LpFile;Title = $LpTitle ;Modules = $ModuleStructure}}
    $courseStructure = @{Course = $CourseCode; LearningPaths = $lpStructure}
    $courseStructure | ConvertTo-Json -Depth 6 | out-File "$LearningPathFolder\structure.json" -Encoding utf8} 

function Export-ibCourse {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$CourseCode,
        [validateSet('en-us','fr-fr')][string]$language = 'en-us',
        [ValidateSet('Lecture', 'Complet')][string]$ExportProfile = 'Lecture')
    if (-not (Get-Command pandoc -ErrorAction SilentlyContinue)) {
        Write-Warning "Pandoc introuvable : installation"
        winget install --id JohnMacFarlane.Pandoc --accept-package-agreements --accept-source-agreements -e }
    $env:Path = [System.Environment]::GetEnvironmentVariable( "Path", "Machine" ) + ";" + [System.Environment]::GetEnvironmentVariable( "Path", "User")
    Install-Module powershell-yaml -Scope CurrentUser -Force
    Import-Module powershell-yaml
    $CacheFolder = Join-Path (Get-Location) "cache"
    get-ibGlobalCache -CourseCode $CourseCode -CacheFolder $CacheFolder -ExportProfile $ExportProfile
    $OutputBaseName = "$CourseCode-$ExportProfile"
    $OutputImagesFolder = Join-Path (Get-Location) $OutputBaseName
    if (Test-Path $OutputImagesFolder) {Remove-Item $OutputImagesFolder -Recurse -Force}
    New-Item -ItemType Directory -Path $OutputImagesFolder -Force | Out-Null
    Copy-Item -Path (Join-Path $CacheFolder "$CourseCode\images\*") -Destination $OutputImagesFolder -Recurse
    $MarkdownFile = Export-ibMarkdown -CourseCode $CourseCode -CacheFolder $CacheFolder -ExportProfile $ExportProfile
    pandoc $MarkdownFile -s -o "$CourseCode-$ExportProfile.html"}