Jump to content
Menü aufrufen
Toggle preferences menu
Persönliches Menü aufrufen
Nicht angemeldet
Ihre IP-Adresse wird öffentlich sichtbar sein, wenn Sie Änderungen vornehmen.

Die Dokumentation für dieses Modul kann unter Modul:CommLink/doc erstellt werden

require('strict')

--- @module CommLink
--- Port of the wiki-tools Module:CommLink (starcitizen.tools) to the German
--- wiki. Renders the rehosting notice, the prev/next bar, the infobox,
--- categories, and SEO metadata for {{CommLink}}, and stores the metadata
--- via SMW.
---
--- Deviations from the EN original (adapted to star-citizen.wiki):
---   * SMW instead of Bucket: `mw.smw.set` writes, `mw.smw.ask` reads. The
---     property names of the old Modul:Comm-Link are kept so the 5,916
---     existing numeric pages retain their stored data.
---   * Zero-argument pages: the archive calls the template without parameters;
---     RSI ID and metadata then come from the page title via Apiunto.
---   * Prev/next bar: with a series, the series neighbours (SMW query); without
---     one, the global ID neighbours from the API -- the numeric archive needs
---     continuous navigation, where the EN original would render empty.
---   * Series image map and title image fallback taken from the old module.
---   * No `list`: {{Comm-Link list}} would need the Bucket manifests.
---   * With an `id=` argument (sandbox) nothing is stored: the series query
---     would otherwise list the sandbox page as a neighbour.

local mbox = require('Module:Mbox')
local infobox = require('Module:InfoboxLua')
local button = require('Module:ButtonLua')
local common = require('Module:Common')

local p = {}

--- The SMW properties of the old Modul:Comm-Link; every existing page keeps
--- reading and writing through these names.
local SMW = {
	channel = 'Comm-Link-Channel',
	category = 'Comm-Link-Kategorie',
	series = 'Comm-Link-Serie',
	id = 'Comm-Link-ID',
	title = 'Comm-Link-Titel',
	published = 'Erstelldatum',
	source = 'Quelle',
}

--- The wiki API metadata endpoint, as linked by the old module.
local API_META_URL = 'https://api.star-citizen.wiki/rsi/comm-links/'

local SERIES_LIMIT = 5000

local IMAGE_MAP = {
	['This Week in Star Citizen'] = 'Comm-Link 12727 Inhaltsbild.jpg',
	['Galactapedia Update'] = 'Comm-Link 17959 Galactapedia Update Banner',
	['Roadmap Roundup'] = 'Comm-Link 17226 Titelbild.jpg',
}

local NOTICE_TITLE = 'Diese Seite gibt Inhalte der Roberts Space Industries-Website wieder.'
local NOTICE_TEXT = '[https://robertsspaceindustries.com/comm-link Comm-Links] sind offizielle '
	.. 'Mitteilungen der [https://cloudimperiumgames.com/ Cloud Imperium Games Corporation] zu '
	.. '[[Star Citizen]] und [[Squadron 42 (Videospiel)|Squadron 42]]. Der Comm-Link wird hier mit '
	.. 'minimalen Anpassungen (Formatierung und Wiki-Links) sowie mit verfuegbaren Uebersetzungen '
	.. 'wiedergegeben.'

--- @class CommLinkRecord
--- @field id number|nil
--- @field title string|nil
--- @field channel string|nil  The channel (EN equivalent: `type`)
--- @field category string|nil
--- @field series string|nil
--- @field published string|nil  ISO date from the API or `publicationdate`
--- @field url string|nil
--- @field image string|nil
--- @field prevId number|nil  global neighbours from the API; -1 becomes nil
--- @field nextId number|nil

--- @param value any
--- @return string|nil
local function clean(value)
	if type(value) ~= 'string' then
		return nil
	end
	local trimmed = mw.text.trim(value)
	-- The API serializes absent fields as the string 'None'; such a value
	-- would be a real series 'None' with a red-link category.
	if trimmed == '' or trimmed == 'None' then
		return nil
	end
	return trimmed
end

--- First value of an SMW printout: multi-valued properties arrive as a table.
--- @param value any
--- @return string|nil
local function first(value)
	if type(value) == 'table' then
		return clean(tostring(value[1]))
	end
	return clean(tostring(value))
end

--- The RSI ID in the page title (`Comm-Link:16828`, `Comm-Link:16828/de`).
--- @return number|nil
local function titleId()
	local root = mw.title.getCurrentTitle().rootText
	return root:match('^%d+$') and tonumber(root) or nil
end

--- Live fetch via Apiunto. A failed fetch returns nil; the page then
--- renders with whatever arguments are available.
--- @param id number|nil
--- @return table|nil data
--- @return table|nil meta
local function fetchApi(id)
	if id == nil then
		return nil, nil
	end
	local ok, raw = pcall(function()
		return mw.ext.Apiunto.fetch('StarCitizenWikiAPI', 'comm-links/' .. id)
	end)
	if not ok or type(raw) ~= 'string' then
		return nil, nil
	end
	local okDecode, result = pcall(mw.text.jsonDecode, raw)
	if not okDecode or type(result) ~= 'table' then
		return nil, nil
	end
	if type(result.data) ~= 'table' then
		return nil, nil
	end
	return result.data, type(result.meta) == 'table' and result.meta or nil
end

--- Merges template arguments and API data; arguments win.
--- @param args table  named arguments from the template and #invoke
--- @return CommLinkRecord|nil
function p.resolve(args)
	local api, meta = fetchApi(tonumber(args.id) or titleId())
	local record = {}
	if api ~= nil then
		record.id = tonumber(api.id)
		record.title = clean(api.title)
		record.channel = clean(api.channel)
		record.category = clean(api.category)
		record.series = clean(api.series)
		record.published = clean(api.created_at)
		record.url = clean(api.rsi_url)
	end
	if meta ~= nil then
		local prev, next = tonumber(meta.prev_id), tonumber(meta.next_id)
		record.prevId = prev ~= nil and prev > 0 and prev or nil
		record.nextId = next ~= nil and next > 0 and next or nil
	end
	if args.id ~= nil then
		record.id = tonumber(args.id)
	end
	record.title = clean(args.title) or record.title
	record.channel = clean(args.type) or record.channel
	record.series = clean(args.series) or record.series
	record.published = clean(args.publicationdate) or record.published
	record.url = clean(args.url) or record.url
	record.image = clean(args.image)
	return record
end

--- The named arguments; #invoke arguments (sandbox) extend the template's
--- so `{{#invoke:CommLink|main|id=...}}` stays testable.
--- @param frame frame
--- @return table
function p.readArgs(frame)
	local args = {}
	local parent = frame.getParent and frame:getParent()
	if parent and parent.args then
		for k, v in pairs(parent.args) do
			args[k] = v
		end
	end
	for k, v in pairs(frame.args or {}) do
		args[k] = v
	end
	return args
end

--- @param a CommLinkRecord
--- @param b CommLinkRecord
--- @return boolean
local function readsBefore(a, b)
	if a.published ~= b.published then
		if a.published == nil or b.published == nil then
			return b.published == nil
		end
		return a.published < b.published
	end
	if a.id ~= b.id then
		if a.id == nil or b.id == nil then
			return b.id == nil
		end
		return a.id < b.id
	end
	return mw.ustring.lower(a.page_name or '') < mw.ustring.lower(b.page_name or '')
end

--- A series in reading order: date, then RSI ID, then page name.
--- @param rows CommLinkRecord[]
--- @return CommLinkRecord[]
function p.orderSeries(rows)
	local ordered = {}
	for i, row in ipairs(rows) do
		ordered[i] = row
	end
	table.sort(ordered, readsBefore)
	return ordered
end

--- A page's neighbours in the ordered series, matched by RSI ID with a
--- page-name fallback.
--- @param ordered CommLinkRecord[]
--- @param own CommLinkRecord
--- @return CommLinkRecord|nil before
--- @return CommLinkRecord|nil after
function p.neighbours(ordered, own)
	for i, row in ipairs(ordered) do
		local match
		if own.id ~= nil and row.id ~= nil then
			match = row.id == own.id
		else
			match = row.page_name ~= nil and mw.ustring.lower(row.page_name) == mw.ustring.lower(own.page_name or '')
		end
		if match then
			return ordered[i - 1], ordered[i + 1]
		end
	end
	return nil, nil
end

--- Writes the metadata via SMW. Base pages only: translation subpages
--- share the base page's data. A failure does not throw; the page renders on.
--- @param record CommLinkRecord
function p.put(record)
	if mw.title.getCurrentTitle().isSubpage then
		return
	end
	-- Nur vorhandene Felder: SMW ersetzt die Semantikdaten einer Seite bei
	-- jedem Parsen als Ganzes, verschwundene Felder verschwinden also mit
	-- dem Reparse von selbst (die 'None'-Reste des alten Moduls brauchen
	-- keinen Leerstring, nur das Neu-Parsen der Seite).
	local setData = {
		[SMW.channel] = record.channel,
		[SMW.category] = record.category,
		[SMW.series] = record.series,
		[SMW.id] = record.id,
		[SMW.title] = record.title,
		[SMW.published] = record.published,
		[SMW.source] = record.url,
	}
	pcall(function()
		common.checkSmwResult(mw.smw.set(setData))
	end)
end

--- Every stored row of the series; the page's own row is built from the
--- current data instead of read, so the page sorts correctly even before its
--- first SMW write.
--- @param series string
--- @param pageName string
--- @param own CommLinkRecord
--- @return CommLinkRecord[]
function p.seriesRows(series, pageName, own)
	local rows = {}
	local ok, stored = pcall(function()
		return mw.smw.ask({
			'[[' .. SMW.series .. '::' .. series .. ']]',
			'?' .. SMW.title,
			'?' .. SMW.published .. '#ISO',
			'?' .. SMW.id,
			mainlabel = 'page_name',
			limit = SERIES_LIMIT,
		})
	end)
	-- SMW's mainlabel returns the display title (' 16368 - Calling All Devs'),
	-- not the canonical page name; it can neither identify the page's own row
	-- nor build valid links. The RSI ID is the numeric archive's stable key:
	-- exclusion and links key on it, Comm-Link:<ID> is the canonical page name.
	if ok and type(stored) == 'table' then
		for _, row in ipairs(stored) do
			local id = tonumber(first(row[SMW.id]))
			if id == nil or id ~= own.id then
				rows[#rows + 1] = {
					page_name = id ~= nil and ('Comm-Link:' .. id) or clean(tostring(row.page_name or '')),
					title = first(row[SMW.title]),
					published = first(row[SMW.published]),
					id = id,
				}
			end
		end
	end
	own.page_name = pageName
	rows[#rows + 1] = own
	return rows
end

--- The date the infobox and the bar show: d.m.Y.
--- @param published string|nil
--- @return string|nil
local function germanDate(published)
	if published == nil then
		return nil
	end
	return mw.getContentLanguage():formatDate('d.m.Y', published)
end

--- The {{Prevnext}} arguments within a series.
--- @param before CommLinkRecord|nil
--- @param after CommLinkRecord|nil
--- @param series string
--- @return table<string, string>
function p.prevnextSeriesArgs(before, after, series)
	local args = { title = '[[:Kategorie:' .. series .. '|' .. series .. ']]' }
	if before ~= nil then
		args.prev = before.page_name
		args.prevTitle = before.title or before.page_name
		args.prevDesc = germanDate(before.published)
	end
	if after ~= nil then
		args.next = after.page_name
		args.nextTitle = after.title or after.page_name
		args.nextDesc = germanDate(after.published)
	end
	return args
end

--- The notice text; `citation` is the expanded {{Cite RSI}} template.
--- @param citation string|nil
--- @return string
function p.noticeText(citation)
	if citation == nil then
		return NOTICE_TEXT
	end
	return NOTICE_TEXT .. ' Die Originalquelle dieses Comm-Links befindet sich unter &nbsp;' .. citation
end

--- The infobox footer: buttons to the RSI website and the API metadata.
--- The EN original's icon files do not exist here; the buttons stay
--- icon-less.
--- @param record CommLinkRecord
--- @return table|nil
function p.footerSection(record)
	local buttons = {}
	if record.url ~= nil then
		buttons[#buttons + 1] = button.render({ label = 'Offizielle Website', url = record.url })
	end
	if record.id ~= nil then
		buttons[#buttons + 1] = button.render({
			label = 'Wiki-API',
			url = API_META_URL .. record.id .. '#meta',
		})
	end
	if #buttons == 0 then
		return nil
	end
	return {
		content = tostring(mw.html.create('div'):addClass('t-infobox-footer-actions'):wikitext(table.concat(buttons))),
		class = 't-infobox-section--footer',
	}
end

--- The title image: argument, series image map (matched against the title),
--- or the `Comm-Link <ID> Titelbild` naming convention; existing files only.
--- @param record CommLinkRecord
--- @return string|nil
function p.image(record)
	local candidates = { record.image }
	if record.id ~= nil then
		candidates[#candidates + 1] = string.format('Comm-Link %d Titelbild', record.id)
	end
	for pattern, file in pairs(IMAGE_MAP) do
		if record.title ~= nil and record.title:find(pattern, 1, true) ~= nil then
			candidates[#candidates + 1] = file
		end
	end
	return common.getImage(candidates)
end

--- The InfoboxLua data.
--- @param record CommLinkRecord
--- @param pageText string
--- @return table
function p.infoboxData(record, pageText)
	local items = {}
	if record.series ~= nil then
		items[#items + 1] =
			{ label = 'Serie', content = '[[:Kategorie:' .. record.series .. '|' .. record.series .. ']]' }
	end
	if record.channel ~= nil then
		items[#items + 1] =
			{ label = 'Kanal', content = '[[:Kategorie:' .. record.channel .. '|' .. record.channel .. ']]' }
	end
	if record.id ~= nil then
		items[#items + 1] = { label = 'ID', content = tostring(record.id) }
	end
	local published = germanDate(record.published)
	if published ~= nil then
		items[#items + 1] = { label = 'Veröffentlicht', content = published }
	end

	local sections = {}
	if #items > 0 then
		sections[#sections + 1] = { columns = 2, items = items }
	end
	local footer = p.footerSection(record)
	if footer ~= nil then
		sections[#sections + 1] = footer
	end

	local header = record.title or pageText
	if record.id ~= nil then
		header = string.format('%s <span class="infobox__desc">(%d)</span>', header, record.id)
	end
	return {
		title = header,
		subtitle = 'Comm-Link',
		image = p.image(record),
		sections = sections,
	}
end

--- The page's categories.
--- @param record CommLinkRecord
--- @return string
function p.categories(record)
	-- Nur Basisseiten: Uebersetzungs-Unterseiten spiegeln die Kategorien
	-- der Basisseite und fuelten sonst jede Kategorie zweifach.
	if mw.title.getCurrentTitle().isSubpage then
		return ''
	end
	local categories = '[[Kategorie:Comm-Link]]'
	if record.channel ~= nil then
		categories = categories .. '[[Kategorie:' .. record.channel .. ']]'
	end
	if record.series ~= nil then
		categories = categories .. '[[Kategorie:' .. record.series .. ']]'
	end
	return categories
end

--- The WikiSEO arguments for a Comm-Link page: German title suffix,
--- keywords, and the page-specific description and title image.
--- @param record CommLinkRecord
--- @param authorUrl string {{SERVER}}/Benutzer:{{REVISIONUSER}}, expanded by the caller
--- @param pageUrl string the page's canonical URL
--- @param sitename string {{SITENAME}}, expanded by the caller
--- @param locale string
--- @return table
function p.seoArgs(record, authorUrl, pageUrl, sitename, locale)
	local seo = {
		author = authorUrl,
		section = 'Comm-Link',
		url = pageUrl,
		title = table.concat({ record.title, sitename }, ' - '),
		title_mode = 'replace',
		keywords = table.concat({
			'Comm-Link',
			'Comm Link',
			'Star Citizen',
			'Squadron 42',
			'Cloud Imperium Games',
			record.channel or '',
			record.category or '',
			record.series or '',
		}, ', '),
		locale = locale,
		type = 'article',
		published_time = record.published,
		description = record.title .. ' ist Teil des Comm-Link-Archivs im ' .. sitename .. '.',
	}
	-- p.image returns false (not nil) when no candidate file exists; an absent
	-- key leaves og:image to the sitewide default instead.
	local image = p.image(record)
	if type(image) == 'string' then
		seo.image = image
	end
	return seo
end

--- SEO via the WikiSEO extension, like the old module.
--- @param record CommLinkRecord
function p.setSeo(record)
	if record.title == nil then
		return
	end
	local title = mw.title.getCurrentTitle()
	-- /en subpages hold the English original of a translated Comm-Link; en_US
	-- because en_EN is not a valid og:locale value.
	local locale = 'de_DE'
	if title.isSubpage and title.subpageText == 'en' then
		locale = 'en_US'
	end
	mw.ext.seo.set(
		p.seoArgs(
			record,
			mw.getCurrentFrame():preprocess('{{SERVER}}/Benutzer:{{urlencode:{{REVISIONUSER}}|WIKI}}'),
			tostring(title:fullUrl('', 'https')),
			mw.getCurrentFrame():preprocess('{{SITENAME}}'),
			locale
		)
	)
end

--- {{CommLink}}'s prev/next bar.
--- @param frame frame
--- @param record CommLinkRecord
--- @param pageName string
--- @param testing boolean  sandbox mode: no series query
--- @return string
function p.seriesBar(frame, record, pageName, testing)
	if record.series ~= nil and not testing then
		local before, after = p.neighbours(p.orderSeries(p.seriesRows(record.series, pageName, record)), record)
		return frame:expandTemplate({ title = 'Prevnext', args = p.prevnextSeriesArgs(before, after, record.series) })
	end
	if record.prevId ~= nil or record.nextId ~= nil then
		local args = { title = '[[Comm-Link:Übersicht]]' }
		if record.prevId ~= nil then
			args.prev = 'Comm-Link:' .. record.prevId
		end
		if record.nextId ~= nil then
			args.next = 'Comm-Link:' .. record.nextId
		end
		return frame:expandTemplate({ title = 'Prevnext', args = args })
	end
	return ''
end

--- {{CommLink}}'s entry point.
--- @param frame frame
--- @return string
function p.main(frame)
	local args = p.readArgs(frame)
	-- `id=` in the #invoke call marks sandbox mode: no SMW write, so test
	-- pages never appear as series neighbours.
	local testing = args.id ~= nil and mw.title.getCurrentTitle().rootText:match('^%d+$') == nil
	local record = p.resolve(args)
	if record.title == nil and record.id == nil then
		return mbox.render({
			title = 'Keine Daten',
			text = 'Für diese Seite konnten keine Comm-Link-Daten ermittelt werden.',
		}) .. '[[Kategorie:Comm-Link mit fehlenden Daten]]'
	end
	if not testing then
		p.put(record)
	end
	local pageText = mw.title.getCurrentTitle().text
	local pageName = mw.title.getCurrentTitle().prefixedText
	local citation
	if record.url ~= nil then
		citation =
			frame:expandTemplate({ title = 'Cite RSI', args = { url = record.url, text = record.title or pageText } })
	end
	local notice = mbox.render({
		title = NOTICE_TITLE,
		text = p.noticeText(citation),
		icon = 'WikimediaUI-Notice.svg',
		iconMask = true,
	})
	if not testing then
		p.setSeo(record)
		if record.id ~= nil and not mw.title.getCurrentTitle().isSubpage and record.title ~= nil then
			common.setDisplayTitle(frame, 'Comm-Link:' .. record.id .. ' - ' .. record.title)
		end
	end
	return notice
		.. p.seriesBar(frame, record, pageName, testing)
		.. frame:extensionTag({ name = 'templatestyles', args = { src = 'Modul:CommLink/styles.css' } })
		.. infobox.render(p.infoboxData(record, pageText))
		.. p.categories(record)
end

return p
Zuletzt geändert
Urheberrecht
Cookies helfen uns bei der Bereitstellung dieses Wikis. Durch die Nutzung des Star Citizen Wiki erklärst du dich damit einverstanden, dass wir Cookies speichern.