Merge pull request #189 from thebells1111/alby-integration

WebLN/Alby integration
This commit is contained in:
Dave Jones authored and GitHub committed 2022-08-08 13:45:35 -05:00
commit e53afefebe
6 files changed
+424 -97

No files matched your search

+3 -1
View File
@@ -16,6 +16,7 @@
"@types/redux-actions": "^2.6.1",
"@types/redux-thunk": "^2.1.0",
"apexcharts": "^3.20.0",
"canvas-confetti": "^1.5.1",
"connected-react-router": "^6.7.0",
"crypto-js": "^4.0.0",
"dotenv": "^8.2.0",
@@ -39,7 +40,8 @@
"reduxsauce": "^1.1.2",
"shortid": "^2.2.15",
"typesafe-actions": "^5.1.0",
"uuid": "^8.3.2"
"uuid": "^8.3.2",
"webln": "^0.3.0"
},
"devDependencies": {
"@babel/core": "^7.11.6",
+220
View File
@@ -0,0 +1,220 @@
import * as React from 'react'
import './styles.scss'
import { requestProvider } from 'webln'
import confetti from 'canvas-confetti'
interface IProps {
episode?: any
podcast?: any
player?: any
}
export default class Boostagram extends React.PureComponent<IProps> {
constructor(props) {
super(props)
}
state = {
satAmount: 5000,
boostagram: '',
destinations: undefined,
senderName: '',
}
componentDidMount() {
const { episode, podcast } = this.props
this.setState({
destinations:
episode?.value?.destinations || podcast?.value?.destinations,
senderName: localStorage.getItem('senderName'),
})
}
handleSatChange = (e: any) => {
this.setState({
satAmount: e.target.validity.valid
? e.target.value
: this.state.satAmount,
})
}
handleTextAreaChange = (e: any) => {
this.setState({
boostagram: e.target.value,
})
}
handleSenderNameChange = (e: any) => {
this.setState({
senderName: e.target.value,
})
localStorage.setItem('senderName', e.target.value)
}
boost = async () => {
const { episode, podcast, player } = this.props
let webln
let destinations = this.state.destinations
const getBaseRecord = () => {
return {
podcast: podcast?.title,
feedID: podcast?.id,
itemID: episode?.id,
episode: episode?.title,
ts: Math.trunc(player.current.audio.current.currentTime),
action: 'boost',
app_name: 'Podcast Index',
value_msat: 0,
value_msat_total: this.state.satAmount * 1000,
name: undefined,
message: this.state.boostagram,
sender_name: this.state.senderName,
}
}
let feesDestinations = destinations.filter((v) => v.fee)
let splitsDestinations = destinations.filter((v) => !v.fee)
let runningTotal = this.state.satAmount
try {
webln = await requestProvider()
} catch (err) {
// Tell the user what went wrong
alert(
`${err.message} \r\n Try using Alby ( https://getalby.com/ ) on the Desktop \r\n or installing Blue Wallet ( https://bluewallet.io/ ) \r\n or Blixt Wallet ( https://blixtwallet.github.io/ ) \r\n on your mobile device.`
)
}
if (webln) {
this.throwConfetti()
for (const dest of feesDestinations) {
let feeRecord = getBaseRecord()
let amount = Math.round(
(dest.split / 100) * this.state.satAmount
)
if (amount) {
runningTotal -= amount
feeRecord.name = dest.name
feeRecord.value_msat = amount * 1000
let customRecords = { '7629169': JSON.stringify(feeRecord) }
if (dest.customKey) {
customRecords[dest.customKey] = dest.customValue
}
try {
await webln.keysend({
destination: dest.address,
amount: amount,
customRecords: customRecords,
})
} catch (err) {
alert(`error with ${dest.name}: ${err.message}`)
}
}
}
for (const dest of splitsDestinations) {
let record = getBaseRecord()
let amount = Math.round((dest.split / 100) * runningTotal)
record.name = dest.name
record.value_msat = amount * 1000
if (amount >= 1) {
let customRecords = { '7629169': JSON.stringify(record) }
if (dest.customKey) {
customRecords[dest.customKey] = dest.customValue
}
try {
await webln.keysend({
destination: dest.address,
amount: amount,
customRecords: customRecords,
})
} catch (err) {
alert(`error with ${dest.name}: ${err.message}`)
}
}
}
}
}
throwConfetti() {
let end = Date.now() + 0.1 * 1000
let colors = [
'#fa6060',
'#faa560',
'#faf760',
'#b2fa60',
'#60c1fa',
'#7260fa',
'#fa60f2',
]
;(function frame() {
confetti({
particleCount: 12,
angle: 60,
spread: 75,
origin: { x: 0, y: 0.9 },
colors: colors,
})
confetti({
particleCount: 12,
angle: 120,
spread: 75,
origin: { x: 1, y: 0.9 },
colors: colors,
})
if (Date.now() < end) {
requestAnimationFrame(frame)
}
})()
}
render() {
let boostagram = <div className="boostagram-corner" />
if (this.state.destinations) {
boostagram = (
<div className="boostagram-corner">
<textarea
value={this.state.boostagram}
onChange={this.handleTextAreaChange}
placeholder="type your boostagram here"
/>
<div>
<div className="boostagram-sender-name">
<input
type="text"
value={this.state.senderName}
onChange={this.handleSenderNameChange}
onFocus={(e) => e.target.select()}
placeholder="Sender's Name"
/>
</div>
<div className="boostagram-sat-input">
<label>
<input
type="text"
pattern="[0-9]*"
value={this.state.satAmount}
onChange={this.handleSatChange}
onFocus={(e) => e.target.select()}
/>
sats
</label>
<button onClick={this.boost}>Boost</button>
</div>
</div>
</div>
)
}
return boostagram
}
}
+81
View File
@@ -0,0 +1,81 @@
.boostagram-corner{
display: flex;
margin: 0 0 8px 0;
align-items: center;
height: 90px
}
.boostagram-corner > div{
width: 260px
}
.boostagram-corner textarea{
flex-grow:1;
margin: 0 16px;
font-size: 1.2em;
border-radius: 5px;
height: 88px;
resize: none;
padding: 8px
}
.boostagram-corner label{
font-size: 1.1em;
font-weight: 550;
}
.boostagram-corner input{
border:1px solid gray;
padding: 8px;
font-size: 1.1em;
font-weight: 550;
text-align: right ;
width: 100px;
margin-right: 4px;
border-radius: 5px
}
.boostagram-corner .boostagram-sender-name{
width: 100%;
text-align: left;
margin: 0 0 8px 0;
height: 41px;
display:flex;
align-items: center;
justify-content: center;
}
.boostagram-corner .boostagram-sender-name input{
width: 100%;
text-align: left;
margin: 0
}
.boostagram-corner .boostagram-sat-input{
width: 100%;
text-align: left;
height: 41px;
display:flex;
align-items: center;
justify-content: center;
}
.boostagram-corner input:focus{
border:2px solid black;
}
.boostagram-corner button{
margin: 0 0 0 16px;
padding: 8px 12px;
width: 100px;
border: none;
background-color: #E90000;
border-radius: 5px;
color: #fff;
cursor: pointer;
font-size: 1.1em;
font-weight: 600;
}
+70 -47
View File
@@ -1,16 +1,19 @@
import * as React from 'react'
import AudioPlayer from 'react-h5-audio-player'
import sha256 from 'crypto-js/sha256';
import { AUDIO_PRELOAD_ATTRIBUTE } from "react-h5-audio-player/src/constants";
import { v4 as uuidv4 } from 'uuid';
import {Link} from "react-router-dom";
import { getISODate, getPrettyDate } from "../../utils";
import sha256 from 'crypto-js/sha256'
import { AUDIO_PRELOAD_ATTRIBUTE } from 'react-h5-audio-player/src/constants'
import { v4 as uuidv4 } from 'uuid'
import { Link } from 'react-router-dom'
import { getISODate, getPrettyDate } from '../../utils'
import 'react-h5-audio-player/src/styles.scss'
import './styles.scss'
import Boostagram from '../Boostagram'
interface IProps {
episode?: any
podcast?: any
onPlay?: any
onPause?: any
onCanPlay?: any
@@ -19,10 +22,13 @@ interface IProps {
export default class Player extends React.Component<IProps> {
static defaultProps = {
preload: "none"
preload: 'none',
}
state = {
playing: false,
satAmount: 5000,
boostagram: '',
destinations: undefined,
}
player = React.createRef<AudioPlayer>()
@@ -36,21 +42,21 @@ export default class Player extends React.Component<IProps> {
}
onCanPlay() {
if (this.props.onCanPlay){
if (this.props.onCanPlay) {
this.props.onCanPlay()
}
}
play(){
play() {
this.player.current.audio.current.play()
}
pause(){
pause() {
this.player.current.audio.current.pause()
}
onPlay() {
if (this.props.onPlay){
if (this.props.onPlay) {
this.props.onPlay()
}
this.setState({
@@ -59,7 +65,7 @@ export default class Player extends React.Component<IProps> {
}
onPause() {
if (this.props.onPause){
if (this.props.onPause) {
this.props.onPause()
}
this.setState({
@@ -68,75 +74,82 @@ export default class Player extends React.Component<IProps> {
}
componentDidMount() {
this.setMediaSessionActionHandlers();
const { episode, podcast } = this.props
this.setMediaSessionActionHandlers()
this.setState({
destinations:
episode?.value?.destinations || podcast?.value?.destinations,
})
}
componentDidUpdate() {
this.setMediaSessionMetadata();
this.setMediaSessionMetadata()
}
setMediaSessionActionHandlers() {
let navigator: any = window.navigator;
if('mediaSession' in window.navigator) {
navigator.mediaSession.setActionHandler('seekbackward', () => this.seekBackward());
navigator.mediaSession.setActionHandler('seekforward', () => this.seekForward());
let navigator: any = window.navigator
if ('mediaSession' in window.navigator) {
navigator.mediaSession.setActionHandler('seekbackward', () =>
this.seekBackward()
)
navigator.mediaSession.setActionHandler('seekforward', () =>
this.seekForward()
)
}
}
seekBackward() {
let audio = this.player.current.audio.current;
audio.currentTime = Math.max(0, audio.currentTime - 5);
let audio = this.player.current.audio.current
audio.currentTime = Math.max(0, audio.currentTime - 5)
}
seekForward() {
let audio = this.player.current.audio.current;
audio.currentTime = Math.min(audio.duration, audio.currentTime + 5);
let audio = this.player.current.audio.current
audio.currentTime = Math.min(audio.duration, audio.currentTime + 5)
}
setMediaSessionMetadata() {
let navigator: any = window.navigator;
let episode = this.props.episode;
let image: string = episode.image || episode.feedImage;
if(episode && 'mediaSession' in window.navigator) {
let navigator: any = window.navigator
let episode = this.props.episode
let image: string = episode.image || episode.feedImage
if (episode && 'mediaSession' in window.navigator) {
// @ts-ignore
navigator.mediaSession.metadata = new MediaMetadata({
title: episode.title,
artist: episode.feedTitle,
...(image &&
{
artwork: [{ src: image, sizes: '512x512'}]
}
)
});
...(image && {
artwork: [{ src: image, sizes: '512x512' }],
}),
})
}
}
render() {
const {episode, preload} = this.props
const { episode, podcast, preload } = this.props
//See if a pciguid exists in local storage. They are stored using a hash of the enclosure url as the key to avoid
//character encoding issues with what browsers accept as a valid key. If the value exists, get it. If not, create
//a new on and store it for potential use later if this enclosure is played again by this user
let enclosureHash = sha256(episode.enclosureUrl)
var pciStatsGuid = localStorage.getItem(enclosureHash)
if(pciStatsGuid === null) {
pciStatsGuid = uuidv4();
let pciStatsGuid = localStorage.getItem(enclosureHash)
if (pciStatsGuid === null) {
pciStatsGuid = uuidv4()
localStorage.setItem(enclosureHash, pciStatsGuid)
}
//Attach the pciguid value to the end of the enclosure url as a query parameter to pass back to the host/cdn for
//anonymous, yet reliable tracking stats
var pciGuid = ""
if(episode.enclosureUrl.indexOf('?') > -1) {
let pciGuid = ''
if (episode.enclosureUrl.indexOf('?') > -1) {
pciGuid = '&_ulid=' + pciStatsGuid
} else {
pciGuid = '?_ulid=' + pciStatsGuid
}
//Tag a _from on the end to give a stats hint
var fromTag = "&_from=podcastindex.org";
if(episode.enclosureUrl.indexOf('_from=') > -1) {
fromTag = "";
let fromTag = '&_from=podcastindex.org'
if (episode.enclosureUrl.indexOf('_from=') > -1) {
fromTag = ''
}
//Assemble the new url
@@ -152,15 +165,21 @@ export default class Player extends React.Component<IProps> {
<p title={episode.title}>{episode.title}</p>
</div>
<div className="player-podcast-name">
{episode.feedTitle !== undefined ?
<Link to={`/podcast/${episode.feedId}`} title={episode.feedTitle}>
{episode.feedTitle !== undefined ? (
<Link
to={`/podcast/${episode.feedId}`}
title={episode.feedTitle}
>
{`from: ${episode.feedTitle}`}
</Link>
: ""
}
) : (
''
)}
</div>
<p>
<time dateTime={getISODate(episode.datePublished)}>
<time
dateTime={getISODate(episode.datePublished)}
>
{getPrettyDate(episode.datePublished)}
</time>
</p>
@@ -178,12 +197,16 @@ export default class Player extends React.Component<IProps> {
<a
className="player-feed-button"
// href={}
style={{width: 30}}
style={{ width: 30 }}
>
{/* <img src={FeedIcon} /> */}
</a>,
]}
/>
<Boostagram
episode={episode}
podcast={podcast}
player={this.player}
/>
</div>
)
+1 -1
View File
@@ -76,7 +76,7 @@
fill: var(--color-primary);
}
}
}
}
}
@media only screen and (max-width: 520px) {
+49 -48
View File
@@ -1,7 +1,7 @@
import * as React from 'react'
import ReactLoading from 'react-loading'
import EpisodeItem from '../../../components/EpisodeItem'
import InfiniteList from "../../../components/InfiniteList";
import InfiniteList from '../../../components/InfiniteList'
import Player from '../../../components/Player'
import PodcastHeader from '../../../components/PodcastHeader'
import { fixURL, updateTitle } from '../../../utils'
@@ -90,15 +90,13 @@ export default class PodcastInfo extends React.PureComponent<IProps> {
}
onEpisodePlay(index: number) {
const {episodes, selectedEpisode} = this.state
const { episodes, selectedEpisode } = this.state
this.setState({
playing: true,
})
if (index === undefined) {
index = episodes.findIndex(
(x) => x === selectedEpisode
)
index = episodes.findIndex((x) => x === selectedEpisode)
}
const episode = episodes[index]
@@ -135,21 +133,33 @@ export default class PodcastInfo extends React.PureComponent<IProps> {
}
onEpisodeCanPlay() {
const {playing} = this.state
const { playing } = this.state
if (playing) {
this.player.current.play()
}
}
renderHeader() {
let {result} = this.state
let {title, image, artwork, author, description, categories, value, id, link, url, funding} = result
let { result } = this.state
let {
title,
image,
artwork,
author,
description,
categories,
value,
id,
link,
url,
funding,
} = result
image = artwork || image
let podcastURL = fixURL(link)
let feedURL = fixURL(url)
let donationPageURL = null
if (result.funding) // not null, exists
{
if (result.funding) {
// not null, exists
donationPageURL = funding?.url
}
@@ -171,59 +181,50 @@ export default class PodcastInfo extends React.PureComponent<IProps> {
}
renderPlayer() {
const {episodes, selectedEpisode, playing} = this.state
const preload = playing ? "auto" : "none"
const { episodes, selectedEpisode, playing, result } = this.state
const preload = playing ? 'auto' : 'none'
return (
<div className="podcast-header-player">
{
episodes.length > 0
?
<Player
ref={this.player}
episode={selectedEpisode}
onPlay={this.onEpisodePlay}
onPause={this.onEpisodePause}
onCanPlay={this.onEpisodeCanPlay}
preload={preload}
/>
:
<div/>
}
{episodes.length > 0 ? (
<Player
ref={this.player}
episode={selectedEpisode}
podcast={result}
onPlay={this.onEpisodePlay}
onPause={this.onEpisodePause}
onCanPlay={this.onEpisodeCanPlay}
preload={preload}
/>
) : (
<div />
)}
</div>
)
}
renderEpisodes() {
const {episodes} = this.state
const { episodes } = this.state
return (
<div className="episodes-list">
<h2 className="episode-header">Episodes</h2>
{
episodes.length > 0
?
<InfiniteList
data={episodes}
itemRenderer={this.renderEpisode}
/>
:
<div>
No episodes found
</div>
}
{episodes.length > 0 ? (
<InfiniteList
data={episodes}
itemRenderer={this.renderEpisode}
/>
) : (
<div>No episodes found</div>
)}
</div>
)
}
renderEpisode(item, index: number) {
let {title, image, feedImage, link, enclosureUrl, transcriptUrl, description, datePublished, value} = item
let {result} = this.state
// try to use episode image, fall back to feed images
image =
image ||
feedImage ||
result.image ||
result.artwork
image = image || feedImage || result.image || result.artwork
enclosureUrl = fixURL(enclosureUrl)
description = he.decode(description)
@@ -253,7 +254,7 @@ export default class PodcastInfo extends React.PureComponent<IProps> {
}
render() {
const {loading, result} = this.state
const { loading, result } = this.state
if ((result === undefined || result.length === 0) && !loading) {
const errorMessage = `Unknown podcast ID: ${this.props.match.params.podcastId}`
updateTitle(errorMessage)
@@ -262,8 +263,8 @@ export default class PodcastInfo extends React.PureComponent<IProps> {
if (loading) {
updateTitle('Loading podcast ...')
return (
<div className="loader-wrapper" style={{height: 300}}>
<ReactLoading type="cylon" color="#e90000"/>
<div className="loader-wrapper" style={{ height: 300 }}>
<ReactLoading type="cylon" color="#e90000" />
</div>
)
}