Module:Sandbox/User:Waddie96/protection

From Wikipedia, the free encyclopedia
Jump to navigation Jump to search
local p = {}
local mwHttp = require('mw.http')
local mwJson = mw.text.jsonDecode

function p.getProtectionLogs()
	local url = 'https://en.wikipedia.org/w/api.php' ..
		'?action=query' ..
		'&list=logevents' ..
		'&letype=protect' ..
		'&leprop=title|details|timestamp|comment|user' ..
		'&lelimit=500' ..
		'&ledir=older' ..
		'&format=json'

	local result = mwHttp.fetch(url)
	if not result or result.status ~= 200 then
		return nil, 'HTTP request failed'
	end

	local data = mwJson(result.body)
	if not data or not data.query or not data.query.logevents then
		return nil, 'Malformed response'
	end

	return data.query.logevents
end

function p.findExpiredProtections(events)
	local expired = {}
	local now = os.time(os.date('!*t')) -- UTC

	for _, event in ipairs(events) do
		if event.params and event.params.expiry and event.params.expiry ~= 'infinity' then
			local y, m, d, h, min, s = event.params.expiry:match('^(%d+)%-(%d+)%-(%d+)T(%d+):(%d+):(%d+)Z$')
			if y then
				local expiryTime = os.time({
					year = y, month = m, day = d,
					hour = h, min = min, sec = s
				})
				if expiryTime < now then
					table.insert(expired, event)
				end
			end
		end
	end

	return expired
end