Initial commit

This commit is contained in:
László Károlyi 2022-02-23 22:23:56 +01:00
commit 85c6782e38
Signed by: karolyi
GPG Key ID: 2DCAF25E55735BFE
12 changed files with 507 additions and 0 deletions

11
.babelrc Normal file
View File

@ -0,0 +1,11 @@
{
"plugins": ["@babel/syntax-dynamic-import"],
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
]
]
}

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules
dist

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT+NIGGER License
Copyright (c) <2022> <László Károlyi>
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:
The above copyright notice, this permission notice and the word "NIGGER" shall be included in all copies or substantial portions of the Software.
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.

15
README.md Normal file
View File

@ -0,0 +1,15 @@
# 🚀 Welcome to your new awesome project!
This project has been created using **webpack-cli**, you can now run
```
npm run build
```
or
```
yarn build
```
to bundle your application

26
index.html Normal file
View File

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Webpack App</title>
</head>
<body>
<h1>Hello world!</h1>
<h2>Tip: Check your console</h2>
<div id="karolyimusic-webplayer">
<div class="stream-title-wrapper">-</div>
<div class="play-button-wrapper">
<div class="play-button">
<i class="fa-solid fa-play"></i>
</div>
</div>
<div class="stream-list-wrapper">
<div class="stream-channel-wrapper" data-channel-id="1">1</div>
<div class="stream-channel-wrapper" data-channel-id="2">2</div>
<div class="stream-channel-wrapper" data-channel-id="3">3</div>
</div>
</div>
<a href="/">click me</a>
</body>
</html>

35
package.json Normal file
View File

@ -0,0 +1,35 @@
{
"devDependencies": {
"@babel/plugin-syntax-dynamic-import": "^7.8.3",
"@babel/preset-env": "^7.16.11",
"@fortawesome/fontawesome-svg-core": "^1.3.0",
"@fortawesome/free-regular-svg-icons": "^6.0.0",
"@fortawesome/free-solid-svg-icons": "^6.0.0",
"@types/lodash": "^4.14.178",
"@webpack-cli/generators": "^2.4.2",
"autoprefixer": "^10.4.2",
"babel-loader": "^8.2.3",
"css-loader": "^6.6.0",
"html-webpack-plugin": "^5.5.0",
"icecast-metadata-player": "^1.11.3",
"postcss-loader": "^6.2.1",
"sass": "^1.49.8",
"sass-loader": "^12.6.0",
"style-loader": "^3.3.1",
"ts-loader": "^9.2.6",
"typescript": "^4.5.5",
"webpack": "^5.69.1",
"webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.7.4"
},
"version": "1.0.0",
"description": "karolyimusic.com webradio player",
"name": "karolyimusic-webplayer",
"scripts": {
"build": "webpack --mode=production --node-env=production",
"build:dev": "webpack --mode=development",
"build:prod": "webpack --mode=production --node-env=production",
"watch": "webpack --watch",
"serve": "webpack serve"
}
}

5
postcss.config.js Normal file
View File

@ -0,0 +1,5 @@
module.exports = {
// Add you postcss configuration here
// Learn more about it at https://github.com/webpack-contrib/postcss-loader#config-files
plugins: [["autoprefixer"]],
};

162
src/index.ts Normal file
View File

@ -0,0 +1,162 @@
import IcecastMetadataPlayer from 'icecast-metadata-player'
import { library, dom } from '@fortawesome/fontawesome-svg-core'
import { faPlay } from "@fortawesome/free-solid-svg-icons/faPlay"
import { faArrowsRotate } from "@fortawesome/free-solid-svg-icons/faArrowsRotate"
import { faPause } from "@fortawesome/free-solid-svg-icons/faPause"
import { faArrowUpRightFromSquare } from "@fortawesome/free-solid-svg-icons/faArrowUpRightFromSquare"
import {
StationItem, PlaylistHandler, Config as PhConfig
} from './playlist-handler'
import { cond } from 'lodash'
library.add(faPlay, faArrowsRotate, faPause, faArrowUpRightFromSquare)
dom.watch()
interface PlayerLocalStorage {
playing: boolean,
streamId: Number
}
interface Config {
rootElement: HTMLDivElement,
streams: Array<StationItem>
}
class RadioPlayer {
private playButton!: HTMLDivElement
private titleWrapper!: HTMLDivElement
private icyPlayer!: IcecastMetadataPlayer
private playlistHandler!: PlaylistHandler
private isLoading: boolean = false
private lastTitle: string = ''
private playerState: PlayerLocalStorage = {
playing: false,
streamId: 1,
}
private config: Config
constructor(config: Config) {
this.config = config
}
public start() {
document.addEventListener('DOMContentLoaded', (event) => {
this.declareVariables()
this.configure()
this.hookupEvents()
this.loadPlayerState()
})
}
private configure() {
this.playlistHandler = new PlaylistHandler({
rootElementClass: 'stream-list-wrapper',
playerRootElement: this.config.rootElement,
streams: this.config.streams,
channelChangeCallback: this.onChangeChannel.bind(this),
})
}
private loadPlayerState() {
try {
Object.assign(
this.playerState,
JSON.parse(localStorage.getItem('WebIcyPlayerStorage') || 'x'))
} catch (error) {
// Nothing to do here, silently fail
}
if (this.playerState.playing)
this.icyPlayer.play()
}
private onChangeChannel(channelId: number) {
console.log('channel change to', channelId, this)
this.icyPlayer.stop().then(x => {
console.log('stopped:', this.icyPlayer)
})
}
private onTitleChange(title: string) {
if (this.lastTitle == title)
return
this.titleWrapper.textContent = title ? title : '<no title>';
this.lastTitle = title
}
private markButtonLoading() {
if (this.isLoading) return
this.playButton.innerHTML =
'<i class="fa-solid fa-arrows-rotate fa-spin"></i>'
this.isLoading = true
}
private declareVariables() {
const root = this.config.rootElement
this.playButton =
<HTMLDivElement>root.getElementsByClassName('play-button')[0];
this.titleWrapper =
<HTMLDivElement>root.getElementsByClassName('stream-title-wrapper')[0]
this.icyPlayer = new IcecastMetadataPlayer(
'https://stream.tilos.hu/karolyi-mixes', {
onMetadata:
(metadata: { StreamTitle: string }) =>
this.onTitleChange(metadata.StreamTitle),
icyCharacterEncoding: 'iso-8859-2',
onLoad: this.markButtonLoading.bind(this),
onBuffer: this.markButtonLoading.bind(this),
onPlay: () => {
this.playButton.innerHTML = '<i class="fa-solid fa-pause"></i>'
this.isLoading = false;
},
onRetry: this.markButtonLoading.bind(this),
onStreamEnd: this.markButtonLoading.bind(this),
onStop: () => {
this.playButton.innerHTML = '<i class="fa-solid fa-play"></i>'
this.isLoading = false;
this.onTitleChange('-')
}
})
}
private storeState() {
localStorage.setItem(
'WebIcyPlayerStorage', JSON.stringify(this.playerState))
}
private hookupEvents() {
this.playButton.addEventListener('click', (event) => {
if (this.icyPlayer.state === 'stopped') {
this.icyPlayer.play()
this.playerState.playing = true
this.storeState()
return
}
this.icyPlayer.stop()
this.playerState.playing = false
this.storeState()
})
addEventListener('beforeunload', (event) => {
this.icyPlayer.stop()
})
}
}
const player = new RadioPlayer({
rootElement:
<HTMLDivElement>document.getElementById('karolyimusic-webplayer'),
streams: [{
streamName: 'Analog teszt stream',
listenUrl: 'https://stream.tilos.hu/analog-teszt',
externalLink: 'https://stream.tilos.hu/analog-teszt.m3u',
}, {
streamName: 'Tilos 256',
listenUrl: 'https://stream.tilos.hu/tilos',
externalLink: 'https://stream.tilos.hu/tilos.m3u',
}, {
streamName: 'Tilos 32',
listenUrl: 'https://stream.tilos.hu/tilos_32.mp3',
externalLink: 'https://stream.tilos.hu/tilos_32.mp3.m3u',
}]
})
player.start()

91
src/playlist-handler.ts Normal file
View File

@ -0,0 +1,91 @@
import { escape as _escape } from 'lodash'
interface channelChangeCallbackType {
(channelId: number): void
}
interface GetRootElementReturnType {
isExternalClicked: boolean,
clickedRoot: HTMLDivElement
}
export interface StationItem {
streamName: string,
listenUrl: string,
externalLink: string,
}
export interface Config {
rootElementClass: string,
playerRootElement: HTMLDivElement,
streams: Array<StationItem>,
channelChangeCallback: channelChangeCallbackType
}
export class PlaylistHandler {
private rootElement: HTMLDivElement
private streams!: Array<StationItem>
private config: Config
constructor(config: Config) {
this.config = config
this.rootElement =
<HTMLDivElement>config.playerRootElement.getElementsByClassName(
config.rootElementClass)[0]
this.setupChannels()
}
private getRootelement(event: MouseEvent): GetRootElementReturnType | void {
let iter_element = <Element>event.target
if (iter_element.classList.contains('stream-listen-wrapper'))
return {
clickedRoot: <HTMLDivElement>iter_element.parentElement,
isExternalClicked: false
}
let root: HTMLDivElement | void = undefined
let isExternalClicked = false
while (true) {
if (iter_element.nodeName === 'A') {
isExternalClicked = true
} else if (iter_element.nodeName === 'DIV') {
root = <HTMLDivElement>iter_element
break
}
iter_element = <Element>iter_element.parentNode
if (!iter_element) break
}
if (!root) return
return { clickedRoot: root, isExternalClicked }
}
private onClickRoot(event: MouseEvent): void {
event.preventDefault()
const result = this.getRootelement(event)
if (!result)
return
const stationId = parseInt(result.clickedRoot.dataset.channelId!)
if (result.isExternalClicked) {
open(this.config.streams[stationId - 1].externalLink)
return
}
this.config.channelChangeCallback(stationId)
}
setupChannels() {
let idx = 0
this.rootElement.innerHTML = ''
for (const item of this.config.streams) {
idx += 1
const newElement: HTMLDivElement = document.createElement('div')
newElement.classList.add('stream-channel-wrapper')
newElement.dataset.channelId = idx.toString()
newElement.innerHTML =
`<div class="stream-listen-wrapper">${_escape(item.streamName)}` +
`</div><a class="stream-external-link" href="${item.externalLink}">` +
`<i class="fa-solid fa-arrow-up-right-from-square"></i></a>`
this.rootElement.appendChild(newElement)
}
this.rootElement.addEventListener('click', this.onClickRoot.bind(this))
}
}

56
src/sass/player.scss Normal file
View File

@ -0,0 +1,56 @@
#karolyimusic-webplayer {
background-color: aliceblue;
width: 100%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
.stream-title-wrapper {
width: 100%;
border: 1px dotted red;
flex-basis: 100%;
align-self: center;
}
.play-button-wrapper {
margin-right: 1rem;
flex-basis: 5rem;
.play-button {
display: flex;
cursor: pointer;
width: 5rem;
height: 5rem;
border: .15rem dotted black;
border-radius: 100%;
justify-content: center;
svg {
&.svg-inline--fa.fa-play {
margin-left: .4rem;
}
align-self: center;
height: 50%;
width: 50%;
}
}
}
.stream-list-wrapper {
flex-basis: calc(100% - 6.3rem);
display: flex;
align-items: center;
flex-direction: row;
flex-wrap: wrap;
float: left;
// animation: ;
.stream-channel-wrapper {
flex-basis: 100%;
align-self: center;
cursor: pointer;
user-select: none;
display: flex;
.stream-listen-wrapper {
flex-basis: calc(100% - 1.2rem);
}
.stream-external-link {
flex-basis: 1.2rem;
}
}
}
}

13
tsconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "ES6",
"target": "ES5",
"jsx": "react-jsx",
"allowJs": false,
"moduleResolution": "Node",
"strictNullChecks": true,
"strictPropertyInitialization": true,
}
}

82
webpack.config.js Normal file
View File

@ -0,0 +1,82 @@
// Generated using webpack-cli https://github.com/webpack/webpack-cli
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isProduction = process.env.NODE_ENV == 'production';
// const NodePolyfillPlugin = require("node-polyfill-webpack-plugin")
const stylesHandler = 'style-loader';
const config = {
entry: [
'./src/index.ts',
'./src/sass/player.scss',
],
devtool: 'inline-source-map',
output: {
path: path.resolve(__dirname, 'dist'),
},
devServer: {
open: true,
host: 'localhost',
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
fallback: {
// make it shut up about missing nodejs plugins in the browser
util: false,
}
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
}),
// new NodePolyfillPlugin({
// excludeAliases: ['console'],
// }),
// Add your plugins here
// Learn more about plugins from https://webpack.js.org/configuration/plugins/
],
module: {
rules: [
{
test: /\.(js|jsx)$/i,
loader: 'babel-loader',
},
{
test: /\.(ts|tsx)$/i,
use: 'ts-loader',
exclude: /node_modules/,
},
{
test: /\.s[ac]ss$/i,
use: [stylesHandler, 'css-loader', 'postcss-loader', 'sass-loader'],
},
{
test: /\.css$/i,
use: [stylesHandler, 'css-loader', 'postcss-loader'],
},
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
},
// Add your rules for custom modules here
// Learn more about loaders from https://webpack.js.org/loaders/
],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
} else {
config.mode = 'development';
}
return config;
};