Saltar para o conteúdo

Módulo:Citar tweet

Origem: Wikipédia, a enciclopédia livre.
local p = {}
local TwitterSnowflake = require('Módulo:TwitterSnowflake')
local CiteWeb = require('Módulo:Citar web').web

local err_msgs_t = {															-- uma sequência de mensagens de erro de data em Snowflake; todas devem ser terminadas com ponto e vírgula (;)
	' <kbd>&#124;data=</kbd> e <kbd>&#124;numero=</kbd> incompatíveis;',		-- [1]
	' <kbd>&#124;data=</kbd> requerido;',										-- [2]
	' <kbd>&#124;numero=</kbd> inválido;',										-- [3]
	' <kbd>&#124;numero=</kbd> ausente ou vazio;',								-- [4]
	' <kbd>&#124;usuario=</kbd> ausente ou vazio;'								-- [5]
	}


--[[--------------------------< P R I N C I P A L >------------------------------------------------------------
]]

p.main = function(frame)
	return p[''](frame)
end

--[[--------------------------< S U P R I M I R _ U R L _ N O _ T Í T U L O >----------------------------------

This function searches for and suppresses urls in |title=, |script-title=, and |trans-title= parameters so that
{{cite web}} won't emit 'External link in |title=' error messages when rendered In the redering, urls are correctly
formed as they were in the original tweet.  The function looks for valid schemes and then wraps them in
<nowiki>..</nowiki> tags.

]]

local function suppress_url_in_title (frame, title)
	local schemes = {															-- schemes commonly found in tweets
		'https://',
		'http://',
		'ftp://',
		}

	if title then																-- when there is a title, suppress any urls with known schemes; abandon else
		for _, scheme in ipairs (schemes) do									-- spin through the list of schemes looking for a match
			title = title:gsub (scheme, frame:callParserFunction ('#tag', {'nowiki', scheme}));	-- replace the scheme with its nowiki'd form (a strip marker)
		end
	end

	return title;																-- done; return <title> modified or not
end


--[[--------------------------< O B T E R _ D A T A _ E _ U R L _ D O _ N Ú M E R O >--------------------------

extrai os valores dos parâmetros |data= e |numero= se presentes. Extrai data de |numero= e compara com |data=.

constroi |url= para {{citar web}} a partir da url base e |numero= e |usuario=

não retorna nada; adiciona data, número, url a <cite_args_t>; adiciona mensagem(ns) de erro a <errors_t>.

]]

local function date_number_url_get (args_t, cite_args_t, errors_t)
	local err_msg_index;

	cite_args_t.url = 'https://x.com/';									        -- initialize with minimal base url because {{cite web}} requires |url=
	if not args_t.user then
		table.insert (errors_t, err_msgs_t[5]);									-- error: missing or empty |user=
	end

	if not args_t.date and not args_t.number then
		err_msg_index = 4;														-- error: missing or empty |number=
	elseif tonumber (args_t.number) then										-- |number= without |date=? use number
		if tonumber(args_t.number) then
			cite_args_t.date = args_t.date or (args_t.number and TwitterSnowflake.snowflakeToDate{ args = {id_str = args_t.number} });
		else
			cite_args_t.date = args_t.date;
		end
			cite_args_t.number = args_t.number;

			if args_t.user then													-- |number= appears to have a valid value; if |user= has a value
				cite_args_t.url = cite_args_t.url .. args_t.user .. '/status/' .. args_t.number;	-- construct |url= for {{cite web}}
			end
	elseif args_t.number then													-- |number= with a value that can't be converted to a number; invalid
		err_msg_index = 3;														-- error: invalid number (couldn't convert to number)
	elseif not args_t.number then												-- |date= without |number= use date
		cite_args_t.date = args_t.date;											-- |date= has a value, use it
		err_msg_index = 4;														-- error: missing or empty |number=
	end

	if err_msg_index then
		table.insert (errors_t, err_msgs_t[err_msg_index]);						-- invalid number or missing necessary parameters so abandon
		return;
	end

	err_msg_index = TwitterSnowflake.datecheck ({ args = {						-- returns error message index number on error; nil else
		id_str	= args_t.number or '',
		date	= args_t.date or '',
		error1	= 1,															-- these numbers are indexes into <err_msgs_t> to override snowflake default error messages
		error2  = 2,															-- done this way to avoid long string comparison looking for
		error3	= 3																-- the undated-pre-twitter-epoch-post message
		}});

	if	2 == err_msg_index then													-- when no date and posted before twitter epoch
		cite_args_t.date = nil;													-- suppress default date because {{cite tweet}} should not claim in its own voice that the undated post was posted 2010-11-04
	end
	
	table.insert (errors_t, err_msgs_t[err_msg_index]);							-- add error message
end


--[[--------------------------< p[''] >------------------------------------------------------------------------

constroi conjunto de parâmetros para {{citar web}} a partir do parâmetros de {{citar tweet}}; faz alguma verificação de erros

]]

p[''] = function(frame)
	local args_t = require ('Módulo:Arguments').getArgs (frame);

	local cite_args_t = {
		title = suppress_url_in_title (frame, args_t.title or args_t.titulo or args_t['título']),
		['script-title'] = suppress_url_in_title (frame, args_t['script-title'] or args_t['título-translit'] or args_t['titulo-translit']),
		['trans-title'] = suppress_url_in_title (frame, args_t['trans-title'] or args_t['títulotrad'] or args_t['titulotrad'] or args_t['título-trad']),
		language = args_t.language or args_t.lingua or args_t['língua'] or args_t.idioma,
		last1 = args_t.last1 or args_t.last or args_t.ultimo1 or args_t['último1'] or args_t.sobrenome or args_t.apelido or args_t.ultimo1 or args_t['último1'] or args_t.sobrenome1 or args_t.apelido1,
		first1 = args_t.first1 or args_t.first or args_t.primeiro or args_t.nome or args_t.primeiro or args_t.nome,
		author1 = args_t.author1 or args_t.author or args_t.autor or args_t.autor1,
		['author-link'] = args_t['author-link'] or args_t.authorlink or args_t.autorlink,
		others = args_t.retweet and ('Retweetado por ' .. args_t.retweet),
		via = args_t.link == 'não' and 'Twitter' or '[[Twitter]]',
		type = 'Tweet',
		['access-date'] = args_t['access-date'] or args_t.accessdate or args_t.acessodata,
		['archive-date'] = args_t['archive-date'] or args_t.archivedate or args_t.arquivodata or args_t.dataarquivo,
		['archive-url'] = args_t['archive-url'] or args_t.archiveurl or args_t.arquivourl or args_t.urlarquivo,
		wayb = args_t.wayb,
		['url-status'] = args_t['url-status'] or args_t.urlmorta,
		['url-access'] = args_t['url-access'] or args_t['acesso-url'] or args_t.acessourl,
		quote = args_t.quote or args_t.citacao or args_t['citação'],
		ref = args_t.ref,
		}

	local errors_t = {'<span class="cs1-visible-error citation-comment"> <kbd>{{[[Predefinição:Citar tweet|Citar tweet]]}}</kbd>:'};		-- initialize sequence of error messages with style tag
	date_number_url_get (args_t, cite_args_t, errors_t);						-- add |date=, |number=, |url= to <cite_args_t>

	local author = ((cite_args_t.last1 and cite_args_t.first1) and cite_args_t.last1 .. ', ' .. cite_args_t.first1) or	-- concatenate |last= with |first= for |author-mask=
		(cite_args_t.last1 and cite_args_t.last1) or							-- only |last= for |author-mask=
		(cite_args_t.author1 and cite_args_t.author1:gsub('^%(%((.+)%)%)$', '%1'));	-- |author= or |author1= stripped of accept-as-written markup for |author-mask=

	if author and args_t.user then
		cite_args_t['author-mask'] = author .. ' [@' .. (args_t.user or '') .. ']'	-- concatenate <author> and |user= into |author-mask=
	elseif args_t.user then
		cite_args_t.author1 = '((' .. args_t.user .. '))';						-- just the user name for cs1|2 metadata
		cite_args_t['author-mask'] = '@' .. args_t.user;						-- make a mask for display
	else																		-- here when neither <author> nor |user=
		cite_args_t.author1 = nil;												-- so unset
	end

	frame.args = cite_args_t;													-- overwrite frame arguments
	local rendering = CiteWeb (frame);											-- render the template

---------- mensagens de erros ----------
	if errors_t[2] then															-- errors_t[2] nil when no errors
		if rendering:find ('cs1-visible-error', 1, true) then					-- rendered {{cite web}} with errors will have this string
			errors_t[1] = errors_t[1]:gsub ('> <', '>; <');						-- insert semicolon to terminate cs1|2 error message string
		end

		errors_t[#errors_t] = errors_t[#errors_t]:gsub (';$',' ([[Template:Cite_tweet#Error_detection|help]])');	-- replace trailing semicolon with help link
		table.insert (errors_t, '</span>');										-- close style span tag
		if mw.title.getCurrentTitle():inNamespace (0) then						-- mainspace only
			table.insert (errors_t, '[[Categoria:!Predefinições de citar tweet com erros]]');	-- add error category
		end

		rendering = rendering .. table.concat (errors_t);						-- append error messaging, help links and catagories
	end
	return rendering;
end

return p