模块:Discussions

来自「荏苒之境」
Sicusa留言 | 贡献2025年8月24日 (日) 15:31的版本

此模块的文档可以在模块:Discussions/doc创建

local utils_str = require("Module:Utils/String")

local escape_url = utils_str.escape_url

local discussions = {}

local API_PAGEINFO = "http://localhost/api.php?action=discussiontoolspageinfo&format=json&prop=threaditemshtml&maxage=0&excludesignatures=1&formatversion=2&page="

local function get_topics(title)
	local d, e = mw.ext.externaldata.getExternalData {
    	url = API_PAGEINFO..escape_url(title),
    	format = "json"
	}
	if e then
		error("发起请求失败")
	end
	return d[1]["__json"]["discussiontoolspageinfo"]["threaditemshtml"]
end

discussions.get_topics = get_topics

local function get_topic_timestamp(name)
	local time_str = string.sub(name, string.find(name, "-[^-]*$") + 1)
	return tonumber(time_str)
end

discussions.show = function(frame)
	local title = frame.args.title
	local limit = tonumber(frame.args.limit) or 5
	local topics = get_topics(title)
	
	if #topics == 0 then
		return frame.args.no_result_wiki
	end
	
	for i = 1, #topics do
		local topic = topics[i]
		topic.timestamp = get_topic_timestamp(topic.name)
	end
	
	table.sort(topics, function(t1, t2)
		return t1.timestamp < t2.timestamp
	end)
	
	local t = {"<ul>"}
	for i = #topics, math.max(1, #topics - limit), -1 do
		local topic = topics[i]
		local author = topic.replies[1].author
		
		t[#t+1] = "<li>[["
		t[#t+1] = title
		t[#t+1] = "#"
		t[#t+1] = topic.id
		t[#t+1] = "|"
		t[#t+1] = topic.html
		t[#t+1] = "]] — [[User:"
		t[#t+1] = author
		t[#t+1] = "|"
		t[#t+1] = author
		t[#t+1] = "]]</li>"
	end
	t[#t+1] = "</ul>"
	return table.concat(t)
end

return discussions