Skip to content

Commit

Permalink
Use hashkey for localstorage
Browse files Browse the repository at this point in the history
  • Loading branch information
Jared K committed Mar 21, 2022
1 parent e612948 commit 9144b25
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 18 deletions.
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cSpell.words": [
"obsstudio"
]
}
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,15 @@ _Perfect for BRB screens!_
- Set `Refresh browser when scene becomes active`
- Video resolutions should match your canvas aspect ratio
- **Autoplay only works in OBS!**
- ~~If you want to test this in your browser:~~ Not working in v3.3.0
1. ~~Open the `obs-random-videos.html` with your browser~~
2. ~~Right-click on the image and click "Show controls"~~
3. ~~Hit the play button~~
- If you want to test this in your browser:
1. Open the `obs-random-videos.html` with your browser
2. Right-click on the image and click "Show controls"
3. Hit the play button
- Pro tip: webm videos support transparency (convert mov to webm to save on file size)

## Stuck? Or nothing happening?

1. Try hitting `Refresh cache of current page` in OBS **at least** as many time as you have videos in your playlist
1. Try hitting `Refresh cache of current page` in OBS
2. [Enable remote debugging](https://github.com/crowbartools/Firebot/wiki/Troubleshooting-Firebot-Overlay-issues-in-OBS-Studio) and open the page for the browser source
1. Open Chrome Dev tools
2. `Application` tab
Expand Down
28 changes: 20 additions & 8 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ const initMediaFiles = /** @type {string[]} */ (["{{ StringsJoin .MediaFiles "\"
const transitionVideoPath = /** @type {string} */("{{ .TransitionVideo }}");
const playOnlyOne = /** @type {boolean} */ ({{ .PlayOnlyOne }});
const loopFirstVideo = /** @type {boolean} */ ({{ .LoopFirstVideo }});
const hashKey = /** @type {string} */("{{ .HashKey }}");
// @ts-ignore
const isOBS = !!window?.obsstudio?.pluginVersion
let isTransition = true;


/**
* shuffleArr takes in an array and returns a new array in random order
* @param {any[]} originalArray any array to be shuffled
Expand All @@ -28,7 +32,7 @@ function shuffleArr(originalArray) {
* @returns {void}
*/
function storePlaylistState(state) {
localStorage.setItem('playlist', JSON.stringify(state));
localStorage.setItem(`playlist-${hashKey}`, JSON.stringify(state));
}

/**
Expand All @@ -49,9 +53,9 @@ function getNewPlaylist() {
function getPlaylist() {
let playlist = [];
try {
playlist = JSON.parse(localStorage.getItem('playlist'));
playlist = JSON.parse(localStorage.getItem(`playlist-${hashKey}`));
} catch {
console.log('playlist doesn\'t exist yet!');
console.debug('playlist doesn\'t exist yet!');
}
if (!playlist || playlist.length === 0 || typeof playlist.pop === 'undefined') {
playlist = getNewPlaylist();
Expand Down Expand Up @@ -80,13 +84,21 @@ function getNextPlaylistItem() {
const playlist = getPlaylist();
let mediaItem = playlist.pop();

console.debug({
lastPlayed: localStorage.getItem(`lastPlayed-${hashKey}`),
mediaItem,
wasLastPlayed: localStorage.getItem(`lastPlayed-${hashKey}`) === mediaItem
});

// check if we played this mediaItem last run
console.log({ lastPlayed: localStorage.getItem('lastPlayed'), mediaItem, wasLastPlayed: localStorage.getItem('lastPlayed') === mediaItem });
if (localStorage.getItem('lastPlayed') === mediaItem) {
if (localStorage.getItem(`lastPlayed-${hashKey}`) === mediaItem) {
// moves the repeated item to the end so its not skipped entirely
storePlaylistState([mediaItem].concat(playlist));
mediaItem = getNextPlaylistItem();
}
if (isOBS) {
mediaItem = `http://absolute/${mediaItem}`;
}
return mediaItem;
}

Expand All @@ -102,13 +114,13 @@ function playNext(player, nextPlayer) {
const nextMp4Source = nextPlayer.getElementsByClassName('mp4Source')[0];
const currentVideo = currentMp4Source.getAttribute('src');
if (currentVideo !== transitionVideoPath) {
localStorage.setItem('lastPlayed', currentVideo);
localStorage.setItem(`lastPlayed-${hashKey}`, currentVideo);
}

let video = localStorage.getItem('lastPlayed');
let video = localStorage.getItem(`lastPlayed-${hashKey}`);
if (!loopFirstVideo && (!transitionVideoPath || !isTransition)) {
video = getNextPlaylistItem();
console.log(`next video: ${video}`);
console.debug(`next video: ${video}`);
}

// TODO: we can use this opacity to crossfade between mediaFiles
Expand Down
28 changes: 23 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package main
import (
"bufio"
"bytes"
"crypto/md5"
_ "embed"
"encoding/hex"
"errors"
"fmt"
"io/fs"
Expand Down Expand Up @@ -35,6 +37,7 @@ type UserAnswers struct {
LoopFirstVideo bool
HaveTransitionVideo bool
TransitionVideo string
HashKey string
}

// Scripts stores javascript scripts that are later injected into templateHTML
Expand All @@ -54,8 +57,8 @@ var (
videoFileExts = []string{".mp4", ".webm", ".mpeg4", ".m4v", ".mov"}
// imagesFileExts = []string{".png", ".jpg", ".jpeg", ".gif", ".webp"}
// mediaFileExts = append(append(audioFileExts, videoFileExts...), imagesFileExts...)
mediaFileExts = append(audioFileExts, videoFileExts...)
promptDelay = 100 * time.Millisecond // helps with race conditionsin promptui
mediaFileExts = append(audioFileExts, videoFileExts...)
promptDelay = 100 * time.Millisecond // helps with race conditionsin promptui
)

func main() {
Expand Down Expand Up @@ -123,12 +126,11 @@ func getMediaFiles(currentDir string) []string {

func fixFilePath(filePath string) string {
separator := string(os.PathSeparator)
newFilePath := fmt.Sprintf("http:%sabsolute%s%s", separator+separator, separator, filePath)
if runtime.GOOS == "windows" {
separatorEscaped := strings.Repeat(separator, 2)
return strings.Replace(newFilePath, separator, separatorEscaped, -1)
return strings.Replace(filePath, separator, separatorEscaped, -1)
}
return newFilePath
return filePath
}

func askQuestions(mediaFiles []string, mainDir string) (UserAnswers, error) {
Expand All @@ -138,6 +140,7 @@ func askQuestions(mediaFiles []string, mainDir string) (UserAnswers, error) {
LoopFirstVideo: false,
HaveTransitionVideo: false,
TransitionVideo: "",
HashKey: "",
}

answers.PlayOnlyOne = showQuestion("Do you only want to play one video? (The first random video will play once and then stop)", false)
Expand All @@ -152,9 +155,24 @@ func askQuestions(mediaFiles []string, mainDir string) (UserAnswers, error) {
}
}
}
answers.HashKey = createHashFromUserAnswers(answers)
return answers, nil
}

func createHashFromUserAnswers(answers UserAnswers) string {
s := fmt.Sprintf(
"%v%v%v%s%s",
answers.PlayOnlyOne,
answers.LoopFirstVideo,
answers.HaveTransitionVideo,
answers.TransitionVideo,
strings.Join(answers.MediaFiles[:], ""))

hasher := md5.New()
hasher.Write([]byte(s))
return hex.EncodeToString(hasher.Sum(nil))
}

func removeTransitionVideo(transitionVideo string, mediaFiles []string) []string {
files := mediaFiles
for i, file := range mediaFiles {
Expand Down

0 comments on commit 9144b25

Please sign in to comment.