Skip to content

Commit b8b2725

Browse files
authored
Add Random Button plugin to CommunityScripts (#565)
1 parent 7a698b6 commit b8b2725

File tree

5 files changed

+250
-0
lines changed

5 files changed

+250
-0
lines changed
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# MIT License
2+
3+
Copyright (c) 2025 Nightyonlyy
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6+
7+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8+
9+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Stash Random Button Plugin
2+
3+
Adds a "Random" button to the image & scenes page to quickly navigate to a random scene.
4+
5+
## Features
6+
- Adds a "Random" button to the Stash UI.
7+
- Selects a random scene via GraphQL query.
8+
- Lightweight, no external dependencies.
9+
10+
## Installation
11+
12+
1. **Download the Plugin**
13+
```bash
14+
git clone https://github.com/Nightyonlyy/StashRandomButton.git
15+
```
16+
17+
2. **Copy to Stash Plugins Folder**
18+
- Move the `StashRandomButton` folder to:
19+
- Windows: `%USERPROFILE%\.stash\plugins\`
20+
- Linux/Mac: `~/.stash/plugins/`
21+
- Ensure it contains:
22+
- `random-button.js`
23+
- `random-button.yml`
24+
- `random_button.css`
25+
26+
3. **Reload Plugins**
27+
- In Stash, go to `Settings > Plugins` and click "Reload Plugins".
28+
- The button should appear on those pages.
29+
30+
## Usage
31+
Click the "Random" button in the navigation bar to jump to a random image or scene depending on the tab.
32+
33+
## Requirements
34+
- Stash version v0.27.2 or higher.
35+
36+
## Development
37+
- Written in JavaScript using the Stash Plugin API.
38+
- Edit `random-button.js` to customize and reload plugins in Stash.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
.random-btn {
2+
background-color: #ff0052;
3+
border-color: #ff0052;
4+
color: #fff;
5+
margin-left: 10px;
6+
}
7+
.random-btn:hover {
8+
background-color: #a10134;
9+
border-color: #a10134;
10+
color: #fff;
11+
}
Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
(function () {
2+
'use strict';
3+
4+
function addRandomButton() {
5+
const existingButton = document.querySelector('.random-btn');
6+
if (existingButton) {
7+
const styles = window.getComputedStyle(existingButton);
8+
return true;
9+
}
10+
11+
const navContainer = document.querySelector('.navbar-buttons.flex-row.ml-auto.order-xl-2.navbar-nav');
12+
if (!navContainer) {
13+
return false;
14+
}
15+
16+
const randomButtonContainer = document.createElement('div');
17+
randomButtonContainer.className = 'mr-2';
18+
randomButtonContainer.innerHTML = `
19+
<a href="javascript:void(0)">
20+
<button type="button" class="btn btn-primary random-btn" style="display: inline-block !important; visibility: visible !important;">Random</button>
21+
</a>
22+
`;
23+
randomButtonContainer.querySelector('button').addEventListener('click', loadRandomContent);
24+
25+
26+
if (window.location.pathname.match(/^\/(scenes|images)(?:$|\?)/)) {
27+
let refButton = document.querySelector('a[href="/scenes/new"]');
28+
if (window.location.pathname.includes('/images')) {
29+
refButton = document.querySelector('a[href="/stats"]');
30+
}
31+
if (!refButton) {
32+
refButton = navContainer.querySelector('a[href="https://opencollective.com/stashapp"]');
33+
}
34+
if (refButton) {
35+
refButton.parentElement.insertAdjacentElement('afterend', randomButtonContainer);
36+
} else {
37+
navContainer.appendChild(randomButtonContainer);
38+
}
39+
return true;
40+
}
41+
42+
if (window.location.pathname.match(/\/(scenes|images)\/\d+/)) {
43+
const refButton = navContainer.querySelector('a[href="https://opencollective.com/stashapp"]');
44+
if (refButton) {
45+
refButton.insertAdjacentElement('afterend', randomButtonContainer);
46+
} else {
47+
const firstLink = navContainer.querySelector('a');
48+
if (firstLink) {
49+
firstLink.parentElement.insertAdjacentElement('afterend', randomButtonContainer);
50+
} else {
51+
navContainer.appendChild(randomButtonContainer);
52+
}
53+
}
54+
return true;
55+
}
56+
57+
return false;
58+
}
59+
60+
function getParentHierarchy(element) {
61+
const hierarchy = [];
62+
let current = element;
63+
while (current && current !== document.body) {
64+
hierarchy.push(current.tagName + (current.className ? '.' + current.className.split(' ').join('.') : ''));
65+
current = current.parentElement;
66+
}
67+
return hierarchy.join(' > ');
68+
}
69+
70+
async function loadRandomContent() {
71+
try {
72+
const isScenes = window.location.pathname.includes('/scenes');
73+
const isImages = window.location.pathname.includes('/images');
74+
const type = isScenes ? 'scenes' : isImages ? 'images' : 'scenes';
75+
76+
const countQuery = `
77+
query Find${type.charAt(0).toUpperCase() + type.slice(1)}($filter: FindFilterType) {
78+
find${type.charAt(0).toUpperCase() + type.slice(1)}(filter: $filter) {
79+
count
80+
}
81+
}
82+
`;
83+
const countVariables = { filter: { per_page: 1 } };
84+
85+
const countResponse = await fetch('/graphql', {
86+
method: 'POST',
87+
headers: { 'Content-Type': 'application/json' },
88+
body: JSON.stringify({ query: countQuery, variables: countVariables })
89+
});
90+
91+
const countResult = await countResponse.json();
92+
if (countResult.errors) {
93+
return;
94+
}
95+
96+
const totalCount = countResult.data[`find${type.charAt(0).toUpperCase() + type.slice(1)}`].count;
97+
if (totalCount === 0) {
98+
return;
99+
}
100+
101+
const randomIndex = Math.floor(Math.random() * totalCount);
102+
const itemQuery = `
103+
query Find${type.charAt(0).toUpperCase() + type.slice(1)}($filter: FindFilterType) {
104+
find${type.charAt(0).toUpperCase() + type.slice(1)}(filter: $filter) {
105+
${type} {
106+
id
107+
}
108+
}
109+
}
110+
`;
111+
const itemVariables = {
112+
filter: { per_page: 1, page: Math.floor(randomIndex / 1) + 1 }
113+
};
114+
115+
const itemResponse = await fetch('/graphql', {
116+
method: 'POST',
117+
headers: { 'Content-Type': 'application/json' },
118+
body: JSON.stringify({ query: itemQuery, variables: itemVariables })
119+
});
120+
121+
const itemResult = await itemResponse.json();
122+
if (itemResult.errors) {
123+
return;
124+
}
125+
126+
const items = itemResult.data[`find${type.charAt(0).toUpperCase() + type.slice(1)}`][type];
127+
if (items.length === 0) {
128+
return;
129+
}
130+
131+
const itemId = items[0].id;
132+
window.location.href = `/${type}/${itemId}`;
133+
} catch (error) {
134+
console.error(error);
135+
}
136+
}
137+
138+
window.addEventListener('load', () => {
139+
addRandomButton();
140+
});
141+
142+
document.addEventListener('click', (event) => {
143+
const target = event.target.closest('a');
144+
if (target && target.href) {
145+
setTimeout(() => {
146+
addRandomButton();
147+
}, 1500);
148+
}
149+
});
150+
151+
window.addEventListener('popstate', () => {
152+
setTimeout(() => {
153+
addRandomButton();
154+
}, 1500);
155+
});
156+
157+
window.addEventListener('hashchange', () => {
158+
setTimeout(() => {
159+
addRandomButton();
160+
}, 1500);
161+
});
162+
163+
const navContainer = document.querySelector('.navbar-buttons.flex-row.ml-auto.order-xl-2.navbar-nav');
164+
if (navContainer) {
165+
const observer = new MutationObserver((mutations) => {
166+
mutations.forEach(m => {
167+
});
168+
if (!document.querySelector('.random-btn')) {
169+
addRandomButton();
170+
}
171+
});
172+
observer.observe(navContainer, { childList: true, subtree: true });
173+
} else {
174+
}
175+
176+
177+
let intervalAttempts = 0;
178+
setInterval(() => {
179+
intervalAttempts++;
180+
addRandomButton();
181+
}, intervalAttempts < 60 ? 500 : 2000);
182+
})();
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
name: RandomButton
2+
description: Adds a button to quickly switch to a random scene or image on both overview and detail pages
3+
version: 1.1.0
4+
url: https://example.com
5+
ui:
6+
requires: []
7+
javascript:
8+
- random_button.js
9+
css:
10+
- random_button.css

0 commit comments

Comments
 (0)