BLAEO API

Useful library for communicating with the BLAEO API.

Versione datata 25/06/2020. Vedi la nuova versione l'ultima versione.

Questo script non dovrebbe essere installato direttamente. È una libreria per altri script da includere con la chiave // @require https://update.greasyfork.org/scripts/406057/820355/BLAEO%20API.js

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

You will need to install an extension such as Tampermonkey to install this script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name BLAEO API
// @namespace https://rafaelgssa.gitlab.io/monkey-scripts
// @version 1.0.0
// @author rafaelgssa
// @description Useful library for communicating with the BLAEO API.
// @match *://*/*
// @require https://greasyfork.org/scripts/405802-monkey-dom/code/Monkey%20DOM.js
// @require https://greasyfork.org/scripts/405822-monkey-requests/code/Monkey%20Requests.js
// @require https://greasyfork.org/scripts/405813-monkey-utils/code/Monkey%20Utils.js
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// ==/UserScript==

/* global Requests */

/**
 * @typedef {Object} UserIdentification
 * @property {string} [steamId]
 * @property {string} [username]
 *
 * @typedef {BlaeoUser} GetUserResponse
 *
 * @typedef {Object} BlaeoUser
 * @property {string} id
 * @property {string} display_name
 * @property {string} steamgifts_name
 * @property {string} steam_name
 * @property {string} steam_id
 * @property {BlaeoUserStatistics} statistics
 *
 * @typedef {Object} BlaeoUserStatistics
 * @property {number} games
 * @property {number} uncategorized
 * @property {number} never_played
 * @property {number} unfinished
 * @property {number} beaten
 * @property {number} completed
 * @property {number} wont_play
 * @property {number} categorized
 *
 * @typedef {Object} GetGamesResponse
 * @property {BlaeoGame[]} games
 *
 * @typedef {Object} BlaeoGame
 * @property {string} id
 * @property {number} steam_id
 * @property {string} name
 * @property {number} playtime
 * @property {BlaeoGameProgress} [progress]
 * @property {BlaeoGameAchievements} [achievements]
 *
 * @typedef {'never played' | 'unfinished' | 'beaten' | 'completed' | 'wont play'} BlaeoGameProgress
 *
 * @typedef {Object} BlaeoGameAchievements
 * @property {number} unlocked
 * @property {number} total
 *
 * @typedef {Object} GetRecentlyPlayedResponse
 * @property {BlaeoRecentlyPlayed[]} playtimes
 *
 * @typedef {Object} BlaeoRecentlyPlayed
 * @property {number} steam_id
 * @property {string} name
 * @property {number} minutes
 * @property {BlaeoGameProgress} progress_before
 * @property {BlaeoGameProgress} progress_now
 */

// eslint-disable-next-line
const BlaeoApi = (() => {
	const BLAEO_URL = 'https://www.backlog-assassins.net';

	let _xcsrfToken = '';
	let _authenticityToken = '';
	let _utf8 = '';

	/**
	 * Initializes the API.
	 */
	const init = () => {
		/** @type {HTMLMetaElement | null} */
		const xcsrfTokenMetadata = document.querySelector('[name="csrf-token"]');
		/** @type {HTMLInputElement | null} */
		const authenticityTokenField = document.querySelector('[name="authenticity_token"]');
		/** @type {HTMLInputElement | null} */
		const utf8Field = document.querySelector('[name="utf8"]');
		if (xcsrfTokenMetadata) {
			_xcsrfToken = xcsrfTokenMetadata.content;
		}
		if (authenticityTokenField) {
			_authenticityToken = authenticityTokenField.value;
		}
		if (utf8Field) {
			_utf8 = utf8Field.value;
		}
	};

	/**
	 * Retrieves information about a user.
	 * @param {UserIdentification} identification The identification of the user.
	 * @returns {Promise<BlaeoUser | undefined>} The information about the user, if successful.
	 */
	const getUser = async (identification) => {
		const userPath = _getUserPath(identification);
		const response = /** @type {ExtendedResponse<GetUserResponse>} */ (await Requests.GET(
			`${BLAEO_URL}/users/${userPath}.json`
		));
		return response.json;
	};

	/**
	 * Retrieves a user's games.
	 * @param {UserIdentification} identification The identification of the user.
	 * @returns {Promise<BlaeoGame[] | undefined>} The user's games, if successful.
	 */
	const getGames = async (identification) => {
		const userPath = _getUserPath(identification);
		const response = /** @type {ExtendedResponse<GetGamesResponse>} */ (await Requests.GET(
			`${BLAEO_URL}/users/${userPath}/games.json`
		));
		return response.json && response.json.games;
	};

	/**
	 * Retrieves a user's recently played games.
	 * @param {UserIdentification} identification The identification of the user.
	 * @returns {Promise<BlaeoRecentlyPlayed[] | undefined>} The user's recently played games, if successful.
	 */
	const getRecentlyPlayed = async (identification) => {
		const userPath = _getUserPath(identification);
		const response = /** @type {ExtendedResponse<GetRecentlyPlayedResponse>} */ (await Requests.GET(
			`${BLAEO_URL}/users/${userPath}/played.json`
		));
		return response.json && response.json.playtimes;
	};

	/**
	 * Previews a markdown post for a user.
	 * @param {UserIdentification} identification The identification of the user.
	 * @param {string} markdown The markdown of the post.
	 * @returns {Promise<string | undefined>} An HTML string containing the preview, if successful.
	 */
	const previewPost = async (identification, markdown) => {
		const userPath = _getUserPath(identification);
		const response = await Requests.POST(`${BLAEO_URL}/posts/preview.${userPath}`, {
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
				'X-CSRF-Token': _xcsrfToken,
			},
			body: Requests.convertToQuery({
				authenticity_token: _authenticityToken,
				utf8: _utf8,
				'post[text]': encodeURIComponent(markdown),
			}),
		});
		if (!response.dom) {
			return;
		}
		const preview = response.dom.querySelector('.markdown');
		return preview ? preview.outerHTML : '';
	};

	/**
	 * Returns the path for a user based on the identification method.
	 * @param {UserIdentification} identification The identification of the user.
	 * @returns {string} The path for the user.
	 */
	const _getUserPath = ({ steamId, username }) => {
		return steamId ? `+${steamId}` : username;
	};

	return {
		BLAEO_URL,
		init,
		getUser,
		getGames,
		getRecentlyPlayed,
		previewPost,
	};
})();