Skip to content

Commit

Permalink
Merge pull request #209 from SimonStnn/dev
Browse files Browse the repository at this point in the history
1.10.1 update
  • Loading branch information
SimonStnn authored May 31, 2024
2 parents e51a041 + 3fc41d3 commit 285998f
Show file tree
Hide file tree
Showing 43 changed files with 584 additions and 156 deletions.
2 changes: 1 addition & 1 deletion components.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@
},
"aliases": {
"components": "@/popup/components",
"utils": "@utils"
"utils": "@/utils"
}
}
4 changes: 1 addition & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ module.exports = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
'^@const': '<rootDir>/src/const',
'^@utils': '<rootDir>/src/utils',
'^@components/(.*)$': '<rootDir>/src/components/$1',
'^@/components/(.*)$': '<rootDir>/src/popup/components/$1',
},
};
48 changes: 46 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "pop-a-loon",
"version": "1.10.0",
"version": "1.10.1",
"description": "The new rising trend (literally) that changes the browser game completely.",
"private": true,
"scripts": {
Expand Down Expand Up @@ -34,6 +34,7 @@
},
"dependencies": {
"@hookform/resolvers": "^3.3.4",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.5",
"@radix-ui/react-hover-card": "^1.0.7",
"@radix-ui/react-label": "^2.0.2",
Expand All @@ -44,6 +45,7 @@
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"js-abbreviation-number": "^1.4.0",
"loglevel": "^1.9.1",
"lucide-react": "^0.356.0",
"postcss-loader": "^8.1.0",
"react": "^18.2.0",
Expand Down
107 changes: 78 additions & 29 deletions src/background/background.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import browser from 'webextension-polyfill';
import { abbreviateNumber } from 'js-abbreviation-number';
import { AlarmName, Message, initalConfig } from '@const';
import storage from '@/storage';
import storage from '@/managers/storage';
import log, { type LogLevelNames } from '@/managers/log';
import remote from '@/remote';
import { AlarmName, Message, initalConfig } from '@/const';
import {
calculateBalloonSpawnDelay,
random,
getBrowser,
isRunningInBackground,
sendMessage,
} from '@utils';
} from '@/utils';

console.log(
"%cIf someone told you to copy/paste something here you have an 11/10 chance you're being scammed.",
'font-size:18px; color: red; font-weight: bold; padding: 25px 10px;'
);

const setBadgeNumber = (count: number) => {
browser.action.setBadgeText({
Expand All @@ -19,7 +25,7 @@ const setBadgeNumber = (count: number) => {

const updateBadgeColors = () => {
(async () => {
const config = await storage.get('config');
const config = await storage.sync.get('config');
browser.action.setBadgeBackgroundColor({
color: config.badge.backgroundColor,
});
Expand All @@ -31,45 +37,61 @@ const updateBadgeColors = () => {
// Check if the background script is running in the background
if (!isRunningInBackground()) return;

if (process.env.NODE_ENV === 'development') log.setLevel('debug');
else log.setLevel('info');

const rapidSpawnPenalty = 5 * 60 * 1000; // 5 minutes
let lastSpawn: number;
let spawnTimeout: number | null = null;

const setup = async () => {
log.info('Pop-a-loon version:', process.env.npm_package_version);
log.debug(`Mode: ${process.env.NODE_ENV}`);
log.debug('Browser:', getBrowser());
log.debug('Running in background:', isRunningInBackground());
log.debug(
'Logging level:',
log.toLogLevelName(log.getLevel()),
'(',
log.getLevel(),
')'
);
log.debug('');

// Clear all alarms
await browser.alarms.clearAll();

//! Fix for #145
try {
console.log('Checking for depricated balloonCount');
await storage.remove('balloonCount' as any);
log.debug('Checking for depricated balloonCount');
await storage.sync.remove('balloonCount' as any);
} catch (e) {}

const remoteAvailable = await remote.isAvailable();
if (!remoteAvailable) {
console.log('Remote is not available, retrying in 1 minute');
log.warn('Remote is not available, retrying in 1 minute');
await browser.alarms.create('restart', { when: Date.now() + 60000 });
return;
}

// Get the user from the local storage
let localUser = await storage.get('user');
let localUser = await storage.sync.get('user');
// If the user is not in the local storage, get a new user from the remote
if (!localUser) {
const usr = await remote.NewUser('Anonymous');
await storage.set('token', usr.token);
await storage.sync.set('token', usr.token);
localUser = usr;
}
// Get the user from the remote and save it to the local storage
const user = await remote.getUser(localUser.id);
await storage.set('user', user);
await storage.sync.set('user', user);

// Get the config from the remote
const remoteConfig = await remote.getConfiguration();
// Get the config from the local storage
const config = (await storage.get('config')) || initalConfig;
const config = (await storage.sync.get('config')) || initalConfig;
// Merge the local config with the remote config
await storage.set('config', {
await storage.sync.set('config', {
...initalConfig,
...config, // config overrides the initial config
...remoteConfig, // remoteConfig overrides the config
Expand All @@ -81,49 +103,70 @@ const updateBadgeColors = () => {
// Set badge number and colors
setBadgeNumber(user.count || 0);
updateBadgeColors();

log.debug('Setup complete');
};

const spawnBalloon = async () => {
log.groupCollapsed(
'info',
`(${new Date().toLocaleTimeString()}) Spawning Balloon...`
);
log.time('info', 'Spawn Time');

const now = Date.now();
const minSpawnInterval = (await storage.get('config')).spawnInterval.min;
const skipSpawnMessage = (note: any, level: 'log' | 'warn' = 'warn') =>
console[level](`Skipping spawnBalloon message: \r\n\t`, note);
const minSpawnInterval = (await storage.sync.get('config')).spawnInterval
.min;
const skipSpawnMessage = (note: any, level: LogLevelNames = 'softwarn') => {
log[level](`Skipping spawnBalloon message: \r\n\t`, note);
log.timeEnd('info', 'Spawn Time');
log.groupEnd('info');
};

// Check if there is a spawn timeout
if (spawnTimeout !== null && Date.now() < spawnTimeout)
return skipSpawnMessage('balloon spawn in timeout');
log.debug(' - No spawn timeout');

// Check if the last spawn was too recent
if (lastSpawn && now - lastSpawn < minSpawnInterval) {
spawnTimeout = now + rapidSpawnPenalty;
return skipSpawnMessage('Spawned too recently, setting timeout');
}

// Get all active tabs
const tabs = await browser.tabs.query({ active: true });
// Select a random tab
const num = Math.round(random(0, tabs.length - 1));
const tab = tabs[num];
if (!tab.id) return skipSpawnMessage('No tab id');
log.debug(' - Last spawn was not too recent');

// Check if the browser is idle
const state = await browser.idle.queryState(5 * 60);
if (state !== 'active') return skipSpawnMessage('Browser is idle', 'log');
if (state !== 'active') return skipSpawnMessage('Browser is idle');
log.debug(' - Browser is not idle');

// Check if no spawn alarms are already set
const alarms = await browser.alarms.getAll();
if (alarms.some((alarm) => alarm.name === 'spawnBalloon'))
return skipSpawnMessage('Spawn alarm already set');
console.log(`Spawning balloon on tab`, tab.id);
log.debug(' - No spawn alarm already set');

// Get all active tabs
const tabs = await browser.tabs.query({ active: true });
// Select a random tab
const num = Math.round(random(0, tabs.length - 1));
const tab = tabs[num];
if (!tab.id) return skipSpawnMessage('No tab id', 'warn');
log.debug(' - Selected tab', tab.id);

try {
// Execute content script on tab
await browser.scripting.executeScript({
files: ['spawn-balloon.js'],
target: { tabId: tab.id },
});
} catch (e) {}
log.info(' - Successfully sent spawn balloon script to tab', tab.id);
} catch (e) {
log.softerror(' - Error sending spawn balloon script to tab', tab.id, e);
}
lastSpawn = now;
log.timeEnd('info', 'Spawn Time');
log.groupEnd('info');
};

const createSpawnAlarm = async (name: AlarmName) => {
Expand All @@ -139,18 +182,20 @@ const updateBadgeColors = () => {
try {
// If extension is being run in firefox, set the browserAction popup
if (getBrowser() === 'Firefox' && !('action' in browser)) {
log.debug('Setting browser action to browser.browserAction');
(browser as any).action = (browser as any).browserAction;
}

await setup();
} catch (e) {
console.error(e);
console.log('Restarting in 1 minute');
log.error(e);
log.info('Restarting in 1 minute');
browser.alarms.create('restart', { when: Date.now() + 60000 });
}
};

browser.alarms.onAlarm.addListener(async (alarm) => {
log.debug('Alarm triggered', alarm.name);
switch (alarm.name as AlarmName) {
case 'spawnBalloon':
// Spawn a balloon
Expand All @@ -170,6 +215,7 @@ const updateBadgeColors = () => {
sender,
sendResponse
) {
log.debug('Message received:', message);
switch (message.action) {
case 'updateCounter':
setBadgeNumber(message.balloonCount);
Expand All @@ -178,8 +224,8 @@ const updateBadgeColors = () => {
case 'incrementCount':
// Increment the count and save it to the local storage
const newCount = await remote.incrementCount();
storage.set('user', {
...(await storage.get('user')),
storage.sync.set('user', {
...(await storage.sync.get('user')),
count: newCount.count,
});

Expand All @@ -192,6 +238,9 @@ const updateBadgeColors = () => {
// Call the listener again to update the badge number
messageListener(msg, sender, sendResponse);
break;
case 'setLogLevel':
log.setLevel(message.level);
break;
}
});

Expand Down
6 changes: 3 additions & 3 deletions src/balloon.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import browser from 'webextension-polyfill';
import storage from '@/storage';
import { getBalloonContainer, random, sendMessage } from '@utils';
import storage from '@/managers/storage';
import { getBalloonContainer, random, sendMessage } from '@/utils';

export const balloonResourceLocation = browser.runtime.getURL(
'resources/balloons/'
Expand Down Expand Up @@ -142,7 +142,7 @@ export default abstract class Balloon {
sendMessage({ action: 'incrementCount' });

// Set volume
this.popSound.volume = (await storage.get('config')).popVolume / 100;
this.popSound.volume = (await storage.sync.get('config')).popVolume / 100;
// Play the pop sound
this.popSound.play().catch((e) => {
this.popSound.src = defaultBalloonResourceLocation + 'pop.mp3';
Expand Down
Loading

0 comments on commit 285998f

Please sign in to comment.