@jovo-community/plugin-playfab
Version:
A Jovo Framework plugin for PlayFab LiveOps game backend.
333 lines • 15.2 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JovoPlayFab = exports.UserDataPermission = exports.LoginStatus = void 0;
const playfab_sdk_1 = require("playfab-sdk");
const util_1 = require("util");
var LoginStatus;
(function (LoginStatus) {
LoginStatus["NewUser"] = "newUser";
LoginStatus["ExistingUser"] = "existingUser";
LoginStatus["Error"] = "error";
})(LoginStatus = exports.LoginStatus || (exports.LoginStatus = {}));
var UserDataPermission;
(function (UserDataPermission) {
UserDataPermission["Private"] = "Private";
UserDataPermission["Public"] = "Public";
})(UserDataPermission = exports.UserDataPermission || (exports.UserDataPermission = {}));
var ApiStatus;
(function (ApiStatus) {
ApiStatus["OK"] = "OK";
})(ApiStatus || (ApiStatus = {}));
class JovoPlayFab {
constructor(config, jovo) {
this.config = config;
this.jovo = jovo;
}
get PlayFabServer() {
return playfab_sdk_1.PlayFabServer;
}
get PlayFabAdmin() {
return playfab_sdk_1.PlayFabAdmin;
}
get PlayFabId() {
var _a, _b, _c, _d;
return (_d = (_c = (_b = (_a = this.jovo.$session.data) === null || _a === void 0 ? void 0 : _a.playfab) === null || _b === void 0 ? void 0 : _b.loginInfo) === null || _c === void 0 ? void 0 : _c.PlayFabId) !== null && _d !== void 0 ? _d : '';
}
init() {
playfab_sdk_1.PlayFab.settings.titleId = this.config.titleId;
playfab_sdk_1.PlayFab.settings.developerSecretKey = this.config.developerSecretKey;
if (!this.jovo.$session.data.playfab) {
this.jovo.$session.data.playfab = {};
}
if (!this.jovo.$session.data.playfab.profile) {
this.jovo.$session.data.playfab.profile = {};
}
}
async login() {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
console.debug('JovoPlayFab.login');
if (!((_c = (_b = (_a = this.jovo.$session.data) === null || _a === void 0 ? void 0 : _a.playfab) === null || _b === void 0 ? void 0 : _b.loginInfo) === null || _c === void 0 ? void 0 : _c.SessionTicket)) {
const loginRequest = {
ServerCustomId: this.jovo.$user.id,
CreateAccount: true,
CustomTags: { sessionId: this.jovo.$request.getSessionId() },
InfoRequestParameters: this.config.login.infoRequestParameters,
};
const loginWithCustomID = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.LoginWithServerCustomId);
try {
const result = await loginWithCustomID(loginRequest);
if (result.status === ApiStatus.OK) {
this.jovo.$session.data.playfab.loginInfo = result.data;
if (result.data.NewlyCreated) {
// new player
this.jovo.$session.data.playfab.loginStatus = LoginStatus.NewUser;
if (this.config.login.onNewProfile) {
const profile = await this.config.login.onNewProfile(this.jovo);
await this.updateProfile(profile);
if (!this.jovo.$session.data.playfab.isDisplayNameUpdated) {
// display name conflict
let count = 0;
do {
count++;
const profile = await this.config.login.onNewProfile(this.jovo);
await this.updateProfile({ displayName: profile.displayName });
} while (count < this.config.login.maxNewProfileRetries &&
!this.jovo.$session.data.playfab.isDisplayNameUpdated);
}
}
}
else {
// existing player
this.jovo.$session.data.playfab.loginStatus = LoginStatus.ExistingUser;
const profile = {
displayName: (_e = (_d = result.data.InfoResultPayload) === null || _d === void 0 ? void 0 : _d.PlayerProfile) === null || _e === void 0 ? void 0 : _e.DisplayName,
avatarUrl: (_g = (_f = result.data.InfoResultPayload) === null || _f === void 0 ? void 0 : _f.PlayerProfile) === null || _g === void 0 ? void 0 : _g.AvatarUrl,
};
const key = this.config.login.extendedProfileKey;
if (key) {
let data;
if ((_j = (_h = this.jovo.$session.data.playfab.loginInfo.InfoResultPayload) === null || _h === void 0 ? void 0 : _h.UserData) === null || _j === void 0 ? void 0 : _j[key]) {
data = this.parseUserDataRecords((_k = this.jovo.$session.data.playfab.loginInfo.InfoResultPayload) === null || _k === void 0 ? void 0 : _k.UserData);
}
else {
data = await this.getUserData(key);
}
if (data && data[key]) {
profile.extendedProfile = data[key];
}
}
this.jovo.$session.data.playfab.profile = profile;
}
}
}
catch (error) {
console.error('PlayFabServer.LoginWithCustomID', error);
this.jovo.$session.data.playfab.loginStatus = LoginStatus.Error;
}
}
}
async updateProfile(profile) {
console.debug('JovoPlayFab.updateProfile');
let result = false;
const updateUserTitleDisplayName = (0, util_1.promisify)(playfab_sdk_1.PlayFabAdmin.UpdateUserTitleDisplayName);
const updateAvatarUrl = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.UpdateAvatarUrl);
const promises = [];
if (!profile.displayName && !profile.avatarUrl) {
return result;
}
if (profile.displayName) {
const updateUserTitleDisplayNamePromise = updateUserTitleDisplayName({
PlayFabId: this.PlayFabId,
DisplayName: profile.displayName,
});
promises.push(updateUserTitleDisplayNamePromise);
}
if (profile.avatarUrl) {
const updateAvatarUrlPromise = updateAvatarUrl({
PlayFabId: this.PlayFabId,
ImageUrl: profile.avatarUrl,
});
promises.push(updateAvatarUrlPromise);
}
const results = await Promise.allSettled(promises);
let successCount = 0;
for (const result of results) {
if (result.status === 'fulfilled') {
if (result.value.status === ApiStatus.OK) {
successCount++;
if (result.value.data.DisplayName) {
profile.displayName = result.value.data.DisplayName;
this.jovo.$session.data.playfab.isDisplayNameUpdated = true;
}
}
}
else {
// rejected
if (result.reason.error === 'NameNotAvailable') {
this.jovo.$session.data.playfab.isDisplayNameUpdated = false;
}
}
}
if (successCount > 0) {
this.jovo.$session.data.playfab.profile = profile;
result = true;
if (profile.extendedProfile && this.config.login.extendedProfileKey) {
const data = {
[this.config.login.extendedProfileKey]: profile.extendedProfile,
};
await this.updateUserData(data);
}
}
return result;
}
async updateStat(statName, value) {
console.debug('JovoPlayFab.updateStat');
const updatePlayerStatisticsRequest = {
PlayFabId: this.PlayFabId,
Statistics: [
{
StatisticName: statName,
Value: value,
CustomTags: { sessionId: this.jovo.$request.getSessionId() },
},
],
};
const updatePlayerStatistics = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.UpdatePlayerStatistics);
try {
const result = await updatePlayerStatistics(updatePlayerStatisticsRequest);
console.debug('PlayFabServer.UpdatePlayerStatistics', JSON.stringify(result, null, 2));
return true;
}
catch (error) {
console.error('PlayFabServer.UpdatePlayerStatistics', error);
}
return false;
}
async getStat(statName) {
let value = null;
const getPlayerStatisticsRequest = {
PlayFabId: this.PlayFabId,
StatisticNames: [statName],
};
const getPlayerStatistics = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.GetPlayerStatistics);
try {
const result = await getPlayerStatistics(getPlayerStatisticsRequest);
console.debug('PlayFabServer.GetPlayerStatistics', JSON.stringify(result, null, 2));
if (result.status === ApiStatus.OK &&
result.data.Statistics &&
result.data.Statistics.length > 0) {
value = result.data.Statistics[0].Value;
}
}
catch (error) {
console.error('PlayFabServer.GetPlayerStatistics', error);
}
return value;
}
async getLeaderboard(statName) {
var _a, _b, _c;
console.debug('JovoPlayFab.getLeaderboard');
const promises = [];
if (this.config.leaderboard.topMax > 0) {
const getLeaderboard = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.GetLeaderboard);
promises.push(getLeaderboard({
MaxResultsCount: this.config.leaderboard.topMax,
ProfileConstraints: this.config.leaderboard.profileConstraints,
StatisticName: statName,
StartPosition: 0,
}));
}
if (this.config.leaderboard.neighborMax > 0) {
const getLeaderboardAroundPlayer = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.GetLeaderboardAroundUser);
promises.push(getLeaderboardAroundPlayer({
PlayFabId: this.PlayFabId,
MaxResultsCount: this.config.leaderboard.neighborMax,
ProfileConstraints: this.config.leaderboard.profileConstraints,
StatisticName: statName,
}));
}
try {
const results = await Promise.all(promises);
let allEntries = [];
if (results.length === 2) {
allEntries = [
...((_a = results[0].data.Leaderboard) !== null && _a !== void 0 ? _a : []),
...((_b = results[1].data.Leaderboard) !== null && _b !== void 0 ? _b : []),
];
}
else {
allEntries = (_c = results[0].data.Leaderboard) !== null && _c !== void 0 ? _c : [];
}
const mappedEntries = allEntries.map((item) => {
const currentPlayerPlayFabId = this.jovo.$session.data.playfab.loginInfo.PlayFabId;
item.IsCurrentPlayer = item.PlayFabId === currentPlayerPlayFabId;
return item;
});
// remove duplicate entries
const combinedLeaderboard = mappedEntries.filter((item, index) => mappedEntries.findIndex((i) => i.PlayFabId === item.PlayFabId) === index);
if (this.config.leaderboard.userDataKeys.length > 0) {
// add user data
for (const entry of Object.values(combinedLeaderboard)) {
const userData = await this.getUserData(this.config.leaderboard.userDataKeys, entry.PlayFabId);
entry.UserData = userData;
}
}
return combinedLeaderboard;
}
catch (error) {
console.error('PlayFabServer Leaderboards', error);
}
return null;
}
async updateUserData(data, permission = UserDataPermission.Public) {
console.debug('JovoPlayFab.updateUserData');
const updateUserDataRequest = {
PlayFabId: this.PlayFabId,
Data: this.stringifyValues(data),
Permission: permission,
};
const updateUserData = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.UpdateUserData);
try {
const result = await updateUserData(updateUserDataRequest);
console.debug('PlayFabServer.UpdateUserData', JSON.stringify(result, null, 2));
return true;
}
catch (error) {
console.error('PlayFabServer.UpdateUserData', error);
}
return false;
}
async getUserData(keys, playFabId) {
console.debug('JovoPlayFab.getUserData');
let value;
if (!playFabId) {
playFabId = this.PlayFabId;
}
const getUserDataRequest = {
PlayFabId: playFabId,
Keys: Array.isArray(keys) ? keys : [keys],
};
const getUserData = (0, util_1.promisify)(playfab_sdk_1.PlayFabServer.GetUserData);
try {
const result = await getUserData(getUserDataRequest);
console.debug('PlayFabServer.GetUserData', JSON.stringify(result, null, 2));
if (result.status === ApiStatus.OK) {
value = this.parseUserDataRecords(result.data.Data);
}
}
catch (error) {
console.error('PlayFabServer.GetUserData', error);
}
return value;
}
stringifyValues(data) {
const newData = {};
for (const [k, v] of Object.entries(data)) {
newData[k] = JSON.stringify(v);
}
return newData;
}
parseUserDataRecords(data) {
var _a;
const newData = {};
if (!data) {
return newData;
}
for (const [k, v] of Object.entries(data)) {
const value = (_a = v === null || v === void 0 ? void 0 : v.Value) !== null && _a !== void 0 ? _a : '';
newData[k] = this.isJson(value) ? JSON.parse(value) : value.toString();
}
return newData;
}
isJson(value) {
try {
JSON.parse(value);
}
catch (e) {
return false;
}
return true;
}
}
exports.JovoPlayFab = JovoPlayFab;
//# sourceMappingURL=JovoPlayFab.js.map