Модуль:File data

Материал из свободной русской энциклопедии «Традиция»
Перейти к навигации Перейти к поиску
  • 117768
  • 115
  • 115
  • 1239
  • 1239
  • 4

-- Convert a property to custom unit of measurement:
local bit32 = require 'bit32'
local conversions = {
	size = function (bytes, unit)
		local shifts = { b = 0, kb = 10, mb = 20, gb = 30 }
		return bit32.rshift (bytes, shifts [(unit or 'b'):lower()] or 0)
	end
}

-- Function that returns a function returning certain file attribute:
local function attribute_function (attr)
	return function (frame)
		local text = frame.args [1]
		local title = mw.title.new (text, 6) -- 6 is File:.
		local attrs = title.file
        if not attrs.exists then
            return nil
        end		
		-- Take multi-page files into account (| page = n):
		if frame.args.page and attrs.pages then
			attrs = attrs.pages[tonumber (frame.args.page) or 1]
		end
		local value = attrs [attr]
		-- Process optional parameters if defined for this property:
		if conversions [attr] then
			-- Normal table methods do not work on frame.args:
			local optional = {}
			for key, arg in ipairs (frame.args) do
				if key ~= 1 then
					optional [key - 1] = arg
				end
			end
			value = conversions [attr] (value, unpack (optional))
		end
		return type (value) == 'table' and #value or value
	end
end

local module = {}

for _, property in ipairs {
	'width',
	'height',
	'size',
	'mimeType',
	'length',
	'pages'
} do
	module [property] = attribute_function (property)
end

return module