wiimart-extension/classDefinitions.js
2025-07-06 13:07:52 -04:00

648 lines
20 KiB
JavaScript

// classDefinitions.js (This code runs in the page's main world)
// IMPORTANT: This script will now receive URLs via window.postMessage from the content script.
// These will be populated by the message listener
let _wiiShopSoundUrls_ = [];
let _wiiShopBgmUrl_ = '';
let _bgmInitiallyEnabled = false; // This flag will also be passed via postMessage if needed, or handled by content.js
let _bgmAlreadyPlaying = false; // This flag can be managed internally by wiiSound
// Add a variable to track the current status (matching your original logic)
let _currentstatus = "";
// --- Listener for messages from the content script ---
window.addEventListener('message', (event) => {
// Ensure the message is from our extension and the correct type
if (event.source === window && event.data && event.data.type === "WII_SHOP_EXTENSION_INIT") {
_wiiShopSoundUrls_ = event.data.soundUrls;
_wiiShopBgmUrl_ = event.data.bgmUrl;
_bgmInitiallyEnabled = event.data.bgmInitiallyEnabled; // Capture this if needed in classDefinitions.js
console.log("classDefinitions.js received URLs and initial BGM state from content script.");
// If you need to trigger BGM playback from *within* classDefinitions.js based on initial state, do it here
// However, your content.js already handles this by sending a message to the background, which is better.
// The _bgmInitiallyEnabled flag is now more for reference within this script if needed by other logic.
}
});
// Existing global variables exposed (these remain the same as your original)
var ecsUrl = "";
var iasUrl = "";
var ccsUrl = "";
var ucsUrl = "";
var tid = "";
var tsz = "";
var ttmdsz = "";
var lv = "";
window.ecsUrl = ecsUrl;
window.iasUrl = iasUrl;
window.ccsUrl = ccsUrl;
window.ucsUrl = ucsUrl;
window.tid = tid;
window.tsz = tsz;
window.ttmdsz = ttmdsz;
window.lv = lv;
window._currentstatus = _currentstatus; // Expose _currentstatus to the global scope
// Define the trace function
const trace = function(...args) {
if (typeof extensionStorage !== 'undefined' && typeof extensionStorage.slog === 'function') {
extensionStorage.slog(args.map(a => String(a)).join(' '));
}
console.log(...args);
};
// --- extensionStorage (remains largely the same, but will include sendMessageToBackground) ---
const storageCache = {};
const STORAGE_ENDPOINT = '/_extension_storage'; // This endpoint must be intercepted by background.js
const extensionStorage = {
set: (key, value) => {
storageCache[key] = value;
fetch(`${STORAGE_ENDPOINT}?set_key=${encodeURIComponent(key)}&set_value=${encodeURIComponent(value)}`)
.catch(e => console.error("[Page] Error sending storage_set:", e));
},
get: (key) => {
if (key in storageCache) return storageCache[key];
const request = new XMLHttpRequest();
// Use synchronous XHR for get, which is fine in page context
request.open('GET', `${STORAGE_ENDPOINT}?get=${encodeURIComponent(key)}`, false);
try {
request.send(null);
if (request.status === 200 || request.status === 0) { // status 0 for local file access in some contexts
const data = JSON.parse(request.responseText);
storageCache[key] = data.value;
return data.value;
}
} catch (e) {
console.error("[Page] Error getting storage via XMLHttpRequest:", e);
}
return null;
},
slog: (message) => {
fetch(`${STORAGE_ENDPOINT}?set_key=slogs&set_value=${encodeURIComponent(message)}`)
.catch(e => console.error("[Page] Error sending slog:", e));
},
getLogs: () => {
return extensionStorage.get('logs') || [];
},
clearLogs: () => {
fetch(`${STORAGE_ENDPOINT}?clogs=true`)
.catch(e => console.error("[Page] Error sending clearLogs:", e));
storageCache.logs = [];
},
spts: (points) => {
const pointsToAdd = parseInt(points) || 0;
if (pointsToAdd > 0) {
fetch(`${STORAGE_ENDPOINT}?set_key=spts&set_value=${pointsToAdd}`)
.catch(e => console.error("[Page] Error sending spts:", e));
}
},
getpts: () => {
const points = extensionStorage.get('pts');
return parseInt(points) || 0;
},
clearpts: () => {
fetch(`${STORAGE_ENDPOINT}?cpts=true`)
.catch(e => console.error("[Page] Error sending clearpts:", e));
storageCache.pts = 0;
},
// New method to send messages to the background script for BGM control
sendMessageToBackground: async (message) => {
let url = `${STORAGE_ENDPOINT}?action=${encodeURIComponent(message.action)}`;
if (message.bgmUrl) {
url += `&bgmUrl=${encodeURIComponent(message.bgmUrl)}`;
}
try {
await fetch(url);
} catch (e) {
console.error(`[Page] Error sending BGM command '${message.action}':`, e);
}
}
};
window.extensionStorage = extensionStorage;
console.log("Current points (from injected script):", extensionStorage.getpts());
console.log("Trace loaded (from injected script):", extensionStorage.getLogs());
// Define the ECommerceInterface class
class ECommerceInterface {
constructor() {
const unwantedPath = "/oss/serv/CheckRegistered.jsp";
if (window.location.pathname === unwantedPath) {
console.log("Do nothing...");
}
trace("ECommerceInterface initialized");
}
getTicketInfos(titleId) {
return {
length: 1,
get: function(index) {
if (index === 0) {
return {
deviceId: 222222,
limits: null
};
}
return null;
}
};
}
getTitleInfo(titleid) {
if (titleid === "0001000248414241") {
return {
titleId: titleid,
isOnDevice: true,
version: 21,
isTmdPresent: true,
occupiedUserBlocks: 0,
occupiedUserInodes: 0,
occupiedSysBlocks: 1599,
occupiedSysInodes: 23
}
} else {
return {
titleId: titleid,
isOnDevice: false,
version: 0,
isTmdPresent: false,
occupiedUserBlocks: 0,
occupiedUserInodes: 0,
occupiedSysBlocks: 0,
occupiedSysInodes: 0
}
}
}
getLog() {
return extensionStorage.getLogs() || "";
}
getPoints() {
return extensionStorage.getpts() || 0;
}
setPoints(newPoints) {
if (!Number.isInteger(newPoints)) {
newPoints = parseInt(newPoints, 10);
}
if (isNaN(newPoints)) {
console.error("Invalid points value provided:", newPoints);
return;
}
extensionStorage.spts(newPoints);
trace("Points updated to: " + extensionStorage.getpts());
}
loadPoints() {
console.log("nah i dont load points, they alr loaded");
}
cancelOperation() {
console.log("bro what do you want me to cancel");
}
setWebSvcUrls(ecsuri, iasuri) {
window.ecsUrl = ecsuri;
window.iasUrl = iasuri;
}
setContentUrls(ccsuri, ucsuri) {
window.ccsUrl = ccsuri;
window.ucsUrl = ucsuri;
}
getCachedBalance() {
window._currentstatus = "getCachedBalance"
const storedPoints = window.localStorage.getItem('points');
if (storedPoints) {
return parseInt(storedPoints, 10);
} else {
return 0;
}
}
refreshCachedBalance() {
window._currentstatus = "refreshCachedBalance"
return {
status: 0,
operation: "refreshCachedBalance",
description: "",
phase: 7,
isCancelRequested: "false",
downloadedSize: 0,
totalSize: 0,
errCode: 0,
errInfo: null,
};
}
checkDeviceStatus() {
window._currentstatus = "checkDeviceStatus";
return {
status: 0,
operation: "checkDeviceStatus",
description: "",
phase: 17,
isCancelRequested: "false",
downloadedSize: 0,
totalSize: 0,
errCode: 0,
errInfo: null,
};
}
getDeviceInfo() {
return {
country: "US",
region: "USA",
isParentalControlEnabled: false,
userAge: 20,
language: "fr",
accountId: "659247864",
deviceId: "4587571479",
serial: "PC156494873",
maxUserInodes: 200000,
usedUserInodes: 100000,
freeChannelAppCount: 41,
blockSize: 536870912,
totalBlocks: 65536,
usedBlocks: 0,
totalSysBlocks: 65536,
usedSysBlocks: 0,
titleId: "0001000248414241",
accountCountry: "CA",
deviceCode: "0302167078436756",
accountDeviceCode: "0302167078436756",
isKeyPairConfirmed: function() { return true; },
registrationStatus: "R",
};
}
setSessionValue(key, value) {
extensionStorage.set(key, value);
}
getSessionValue(key) {
return extensionStorage.get(key);
}
pubKeyEncrypt(nah) {
console.log("behonest this is not required: " + nah);
return nah;
}
purchasePoints(pointsToBuy, itemId, price, payment, taxes, purchaseInfo, discount) {
this.setPoints(pointsToBuy);
return 100;
}
getProgress() {
var downsize = 0;
if (window._currentstatus === "checkRegistration") {
downsize = 727;
} else if (window._currentstatus === "syncRegistration") {
downsize = 913;
} else if (window._currentstatus === "checkDeviceStatus") {
downsize = 846;
} else if (window._currentstatus === "refreshCachedBalance") {
downsize = 731;
} else {
downsize = 0;
}
return {
"status": 0,
"operation": window._currentstatus,
"description": "",
"phase": 2,
"isCancelRequested": false,
"downloadedSize": downsize,
"totalSize": 0,
"errCode": 0,
"errInfo": null
};
}
checkRegistration() {
window._currentstatus = "checkRegistration";
return {
"status": 0,
"operation": "checkRegistration",
"description": "",
"phase": 11,
"isCancelRequested": false,
"downloadedSize": 0,
"totalSize": 0,
"errCode": 0,
"errInfo": null
};
}
syncRegistration(value) {
console.log("idk what to do with this: " + value);
window._currentstatus = "syncRegistration";
return {
"status": 0,
"operation": "syncRegistration",
"description": "",
"phase": 18,
"isCancelRequested": false,
"downloadedSize": 0,
"totalSize": 0,
"errCode": 0,
"errInfo": null
};
}
getWeakToken() {
return "iamaweaktoken";
}
getVersion() {
return parseInt("21");
}
request(value) {
if (value === "checkRegistration") {
return this.checkRegistration();
} else if (value === "checkDeviceStatus") {
return this.checkDeviceStatus();
} else if (value === "refreshCachedBalance") {
return this.refreshCachedBalance();
} else if (value === "getCachedBalance") {
return this.getCachedBalance();
}
}
}
class wiiShop {
constructor() {
trace("wiiShop initialized");
return "isok";
}
connecting = null;
retry() {
window.location.pathname = "/oss/serv/W_01.jsp";
}
endWaiting() {
console.log("Currently does nothing endwaiting");
}
enableHRP() {
console.log("Does Jack shit homebuttonenabler");
}
disableHRP() {
console.log("Does jack shit home button disabler")
}
sleep(duration) {
return new Promise(resolve => setTimeout(resolve, duration));
}
async beginWaiting(seconds) {
if (seconds == null) {
seconds = 3;
}
if (typeof seconds === 'string') {
const parsedValue = parseInt(seconds, 10);
if (isNaN(parsedValue) || parsedValue.toString() !== seconds) {
console.error("Invalid input: Please provide a valid integer value.");
return;
}
seconds = parsedValue;
}
if (!Number.isInteger(seconds)) {
console.error("Invalid input: Please provide an integer value.");
return;
}
let duration;
duration = (seconds < 10) ? seconds * 1000 : seconds;
await this.sleep(duration);
console.log("Wait complete!");
}
isCompatibleMode() {
return true;
}
launchCode = 0;
}
class wiiSound {
// These will now be populated by the message listener
static audioUrls = [];
static bgmUrl = '';
static currentBgmAudio = null; // Stays static to manage a single BGM instance
constructor() {
trace("wiiSound initialized");
// No need to copy _injected variables here, as they'll be populated by the message listener
}
playSE(snd) {
// Ensure URLs are available before attempting to play
if (!_wiiShopSoundUrls_ || _wiiShopSoundUrls_.length === 0) {
console.warn("Audio URLs not yet loaded. Cannot play sound effect.");
return;
}
const soundIndex = parseInt(snd, 10);
if (isNaN(soundIndex) || soundIndex < 1 || soundIndex >= _wiiShopSoundUrls_.length) {
console.warn("Invalid sound index for wiiSound.playSE:", snd);
return;
}
const audioUrl = _wiiShopSoundUrls_[soundIndex];
if (!audioUrl) {
console.warn("No audio URL found for sound index:", soundIndex);
return;
}
const audio = new Audio(audioUrl);
audio.style.display = 'none';
audio.play()
.then(() => {
console.log('Wii Shop Sound played:', soundIndex, audioUrl);
})
.catch(error => {
console.error('Error playing Wii Shop Sound:', soundIndex, audioUrl, error);
});
}
playBGM() {
// Use an internal flag for _bgmAlreadyPlaying
if (_bgmAlreadyPlaying === true) {
return "nah mate, i aint playin for ya, im already playin";
} else {
_bgmAlreadyPlaying = true;
if (wiiSound.currentBgmAudio && !wiiSound.currentBgmAudio.paused) {
wiiSound.currentBgmAudio.pause();
wiiSound.currentBgmAudio.currentTime = 0;
console.log('Stopped previous BGM.');
}
// Ensure BGM URL is available to send via extensionStorage
if (!_wiiShopBgmUrl_) {
console.warn("No BGM URL available to send to background script.");
return;
}
// Use extensionStorage.sendMessageToBackground to control BGM in background
if (typeof window.extensionStorage !== 'undefined' && typeof window.extensionStorage.sendMessageToBackground === 'function') {
window.extensionStorage.sendMessageToBackground({
action: "playBGM",
bgmUrl: _wiiShopBgmUrl_
}).then(() => {
trace('Request to play BGM sent to background script via extensionStorage.');
}).catch(error => {
console.error('Error sending playBGM message to background via extensionStorage:', error);
});
} else {
console.warn("window.extensionStorage.sendMessageToBackground not available for playBGM.");
}
}
}
stopBGM() {
// Use an internal flag for _bgmAlreadyPlaying
if (_bgmAlreadyPlaying === true) {
_bgmAlreadyPlaying = false; // Reset the flag
// Send a message to background via extensionStorage to stop BGM
if (typeof window.extensionStorage !== 'undefined' && typeof window.extensionStorage.sendMessageToBackground === 'function') {
window.extensionStorage.sendMessageToBackground({
action: "stopBGM"
}).then(() => {
trace('Request to stop BGM sent to background script via extensionStorage.');
}).catch(error => {
console.error('Error sending stopBGM message to background via extensionStorage:', error);
});
} else {
console.warn("window.extensionStorage.sendMessageToBackground not available for stopBGM.");
}
} else {
return "wtf do you want me to stop eh?";
}
}
}
class wiiKeyboard {
constructor() {
trace("wiiKeyboard initialized");
}
}
class ECCreditCardEncryptedPayment {
constructor(smth) {
this.smth = smth;
}
}
class ECPrice {
constructor(uhh, ahh) {
return uhh;
}
}
class wiiSDCard {
constructor() {
return;
}
}
class wiiNwc24 {
constructor() {
return;
}
sendable() {
return true;
}
mailErrNo() {
return null;
}
errMsg() {
return null;
}
getFriendNum() {
return 5;
}
getFriendInfo(fnm, data) {
if (typeof fnm === 'string') {
const parsedValue = parseInt(fnm, 10);
if (isNaN(parsedValue) || parsedValue.toString() !== fnm) {
console.error("Invalid input: Please provide a valid integer value.");
return;
}
fnm = parsedValue;
}
if (data == "name") {
if (fnm == 0) {
return "User1";
} else if (fnm == 1) {
return "User2";
} else if (fnm == 2) {
return "User3";
} else if (fnm == 3) {
return "User4";
} else if (fnm == 4) {
return "User5";
}
}
if (data == "userId") {
if (fnm == 0) {
return "3630753603591712";
} else if (fnm == 1) {
return "3630753603591712";
} else if (fnm == 2) {
return "3630753603591712";
} else if (fnm == 3) {
return "3630753603591712";
} else if (fnm == 4) {
return "3630753603591712";
}
}
if (data == "miiImage") {
return "111"
}
}
myUserId = "0302167078436756";
}
class wiiDlTask {
constructor() {
trace("WiiDlTask init");
}
addDownloadTask(url, interval){
trace("yes i got it dw i will download it :tro:");
}
}
class wiiMii {
constructor() {
trace("wiiMii init");
}
}
window.ECommerceInterface = ECommerceInterface;
window.ECCreditCardEncryptedPayment = ECCreditCardEncryptedPayment;
window.ECPrice = ECPrice;
window.wiiKeyboard = wiiKeyboard;
window.wiiShop = wiiShop;
window.wiiSound = wiiSound;
window.wiiMii = wiiMii;
window.wiiDlTask = wiiDlTask;
window.wiiNwc24 = wiiNwc24;
window.wiiSDCard = wiiSDCard;
if (_bgmInitiallyEnabled) {
// Use a short delay or an event listener to ensure all page elements are ready
// and to potentially work around immediate autoplay blocks (though not guaranteed).
document.addEventListener('DOMContentLoaded', () => {
if (window.wiiSound) {
const soundInstance = new window.wiiSound();
soundInstance.playBGM();
}
});
}