Aller au contenu

Module:YouTube

Cette page fait l’objet d’une mesure de semi-protection étendue.
Une page de Wikipédia, l'encyclopédie libre.
Ceci est une version archivée de cette page, en date du 24 mai 2023 à 03:17 et modifiée en dernier par Od1n (discuter | contributions) (encore correction). Elle peut contenir des erreurs, des inexactitudes ou des contenus vandalisés non présents dans la version actuelle.

 Documentation[voir] [modifier] [historique] [purger]

Ce module Lua est utilisé par le modèle {{YouTube}}.

Page à prévisualiser pour vérifier les modifications : Discussion module:YouTube/Test.

--[[
* format canonique : 30s

* YouTube supporte davantage de formats, mais redirige vers le format canonique :
** il peut y avoir des leading zeroes
** heures, minutes, secondes peuvent être spécifiés dans n'importe quel ordre
** si on spécifie uniquement des secondes, le suffixe "s" peut être omis
]]

local p = {}

local function toSeconds( number, unit )
    if unit == 's' then
        return number
    elseif unit == 'm' then
        return number * 60
    elseif unit == 'h' then
        return number * 3600
    end
end

local function timestampToNbSeconds( timestamp )
    local num1, unit1, num2, unit2, num3, unit3

    -- "30s"
    num1, unit1 = timestamp:match( '^0*(%d+)([hms])$' )
    if num1 then
        return toSeconds( num1, unit1 )
    end

    -- "20m30s"
    num1, unit1, num2, unit2 = timestamp:match( '^0*(%d+)([hms])0*(%d+)([hms])$' )
    if num1 then
        return toSeconds( num1, unit1 ) + toSeconds( num2, unit2 )
    end

    -- "1h20m30s"
    num1, unit1, num2, unit2, num3, unit3 = timestamp:match( '^0*(%d+)([hms])0*(%d+)([hms])0*(%d+)([hms])$' )
    if num1 then
        return toSeconds( num1, unit1 ) + toSeconds( num2, unit2 ) + toSeconds( num3, unit3 )
    end

    -- "30"
    local seconds = timestamp:match( '^0*(%d+)$' )
    if seconds then
        return seconds
    end

    return false
end

function p.timestamp( frame )
    local timestamp = frame.args[ 1 ]

    local nbSeconds = timestampToNbSeconds( timestamp )
    if not nbSeconds then
        -- fallback: return the original input
        return timestamp
    end

    return nbSeconds .. 's'
end

function p.libelle( frame )
    local timestamp = frame.args[ 1 ]

    local nbSeconds = timestampToNbSeconds( timestamp )
    if not nbSeconds then
        -- fallback: return nothing
        return ''
    end

    local hours, minutes, seconds = false, false, false

    if nbSeconds / 3600 > 0 then
        hours = math.floor( nbSeconds / 3600 )
        nbSeconds = nbSeconds - hours * 3600
    end

    if nbSeconds / 60 > 0 then
        minutes = math.floor( nbSeconds / 60 )
        nbSeconds = nbSeconds - minutes * 60
    end

    if nbSeconds > 0 then
        seconds = nbSeconds
    end

    return ( hours and ( hours .. 'h' ) or '' )
        .. ( minutes and ( minutes .. 'm' ) or '' )
        .. ( seconds and ( seconds .. 's' ) or '' )
end

return p