Merge pull request #6 from StarManTheGamer/main

PRETTIER MY BELOVED!!!!!!!!!!!!!!!!!!!!!!
This commit is contained in:
Index 2024-05-27 20:26:42 -05:00 committed by GitHub
commit 28e483b02e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
42 changed files with 21923 additions and 6012 deletions

51
.github/workflows/prettier.yml vendored Normal file
View file

@ -0,0 +1,51 @@
name: Prettier Format and Commit
on:
push:
branches:
- main
- 'refs/heads/*'
jobs:
prettier:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Node.js
uses: actions/setup-node@v4
with:
node-version: 'latest'
- name: Install dependencies
run: npm install
- name: Pull latest changes
run: git pull
- name: Run Prettier
run: npx prettier --write .
- name: Commit changes
id: commit
run: |
git config --global user.name "github-actions[bot]"
git config --global user.email "github-actions[bot]@users.noreply.github.com"
git add .
if git diff-index --quiet HEAD; then
echo "No changes to commit."
echo "changes_committed=false" >> $GITHUB_ENV
else
git commit -m "chore: format code with Prettier"
echo "changes_committed=true" >> $GITHUB_ENV
fi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Push changes
if: env.changes_committed == 'true'
run: git push
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

1
.gitignore vendored
View file

@ -1 +1,2 @@
.DS_Store
/node_modules/

17
.prettierrc Normal file
View file

@ -0,0 +1,17 @@
{
"arrowParens": "always",
"bracketSpacing": false,
"printWidth": 200,
"singleQuote": true,
"trailingComma": "none",
"useTabs": true,
"plugins": ["prettier-plugin-jinja-template"],
"overrides": [
{
"files": "*.html",
"options": {
"parser": "jinja-template"
}
}
]
}

View file

@ -41,9 +41,11 @@ And there is more to come!
# Supported Browsers
As of right now, Poly+ only works on Chromium-based browsers. Currently, there are no plans to bring it to other browsers in the future.
> TL;DR Chromium-based browsers
## Examples of Browsers that are Chromium-based
- Google Chrome
- Chromium
- Edge
@ -56,12 +58,12 @@ As of right now, Poly+ only works on Chromium-based browsers. Currently, there a
## How to Download - Stable Build?
1. Go to the releases section of this GitHub repository
3. Go to the latest release and download the .ZIP file for that release
4. Extract the .ZIP
5. Enable developer mode on your browser (developer mode allows you to load unpacked extensions)
6. Click the "Load Unpacked" button
7. When the file selector comes up, open the unzipped folder from this GitHub repository
8. Go to Polytoria and you should see some changes!
2. Go to the latest release and download the .ZIP file for that release
3. Extract the .ZIP
4. Enable developer mode on your browser (developer mode allows you to load unpacked extensions)
5. Click the "Load Unpacked" button
6. When the file selector comes up, open the unzipped folder from this GitHub repository
7. Go to Polytoria and you should see some changes!
## How to Download - Pre-Release Build?
@ -73,6 +75,6 @@ As of right now, Poly+ only works on Chromium-based browsers. Currently, there a
4. Extract the .ZIP
5. Enable developer mode on your browser (developer mode allows you to load unpacked extensions)
6. Go to your browsers extensions page (usually `browserName://extensions`)
8. Click the "Load Unpacked" button
9. When the file selector comes up, open the unzipped folder of this repository's source code
10. Go to Polytoria and you should see some changes!
7. Click the "Load Unpacked" button
8. When the file selector comes up, open the unzipped folder of this repository's source code
9. Go to Polytoria and you should see some changes!

File diff suppressed because one or more lines are too long

View file

@ -2,22 +2,22 @@
FRONTEND FIXES / SPACING IMPROVEMENTS
*/
body[data-URL^="/my/friends"] .col-lg-3 {
margin-bottom: 20px;
body[data-URL^='/my/friends'] .col-lg-3 {
margin-bottom: 20px;
}
body[data-URL^="/create/"] .mt-2.mt-lg-0.col-lg.d-flex.align-content-between.flex-wrap {
width: 50%;
body[data-URL^='/create/'] .mt-2.mt-lg-0.col-lg.d-flex.align-content-between.flex-wrap {
width: 50%;
}
body[data-URL^="/create/"] .col.d-flex.align-content-between.flex-wrap {
width: 50%;
body[data-URL^='/create/'] .col.d-flex.align-content-between.flex-wrap {
width: 50%;
}
.text-truncate {
white-space: nowrap !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
white-space: nowrap !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
}
/* ------------------------------------------ */
@ -26,11 +26,19 @@ body[data-URL^="/create/"] .col.d-flex.align-content-between.flex-wrap {
INLINE EDITING
*/
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-visible {display: block !important;}
.polyplus-inlineEditing-visible {display: none;}
body[data-polyplus-inlineEditing='true'] .polyplus-inlineEditing-visible {
display: block !important;
}
.polyplus-inlineEditing-visible {
display: none;
}
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display: none !important;}
.polyplus-inlineEditing-hidden {display: block;}
body[data-polyplus-inlineEditing='true'] .polyplus-inlineEditing-hidden {
display: none !important;
}
.polyplus-inlineEditing-hidden {
display: block;
}
/* ------------------------------------------ */
@ -38,12 +46,13 @@ body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display
MODALS
*/
html:has(.polyplus-modal[open]), body:has(.polyplus-modal[open]) {
overflow: hidden;
html:has(.polyplus-modal[open]),
body:has(.polyplus-modal[open]) {
overflow: hidden;
}
.polyplus-modal::backdrop {
background: rgba(0, 0, 0, 0.73);
background: rgba(0, 0, 0, 0.73);
}
/* ------------------------------------------ */

View file

@ -1,24 +1,24 @@
let PageContainer = document.querySelector('.container.p-0.p-lg-5')
let PageContainer = document.querySelector('.container.p-0.p-lg-5');
let ItemGrid;
let Wearing;
let Tabs;
let IFrame;
let TabSelected = 'hat'
let TabSelected = 'hat';
let Search;
let Page = 1
let Page = 1;
let Avatar = {
"useCharacter": true,
"items": [],
"shirt": null,
"pants": null,
"tool": {ID: -1, URL: null},
"headColor": "#e0e0e0",
"torsoColor": "#e0e0e0",
"leftArmColor": "#e0e0e0",
"rightArmColor": "#e0e0e0",
"leftLegColor": "#e0e0e0",
"rightLegColor": "#e0e0e0"
}
useCharacter: true,
items: [],
shirt: null,
pants: null,
tool: {ID: -1, URL: null},
headColor: '#e0e0e0',
torsoColor: '#e0e0e0',
leftArmColor: '#e0e0e0',
rightArmColor: '#e0e0e0',
leftLegColor: '#e0e0e0',
rightLegColor: '#e0e0e0'
};
let ItemCardContents = `
<div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container">
@ -37,336 +37,353 @@ let ItemCardContents = `
by <a href="/users/:CreatorID" class="text-reset">:CreatorName</a>
</small>
</div>
`
`;
if (new URLSearchParams(new URL(window.location).search).get('sandbox') === 'true') {
console.log('Avatar Sandbox!')
console.log('Avatar Sandbox!');
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function(html){
PageContainer.innerHTML = html
ItemGrid = document.getElementById('inventory')
Wearing = document.getElementById('wearing')
Tabs = document.getElementById('tabs')
IFrame = document.getElementById('viewFrame')
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function (html) {
PageContainer.innerHTML = html;
ItemGrid = document.getElementById('inventory');
Wearing = document.getElementById('wearing');
Tabs = document.getElementById('tabs');
IFrame = document.getElementById('viewFrame');
Search = document.getElementById('item-search')
Search.addEventListener('change', function(){
RefreshItems()
});
Search = document.getElementById('item-search');
Search.addEventListener('change', function () {
RefreshItems();
});
UpdateAvatar()
RefreshItems()
UpdateAvatar();
RefreshItems();
Array.from(Tabs.children).forEach(element => {
element.addEventListener('click', function(){
let Link = element.getElementsByTagName('a')[0]
if (!(Link.classList.contains('active'))) {
Link.classList.add('active')
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active')
TabSelected = Link.getAttribute('data-tab')
Page = 1
RefreshItems()
}
});
});
Array.from(Tabs.children).forEach((element) => {
element.addEventListener('click', function () {
let Link = element.getElementsByTagName('a')[0];
if (!Link.classList.contains('active')) {
Link.classList.add('active');
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active');
TabSelected = Link.getAttribute('data-tab');
Page = 1;
RefreshItems();
}
});
});
let Clear = document.getElementById('clear')
Clear.addEventListener('click', function(){
Avatar = {
"useCharacter": true,
"items": [],
"shirt": {ID: -1, URL: null},
"pants": {ID: -1, URL: null},
"tool": {ID: -1, URL: null},
"headColor": "#e0e0e0",
"torsoColor": "#e0e0e0",
"leftArmColor": "#e0e0e0",
"rightArmColor": "#e0e0e0",
"leftLegColor": "#e0e0e0",
"rightLegColor": "#e0e0e0"
}
UpdateAvatar()
});
let Clear = document.getElementById('clear');
Clear.addEventListener('click', function () {
Avatar = {
useCharacter: true,
items: [],
shirt: {ID: -1, URL: null},
pants: {ID: -1, URL: null},
tool: {ID: -1, URL: null},
headColor: '#e0e0e0',
torsoColor: '#e0e0e0',
leftArmColor: '#e0e0e0',
rightArmColor: '#e0e0e0',
leftLegColor: '#e0e0e0',
rightLegColor: '#e0e0e0'
};
UpdateAvatar();
});
let JSONUpload = document.getElementById('jsonUpload')
JSONUpload.addEventListener('change', function(){
let Reader = new FileReader()
Reader.addEventListener('loadend', function(){
Avatar = JSON.parse(Reader.result)
UpdateAvatar()
let JSONUpload = document.getElementById('jsonUpload');
JSONUpload.addEventListener('change', function () {
let Reader = new FileReader();
Reader.addEventListener('loadend', function () {
Avatar = JSON.parse(Reader.result);
UpdateAvatar();
JSONUpload.value = ""
});
JSONUpload.value = '';
});
Reader.readAsText(JSONUpload.files[0])
});
Reader.readAsText(JSONUpload.files[0]);
});
let JSONSave = document.getElementById('jsonSave')
JSONSave.addEventListener('click', function(){
FormatAvatar().then(FormattedAvatar => {
let Download = document.createElement('a')
Download.href = URL.createObjectURL(new Blob([JSON.stringify(FormattedAvatar)], {
type: "application/json"
}));
Download.setAttribute('download', 'AvatarSandbox.json')
document.body.appendChild(Download)
Download.click()
document.body.removeChild(Download)
});
});
let JSONSave = document.getElementById('jsonSave');
JSONSave.addEventListener('click', function () {
FormatAvatar().then((FormattedAvatar) => {
let Download = document.createElement('a');
Download.href = URL.createObjectURL(
new Blob([JSON.stringify(FormattedAvatar)], {
type: 'application/json'
})
);
Download.setAttribute('download', 'AvatarSandbox.json');
document.body.appendChild(Download);
Download.click();
document.body.removeChild(Download);
});
});
let OpenInNewTab = document.getElementById('openNewTab')
OpenInNewTab.addEventListener('click', function(){
UpdateAvatar()
});
});
let OpenInNewTab = document.getElementById('openNewTab');
OpenInNewTab.addEventListener('click', function () {
UpdateAvatar();
});
});
}
function UpdateAvatar() {
GenerateHash()
.then(hash => {
IFrame.addEventListener('load', function () {
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
});
IFrame.src = 'about:blank';
});
GenerateHash().then((hash) => {
IFrame.addEventListener('load', function () {
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
});
IFrame.src = 'about:blank';
});
}
function LoadFile(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); }
xhr.open("GET", path, true);
xhr.send();
var xhr = new XMLHttpRequest();
xhr.onload = function () {
return callback(this.responseText);
};
xhr.open('GET', path, true);
xhr.send();
}
async function GenerateHash() {
let FormattedAvatar = await FormatAvatar()
for (let i = 0; i < FormattedAvatar.items.length; i++) {
FormattedAvatar.items[i] = FormattedAvatar.items[i].URL
}
if (FormattedAvatar.shirt) {
FormattedAvatar.shirt = FormattedAvatar.shirt.URL
}
if (FormattedAvatar.pants) {
FormattedAvatar.pants = FormattedAvatar.pants.URL
}
FormattedAvatar.face = FormattedAvatar.face.URL
if (FormattedAvatar.tool) {
FormattedAvatar.tool = FormattedAvatar.tool.URL
}
console.log('Formatted Avatar: ', FormattedAvatar)
console.log('Real Avatar: ', Avatar)
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)))
let FormattedAvatar = await FormatAvatar();
for (let i = 0; i < FormattedAvatar.items.length; i++) {
FormattedAvatar.items[i] = FormattedAvatar.items[i].URL;
}
if (FormattedAvatar.shirt) {
FormattedAvatar.shirt = FormattedAvatar.shirt.URL;
}
if (FormattedAvatar.pants) {
FormattedAvatar.pants = FormattedAvatar.pants.URL;
}
FormattedAvatar.face = FormattedAvatar.face.URL;
if (FormattedAvatar.tool) {
FormattedAvatar.tool = FormattedAvatar.tool.URL;
}
console.log('Formatted Avatar: ', FormattedAvatar);
console.log('Real Avatar: ', Avatar);
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)));
}
async function FormatAvatar() {
let LocalAvatar = structuredClone(Avatar)
let LocalAvatar = structuredClone(Avatar);
if (!LocalAvatar.face) {
LocalAvatar.face = {ID: -1, URL: "https://c0.ptacdn.com/static/3dview/DefaultFace.png"}
}
if (!LocalAvatar.face) {
LocalAvatar.face = {ID: -1, URL: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png'};
}
for (let i = 0; i < LocalAvatar.items.length; i++) {
if (LocalAvatar.items[i].URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve-mesh/:id".replace(':id', LocalAvatar.items[i].ID))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Avatar.items[i].URL = data.url
LocalAvatar.items[i].URL = data.url
})
.catch(error => {
console.error('Fetch error:', error);
});
}
}
for (let i = 0; i < LocalAvatar.items.length; i++) {
if (LocalAvatar.items[i].URL === null) {
await fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', LocalAvatar.items[i].ID))
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Avatar.items[i].URL = data.url;
LocalAvatar.items[i].URL = data.url;
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
}
if (LocalAvatar.tool && LocalAvatar.tool.ID !== -1 && LocalAvatar.tool.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve-mesh/:id".replace(':id', LocalAvatar.tool.ID))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Avatar.tool.URL = data.url
LocalAvatar.tool.URL = data.url
})
.catch(error => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.tool && LocalAvatar.tool.ID !== -1 && LocalAvatar.tool.URL === null) {
await fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', LocalAvatar.tool.ID))
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Avatar.tool.URL = data.url;
LocalAvatar.tool.URL = data.url;
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.face.ID !== -1 && LocalAvatar.face.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.face.ID))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Avatar.face.URL = data.url
LocalAvatar.face.URL = data.url
})
.catch(error => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.face.ID !== -1 && LocalAvatar.face.URL === null) {
await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.face.ID))
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Avatar.face.URL = data.url;
LocalAvatar.face.URL = data.url;
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.shirt && LocalAvatar.shirt.ID !== -1 && LocalAvatar.shirt.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.shirt.ID))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Avatar.shirt.URL = data.url
LocalAvatar.shirt.URL = data.url
})
.catch(error => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.shirt && LocalAvatar.shirt.ID !== -1 && LocalAvatar.shirt.URL === null) {
await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.shirt.ID))
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Avatar.shirt.URL = data.url;
LocalAvatar.shirt.URL = data.url;
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.pants && LocalAvatar.pants.ID !== -1 && LocalAvatar.pants.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.pants.ID))
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Avatar.pants.URL = data.url
LocalAvatar.pants.URL = data.url
})
.catch(error => {
console.error('Fetch error:', error);
});
}
if (LocalAvatar.pants && LocalAvatar.pants.ID !== -1 && LocalAvatar.pants.URL === null) {
await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.pants.ID))
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Avatar.pants.URL = data.url;
LocalAvatar.pants.URL = data.url;
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
return LocalAvatar
return LocalAvatar;
}
function RefreshItems() {
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Array.from(ItemGrid.children).forEach(element => {element.remove()});
data = data.assets
data.forEach(item => {
let NewItemCard = document.createElement('div')
NewItemCard.classList = 'col-auto'
NewItemCard.innerHTML = ItemCardContents.replace(':ItemName', item.name).replace().replace(':ItemID', item.id).replace(':ItemType', item.type.replace(item.type.charAt(0), item.type.charAt(0).toUpperCase())).replace(':CreatorName', item.creator.name).replace(':CreatorID', item.creator.id).replace(':ItemThumbnail', item.thumbnail)
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function(){
WearAsset(NewItemCard, item.name, {Name: item.creator.name, ID: item.creator.id}, item.id, item.type, item.thumbnail)
});
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Array.from(ItemGrid.children).forEach((element) => {
element.remove();
});
data = data.assets;
data.forEach((item) => {
let NewItemCard = document.createElement('div');
NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = ItemCardContents.replace(':ItemName', item.name)
.replace()
.replace(':ItemID', item.id)
.replace(':ItemType', item.type.replace(item.type.charAt(0), item.type.charAt(0).toUpperCase()))
.replace(':CreatorName', item.creator.name)
.replace(':CreatorID', item.creator.id)
.replace(':ItemThumbnail', item.thumbnail);
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item.name, {Name: item.creator.name, ID: item.creator.id}, item.id, item.type, item.thumbnail);
});
ItemGrid.appendChild(NewItemCard)
});
})
.catch(error => {
console.error('Fetch error:', error);
});
ItemGrid.appendChild(NewItemCard);
});
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
function WearAsset(element, name, creator, id, type, thumbnail) {
switch (type) {
case 'hat':
let Index = CheckItemID(Avatar.items, id)
if (Index === -1) {
if (Avatar.items.length !== 3) {
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail})
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
} else {
Avatar.items.splice(0, 1)
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail})
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
} else {
console.log('remove')
Avatar.items.splice(Index, 1)
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
break
case 'face':
if (Avatar.face && Avatar.face.ID !== id) {
Avatar.face = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
} else {
Avatar.face = {Name: "Default Face", Creator: {Name: "Polytoria", ID: 1}, ID: -1, URL: "https://c0.ptacdn.com/static/3dview/DefaultFace.png", Thumbnail: "https://c0.ptacdn.com/static/3dview/DefaultFace.png"}
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
break
case 'tool':
if (Avatar.tool && Avatar.tool.ID !== id) {
Avatar.tool = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
} else {
Avatar.tool = null
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
break
case 'shirt':
if (Avatar.shirt.ID !== id) {
Avatar.shirt = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
} else {
Avatar.shirt = null
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
break
case 'pants':
if (Avatar.pants.ID !== id) {
Avatar.pants = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
} else {
Avatar.pants = null
if (TabSelected === type) {
console.log('tab is', TabSelected, type)
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`))
}
}
break
}
switch (type) {
case 'hat':
let Index = CheckItemID(Avatar.items, id);
if (Index === -1) {
if (Avatar.items.length !== 3) {
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail});
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else {
Avatar.items.splice(0, 1);
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail});
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
} else {
console.log('remove');
Avatar.items.splice(Index, 1);
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
case 'face':
if (Avatar.face && Avatar.face.ID !== id) {
Avatar.face = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else {
Avatar.face = {
Name: 'Default Face',
Creator: {Name: 'Polytoria', ID: 1},
ID: -1,
URL: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png',
Thumbnail: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png'
};
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
case 'tool':
if (Avatar.tool && Avatar.tool.ID !== id) {
Avatar.tool = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else {
Avatar.tool = null;
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
case 'shirt':
if (Avatar.shirt.ID !== id) {
Avatar.shirt = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else {
Avatar.shirt = null;
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
case 'pants':
if (Avatar.pants.ID !== id) {
Avatar.pants = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else {
Avatar.pants = null;
if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
}
UpdateAvatar()
UpdateAvatar();
}
function CheckItemID(object, id) {
for (let i = 0; i < object.length; i++) {
if (object[i] === id || object[i].ID === id) {
console.log('Index: ' + i)
return i
}
}
return -1
for (let i = 0; i < object.length; i++) {
if (object[i] === id || object[i].ID === id) {
console.log('Index: ' + i);
return i;
}
}
return -1;
}

View file

@ -1,240 +1,241 @@
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const BodyColors = [
"#f8f8f8",
"#cdcdcd",
"#111111",
"#ff0000",
"#a34b4b",
"#ffc9c9",
"#957977",
"#c4281c",
"#da867a",
"#694028",
"#cc8e69",
"#a05f35",
"#7c5c46",
"#eab892",
"#da8541",
"#aa5500",
"#ffcc99",
"#e29b40",
"#ffaf00",
"#ffb000",
"#d7c59a",
"#f5cd30",
"#fdea8d",
"#e5e4df",
"#c1be42",
"#ffff00",
"#ffffcc",
"#a4bd47",
"#7f8e64",
"#a1c48c",
"#3a7d15",
"#4b974b",
"#00ff00",
"#ccffcc",
"#27462d",
"#287f47",
"#789082",
"#9ff3e9",
"#12eed4",
"#f2f3f3",
"#00ffff",
"#008f9c",
"#04afec",
"#80bbdb",
"#b4d2e4",
"#0d69ac",
"#1b2a35",
"#afddff",
"#6e99ca",
"#74869d",
"#2154b9",
"#002060",
"#0000ff",
"#b1a7ff",
"#a3a2a5",
"#6225d1",
"#b480ff",
"#8c5b9f",
"#6b327c",
"#aa00aa",
"#635f62",
"#ff00bf",
"#ff66cc",
"#e8bac8"
]
'#f8f8f8',
'#cdcdcd',
'#111111',
'#ff0000',
'#a34b4b',
'#ffc9c9',
'#957977',
'#c4281c',
'#da867a',
'#694028',
'#cc8e69',
'#a05f35',
'#7c5c46',
'#eab892',
'#da8541',
'#aa5500',
'#ffcc99',
'#e29b40',
'#ffaf00',
'#ffb000',
'#d7c59a',
'#f5cd30',
'#fdea8d',
'#e5e4df',
'#c1be42',
'#ffff00',
'#ffffcc',
'#a4bd47',
'#7f8e64',
'#a1c48c',
'#3a7d15',
'#4b974b',
'#00ff00',
'#ccffcc',
'#27462d',
'#287f47',
'#789082',
'#9ff3e9',
'#12eed4',
'#f2f3f3',
'#00ffff',
'#008f9c',
'#04afec',
'#80bbdb',
'#b4d2e4',
'#0d69ac',
'#1b2a35',
'#afddff',
'#6e99ca',
'#74869d',
'#2154b9',
'#002060',
'#0000ff',
'#b1a7ff',
'#a3a2a5',
'#6225d1',
'#b480ff',
'#8c5b9f',
'#6b327c',
'#aa00aa',
'#635f62',
'#ff00bf',
'#ff66cc',
'#e8bac8'
];
let PageContainer = document.querySelector('.container.p-0.p-lg-5')
let PageContainer = document.querySelector('.container.p-0.p-lg-5');
let ItemGrid;
let Wearing;
let Tabs;
let IFrame;
let TabSelected = 'hat'
let TabSelected = 'hat';
let Search;
let Page = 1
let Page = 1;
let Avatar = {
"useCharacter": true,
"items": [
24122
],
"shirt": 24118,
"pants": 24123,
"headColor": "#e0e0e0",
"torsoColor": "#e0e0e0",
"leftArmColor": "#e0e0e0",
"rightArmColor": "#e0e0e0",
"leftLegColor": "#e0e0e0",
"rightLegColor": "#e0e0e0"
}
useCharacter: true,
items: [24122],
shirt: 24118,
pants: 24123,
headColor: '#e0e0e0',
torsoColor: '#e0e0e0',
leftArmColor: '#e0e0e0',
rightArmColor: '#e0e0e0',
leftLegColor: '#e0e0e0',
rightLegColor: '#e0e0e0'
};
if (new URLSearchParams(window.location.search).has('sandbox')) {
console.log('Avatar Sandbox!')
console.log('Avatar Sandbox!');
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function(html){
PageContainer.innerHTML = html
ItemGrid = document.getElementById('inventory')
Wearing = document.getElementById('wearing')
Tabs = document.getElementById('tabs')
IFrame = document.getElementById('viewFrame')
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function (html) {
PageContainer.innerHTML = html;
ItemGrid = document.getElementById('inventory');
Wearing = document.getElementById('wearing');
Tabs = document.getElementById('tabs');
IFrame = document.getElementById('viewFrame');
Search = document.getElementById('item-search')
Search.addEventListener('onchange', function(){
RefreshItems()
});
Search = document.getElementById('item-search');
Search.addEventListener('onchange', function () {
RefreshItems();
});
UpdateAvatar()
RefreshItems()
LoadWearing()
UpdateAvatar();
RefreshItems();
LoadWearing();
Array.from(Tabs.children).forEach(element => {
element.addEventListener('click', function(){
let Link = element.getElementsByTagName('a')[0]
if (!(Link.classList.contains('active'))) {
Link.classList.add('active')
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active')
TabSelected = Link.getAttribute('data-tab')
Page = 1
RefreshItems()
}
});
});
Array.from(Tabs.children).forEach((element) => {
element.addEventListener('click', function () {
let Link = element.getElementsByTagName('a')[0];
if (!Link.classList.contains('active')) {
Link.classList.add('active');
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active');
TabSelected = Link.getAttribute('data-tab');
Page = 1;
RefreshItems();
}
});
});
let Clear = document.getElementById('clear')
Clear.addEventListener('click', function(){
Avatar = {
"useCharacter": true,
"items": [
24122
],
"shirt": 24118,
"pants": 24123,
"headColor": "#e0e0e0",
"torsoColor": "#e0e0e0",
"leftArmColor": "#e0e0e0",
"rightArmColor": "#e0e0e0",
"leftLegColor": "#e0e0e0",
"rightLegColor": "#e0e0e0"
}
UpdateAvatar()
});
let Clear = document.getElementById('clear');
Clear.addEventListener('click', function () {
Avatar = {
useCharacter: true,
items: [24122],
shirt: 24118,
pants: 24123,
headColor: '#e0e0e0',
torsoColor: '#e0e0e0',
leftArmColor: '#e0e0e0',
rightArmColor: '#e0e0e0',
leftLegColor: '#e0e0e0',
rightLegColor: '#e0e0e0'
};
UpdateAvatar();
});
let Myself = document.getElementById('myself')
Myself.addEventListener('click', function(){
LoadMyself()
});
let Myself = document.getElementById('myself');
Myself.addEventListener('click', function () {
LoadMyself();
});
let JSONUpload = document.getElementById('jsonUpload')
JSONUpload.addEventListener('change', function(){
let Reader = new FileReader()
Reader.addEventListener('loadend', function(){
Avatar = JSON.parse(Reader.result)
UpdateAvatar()
let JSONUpload = document.getElementById('jsonUpload');
JSONUpload.addEventListener('change', function () {
let Reader = new FileReader();
Reader.addEventListener('loadend', function () {
Avatar = JSON.parse(Reader.result);
UpdateAvatar();
JSONUpload.value = ""
});
JSONUpload.value = '';
});
Reader.readAsText(JSONUpload.files[0])
});
Reader.readAsText(JSONUpload.files[0]);
});
let JSONSave = document.getElementById('jsonSave')
JSONSave.addEventListener('click', function(){
let Download = document.createElement('a')
Download.href = URL.createObjectURL(new Blob([JSON.stringify(Avatar)], {
type: "application/json"
}));
Download.setAttribute('download', 'AvatarSandbox.json')
document.body.appendChild(Download)
Download.click()
document.body.removeChild(Download)
});
let JSONSave = document.getElementById('jsonSave');
JSONSave.addEventListener('click', function () {
let Download = document.createElement('a');
Download.href = URL.createObjectURL(
new Blob([JSON.stringify(Avatar)], {
type: 'application/json'
})
);
Download.setAttribute('download', 'AvatarSandbox.json');
document.body.appendChild(Download);
Download.click();
document.body.removeChild(Download);
});
let OpenInNewTab = document.getElementById('openNewTab')
OpenInNewTab.addEventListener('click', function(){
UpdateAvatar()
});
let OpenInNewTab = document.getElementById('openNewTab');
OpenInNewTab.addEventListener('click', function () {
UpdateAvatar();
});
let LoadAsset = document.getElementById('load-asset')
LoadAsset.addEventListener('click', async function(){
console.log('clickk')
const MeshURL = (await (await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + LoadAsset.previousElementSibling.value)).json()).url
Avatar.items.push(MeshURL)
UpdateAvatar()
})
});
let LoadAsset = document.getElementById('load-asset');
LoadAsset.addEventListener('click', async function () {
console.log('clickk');
const MeshURL = (await (await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + LoadAsset.previousElementSibling.value)).json()).url;
Avatar.items.push(MeshURL);
UpdateAvatar();
});
});
} else {
const SandboxButton = document.createElement('a')
SandboxButton.classList = 'btn btn-outline-success w-100 mt-3'
SandboxButton.href = '?sandbox=true'
SandboxButton.innerHTML = '<i class="fas fa-shirt"></i> Avatar Sandbox'
document.getElementById('cont-move').parentElement.appendChild(SandboxButton)
const SandboxButton = document.createElement('a');
SandboxButton.classList = 'btn btn-outline-success w-100 mt-3';
SandboxButton.href = '?sandbox=true';
SandboxButton.innerHTML = '<i class="fas fa-shirt"></i> Avatar Sandbox';
document.getElementById('cont-move').parentElement.appendChild(SandboxButton);
}
function UpdateAvatar() {
GenerateHash()
.then(hash => {
IFrame.addEventListener('load', function () {
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
});
IFrame.src = 'about:blank';
});
GenerateHash().then((hash) => {
IFrame.addEventListener('load', function () {
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
});
IFrame.src = 'about:blank';
});
}
function LoadFile(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); }
xhr.open("GET", path, true);
xhr.send();
var xhr = new XMLHttpRequest();
xhr.onload = function () {
return callback(this.responseText);
};
xhr.open('GET', path, true);
xhr.send();
}
async function GenerateHash(data) {
if (!data) {
console.log('Data not provided')
let FormattedAvatar = await FormatAvatar()
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)))
} else {
console.log('Data provided')
return btoa(encodeURIComponent(JSON.stringify(data)))
}
if (!data) {
console.log('Data not provided');
let FormattedAvatar = await FormatAvatar();
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)));
} else {
console.log('Data provided');
return btoa(encodeURIComponent(JSON.stringify(data)));
}
}
function RefreshItems() {
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
Array.from(ItemGrid.children).forEach(element => {element.remove()});
data = data.assets
data.forEach(item => {
let NewItemCard = document.createElement('div')
NewItemCard.setAttribute('data-id', item.id)
NewItemCard.classList = 'col-auto'
NewItemCard.innerHTML = `
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then((data) => {
Array.from(ItemGrid.children).forEach((element) => {
element.remove();
});
data = data.assets;
data.forEach((item) => {
let NewItemCard = document.createElement('div');
NewItemCard.setAttribute('data-id', item.id);
NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = `
<div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container">
<div class="p-2">
@ -252,207 +253,213 @@ function RefreshItems() {
by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a>
</small>
</div>
`
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function(){
WearAsset(NewItemCard, item)
});
`;
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item);
});
ItemGrid.appendChild(NewItemCard)
});
})
.catch(error => {
console.error('Fetch error:', error);
});
ItemGrid.appendChild(NewItemCard);
});
})
.catch((error) => {
console.error('Fetch error:', error);
});
}
async function FormatAvatar() {
const FormattedAvatar = structuredClone(Avatar)
const FormattedAvatar = structuredClone(Avatar);
// Hats, Tools: https://api.polytoria.com/v1/assets/serve-mesh/:id
// or: https://api.polytoria.com/v1/assets/serve/:id/Asset
// Hats, Tools: https://api.polytoria.com/v1/assets/serve-mesh/:id
// or: https://api.polytoria.com/v1/assets/serve/:id/Asset
Avatar.items.forEach(async (item, index) => {
if (typeof(item) === 'number') {
console.log(item)
await FetchMesh(item)
.then(URL => {
console.log('URL: ' + URL)
FormattedAvatar.items[index] = URL
})
.catch(error => {
throw new Error(error)
});
console.log('after url')
//Avatar.items[index] = URL
}
});
Avatar.items.forEach(async (item, index) => {
if (typeof item === 'number') {
console.log(item);
await FetchMesh(item)
.then((URL) => {
console.log('URL: ' + URL);
FormattedAvatar.items[index] = URL;
})
.catch((error) => {
throw new Error(error);
});
console.log('after url');
//Avatar.items[index] = URL
}
});
if (typeof(FormattedAvatar.tool) === 'number') {console.log(FormattedAvatar.tool); FormattedAvatar.tool = await FetchMesh(FormattedAvatar.tool)}
if (typeof FormattedAvatar.tool === 'number') {
console.log(FormattedAvatar.tool);
FormattedAvatar.tool = await FetchMesh(FormattedAvatar.tool);
}
if (FormattedAvatar.face && typeof(FormattedAvatar.face) === 'number') {
FormattedAvatar.face = await FetchAsset(FormattedAvatar.face)
} else {
FormattedAvatar.face = "https://c0.ptacdn.com/static/3dview/DefaultFace.png"
}
if (FormattedAvatar.face && typeof FormattedAvatar.face === 'number') {
FormattedAvatar.face = await FetchAsset(FormattedAvatar.face);
} else {
FormattedAvatar.face = 'https://c0.ptacdn.com/static/3dview/DefaultFace.png';
}
if (typeof(FormattedAvatar.shirt) === 'number') {FormattedAvatar.shirt = await FetchAsset(FormattedAvatar.shirt)}
if (typeof(FormattedAvatar.pants) === 'number') {FormattedAvatar.pants = await FetchAsset(FormattedAvatar.pants)}
if (typeof FormattedAvatar.shirt === 'number') {
FormattedAvatar.shirt = await FetchAsset(FormattedAvatar.shirt);
}
if (typeof FormattedAvatar.pants === 'number') {
FormattedAvatar.pants = await FetchAsset(FormattedAvatar.pants);
}
console.log('Real Avatar: ', Avatar, 'Formatted: ', FormattedAvatar)
return FormattedAvatar
console.log('Real Avatar: ', Avatar, 'Formatted: ', FormattedAvatar);
return FormattedAvatar;
}
function LoadMyself() {
fetch('https://api.polytoria.com/v1/users/:id/avatar'.replace(':id', UserID))
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
Avatar.items = []
fetch('https://api.polytoria.com/v1/users/:id/avatar'.replace(':id', UserID))
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
Avatar.items = [];
data.assets.forEach(item => {
switch(item.type) {
case 'hat':
Avatar.items.push(item.id)
break
default:
Avatar[item.type] = item.id
break
}
});
data.assets.forEach((item) => {
switch (item.type) {
case 'hat':
Avatar.items.push(item.id);
break;
default:
Avatar[item.type] = item.id;
break;
}
});
Avatar.headColor = '#' + data.colors.head || '#cdcdcd'
Avatar.torsoColor = '#' + data.colors.torso || '#cdcdcd'
Avatar.leftArmColor = '#' + data.colors.leftArm || '#cdcdcd'
Avatar.rightArmColor = '#' + data.colors.rightArm || '#cdcdcd'
Avatar.leftLegColor = '#' + data.colors.leftLeg || '#cdcdcd'
Avatar.rightLegColor = '#' + data.colors.rightLeg || '#cdcdcd'
Avatar.headColor = '#' + data.colors.head || '#cdcdcd';
Avatar.torsoColor = '#' + data.colors.torso || '#cdcdcd';
Avatar.leftArmColor = '#' + data.colors.leftArm || '#cdcdcd';
Avatar.rightArmColor = '#' + data.colors.rightArm || '#cdcdcd';
Avatar.leftLegColor = '#' + data.colors.leftLeg || '#cdcdcd';
Avatar.rightLegColor = '#' + data.colors.rightLeg || '#cdcdcd';
UpdateAvatar()
})
.catch(error => {
console.log(error)
});
UpdateAvatar();
})
.catch((error) => {
console.log(error);
});
}
function WearAsset(element, info) {
if (Avatar.items.indexOf(info.id) === -1 && Avatar[info.type] !== info.id) {
console.log('Equip', info)
switch(info.type) {
case 'hat':
Avatar.items.push(info.id)
break
default:
Avatar[info.type] = info.id
break
}
} else {
console.log('unequip', info)
switch(info.type) {
case 'hat':
Avatar.items.splice(Avatar.items.indexOf(info.id), 1)
break
case 'face':
Avatar.face = "https://c0.ptacdn.com/static/3dview/DefaultFace.png"
break
default:
Avatar[info.type] = undefined
break
}
}
if (Avatar.items.indexOf(info.id) === -1 && Avatar[info.type] !== info.id) {
console.log('Equip', info);
switch (info.type) {
case 'hat':
Avatar.items.push(info.id);
break;
default:
Avatar[info.type] = info.id;
break;
}
} else {
console.log('unequip', info);
switch (info.type) {
case 'hat':
Avatar.items.splice(Avatar.items.indexOf(info.id), 1);
break;
case 'face':
Avatar.face = 'https://c0.ptacdn.com/static/3dview/DefaultFace.png';
break;
default:
Avatar[info.type] = undefined;
break;
}
}
const ToggleButton = element.getElementsByClassName('avatarAction')[0]
ToggleButton.classList.toggle('btn-success')
ToggleButton.classList.toggle('btn-danger')
ToggleButton.children[0].classList.toggle('fa-plus')
ToggleButton.children[0].classList.toggle('fa-minus')
const ToggleButton = element.getElementsByClassName('avatarAction')[0];
ToggleButton.classList.toggle('btn-success');
ToggleButton.classList.toggle('btn-danger');
ToggleButton.children[0].classList.toggle('fa-plus');
ToggleButton.children[0].classList.toggle('fa-minus');
const Duplicate = ItemGrid.querySelector(`[data-id="${info.id}"]`)
if (Duplicate !== null && Duplicate !== element) {
const DuplicateToggleButton = Duplicate.getElementsByClassName('avatarAction')[0]
DuplicateToggleButton.classList.toggle('btn-success')
DuplicateToggleButton.classList.toggle('btn-danger')
DuplicateToggleButton.children[0].classList.toggle('fa-plus')
DuplicateToggleButton.children[0].classList.toggle('fa-minus')
}
const Duplicate = ItemGrid.querySelector(`[data-id="${info.id}"]`);
if (Duplicate !== null && Duplicate !== element) {
const DuplicateToggleButton = Duplicate.getElementsByClassName('avatarAction')[0];
DuplicateToggleButton.classList.toggle('btn-success');
DuplicateToggleButton.classList.toggle('btn-danger');
DuplicateToggleButton.children[0].classList.toggle('fa-plus');
DuplicateToggleButton.children[0].classList.toggle('fa-minus');
}
LoadWearing()
UpdateAvatar()
LoadWearing();
UpdateAvatar();
}
async function FetchMesh(id) {
if (id === null) {return null}
console.log('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id))
return fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id))
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
console.log(data, 'finished', data.url)
return data.url
})
.catch(error => {
console.log('Fetch error: ' + error)
});
if (id === null) {
return null;
}
console.log('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id));
return fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id))
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
console.log(data, 'finished', data.url);
return data.url;
})
.catch((error) => {
console.log('Fetch error: ' + error);
});
}
async function FetchAsset(id) {
if (id === null) {return null}
return fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', id))
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
return data.url
})
.catch(error => {
console.log('Fetch error: ' + error)
});
if (id === null) {
return null;
}
return fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', id))
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
return data.url;
})
.catch((error) => {
console.log('Fetch error: ' + error);
});
}
function LoadWearing() {
const WearingItems = [
...Avatar.items,
Avatar.shirt,
Avatar.pants,
Avatar.face
].filter(item => item !== null && item !== undefined);
const WearingItems = [...Avatar.items, Avatar.shirt, Avatar.pants, Avatar.face].filter((item) => item !== null && item !== undefined);
Array.from(Wearing.children).forEach(element => {
const ItemID = element.getElementsByTagName('a')[0].href.split('/')[2]
if (!WearingItems.includes(ItemID)) {
element.remove();
}
});
Array.from(Wearing.children).forEach((element) => {
const ItemID = element.getElementsByTagName('a')[0].href.split('/')[2];
if (!WearingItems.includes(ItemID)) {
element.remove();
}
});
WearingItems.forEach(item => {
const ExistingElement = Wearing.querySelector(`[data-itemid="${item}"]`);
WearingItems.forEach((item) => {
const ExistingElement = Wearing.querySelector(`[data-itemid="${item}"]`);
if (!ExistingElement) {
fetch(`https://api.polytoria.com/v1/store/${item}`)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then(item => {
if (Wearing.innerHTML === 'No items to show.') {
Wearing.innerHTML = ''
}
let NewItemCard = document.createElement('div');
NewItemCard.setAttribute('data-id', item.id)
NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = `
if (!ExistingElement) {
fetch(`https://api.polytoria.com/v1/store/${item}`)
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((item) => {
if (Wearing.innerHTML === 'No items to show.') {
Wearing.innerHTML = '';
}
let NewItemCard = document.createElement('div');
NewItemCard.setAttribute('data-id', item.id);
NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = `
<div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container">
<div class="p-2">
@ -470,19 +477,19 @@ function LoadWearing() {
by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a>
</small>
</div>
`
Wearing.appendChild(NewItemCard);
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item);
});
})
.catch(error => {
console.log('Fetch error: ' + error);
});
}
});
`;
Wearing.appendChild(NewItemCard);
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item);
});
})
.catch((error) => {
console.log('Fetch error: ' + error);
});
}
});
if (Array.from(Wearing.children).length === 0) {
Wearing.innerHTML = 'No items to show.'
}
if (Array.from(Wearing.children).length === 0) {
Wearing.innerHTML = 'No items to show.';
}
}

View file

@ -1,41 +1,40 @@
var SelectedFriends = []
var SelectedFriends = [];
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Settings = result.PolyPlus_Settings;
if (Settings.ImprovedFrListsOn === true) {
var Tab = "requests"
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings;
if (Settings.ImprovedFrListsOn === true) {
var Tab = 'requests';
var FriendsContainer = document.getElementById('friends-container')
var Container = document.createElement('div')
Container.classList = 'row mb-3'
Container.innerHTML = `
var FriendsContainer = document.getElementById('friends-container');
var Container = document.createElement('div');
Container.classList = 'row mb-3';
Container.innerHTML = `
<div class="col"><button id="AccAllFrBtn" class="btn btn-success w-100">Accept all Friend Request(s)</button></div>
<div class="col"><button id="DelAllFrBtn" class="btn btn-danger w-100">Decline all Friend Request(s)</button></div>
`
FriendsContainer.parentElement.insertBefore(Container, FriendsContainer)
var AccAllFrBtn = document.getElementById('AccAllFrBtn')
var DelAllFrBtn = document.getElementById('DelAllFrBtn')
var AccBtns = document.querySelectorAll('[onclick="acceptFriendRequest(this)"]')
var DelBtns = document.querySelectorAll('[onclick="declineFriendRequest(this)"]')
if (!(AccBtns.length === 0)) {
AccAllFrBtn.addEventListener('click', function(){
AccBtns.forEach(element => {
setTimeout(function () {}, 145)
fetch('https://polytoria.com/api/friends/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({ userID: parseInt(element.getAttribute('data-user-id')) }),
})
.catch(error => {
// Handle any errors
console.error('Error:', error);
Success = false
});
`;
FriendsContainer.parentElement.insertBefore(Container, FriendsContainer);
var AccAllFrBtn = document.getElementById('AccAllFrBtn');
var DelAllFrBtn = document.getElementById('DelAllFrBtn');
var AccBtns = document.querySelectorAll('[onclick="acceptFriendRequest(this)"]');
var DelBtns = document.querySelectorAll('[onclick="declineFriendRequest(this)"]');
if (!(AccBtns.length === 0)) {
AccAllFrBtn.addEventListener('click', function () {
AccBtns.forEach((element) => {
setTimeout(function () {}, 145);
fetch('https://polytoria.com/api/friends/send', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({userID: parseInt(element.getAttribute('data-user-id'))})
}).catch((error) => {
// Handle any errors
console.error('Error:', error);
Success = false;
});
/*
/*
let NewAcceptBtn = document.createElement('a')
NewAcceptBtn.style.display = 'none'
sNewAcceptBtn.classList = 'btn btn-success'
@ -44,30 +43,29 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
FriendsContainer.appendChild(NewAcceptBtn)
NewAcceptBtn.click();
*/
})
});
} else {
AccAllFrBtn.setAttribute('disabled', 'true')
}
if (!(DelBtns.length === 0)) {
DelAllFrBtn.addEventListener('click', function(){
DelBtns.forEach(element => {
setTimeout(function () {}, 110)
fetch('https://polytoria.com/api/friends/remove', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({ userID: parseInt(element.getAttribute('data-user-id')) }),
})
.catch(error => {
// Handle any errors
console.error('Error:', error, document.querySelector('input[name="_csrf"]').value);
Success = false
});
});
});
} else {
AccAllFrBtn.setAttribute('disabled', 'true');
}
if (!(DelBtns.length === 0)) {
DelAllFrBtn.addEventListener('click', function () {
DelBtns.forEach((element) => {
setTimeout(function () {}, 110);
fetch('https://polytoria.com/api/friends/remove', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({userID: parseInt(element.getAttribute('data-user-id'))})
}).catch((error) => {
// Handle any errors
console.error('Error:', error, document.querySelector('input[name="_csrf"]').value);
Success = false;
});
/*
/*
let NewDeclineBtn = document.createElement('a')
NewDeclineBtn.style.display = 'none'
NewDeclineBtn.classList = 'btn btn-danger'
@ -76,135 +74,137 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
FriendsContainer.appendChild(NewDeclineBtn)
NewDeclineBtn.click();
*/
})
});
} else {
DelAllFrBtn.setAttribute('disabled', 'true')
}
let Text = document.createElement('p')
Text.classList = 'mx-auto'
Text.style.textAlign = 'center'
Text.style.fontSize = '1.3rem'
Text.style.display = 'none'
Text.innerHTML = `
});
});
} else {
DelAllFrBtn.setAttribute('disabled', 'true');
}
let Text = document.createElement('p');
Text.classList = 'mx-auto';
Text.style.textAlign = 'center';
Text.style.fontSize = '1.3rem';
Text.style.display = 'none';
Text.innerHTML = `
<span>0</span> friends selected!
<br>
<button id="viewSelectionBtn" class="btn btn-primary">View Selection</button>
<button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button>
<button id="removeSelectionBtn" class="btn btn-danger">Remove Selected Friends</button>
`
FriendsContainer.parentElement.insertBefore(Text, FriendsContainer)
let Text_Span = Text.querySelector('span');
let Text_View = document.getElementById('viewSelectionBtn');
let Text_Clear = document.getElementById('clearSelectionBtn');
let Text_Remove = document.getElementById('removeSelectionBtn');
document.querySelector('[data-friends-tab="requests"]').addEventListener('click', function(){
Tab = "requests"
Container.style.display = '';
Text.style.display = 'none';
document.querySelectorAll('input[type="check"]').forEach(element => {element.remove();});
});
document.querySelector('[data-friends-tab="friends"]').addEventListener('click', function(){
Tab = "friends"
Container.style.display = 'none';
Text.style.display = '';
});
var ConfirmRemove = 0
Text_View.addEventListener('click', function(){});
Text_Clear.addEventListener('click', function(){
SelectedFriends = []
UpdateCheckboxes();
Text_Span.innerText = SelectedFriends.length
});
Text_Remove.addEventListener('click', function(){
ConfirmRemove = ConfirmRemove + 1
switch(ConfirmRemove) {
case 0:
Text_Remove.innerText = 'Remove Selected Friends'
break
case 1:
Text_Remove.innerText = 'Are you sure?'
break
case 2:
for (let i = 0; i < SelectedFriends.length; i++) {
setTimeout(function () {}, 110)
let NewDeclineBtn = document.createElement('a')
NewDeclineBtn.style.display = 'none'
NewDeclineBtn.classList = 'btn btn-danger'
NewDeclineBtn.setAttribute('data-user-id', SelectedFriends[i])
NewDeclineBtn.setAttribute('onclick', 'declineFriendRequest(this)')
FriendsContainer.appendChild(NewDeclineBtn)
NewDeclineBtn.click();
}
SelectedFriends = []
UpdateCheckboxes();
Text_Remove.innerText = 'Remove Selected Friends'
ConfirmRemove = 0
break
}
});
`;
FriendsContainer.parentElement.insertBefore(Text, FriendsContainer);
let Text_Span = Text.querySelector('span');
let Text_View = document.getElementById('viewSelectionBtn');
let Text_Clear = document.getElementById('clearSelectionBtn');
let Text_Remove = document.getElementById('removeSelectionBtn');
document.querySelector('[data-friends-tab="requests"]').addEventListener('click', function () {
Tab = 'requests';
Container.style.display = '';
Text.style.display = 'none';
document.querySelectorAll('input[type="check"]').forEach((element) => {
element.remove();
});
});
document.querySelector('[data-friends-tab="friends"]').addEventListener('click', function () {
Tab = 'friends';
Container.style.display = 'none';
Text.style.display = '';
});
var ConfirmRemove = 0;
Text_View.addEventListener('click', function () {});
Text_Clear.addEventListener('click', function () {
SelectedFriends = [];
UpdateCheckboxes();
Text_Span.innerText = SelectedFriends.length;
});
Text_Remove.addEventListener('click', function () {
ConfirmRemove = ConfirmRemove + 1;
switch (ConfirmRemove) {
case 0:
Text_Remove.innerText = 'Remove Selected Friends';
break;
case 1:
Text_Remove.innerText = 'Are you sure?';
break;
case 2:
for (let i = 0; i < SelectedFriends.length; i++) {
setTimeout(function () {}, 110);
let NewDeclineBtn = document.createElement('a');
NewDeclineBtn.style.display = 'none';
NewDeclineBtn.classList = 'btn btn-danger';
NewDeclineBtn.setAttribute('data-user-id', SelectedFriends[i]);
NewDeclineBtn.setAttribute('onclick', 'declineFriendRequest(this)');
FriendsContainer.appendChild(NewDeclineBtn);
NewDeclineBtn.click();
}
SelectedFriends = [];
UpdateCheckboxes();
Text_Remove.innerText = 'Remove Selected Friends';
ConfirmRemove = 0;
break;
}
});
const observer = new MutationObserver(function (){
if (FriendsContainer.children.length > 0 && Tab === "friends") {
LoadCheckBoxes();
}
});
observer.observe(FriendsContainer, {childList: true, subtree: false});
const observer = new MutationObserver(function () {
if (FriendsContainer.children.length > 0 && Tab === 'friends') {
LoadCheckBoxes();
}
});
observer.observe(FriendsContainer, {childList: true, subtree: false});
function LoadCheckBoxes() {
Array.from(FriendsContainer.children).forEach(element => {
let DeclineBtn = element.querySelector('a.btn.btn-danger')
let UserID = DeclineBtn.getAttribute('data-user-id')
let Column = document.createElement('div')
let EditColumn = element.querySelector('.col-9')
Column.classList = 'col-auto'
var NewCheckBox = document.createElement('button')
NewCheckBox.classList = 'polyplus-multiremovefr-checkbox'
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem;')
var Index = SelectedFriends.indexOf(UserID)
if (Index !== -1) {
DeclineBtn.classList.add('disabled')
NewCheckBox.style.borderColor = 'lime'
}
EditColumn.classList.remove('col-9')
EditColumn.classList.add('col')
Column.appendChild(NewCheckBox)
EditColumn.parentElement.appendChild(Column)
NewCheckBox.addEventListener('click', function(){
var Index = SelectedFriends.indexOf(UserID)
if (Index === -1) {
DeclineBtn.classList.add('disabled')
SelectedFriends.push(UserID)
NewCheckBox.style.borderColor = 'lime'
} else {
SelectedFriends.splice(Index, 1)
NewCheckBox.style.borderColor = '#393939'
DeclineBtn.classList.remove('disabled')
}
Text_Span.innerText = SelectedFriends.length
UpdateCheckboxes();
});
});
}
function LoadCheckBoxes() {
Array.from(FriendsContainer.children).forEach((element) => {
let DeclineBtn = element.querySelector('a.btn.btn-danger');
let UserID = DeclineBtn.getAttribute('data-user-id');
let Column = document.createElement('div');
let EditColumn = element.querySelector('.col-9');
Column.classList = 'col-auto';
var NewCheckBox = document.createElement('button');
NewCheckBox.classList = 'polyplus-multiremovefr-checkbox';
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem;');
var Index = SelectedFriends.indexOf(UserID);
if (Index !== -1) {
DeclineBtn.classList.add('disabled');
NewCheckBox.style.borderColor = 'lime';
}
EditColumn.classList.remove('col-9');
EditColumn.classList.add('col');
Column.appendChild(NewCheckBox);
EditColumn.parentElement.appendChild(Column);
NewCheckBox.addEventListener('click', function () {
var Index = SelectedFriends.indexOf(UserID);
if (Index === -1) {
DeclineBtn.classList.add('disabled');
SelectedFriends.push(UserID);
NewCheckBox.style.borderColor = 'lime';
} else {
SelectedFriends.splice(Index, 1);
NewCheckBox.style.borderColor = '#393939';
DeclineBtn.classList.remove('disabled');
}
Text_Span.innerText = SelectedFriends.length;
UpdateCheckboxes();
});
});
}
function UpdateCheckboxes(){
document.querySelectorAll('.polyplus-multiremovefr-checkbox').forEach(element => {
let Parent = element.parentElement.parentElement.parentElement.parentElement.parentElement
let DeclineBtn = Parent.querySelector('a.btn.btn-danger')
if (element.getAttribute('disabled')) {
element.removeAttribute('disabled')
}
if (SelectedFriends.IndexOf(DeclineBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939'
DeclineBtn.classList.remove('disabled')
if (SelectedFriends.length >= 25) {
element.setAttribute('disabled', true)
}
} else {
DeclineBtn.classList.add('disabled')
element.style.borderColor = 'lime'
}
})
}
}
function UpdateCheckboxes() {
document.querySelectorAll('.polyplus-multiremovefr-checkbox').forEach((element) => {
let Parent = element.parentElement.parentElement.parentElement.parentElement.parentElement;
let DeclineBtn = Parent.querySelector('a.btn.btn-danger');
if (element.getAttribute('disabled')) {
element.removeAttribute('disabled');
}
if (SelectedFriends.IndexOf(DeclineBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939';
DeclineBtn.classList.remove('disabled');
if (SelectedFriends.length >= 25) {
element.setAttribute('disabled', true);
}
} else {
DeclineBtn.classList.add('disabled');
element.style.borderColor = 'lime';
}
});
}
}
});

View file

@ -3,25 +3,25 @@ this file needs a rewrite by me lol
*/
var Settings;
var PinnedGamesData
var BestFriendsData
var PinnedGamesData;
var BestFriendsData;
let Utilities;
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result) {
Settings = result.PolyPlus_Settings || Utilities.DefaultSettings
chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || Utilities.DefaultSettings;
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice()
}
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice();
}
if (Settings.HomeFriendCountOn === true) {
ShowFriendCount()
}
if (Settings.HomeFriendCountOn === true) {
ShowFriendCount();
}
if (Settings.PinnedGamesOn === true || Settings.BestFriendsOn === true) {
Update()
}
if (Settings.PinnedGamesOn === true || Settings.BestFriendsOn === true) {
Update();
}
});
let ContainerElement = `
@ -56,148 +56,151 @@ let TitleElement = `
<h6 class="dash-ctitle2">Jump right back into your favorite games</h6>
<h5 class="dash-ctitle">Pinned Games</h5>
</div>`;
var FriendContainer = document.querySelector('.card:has(.friendsPopup) .card-body')
var FriendContainer = document.querySelector('.card:has(.friendsPopup) .card-body');
let NewContainer = document.createElement('div');
NewContainer.style.display = 'none'
NewContainer.style.display = 'none';
NewContainer.classList = 'card card-dash mcard';
NewContainer.style.animationDelay = '0.18s';
NewContainer.innerHTML = ContainerElement;
let NewTitle = document.createElement('div');
NewTitle.style.display = 'none'
NewTitle.style.display = 'none';
NewTitle.classList = 'row reqFadeAnim px-2 px-lg-0';
NewTitle.innerHTML = TitleElement;
let BestFriendsContainer = document.createElement('div')
BestFriendsContainer.classList = 'd-flex'
BestFriendsContainer.style = 'display: none; border-bottom: 1px solid #000; padding-bottom: 10px; margin-bottom: 10px; width: 100%;'
let BestFriendsContainer = document.createElement('div');
BestFriendsContainer.classList = 'd-flex';
BestFriendsContainer.style = 'display: none; border-bottom: 1px solid #000; padding-bottom: 10px; margin-bottom: 10px; width: 100%;';
let Spacer = document.createElement('div')
Spacer.innerHTML = ' '
Spacer.style.width = '50px'
Spacer.prepend(BestFriendsContainer)
let Spacer = document.createElement('div');
Spacer.innerHTML = ' ';
Spacer.style.width = '50px';
Spacer.prepend(BestFriendsContainer);
FriendContainer.prepend(BestFriendsContainer)
FriendContainer.prepend(BestFriendsContainer);
async function Update() {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
if (Settings.PinnedGamesOn === true) {
PinnedGames()
} else {
NewContainer.style.display = 'none'
NewTitle.style.display = 'none'
}
});
if (Settings.PinnedGamesOn === true) {
PinnedGames();
} else {
NewContainer.style.display = 'none';
NewTitle.style.display = 'none';
}
});
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) {
BestFriendsData = result.PolyPlus_BestFriends || [];
chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriendsData = result.PolyPlus_BestFriends || [];
if (Settings.BestFriendsOn === true) {
BestFriends();
} else {
BestFriendsContainer.style.display = 'none'
Spacer.style.display = 'none'
}
});
if (Settings.BestFriendsOn === true) {
BestFriends();
} else {
BestFriendsContainer.style.display = 'none';
Spacer.style.display = 'none';
}
});
}
function PinnedGames() {
var Existing = NewContainer.children[0].children
Array.from(Existing).forEach(element => {
element.remove();
});
var Existing = NewContainer.children[0].children;
Array.from(Existing).forEach((element) => {
element.remove();
});
if (PinnedGamesData.length === 0) {
NewContainer.style.display = 'none'
NewTitle.style.display = 'none'
} else {
NewContainer.style.display = ''
NewTitle.style.display = ''
}
if (PinnedGamesData.length === 0) {
NewContainer.style.display = 'none';
NewTitle.style.display = 'none';
} else {
NewContainer.style.display = '';
NewTitle.style.display = '';
}
PinnedGamesData.forEach(element => {
fetch('https://api.polytoria.com/v1/places/' + element)
.then(response => response.json())
.then(data => {
let GameName = data.name;
let GameThumbnail = data.thumbnail;
PinnedGamesData.forEach((element) => {
fetch('https://api.polytoria.com/v1/places/' + element)
.then((response) => response.json())
.then((data) => {
let GameName = data.name;
let GameThumbnail = data.thumbnail;
var NewGameContainer = document.createElement('a');
NewGameContainer.innerHTML = GameContainerElement.replace(':GameName',GameName).replace(':Thumbnail',GameThumbnail).replace(':Likes', data.rating.likes).replace(':Dislikes', data.rating.dislikes);
NewGameContainer.href = '/places/' + element
var NewGameContainer = document.createElement('a');
NewGameContainer.innerHTML = GameContainerElement.replace(':GameName', GameName)
.replace(':Thumbnail', GameThumbnail)
.replace(':Likes', data.rating.likes)
.replace(':Dislikes', data.rating.dislikes);
NewGameContainer.href = '/places/' + element;
/*
/*
if (new Date().getDate() >= new Date(data.updatedAt).getDate()) {
console.log('Game has updated')
}
*/
NewContainer.children[0].appendChild(NewGameContainer);
})
.catch(error => {
console.error('Error:', error);
});
});
NewContainer.children[0].appendChild(NewGameContainer);
})
.catch((error) => {
console.error('Error:', error);
});
});
}
function BestFriends() {
Array.from(document.querySelectorAll('[bestFriend]')).forEach(element => {
element.removeAttribute('bestFriend')
element.getElementsByClassName('friend-name')[0].style.color = 'initial';
FriendContainer.appendChild(element)
});
Array.from(document.querySelectorAll('[bestFriend]')).forEach((element) => {
element.removeAttribute('bestFriend');
element.getElementsByClassName('friend-name')[0].style.color = 'initial';
FriendContainer.appendChild(element);
});
if (BestFriendsData.length === 0) {
BestFriendsContainer.style.visibility = 'hidden'
BestFriendsContainer.style.padding = '0px !important'
BestFriendsContainer.style.margin = '0px !important'
} else {
BestFriendsContainer.style.visibility = 'visible'
BestFriendsContainer.style.padding = ''
BestFriendsContainer.style.margin = ''
}
if (BestFriendsData.length === 0) {
BestFriendsContainer.style.visibility = 'hidden';
BestFriendsContainer.style.padding = '0px !important';
BestFriendsContainer.style.margin = '0px !important';
} else {
BestFriendsContainer.style.visibility = 'visible';
BestFriendsContainer.style.padding = '';
BestFriendsContainer.style.margin = '';
}
BestFriendsData.forEach(element => {
let ExistingFriend = document.getElementById('friend-' + element)
if (ExistingFriend) {
ExistingFriend.setAttribute('bestFriend', 'true')
ExistingFriend.getElementsByClassName('friend-name')[0].style.color = 'yellow';
BestFriendsContainer.prepend(ExistingFriend)
}
});
BestFriendsData.forEach((element) => {
let ExistingFriend = document.getElementById('friend-' + element);
if (ExistingFriend) {
ExistingFriend.setAttribute('bestFriend', 'true');
ExistingFriend.getElementsByClassName('friend-name')[0].style.color = 'yellow';
BestFriendsContainer.prepend(ExistingFriend);
}
});
}
var SecondaryColumn = document.getElementsByClassName('col-lg-8')[0]
var SecondaryColumn = document.getElementsByClassName('col-lg-8')[0];
SecondaryColumn.insertBefore(NewContainer, SecondaryColumn.children[0]);
SecondaryColumn.insertBefore(NewTitle, SecondaryColumn.children[0]);
async function IRLPrice() {
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
const TrendingItems = document.getElementById('home-trendingItems')
for (let item of TrendingItems.children[1].getElementsByClassName('d-flex')[0].children) {
const Price = item.getElementsByClassName('text-success')[0]
if (Price !== undefined) {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency)
const TrendingItems = document.getElementById('home-trendingItems');
for (let item of TrendingItems.children[1].getElementsByClassName('d-flex')[0].children) {
const Price = item.getElementsByClassName('text-success')[0];
if (Price !== undefined) {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span')
Span.classList = 'text-muted polyplus-price-tag'
Span.style = 'font-size: 0.7rem; font-weight: lighter;'
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")"
Price.appendChild(Span)
}
}
})();
let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag';
Span.style = 'font-size: 0.7rem; font-weight: lighter;';
Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span);
}
}
})();
}
async function ShowFriendCount() {
let FriendCount = (await (await fetch('https://polytoria.com/api/friends?page=1')).json()).meta.total
/*
let FriendCount = (await (await fetch('https://polytoria.com/api/friends?page=1')).json()).meta.total;
/*
const FirstPage = (await (await fetch('https://polytoria.com/api/friends?page=1')).json())
if (FirstPage.meta.lastPage > 1) {
const LastPage = (await (await fetch('https://polytoria.com/api/friends?page=' + Pages)).json())
@ -207,9 +210,9 @@ async function ShowFriendCount() {
}
*/
const CountText = document.createElement('small')
CountText.classList = 'text-muted fw-lighter'
CountText.style.fontSize = '0.8rem'
CountText.innerText = ' (' + FriendCount + ')'
document.querySelector('#home-friendsOnline h5').appendChild(CountText)
const CountText = document.createElement('small');
CountText.classList = 'text-muted fw-lighter';
CountText.style.fontSize = '0.8rem';
CountText.innerText = ' (' + FriendCount + ')';
document.querySelector('#home-friendsOnline h5').appendChild(CountText);
}

View file

@ -1,47 +1,47 @@
ExpandMessages()
ExpandMessages();
function ExpandMessages() {
const Messages = document.getElementById('messages')
const Messages = document.getElementById('messages');
for (let message of Messages.children) {
let Expanded = false
let ContentDiv = null
for (let message of Messages.children) {
let Expanded = false;
let ContentDiv = null;
const ViewButton = message.querySelector('a.btn[href^="/inbox/messages"]')
const MessageID = ViewButton.getAttribute('href').split('/')[3]
const ViewButton = message.querySelector('a.btn[href^="/inbox/messages"]');
const MessageID = ViewButton.getAttribute('href').split('/')[3];
const ExpandButton = document.createElement('button')
ExpandButton.classList = 'btn btn-outline-warning px-4 mt-1'
ExpandButton.innerText = 'Expand'
ViewButton.parentElement.appendChild(ExpandButton)
const ExpandButton = document.createElement('button');
ExpandButton.classList = 'btn btn-outline-warning px-4 mt-1';
ExpandButton.innerText = 'Expand';
ViewButton.parentElement.appendChild(ExpandButton);
ExpandButton.addEventListener('click', function(){
if (ContentDiv === null) {
fetch('https://polytoria.com/inbox/messages/'+MessageID)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.text()
})
.then(data => {
const Doc = new DOMParser().parseFromString(data, 'text/html')
const MessageContent = Doc.querySelector('p.mb-0').innerText
ExpandButton.addEventListener('click', function () {
if (ContentDiv === null) {
fetch('https://polytoria.com/inbox/messages/' + MessageID)
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.text();
})
.then((data) => {
const Doc = new DOMParser().parseFromString(data, 'text/html');
const MessageContent = Doc.querySelector('p.mb-0').innerText;
ContentDiv = document.createElement('div')
ContentDiv.classList = 'py-2'
ContentDiv.innerText = MessageContent
message.appendChild(ContentDiv)
})
.catch(error => {
console.log(error)
});
}
ContentDiv = document.createElement('div');
ContentDiv.classList = 'py-2';
ContentDiv.innerText = MessageContent;
message.appendChild(ContentDiv);
})
.catch((error) => {
console.log(error);
});
}
Expanded = !Expanded
Expanded = !Expanded;
ExpandButton.innerText = (Expanded === false) ? 'Expand' : 'Minimize'
ContentDiv.style.display = (Expanded === false) ? 'none' : 'block'
});
}
ExpandButton.innerText = Expanded === false ? 'Expand' : 'Minimize';
ContentDiv.style.display = Expanded === false ? 'none' : 'block';
});
}
}

View file

@ -1,25 +1,25 @@
console.log('path', window.location.pathname.split('/')[3])
console.log('path', window.location.pathname.split('/')[3]);
if (window.location.pathname.split('/')[3] === "inventory") {
const Username = window.location.pathname.split('/')[2]
console.log(JSON.parse(window.localStorage.getItem('p+account_info')).Username)
if (Username === JSON.parse(window.localStorage.getItem('p+account_info')).Username) {
console.log('is user')
let Nav = document.getElementsByClassName('nav-pills')[0]
let WishlistNav = document.createElement('li')
WishlistNav.classList.add('nav-item')
WishlistNav.innerHTML = `
if (window.location.pathname.split('/')[3] === 'inventory') {
const Username = window.location.pathname.split('/')[2];
console.log(JSON.parse(window.localStorage.getItem('p+account_info')).Username);
if (Username === JSON.parse(window.localStorage.getItem('p+account_info')).Username) {
console.log('is user');
let Nav = document.getElementsByClassName('nav-pills')[0];
let WishlistNav = document.createElement('li');
WishlistNav.classList.add('nav-item');
WishlistNav.innerHTML = `
<a href="wishlist/" class="nav-link">
<i class="fa-regular fa-sparkles me-1"></i>
<span class="pilltitle">Item Wishlist</span>
</a>
`
Nav.appendChild(WishlistNav)
`;
Nav.appendChild(WishlistNav);
if (window.location.pathname.split('/')[4] === "wishlist") {
console.log('aaa')
const ItemGrid = document.getElementsByClassName('itemgrid')[0]
const ItemCardContents = `
if (window.location.pathname.split('/')[4] === 'wishlist') {
console.log('aaa');
const ItemGrid = document.getElementsByClassName('itemgrid')[0];
const ItemCardContents = `
<a href="/store/:ItemID" class="text-reset">
<div class="card mb-2">
:LimitedTag
@ -35,23 +35,23 @@ if (window.location.pathname.split('/')[3] === "inventory") {
by <a href="/users/:CreatorID" class="text-muted">:CreatorName</a>
</small>
<button class="polyplus-itemwish-removebtn btn btn-danger btn-sm" style="width: 100%;">X</button>
`
`;
Array.from(ItemGrid.children).forEach(element => {
element.remove();
});
Array.from(Nav.children).forEach(element => {
element = element.children[0]
if (!(element === WishlistNav)) {
if (element.classList.contains('active')) {
element.classList.remove('active')
}
}
});
WishlistNav.children[0].classList.add('active')
const Search = document.createElement('div')
Search.classList = 'row'
Search.innerHTML = `
Array.from(ItemGrid.children).forEach((element) => {
element.remove();
});
Array.from(Nav.children).forEach((element) => {
element = element.children[0];
if (!(element === WishlistNav)) {
if (element.classList.contains('active')) {
element.classList.remove('active');
}
}
});
WishlistNav.children[0].classList.add('active');
const Search = document.createElement('div');
Search.classList = 'row';
Search.innerHTML = `
<div class="col-auto">
<select class="form-select" id="polyplus-itemwish-type" style="width: 150px;">
<option value="any">Any</option>
@ -83,109 +83,121 @@ if (window.location.pathname.split('/')[3] === "inventory") {
</label>
</div>
</div>
`
ItemGrid.parentElement.prepend(document.createElement('br'), ItemGrid.parentElement.children[0])
ItemGrid.parentElement.prepend(Search, ItemGrid.parentElement.children[0])
`;
ItemGrid.parentElement.prepend(document.createElement('br'), ItemGrid.parentElement.children[0]);
ItemGrid.parentElement.prepend(Search, ItemGrid.parentElement.children[0]);
let Type = document.getElementById('polyplus-itemwish-type')
let SearchBar = document.getElementById('polyplus-itemwish-searchbar')
let IsLimited = document.getElementById('polyplus-itemwish-isLimited')
let IsAvailable = document.getElementById('polyplus-itemwish-isAvailable')
let Type = document.getElementById('polyplus-itemwish-type');
let SearchBar = document.getElementById('polyplus-itemwish-searchbar');
let IsLimited = document.getElementById('polyplus-itemwish-isLimited');
let IsAvailable = document.getElementById('polyplus-itemwish-isAvailable');
Type.addEventListener('change', function(){
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked)
});
Type.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
});
SearchBar.addEventListener('change', function(){
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked)
});
SearchBar.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
});
IsLimited.addEventListener('change', function(){
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked)
});
IsLimited.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
});
IsAvailable.addEventListener('change', function(){
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked)
});
IsAvailable.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
});
chrome.storage.sync.get(['PolyPlus_ItemWishlist'], function(result){
let Wishlist = result.PolyPlus_ItemWishlist || [];
console.log('wishlist: ', Wishlist)
Wishlist.forEach(element => {
let NewItemCard = document.createElement('div')
NewItemCard.classList = 'px-0'
fetch('https://api.polytoria.com/v1/store/:id'.replace(':id', element))
.then(response => response.json())
.then(data => {
NewItemCard.innerHTML = ItemCardContents.replace(':ItemID', data.id).replace(':ItemThumbnail', data.thumbnail).replace(':ItemName', data.name).replace(':CreatorID', data.creator.id).replace(':CreatorName', data.creator.name)
if (data.isLimited === true) {
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '<div class="ribbon ribbon-limited ribbon-top-right"><span>Limited</span></div>')
} else {
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '')
}
NewItemCard.setAttribute('data-id', data.id)
NewItemCard.setAttribute('data-name', data.name)
NewItemCard.setAttribute('data-type', data.type)
NewItemCard.setAttribute('data-creator', data.creator.name)
NewItemCard.setAttribute('data-limited', data.isLimited)
if (data.isLimited === false) {
NewItemCard.setAttribute('data-price', data.price)
}
chrome.storage.sync.get(['PolyPlus_ItemWishlist'], function (result) {
let Wishlist = result.PolyPlus_ItemWishlist || [];
console.log('wishlist: ', Wishlist);
Wishlist.forEach((element) => {
let NewItemCard = document.createElement('div');
NewItemCard.classList = 'px-0';
fetch('https://api.polytoria.com/v1/store/:id'.replace(':id', element))
.then((response) => response.json())
.then((data) => {
NewItemCard.innerHTML = ItemCardContents.replace(':ItemID', data.id)
.replace(':ItemThumbnail', data.thumbnail)
.replace(':ItemName', data.name)
.replace(':CreatorID', data.creator.id)
.replace(':CreatorName', data.creator.name);
if (data.isLimited === true) {
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '<div class="ribbon ribbon-limited ribbon-top-right"><span>Limited</span></div>');
} else {
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '');
}
NewItemCard.setAttribute('data-id', data.id);
NewItemCard.setAttribute('data-name', data.name);
NewItemCard.setAttribute('data-type', data.type);
NewItemCard.setAttribute('data-creator', data.creator.name);
NewItemCard.setAttribute('data-limited', data.isLimited);
if (data.isLimited === false) {
NewItemCard.setAttribute('data-price', data.price);
}
ItemGrid.appendChild(NewItemCard)
ItemGrid.appendChild(NewItemCard);
NewItemCard.getElementsByClassName('polyplus-itemwish-removebtn')[0].addEventListener('click', function(){
let Index = Wishlist.indexOf(parseInt(NewItemCard.getAttribute('data-id')))
if (Index === -1) {
NewItemCard.remove();
return
} else {
Wishlist.splice(Index, 1)
console.log(Wishlist)
NewItemCard.remove();
}
chrome.storage.sync.set({'PolyPlus_ItemWishlist': Wishlist, arrayOrder: true}, function() {
console.log('ItemWishlist successfully saved: ' + ItemWishlist)
});
});
})
.catch(error => {
console.error('Error:', error);
});
});
});
}
}
NewItemCard.getElementsByClassName('polyplus-itemwish-removebtn')[0].addEventListener('click', function () {
let Index = Wishlist.indexOf(parseInt(NewItemCard.getAttribute('data-id')));
if (Index === -1) {
NewItemCard.remove();
return;
} else {
Wishlist.splice(Index, 1);
console.log(Wishlist);
NewItemCard.remove();
}
chrome.storage.sync.set({PolyPlus_ItemWishlist: Wishlist, arrayOrder: true}, function () {
console.log('ItemWishlist successfully saved: ' + ItemWishlist);
});
});
})
.catch((error) => {
console.error('Error:', error);
});
});
});
}
}
}
function Update(type, query, isLimited, isAvailable) {
let ItemGrid = document.getElementsByClassName('itemgrid')[0]
let BrickBalance = parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).Bricks)
query = query.toLowerCase();
let Results = Array.from(ItemGrid.children)
for (let i = 0; i < Results.length; i++) {
let Show = true
let ItemGrid = document.getElementsByClassName('itemgrid')[0];
let BrickBalance = parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).Bricks);
query = query.toLowerCase();
let Results = Array.from(ItemGrid.children);
for (let i = 0; i < Results.length; i++) {
let Show = true;
console.log('type: ', type)
if (!(type === 'any')) {
console.log('isn\'t any')
if (!(Results[i].getAttribute('data-type') === type)) {Show = false}
}
console.log('type: ', type);
if (!(type === 'any')) {
console.log("isn't any");
if (!(Results[i].getAttribute('data-type') === type)) {
Show = false;
}
}
if (!(Results[i].getAttribute('data-name').toLowerCase().startsWith(query))) {Show = false}
if (!Results[i].getAttribute('data-name').toLowerCase().startsWith(query)) {
Show = false;
}
if (isLimited === true) {
if (!(Results[i].getAttribute('data-limited') === 'true')) {Show = false}
}
if (isLimited === true) {
if (!(Results[i].getAttribute('data-limited') === 'true')) {
Show = false;
}
}
if (isAvailable === true) {
if (!(parseInt(Results[i].getAttribute('data-price')) <= BrickBalance)) {Show = false}
}
if (isAvailable === true) {
if (!(parseInt(Results[i].getAttribute('data-price')) <= BrickBalance)) {
Show = false;
}
}
if (Show === true) {
Results[i].style.display = 'block'
} else {
Results[i].style.display = 'none'
}
}
if (Show === true) {
Results[i].style.display = 'block';
} else {
Results[i].style.display = 'none';
}
}
}

View file

@ -1,6 +1,6 @@
let UserID = window.location.pathname.split('/')[2];
const AvatarRow = document.getElementsByClassName('d-flex flex-row flex-nowrap overflow-x-scroll px-3 px-lg-0 mb-2 mb-lg-0')[0]
const AvatarHeading = document.querySelector('.section-title:has(i.fa-user-crown)')
const AvatarRow = document.getElementsByClassName('d-flex flex-row flex-nowrap overflow-x-scroll px-3 px-lg-0 mb-2 mb-lg-0')[0];
const AvatarHeading = document.querySelector('.section-title:has(i.fa-user-crown)');
var Settings;
var BestFriends;
@ -10,238 +10,244 @@ let CalculateButton;
let Utilities;
if (UserID) {
(async () => {
UserID = (await (await fetch('https://api.polytoria.com/v1/users/')).json()).id
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
(async () => {
UserID = (await (await fetch('https://api.polytoria.com/v1/users/')).json()).id;
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) {
Settings = result.PolyPlus_Settings || {}
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {};
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice()
}
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice();
}
if (Settings.BestFriendsOn === true) {
BestFriends()
}
if (Settings.BestFriendsOn === true) {
BestFriends();
}
if (Settings.OutfitCostOn === true) {
CalculateButton = document.createElement('small')
CalculateButton.classList = 'fw-normal text-success'
CalculateButton.style.letterSpacing = '0px'
CalculateButton.setAttribute('data-bs-toggle', 'tooltip')
CalculateButton.setAttribute('data-bs-title', 'Calculate this avatar\'s cost!')
CalculateButton.setAttribute('data-bs-placement', 'right')
CalculateButton.innerHTML = `
if (Settings.OutfitCostOn === true) {
CalculateButton = document.createElement('small');
CalculateButton.classList = 'fw-normal text-success';
CalculateButton.style.letterSpacing = '0px';
CalculateButton.setAttribute('data-bs-toggle', 'tooltip');
CalculateButton.setAttribute('data-bs-title', "Calculate this avatar's cost!");
CalculateButton.setAttribute('data-bs-placement', 'right');
CalculateButton.innerHTML = `
<a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ calculate</a>
`
AvatarHeading.appendChild(CalculateButton)
`;
AvatarHeading.appendChild(CalculateButton);
Utilities.InjectResource('registerTooltips')
Utilities.InjectResource('registerTooltips');
let Calculating = false
CalculateButton.addEventListener('click', function(){
if (Calculating === false) {
Calculating = true
CalculateButton.innerText = '$ Calculating...'
OutfitCost()
}
});
}
});
})();
let Calculating = false;
CalculateButton.addEventListener('click', function () {
if (Calculating === false) {
Calculating = true;
CalculateButton.innerText = '$ Calculating...';
OutfitCost();
}
});
}
});
})();
const AvatarIFrame = document.querySelector('[src^="/ptstatic"]')
const DropdownMenu = document.getElementsByClassName('dropdown-menu dropdown-menu-right')[0]
const AvatarIFrame = document.querySelector('[src^="/ptstatic"]');
const DropdownMenu = document.getElementsByClassName('dropdown-menu dropdown-menu-right')[0];
const CopyItem = document.createElement('a')
CopyItem.classList = 'dropdown-item text-primary'
CopyItem.href = '#'
CopyItem.innerHTML = `
const CopyItem = document.createElement('a');
CopyItem.classList = 'dropdown-item text-primary';
CopyItem.href = '#';
CopyItem.innerHTML = `
<i class="fa-duotone fa-book"></i>
Copy 3D Avatar URL
`
DropdownMenu.appendChild(CopyItem)
`;
DropdownMenu.appendChild(CopyItem);
CopyItem.addEventListener('click', function(){
navigator.clipboard.writeText(AvatarIFrame.src)
.then(() => {
alert('Successfully copied 3D avatar URL!')
})
.catch(() => {
alert('Failure to copy 3D avatar URL.')
});
});
CopyItem.addEventListener('click', function () {
navigator.clipboard
.writeText(AvatarIFrame.src)
.then(() => {
alert('Successfully copied 3D avatar URL!');
})
.catch(() => {
alert('Failure to copy 3D avatar URL.');
});
});
const ShareItem = document.createElement('a')
ShareItem.classList = 'dropdown-item text-warning'
ShareItem.href = '#'
ShareItem.innerHTML = `
const ShareItem = document.createElement('a');
ShareItem.classList = 'dropdown-item text-warning';
ShareItem.href = '#';
ShareItem.innerHTML = `
<i class="fa-duotone fa-book"></i>
Share your 3D Avatar URL!
`
DropdownMenu.appendChild(ShareItem)
`;
DropdownMenu.appendChild(ShareItem);
ShareItem.addEventListener('click', function(){
navigator.clipboard.writeText("Hey! Look at my Polytoria avatar in 3D [here](" + AvatarIFrame.src + ")!")
.then(() => {
alert('Successfully copied sharable 3D avatar URL!')
})
.catch(() => {
alert('Failure to copy sharable 3D avatar URL.')
});
});
} else if (UserID && UserID[0] === "@") {
const Username = window.location.pathname.split('/')[2].substring(1)
ShareItem.addEventListener('click', function () {
navigator.clipboard
.writeText('Hey! Look at my Polytoria avatar in 3D [here](' + AvatarIFrame.src + ')!')
.then(() => {
alert('Successfully copied sharable 3D avatar URL!');
})
.catch(() => {
alert('Failure to copy sharable 3D avatar URL.');
});
});
} else if (UserID && UserID[0] === '@') {
const Username = window.location.pathname.split('/')[2].substring(1);
let Reference = new URLSearchParams(new URL(window.location.href).search)
if (!Reference.has('ref')) {
Reference = ""
}
let Reference = new URLSearchParams(new URL(window.location.href).search);
if (!Reference.has('ref')) {
Reference = '';
}
fetch("https://api.polytoria.com/v1/users/find?username=" + Username)
.then(response => {
if (!response.ok) {
window.location.href = window.location.origin + decodeURIComponent(Reference.get('ref'))
} else {
return response.json()
}
})
.then(data => {
window.location.href = "https://polytoria.com/users/" + data.id
})
.catch(error => {
console.log("An error occurred:", error);
});
fetch('https://api.polytoria.com/v1/users/find?username=' + Username)
.then((response) => {
if (!response.ok) {
window.location.href = window.location.origin + decodeURIComponent(Reference.get('ref'));
} else {
return response.json();
}
})
.then((data) => {
window.location.href = 'https://polytoria.com/users/' + data.id;
})
.catch((error) => {
console.log('An error occurred:', error);
});
}
async function IRLPrice() {
const NetWorthElement = document.getElementsByClassName('float-end text-success')[0];
const IRLResult = await Utilities.CalculateIRL(NetWorthElement.innerText, Settings.IRLPriceWithCurrency.Currency)
NetWorthElement.innerHTML = NetWorthElement.innerHTML + '<div class="text-muted" style="font-size: 0.6rem;">(' + IRLResult.icon + IRLResult.result + ' ' + IRLResult.display + ')</div>'
const NetWorthElement = document.getElementsByClassName('float-end text-success')[0];
const IRLResult = await Utilities.CalculateIRL(NetWorthElement.innerText, Settings.IRLPriceWithCurrency.Currency);
NetWorthElement.innerHTML = NetWorthElement.innerHTML + '<div class="text-muted" style="font-size: 0.6rem;">(' + IRLResult.icon + IRLResult.result + ' ' + IRLResult.display + ')</div>';
}
function BestFriends() {
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result){
BestFriends = result.PolyPlus_BestFriends || [];
chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriends = result.PolyPlus_BestFriends || [];
FavoriteBtn = document.createElement('button');
FavoriteBtn.classList = 'btn btn-warning btn-sm ml-2';
if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status';
} else {
FavoriteBtn.innerText = 'Best Friend';
}
} else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')'
}
if (UserID !== JSON.parse(window.localStorage.getItem('p+account_info')).ID && document.getElementById('add-friend-button').classList.contains('btn-success') === false) {
FavoriteBtn.addEventListener('click', function() {
Fav(UserID, FavoriteBtn);
});
} else {
FavoriteBtn.style.display = 'none'
}
document.querySelectorAll('.section-title.px-3.px-lg-0.mt-3')[0].appendChild(FavoriteBtn);
FavoriteBtn = document.createElement('button');
FavoriteBtn.classList = 'btn btn-warning btn-sm ml-2';
if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status';
} else {
FavoriteBtn.innerText = 'Best Friend';
}
} else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')';
}
if (UserID !== JSON.parse(window.localStorage.getItem('p+account_info')).ID && document.getElementById('add-friend-button').classList.contains('btn-success') === false) {
FavoriteBtn.addEventListener('click', function () {
Fav(UserID, FavoriteBtn);
});
} else {
FavoriteBtn.style.display = 'none';
}
document.querySelectorAll('.section-title.px-3.px-lg-0.mt-3')[0].appendChild(FavoriteBtn);
function Fav(UserID, btn) {
if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) { return }
btn.setAttribute('disabled', 'true')
function Fav(UserID, btn) {
if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) {
return;
}
btn.setAttribute('disabled', 'true');
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) {
const BestFriends = result.PolyPlus_BestFriends || [];
const index = BestFriends.indexOf(parseInt(UserID));
chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
const BestFriends = result.PolyPlus_BestFriends || [];
const index = BestFriends.indexOf(parseInt(UserID));
if (index !== -1) {
// Number exists, remove it
BestFriends.splice(index, 1);
btn.innerText = "Best Friend"
console.log('Number', parseInt(UserID), 'removed from BestFriends');
} else {
// Number doesn't exist, add it
BestFriends.push(parseInt(UserID));
btn.innerText = "Remove Best Friend Status"
console.log('Number', parseInt(UserID), 'added to BestFriends');
}
if (index !== -1) {
// Number exists, remove it
BestFriends.splice(index, 1);
btn.innerText = 'Best Friend';
console.log('Number', parseInt(UserID), 'removed from BestFriends');
} else {
// Number doesn't exist, add it
BestFriends.push(parseInt(UserID));
btn.innerText = 'Remove Best Friend Status';
console.log('Number', parseInt(UserID), 'added to BestFriends');
}
chrome.storage.sync.set({ 'PolyPlus_BestFriends': BestFriends, arrayOrder: true }, function() {
console.log('BestFriends saved successfully!');
setTimeout(function() {
btn.removeAttribute('disabled')
}, 1500)
});
});
}
});
chrome.storage.sync.set({PolyPlus_BestFriends: BestFriends, arrayOrder: true}, function () {
console.log('BestFriends saved successfully!');
setTimeout(function () {
btn.removeAttribute('disabled');
}, 1500);
});
});
}
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
if ('PolyPlus_BestFriends' in changes) {
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) {
BestFriends = result.PolyPlus_BestFriends || [];
chrome.storage.onChanged.addListener(function (changes, namespace) {
if ('PolyPlus_BestFriends' in changes) {
chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriends = result.PolyPlus_BestFriends || [];
if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status'
} else {
FavoriteBtn.innerText = 'Best Friend'
}
} else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')'
}
});
}
});
if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status';
} else {
FavoriteBtn.innerText = 'Best Friend';
}
} else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')';
}
});
}
});
function ClearBestFriends(){
chrome.storage.sync.set({ 'PolyPlus_BestFriends': {"BestFriends": []}, arrayOrder: true }, function() {
console.log('BestFriends saved successfully!');
setTimeout(function() {
btn.removeAttribute('disabled')
}, 1500)
});
}
function ClearBestFriends() {
chrome.storage.sync.set({PolyPlus_BestFriends: {BestFriends: []}, arrayOrder: true}, function () {
console.log('BestFriends saved successfully!');
setTimeout(function () {
btn.removeAttribute('disabled');
}, 1500);
});
}
}
async function OutfitCost() {
const AvatarCost = {
Total: 0,
Collectibles: 0,
Offsale: 0,
HasProfileTheme: false
}
for (let item of AvatarRow.children) {
const ItemID = item.getElementsByTagName('a')[0].href.split('/')[4]
await fetch('https://api.polytoria.com/v1/store/'+ItemID)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
let Price = data.price
if (data.isLimited === true) {
AvatarCost.Collectibles += 1
Price = data.averagePrice
} else if (data.sales === 0) {
AvatarCost.Offsale += 1
Price = 0
} else if (data.type === 'profileTheme') {
AvatarCost.HasProfileTheme = true
Price = 0
}
const AvatarCost = {
Total: 0,
Collectibles: 0,
Offsale: 0,
HasProfileTheme: false
};
for (let item of AvatarRow.children) {
const ItemID = item.getElementsByTagName('a')[0].href.split('/')[4];
await fetch('https://api.polytoria.com/v1/store/' + ItemID)
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
let Price = data.price;
if (data.isLimited === true) {
AvatarCost.Collectibles += 1;
Price = data.averagePrice;
} else if (data.sales === 0) {
AvatarCost.Offsale += 1;
Price = 0;
} else if (data.type === 'profileTheme') {
AvatarCost.HasProfileTheme = true;
Price = 0;
}
AvatarCost.Total += Price
})
.catch(error => {console.log(error)});
}
const ResultText = document.createElement('small')
ResultText.classList = 'fw-normal text-success'
ResultText.style.letterSpacing = '0px'
ResultText.innerHTML = `(<i class="pi pi-brick mx-1"></i> ${ (AvatarCost.Collectibles > 0 || AvatarCost.Offsale > 0 || AvatarCost.HasProfileTheme === true) ? '~' : '' }${ AvatarCost.Total.toLocaleString() } | ${ (AvatarCost.Collectibles > 0) ? AvatarCost.Collectibles + ' collectible' : '' }${ (AvatarCost.Offsale > 0) ? `, ${AvatarCost.Offsale} offsale` : '' }${ (AvatarCost.HasProfileTheme === true) ? ', profile theme excluded' : '' })`
AvatarCost.Total += Price;
})
.catch((error) => {
console.log(error);
});
}
const ResultText = document.createElement('small');
ResultText.classList = 'fw-normal text-success';
ResultText.style.letterSpacing = '0px';
ResultText.innerHTML = `(<i class="pi pi-brick mx-1"></i> ${AvatarCost.Collectibles > 0 || AvatarCost.Offsale > 0 || AvatarCost.HasProfileTheme === true ? '~' : ''}${AvatarCost.Total.toLocaleString()} | ${AvatarCost.Collectibles > 0 ? AvatarCost.Collectibles + ' collectible' : ''}${AvatarCost.Offsale > 0 ? `, ${AvatarCost.Offsale} offsale` : ''}${AvatarCost.HasProfileTheme === true ? ', profile theme excluded' : ''})`;
CalculateButton.remove()
AvatarHeading.appendChild(ResultText)
CalculateButton.remove();
AvatarHeading.appendChild(ResultText);
}

View file

@ -1,30 +1,30 @@
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
if (result.PolyPlus_Settings.MoreSearchFiltersOn === true) {
const BlockedUsersCard = document.getElementsByClassName('card-body')[1]
const InputGroup = document.createElement('div')
InputGroup.classList = 'input-group mb-2'
InputGroup.innerHTML = `
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
if (result.PolyPlus_Settings.MoreSearchFiltersOn === true) {
const BlockedUsersCard = document.getElementsByClassName('card-body')[1];
const InputGroup = document.createElement('div');
InputGroup.classList = 'input-group mb-2';
InputGroup.innerHTML = `
<input id="blocked-users-search" type="text" class="form-control bg-dark" placeholder="Search blocked users...">
<button id="blocked-users-confirm" class="btn btn-secondary"><i class="fad fa-search"></i></button>
`
BlockedUsersCard.insertBefore(InputGroup, BlockedUsersCard.children[0])
const SearchBar = document.getElementById('blocked-users-search')
const ConfirmBtn = document.getElementById('blocked-users-confirm')
`;
BlockedUsersCard.insertBefore(InputGroup, BlockedUsersCard.children[0]);
const SearchBar = document.getElementById('blocked-users-search');
const ConfirmBtn = document.getElementById('blocked-users-confirm');
ConfirmBtn.addEventListener('click', function(){
SearchBlockedUsers(SearchBar.value);
});
ConfirmBtn.addEventListener('click', function () {
SearchBlockedUsers(SearchBar.value);
});
function SearchBlockedUsers(query) {
query = query.toLowerCase();
for (let i = 1; i < BlockedUsersCard.children.length; i++) {
let Username = BlockedUsersCard.children[i].getElementsByTagName('h5')[0].innerText.toLowerCase();
if (Username.includes(query)) {
BlockedUsersCard.children[i].style.display = 'block'
} else {
BlockedUsersCard.children[i].style.display = 'none'
}
}
}
}
function SearchBlockedUsers(query) {
query = query.toLowerCase();
for (let i = 1; i < BlockedUsersCard.children.length; i++) {
let Username = BlockedUsersCard.children[i].getElementsByTagName('h5')[0].innerText.toLowerCase();
if (Username.includes(query)) {
BlockedUsersCard.children[i].style.display = 'block';
} else {
BlockedUsersCard.children[i].style.display = 'none';
}
}
}
}
});

View file

@ -1,109 +1,108 @@
var SelectedTrades = []
var SelectedTrades = [];
let Parent = document.getElementsByClassName('card mcard p-5 text-center text-muted')[0].parentElement
let Text = document.createElement('p')
Text.classList = 'mx-auto'
Text.style.textAlign = 'center'
Text.style.fontSize = '1.3rem'
let Parent = document.getElementsByClassName('card mcard p-5 text-center text-muted')[0].parentElement;
let Text = document.createElement('p');
Text.classList = 'mx-auto';
Text.style.textAlign = 'center';
Text.style.fontSize = '1.3rem';
Text.innerHTML = `
<span>0</span> trades selected!
<br>
<button id="viewSelectionBtn" class="btn btn-primary">View Selection</button>
<button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button>
<button id="cancelSelectionBtn" class="btn btn-danger">Cancel Selected Trades</button>
`
Parent.insertBefore(Text, Parent.children[0])
`;
Parent.insertBefore(Text, Parent.children[0]);
let Text_Span = Text.querySelector('span');
let Text_View = document.getElementById('viewSelectionBtn');
let Text_Clear = document.getElementById('clearSelectionBtn');
let Text_Cancel = document.getElementById('cancelSelectionBtn');
var ConfirmCancel = 0
Text_View.addEventListener('click', function(){});
Text_Clear.addEventListener('click', function(){
SelectedTrades = []
UpdateCheckboxes();
Text_Span.innerText = SelectedTrades.length
var ConfirmCancel = 0;
Text_View.addEventListener('click', function () {});
Text_Clear.addEventListener('click', function () {
SelectedTrades = [];
UpdateCheckboxes();
Text_Span.innerText = SelectedTrades.length;
});
Text_Cancel.addEventListener('click', function(){
ConfirmCancel = ConfirmCancel + 1
switch(ConfirmCancel) {
case 0:
Text_Cancel.innerText = 'Cancel Selected Trades'
break
case 1:
Text_Cancel.innerText = 'Are you sure?'
break
case 2:
let Success = true
for (let i = 0; i < SelectedTrades.length; i++) {
setTimeout(function () {}, 110)
console.log(SelectedTrades[i])
fetch('https://polytoria.com/api/trade/decline', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({ id: SelectedTrades[i] }),
})
.catch(error => {
// Handle any errors
console.error('Error:', error);
Success = false
});
}
SelectedTrades = []
UpdateCheckboxes();
Text_Cancel.innerText = 'Cancel Selected Trades'
ConfirmCancel = 0
break
}
Text_Cancel.addEventListener('click', function () {
ConfirmCancel = ConfirmCancel + 1;
switch (ConfirmCancel) {
case 0:
Text_Cancel.innerText = 'Cancel Selected Trades';
break;
case 1:
Text_Cancel.innerText = 'Are you sure?';
break;
case 2:
let Success = true;
for (let i = 0; i < SelectedTrades.length; i++) {
setTimeout(function () {}, 110);
console.log(SelectedTrades[i]);
fetch('https://polytoria.com/api/trade/decline', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({id: SelectedTrades[i]})
}).catch((error) => {
// Handle any errors
console.error('Error:', error);
Success = false;
});
}
SelectedTrades = [];
UpdateCheckboxes();
Text_Cancel.innerText = 'Cancel Selected Trades';
ConfirmCancel = 0;
break;
}
});
LoadCheckBoxes();
function LoadCheckBoxes() {
Array.from(document.getElementsByClassName('card-inbox')).forEach(element => {
let ViewBtn = element.querySelector('a.btn.btn-primary')
let TradeID = parseInt(ViewBtn.getAttribute('href').split('/')[3])
var NewCheckBox = document.createElement('button')
NewCheckBox.classList = 'polyplus-multicanceltr-checkbox'
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem; margin-left: 10px;')
var Index = SelectedTrades.indexOf(TradeID)
if (Index !== -1) {
NewCheckBox.style.borderColor = 'lime'
}
ViewBtn.parentElement.appendChild(NewCheckBox)
NewCheckBox.addEventListener('click', function(){
var Index = SelectedTrades.indexOf(TradeID)
if (Index === -1) {
SelectedTrades.push(TradeID)
NewCheckBox.style.borderColor = 'lime'
} else {
SelectedTrades.splice(Index, 1)
NewCheckBox.style.borderColor = '#393939'
}
Text_Span.innerText = SelectedTrades.length
UpdateCheckboxes();
});
});
Array.from(document.getElementsByClassName('card-inbox')).forEach((element) => {
let ViewBtn = element.querySelector('a.btn.btn-primary');
let TradeID = parseInt(ViewBtn.getAttribute('href').split('/')[3]);
var NewCheckBox = document.createElement('button');
NewCheckBox.classList = 'polyplus-multicanceltr-checkbox';
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem; margin-left: 10px;');
var Index = SelectedTrades.indexOf(TradeID);
if (Index !== -1) {
NewCheckBox.style.borderColor = 'lime';
}
ViewBtn.parentElement.appendChild(NewCheckBox);
NewCheckBox.addEventListener('click', function () {
var Index = SelectedTrades.indexOf(TradeID);
if (Index === -1) {
SelectedTrades.push(TradeID);
NewCheckBox.style.borderColor = 'lime';
} else {
SelectedTrades.splice(Index, 1);
NewCheckBox.style.borderColor = '#393939';
}
Text_Span.innerText = SelectedTrades.length;
UpdateCheckboxes();
});
});
}
function UpdateCheckboxes(){
document.querySelectorAll('.polyplus-multicanceltr-checkbox').forEach(element => {
let Parent = element.parentElement
let ViewBtn = Parent.querySelector('a.btn.btn-primary')
if (element.getAttribute('disabled')) {
element.removeAttribute('disabled')
}
if (SelectedTrades.IndexOf(ViewBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939'
} else {
element.style.borderColor = 'lime'
if (SelectedTrades.length >= 10) {
element.setAttribute('disabled', true)
}
}
})
function UpdateCheckboxes() {
document.querySelectorAll('.polyplus-multicanceltr-checkbox').forEach((element) => {
let Parent = element.parentElement;
let ViewBtn = Parent.querySelector('a.btn.btn-primary');
if (element.getAttribute('disabled')) {
element.removeAttribute('disabled');
}
if (SelectedTrades.IndexOf(ViewBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939';
} else {
element.style.borderColor = 'lime';
if (SelectedTrades.length >= 10) {
element.setAttribute('disabled', true);
}
}
});
}

View file

@ -9,12 +9,12 @@ LoadFile(chrome.runtime.getURL('resources/currencies.json'), function(text){
let Utilities;
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
})();
let Nav = document.getElementsByClassName('nav-pills')[0]
let DIV = document.createElement('div')
let Nav = document.getElementsByClassName('nav-pills')[0];
let DIV = document.createElement('div');
DIV.innerHTML = `
<input id="polyplus-brickconverter-input" type="number" class="form-control bg-dark mb-2" placeholder="How many Bricks?">
<input id="polyplus-brickconverter-output" type="text" class="form-control bg-dark mb-2" placeholder="Result" disabled>
@ -37,24 +37,24 @@ DIV.innerHTML = `
<option value="5">d</option>
</select>
-->
`
Nav.appendChild(document.createElement('hr'))
Nav.appendChild(DIV)
`;
Nav.appendChild(document.createElement('hr'));
Nav.appendChild(DIV);
let Input = document.getElementById('polyplus-brickconverter-input')
let Output = document.getElementById('polyplus-brickconverter-output')
let Type = document.getElementById('polyplus-brickconverter-type')
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Type.selectedIndex = result.PolyPlus_Settings.IRLPriceWithCurrency.Currency || 0
let Input = document.getElementById('polyplus-brickconverter-input');
let Output = document.getElementById('polyplus-brickconverter-output');
let Type = document.getElementById('polyplus-brickconverter-type');
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Type.selectedIndex = result.PolyPlus_Settings.IRLPriceWithCurrency.Currency || 0;
});
//let Package = document.getElementById('polyplus-brickconverter-package')
Input.addEventListener('input', function(){
Update()
Input.addEventListener('input', function () {
Update();
});
Type.addEventListener('change', function(){
Update()
Type.addEventListener('change', function () {
Update();
});
/*
@ -63,18 +63,20 @@ Package.addEventListener('change', function(){
});
*/
async function Update(){
if (Input.value === "") {
Output.value = ''
return
}
const IRLResult = await Utilities.CalculateIRL(Input.value, Type.selectedIndex)
Output.value = "$" + IRLResult.result + " " + IRLResult.display
async function Update() {
if (Input.value === '') {
Output.value = '';
return;
}
const IRLResult = await Utilities.CalculateIRL(Input.value, Type.selectedIndex);
Output.value = '$' + IRLResult.result + ' ' + IRLResult.display;
}
function LoadFile(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); }
xhr.open("GET", path, true);
xhr.send();
var xhr = new XMLHttpRequest();
xhr.onload = function () {
return callback(this.responseText);
};
xhr.open('GET', path, true);
xhr.send();
}

View file

@ -1,5 +1,5 @@
const Manifest = chrome.runtime.getManifest()
const SettingsURL = chrome.runtime.getURL('settings.html')
const Manifest = chrome.runtime.getManifest();
const SettingsURL = chrome.runtime.getURL('settings.html');
/*
ON INSTALL:
@ -11,153 +11,142 @@ chrome.runtime.onInstalled.addListener(() => {
// WHEN CLICKING ON EXTENSION ICON OPEN THE SETTINGS PAGE
chrome.action.onClicked.addListener((tab) => {
chrome.tabs.create({ active: true, url: SettingsURL });
chrome.tabs.create({active: true, url: SettingsURL});
});
// REGISTER AN ALARM FOR DAILY UPDATE CHECK
chrome.alarms.create('PolyPlus-UpdateCheck', {
when: Date.now() + (GetNext12PM())
when: Date.now() + GetNext12PM()
});
function GetNext12PM() {
const Now = new Date();
const Next = new Date();
Next.setHours(12, 0, 0, 0);
if (Now.getHours() >= 12) {
Next.setDate(Next.getDate() + 1);
}
return Next - Now;
const Now = new Date();
const Next = new Date();
Next.setHours(12, 0, 0, 0);
if (Now.getHours() >= 12) {
Next.setDate(Next.getDate() + 1);
}
return Next - Now;
}
// HANDLE ALARMS FIRING
chrome.alarms.onAlarm.addListener(function(alarm){
if (alarm.name === 'PolyPlus-UpdateCheck') {
RunUpdateNotifier()
}
chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name === 'PolyPlus-UpdateCheck') {
RunUpdateNotifier();
}
});
function RunUpdateNotifier() {
chrome.storage.local.get(["PolyPlus_LiveVersion", "PolyPlus_OutOfDate", "PolyPlus_SkipUpdate"], function(result){
const OutOfDate = result.PolyPlus_OutOfDate || false
const SkipUpdate = result.PolyPlus_SkipUpdate || null
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version
if (OutOfDate !== true && SkipUpdate !== LiveVersion) {
fetch('https://polyplus.vercel.app/data/version.json')
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
chrome.storage.local.set({'PolyPlus_LiveVersion': data.version}, function(){
console.log('Cached live version')
})
if (data.version > Manifest.version) {
chrome.storage.local.set({'PolyPlus_OutOfDate': true, 'PolyPlus_ReleaseNotes': data.releaseNotes}, function(){
console.log('Cached update notifier result')
});
chrome.notifications.create("", {
type: "basic",
iconUrl: chrome.runtime.getURL("icon.png"),
title: "New Update Available",
message: "A new update is available for Poly+! (v" + data.version + ")"
}, function(notificationID) {
chrome.notifications.onClicked.addListener(function (id) {
if (id === notificationID) {
chrome.tabs.create({url: 'https://github.com/IndexingGitHub/PolyPlus/releases', active: true})
chrome.notifications.clear(notificationID)
}
})
})
/*
chrome.storage.local.get(['PolyPlus_LiveVersion', 'PolyPlus_OutOfDate', 'PolyPlus_SkipUpdate'], function (result) {
const OutOfDate = result.PolyPlus_OutOfDate || false;
const SkipUpdate = result.PolyPlus_SkipUpdate || null;
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version;
if (OutOfDate !== true && SkipUpdate !== LiveVersion) {
fetch('https://polyplus.vercel.app/data/version.json')
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
chrome.storage.local.set({PolyPlus_LiveVersion: data.version}, function () {
console.log('Cached live version');
});
if (data.version > Manifest.version) {
chrome.storage.local.set({PolyPlus_OutOfDate: true, PolyPlus_ReleaseNotes: data.releaseNotes}, function () {
console.log('Cached update notifier result');
});
chrome.notifications.create(
'',
{
type: 'basic',
iconUrl: chrome.runtime.getURL('icon.png'),
title: 'New Update Available',
message: 'A new update is available for Poly+! (v' + data.version + ')'
},
function (notificationID) {
chrome.notifications.onClicked.addListener(function (id) {
if (id === notificationID) {
chrome.tabs.create({url: 'https://github.com/IndexingGitHub/PolyPlus/releases', active: true});
chrome.notifications.clear(notificationID);
}
});
}
);
/*
chrome.action.setBadgeBackgroundColor(
{color: 'red'},
() => { },
);
*/
}
})
.catch(error => {console.log(error)})
}
});
}
})
.catch((error) => {
console.log(error);
});
}
});
}
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({
title: 'Run Update Notifier',
id: 'PolyPlus-RunUpdateNotifier',
contexts: ['all'],
documentUrlPatterns: [
"https://polytoria.com/my/settings/polyplus#dev",
]
});
chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({
title: 'Run Update Notifier',
id: 'PolyPlus-RunUpdateNotifier',
contexts: ['all'],
documentUrlPatterns: ['https://polytoria.com/my/settings/polyplus#dev']
});
// COPY ASSET ID CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({
title: 'Copy Asset ID',
id: 'PolyPlus-CopyID',
contexts: ['link'],
documentUrlPatterns: [
"https://polytoria.com/*",
SettingsURL
],
targetUrlPatterns: [
"https://polytoria.com/places/**",
"https://polytoria.com/users/**",
"https://polytoria.com/u/**",
"https://polytoria.com/store/**",
"https://polytoria.com/guilds/**",
]
});
// COPY ASSET ID CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({
title: 'Copy Asset ID',
id: 'PolyPlus-CopyID',
contexts: ['link'],
documentUrlPatterns: ['https://polytoria.com/*', SettingsURL],
targetUrlPatterns: ['https://polytoria.com/places/**', 'https://polytoria.com/users/**', 'https://polytoria.com/u/**', 'https://polytoria.com/store/**', 'https://polytoria.com/guilds/**']
});
// COPY AVATAR HASH CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({
title: 'Copy Avatar Hash',
id: 'PolyPlus-CopyAvatarHash',
contexts: ['image'],
documentUrlPatterns: [
"https://polytoria.com/*",
SettingsURL
],
targetUrlPatterns: [
"https://c0.ptacdn.com/thumbnails/avatars/**",
"https://c0.ptacdn.com/thumbnails/avatars/**"
]
});
})
// COPY AVATAR HASH CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({
title: 'Copy Avatar Hash',
id: 'PolyPlus-CopyAvatarHash',
contexts: ['image'],
documentUrlPatterns: ['https://polytoria.com/*', SettingsURL],
targetUrlPatterns: ['https://c0.ptacdn.com/thumbnails/avatars/**', 'https://c0.ptacdn.com/thumbnails/avatars/**']
});
});
// HANDLE CONTEXT MENU ITEMS
chrome.contextMenus.onClicked.addListener(async function (info, tab){
if (info.menuItemId === 'PolyPlus-CopyID') {
console.log(info.linkUrl.split('/')[3])
let ID = info.linkUrl.split('/')[4]
if (info.linkUrl.split('/')[3] === "u") {
ID = (await (await fetch('https://api.polytoria.com/v1/users/find?username=' + info.linkUrl.split('/')[4])).json()).id
}
console.log(ID)
chrome.scripting
.executeScript({
target: {tabId: tab.id},
func: CopyAssetID,
args: [ID]
})
.then(() => console.log("Copied ID!"));
}
chrome.contextMenus.onClicked.addListener(async function (info, tab) {
if (info.menuItemId === 'PolyPlus-CopyID') {
console.log(info.linkUrl.split('/')[3]);
let ID = info.linkUrl.split('/')[4];
if (info.linkUrl.split('/')[3] === 'u') {
ID = (await (await fetch('https://api.polytoria.com/v1/users/find?username=' + info.linkUrl.split('/')[4])).json()).id;
}
console.log(ID);
chrome.scripting
.executeScript({
target: {tabId: tab.id},
func: CopyAssetID,
args: [ID]
})
.then(() => console.log('Copied ID!'));
}
if (info.menuItemId === 'PolyPlus-CopyAvatarHash') {
let Hash = new URL(info.srcUrl).pathname.split('/')[3].replace('-icon', '').replace('.png', '')
chrome.scripting
.executeScript({
target: {tabId: tab.id},
func: CopyAvatarHash,
args: [Hash]
})
.then(() => console.log("Copied ID!"));
}
if (info.menuItemId === 'PolyPlus-CopyAvatarHash') {
let Hash = new URL(info.srcUrl).pathname.split('/')[3].replace('-icon', '').replace('.png', '');
chrome.scripting
.executeScript({
target: {tabId: tab.id},
func: CopyAvatarHash,
args: [Hash]
})
.then(() => console.log('Copied ID!'));
}
if (info.menuItemId === 'PolyPlus-RunUpdateNotifier') {
RunUpdateNotifier()
}
if (info.menuItemId === 'PolyPlus-RunUpdateNotifier') {
RunUpdateNotifier();
}
});
/*
@ -194,23 +183,23 @@ function matchesUrl(patterns, url) {
*/
function CopyAssetID(id) {
navigator.clipboard
.writeText(id)
.then(() => {
alert('Successfully copied ID!')
})
.catch(() => {
alert('Failure to copy ID.')
});
navigator.clipboard
.writeText(id)
.then(() => {
alert('Successfully copied ID!');
})
.catch(() => {
alert('Failure to copy ID.');
});
}
function CopyAvatarHash(hash) {
navigator.clipboard
.writeText(hash)
.then(() => {
alert('Successfully copied avatar hash!')
})
.catch(() => {
alert('Failure to copy avatar hash.')
});
navigator.clipboard
.writeText(hash)
.then(() => {
alert('Successfully copied avatar hash!');
})
.catch(() => {
alert('Failure to copy avatar hash.');
});
}

View file

@ -3,12 +3,12 @@
Accessable at /my/settings/polyplus#dev
*/
if (window.location.pathname.split('/')[3] === "polyplus" && window.location.hash === '#dev') {
document.title = 'Poly+ Debug - Polytoria'
const Version = chrome.runtime.getManifest().version
if (window.location.pathname.split('/')[3] === 'polyplus' && window.location.hash === '#dev') {
document.title = 'Poly+ Debug - Polytoria';
const Version = chrome.runtime.getManifest().version;
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#main-content .container').innerHTML = `
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#main-content .container').innerHTML = `
<style>
#main-content .container label {
font-size: 0.8rem;
@ -101,133 +101,141 @@ if (window.location.pathname.split('/')[3] === "polyplus" && window.location.has
</div>
</div>
</div>
`
`;
const CheckForUpdatesButton = document.getElementById('check-for-updates')
function CheckForUpdates() {
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates)
CheckForUpdatesButton.disabled = true
fetch('https://polyplus.vercel.app/data/version.json')
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
if (data.version === Version || Math.floor((data.version - Version) * 10) === 0) {
CheckForUpdatesButton.innerText = 'No updates available'
} else {
CheckForUpdatesButton.innerText = Math.floor((data.version - Version) * 10) + ' updates available'
}
})
.catch(error => {console.log(error)});
}
CheckForUpdatesButton.addEventListener('click', CheckForUpdates);
const CheckForUpdatesButton = document.getElementById('check-for-updates');
function CheckForUpdates() {
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates);
CheckForUpdatesButton.disabled = true;
fetch('https://polyplus.vercel.app/data/version.json')
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
if (data.version === Version || Math.floor((data.version - Version) * 10) === 0) {
CheckForUpdatesButton.innerText = 'No updates available';
} else {
CheckForUpdatesButton.innerText = Math.floor((data.version - Version) * 10) + ' updates available';
}
})
.catch((error) => {
console.log(error);
});
}
CheckForUpdatesButton.addEventListener('click', CheckForUpdates);
document.getElementById('edit-setting').addEventListener('click', function(){
const EditSettingName = document.getElementById('edit-setting-name')
const EditSettingValue = document.getElementById('edit-setting-value')
document.getElementById('edit-setting').addEventListener('click', function () {
const EditSettingName = document.getElementById('edit-setting-name');
const EditSettingValue = document.getElementById('edit-setting-value');
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) {
result = result.PolyPlus_Settings
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
result = result.PolyPlus_Settings;
let NewValue = EditSettingValue.value
switch (NewValue) {
case 'true':
NewValue = true
break
case 'false':
NewValue = false
break
case 'null':
NewValue = null
break
case 'undefined':
NewValue = undefined
break
case parseInt(NewValue):
NewValue = parseInt(NewValue)
break
}
result[EditSettingName.value] = NewValue
let NewValue = EditSettingValue.value;
switch (NewValue) {
case 'true':
NewValue = true;
break;
case 'false':
NewValue = false;
break;
case 'null':
NewValue = null;
break;
case 'undefined':
NewValue = undefined;
break;
case parseInt(NewValue):
NewValue = parseInt(NewValue);
break;
}
result[EditSettingName.value] = NewValue;
chrome.storage.sync.set({ 'PolyPlus_Settings': result }, function() {
alert('Successfully set: "' + EditSettingName.value + '" to ' + NewValue)
});
});
});
chrome.storage.sync.set({PolyPlus_Settings: result}, function () {
alert('Successfully set: "' + EditSettingName.value + '" to ' + NewValue);
});
});
});
document.getElementById('reset-settings').addEventListener('click', async function(){
let Utilities = await import(chrome.runtime.getURL('resources/utils.js'))
Utilities = Utilities.default
chrome.storage.sync.set({ 'PolyPlus_Settings': Utilities.DefaultSettings }, function() {
alert('Successfully reset settings to their defaults!')
});
});
document.getElementById('reset-settings').addEventListener('click', async function () {
let Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
chrome.storage.sync.set({PolyPlus_Settings: Utilities.DefaultSettings}, function () {
alert('Successfully reset settings to their defaults!');
});
});
document.getElementById('example-pinnedgames').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': [6012, 3857, 2537] }, function() {
alert('Successfully loaded example for Pinned Games!')
});
});
document.getElementById('example-pinnedgames').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_PinnedGames: [6012, 3857, 2537]}, function () {
alert('Successfully loaded example for Pinned Games!');
});
});
document.getElementById('example-bestfriends').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_BestFriends': [1, 2, 3] }, function() {
alert('Successfully loaded example for Best Friends!')
});
});
document.getElementById('example-bestfriends').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_BestFriends: [1, 2, 3]}, function () {
alert('Successfully loaded example for Best Friends!');
});
});
document.getElementById('example-itemwishlist').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_ItemWishlist': [31495, 31493, 31492] }, function() {
alert('Successfully loaded example for Item Wishlist!')
});
});
document.getElementById('example-itemwishlist').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_ItemWishlist: [31495, 31493, 31492]}, function () {
alert('Successfully loaded example for Item Wishlist!');
});
});
document.getElementById('clear-pinnedgames').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': [] }, function() {
alert('Successfully cleared Pinned Games!')
});
});
document.getElementById('clear-pinnedgames').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_PinnedGames: []}, function () {
alert('Successfully cleared Pinned Games!');
});
});
document.getElementById('clear-bestfriends').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_BestFriends': [] }, function() {
alert('Successfully cleared Best Friends!')
});
});
document.getElementById('clear-bestfriends').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_BestFriends: []}, function () {
alert('Successfully cleared Best Friends!');
});
});
document.getElementById('clear-itemwishlist').addEventListener('click', function(){
chrome.storage.sync.set({ 'PolyPlus_ItemWishlist': [] }, function() {
alert('Successfully cleared Item Wishlist!')
});
});
document.getElementById('clear-itemwishlist').addEventListener('click', function () {
chrome.storage.sync.set({PolyPlus_ItemWishlist: []}, function () {
alert('Successfully cleared Item Wishlist!');
});
});
document.getElementById('delete-sync').addEventListener('click', function(){
if (confirm("Are you sure you'd like to delete all sync data associated with the extension?") === false) { return }
chrome.storage.sync.clear(function() {
alert('Successfully deleted all sync data associated with the extension!')
});
});
document.getElementById('delete-sync').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all sync data associated with the extension?") === false) {
return;
}
chrome.storage.sync.clear(function () {
alert('Successfully deleted all sync data associated with the extension!');
});
});
document.getElementById('delete-local').addEventListener('click', function(){
if (confirm("Are you sure you'd like to delete all local data associated with the extension?") === false) { return }
chrome.storage.local.clear(function() {
alert('Successfully deleted all local data associated with the extension!')
});
});
document.getElementById('delete-local').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all local data associated with the extension?") === false) {
return;
}
chrome.storage.local.clear(function () {
alert('Successfully deleted all local data associated with the extension!');
});
});
document.getElementById('delete-all-data').addEventListener('click', function(){
if (confirm("Are you sure you'd like to delete all sync and local data associated with the extension?") === false) { return }
chrome.storage.sync.clear(function() {
alert('Successfully deleted all sync data associated with the extension!')
});
chrome.storage.local.clear(function() {
alert('Successfully deleted all local data associated with the extension!')
});
});
document.getElementById('delete-all-data').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all sync and local data associated with the extension?") === false) {
return;
}
chrome.storage.sync.clear(function () {
alert('Successfully deleted all sync data associated with the extension!');
});
chrome.storage.local.clear(function () {
alert('Successfully deleted all local data associated with the extension!');
});
});
chrome.storage.sync.getBytesInUse(["PolyPlus_Settings", "PolyPlus_PinnedGames", "PolyPlus_BestFriends", "PolyPlus_ItemWishlist"], function(bytes){
document.getElementById('data-size').innerText = bytes.toLocaleString()
});
})
chrome.storage.sync.getBytesInUse(['PolyPlus_Settings', 'PolyPlus_PinnedGames', 'PolyPlus_BestFriends', 'PolyPlus_ItemWishlist'], function (bytes) {
document.getElementById('data-size').innerText = bytes.toLocaleString();
});
});
}

View file

@ -1,40 +1,40 @@
setTimeout(function () {}, 100)
setTimeout(function () {}, 100);
var Settings;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Settings = result.PolyPlus_Settings;
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings;
if (!(Settings.MoreSearchFiltersOn === true)) {
return
}
if (!(Settings.MoreSearchFiltersOn === true)) {
return;
}
let Form = document.querySelector('form[action="/forum/search"]')
let SearchBtn = document.querySelector('button[type="submit"]')
let CreatedByFilter = document.createElement('div')
CreatedByFilter.classList = 'input-group mt-2'
CreatedByFilter.innerHTML = `
let Form = document.querySelector('form[action="/forum/search"]');
let SearchBtn = document.querySelector('button[type="submit"]');
let CreatedByFilter = document.createElement('div');
CreatedByFilter.classList = 'input-group mt-2';
CreatedByFilter.innerHTML = `
<div class="form-check">
<input class="form-check-input" type="checkbox">
<label class="form-check-label" for="createdBy">Created by <input type="text" class="form-control" placeholder="willemsteller" id="createdBy" name="createdBy"></label>
</div>
`
console.log(SearchBtn)
Form.insertBefore(CreatedByFilter, SearchBtn.parentElement)
let CreatedByFilter_Checkbox = CreatedByFilter.querySelector('input[type="checkbox"]')
let CreatedByFilter_Input = CreatedByFilter.querySelector('input[type="text"]')
let CreatedByValue = GetURLParameter("createdBy")
console.log(CreatedByValue)
if (CreatedByValue) {
CreatedByFilter_Checkbox.setAttribute('checked', true)
CreatedByFilter_Input.setAttribute('value', CreatedByValue)
CreatedByFilter_Input.removeAttribute('disabled')
document.querySelectorAll('.forum-entry').forEach(element => {
console.log(element.querySelectorAll('a[href^="/users/"]')[1].innerText)
if (!(element.querySelectorAll('a[href^="/users/"]')[1].innerText === CreatedByValue)) {
element.remove();
}
});
}
/*
`;
console.log(SearchBtn);
Form.insertBefore(CreatedByFilter, SearchBtn.parentElement);
let CreatedByFilter_Checkbox = CreatedByFilter.querySelector('input[type="checkbox"]');
let CreatedByFilter_Input = CreatedByFilter.querySelector('input[type="text"]');
let CreatedByValue = GetURLParameter('createdBy');
console.log(CreatedByValue);
if (CreatedByValue) {
CreatedByFilter_Checkbox.setAttribute('checked', true);
CreatedByFilter_Input.setAttribute('value', CreatedByValue);
CreatedByFilter_Input.removeAttribute('disabled');
document.querySelectorAll('.forum-entry').forEach((element) => {
console.log(element.querySelectorAll('a[href^="/users/"]')[1].innerText);
if (!(element.querySelectorAll('a[href^="/users/"]')[1].innerText === CreatedByValue)) {
element.remove();
}
});
}
/*
CreatedByFilter_Checkbox.addEventListener('click', function(){
let Status = CreatedByFilter_Checkbox.getAttribute('checked')
if (Status === true) {
@ -47,7 +47,7 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
});
function GetURLParameter(param) {
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
return urlParams.get(param);
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
return urlParams.get(param);
}

View file

@ -1,51 +1,51 @@
const ForumText = document.querySelectorAll('p:not(.text-muted):not(.mb-0)')
const ForumText = document.querySelectorAll('p:not(.text-muted):not(.mb-0)');
var Settings = []
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) {
Settings = result.PolyPlus_Settings || {
ForumMentsOn: false,
ForumUnixStampsOn: false
}
var Settings = [];
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {
ForumMentsOn: false,
ForumUnixStampsOn: false
};
if (Settings.ForumMentsOn === true) {
ForumMentions()
}
if (Settings.ForumMentsOn === true) {
ForumMentions();
}
if (Settings.ForumUnixStampsOn === true) {
ForumUnixTimestamps()
}
if (Settings.ForumUnixStampsOn === true) {
ForumUnixTimestamps();
}
});
function ForumMentions() {
const Regex = /@([\w.]+)/g
const Regex = /@([\w.]+)/g;
for (let text of ForumText) {
let FormattedText = text.innerHTML
let match;
while ((match = Regex.exec(text.innerText)) !== null) {
const Username = match[0].substring(1)
FormattedText = FormattedText.replaceAll(match[0], `<a href="/users/@${Username}?ref=${encodeURIComponent(window.location.pathname)}" class="polyplus-mention">${match[0]}</a>`)
}
text.innerHTML = FormattedText
}
for (let text of ForumText) {
let FormattedText = text.innerHTML;
let match;
while ((match = Regex.exec(text.innerText)) !== null) {
const Username = match[0].substring(1);
FormattedText = FormattedText.replaceAll(match[0], `<a href="/users/@${Username}?ref=${encodeURIComponent(window.location.pathname)}" class="polyplus-mention">${match[0]}</a>`);
}
text.innerHTML = FormattedText;
}
}
function ForumUnixTimestamps() {
const Regex = /&lt;t:[A-Za-z0-9]+&gt;/i
const Regex = /&lt;t:[A-Za-z0-9]+&gt;/i;
for (let text of ForumText) {
let FormattedText = text.innerHTML
let match;
for (let text of ForumText) {
let FormattedText = text.innerHTML;
let match;
while ((match = Regex.exec(FormattedText)) !== null) {
const Timestamp = new Date(match[0].substring(6, match[0].length - 4) * 1000)
const Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
while ((match = Regex.exec(FormattedText)) !== null) {
const Timestamp = new Date(match[0].substring(6, match[0].length - 4) * 1000);
const Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const Distance = new Intl.RelativeTimeFormat({numeric: 'auto', style: 'short'}).format(Math.floor((Timestamp - new Date()) / (60 * 1000)), 'day')
const Result = `<code style="color: orange;">${Months[Timestamp.getMonth()]} ${Timestamp.getDate()}, ${Timestamp.getFullYear()} (${["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][Timestamp.getDay()-1]}) at ${Timestamp.getHours()-12}:${String(Timestamp.getMinutes()).padStart(2, "0")} (${Distance})</code>`
FormattedText = FormattedText.replaceAll(match[0], Result)
console.log(FormattedText)
}
text.innerHTML = FormattedText
}
const Distance = new Intl.RelativeTimeFormat({numeric: 'auto', style: 'short'}).format(Math.floor((Timestamp - new Date()) / (60 * 1000)), 'day');
const Result = `<code style="color: orange;">${Months[Timestamp.getMonth()]} ${Timestamp.getDate()}, ${Timestamp.getFullYear()} (${['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][Timestamp.getDay() - 1]}) at ${Timestamp.getHours() - 12}:${String(Timestamp.getMinutes()).padStart(2, '0')} (${Distance})</code>`;
FormattedText = FormattedText.replaceAll(match[0], Result);
console.log(FormattedText);
}
text.innerHTML = FormattedText;
}
}

View file

@ -1,52 +1,52 @@
const StoreItems = document.getElementById('store-items')
const StoreItems = document.getElementById('store-items');
var Settings;
let Utilities;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Settings = result.PolyPlus_Settings
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings;
if (Settings.IRLPriceWithCurrency.Enabled === true) {
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
if (Settings.IRLPriceWithCurrency.Enabled === true) {
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
for (let item of Array.from(StoreItems.children)) {
IRLPrice(item)
}
for (let item of Array.from(StoreItems.children)) {
IRLPrice(item);
}
const PreviousPage = document.querySelector('#store-prev a')
const NextPage = document.querySelector('#store-next a')
//PreviousPage.addEventListener('click', IRLPrice)
//NextPage.addEventListener('click', IRLPrice)
})();
}
const PreviousPage = document.querySelector('#store-prev a');
const NextPage = document.querySelector('#store-next a');
//PreviousPage.addEventListener('click', IRLPrice)
//NextPage.addEventListener('click', IRLPrice)
})();
}
});
async function IRLPrice(item) {
const Price = item.getElementsByClassName('text-success')[0]
if (Price !== undefined && Price.innerText !== "Free") {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency)
const Price = item.getElementsByClassName('text-success')[0];
if (Price !== undefined && Price.innerText !== 'Free') {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span')
Span.classList = 'text-muted polyplus-price-tag'
Span.style.fontSize = '0.7rem'
Span.innerText = " ($" + IRLResult.result + " " + IRLResult.display + ")"
Price.appendChild(Span)
}
let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag';
Span.style.fontSize = '0.7rem';
Span.innerText = ' ($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span);
}
}
const observer = new MutationObserver(async function (list){
for (const record of list) {
for (const element of record.addedNodes) {
if (element.tagName === "DIV" && element.classList.value === 'col-auto mb-3') {
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice(element)
}
}
}
observer.observe(StoreItems, {attributes: false,childList: true,subtree: false});
}
const observer = new MutationObserver(async function (list) {
for (const record of list) {
for (const element of record.addedNodes) {
if (element.tagName === 'DIV' && element.classList.value === 'col-auto mb-3') {
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice(element);
}
}
}
observer.observe(StoreItems, {attributes: false, childList: true, subtree: false});
}
});
observer.observe(StoreItems, {attributes: false,childList: true,subtree: false});
observer.observe(StoreItems, {attributes: false, childList: true, subtree: false});

View file

@ -1,57 +1,56 @@
const AssetID = window.location.pathname.split('/')[2]
const LibraryType = document.querySelectorAll('ol a')[1].innerText
const LibraryTypes = [
"Models",
"Audio",
"Decal",
"Mesh"
]
const AssetID = window.location.pathname.split('/')[2];
const LibraryType = document.querySelectorAll('ol a')[1].innerText;
const LibraryTypes = ['Models', 'Audio', 'Decal', 'Mesh'];
if (LibraryTypes.indexOf(LibraryType) !== -1) {
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Settings = result.PolyPlus_Settings || {};
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {};
if (Settings.LibraryDownloadsOn === false) { return }
if (Settings.LibraryDownloadsOn === false) {
return;
}
const Dropdown = document.querySelector('#app div[style] .dropdown-menu li')
const Dropdown = document.querySelector('#app div[style] .dropdown-menu li');
const DownloadLink = document.createElement('a')
DownloadLink.classList = 'dropdown-item text-warning'
DownloadLink.href = '#'
DownloadLink.innerHTML = `<i class="fa-duotone fa-download"></i> Download`
Dropdown.insertBefore(DownloadLink, Dropdown.children[Dropdown.children.length-1])
const DownloadLink = document.createElement('a');
DownloadLink.classList = 'dropdown-item text-warning';
DownloadLink.href = '#';
DownloadLink.innerHTML = `<i class="fa-duotone fa-download"></i> Download`;
Dropdown.insertBefore(DownloadLink, Dropdown.children[Dropdown.children.length - 1]);
switch(LibraryType) {
case 'Models':
DownloadLink.href = 'https://api.polytoria.com/v1/models/get-model?id=' + AssetID
break
case 'Audio':
const AudioBlob = new Blob([document.getElementsByTagName('audio')[0]], {type: 'octet-steam'})
DownloadLink.href = URL.createObjectURL(AudioBlob)
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.mp3'
case 'Decal':
const DecalBlob = new Blob([document.getElementsByClassName('store-thumbnail')[0]], {type: 'image/png'})
DownloadLink.href = URL.createObjectURL(DecalBlob)
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.png'
break
}
switch (LibraryType) {
case 'Models':
DownloadLink.href = 'https://api.polytoria.com/v1/models/get-model?id=' + AssetID;
break;
case 'Audio':
const AudioBlob = new Blob([document.getElementsByTagName('audio')[0]], {type: 'octet-steam'});
DownloadLink.href = URL.createObjectURL(AudioBlob);
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.mp3';
case 'Decal':
const DecalBlob = new Blob([document.getElementsByClassName('store-thumbnail')[0]], {type: 'image/png'});
DownloadLink.href = URL.createObjectURL(DecalBlob);
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.png';
break;
}
if (LibraryType === 'Mesh') {
let MeshURL = null
DownloadLink.addEventListener('click', async function(){
if (MeshURL !== null) { return }
MeshURL = await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + AssetID)
MeshURL = await MeshURL.json()
if (LibraryType === 'Mesh') {
let MeshURL = null;
DownloadLink.addEventListener('click', async function () {
if (MeshURL !== null) {
return;
}
MeshURL = await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + AssetID);
MeshURL = await MeshURL.json();
if (MeshURL.success === true) {
DownloadLink.href = MeshURL.url
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.glb'
if (MeshURL.success === true) {
DownloadLink.href = MeshURL.url;
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.glb';
DownloadLink.click()
} else {
alert('Failure to fetch .glb file for mesh')
}
})
}
});
DownloadLink.click();
} else {
alert('Failure to fetch .glb file for mesh');
}
});
}
});
}

View file

@ -1,46 +1,48 @@
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
Settings = result.PolyPlus_Settings || {
ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0
};
if (Settings.ApplyMembershipThemeOn !== true) {return}
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {
ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0
};
if (Settings.ApplyMembershipThemeOn !== true) {
return;
}
MembershipTheme = Settings.ApplyMembershipThemeTheme === 0 ? 'plus': 'plusdx'
MembershipTheme = Settings.ApplyMembershipThemeTheme === 0 ? 'plus' : 'plusdx';
document.addEventListener('DOMContentLoaded', function(){
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return
}
document.addEventListener('DOMContentLoaded', function () {
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return;
}
if (document.getElementsByTagName('NAV')[0].classList.contains('navbar-plus') === true || document.getElementsByTagName('NAV')[0].classList.contains('navbar-plusdx') === true) {
return
}
if (document.getElementsByTagName('NAV')[0].classList.contains('navbar-plus') === true || document.getElementsByTagName('NAV')[0].classList.contains('navbar-plusdx') === true) {
return;
}
const Navbar = document.querySelector('.navbar.navbar-expand-lg.navbar-light.bg-navbar.nav-topbar');
const Sidebar = document.querySelector('.d-flex.flex-column.flex-shrink-0.bg-sidebar.nav-sidebar');
const Navbar = document.querySelector('.navbar.navbar-expand-lg.navbar-light.bg-navbar.nav-topbar');
const Sidebar = document.querySelector('.d-flex.flex-column.flex-shrink-0.bg-sidebar.nav-sidebar');
Navbar.classList.add('navbar-' + MembershipTheme);
Sidebar.classList.add('sidebar-' + MembershipTheme);
Navbar.classList.add('navbar-' + MembershipTheme);
Sidebar.classList.add('sidebar-' + MembershipTheme);
if (MembershipTheme === 'plusdx') {
let SidebarLogo = document.querySelector('.nav-sidebar img');
SidebarLogo.setAttribute('src', 'https://c0.ptacdn.com/static/images/branding/icon-plusdx.bd9daa92.svg')
let SidebarLogoLabel = document.createElement('div')
SidebarLogoLabel.classList = 'nplusdx-banner'
SidebarLogoLabel.innerHTML = `
if (MembershipTheme === 'plusdx') {
let SidebarLogo = document.querySelector('.nav-sidebar img');
SidebarLogo.setAttribute('src', 'https://c0.ptacdn.com/static/images/branding/icon-plusdx.bd9daa92.svg');
let SidebarLogoLabel = document.createElement('div');
SidebarLogoLabel.classList = 'nplusdx-banner';
SidebarLogoLabel.innerHTML = `
<i class="pi pi-plusdx" style="margin-right:-0.4em"></i>
`
SidebarLogo.parentElement.appendChild(SidebarLogoLabel)
`;
SidebarLogo.parentElement.appendChild(SidebarLogoLabel);
if (window.location.pathname === "/home") {
let HomeUsernameText = document.getElementsByClassName('home-title2')[0]
HomeUsernameText.children[0].classList.add('text-plusdx')
let Label = document.createElement('div')
Label.classList = 'hplusdx-banner rounded-2'
Label.setAttribute('style', 'margin-top: -8px; animation-delay: 0.09s;')
Label.innerText = 'Deluxe'
HomeUsernameText.appendChild(Label)
}
}
});
if (window.location.pathname === '/home') {
let HomeUsernameText = document.getElementsByClassName('home-title2')[0];
HomeUsernameText.children[0].classList.add('text-plusdx');
let Label = document.createElement('div');
Label.classList = 'hplusdx-banner rounded-2';
Label.setAttribute('style', 'margin-top: -8px; animation-delay: 0.09s;');
Label.innerText = 'Deluxe';
HomeUsernameText.appendChild(Label);
}
}
});
});

View file

@ -1,55 +1,57 @@
!(() => {
let Comments = document.getElementById('comments')
const Type = window.location.pathname.split('/')[1]
let Comments = document.getElementById('comments');
const Type = window.location.pathname.split('/')[1];
let CreatorID;
if (Type === 'store') {
if (document.querySelector('h5 .text-reset[href^="/users/"]')) {
CreatorID = document.querySelector('h5 .text-reset[href^="/users/"]').getAttribute('href').split('/')[2]
} else {
CreatorID = 1
}
} else if (Type === 'places') {
CreatorID = document.querySelector('.mcard .col .text-muted [href^="/users/"]').getAttribute('href').split('/')[2]
} else if (Type === 'feed') {
CreatorID = document.querySelector('p a[href^="/users/"].text-reset').getAttribute('href').split('/')[2]
} else if (Type === 'guilds') {
CreatorID = document.querySelector('[class^="userlink-"][href^="/users/"]').getAttribute('href').split('/')[2]
Comments = document.getElementById('wall-posts')
}
let CreatorID;
if (Type === 'store') {
if (document.querySelector('h5 .text-reset[href^="/users/"]')) {
CreatorID = document.querySelector('h5 .text-reset[href^="/users/"]').getAttribute('href').split('/')[2];
} else {
CreatorID = 1;
}
} else if (Type === 'places') {
CreatorID = document.querySelector('.mcard .col .text-muted [href^="/users/"]').getAttribute('href').split('/')[2];
} else if (Type === 'feed') {
CreatorID = document.querySelector('p a[href^="/users/"].text-reset').getAttribute('href').split('/')[2];
} else if (Type === 'guilds') {
CreatorID = document.querySelector('[class^="userlink-"][href^="/users/"]').getAttribute('href').split('/')[2];
Comments = document.getElementById('wall-posts');
}
const Observer = new MutationObserver(function (list){
for (let record of list) {
for (let element of record.addedNodes) {
if (element.classList === 'card mb-3') {
LoadCreatorTag(element)
}
}
}
});
Observer.observe(Comments, {attributes: false, childList: true, subtree: false})
const Observer = new MutationObserver(function (list) {
for (let record of list) {
for (let element of record.addedNodes) {
if (element.classList === 'card mb-3') {
LoadCreatorTag(element);
}
}
}
});
Observer.observe(Comments, {attributes: false, childList: true, subtree: false});
const LoadCreatorTag = function(element) {
let NameElement = element.querySelector('.text-reset[href^="/users/"]')
if (Type === 'guilds') {
NameElement = element.querySelector('[class^="userlink-"][href^="/users/"]')
}
const LoadCreatorTag = function (element) {
let NameElement = element.querySelector('.text-reset[href^="/users/"]');
if (Type === 'guilds') {
NameElement = element.querySelector('[class^="userlink-"][href^="/users/"]');
}
let UserID = NameElement.getAttribute('href').split('/')[2]
if (UserID === CreatorID) {
let Tag = document.createElement('span')
Tag.classList = 'badge bg-primary'
Tag.style.marginLeft = '5px'
Tag.style.verticalAlign = 'text-top'
Tag.innerText = 'CREATOR'
if (Type === 'guilds') { Tag.innerText = 'LEADER' }
NameElement.appendChild(Tag)
let UserID = NameElement.getAttribute('href').split('/')[2];
if (UserID === CreatorID) {
let Tag = document.createElement('span');
Tag.classList = 'badge bg-primary';
Tag.style.marginLeft = '5px';
Tag.style.verticalAlign = 'text-top';
Tag.innerText = 'CREATOR';
if (Type === 'guilds') {
Tag.innerText = 'LEADER';
}
NameElement.appendChild(Tag);
//new window.bootstrap.Tooltip(Tag, {toggle:"tooltip",title:"This user is the creator of this asset!"})
}
}
//new window.bootstrap.Tooltip(Tag, {toggle:"tooltip",title:"This user is the creator of this asset!"})
}
};
Array.from(Comments.children).forEach(element => {
LoadCreatorTag(element)
});
Array.from(Comments.children).forEach((element) => {
LoadCreatorTag(element);
});
})();

View file

@ -1,69 +1,69 @@
const PlaceID = window.location.pathname.split('/')[3]
const Form = document.querySelector('form[action="/create/place/update"]')
const PlaceID = window.location.pathname.split('/')[3];
const Form = document.querySelector('form[action="/create/place/update"]');
var Settings;
var PlaceData = null
var PlaceData = null;
!(async () => {
ActivityToggle()
//RequestGameProfile()
CopyOwnedPlace()
})()
ActivityToggle();
//RequestGameProfile()
CopyOwnedPlace();
})();
async function ActivityToggle() {
if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + PlaceID)
PlaceData = await PlaceData.json()
}
let Status = PlaceData.isActive
if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + PlaceID);
PlaceData = await PlaceData.json();
}
let Status = PlaceData.isActive;
const DIV = document.createElement('div')
DIV.classList = 'form-group mt-4'
DIV.innerHTML = `
const DIV = document.createElement('div');
DIV.classList = 'form-group mt-4';
DIV.innerHTML = `
<label class="mb-2">
<h5 class="mb-0">Toggle Activity</h5>
<small class="text-muted">Make your place active or inactive (currently ${(Status === true) ? 'active' : 'inactive'}).</small>
<small class="text-muted">Make your place active or inactive (currently ${Status === true ? 'active' : 'inactive'}).</small>
</label>
<br>
`
`;
Form.insertBefore(DIV, Form.children[Form.children.length-1])
Form.insertBefore(DIV, Form.children[Form.children.length - 1]);
const ActivityBtn = document.createElement('button')
ActivityBtn.type = 'button'
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success')
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate'
DIV.appendChild(ActivityBtn)
const ActivityBtn = document.createElement('button');
ActivityBtn.type = 'button';
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success');
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate';
DIV.appendChild(ActivityBtn);
ActivityBtn.addEventListener('click', function() {
fetch(`https://polytoria.com/api/places/${PlaceID}/toggle-active`, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network not ok ' + response.status)
}
return response.json()
})
.then(data => {
Status = data.isActive
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate'
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success')
})
.catch(error => {
console.log(error)
});
});
ActivityBtn.addEventListener('click', function () {
fetch(`https://polytoria.com/api/places/${PlaceID}/toggle-active`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}
})
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok ' + response.status);
}
return response.json();
})
.then((data) => {
Status = data.isActive;
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate';
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success');
})
.catch((error) => {
console.log(error);
});
});
}
function RequestGameProfile() {
const Div = document.createElement('div')
Div.classList = 'card mt-4'
Div.innerHTML = `
const Div = document.createElement('div');
Div.classList = 'card mt-4';
Div.innerHTML = `
<div class="card-body">
<input type="text" class="form-control bg-dark mb-2" placeholder="Game Title..">
<input type="color" class="form-control bg-dark mb-2" placeholder="Background Color..">
@ -73,86 +73,88 @@ function RequestGameProfile() {
<input type="color" class="form-control bg-dark mb-2" placeholder="Text Color..">
<button type="button" class="btn btn-primary">Submit Request</button>
</div>
`
Form.insertBefore(Div, Form.children[Form.children.length-1])
`;
Form.insertBefore(Div, Form.children[Form.children.length - 1]);
const SubmitBtn = Div.getElementsByTagName('button')[0]
const SubmitBtn = Div.getElementsByTagName('button')[0];
SubmitBtn.addEventListener('click', function(){
const CardBody = Div.children[0]
const Result = {
gameTitle: CardBody.children[0].value,
bg: CardBody.children[1].value,
accent: CardBody.children[2].value,
secondary: CardBody.children[3].value,
cardBg: CardBody.children[4].value,
text: CardBody.children[5].value
}
window.location.href = 'https://polyplus.vercel.app/app/game-profile.html?gameId=' + PlaceID + '&profile=' + encodeURIComponent(btoa(JSON.stringify(Result)))
});
SubmitBtn.addEventListener('click', function () {
const CardBody = Div.children[0];
const Result = {
gameTitle: CardBody.children[0].value,
bg: CardBody.children[1].value,
accent: CardBody.children[2].value,
secondary: CardBody.children[3].value,
cardBg: CardBody.children[4].value,
text: CardBody.children[5].value
};
window.location.href = 'https://polyplus.vercel.app/app/game-profile.html?gameId=' + PlaceID + '&profile=' + encodeURIComponent(btoa(JSON.stringify(Result)));
});
}
async function CopyOwnedPlace() {
console.log('ran function')
if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + 2640)
PlaceData = await PlaceData.json()
}
console.log('ran function');
if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + 2640);
PlaceData = await PlaceData.json();
}
if (PlaceData.creator.id !== parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).ID)) {
console.log('returned')
//return
}
if (PlaceData.creator.id !== parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).ID)) {
console.log('returned');
//return
}
const DIV = document.createElement('div')
DIV.classList = 'form-group mt-4'
DIV.innerHTML = `
const DIV = document.createElement('div');
DIV.classList = 'form-group mt-4';
DIV.innerHTML = `
<label class="mb-2">
<h5 class="mb-0">Download <code style="color: orange;">.poly</code> File</h5>
<small class="text-muted">Quickly download your place from the site!</small>
</label>
<br>
<button type="button" class="btn btn-primary">Download</button>
`
`;
Form.insertBefore(DIV, Form.children[Form.children.length-1])
Form.insertBefore(DIV, Form.children[Form.children.length - 1]);
const DownloadButton = DIV.getElementsByTagName('button')[0]
DownloadButton.addEventListener('click', async function() {
console.log('clicked download epic')
const DownloadButton = DIV.getElementsByTagName('button')[0];
DownloadButton.addEventListener('click', async function () {
console.log('clicked download epic');
let CreatorToken = await fetch('https://polytoria.com/api/places/edit', {
method: "POST",
headers: {
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({ placeID: PlaceID })
})
CreatorToken = await CreatorToken.json()
CreatorToken = CreatorToken.token
let CreatorToken = await fetch('https://polytoria.com/api/places/edit', {
method: 'POST',
headers: {
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
},
body: JSON.stringify({placeID: PlaceID})
});
CreatorToken = await CreatorToken.json();
CreatorToken = CreatorToken.token;
fetch(`https://api.polytoria.com/v1/places/get-place?id=${PlaceID}&tokenType=creator`, {
headers: {
'Authorization': CreatorToken
}
})
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.blob()
})
.then(data => {
//const JSONBlob = new Blob([data], {type: "application/xml"})
const DownloadURL = URL.createObjectURL(data)
fetch(`https://api.polytoria.com/v1/places/get-place?id=${PlaceID}&tokenType=creator`, {
headers: {
Authorization: CreatorToken
}
})
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.blob();
})
.then((data) => {
//const JSONBlob = new Blob([data], {type: "application/xml"})
const DownloadURL = URL.createObjectURL(data);
const Link = document.createElement('a')
Link.href = DownloadURL
Link.download = PlaceData.name + '.poly'
document.body.appendChild(Link)
Link.click()
Link.remove()
})
.catch(error => {console.log(error)});
})
const Link = document.createElement('a');
Link.href = DownloadURL;
Link.download = PlaceData.name + '.poly';
document.body.appendChild(Link);
Link.click();
Link.remove();
})
.catch((error) => {
console.log(error);
});
});
}

View file

@ -3,43 +3,47 @@
*/
!(() => {
return
const PlaceID = parseInt(window.location.pathname.split('/')[2])
return;
const PlaceID = parseInt(window.location.pathname.split('/')[2]);
fetch('https://polytoria.com/home')
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.text()
})
.then(data => {
const Parser = new DOMParser()
const Doc = Parser.parseFromString(data, 'text/html')
fetch('https://polytoria.com/home')
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.text();
})
.then((data) => {
const Parser = new DOMParser();
const Doc = Parser.parseFromString(data, 'text/html');
fetch('https://polytoria.com/api/places/join',{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Csrf-Token': Doc.querySelector('[name="_csrf"]').value
},
body: JSON.stringify({
'placeID': PlaceID
})
})
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
if (data.success !== true) {throw new Error(data.message)}
setTimeout(function(){
window.location.href = 'polytoria://client/' + data.token
window.location.href = 'https://polytoria.com/places/' + PlaceID
}, 5000)
})
.catch(error => {console.log(error)})
})
fetch('https://polytoria.com/api/places/join', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Csrf-Token': Doc.querySelector('[name="_csrf"]').value
},
body: JSON.stringify({
placeID: PlaceID
})
})
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
if (data.success !== true) {
throw new Error(data.message);
}
setTimeout(function () {
window.location.href = 'polytoria://client/' + data.token;
window.location.href = 'https://polytoria.com/places/' + PlaceID;
}, 5000);
})
.catch((error) => {
console.log(error);
});
});
})();

View file

@ -1,136 +1,138 @@
const PlaceID = window.location.pathname.split('/')[2]
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID
const GameCreator = document.querySelector('#main-content .card-body .col div.text-muted a[href^="/users/"]').getAttribute('href').split('/')[2]
const PlaceID = window.location.pathname.split('/')[2];
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const GameCreator = document.querySelector('#main-content .card-body .col div.text-muted a[href^="/users/"]').getAttribute('href').split('/')[2];
let Utilities;
var Settings;
var PinnedGamesData = []
var PinnedGamesData = [];
let GamePinned;
let InfoColumns = document.querySelectorAll('#main-content .col:has(#likes-data-container) .card:has(.fas.fa-chart-bar) ul')
let InfoColumns = document.querySelectorAll('#main-content .col:has(#likes-data-container) .card:has(.fas.fa-chart-bar) ul');
let CalculateRevenueButton;
const AchievementsTab = document.getElementById('achievements-tabpane')
const GamepassesTab = document.getElementById('gamepasses-tabpane')
const Achievements = Array.from(AchievementsTab.getElementsByClassName('card')) || []
const Gamepasses = Array.from(GamepassesTab.getElementsByClassName('card')) || []
const AchievementsTab = document.getElementById('achievements-tabpane');
const GamepassesTab = document.getElementById('gamepasses-tabpane');
const Achievements = Array.from(AchievementsTab.getElementsByClassName('card')) || [];
const Gamepasses = Array.from(GamepassesTab.getElementsByClassName('card')) || [];
!(() => {
if (PlaceID === undefined) { return }
if (PlaceID === undefined) {
return;
}
const DataContainer = document.getElementById('likes-data-container')
const RatingsData = {
Likes: parseInt(DataContainer.getAttribute('data-like-count')),
Dislikes: parseInt(DataContainer.getAttribute('data-dislike-count')),
Percentage: null
}
RatingsData.Percentage = Math.floor((RatingsData.Likes / (RatingsData.Likes + RatingsData.Dislikes)) * 100)
const RatingsContainer = document.getElementById('thumbup-btn').parentElement.parentElement
const DataContainer = document.getElementById('likes-data-container');
const RatingsData = {
Likes: parseInt(DataContainer.getAttribute('data-like-count')),
Dislikes: parseInt(DataContainer.getAttribute('data-dislike-count')),
Percentage: null
};
RatingsData.Percentage = Math.floor((RatingsData.Likes / (RatingsData.Likes + RatingsData.Dislikes)) * 100);
const RatingsContainer = document.getElementById('thumbup-btn').parentElement.parentElement;
const PercentageLabel = document.createElement('small')
PercentageLabel.classList = 'text-muted'
PercentageLabel.style.fontSize = '0.8rem'
PercentageLabel.style.marginLeft = '10px'
PercentageLabel.style.marginRight = '10px'
const PercentageLabel = document.createElement('small');
PercentageLabel.classList = 'text-muted';
PercentageLabel.style.fontSize = '0.8rem';
PercentageLabel.style.marginLeft = '10px';
PercentageLabel.style.marginRight = '10px';
if (!isNaN(RatingsData.Percentage)) {
PercentageLabel.innerText = RatingsData.Percentage + '%'
} else {
PercentageLabel.innerText = 'N/A'
}
if (!isNaN(RatingsData.Percentage)) {
PercentageLabel.innerText = RatingsData.Percentage + '%';
} else {
PercentageLabel.innerText = 'N/A';
}
RatingsContainer.children[0].appendChild(PercentageLabel)
RatingsContainer.children[0].appendChild(PercentageLabel);
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result) {
Settings = result.PolyPlus_Settings || {}
chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || {};
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
if (Settings.PinnedGamesOn === true) {
PinnedGames()
}
if (Settings.PinnedGamesOn === true) {
PinnedGames();
}
if (Settings.InlineEditingOn === true && GameCreator === UserID) {
InlineEditing()
}
if (Settings.InlineEditingOn === true && GameCreator === UserID) {
InlineEditing();
}
const Description = document.querySelector('.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small')
if (Settings.GameProfilesOn === true && Description !== null) {
const GameProfileRegex = /p\+gp;(#(?:[A-Fa-f0-9]{3}){1,2}\b(;#(?:[A-Fa-f0-9]{3}){1,2}\b)+)/gm
if (GameProfileRegex.test(Description.innerText)) {
const Info = GameProfileRegex.exec(Description.innerText)[1].split(';')
GameProfile(Info)
}
}
const Description = document.querySelector('.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small');
if (Settings.GameProfilesOn === true && Description !== null) {
const GameProfileRegex = /p\+gp;(#(?:[A-Fa-f0-9]{3}){1,2}\b(;#(?:[A-Fa-f0-9]{3}){1,2}\b)+)/gm;
if (GameProfileRegex.test(Description.innerText)) {
const Info = GameProfileRegex.exec(Description.innerText)[1].split(';');
GameProfile(Info);
}
}
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice()
}
if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice();
}
if (Settings.ShowPlaceRevenueOn === true) {
const NameRow = document.createElement('li')
NameRow.innerText = 'Revenue:'
if (Settings.ShowPlaceRevenueOn === true) {
const NameRow = document.createElement('li');
NameRow.innerText = 'Revenue:';
CalculateRevenueButton = document.createElement('li')
CalculateRevenueButton.classList = 'fw-normal text-success'
CalculateRevenueButton.style.letterSpacing = '0px'
CalculateRevenueButton.innerHTML = `
CalculateRevenueButton = document.createElement('li');
CalculateRevenueButton.classList = 'fw-normal text-success';
CalculateRevenueButton.style.letterSpacing = '0px';
CalculateRevenueButton.innerHTML = `
<a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ Calculate</a>
`
`;
InfoColumns[0].appendChild(NameRow)
InfoColumns[1].appendChild(CalculateRevenueButton)
InfoColumns[0].appendChild(NameRow);
InfoColumns[1].appendChild(CalculateRevenueButton);
let Calculating = false
CalculateRevenueButton.addEventListener('click', function() {
if (Calculating === false) {
Calculating = true
CalculateRevenueButton.innerText = '$ Calculating...'
PlaceRevenue()
}
})
}
let Calculating = false;
CalculateRevenueButton.addEventListener('click', function () {
if (Calculating === false) {
Calculating = true;
CalculateRevenueButton.innerText = '$ Calculating...';
PlaceRevenue();
}
});
}
if (AchievementsTab.getElementsByClassName('display-3')[0] === undefined) {
AchievementProgressBar()
AchievementEarnedPercentage()
if (AchievementsTab.getElementsByClassName('display-3')[0] === undefined) {
AchievementProgressBar();
AchievementEarnedPercentage();
for (let achievement of Achievements) {
if ((achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined) === false) {
achievement.style.opacity = '0.5'
}
}
}
});
})()
for (let achievement of Achievements) {
if ((achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined) === false) {
achievement.style.opacity = '0.5';
}
}
}
});
})();
async function PinnedGames() {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result){
PinnedGamesData = result.PolyPlus_PinnedGames || [];
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
const PinBtn = document.createElement('button');
PinBtn.classList = 'btn btn-warning btn-sm';
PinBtn.style = 'position: absolute; right: 0; margin-right: 7px;'
const PinBtn = document.createElement('button');
PinBtn.classList = 'btn btn-warning btn-sm';
PinBtn.style = 'position: absolute; right: 0; margin-right: 7px;';
if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin'
} else {
PinBtn.setAttribute('disabled', true)
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`
}
}
if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else {
PinBtn.setAttribute('disabled', true);
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`;
}
}
PinBtn.addEventListener('click', function() {
PinBtn.setAttribute('disabled', 'true')
PinBtn.addEventListener('click', function () {
PinBtn.setAttribute('disabled', 'true');
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
/*
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
/*
const Index = PinnedGames.indexOf(parseInt(PlaceID))
if (Index !== -1) {
//delete PinnedGames[PlaceID]
@ -142,32 +144,32 @@ async function PinnedGames() {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
}
*/
const Index = PinnedGamesData.indexOf(parseInt(PlaceID));
if (Index !== -1) {
PinnedGamesData.splice(Index, 1);
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin'
} else {
PinnedGamesData.push(parseInt(PlaceID));
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
}
const Index = PinnedGamesData.indexOf(parseInt(PlaceID));
if (Index !== -1) {
PinnedGamesData.splice(Index, 1);
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else {
PinnedGamesData.push(parseInt(PlaceID));
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
}
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': PinnedGamesData, arrayOrder: true }, function() {
setTimeout(function() {
PinBtn.removeAttribute('disabled')
console.log(PinnedGamesData)
}, 1250)
});
});
});
chrome.storage.sync.set({PolyPlus_PinnedGames: PinnedGamesData, arrayOrder: true}, function () {
setTimeout(function () {
PinBtn.removeAttribute('disabled');
console.log(PinnedGamesData);
}, 1250);
});
});
});
document.getElementsByClassName('card-header')[2].appendChild(PinBtn);
document.getElementsByClassName('card-header')[2].appendChild(PinBtn);
chrome.storage.onChanged.addListener(function(changes, namespace) {
if ('PolyPlus_PinnedGames' in changes) {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
chrome.storage.onChanged.addListener(function (changes, namespace) {
if ('PolyPlus_PinnedGames' in changes) {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || [];
/*
/*
if (PinnedGamesData[PlaceID]) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
} else {
@ -180,162 +182,160 @@ async function PinnedGames() {
}
}
*/
if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
} else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.removeAttribute('disabled')
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin'
} else {
PinBtn.setAttribute('disabled', true)
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`
}
}
});
}
});
});
if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.removeAttribute('disabled');
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else {
PinBtn.setAttribute('disabled', true);
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`;
}
}
});
}
});
});
}
async function InlineEditing() {
/*
/*
INLINE EDITING TO-DO:
- Make it possible to edit the description even if there is no description initially
- Make it possible to edit the place's genre
*/
let Editing = false
let Editing = false;
const Style = document.createElement('style')
Style.innerHTML = `
const Style = document.createElement('style');
Style.innerHTML = `
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-visible {display: block !important;}
.polyplus-inlineEditing-visible {display: none;}
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display: none !important;}
.polyplus-inlineEditing-hidden {display: block;}
`
document.body.prepend(Style)
`;
document.body.prepend(Style);
const Inputs = [
{
name: "name",
element: null,
reference: '.card-header h1[style="font-weight:800;font-size:1.6em"]',
placeholder: "Place Title..",
required: true,
isTextarea: false,
styles: 'font-weight:800;font-size:1.6em'
},
{
name: "description",
element: null,
reference: '.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small',
placeholder: "Place Description..",
required: false,
isTextarea: true,
styles: 'height:300px; overflow-y:auto;'
}
]
console.log(Inputs)
for (let input of Inputs) {
let Input = (input.isTextarea === true) ? document.createElement('textarea') : document.createElement('input')
input.element = Input
const Inputs = [
{
name: 'name',
element: null,
reference: '.card-header h1[style="font-weight:800;font-size:1.6em"]',
placeholder: 'Place Title..',
required: true,
isTextarea: false,
styles: 'font-weight:800;font-size:1.6em'
},
{
name: 'description',
element: null,
reference: '.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small',
placeholder: 'Place Description..',
required: false,
isTextarea: true,
styles: 'height:300px; overflow-y:auto;'
}
];
console.log(Inputs);
for (let input of Inputs) {
let Input = input.isTextarea === true ? document.createElement('textarea') : document.createElement('input');
input.element = Input;
const Reference = document.querySelector(input.reference)
const Reference = document.querySelector(input.reference);
Input.classList = 'polyplus-inlineEditing-visible form-control'
Input.placeholder = input.placeholder
Input.value = Reference.innerText
Input.style = input.styles
Input.classList = 'polyplus-inlineEditing-visible form-control';
Input.placeholder = input.placeholder;
Input.value = Reference.innerText;
Input.style = input.styles;
Reference.classList.add('polyplus-inlineEditing-hidden')
Reference.parentElement.appendChild(Input)
}
Reference.classList.add('polyplus-inlineEditing-hidden');
Reference.parentElement.appendChild(Input);
}
const PlaceGenre = document.getElementsByClassName('list-unstyled m-0 col')[0].children[3]
const PlaceGenre = document.getElementsByClassName('list-unstyled m-0 col')[0].children[3];
const Genres = [
"other",
"adventure",
"building",
"competitive",
"creative",
"fighting",
"funny",
"hangout",
"medieval",
"parkour",
"puzzle",
"racing",
"roleplay",
"sandbox",
"showcase",
"simulator",
"sports",
"strategy",
"survival",
"techdemo",
"trading",
"tycoon",
"western"
]
const Genres = [
'other',
'adventure',
'building',
'competitive',
'creative',
'fighting',
'funny',
'hangout',
'medieval',
'parkour',
'puzzle',
'racing',
'roleplay',
'sandbox',
'showcase',
'simulator',
'sports',
'strategy',
'survival',
'techdemo',
'trading',
'tycoon',
'western'
];
const EditBtn = document.createElement('button');
EditBtn.classList = 'btn btn-primary btn-sm';
EditBtn.style = 'position: absolute; right: 0; margin-right: 7px;'
EditBtn.innerHTML = '<i class="fa-duotone fa-hammer"></i> <span>Edit Details</span>'
document.getElementsByClassName('card-header')[3].appendChild(EditBtn);
const EditBtn = document.createElement('button');
EditBtn.classList = 'btn btn-primary btn-sm';
EditBtn.style = 'position: absolute; right: 0; margin-right: 7px;';
EditBtn.innerHTML = '<i class="fa-duotone fa-hammer"></i> <span>Edit Details</span>';
document.getElementsByClassName('card-header')[3].appendChild(EditBtn);
EditBtn.addEventListener('click', function(){
Editing = !Editing
EditBtn.addEventListener('click', function () {
Editing = !Editing;
EditBtn.children[0].classList.toggle('fa-hammer')
EditBtn.children[0].classList.toggle('fa-check-double')
EditBtn.children[0].classList.toggle('fa-fade')
EditBtn.children[0].classList.toggle('fa-hammer');
EditBtn.children[0].classList.toggle('fa-check-double');
EditBtn.children[0].classList.toggle('fa-fade');
document.body.setAttribute('data-polyplus-inlineEditing', Editing)
document.body.setAttribute('data-polyplus-inlineEditing', Editing);
if (Editing === false) {
const Send = new FormData()
Send.append("_csrf", document.querySelector('input[name="_csrf"]').value)
Send.append("id", PlaceID)
for (let input of Inputs) {
console.log('start of loop')
Send.append(input.name, input.element.value)
}
if (Editing === false) {
const Send = new FormData();
Send.append('_csrf', document.querySelector('input[name="_csrf"]').value);
Send.append('id', PlaceID);
for (let input of Inputs) {
console.log('start of loop');
Send.append(input.name, input.element.value);
}
console.log('after')
fetch('/create/place/update', {method:"POST",body:Send})
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.text()
})
.then(data => {
console.log('Successfully edited game')
for (let input of Inputs) {
const Reference = document.querySelector(input.reference)
Reference.innerText = input.element.value
}
})
.catch(error => {
alert('Error while saving changes')
console.log('Error while editing game')
});
}
});
console.log('after');
fetch('/create/place/update', {method: 'POST', body: Send})
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.text();
})
.then((data) => {
console.log('Successfully edited game');
for (let input of Inputs) {
const Reference = document.querySelector(input.reference);
Reference.innerText = input.element.value;
}
})
.catch((error) => {
alert('Error while saving changes');
console.log('Error while editing game');
});
}
});
}
async function GameProfile(data) {
document.querySelector('h1.my-0')
.setAttribute('game-key', 'true');
document.querySelector('div[style="min-height: 60vh;"]')
.id = 'gameprofile';
document.querySelector('h1.my-0').setAttribute('game-key', 'true');
document.querySelector('div[style="min-height: 60vh;"]').id = 'gameprofile';
const Style = document.createElement('style')
const Style = document.createElement('style');
Style.innerHTML = `
Style.innerHTML = `
div#app {
background: ${data[0]} !important;
}
@ -362,58 +362,58 @@ async function GameProfile(data) {
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
`
document.body.appendChild(Style)
`;
document.body.appendChild(Style);
}
async function IRLPrice() {
const Gamepasses = document.querySelector('#gamepasses-tabpane .row.flex-row').children
for (let gamepass of Gamepasses) {
const Price = gamepass.getElementsByClassName('text-success')[0]
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency)
const Gamepasses = document.querySelector('#gamepasses-tabpane .row.flex-row').children;
for (let gamepass of Gamepasses) {
const Price = gamepass.getElementsByClassName('text-success')[0];
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span')
Span.classList = 'text-muted polyplus-price-tag'
Span.style.fontSize = '0.7rem'
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")"
Price.appendChild(Span)
}
let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag';
Span.style.fontSize = '0.7rem';
Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span);
}
}
async function PlaceRevenue() {
const BricksPerView = 5
const BricksPerView = 5;
let PlaceDetails = await fetch('https://api.polytoria.com/v1/places/' + PlaceID)
PlaceDetails = await PlaceDetails.json()
let PlaceDetails = await fetch('https://api.polytoria.com/v1/places/' + PlaceID);
PlaceDetails = await PlaceDetails.json();
let CreatorDetails = await fetch('https://api.polytoria.com/v1/users/' + GameCreator)
CreatorDetails = await CreatorDetails.json()
let CreatorDetails = await fetch('https://api.polytoria.com/v1/users/' + GameCreator);
CreatorDetails = await CreatorDetails.json();
let Total = (round5(PlaceDetails.uniqueVisits) / 5)
let Revenue = (round5(PlaceDetails.uniqueVisits) / 5)
let Total = round5(PlaceDetails.uniqueVisits) / 5;
let Revenue = round5(PlaceDetails.uniqueVisits) / 5;
let CreatorTax = 0.35
switch (CreatorDetails.membershipType) {
case 'plus':
CreatorTax = 0.25
break
case 'plusDeluxe':
CreatorTax = 0.15
break
}
let CreatorTax = 0.35;
switch (CreatorDetails.membershipType) {
case 'plus':
CreatorTax = 0.25;
break;
case 'plusDeluxe':
CreatorTax = 0.15;
break;
}
let Achievements = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/achievements')
Achievements = await Achievements.json()
let Achievements = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/achievements');
Achievements = await Achievements.json();
let Gamepasses = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/gamepasses')
Gamepasses = await Gamepasses.json()
let Gamepasses = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/gamepasses');
Gamepasses = await Gamepasses.json();
for (let gamepass of Gamepasses.gamepasses) {
const PriceAfterTax = Math.floor(gamepass.asset.price - (gamepass.asset.price * CreatorTax))
Revenue += (PriceAfterTax * gamepass.asset.sales)
}
for (let gamepass of Gamepasses.gamepasses) {
const PriceAfterTax = Math.floor(gamepass.asset.price - gamepass.asset.price * CreatorTax);
Revenue += PriceAfterTax * gamepass.asset.sales;
}
/*
/*
let AchievementCost = 0
let FreeAchievements = null;
for (let achievement of Achievements.achievements) {
@ -423,84 +423,93 @@ async function PlaceRevenue() {
}
*/
const ResultText = document.createElement('li')
ResultText.classList = 'fw-normal text-success'
ResultText.style.letterSpacing = '0px'
ResultText.innerHTML = `<i class="pi pi-brick mx-1"></i> ~` + Revenue.toLocaleString()
const ResultText = document.createElement('li');
ResultText.classList = 'fw-normal text-success';
ResultText.style.letterSpacing = '0px';
ResultText.innerHTML = `<i class="pi pi-brick mx-1"></i> ~` + Revenue.toLocaleString();
CalculateRevenueButton.remove()
InfoColumns[1].appendChild(ResultText)
CalculateRevenueButton.remove();
InfoColumns[1].appendChild(ResultText);
}
function round5(number) { const remainder = number % 5; if (remainder < 2.5) { return number - remainder; } else { return number + (5 - remainder); } }
function round5(number) {
const remainder = number % 5;
if (remainder < 2.5) {
return number - remainder;
} else {
return number + (5 - remainder);
}
}
function AchievementProgressBar() {
const AchievementCount = Achievements.length
let AchievementsEarned = 0
const AchievementCount = Achievements.length;
let AchievementsEarned = 0;
for (let achievement of Achievements) {
Achieved = (achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined)
for (let achievement of Achievements) {
Achieved = achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined;
if (Achieved === true) {
AchievementsEarned++
}
}
if (Achieved === true) {
AchievementsEarned++;
}
}
const PercentageEarned = ((AchievementsEarned*100)/AchievementCount).toFixed(0)
const PercentageEarned = ((AchievementsEarned * 100) / AchievementCount).toFixed(0);
const ProgressBar = document.createElement('div')
ProgressBar.role = 'progressbar'
ProgressBar.classList = 'progress'
ProgressBar.style.background = '#000'
ProgressBar.ariaValueNow = PercentageEarned
ProgressBar.ariaValueMin = "0"
ProgressBar.ariaValueMax = "100"
ProgressBar.innerHTML = `<div class="progress-bar progress-bar-striped text-bg-warning" style="width: ${PercentageEarned}%">${PercentageEarned}%</div>`
const ProgressBar = document.createElement('div');
ProgressBar.role = 'progressbar';
ProgressBar.classList = 'progress';
ProgressBar.style.background = '#000';
ProgressBar.ariaValueNow = PercentageEarned;
ProgressBar.ariaValueMin = '0';
ProgressBar.ariaValueMax = '100';
ProgressBar.innerHTML = `<div class="progress-bar progress-bar-striped text-bg-warning" style="width: ${PercentageEarned}%">${PercentageEarned}%</div>`;
AchievementsTab.prepend(document.createElement('hr'))
AchievementsTab.prepend(ProgressBar)
AchievementsTab.prepend(document.createElement('hr'));
AchievementsTab.prepend(ProgressBar);
}
function AchievementEarnedPercentage() {
fetch('https://api.polytoria.com/v1/places/' + PlaceID)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
const UserCount = data.uniqueVisits
for (let achievement of Achievements) {
const OwnerText = achievement.getElementsByClassName('text-muted small my-0')[0]
// thanks to Stackoverflow on how to remove everything except numbers from string
const OwnerCount = parseInt(OwnerText.innerText.replace(/[^0-9]/g, ''))
const PercentageOfPlayers = ((OwnerCount*100)/UserCount).toFixed(2)
fetch('https://api.polytoria.com/v1/places/' + PlaceID)
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
const UserCount = data.uniqueVisits;
for (let achievement of Achievements) {
const OwnerText = achievement.getElementsByClassName('text-muted small my-0')[0];
// thanks to Stackoverflow on how to remove everything except numbers from string
const OwnerCount = parseInt(OwnerText.innerText.replace(/[^0-9]/g, ''));
const PercentageOfPlayers = ((OwnerCount * 100) / UserCount).toFixed(2);
OwnerText.innerHTML += " (" + PercentageOfPlayers + "%, " + GetAchievementDifficulty(PercentageOfPlayers) + ")"
}
})
.catch(error => {console.log(error)});
OwnerText.innerHTML += ' (' + PercentageOfPlayers + '%, ' + GetAchievementDifficulty(PercentageOfPlayers) + ')';
}
})
.catch((error) => {
console.log(error);
});
}
function GetAchievementDifficulty(percent) {
if (percent >= 90 && percent <= 100) {
return 'Freebie'
} else if (percent >= 80 && percent <= 89.9) {
return 'Cake Walk'
} else if (percent >= 50 && percent <= 79.9) {
return 'Easy'
} else if (percent >= 30 && percent <= 49.9) {
return 'Moderate'
} else if (percent >= 20 && percent <= 29.9) {
return 'Challenging'
} else if (percent >= 10 && percent <= 19.9) {
return 'Hard'
} else if (percent >= 5 && percent <= 9.9) {
return 'Extreme'
} else if (percent >= 1 && percent <= 4.9) {
return 'Insane'
} else if (percent >= 0 && percent <= 0.9) {
return 'Impossible'
}
if (percent >= 90 && percent <= 100) {
return 'Freebie';
} else if (percent >= 80 && percent <= 89.9) {
return 'Cake Walk';
} else if (percent >= 50 && percent <= 79.9) {
return 'Easy';
} else if (percent >= 30 && percent <= 49.9) {
return 'Moderate';
} else if (percent >= 20 && percent <= 29.9) {
return 'Challenging';
} else if (percent >= 10 && percent <= 19.9) {
return 'Hard';
} else if (percent >= 5 && percent <= 9.9) {
return 'Extreme';
} else if (percent >= 1 && percent <= 4.9) {
return 'Insane';
} else if (percent >= 0 && percent <= 0.9) {
return 'Impossible';
}
}

View file

@ -6,25 +6,28 @@
let Settings;
let PinnedGamesData;
chrome.storage.sync.get(['PolyPlus_Settings', 'PolyPlus_PinnedGames'], function(result){
Settings = result.PolyPlus_Settings || {}
PinnedGamesData = result.PolyPlus_PinnedGames || []
chrome.storage.sync.get(['PolyPlus_Settings', 'PolyPlus_PinnedGames'], function (result) {
Settings = result.PolyPlus_Settings || {};
PinnedGamesData = result.PolyPlus_PinnedGames || [];
if (Settings.PinnedGamesOn === true) {}
})
if (Settings.PinnedGamesOn === true) {
}
});
function PinnedGames() {
for (let game of PinnedGamesData) {
fetch('https://api.polytoria.com/v1/places/' + game)
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
// epic
})
.catch(error => {console.log(error)})
}
for (let game of PinnedGamesData) {
fetch('https://api.polytoria.com/v1/places/' + game)
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
// epic
})
.catch((error) => {
console.log(error);
});
}
}

View file

@ -1,18 +1,18 @@
const SettingsURL = chrome.runtime.getURL('settings.html')
const InExtensionSettings = (window.location.pathname.split('/')[3] === "polyplus" && window.location.hash !== "#dev")
const SettingsURL = chrome.runtime.getURL('settings.html');
const InExtensionSettings = window.location.pathname.split('/')[3] === 'polyplus' && window.location.hash !== '#dev';
if (InExtensionSettings === true) {
window.location.href = SettingsURL + window.location.hash
window.location.href = SettingsURL + window.location.hash;
}
document.addEventListener('DOMContentLoaded', function(){
const Nav = document.getElementsByClassName('nav nav-pills')[0]
document.addEventListener('DOMContentLoaded', function () {
const Nav = document.getElementsByClassName('nav nav-pills')[0];
const PolyPlusItem = document.createElement('a')
PolyPlusItem.classList = 'nav-link'
PolyPlusItem.href = SettingsURL
PolyPlusItem.innerHTML = `
const PolyPlusItem = document.createElement('a');
PolyPlusItem.classList = 'nav-link';
PolyPlusItem.href = SettingsURL;
PolyPlusItem.innerHTML = `
<i class="fa-regular fa-sparkles me-1"></i> <span class="pilltitle">Poly+</span>
`
`;
Nav.insertBefore(PolyPlusItem, Nav.getElementsByTagName('hr')[0])
Nav.insertBefore(PolyPlusItem, Nav.getElementsByTagName('hr')[0]);
});

View file

@ -2,28 +2,28 @@ var Settings;
let Theme = ``;
(async () => {
let Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
let Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
chrome.storage.sync.get(["PolyPlus_Settings"], function(result) {
// Merge settings and expected settings to make sure all keys exist
const RawSettings = result.PolyPlus_Settings
Settings = MergeObjects(RawSettings || Utilities.DefaultSettings, Utilities.DefaultSettings);
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
// Merge settings and expected settings to make sure all keys exist
const RawSettings = result.PolyPlus_Settings;
Settings = MergeObjects(RawSettings || Utilities.DefaultSettings, Utilities.DefaultSettings);
// If theme exists, create a style element to represent it
if (Settings.ThemeCreator.Enabled && Settings.ThemeCreator.Enabled === true) {
switch (Settings.ThemeCreator.BGImageSize) {
case 0:
Settings.ThemeCreator.BGImageSize = 'fit'
break
case 1:
Settings.ThemeCreator.BGImageSize = 'cover'
break
case 2:
Settings.ThemeCreator.BGImageSize = 'contain'
break
}
Theme += `
// If theme exists, create a style element to represent it
if (Settings.ThemeCreator.Enabled && Settings.ThemeCreator.Enabled === true) {
switch (Settings.ThemeCreator.BGImageSize) {
case 0:
Settings.ThemeCreator.BGImageSize = 'fit';
break;
case 1:
Settings.ThemeCreator.BGImageSize = 'cover';
break;
case 2:
Settings.ThemeCreator.BGImageSize = 'contain';
break;
}
Theme += `
:root {
--polyplus-navbgcolor: ${Settings.ThemeCreator.NavBGColor};
--polyplus-navbordercolor: ${Settings.ThemeCreator.NavBorderColor};
@ -109,99 +109,101 @@ let Theme = ``;
.nav-sidebar-text {
color: var(--polyplus-sidebaritemlabelcolor) !important;
}
`
}
});
`;
}
});
if (Settings.HideUserAds.Enabled === true) {
if (Settings.HideUserAds.Banners === true) {
Theme += `
if (Settings.HideUserAds.Enabled === true) {
if (Settings.HideUserAds.Banners === true) {
Theme += `
div[style^="max-width: 728px;"]:has(a[href^="/ads"]) {
display: none;
}
`
}
`;
}
if (Settings.HideUserAds.Rectangles === true) {
Theme += `
if (Settings.HideUserAds.Rectangles === true) {
Theme += `
div[style^="max-width: 300px;"]:has(a[href^="/ads"]) {
display: none;
}
`
}
}
`;
}
}
if (Settings.HideNotifBadgesOn === true) {
Theme += `
if (Settings.HideNotifBadgesOn === true) {
Theme += `
.notif-nav .notif-sidebar {
display: none;
}
`
}
`;
}
// Credit to @SK-Fast (also known as DevPixels) for the improved loading code (taken from his original Poly+, and reformatted to Index Poly+)
const ThemeBlob = new Blob([Theme], { type: 'text/css' })
const ThemeURL = URL.createObjectURL(ThemeBlob)
document.head.innerHTML += `<link href="${ThemeURL}" rel="stylesheet" type="text/css">`
// Credit to @SK-Fast (also known as DevPixels) for the improved loading code (taken from his original Poly+, and reformatted to Index Poly+)
const ThemeBlob = new Blob([Theme], {type: 'text/css'});
const ThemeURL = URL.createObjectURL(ThemeBlob);
document.head.innerHTML += `<link href="${ThemeURL}" rel="stylesheet" type="text/css">`;
document.addEventListener('DOMContentLoaded', async function() {
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return
}
document.addEventListener('DOMContentLoaded', async function () {
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return;
}
Utilities.InjectResource('getUserDetails')
document.body.setAttribute('data-URL', window.location.pathname)
Utilities.InjectResource('getUserDetails');
document.body.setAttribute('data-URL', window.location.pathname);
const UserData = JSON.parse(window.localStorage.getItem('p+account_info'))
const UserData = JSON.parse(window.localStorage.getItem('p+account_info'));
if (Settings.IRLPriceWithCurrency.Enabled === true) {
const IRLResult = await Utilities.CalculateIRL(document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g,''), Settings.IRLPriceWithCurrency.Currency)
// Desktop
document.querySelector('.text-success .brickBalanceCount').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`
if (Settings.IRLPriceWithCurrency.Enabled === true) {
const IRLResult = await Utilities.CalculateIRL(document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g, ''), Settings.IRLPriceWithCurrency.Currency);
// Desktop
document.querySelector('.text-success .brickBalanceCount').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`;
// Mobile
document.querySelector('.text-success .brickBalanceCont').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`
//document.querySelector('.text-success .brickBalanceCont').innerHTML += `<div class="text-muted" style="font-size: 0.6rem;text-align: right;">(${IRLResult.icon}${IRLResult.result} ${IRLResult.display})</div>`
}
// Mobile
document.querySelector('.text-success .brickBalanceCont').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`;
//document.querySelector('.text-success .brickBalanceCont').innerHTML += `<div class="text-muted" style="font-size: 0.6rem;text-align: right;">(${IRLResult.icon}${IRLResult.result} ${IRLResult.display})</div>`
}
if (Settings.ModifyNavOn && Settings.ModifyNavOn === true) {
let NavbarItems = document.querySelectorAll('.navbar-nav.me-auto a.nav-link[href]')
let Needed = [NavbarItems[11],NavbarItems[12],NavbarItems[13],NavbarItems[14],NavbarItems[15]]
for (let i = 0; i < Settings.ModifyNav.length; i++) {
if (Settings.ModifyNav[i].Label != null) {
console.log(Needed[i], Needed[i].children[1])
Needed[i].children[1].innerText = Settings.ModifyNav[i].Label
Needed[i].href = Settings.ModifyNav[i].Link
}
}
}
if (Settings.ModifyNavOn && Settings.ModifyNavOn === true) {
let NavbarItems = document.querySelectorAll('.navbar-nav.me-auto a.nav-link[href]');
let Needed = [NavbarItems[11], NavbarItems[12], NavbarItems[13], NavbarItems[14], NavbarItems[15]];
for (let i = 0; i < Settings.ModifyNav.length; i++) {
if (Settings.ModifyNav[i].Label != null) {
console.log(Needed[i], Needed[i].children[1]);
Needed[i].children[1].innerText = Settings.ModifyNav[i].Label;
Needed[i].href = Settings.ModifyNav[i].Link;
}
}
}
/*
/*
if (Settings.HideUserAdsOn === true) {
Array.from(document.querySelectorAll('.text-center:has(a[href^="/ads"])')).forEach(ad => {ad.remove()})
}
*/
if (Settings.HideNotifBadgesOn === true) {
document.getElementsByClassName('notif-nav notif-sidebar').forEach(element => {element.remove();});
}
});
if (Settings.HideNotifBadgesOn === true) {
document.getElementsByClassName('notif-nav notif-sidebar').forEach((element) => {
element.remove();
});
}
});
})();
function MergeObjects(obj1, obj2) {
var mergedObj = {};
var mergedObj = {};
// Copy the values from obj1 to the mergedObj
for (var key in obj1) {
mergedObj[key] = obj1[key];
}
// Copy the values from obj1 to the mergedObj
for (var key in obj1) {
mergedObj[key] = obj1[key];
}
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key];
}
}
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key];
}
}
return mergedObj;
return mergedObj;
}

File diff suppressed because it is too large Load diff

View file

@ -1,174 +1,184 @@
const ItemID = window.location.pathname.split('/')[2]
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID
const ItemGrid = document.getElementById('assets')
const Categories = document.getElementById('store-categories').children[0]
const ItemID = window.location.pathname.split('/')[2];
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const ItemGrid = document.getElementById('assets');
const Categories = document.getElementById('store-categories').children[0];
var Settings;
var Inventory = null;
var Utilities;
let EventItemsShown = false
let EventItemsShown = false;
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result){
Settings = result.PolyPlus_Settings || {};
chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || {};
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
if (Settings.IRLPriceWithCurrency.Enabled === true) {
Array.from(ItemGrid.children).forEach(element => {
LoadIRLPrices(element)
});
}
if (Settings.IRLPriceWithCurrency.Enabled === true) {
Array.from(ItemGrid.children).forEach((element) => {
LoadIRLPrices(element);
});
}
if (Settings.StoreOwnTagOn === true) {
Inventory = (await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=hat&limit=100')).json()).inventory
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=face&limit=100')).json()).inventory
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=tool&limit=100')).json()).inventory
console.log(Inventory)
Array.from(ItemGrid.children).forEach(element => {
LoadOwnedTags(element)
});
}
if (Settings.StoreOwnTagOn === true) {
Inventory = (await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=hat&limit=100')).json()).inventory;
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=face&limit=100')).json()).inventory;
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=tool&limit=100')).json()).inventory;
console.log(Inventory);
Array.from(ItemGrid.children).forEach((element) => {
LoadOwnedTags(element);
});
}
if (Settings.EventItemsCatOn === true) {
EventItems()
}
if (Settings.EventItemsCatOn === true) {
EventItems();
}
});
const observer = new MutationObserver(async function (list){
if (Settings.EventItemsCatOn === true) {
if (document.getElementById('event-items-pagination') === null) {
ItemGrid.classList.add('itemgrid')
ItemGrid.parentElement.classList.remove('col-lg-9')
document.getElementById('pagination').style.display = 'block'
if (document.getElementById('storecat-eventitems') !== null) {
document.getElementById('storecat-eventitems').checked = false
}
} else {
ItemGrid.classList.remove('itemgrid')
ItemGrid.parentElement.classList.add('col-lg-9')
document.getElementById('pagination').style.display = 'none'
}
}
for (const record of list) {
for (const element of record.addedNodes) {
if (element.tagName === "DIV" && element.classList.value === 'mb-3 itemCardCont') {
if (Settings.IRLPriceWithCurrency.Enabled === true) {
LoadIRLPrices(element)
}
const observer = new MutationObserver(async function (list) {
if (Settings.EventItemsCatOn === true) {
if (document.getElementById('event-items-pagination') === null) {
ItemGrid.classList.add('itemgrid');
ItemGrid.parentElement.classList.remove('col-lg-9');
document.getElementById('pagination').style.display = 'block';
if (document.getElementById('storecat-eventitems') !== null) {
document.getElementById('storecat-eventitems').checked = false;
}
} else {
ItemGrid.classList.remove('itemgrid');
ItemGrid.parentElement.classList.add('col-lg-9');
document.getElementById('pagination').style.display = 'none';
}
}
for (const record of list) {
for (const element of record.addedNodes) {
if (element.tagName === 'DIV' && element.classList.value === 'mb-3 itemCardCont') {
if (Settings.IRLPriceWithCurrency.Enabled === true) {
LoadIRLPrices(element);
}
if (Settings.StoreOwnTagOn === true && Inventory !== null) {
LoadOwnedTags(element)
}
}
}
observer.observe(ItemGrid, {attributes: false,childList: true,subtree: false});
}
if (Settings.StoreOwnTagOn === true && Inventory !== null) {
LoadOwnedTags(element);
}
}
}
observer.observe(ItemGrid, {attributes: false, childList: true, subtree: false});
}
});
observer.observe(ItemGrid, {attributes: false,childList: true,subtree: false});
observer.observe(ItemGrid, {attributes: false, childList: true, subtree: false});
async function LoadIRLPrices(element) {
if (element.tagName != "DIV" || element.querySelector('small.text-primary')) {return}
const Parent = element.getElementsByTagName('small')[1]
if (Parent.innerText !== "") {
const Span = document.createElement('span')
Span.classList = 'text-muted polyplus-price-tag'
Span.style = 'font-size: 0.7rem; font-weight: lighter;'
const Price = Parent.innerText.split(' ')[1]
const IRLResult = await Utilities.CalculateIRL(Price, Settings.IRLPriceWithCurrency.Currency)
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")"
Parent.appendChild(Span)
}
if (element.tagName != 'DIV' || element.querySelector('small.text-primary')) {
return;
}
const Parent = element.getElementsByTagName('small')[1];
if (Parent.innerText !== '') {
const Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag';
Span.style = 'font-size: 0.7rem; font-weight: lighter;';
const Price = Parent.innerText.split(' ')[1];
const IRLResult = await Utilities.CalculateIRL(Price, Settings.IRLPriceWithCurrency.Currency);
Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Parent.appendChild(Span);
}
}
function LoadOwnedTags(element) {
let Item = CheckInventory(parseInt(element.querySelector('[href^="/store/"]').getAttribute('href').split('/')[2]))
if (Item !== null) {
const Tag = document.createElement('span')
Tag.classList = `badge ${ (Item.asset.isLimited === false) ? 'bg-primary' : 'bg-warning' } polyplus-own-tag`
Tag.style = 'position: absolute;font-size: 0.9rem;top: 0px;left: 0px;padding: 5.5px;border-top-left-radius: var(--bs-border-radius-lg)!important;border-top-right-radius: 0px;border-bottom-left-radius: 0px;font-size: 0.65rem;'
Tag.innerHTML = "<i class='fas fa-star'></i>"
element.getElementsByTagName('img')[0].parentElement.appendChild(Tag)
if (Item.asset.isLimited === true) {
Tag.setAttribute('data-bs-toggle', 'tooltip')
Tag.setAttribute('data-bs-title', '#' + Item.serial)
let Item = CheckInventory(parseInt(element.querySelector('[href^="/store/"]').getAttribute('href').split('/')[2]));
if (Item !== null) {
const Tag = document.createElement('span');
Tag.classList = `badge ${Item.asset.isLimited === false ? 'bg-primary' : 'bg-warning'} polyplus-own-tag`;
Tag.style =
'position: absolute;font-size: 0.9rem;top: 0px;left: 0px;padding: 5.5px;border-top-left-radius: var(--bs-border-radius-lg)!important;border-top-right-radius: 0px;border-bottom-left-radius: 0px;font-size: 0.65rem;';
Tag.innerHTML = "<i class='fas fa-star'></i>";
element.getElementsByTagName('img')[0].parentElement.appendChild(Tag);
if (Item.asset.isLimited === true) {
Tag.setAttribute('data-bs-toggle', 'tooltip');
Tag.setAttribute('data-bs-title', '#' + Item.serial);
Utilities.InjectResource('registerTooltips')
}
}
Utilities.InjectResource('registerTooltips');
}
}
}
function CheckInventory(id) {
let Item = null
Inventory.forEach(element => {
if (element.asset.id === id) {
Item = element
}
})
return Item
let Item = null;
Inventory.forEach((element) => {
if (element.asset.id === id) {
Item = element;
}
});
return Item;
}
function EventItems() {
const Selector = document.createElement('div')
Selector.classList = 'form-check store-category-check fw-bold'
Selector.style.borderColor = '#B008B0'
Selector.innerHTML = `
const Selector = document.createElement('div');
Selector.classList = 'form-check store-category-check fw-bold';
Selector.style.borderColor = '#B008B0';
Selector.innerHTML = `
<input class="form-check-input" type="radio" name="storecat" id="storecat-eventitems">
<label class="form-check-label" for="storecat-eventitems">
<i class="fad fa-party-horn"></i> Event Items
</label>
`
`;
Categories.appendChild(Selector)
Categories.appendChild(Selector);
let EventData = null
let Events = []
let Groups = []
let Page = 0
let EventData = null;
let Events = [];
let Groups = [];
let Page = 0;
Selector.children[0].addEventListener('click', async function() {
Array.from(Categories.children).forEach(selector => {
selector.classList.remove('active')
})
Selector.classList.add('active')
if (EventData === null) {
EventData = await (await fetch('https://polyplus.vercel.app/data/eventItems.json')).json()
Selector.children[0].addEventListener('click', async function () {
Array.from(Categories.children).forEach((selector) => {
selector.classList.remove('active');
});
Selector.classList.add('active');
if (EventData === null) {
EventData = await (await fetch('https://polyplus.vercel.app/data/eventItems.json')).json();
Object.values(EventData.eventDetails).forEach((x, index) => {Events.push({
...x,
items: EventData.items.filter((x) => x.event === Object.keys(EventData.eventDetails)[index]).sort((a, b) => a.id - b.id)
})})
while (Events.length > 0) {
Groups.push(Events.splice(0, 5))
}
}
Object.values(EventData.eventDetails).forEach((x, index) => {
Events.push({
...x,
items: EventData.items.filter((x) => x.event === Object.keys(EventData.eventDetails)[index]).sort((a, b) => a.id - b.id)
});
});
while (Events.length > 0) {
Groups.push(Events.splice(0, 5));
}
}
ItemGrid.classList.remove('itemgrid')
ItemGrid.innerHTML = `
ItemGrid.classList.remove('itemgrid');
ItemGrid.innerHTML = `
<div id="p+ei">
${
Groups[Page].map((x, index) => `
${Groups[Page].map(
(x, index) => `
<div class="row px-2 px-lg-0" style="animation-delay: 0.24s;">
<div class="col">
<h6 class="dash-ctitle2">${x.date}</h6>
<h5 class="dash-ctitle">${x.name}</h5>
</div>
${ (x.link !== undefined) ? `
${
x.link !== undefined
? `
<div class="col-auto d-flex align-items-center">
<a class="text-muted" href="${x.link}">
<span class="d-none d-lg-inline">${ (x.link.startsWith('https://polytoria.com/places/')) ? 'Event Place' : 'Blog Post' }</span>
<span class="d-none d-lg-inline">${x.link.startsWith('https://polytoria.com/places/') ? 'Event Place' : 'Blog Post'}</span>
<i class="fas fa-angle-right ms-2"></i>
</a>
</div>
` : '' }
`
: ''
}
</div>
<div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;">
<div class="card-body p-0 m-1 scrollFadeContainer">
<div class="d-flex">
${
x.items.map((x) => `
${x.items
.map(
(x) => `
<a href="/store/${x.id}">
<div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;">
<div class="card-body">
@ -181,13 +191,14 @@ function EventItems() {
</div>
</div>
</a>
`).join('')
}
`
)
.join('')}
</div>
</div>
</div>
`).join('')
}
`
).join('')}
</div>
<div class="d-flex justify-content-center mt-3">
@ -214,62 +225,63 @@ function EventItems() {
</ul>
</nav>
</div>
`
`;
const Container = document.getElementById('p+ei')
const Pagination = document.getElementById('event-items-pagination')
const First = document.getElementById('p+ei-pagination-first')
const Prev = document.getElementById('p+ei-pagination-prev')
const Current = document.getElementById('p+ei-pagination-current')
const Next = document.getElementById('p+ei-pagination-next')
const Last = document.getElementById('p+ei-pagination-last')
const Container = document.getElementById('p+ei');
const Pagination = document.getElementById('event-items-pagination');
const First = document.getElementById('p+ei-pagination-first');
const Prev = document.getElementById('p+ei-pagination-prev');
const Current = document.getElementById('p+ei-pagination-current');
const Next = document.getElementById('p+ei-pagination-next');
const Last = document.getElementById('p+ei-pagination-last');
if (Page > 0) {
Prev.parentElement.classList.remove('disabled')
First.parentElement.classList.remove('disabled')
} else {
Prev.parentElement.classList.add('disabled')
First.parentElement.classList.add('disabled')
}
if (Page < Groups.length-1) {
Next.parentElement.classList.remove('disabled')
Last.parentElement.classList.remove('disabled')
} else {
Next.parentElement.classList.add('disabled')
Last.parentElement.classList.add('disabled')
}
if (Page > 0) {
Prev.parentElement.classList.remove('disabled');
First.parentElement.classList.remove('disabled');
} else {
Prev.parentElement.classList.add('disabled');
First.parentElement.classList.add('disabled');
}
if (Page < Groups.length - 1) {
Next.parentElement.classList.remove('disabled');
Last.parentElement.classList.remove('disabled');
} else {
Next.parentElement.classList.add('disabled');
Last.parentElement.classList.add('disabled');
}
First.addEventListener('click', function() {
if (Page > 0) {
Page = 0
UpdateEventItems()
}
})
First.addEventListener('click', function () {
if (Page > 0) {
Page = 0;
UpdateEventItems();
}
});
Prev.addEventListener('click', function() {
if (Page > 0) {
Page--
UpdateEventItems()
}
})
Prev.addEventListener('click', function () {
if (Page > 0) {
Page--;
UpdateEventItems();
}
});
Next.addEventListener('click', function() {
if (Page < Groups.length-1) {
Page++
UpdateEventItems()
}
})
Next.addEventListener('click', function () {
if (Page < Groups.length - 1) {
Page++;
UpdateEventItems();
}
});
Last.addEventListener('click', function() {
if (Page < Groups.length-1) {
Page = Groups.length-1
UpdateEventItems()
}
})
Last.addEventListener('click', function () {
if (Page < Groups.length - 1) {
Page = Groups.length - 1;
UpdateEventItems();
}
});
const UpdateEventItems = function() {
Current.innerText = Page+1
Container.innerHTML = Groups[Page].map((x, index) => `
const UpdateEventItems = function () {
Current.innerText = Page + 1;
Container.innerHTML = Groups[Page].map(
(x, index) => `
<div class="row px-2 px-lg-0" style="animation-delay: 0.24s;">
<div class="col">
<h6 class="dash-ctitle2">${x.date}</h6>
@ -279,8 +291,9 @@ function EventItems() {
<div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;">
<div class="card-body p-0 m-1 scrollFadeContainer">
<div class="d-flex">
${
x.items.map((x) => `
${x.items
.map(
(x) => `
<a href="/store/${x.id}">
<div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;">
<div class="card-body">
@ -293,28 +306,30 @@ function EventItems() {
</div>
</div>
</a>
`).join('')
}
`
)
.join('')}
</div>
</div>
</div>
</div>
`).join('')
`
).join('');
if (Page > 0) {
Prev.parentElement.classList.remove('disabled')
First.parentElement.classList.remove('disabled')
} else {
Prev.parentElement.classList.add('disabled')
First.parentElement.classList.add('disabled')
}
if (Page < Groups.length-1) {
Next.parentElement.classList.remove('disabled')
Last.parentElement.classList.remove('disabled')
} else {
Next.parentElement.classList.add('disabled')
Last.parentElement.classList.add('disabled')
}
}
})
if (Page > 0) {
Prev.parentElement.classList.remove('disabled');
First.parentElement.classList.remove('disabled');
} else {
Prev.parentElement.classList.add('disabled');
First.parentElement.classList.add('disabled');
}
if (Page < Groups.length - 1) {
Next.parentElement.classList.remove('disabled');
Last.parentElement.classList.remove('disabled');
} else {
Next.parentElement.classList.add('disabled');
Last.parentElement.classList.add('disabled');
}
};
});
}

View file

@ -1,150 +1,148 @@
{
"manifest_version": 3,
"author": "Index",
"name": "Poly+",
"version": "1.11",
"version_name": "Pre-Release Build (v1.1.1)",
"description": "Power-up your Polytoria experience with Poly+! Created by Index.",
"homepage_url": "https://polyplus.vercel.app/",
"permissions": ["storage", "contextMenus", "tabs", "scripting", "alarms", "notifications"],
"content_scripts": [
{
"matches": ["https://polytoria.com/*"],
"js": ["/js/sitewide.js","/js/membership-themes.js"],
"css": ["/css/specific.css"],
"run_at": "document_start"
},
"manifest_version": 3,
"author": "Index",
"name": "Poly+",
"version": "1.11",
"version_name": "Pre-Release Build (v1.1.1)",
"description": "Power-up your Polytoria experience with Poly+! Created by Index.",
"homepage_url": "https://polyplus.vercel.app/",
"permissions": ["storage", "contextMenus", "tabs", "scripting", "alarms", "notifications"],
"content_scripts": [
{
"matches": ["https://polytoria.com/*"],
"js": ["/js/sitewide.js", "/js/membership-themes.js"],
"css": ["/css/specific.css"],
"run_at": "document_start"
},
{
"matches": ["https://polytoria.com/my/settings/*"],
"js": ["/js/settings.js", "/js/debug.js"],
"run_at": "document_start"
},
{
"matches": ["https://polytoria.com/my/settings/*"],
"js": ["/js/settings.js", "/js/debug.js"],
"run_at": "document_start"
},
{
"matches": ["https://polytoria.com/", "https://polytoria.com/home"],
"js": ["/js/account/home.js"],
"run_at": "document_idle"
},
{
"matches": ["https://polytoria.com/", "https://polytoria.com/home"],
"js": ["/js/account/home.js"],
"run_at": "document_idle"
},
{
"matches": ["https://polytoria.com/places/**"],
"js": ["/js/places/place-view.js"]
},
{
"matches": ["https://polytoria.com/places/**"],
"js": ["/js/places/place-view.js"]
},
{
"matches": ["https://polytoria.com/create/place/**"],
"js": ["/js/places/place-edit.js"]
},
{
"matches": ["https://polytoria.com/create/place/**"],
"js": ["/js/places/place-edit.js"]
},
{
"matches": ["https://polytoria.com/forum/post/**"],
"js": ["/js/forum/forum-view.js"]
},
{
"matches": ["https://polytoria.com/forum/post/**"],
"js": ["/js/forum/forum-view.js"]
},
{
"matches": ["https://polytoria.com/u/**", "https://polytoria.com/users/**"],
"js": ["/js/account/profile.js", "/js/account/inventory.js"]
},
{
"matches": ["https://polytoria.com/u/**", "https://polytoria.com/users/**"],
"js": ["/js/account/profile.js", "/js/account/inventory.js"]
},
{
"matches": ["https://polytoria.com/my/friends", "https://polytoria.com/my/friends/"],
"js": ["/js/account/friends.js"]
},
{
"matches": ["https://polytoria.com/my/friends", "https://polytoria.com/my/friends/"],
"js": ["/js/account/friends.js"]
},
{
"matches": ["https://polytoria.com/store", "https://polytoria.com/store/"],
"js": ["/js/store/store.js"]
},
{
"matches": ["https://polytoria.com/store", "https://polytoria.com/store/"],
"js": ["/js/store/store.js"]
},
{
"matches": ["https://polytoria.com/store/**"],
"js": ["/js/store/item-view.js"]
},
{
"matches": ["https://polytoria.com/store/**"],
"js": ["/js/store/item-view.js"]
},
{
"matches": ["https://polytoria.com/forum/search","https://polytoria.com/forum/search?*"],
"js": ["/js/forum/forum-search.js"]
},
{
"matches": ["https://polytoria.com/forum/search", "https://polytoria.com/forum/search?*"],
"js": ["/js/forum/forum-search.js"]
},
{
"matches": ["https://polytoria.com/trade/sent/*"],
"js": ["/js/account/trades-outbound.js"]
},
{
"matches": ["https://polytoria.com/trade/sent/*"],
"js": ["/js/account/trades-outbound.js"]
},
{
"matches": ["https://polytoria.com/u/*/inventory/"],
"js": ["/js/account/inventory.js"],
"run_at": "document_idle"
},
{
"matches": ["https://polytoria.com/u/*/inventory/"],
"js": ["/js/account/inventory.js"],
"run_at": "document_idle"
},
{
"matches": ["https://polytoria.com/my/settings/privacy"],
"js": ["/js/account/settings-privacy.js"]
},
{
"matches": ["https://polytoria.com/my/settings/privacy"],
"js": ["/js/account/settings-privacy.js"]
},
{
"matches": ["https://polytoria.com/my/settings/transactions*"],
"js": ["/js/account/transactions.js"]
},
{
"matches": ["https://polytoria.com/my/settings/transactions*"],
"js": ["/js/account/transactions.js"]
},
{
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/places/**", "https://polytoria.com/guilds/**", "https://polytoria.com/feed/**"],
"js": ["/js/op-comments.js"]
},
{
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/places/**", "https://polytoria.com/guilds/**", "https://polytoria.com/feed/**"],
"js": ["/js/op-comments.js"]
},
{
"matches": ["https://polytoria.com/my/avatar*"],
"js": ["/js/account/avatar-sandbox2.js"]
},
{
"matches": ["https://polytoria.com/my/avatar*"],
"js": ["/js/account/avatar-sandbox2.js"]
},
{
"matches": ["https://polytoria.com/inbox*"],
"js": ["/js/account/inbox.js"]
},
{
"matches": ["https://polytoria.com/inbox*"],
"js": ["/js/account/inbox.js"]
},
{
"matches": ["https://polytoria.com/guilds/**"],
"js": ["/js/guilds.js"]
},
{
"matches": ["https://polytoria.com/guilds/**"],
"js": ["/js/guilds.js"]
},
{
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/models/**"],
"js": ["/js/library-download.js"]
}
],
"background": {
"service_worker": "/js/background.js",
"type": "module"
},
"host_permissions": [
"https://*.polytoria.com/*"
],
"web_accessible_resources": [
{
"resources": ["resources/*"],
"matches": ["https://polytoria.com/*"]
},
{
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/models/**"],
"js": ["/js/library-download.js"]
}
],
"background": {
"service_worker": "/js/background.js",
"type": "module"
},
"host_permissions": ["https://*.polytoria.com/*"],
"web_accessible_resources": [
{
"resources": ["resources/*"],
"matches": ["https://polytoria.com/*"]
},
{
"resources": ["settings.html", "settings.js"],
"matches": ["https://polytoria.com/*"]
}
],
"short_name": "Poly+",
"action": {
"default_title": "Poly+",
"default_icon": {
"16": "/icons/icon.png",
"32": "/icons/icon.png",
"48": "/icons/icon.png",
"128": "/icons/icon.png"
}
},
"icons": {
"16": "/icons/icon.png",
"32": "/icons/icon.png",
"48": "/icons/icon.png",
"128": "/icons/icon.png"
}
{
"resources": ["settings.html", "settings.js"],
"matches": ["https://polytoria.com/*"]
}
],
"short_name": "Poly+",
"action": {
"default_title": "Poly+",
"default_icon": {
"16": "/icons/icon.png",
"32": "/icons/icon.png",
"48": "/icons/icon.png",
"128": "/icons/icon.png"
}
},
"icons": {
"16": "/icons/icon.png",
"32": "/icons/icon.png",
"48": "/icons/icon.png",
"128": "/icons/icon.png"
}
}

37
package-lock.json generated Normal file
View file

@ -0,0 +1,37 @@
{
"name": "PolyPlus",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"devDependencies": {
"prettier": "^3.2.5",
"prettier-plugin-jinja-template": "^1.4.0"
}
},
"node_modules/prettier": {
"version": "3.2.5",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
"dev": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/prettier-plugin-jinja-template": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/prettier-plugin-jinja-template/-/prettier-plugin-jinja-template-1.4.0.tgz",
"integrity": "sha512-9i7HwTAryhOTtY1ENyZBZA+KNaPphSaI/sXbQno5a6/DgiP6ZAnUiax4cOKiutEwiSDhVfLbTXEfHS5QAUVWBg==",
"dev": true,
"peerDependencies": {
"prettier": "^3.0.0"
}
}
}
}

9
package.json Normal file
View file

@ -0,0 +1,9 @@
{
"scripts": {
"format": "prettier --write ."
},
"devDependencies": {
"prettier": "^3.2.5",
"prettier-plugin-jinja-template": "^1.4.0"
}
}

View file

@ -1,134 +1,137 @@
<style>
#options {
position: absolute;
bottom: 0;
margin: 20px;
margin-bottom: 40px;
font-size: 1.25rem;
}
#options {
position: absolute;
bottom: 0;
margin: 20px;
margin-bottom: 40px;
font-size: 1.25rem;
}
#options *:not(input) {
background: transparent;
border: none;
color: #fff;
font-size: 1.25rem;
}
#options *:not(input) {
background: transparent;
border: none;
color: #fff;
font-size: 1.25rem;
}
#options *:not(input):not(:nth-child(2)) {
margin-bottom: 3.5px;
}
#options *:not(input):not(:nth-child(2)) {
margin-bottom: 3.5px;
}
</style>
<div class="row">
<div class="col-12 col-lg-3">
<div class="card mcard mb-3">
<h6 class="card-header">
<i class="fad fa-user-crown"></i>
Avatar Sandbox
</h6>
<div class="card-body">
<iframe id="viewFrame" style="width: 100%; height: 314px; border-radius: 0.65rem;"></iframe>
<div id="options">
<input name="JSONUpload" type="file" accept="application/json" multiple="false" id="jsonUpload" aria-label="Upload JSON!" style="display: none;">
<div class="col-12 col-lg-3">
<div class="card mcard mb-3">
<h6 class="card-header">
<i class="fad fa-user-crown"></i>
Avatar Sandbox
</h6>
<div class="card-body">
<iframe id="viewFrame" style="width: 100%; height: 314px; border-radius: 0.65rem;"></iframe>
<div id="options">
<input name="JSONUpload" type="file" accept="application/json" multiple="false" id="jsonUpload" aria-label="Upload JSON!" style="display: none;" />
<label for="JSONUpload" style="display: block;">
<button aria-label="Upload JSON!" onclick="this.parentElement.previousElementSibling.click()">
<i class="fa-duotone fa-download"></i>
</button>
</label>
<label for="JSONUpload" style="display: block;">
<button aria-label="Upload JSON!" onclick="this.parentElement.previousElementSibling.click()">
<i class="fa-duotone fa-download"></i>
</button>
</label>
<button id="jsonSave" aria-label="Save as JSON!" style="display: block;">
<i class="fa-duotone fa-upload"></i>
</button>
<button id="jsonSave" aria-label="Save as JSON!" style="display: block;">
<i class="fa-duotone fa-upload"></i>
</button>
<button id="openNewTab" aria-label="View in a new tab!" style="display: block;">
<i class="fa-duotone fa-up-right-from-square"></i>
</button>
<button id="openNewTab" aria-label="View in a new tab!" style="display: block;">
<i class="fa-duotone fa-up-right-from-square"></i>
</button>
<button aria-label="View in full screen!" style="display: block;" onclick="document.getElementById('viewFrame').requestFullscreen()">
<i class="fa-duotone fa-minimize"></i>
</button>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<button id="myself" class="btn btn-outline-primary w-100">
<i class="fa-duotone fa-shirt"></i>
Myself
</button>
</div>
<div class="col">
<button id="clear" class="btn btn-outline-warning w-100">
<i class="fa-duotone fa-trash"></i>
Clear
</button>
</div>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control bg-dark" placeholder="Asset ID..">
<button class="btn btn-primary" id="load-asset">Load Asset</button>
</div>
<div class="card mcard mb-3">
<h6 class="card-header">
<i class="fad fa-palette"></i>
Body Colors
</h6>
<div class="card-body">
<div class="card-body text-center" id="body-parts">
<button aria-label="View in full screen!" style="display: block;" onclick="document.getElementById('viewFrame').requestFullscreen()">
<i class="fa-duotone fa-minimize"></i>
</button>
</div>
</div>
</div>
<div class="row mb-3">
<div class="col">
<button id="myself" class="btn btn-outline-primary w-100">
<i class="fa-duotone fa-shirt"></i>
Myself
</button>
</div>
<div class="col">
<button id="clear" class="btn btn-outline-warning w-100">
<i class="fa-duotone fa-trash"></i>
Clear
</button>
</div>
</div>
<div class="input-group mb-3">
<input type="text" class="form-control bg-dark" placeholder="Asset ID.." />
<button class="btn btn-primary" id="load-asset">Load Asset</button>
</div>
<div class="card mcard mb-3">
<h6 class="card-header">
<i class="fad fa-palette"></i>
Body Colors
</h6>
<div class="card-body">
<div class="card-body text-center" id="body-parts">
<div style="margin-bottom: 5px">
<button id="head" class="avatarAction bodypart bp1x1" style="background-color: #e0e0e0;"></button>
</div>
<button id="head" class="avatarAction bodypart bp1x1" style="background-color: #e0e0e0;"></button>
</div>
<div style="margin-bottom: 5px">
<button id="rightArm" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; margin-right: 5px;"></button><button id="torso" class="avatarAction bodypart bp2x2" style="background-color: #e0e0e0;"></button><button class="avatarAction bodypart bp1x2" id="leftArm" style="background-color: #e0e0e0; margin-left: 5px;"></button>
</div>
<button id="rightArm" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; margin-right: 5px;"></button
><button id="torso" class="avatarAction bodypart bp2x2" style="background-color: #e0e0e0;"></button
><button class="avatarAction bodypart bp1x2" id="leftArm" style="background-color: #e0e0e0; margin-left: 5px;"></button>
</div>
<div>
<button class="avatarAction bodypart bp1x2" id="rightLeg" style="background-color: #e0e0e0; margin-right: 5px; padding-right: 18px;"></button><button id="leftLeg" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; padding-right: 18px;"></button>
<button class="avatarAction bodypart bp1x2" id="rightLeg" style="background-color: #e0e0e0; margin-right: 5px; padding-right: 18px;"></button
><button id="leftLeg" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; padding-right: 18px;"></button>
</div>
</div>
</div>
</div>
<small class="text-muted text-center" style="font-size: 0.7rem;">feature of Poly+</small>
</div>
<div class="col-12 col-lg-9">
<ul class="nav nav-pills nav-justified mb-3" id="tabs">
<li class="nav-item">
<a class="nav-link active" data-tab="hat">
<i class="fas fa-hat-cowboy me-1"></i>
Hats
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="tool">
<i class="fas fa-hammer me-1"></i>
Tools
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="face">
<i class="fas fa-face-smile me-1"></i>
Faces
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="shirt">
<i class="fas fa-tshirt me-1"></i>
Shirts
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="pants">
<i class="fas fa-socks me-1"></i>
Pants
</a>
</li>
</ul>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<input id="item-search" type="text" class="form-control mb-2" placeholder="Search for an item...">
<div class="row alignleft itemgrid" id="inventory"></div>
</div>
<h6 class="card-header mb-2"><i class="fad fa-hat-wizard me-1"></i> Wearing</h6>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<div class="row alignleft itemgrid" id="wearing"></div>
</div>
</div>
</div>
</div>
<small class="text-muted text-center" style="font-size: 0.7rem;">feature of Poly+</small>
</div>
<div class="col-12 col-lg-9">
<ul class="nav nav-pills nav-justified mb-3" id="tabs">
<li class="nav-item">
<a class="nav-link active" data-tab="hat">
<i class="fas fa-hat-cowboy me-1"></i>
Hats
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="tool">
<i class="fas fa-hammer me-1"></i>
Tools
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="face">
<i class="fas fa-face-smile me-1"></i>
Faces
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="shirt">
<i class="fas fa-tshirt me-1"></i>
Shirts
</a>
</li>
<li class="nav-item">
<a class="nav-link" data-tab="pants">
<i class="fas fa-socks me-1"></i>
Pants
</a>
</li>
</ul>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<input id="item-search" type="text" class="form-control mb-2" placeholder="Search for an item..." />
<div class="row alignleft itemgrid" id="inventory"></div>
</div>
<h6 class="card-header mb-2"><i class="fad fa-hat-wizard me-1"></i> Wearing</h6>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<div class="row alignleft itemgrid" id="wearing"></div>
</div>
</div>
</div>

View file

@ -1,59 +1,59 @@
{
"Date": "2023-7-17",
"Data": [
{
"USD": 0.009899999999999999,
"EUR": 0.011200000000000002,
"CAD": 0.0123,
"GBP": 0.008100000000000001,
"MXN": 0.1928,
"AUD": 0.014199999999999999,
"TRY": 0.1583
},
{
"USD": 0.009072727272727274,
"EUR": 0.010163636363636363,
"CAD": 0.011290909090909091,
"GBP": 0.007363636363636363,
"MXN": 0.17534545454545455,
"AUD": 0.013418181818181819,
"TRY": 0.14616363636363636
},
{
"USD": 0.00868695652173913,
"EUR": 0.009721739130434783,
"CAD": 0.010730434782608695,
"GBP": 0.007043478260869565,
"MXN": 0.1676521739130435,
"AUD": 0.012834782608695652,
"TRY": 0.13767826086956522
},
{
"USD": 0.009087272727272727,
"EUR": 0.00996,
"CAD": 0.010625454545454546,
"GBP": 0.006981818181818182,
"MXN": 0.17294545454545454,
"AUD": 0.012698181818181819,
"TRY": 0.14424
},
{
"USD": 0.008331666666666668,
"EUR": 0.009323333333333333,
"CAD": 0.00974,
"GBP": 0.006066666666666666,
"MXN": 0.15853333333333333,
"AUD": 0.012306666666666667,
"TRY": 0.13222
},
{
"USD": 0.0079992,
"EUR": 0.008950399999999999,
"CAD": 0.0093504,
"GBP": 0.005824,
"MXN": 0.152192,
"AUD": 0.011814400000000001,
"TRY": 0.12693120000000002
}
]
"Date": "2023-7-17",
"Data": [
{
"USD": 0.009899999999999999,
"EUR": 0.011200000000000002,
"CAD": 0.0123,
"GBP": 0.008100000000000001,
"MXN": 0.1928,
"AUD": 0.014199999999999999,
"TRY": 0.1583
},
{
"USD": 0.009072727272727274,
"EUR": 0.010163636363636363,
"CAD": 0.011290909090909091,
"GBP": 0.007363636363636363,
"MXN": 0.17534545454545455,
"AUD": 0.013418181818181819,
"TRY": 0.14616363636363636
},
{
"USD": 0.00868695652173913,
"EUR": 0.009721739130434783,
"CAD": 0.010730434782608695,
"GBP": 0.007043478260869565,
"MXN": 0.1676521739130435,
"AUD": 0.012834782608695652,
"TRY": 0.13767826086956522
},
{
"USD": 0.009087272727272727,
"EUR": 0.00996,
"CAD": 0.010625454545454546,
"GBP": 0.006981818181818182,
"MXN": 0.17294545454545454,
"AUD": 0.012698181818181819,
"TRY": 0.14424
},
{
"USD": 0.008331666666666668,
"EUR": 0.009323333333333333,
"CAD": 0.00974,
"GBP": 0.006066666666666666,
"MXN": 0.15853333333333333,
"AUD": 0.012306666666666667,
"TRY": 0.13222
},
{
"USD": 0.0079992,
"EUR": 0.008950399999999999,
"CAD": 0.0093504,
"GBP": 0.005824,
"MXN": 0.152192,
"AUD": 0.011814400000000001,
"TRY": 0.12693120000000002
}
]
}

View file

@ -1,5 +1,8 @@
window.localStorage.setItem('p+account_info', JSON.stringify({
ID: userID,
Username: document.querySelector('a[href^="/u"]:has(.dropdown-item):first-child').innerText.replaceAll('\n', '').replaceAll('\t', '').trim(),
Bricks: document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g,'').split('(')[0]
}))
window.localStorage.setItem(
'p+account_info',
JSON.stringify({
ID: userID,
Username: document.querySelector('a[href^="/u"]:has(.dropdown-item):first-child').innerText.replaceAll('\n', '').replaceAll('\t', '').trim(),
Bricks: document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g, '').split('(')[0]
})
);

View file

@ -1,2 +1,2 @@
var tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]')
var list = [...tooltips].map(tool => new bootstrap.Tooltip(tool))
var tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
var list = [...tooltips].map((tool) => new bootstrap.Tooltip(tool));

View file

@ -8,115 +8,107 @@ HOW TO USE IN CONTENT SCRIPTS:
*/
function ParseFullNumber(ab) {
if (typeof(ab) === "number") { return ab }
const Suffixes = {"k": 1000, "m": 1000000, "b": 1000000000}
const Suffix = ab.slice(-1).toLowerCase();
if (Suffixes[Suffix]) {return parseFloat(ab)*Suffixes[Suffix]} else {return parseFloat(ab)}
if (typeof ab === 'number') {
return ab;
}
const Suffixes = {k: 1000, m: 1000000, b: 1000000000};
const Suffix = ab.slice(-1).toLowerCase();
if (Suffixes[Suffix]) {
return parseFloat(ab) * Suffixes[Suffix];
} else {
return parseFloat(ab);
}
}
export default {
DefaultSettings: {
PinnedGamesOn: true,
ForumMentsOn: true,
BestFriendsOn: false,
ImprovedFrListsOn: false,
IRLPriceWithCurrency: {
Enabled: true,
Currency: 0,
Package: 0
},
IRLPriceWithCurrencyOn: true,
IRLPriceWithCurrencyCurrency: 0,
IRLPriceWithCurrencyPackage: 0,
HideNotifBadgesOn: false,
StoreOwnTagOn: true,
ThemeCreatorOn: false,
ThemeCreator: {
Enabled: false,
BGColor: null,
BGImage: null,
BGImageSize: 'fit',
PrimaryTextColor: null,
SecondaryTextColor: null,
LinkTextColor: null,
WebsiteLogo: null
},
ModifyNavOn: false,
ModifyNav: [
{
Label: "Places",
Link: "https://polytoria.com/places"
},
{
Label: "Store",
Link: "https://polytoria.com/store"
},
{
Label: "Guilds",
Link: "https://polytoria.com/guilds"
},
{
Label: "People",
Link: "https://polytoria.com/users"
},
{
Label: "Forum",
Link: "https://polytoria.com/forum"
}
],
MoreSearchFiltersOn: true,
ApplyMembershipTheme: {
Enabled: false,
Theme: 0
},
ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0,
MultiCancelOutTradesOn: true,
ItemWishlistOn: true,
HideUpgradeBtnOn: false,
TryOnItemsOn: true,
OutfitCostOn: true,
ShowPlaceRevenueOn: true,
ReplaceItemSalesOn: false,
HoardersListOn: true,
HoardersList: {
Enabled: true,
AvatarsEnabled: false,
MinCopies: 2
},
LibraryDownloadsOn: true,
EventItemsCatOn: true,
HomeFriendCountOn: true,
HideUserAds: {
Enabled: false,
Banners: true,
Rectangles: true
}
},
Limits: {
PinnedGames: 10,
BestFriends: 15,
ImprovedFrLists: 20,
ItemWishlist: 20
},
MeshTypes: [
"hat",
"hair",
"head attachment",
"face accessory",
"neck accessory",
"head cover",
"back accessory",
"shoulder accessory",
"tool"
],
TextureTypes: [
"shirt",
"pants",
"face"
],
CalculateIRL: async function(bricks, to, brickPackage) {
/*
DefaultSettings: {
PinnedGamesOn: true,
ForumMentsOn: true,
BestFriendsOn: false,
ImprovedFrListsOn: false,
IRLPriceWithCurrency: {
Enabled: true,
Currency: 0,
Package: 0
},
IRLPriceWithCurrencyOn: true,
IRLPriceWithCurrencyCurrency: 0,
IRLPriceWithCurrencyPackage: 0,
HideNotifBadgesOn: false,
StoreOwnTagOn: true,
ThemeCreatorOn: false,
ThemeCreator: {
Enabled: false,
BGColor: null,
BGImage: null,
BGImageSize: 'fit',
PrimaryTextColor: null,
SecondaryTextColor: null,
LinkTextColor: null,
WebsiteLogo: null
},
ModifyNavOn: false,
ModifyNav: [
{
Label: 'Places',
Link: 'https://polytoria.com/places'
},
{
Label: 'Store',
Link: 'https://polytoria.com/store'
},
{
Label: 'Guilds',
Link: 'https://polytoria.com/guilds'
},
{
Label: 'People',
Link: 'https://polytoria.com/users'
},
{
Label: 'Forum',
Link: 'https://polytoria.com/forum'
}
],
MoreSearchFiltersOn: true,
ApplyMembershipTheme: {
Enabled: false,
Theme: 0
},
ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0,
MultiCancelOutTradesOn: true,
ItemWishlistOn: true,
HideUpgradeBtnOn: false,
TryOnItemsOn: true,
OutfitCostOn: true,
ShowPlaceRevenueOn: true,
ReplaceItemSalesOn: false,
HoardersListOn: true,
HoardersList: {
Enabled: true,
AvatarsEnabled: false,
MinCopies: 2
},
LibraryDownloadsOn: true,
EventItemsCatOn: true,
HomeFriendCountOn: true,
HideUserAds: {
Enabled: false,
Banners: true,
Rectangles: true
}
},
Limits: {
PinnedGames: 10,
BestFriends: 15,
ImprovedFrLists: 20,
ItemWishlist: 20
},
MeshTypes: ['hat', 'hair', 'head attachment', 'face accessory', 'neck accessory', 'head cover', 'back accessory', 'shoulder accessory', 'tool'],
TextureTypes: ['shirt', 'pants', 'face'],
CalculateIRL: async function (bricks, to, brickPackage) {
/*
Disabled for now: currency retrieval from currencies.json
const response = await fetch(chrome.runtime.getURL('resources/currencies.json'))
@ -127,108 +119,114 @@ export default {
const UnitPrice = data.Data[brickPackage][to]
*/
let Icon = "$"
let Result = "N/A";
let Display = "Currency Not Found";
let Icon = '$';
let Result = 'N/A';
let Display = 'Currency Not Found';
// is the icon abbreviated text, or an entity
let IsIconAbbr = false
// is the icon abbreviated text, or an entity
let IsIconAbbr = false;
bricks = ParseFullNumber(bricks.replace(/,/g, ''))
switch (to) {
// U.S. Dollar
case 0:
Result = (bricks * 0.0099).toFixed(2)
Display = "USD"
bricks = ParseFullNumber(bricks.replace(/,/g, ''));
switch (to) {
// U.S. Dollar
case 0:
Result = (bricks * 0.0099).toFixed(2);
Display = 'USD';
break
break;
// Euro
case 1:
Icon = "&#8364;"
Result = (bricks * 0.009).toFixed(2)
Display = "EUR"
// Euro
case 1:
Icon = '&#8364;';
Result = (bricks * 0.009).toFixed(2);
Display = 'EUR';
break
break;
// Canadian Dollar
case 2:
Icon = "CAD$"
IsIconAbbr = true
// Canadian Dollar
case 2:
Icon = 'CAD$';
IsIconAbbr = true;
Result = (bricks * 0.0131).toFixed(2)
Display = "CAD"
Result = (bricks * 0.0131).toFixed(2);
Display = 'CAD';
break
break;
// Great British Pound
case 3:
Icon = "&#163;"
Result = (bricks * 0.0077).toFixed(2)
Display = "GBP"
// Great British Pound
case 3:
Icon = '&#163;';
Result = (bricks * 0.0077).toFixed(2);
Display = 'GBP';
break
break;
// Mexican Peso
case 4:
Icon = "MXN$"
IsIconAbbr = true
// Mexican Peso
case 4:
Icon = 'MXN$';
IsIconAbbr = true;
Result = (bricks * 0.1691).toFixed(2)
Display = "MXN"
Result = (bricks * 0.1691).toFixed(2);
Display = 'MXN';
break
break;
// Australia Dollar
case 5:
Icon = "AU$"
IsIconAbbr = true
// Australia Dollar
case 5:
Icon = 'AU$';
IsIconAbbr = true;
Result = (bricks * 0.0144).toFixed(2)
Display = "AUD"
Result = (bricks * 0.0144).toFixed(2);
Display = 'AUD';
break
break;
// Turkish Lira
case 6:
Icon = "&#8378;"
Result = (bricks * 0.2338).toFixed(2)
Display = "TRY"
// Turkish Lira
case 6:
Icon = '&#8378;';
Result = (bricks * 0.2338).toFixed(2);
Display = 'TRY';
break
break;
// Brazillian Real
case 7:
Icon = "R$"
IsIconAbbr = true
// Brazillian Real
case 7:
Icon = 'R$';
IsIconAbbr = true;
Result = (bricks * 0.49).toFixed(2)
Display = "BRL"
Result = (bricks * 0.49).toFixed(2);
Display = 'BRL';
break
}
break;
}
if (typeof(Result) === "number") { Result = Result.toFixed(2) }
if (typeof Result === 'number') {
Result = Result.toFixed(2);
}
return {
result: Result,
display: Display,
icon: Icon,
isIconAbbr: IsIconAbbr
}
},
InjectResource: function(path, element) {
// Function by devjin0617 on GitHub
// Gist: https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a
// Slightly modified to use constants and fit the rest of the code style more
// Function only used for registering bootstrap tooltips currently
return {
result: Result,
display: Display,
icon: Icon,
isIconAbbr: IsIconAbbr
};
},
InjectResource: function (path, element) {
// Function by devjin0617 on GitHub
// Gist: https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a
// Slightly modified to use constants and fit the rest of the code style more
// Function only used for registering bootstrap tooltips currently
if (element === undefined) { element = 'body' }
const Node = document.getElementsByTagName(element)[0];
const Script = document.createElement('script');
Script.setAttribute('type', 'text/javascript');
Script.setAttribute('src', chrome.runtime.getURL('resources/' + path + '.js'));
Script.addEventListener('load', function(){Script.remove()})
Node.appendChild(Script);
}
}
if (element === undefined) {
element = 'body';
}
const Node = document.getElementsByTagName(element)[0];
const Script = document.createElement('script');
Script.setAttribute('type', 'text/javascript');
Script.setAttribute('src', chrome.runtime.getURL('resources/' + path + '.js'));
Script.addEventListener('load', function () {
Script.remove();
});
Node.appendChild(Script);
}
};

File diff suppressed because it is too large Load diff

View file

@ -1,400 +1,426 @@
const SaveBtn = document.getElementById('Save')
const Elements = Array.from(document.getElementsByClassName('setting-container'))
const SaveBtn = document.getElementById('Save');
const Elements = Array.from(document.getElementsByClassName('setting-container'));
var Settings;
var Utilities;
(async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default
LoadCurrent()
Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default;
LoadCurrent();
document.getElementById('PinnedGames-limit').innerText = Utilities.Limits.PinnedGames
document.getElementById('BestFriends-limit').innerText = Utilities.Limits.BestFriends
document.getElementById('ImprovedFrLists-limit').innerText = Utilities.Limits.ImprovedFrLists
document.getElementById('ItemWishlist-limit').innerText = Utilities.Limits.ItemWishlist
document.getElementById('PinnedGames-limit').innerText = Utilities.Limits.PinnedGames;
document.getElementById('BestFriends-limit').innerText = Utilities.Limits.BestFriends;
document.getElementById('ImprovedFrLists-limit').innerText = Utilities.Limits.ImprovedFrLists;
document.getElementById('ItemWishlist-limit').innerText = Utilities.Limits.ItemWishlist;
})();
// Handle buttons at the bottom of the page
document.getElementById('ResetDefaults').addEventListener('click', function() {
document.getElementById('ResetDefaults-Modal').showModal();
document.getElementById('ResetDefaults').addEventListener('click', function () {
document.getElementById('ResetDefaults-Modal').showModal();
});
SaveBtn.addEventListener("click", function() {
Save();
SaveBtn.addEventListener('click', function () {
Save();
});
// Handle modal buttons for Reset Defaults modal
document.getElementById('ResetDefaults-Modal-Yes').addEventListener('click', function() {
Settings = Utilities.DefaultSettings
Save()
setTimeout(function () {
LoadCurrent();
document.getElementById('ResetDefaults-Modal').close();
}, 400)
document.getElementById('ResetDefaults-Modal-Yes').addEventListener('click', function () {
Settings = Utilities.DefaultSettings;
Save();
setTimeout(function () {
LoadCurrent();
document.getElementById('ResetDefaults-Modal').close();
}, 400);
});
document.getElementById('ResetDefaults-Modal-No').addEventListener('click', function() {
document.getElementById('ResetDefaults-Modal').close();
document.getElementById('ResetDefaults-Modal-No').addEventListener('click', function () {
document.getElementById('ResetDefaults-Modal').close();
});
// Handle leaving the settings page before saving
window.onbeforeunload = function() {
if (SaveBtn.getAttribute('disabled') !== undefined) {
return "Are you sure you'd like to leave? Your Poly+ settings haven't been saved."
}
}
window.onbeforeunload = function () {
if (SaveBtn.getAttribute('disabled') !== undefined) {
return "Are you sure you'd like to leave? Your Poly+ settings haven't been saved.";
}
};
// Loop thru each setting container and handle toggling, selecting, opening modal, etc
Elements.forEach(element => {
console.log('Handle Element', element)
let Button = element.getElementsByTagName('button')[0]
let Options = element.getElementsByTagName('button')[1]
let Select = element.getElementsByTagName('select')[0]
let Checkbox = element.getElementsByTagName('input')[0]
Elements.forEach((element) => {
console.log('Handle Element', element);
let Button = element.getElementsByTagName('button')[0];
let Options = element.getElementsByTagName('button')[1];
let Select = element.getElementsByTagName('select')[0];
let Checkbox = element.getElementsByTagName('input')[0];
if (Button) {
Button.addEventListener('click', function() {
SetSetting(Button, "bool")
});
}
if (Button) {
Button.addEventListener('click', function () {
SetSetting(Button, 'bool');
});
}
if (Select) {
Select.addEventListener('change', function(){
if (Select.getAttribute('data-useValue') !== undefined) {
let Value = Select.options[Select.selectedIndex].value
if (!isNaN(Value)) { Value = parseInt(Value) }
SetSetting(Select, Value, false)
} else {
SetSetting(Select, Select.selectedIndex, false)
}
})
}
if (Select) {
Select.addEventListener('change', function () {
if (Select.getAttribute('data-useValue') !== undefined) {
let Value = Select.options[Select.selectedIndex].value;
if (!isNaN(Value)) {
Value = parseInt(Value);
}
SetSetting(Select, Value, false);
} else {
SetSetting(Select, Select.selectedIndex, false);
}
});
}
if (Checkbox) {
Checkbox.addEventListener('change', function(){
SetSetting(Checkbox, Checkbox.checked, false)
})
}
if (Checkbox) {
Checkbox.addEventListener('change', function () {
SetSetting(Checkbox, Checkbox.checked, false);
});
}
if (Options) {
const Modal = document.getElementById(Options.getAttribute('data-modal') + '-Modal')
const ModalButtons = Modal.getElementsByTagName('button')
const ModalInputs = Modal.getElementsByTagName('input')
const ModalSelect = Modal.getElementsByTagName('select')
if (Options) {
const Modal = document.getElementById(Options.getAttribute('data-modal') + '-Modal');
const ModalButtons = Modal.getElementsByTagName('button');
const ModalInputs = Modal.getElementsByTagName('input');
const ModalSelect = Modal.getElementsByTagName('select');
Options.addEventListener('click', function(){
Array.from(ModalButtons).filter((x) => !x.classList.contains('ignore')).forEach(button => {
button.addEventListener('click', function(){
const Setting = button.getAttribute('data-setting')
Options.addEventListener('click', function () {
Array.from(ModalButtons)
.filter((x) => !x.classList.contains('ignore'))
.forEach((button) => {
button.addEventListener('click', function () {
const Setting = button.getAttribute('data-setting');
if (Setting === '[save]') {
// Save Modal Button
if (Setting === '[save]') {
// Save Modal Button
Array.from(ModalInputs).filter((x) => !x.classList.contains('ignore')).forEach(input => {
SetSetting(input, input.value, false, Modal.getAttribute('data-setting'))
});
Array.from(ModalSelect).filter((x) => !x.classList.contains('ignore')).forEach(select => {
SetSetting(select, select.selectedIndex, false, Modal.getAttribute('data-setting'))
});
Save();
setTimeout(function () {
LoadCurrent();
Modal.close();
}, 400)
} else if (Setting === '[reset-default]') {
// Reset to Defaults Modal Button
Array.from(ModalInputs)
.filter((x) => !x.classList.contains('ignore'))
.forEach((input) => {
SetSetting(input, input.value, false, Modal.getAttribute('data-setting'));
});
Array.from(ModalSelect)
.filter((x) => !x.classList.contains('ignore'))
.forEach((select) => {
SetSetting(select, select.selectedIndex, false, Modal.getAttribute('data-setting'));
});
Save();
setTimeout(function () {
LoadCurrent();
Modal.close();
}, 400);
} else if (Setting === '[reset-default]') {
// Reset to Defaults Modal Button
if (confirm("Are you sure you'd like to reset these options to their defaults?") === true) {
Settings[Modal.getAttribute('data-setting')] = Utilities.DefaultSettings[Modal.getAttribute('data-setting')]
Save()
Modal.close();
}
} else if (Setting === '[cancel]') {
// Cancel Changes Button
if (confirm("Are you sure you'd like to reset these options to their defaults?") === true) {
Settings[Modal.getAttribute('data-setting')] = Utilities.DefaultSettings[Modal.getAttribute('data-setting')];
Save();
Modal.close();
}
} else if (Setting === '[cancel]') {
// Cancel Changes Button
Modal.close();
} else {
// Default Toggle Button
Modal.close();
} else {
// Default Toggle Button
SetSetting(button, "bool", false, Modal.getAttribute('data-setting'))
}
})
})
SetSetting(button, 'bool', false, Modal.getAttribute('data-setting'));
}
});
});
Array.from(ModalInputs).filter((x) => !x.classList.contains('ignore')).forEach(input => {
const Status = GetSettingValue(input, Modal.getAttribute('data-setting'))
if (Status !== "undefined" && Status !== undefined) {
input.value = Status
} else {
input.value = ''
}
});
Array.from(ModalInputs)
.filter((x) => !x.classList.contains('ignore'))
.forEach((input) => {
const Status = GetSettingValue(input, Modal.getAttribute('data-setting'));
if (Status !== 'undefined' && Status !== undefined) {
input.value = Status;
} else {
input.value = '';
}
});
Array.from(ModalSelect).filter((x) => !x.classList.contains('ignore')).forEach(select => {
const Status = GetSettingValue(select, Modal.getAttribute('data-setting'))
if (Status !== "undefined" && Status !== undefined) {
select.selectedIndex = Status
}
});
Array.from(ModalSelect)
.filter((x) => !x.classList.contains('ignore'))
.forEach((select) => {
const Status = GetSettingValue(select, Modal.getAttribute('data-setting'));
if (Status !== 'undefined' && Status !== undefined) {
select.selectedIndex = Status;
}
});
Modal.showModal()
})
}
Modal.showModal();
});
}
});
function LoadCurrent() {
chrome.storage.sync.get(["PolyPlus_Settings"], function(result) {
Settings = MergeObjects(result.PolyPlus_Settings || Utilities.DefaultSettings, Utilities.DefaultSettings)
chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = MergeObjects(result.PolyPlus_Settings || Utilities.DefaultSettings, Utilities.DefaultSettings);
console.log("Current Settings: ", Settings)
console.log('Current Settings: ', Settings);
Elements.forEach(element => {
console.log('For Each Update')
UpdateElementState(element)
});
});
Elements.forEach((element) => {
console.log('For Each Update');
UpdateElementState(element);
});
});
}
function SetSetting(element, value, update, modalParent) {
const name = element.getAttribute('data-setting')
let parent = element.getAttribute('data-parent')
const name = element.getAttribute('data-setting');
let parent = element.getAttribute('data-parent');
if (modalParent !== undefined) {
console.log(modalParent)
parent = modalParent
}
if (modalParent !== undefined) {
console.log(modalParent);
parent = modalParent;
}
if (value === "bool") {
value = !GetSettingValue(element, modalParent)
}
if (parent !== null) {
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)]
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
console.log('is numbere!!!!')
Parent = Parent[parseInt(element.getAttribute('data-parent'))]
}
Parent[name] = value
} else {
Settings[name] = value
}
if (update !== false) {
UpdateElementState(document.querySelector(`.setting-container:has([data-setting="${name}"])${ (parent !== null) ? `:has([data-parent="${parent}"])` : '' }`), value)
}
if (SaveBtn.getAttribute('disabled')) {
SaveBtn.removeAttribute('disabled')
}
if (value === 'bool') {
value = !GetSettingValue(element, modalParent);
}
if (parent !== null) {
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)];
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
console.log('is numbere!!!!');
Parent = Parent[parseInt(element.getAttribute('data-parent'))];
}
Parent[name] = value;
} else {
Settings[name] = value;
}
if (update !== false) {
UpdateElementState(document.querySelector(`.setting-container:has([data-setting="${name}"])${parent !== null ? `:has([data-parent="${parent}"])` : ''}`), value);
}
if (SaveBtn.getAttribute('disabled')) {
SaveBtn.removeAttribute('disabled');
}
const getInObject = function(a, b) { return Object.values(a)[Object.keys(a).indexOf(b)] }
const getInObject = function (a, b) {
return Object.values(a)[Object.keys(a).indexOf(b)];
};
}
function GetSettingValue(element, modalParent) {
const name = element.getAttribute('data-setting')
let parent = element.getAttribute('data-parent')
const name = element.getAttribute('data-setting');
let parent = element.getAttribute('data-parent');
if (modalParent !== undefined) {
parent = modalParent
}
if (modalParent !== undefined) {
parent = modalParent;
}
let Status = name;
if (parent !== null) {
let Status = name;
if (parent !== null) {
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)];
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))];
Status = Parent[name];
} else {
Status = Object.values(Parent)[Object.keys(Parent).indexOf(name)];
}
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)]
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))]
Status = Parent[name]
} else {
Status = Object.values(Parent)[Object.keys(Parent).indexOf(name)]
}
/*
/*
if (!isNaN(element.getAttribute('data-parent'))) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))]
}
Status = Object.values(Parent)[Object.keys(Parent).indexOf(Status)]
*/
} else {
Status = Settings[Status]
}
console.log('Get Value Result', Status)
} else {
Status = Settings[Status];
}
console.log('Get Value Result', Status);
return Status
return Status;
}
function UpdateElementState(element, status) {
console.log('Update Element State', element, status)
console.log('Update Element State', element, status);
const Button = element.getElementsByClassName('toggle-btn')[0]
const Button = element.getElementsByClassName('toggle-btn')[0];
if (status === undefined) {
console.log('Update Element State, no status provided')
status = GetSettingValue(Button)
}
if (status === undefined) {
console.log('Update Element State, no status provided');
status = GetSettingValue(Button);
}
if (status === true) {
console.log('Is Enabled so Set False')
element.classList.add('enabled')
element.classList.remove('disabled')
Button.innerText = 'Disable'
Button.classList.add('btn-danger')
Button.classList.remove('btn-success')
} else {
console.log('Is Disabled so Set True')
element.classList.add('disabled')
element.classList.remove('enabled')
Button.innerText = 'Enable'
Button.classList.add('btn-success')
Button.classList.remove('btn-danger')
}
if (status === true) {
console.log('Is Enabled so Set False');
element.classList.add('enabled');
element.classList.remove('disabled');
Button.innerText = 'Disable';
Button.classList.add('btn-danger');
Button.classList.remove('btn-success');
} else {
console.log('Is Disabled so Set True');
element.classList.add('disabled');
element.classList.remove('enabled');
Button.innerText = 'Enable';
Button.classList.add('btn-success');
Button.classList.remove('btn-danger');
}
let SelectInput = element.getElementsByTagName('select')[0]
if (SelectInput) {
console.log('Select Found')
SelectInput.selectedIndex = GetSettingValue(SelectInput)
}
let SelectInput = element.getElementsByTagName('select')[0];
if (SelectInput) {
console.log('Select Found');
SelectInput.selectedIndex = GetSettingValue(SelectInput);
}
let Checkbox = Array.from(element.getElementsByTagName('input'))
if (Checkbox.length > 0) {
console.log('Checkbox/Input(s) Found', Checkbox)
Checkbox.forEach(check => {
console.log('check', GetSettingValue(check))
check.checked = GetSettingValue(check)
})
}
let Checkbox = Array.from(element.getElementsByTagName('input'));
if (Checkbox.length > 0) {
console.log('Checkbox/Input(s) Found', Checkbox);
Checkbox.forEach((check) => {
console.log('check', GetSettingValue(check));
check.checked = GetSettingValue(check);
});
}
}
function Save() {
document.title = 'Poly+ Settings'
SaveBtn.setAttribute('disabled', 'true')
chrome.storage.sync.set({ 'PolyPlus_Settings': Settings, arrayOrder: true }, function() {
console.log('Saved successfully!');
});
document.title = 'Poly+ Settings';
SaveBtn.setAttribute('disabled', 'true');
chrome.storage.sync.set({PolyPlus_Settings: Settings, arrayOrder: true}, function () {
console.log('Saved successfully!');
});
console.log("Save:", Settings);
console.log('Save:', Settings);
}
let LoadThemeFromJSONBtn = document.getElementById('LoadThemeFromJSONBtn')
let SaveThemeToJSONInput = document.getElementById('SaveThemeToJSONInput')
let CopyThemeJSONBtn = document.getElementById('CopyThemeJSONBtn')
LoadThemeFromJSONBtn.addEventListener('click', function(){
LoadThemeJSON(LoadThemeFromJSONBtn.previousElementSibling.value)
let LoadThemeFromJSONBtn = document.getElementById('LoadThemeFromJSONBtn');
let SaveThemeToJSONInput = document.getElementById('SaveThemeToJSONInput');
let CopyThemeJSONBtn = document.getElementById('CopyThemeJSONBtn');
LoadThemeFromJSONBtn.addEventListener('click', function () {
LoadThemeJSON(LoadThemeFromJSONBtn.previousElementSibling.value);
});
document.getElementById('theme-creator').getElementsByTagName('button')[1].addEventListener('click', function(){
SaveThemeToJSONInput.value = JSON.stringify(Settings.ThemeCreator)
});
CopyThemeJSONBtn.addEventListener('click', function(){
if (SaveThemeToJSONInput.value.length > 0) {
navigator.clipboard.writeText(SaveThemeToJSONInput.value)
.then(() => {
alert('Successfully copied theme data to clipboard!')
})
.catch(() => {
alert('Failure to copy theme data to clipboard.')
});
}
document
.getElementById('theme-creator')
.getElementsByTagName('button')[1]
.addEventListener('click', function () {
SaveThemeToJSONInput.value = JSON.stringify(Settings.ThemeCreator);
});
CopyThemeJSONBtn.addEventListener('click', function () {
if (SaveThemeToJSONInput.value.length > 0) {
navigator.clipboard
.writeText(SaveThemeToJSONInput.value)
.then(() => {
alert('Successfully copied theme data to clipboard!');
})
.catch(() => {
alert('Failure to copy theme data to clipboard.');
});
}
});
function LoadThemeJSON(string) {
try {
let JSONTable = JSON.parse(string)
if (JSONTable.length === Utilities.DefaultSettings.ThemeCreator.length) {
if (confirm('Are you sure you\'d like to replace this theme with the theme specified in the JSON?') === true) {
LoadThemeFromJSONBtn.previousElementSibling.value = ''
document.getElementById('ThemeCreator-Modal').close()
for (let i = 0; i < JSONTable.length; i++) {
if (JSONTable[i][0] !== "#") {
JSONTable[i] = ""
}
}
Settings.ThemeCreator = MergeObjects(JSONTable, Utilities.DefaultSettings.ThemeCreator)
Save();
console.log(JSONTable.length, JSONTable, 'applied')
document.getElementById('ThemeCreator').getElementsByTagName('button')[1].click();
}
} else {
alert('JSON is not a theme!')
}
} catch (error) {
alert('JSON is invalid!')
}
try {
let JSONTable = JSON.parse(string);
if (JSONTable.length === Utilities.DefaultSettings.ThemeCreator.length) {
if (confirm("Are you sure you'd like to replace this theme with the theme specified in the JSON?") === true) {
LoadThemeFromJSONBtn.previousElementSibling.value = '';
document.getElementById('ThemeCreator-Modal').close();
for (let i = 0; i < JSONTable.length; i++) {
if (JSONTable[i][0] !== '#') {
JSONTable[i] = '';
}
}
Settings.ThemeCreator = MergeObjects(JSONTable, Utilities.DefaultSettings.ThemeCreator);
Save();
console.log(JSONTable.length, JSONTable, 'applied');
document.getElementById('ThemeCreator').getElementsByTagName('button')[1].click();
}
} else {
alert('JSON is not a theme!');
}
} catch (error) {
alert('JSON is invalid!');
}
}
// MergeObjects function was written by ChatGPT cause I was lazy and it was awhile ago
function MergeObjects(obj1, obj2) {
var mergedObj = {};
var mergedObj = {};
// Copy the values from obj1 to the mergedObj
for (var key in obj1) {
mergedObj[key] = obj1[key];
}
// Copy the values from obj1 to the mergedObj
for (var key in obj1) {
mergedObj[key] = obj1[key];
}
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key];
}
}
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key];
}
}
return mergedObj;
return mergedObj;
}
function FormatBool(bool){
if (bool === true) { return 'enabled' }
else { return 'disabled' }
function FormatBool(bool) {
if (bool === true) {
return 'enabled';
} else {
return 'disabled';
}
}
const Manifest = chrome.runtime.getManifest()
let BuildType = "Stable"
if (Manifest.version_name !== undefined) {BuildType = "Pre-Release"}
const Manifest = chrome.runtime.getManifest();
let BuildType = 'Stable';
if (Manifest.version_name !== undefined) {
BuildType = 'Pre-Release';
}
const FooterText = document.getElementById('footer-text')
FooterText.children[0].innerHTML = `Version: v${Manifest.version} | Build Type: ${BuildType}`
const FooterText = document.getElementById('footer-text');
FooterText.children[0].innerHTML = `Version: v${Manifest.version} | Build Type: ${BuildType}`;
const CheckForUpdatesButton = document.getElementById('check-for-updates')
const CheckForUpdatesButton = document.getElementById('check-for-updates');
function CheckForUpdates() {
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates)
CheckForUpdatesButton.disabled = true
fetch('https://polyplus.vercel.app/data/version.json')
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
if (data.version === Manifest.version || Math.floor((data.version - Manifest.version) * 10) === 0) {
CheckForUpdatesButton.innerHTML = '<b>No updates available</b>'
alert('No updates available')
} else {
const NumberOfUpdatesAvailable = Math.floor((data.version - Version) * 10)
CheckForUpdatesButton.innerHTML = '<b>'+NumberOfUpdatesAvailable+' update(s) available</b>'
alert(NumberOfUpdatesAvailable + ' updates available')
}
})
.catch(error => {console.log(error)});
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates);
CheckForUpdatesButton.disabled = true;
fetch('https://polyplus.vercel.app/data/version.json')
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
if (data.version === Manifest.version || Math.floor((data.version - Manifest.version) * 10) === 0) {
CheckForUpdatesButton.innerHTML = '<b>No updates available</b>';
alert('No updates available');
} else {
const NumberOfUpdatesAvailable = Math.floor((data.version - Version) * 10);
CheckForUpdatesButton.innerHTML = '<b>' + NumberOfUpdatesAvailable + ' update(s) available</b>';
alert(NumberOfUpdatesAvailable + ' updates available');
}
})
.catch((error) => {
console.log(error);
});
}
CheckForUpdatesButton.addEventListener('click', CheckForUpdates)
CheckForUpdatesButton.addEventListener('click', CheckForUpdates);
fetch(chrome.runtime.getURL('resources/currencies.json'))
.then(response => {
if (!response.ok) {
throw new Error('Network not ok')
}
return response.json()
})
.then(data => {
const DateText = new Date(data.Date).toLocaleDateString("en-US", {day:"numeric",month:"long",year:"numeric"})
document.getElementById('IRLPriceWithCurrency-Date').innerText = DateText
})
.catch(error => {console.log(error)})
.then((response) => {
if (!response.ok) {
throw new Error('Network not ok');
}
return response.json();
})
.then((data) => {
const DateText = new Date(data.Date).toLocaleDateString('en-US', {day: 'numeric', month: 'long', year: 'numeric'});
document.getElementById('IRLPriceWithCurrency-Date').innerText = DateText;
})
.catch((error) => {
console.log(error);
});
chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlus_ReleaseNotes', 'PolyPlus_SkipUpdate'], function(result) {
const OutOfDate = result.PolyPlus_OutOfDate || false
const SkipUpdate = result.PolyPlus_SkipUpdate || null
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version
if (OutOfDate === true && SkipUpdate !== LiveVersion) {
const Banner = document.createElement('div')
Banner.classList = 'alert position-sticky p-3'
Banner.style = 'top: 30px; box-shadow: 0 0 20px 2px #000; z-index: 2000; background: rgb(163 39 39);'
Banner.innerHTML = `
chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlus_ReleaseNotes', 'PolyPlus_SkipUpdate'], function (result) {
const OutOfDate = result.PolyPlus_OutOfDate || false;
const SkipUpdate = result.PolyPlus_SkipUpdate || null;
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version;
if (OutOfDate === true && SkipUpdate !== LiveVersion) {
const Banner = document.createElement('div');
Banner.classList = 'alert position-sticky p-3';
Banner.style = 'top: 30px; box-shadow: 0 0 20px 2px #000; z-index: 2000; background: rgb(163 39 39);';
Banner.innerHTML = `
<b>New Update Available!</b>
<br>
Your Poly+ installation is out of date! If you would like to get the latest and greatest features, improvements, and bug fixes click on one of the links below to dismiss this banner!
@ -403,15 +429,15 @@ chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlu
<a href="${result.PolyPlus_ReleaseNotes}" class="btn btn-primary btn-sm w-25" target="_blank">Go to Release Notes</a>
<button id="skip-this-update" class="btn btn-warning btn-sm w-25">(Not Recommended) Skip this Update</button>
</div>
`
document.getElementById('page').insertBefore(Banner, document.getElementById('page').children[1])
`;
document.getElementById('page').insertBefore(Banner, document.getElementById('page').children[1]);
const SkipButton = document.getElementById('skip-this-update')
SkipButton.addEventListener('click', function(){
Banner.remove()
chrome.storage.local.set({'PolyPlus_SkipUpdate': result.PolyPlus_LiveVersion}, function(){
console.log('set skip update to live version: ', result.PolyPlus_LiveVersion)
})
});
}
})
const SkipButton = document.getElementById('skip-this-update');
SkipButton.addEventListener('click', function () {
Banner.remove();
chrome.storage.local.set({PolyPlus_SkipUpdate: result.PolyPlus_LiveVersion}, function () {
console.log('set skip update to live version: ', result.PolyPlus_LiveVersion);
});
});
}
});