Compare commits

..
Author SHA1 Message Date
DispatchCommit 4193c09f68 create watchman plugin 2021-07-31 12:33:13 -04:00
90 changed files with 1162 additions and 2823 deletions

No files matched your search

-7
View File
@@ -12,9 +12,7 @@ LBRY_WEB_API=https://api.na-backend.odysee.com
LBRY_WEB_STREAMING_API=https://cdn.lbryplayer.xyz
LBRY_WEB_BUFFER_API=https://collector-service.api.lbry.tv/api/v1/events/video
COMMENT_SERVER_API=https://comments.odysee.com/api/v2
COMMENT_SERVER_NAME=Odysee
SEARCH_SERVER_API=https://lighthouse.odysee.com/search
SOCKETY_SERVER_API=wss://sockety.odysee.com/ws
THUMBNAIL_CDN_URL=https://image-processor.vanwanet.com/optimize/
WELCOME_VERSION=1.0
@@ -40,9 +38,6 @@ SITE_NAME=lbry.tv
SITE_DESCRIPTION=Meet LBRY, an open, free, and community-controlled content wonderland.
SITE_HELP_EMAIL=help@lbry.com
LOGO_TITLE=lbry.tv
## Social media
TWITTER_ACCOUNT=LBRYcom
BRANDED_SITE=odysee
## IMAGE ASSETS
YRBL_HAPPY_IMG_URL=https://cdn.lbryplayer.xyz/api/v3/streams/free/yrbl-happy/7aa50a7e5adaf48691935d55e45d697547392929/839d9a
@@ -110,5 +105,3 @@ ENABLE_UI_NOTIFICATIONS=false
#IMAGES_ENABLED=true
#FILES_ENABLED=true
#MODELS_ENABLED=true
BRANDED_SITE=odysee
+23 -37
View File
@@ -1,39 +1,4 @@
## Fixes
Issue Number:
<!-- Tip:
- Add keywords to directly close the Issue when the PR is merged.
- Skip the keyword if the Issue contains multiple items.
- https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword
-->
## What is the current behavior?
## What is the new behavior?
## Other information
<!-- If this PR contains a breaking change, please describe the impact and solution strategy for existing applications below. -->
## PR Type & Checklist
<details><summary>PR Type...</summary>
What kind of change does this PR introduce?
- [ ] Bugfix
- [ ] Feature
- [ ] Code style update (formatting)
- [ ] Refactoring (no functional changes)
- [ ] Documentation changes
- [ ] Other - Please describe:
</details>
<!---------------------------------------------------------------------------->
<details><summary>PR Checklist...</summary>
## PR Checklist
<!-- For the checkbox formatting to work properly, make sure there are no spaces on either side of the "x" -->
@@ -44,4 +9,25 @@ Please check all that apply to this PR using "x":
- [ ] I have checked that this PR does not introduce a breaking change
- [ ] This PR introduces breaking changes and I have provided a detailed explanation below
</details>
## PR Type
What kind of change does this PR introduce?
- [ ] Bugfix
- [ ] Feature
- [ ] Code style update (formatting)
- [ ] Refactoring (no functional changes)
- [ ] Documentation changes
- [ ] Other - Please describe:
## Fixes
Issue Number:
## What is the current behavior?
## What is the new behavior?
## Other information
<!-- If this PR contains a breaking change, please describe the impact and solution strategy for existing applications below. -->
+2 -11
View File
@@ -8,17 +8,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
- Show currently active playing item on playlist _community pr!_ ([#6453](https://github.com/lbryio/lbry-desktop/pull/6453))
- Add watch later to hover action for last used playlist on popup _community pr!_ ([#6274](https://github.com/lbryio/lbry-desktop/pull/6274))
- Open in desktop (web feature) _community pr!_ ([#6667](https://github.com/lbryio/lbry-desktop/pull/6667))
- Add confirmation on comment removal _community pr!_ ([#6563](https://github.com/lbryio/lbry-desktop/pull/6563))
- Show on content page if a file is part of a playlist already _community pr!_([#6393](https://github.com/lbryio/lbry-desktop/pull/6393))
### Changed
- Use Canonical Url for copy link ([#6500](https://github.com/lbryio/lbry-desktop/pull/6500))
- Use better icon for copy link ([#6485](https://github.com/lbryio/lbry-desktop/pull/6485))
- Comments load paginated ([#6390](https://github.com/lbryio/lbry-desktop/pull/6390))
- Improve twitter share _community pr!_ ([#6690](https://github.com/lbryio/lbry-desktop/pull/6690))
- Update lighthouse search api _community pr!_ ([#6731](https://github.com/lbryio/lbry-desktop/pull/6731))
- Update sockety api _community pr!_ ([#6747](https://github.com/lbryio/lbry-desktop/pull/6747))
- Use resolve for OG metadata instead of chainquery _community pr!_ ([#6787](https://github.com/lbryio/lbry-desktop/pull/6787))
- Improve twitter share _community pr!_ ([#6690](https://github.com/lbryio/lbry-desktop/pull/6690))
### Fixed
- App now supports '#' and ':' for claimId separator ([#6496](https://github.com/lbryio/lbry-desktop/pull/6496))
@@ -29,13 +27,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Fix drag / drop publish issues for web users _community pr!_ ([#6466](https://github.com/lbryio/lbry-desktop/pull/6466))
- Fix yarn copyenv on windows _community pr!_ ([#6702](https://github.com/lbryio/lbry-desktop/pull/6702))
- Fix unnecessary livestream api calls in channel page _community pr!_ ([#6652](https://github.com/lbryio/lbry-desktop/pull/6652))
- Fix desktop app fails to resolve deep links _community pr!_ ([#6779](https://github.com/lbryio/lbry-desktop/pull/6779))
- Fix wrong release date on GoogleVideo metadata _community pr!_ ([#6787](https://github.com/lbryio/lbry-desktop/pull/6787))
- Fix markdown line breaking mid word _community pr!_ ([#6805](https://github.com/lbryio/lbry-desktop/pull/6805))
- Added \ and = to reserved symbol warning _community pr!_ ([#6733](https://github.com/lbryio/lbry-desktop/pull/6733))
- Don't break words in chat + fix text overflow past 3 dot menu _community pr!_ ([#6602](https://github.com/lbryio/lbry-desktop/pull/6602))
- Fix embed shows wrong OG metadata _community pr!_ ([#6815](https://github.com/lbryio/lbry-desktop/pull/6815))
- Fix OG: "Unparsable data structure - Truncated Unicode character" _community pr!_ ([#6839](https://github.com/lbryio/lbry-desktop/pull/6839))
## [0.51.1] - [2021-06-26]
+1 -5
View File
@@ -15,8 +15,6 @@ const config = {
LBRY_WEB_BUFFER_API: process.env.LBRY_WEB_BUFFER_API,
SEARCH_SERVER_API: process.env.SEARCH_SERVER_API,
COMMENT_SERVER_API: process.env.COMMENT_SERVER_API,
COMMENT_SERVER_NAME: process.env.COMMENT_SERVER_NAME,
SOCKETY_SERVER_API: process.env.SOCKETY_SERVER_API,
WELCOME_VERSION: process.env.WELCOME_VERSION,
DOMAIN: process.env.DOMAIN,
SHARE_DOMAIN_URL: process.env.SHARE_DOMAIN_URL,
@@ -26,8 +24,6 @@ const config = {
SITE_NAME: process.env.SITE_NAME,
SITE_DESCRIPTION: process.env.SITE_DESCRIPTION,
SITE_HELP_EMAIL: process.env.SITE_HELP_EMAIL,
// SOCIAL MEDIA
TWITTER_ACCOUNT: process.env.TWITTER_ACCOUNT,
// LOGO
LOGO_TITLE: process.env.LOGO_TITLE,
FAVICON: process.env.FAVICON,
@@ -74,7 +70,7 @@ const config = {
BRANDED_SITE: process.env.BRANDED_SITE,
};
config.URL_DEV = `http://localhost:${config.WEBPACK_WEB_PORT}`;
config.URL_LOCAL = `http://localhost:${config.WEB_SERVER_PORT}`;
config.URL_DEV = `http://localhost:${config.WEBPACK_WEB_PORT}`;
module.exports = config;
+5 -17
View File
@@ -45,15 +45,9 @@ let daemon;
let lbryFirst;
const appState = {};
const PROTOCOL = 'lbry';
if (isDev && process.platform === 'win32') {
// Setting this is required to get this working in dev mode.
app.setAsDefaultProtocolClient(PROTOCOL, process.execPath, [
path.resolve(process.argv[1]),
]);
} else {
app.setAsDefaultProtocolClient(PROTOCOL);
if (process.platform !== 'linux') {
app.setAsDefaultProtocolClient('lbry');
}
app.name = 'LBRY';
@@ -155,15 +149,9 @@ if (!gotSingleInstanceLock) {
app.on('second-instance', (event, argv) => {
// Send the url to the app to navigate first, then focus
if (rendererWindow) {
// External uri (last item on argv):
const EXTERNAL_URI = (argv.length) ? argv[argv.length - 1] : '';
// Handle protocol requests for windows and linux
const platforms = (process.platform === 'win32' || process.platform === 'linux');
// Is LBRY protocol
const isProtocolURI = String(EXTERNAL_URI).startsWith(PROTOCOL + '://');
// External protocol requested:
if (platforms && isProtocolURI) {
let URI = EXTERNAL_URI;
if ((process.platform === 'win32' || process.platform === 'linux') && String(argv[1]).startsWith('lbry')) {
let URI = argv[1];
// Keep only command line / deep linked arguments
// Windows normalizes URIs when they're passed in from other apps. On Windows, this tries to
// restore the original URI that was typed.
-1
View File
@@ -38,7 +38,6 @@ declare type CommentsState = {
topLevelTotalCommentsById: { [string]: number }, // ClaimID -> total top level comments in commentron.
commentById: { [string]: Comment },
linkedCommentAncestors: { [string]: Array<string> }, // {"linkedCommentId": ["parentId", "grandParentId", ...]}
pinnedCommentsById: {}, // ClaimId -> array of pinned comment IDs
isLoading: boolean,
isLoadingByParentId: { [string]: boolean },
myComments: ?Set<string>,
+4 -4
View File
@@ -1,6 +1,6 @@
{
"name": "lbry",
"version": "0.51.2-rc.1",
"version": "0.51.1",
"description": "A browser for the LBRY network, a digital marketplace controlled by its users.",
"keywords": [
"lbry"
@@ -38,7 +38,7 @@
"build:dir": "yarn build -- --dir -c.compression=store -c.mac.identity=null",
"crossenv": "./node_modules/cross-env/dist/bin/cross-env",
"lint": "eslint 'ui/**/*.{js,jsx}' && eslint 'web/**/*.{js,jsx}' && eslint 'electron/**/*.js' && flow",
"lint-fix": "eslint --fix --quiet 'ui/**/*.{js,jsx}' && eslint --fix --quiet 'web/**/*.{js,jsx}' && eslint --fix --quiet 'electron/**/*.js'",
"lint-fix": "eslint --fix 'ui/**/*.{js,jsx}' && eslint --fix 'web/**/*.{js,jsx}' && eslint --fix 'electron/**/*.js' && flow",
"format": "prettier 'src/**/*.{js,jsx,scss,json}' --write",
"flow-defs": "flow-typed install",
"precommit": "lint-staged",
@@ -54,12 +54,12 @@
"electron-notarize": "^1.0.0",
"electron-updater": "^4.2.4",
"express": "^4.17.1",
"feed": "^4.2.2",
"if-env": "^1.0.4",
"react-datetime-picker": "^3.2.1",
"react-plastic": "^1.1.1",
"react-top-loading-bar": "^2.0.1",
"remove-markdown": "^0.3.0",
"rss": "^1.2.2",
"source-map-explorer": "^2.5.2",
"tempy": "^0.6.0",
"videojs-contrib-ads": "^6.9.0",
@@ -152,7 +152,7 @@
"imagesloaded": "^4.1.4",
"json-loader": "^0.5.4",
"lbry-format": "https://github.com/lbryio/lbry-format.git",
"lbry-redux": "lbryio/lbry-redux#e4d0662100a5f4b28bb1bf3cbc1e51b2eebab5b6",
"lbry-redux": "lbryio/lbry-redux#a327385cdf71568dbd15a17f3dcf5f4b83e0966d",
"lbryinc": "lbryio/lbryinc#8f9a58bfc8312a65614fd7327661cdcc502c4e59",
"lint-staged": "^7.0.2",
"localforage": "^1.7.1",
+7 -28
View File
@@ -209,7 +209,6 @@
"Your comment": "Your comment",
"Post --[button to submit something]--": "Post",
"Post --[noun, markdown post tab button]--": "Post",
"Livestream --[noun, livestream tab button]--": "Livestream",
"Posting...": "Posting...",
"Incompatible daemon": "Incompatible daemon",
"Incompatible daemon running": "Incompatible daemon running",
@@ -378,6 +377,8 @@
"Unfollow": "Unfollow",
"Follow @%channelName%": "Follow @%channelName%",
"Unfollow @%channelName%": "Unfollow @%channelName%",
"Item removed from %name%": "Item removed from %name%",
"Item added to %name%": "Item added to %name%",
"These LBRY Credits remain yours. It is a deposit to reserve the name and can be undone at any time.": "These LBRY Credits remain yours. It is a deposit to reserve the name and can be undone at any time.",
"Create channel": "Create channel",
"Uh oh. The flux in our Retro Encabulator must be out of whack. Try refreshing to fix it.": "Uh oh. The flux in our Retro Encabulator must be out of whack. Try refreshing to fix it.",
@@ -1186,7 +1187,6 @@
"Edit existing claim instead": "Edit existing claim instead",
"You already have a claim at %existing_uri%. Publishing will update (overwrite) your existing claim.": "You already have a claim at %existing_uri%. Publishing will update (overwrite) your existing claim.",
"Save": "Save",
"Saved": "Saved",
"Saving...": "Saving...",
"Downloading update": "Downloading update",
"complete": "complete",
@@ -1449,15 +1449,13 @@
"Best": "Best",
"Controversial": "Controversial",
"Show Replies": "Show Replies",
"Hide replies": "Hide replies",
"Unable to create comment, please try again later.": "Unable to create comment, please try again later.",
"Unable to comment. This channel has blocked you.": "Unable to comment. This channel has blocked you.",
"Unable to comment. Your channel has been blocked by an admin.": "Unable to comment. Your channel has been blocked by an admin.",
"Unable to comment. The content owner has disabled comments.": "Unable to comment. The content owner has disabled comments.",
"Please do not spam.": "Please do not spam.",
"Slow mode is on. Please wait up to %1% seconds before commenting again.": "Slow mode is on. Please wait up to %1% seconds before commenting again.",
"The comment contains contents that are blocked by %1%.": "The comment contains contents that are blocked by %1%.",
"Your user name \"%1%\" is too close to the creator's user name \"%2%\" and may cause confusion. Please use another identity.": "Your user name \"%1%\" is too close to the creator's user name \"%2%\" and may cause confusion. Please use another identity.",
"Slow mode is on. Please wait up to %value% seconds before commenting again.": "Slow mode is on. Please wait up to %value% seconds before commenting again.",
"The comment contains contents that are blocked by %author%": "The comment contains contents that are blocked by %author%",
"Your channel is still being setup, try again in a few moments.": "Your channel is still being setup, try again in a few moments.",
"Unable to delete this comment, please try again later.": "Unable to delete this comment, please try again later.",
"Unable to edit this comment, please try again later.": "Unable to edit this comment, please try again later.",
@@ -2029,22 +2027,13 @@
"Remove from Watch Later": "Remove from Watch Later",
"Add to Watch Later": "Add to Watch Later",
"Added": "Added",
"Item removed from %name%": "Item removed from %name%",
"Item added to %name%": "Item added to %name%",
"Item added to Watch Later": "Item added to Watch Later",
"Item removed from Watch Later": "Item removed from Watch Later",
"Item added to Favorites": "Item added to Favorites",
"Item removed from Favorites": "Item removed from Favorites",
"Item added to %lastCollectionName%": "Item added to %lastCollectionName%",
"Item removed from %lastCollectionName%": "Item removed from %lastCollectionName%",
"Your publish is being confirmed and will be live soon": "Your publish is being confirmed and will be live soon",
"Clear Edits": "Clear Edits",
"Something not quite right..": "Something not quite right..",
"Comments server": "Comments server",
"Default comments server (%name%)": "Default comments server (%name%)",
"Custom comments server": "Custom comments server",
"Failed to fetch comments.": "Failed to fetch comments.",
"Failed to fetch comments. Verify custom server settings.": "Failed to fetch comments. Verify custom server settings.",
"Commenting server is not set.": "Commenting server is not set.",
"Comments are not currently enabled.": "Comments are not currently enabled.",
"See All": "See All",
"Supporting content requires %lbc%": "Supporting content requires %lbc%",
"With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to see.": "With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to see.",
@@ -2075,19 +2064,9 @@
"Skip Navigation": "Skip Navigation",
"Reset": "Reset",
"Reset to original (previous) publish date": "Reset to original (previous) publish date",
"Search for something...": "Search for something...",
"Confirm Comment Deletion": "Confirm Comment Deletion",
"Remove Comment": "Remove Comment",
"Are you sure you want to remove this comment?": "Are you sure you want to remove this comment?",
"This comment has a tip associated with it which cannot be reverted.": "This comment has a tip associated with it which cannot be reverted.",
"Recent Comments": "Recent Comments",
"%title% by %channelTitle%": "%title% by %channelTitle%",
"%title% by %channelTitle% %ariaDate%": "%title% by %channelTitle% %ariaDate%",
"%title% by %channelTitle% %ariaDate%, %mediaDuration%": "%title% by %channelTitle% %ariaDate%, %mediaDuration%",
"Collapse Thread": "Collapse Thread",
"Collapse": "Collapse",
"Expand Comments": "Expand Comments",
"Expand": "Expand",
"Load More": "Load More",
"Search for something...": "Search for something...",
"--end--": "--end--"
}
+36 -167
View File
@@ -9,7 +9,7 @@ import Native from 'native';
import ElectronCookies from '@exponent/electron-cookies';
import { generateInitialUrl } from 'util/url';
// @endif
import { MATOMO_ID, MATOMO_URL } from 'config';
import { MATOMO_ID, MATOMO_URL, LBRY_WEB_BUFFER_API } from 'config';
const isProduction = process.env.NODE_ENV === 'production';
const devInternalApis = process.env.LBRY_API_URL && process.env.LBRY_API_URL.includes('dev');
@@ -17,9 +17,6 @@ const devInternalApis = process.env.LBRY_API_URL && process.env.LBRY_API_URL.inc
export const SHARE_INTERNAL = 'shareInternal';
const SHARE_THIRD_PARTY = 'shareThirdParty';
const WATCHMAN_BACKEND_ENDPOINT = 'https://watchman.na-backend.odysee.com/reports/playback';
const SEND_DATA_TO_WATCHMAN_INTERVAL = 10; // in seconds
// @if TARGET='app'
if (isProduction) {
ElectronCookies.enable({
@@ -40,8 +37,7 @@ type Analytics = {
tagFollowEvent: (string, boolean, ?string) => void,
playerLoadedEvent: (?boolean) => void,
playerStartedEvent: (?boolean) => void,
videoStartEvent: (string, number, string, number, string, any) => void,
videoIsPlaying: (boolean, any) => void,
videoStartEvent: (string, number) => void,
videoBufferEvent: (
StreamClaim,
{
@@ -53,7 +49,7 @@ type Analytics = {
playerPoweredBy: string,
readyState: number,
}
) => Promise<any>,
) => void,
adsFetchedEvent: () => void,
adsReceivedEvent: (any) => void,
adsErrorEvent: (any) => void,
@@ -80,167 +76,7 @@ if (window.localStorage.getItem(SHARE_INTERNAL) === 'true') internalAnalyticsEna
// if (window.localStorage.getItem(SHARE_THIRD_PARTY) === 'true') thirdPartyAnalyticsEnabled = true;
// @endif
/**
* Determine the mobile device type viewing the data
* This function returns one of 'and' (Android), 'ios', or 'web'.
*
* @returns {String}
*/
function getDeviceType() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android/i.test(userAgent)) {
return 'and';
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return 'ios';
}
// default as web, this can be optimized
return 'web';
}
// variables initialized for watchman
let amountOfBufferEvents = 0;
let amountOfBufferTimeInMS = 0;
let videoType, userId, claimUrl, playerPoweredBy, videoPlayer;
let lastSentTime;
// calculate data for backend, send them, and reset buffer data for next interval
async function sendAndResetWatchmanData() {
if (!userId) {
return 'Can only be used with a user id';
}
let timeSinceLastIntervalSend = new Date() - lastSentTime;
lastSentTime = new Date();
let protocol;
if (videoType === 'application/x-mpegURL') {
protocol = 'hls';
} else {
protocol = 'stb';
}
// current position in video in MS
const positionInVideo = Math.round(videoPlayer.currentTime()) * 1000;
// get the duration marking the time in the video for relative position calculation
const totalDurationInSeconds = Math.round(videoPlayer.duration());
// build object for watchman backend
const objectToSend = {
rebuf_count: amountOfBufferEvents,
rebuf_duration: amountOfBufferTimeInMS,
url: claimUrl.replace('lbry://', ''),
device: getDeviceType(),
duration: timeSinceLastIntervalSend,
protocol,
player: playerPoweredBy,
user_id: userId.toString(),
position: Math.round(positionInVideo),
rel_position: Math.round((positionInVideo / (totalDurationInSeconds * 1000)) * 100),
};
// post to watchman
await sendWatchmanData(objectToSend);
// reset buffer data
amountOfBufferEvents = 0;
amountOfBufferTimeInMS = 0;
}
let watchmanInterval;
// clear watchman interval and mark it as null (when video paused)
function stopWatchmanInterval() {
clearInterval(watchmanInterval);
watchmanInterval = null;
}
// creates the setInterval that will run send to watchman on recurring basis
function startWatchmanIntervalIfNotRunning() {
if (!watchmanInterval) {
// instantiate the first time to calculate duration from
lastSentTime = new Date();
// only set an interval if analytics are enabled and is prod
if (internalAnalyticsEnabled && isProduction) {
watchmanInterval = setInterval(sendAndResetWatchmanData, 1000 * SEND_DATA_TO_WATCHMAN_INTERVAL);
}
}
}
// post data to the backend
async function sendWatchmanData(body) {
try {
const response = await fetch(WATCHMAN_BACKEND_ENDPOINT, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
return response;
} catch (err) {
console.log('ERROR FROM WATCHMAN BACKEND');
console.log(err);
}
}
const analytics: Analytics = {
// receive buffer events from tracking plugin and jklj
videoBufferEvent: async (claim, data) => {
amountOfBufferEvents = amountOfBufferEvents + 1;
amountOfBufferTimeInMS = amountOfBufferTimeInMS + data.bufferDuration;
},
onDispose: () => {
stopWatchmanInterval();
},
/**
* Is told whether video is being started or paused, and adjusts interval accordingly
* @param {boolean} isPlaying - Whether video was started or paused
* @param {object} passedPlayer - VideoJS Player object
*/
videoIsPlaying: (isPlaying, passedPlayer) => {
let playerIsSeeking = false;
// have to use this because videojs pauses/unpauses during seek
// sometimes the seeking function isn't populated yet so check for it as well
if (passedPlayer && passedPlayer.seeking) {
playerIsSeeking = passedPlayer.seeking();
}
// if being paused, and not seeking, send existing data and stop interval
if (!isPlaying && !playerIsSeeking) {
sendAndResetWatchmanData();
stopWatchmanInterval();
// if being told to pause, and seeking, send and restart interval
} else if (!isPlaying && playerIsSeeking) {
sendAndResetWatchmanData();
stopWatchmanInterval();
startWatchmanIntervalIfNotRunning();
// is being told to play, and seeking, don't do anything,
// assume it's been started already from pause
} else if (isPlaying && playerIsSeeking) {
// start but not a seek, assuming a start from paused content
} else if (isPlaying && !playerIsSeeking) {
startWatchmanIntervalIfNotRunning();
}
},
videoStartEvent: (claimId, duration, poweredBy, passedUserId, canonicalUrl, passedPlayer) => {
// populate values for watchman when video starts
userId = passedUserId;
claimUrl = canonicalUrl;
playerPoweredBy = poweredBy;
videoType = passedPlayer.currentSource().type;
videoPlayer = passedPlayer;
sendPromMetric('time_to_start', duration);
sendMatomoEvent('Media', 'TimeToStart', claimId, duration);
},
error: (message) => {
return new Promise((resolve) => {
if (internalAnalyticsEnabled && isProduction) {
@@ -359,6 +195,39 @@ const analytics: Analytics = {
Lbryio.call('content_tags', 'sync', params);
}
},
videoStartEvent: (claimId, duration) => {
sendPromMetric('time_to_start', duration);
sendMatomoEvent('Media', 'TimeToStart', claimId, duration);
},
videoBufferEvent: (claim, data) => {
sendMatomoEvent('Media', 'BufferTimestamp', claim.claim_id, data.timeAtBuffer);
if (LBRY_WEB_BUFFER_API) {
fetch(LBRY_WEB_BUFFER_API, {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
device: 'web',
type: 'buffering',
client: data.userId,
data: {
url: claim.canonical_url,
position: data.timeAtBuffer,
duration: data.bufferDuration,
player: data.playerPoweredBy,
readyState: data.readyState,
stream_duration: data.duration,
stream_bitrate: data.bitRate,
},
}),
});
}
},
adsFetchedEvent: () => {
sendMatomoEvent('Media', 'AdsFetched');
},
+2 -11
View File
@@ -4,13 +4,6 @@ import { COMMENT_SERVER_API } from 'config';
const Comments = {
url: COMMENT_SERVER_API,
enabled: Boolean(COMMENT_SERVER_API),
isCustomServer: false,
setServerUrl: (customUrl: ?string) => {
Comments.url = customUrl === undefined ? COMMENT_SERVER_API : customUrl;
Comments.enabled = Boolean(Comments.url);
Comments.isCustomServer = Comments.url !== COMMENT_SERVER_API;
},
moderation_block: (params: ModerationBlockParams) => fetchCommentsApi('moderation.Block', params),
moderation_unblock: (params: ModerationBlockParams) => fetchCommentsApi('moderation.UnBlock', params),
@@ -38,10 +31,8 @@ const Comments = {
};
function fetchCommentsApi(method: string, params: {}) {
if (!Comments.url) {
return Promise.reject(new Error('Commenting server is not set.'));
} else if (!Comments.enabled) {
return Promise.reject('Comments are not currently enabled.'); // eslint-disable-line
if (!Comments.enabled) {
return Promise.reject('Comments are not currently enabled'); // eslint-disable-line
}
const url = `${Comments.url}?m=${method}`;
-7
View File
@@ -48,11 +48,9 @@ const NagDegradedPerformance = lazyImport(() =>
import('web/component/nag-degraded-performance' /* webpackChunkName: "secondary" */)
);
const NagNoUser = lazyImport(() => import('web/component/nag-no-user' /* webpackChunkName: "nag-no-user" */));
const NagSunset = lazyImport(() => import('web/component/nag-sunset' /* webpackChunkName: "nag-no-user" */));
const YoutubeWelcome = lazyImport(() =>
import('web/component/youtubeReferralWelcome' /* webpackChunkName: "secondary" */)
);
// @endif
const SyncFatalError = lazyImport(() => import('component/syncFatalError' /* webpackChunkName: "syncFatalError" */));
@@ -164,14 +162,12 @@ function App(props: Props) {
const [upgradeNagClosed, setUpgradeNagClosed] = useState(false);
const [resolvedSubscriptions, setResolvedSubscriptions] = useState(false);
const [sidebarOpen] = usePersistedState('sidebar', true);
const [seenSunsestMessage, setSeenSunsetMessage] = usePersistedState('lbrytv-sunset', false);
const showUpgradeButton =
(autoUpdateDownloaded || (process.platform === 'linux' && isUpgradeAvailable)) && !upgradeNagClosed;
// referral claiming
const referredRewardAvailable = rewards && rewards.some((reward) => reward.reward_type === REWARDS.TYPE_REFEREE);
const urlParams = new URLSearchParams(search);
const rawReferrerParam = urlParams.get('r');
const fromLbrytvParam = urlParams.get('sunset');
const sanitizedReferrerParam = rawReferrerParam && rawReferrerParam.replace(':', '#');
const shouldHideNag = pathname.startsWith(`/$/${PAGES.EMBED}`) || pathname.startsWith(`/$/${PAGES.AUTH_VERIFY}`);
const userId = user && user.id;
@@ -464,9 +460,6 @@ function App(props: Props) {
<YoutubeWelcome />
{!SIMPLE_SITE && !shouldHideNag && <OpenInAppLink uri={uri} />}
{!shouldHideNag && <NagContinueFirstRun />}
{fromLbrytvParam && !seenSunsestMessage && !shouldHideNag && (
<NagSunset email={hasVerifiedEmail} onClose={() => setSeenSunsetMessage(true)} />
)}
{(lbryTvApiStatus === STATUS_DEGRADED || lbryTvApiStatus === STATUS_FAILING) && !shouldHideNag && (
<NagDegradedPerformance onClose={() => setLbryTvApiStatus(STATUS_OK)} />
)}
+4 -10
View File
@@ -1,17 +1,11 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import CollectionAddButton from './view';
import { makeSelectClaimForUri, makeSelectClaimUrlInCollection } from 'lbry-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const permanentUrl = claim && claim.permanent_url;
return {
claim,
isSaved: makeSelectClaimUrlInCollection(permanentUrl)(state),
};
};
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
});
export default connect(select, {
doOpenModal,
@@ -11,11 +11,10 @@ type Props = {
fileAction?: boolean,
type?: boolean,
claim: Claim,
isSaved: boolean,
};
export default function CollectionAddButton(props: Props) {
const { doOpenModal, uri, fileAction, type = 'playlist', claim, isSaved } = props;
const { doOpenModal, uri, fileAction, type = 'playlist', claim } = props;
// $FlowFixMe
const streamType = (claim && claim.value && claim.value.stream_type) || '';
@@ -26,9 +25,9 @@ export default function CollectionAddButton(props: Props) {
<Button
button={fileAction ? undefined : 'alt'}
className={classnames({ 'button--file-action': fileAction })}
icon={fileAction ? (!isSaved ? ICONS.ADD : ICONS.STACK) : ICONS.LIBRARY}
icon={fileAction ? ICONS.ADD : ICONS.LIBRARY}
iconSize={fileAction ? 22 : undefined}
label={uri ? (!isSaved ? __('Save') : __('Saved')) : __('New List')}
label={uri ? __('Save') : __('New List')}
requiresAuth={IS_WEB}
title={__('Add this claim to a list')}
onClick={(e) => {
-12
View File
@@ -47,7 +47,6 @@ type Props = {
searchOptions?: any,
collectionId?: string,
showNoSourceClaims?: boolean,
onClick?: (e: any, index?: number) => void,
};
export default function ClaimList(props: Props) {
@@ -56,7 +55,6 @@ export default function ClaimList(props: Props) {
uris,
headerAltControls,
loading,
id,
persistedStorageKey,
empty,
defaultSort,
@@ -82,7 +80,6 @@ export default function ClaimList(props: Props) {
searchOptions,
collectionId,
showNoSourceClaims,
onClick,
} = props;
const [currentSort, setCurrentSort] = usePersistedState(persistedStorageKey, SORT_NEW);
@@ -110,12 +107,6 @@ export default function ClaimList(props: Props) {
setCurrentSort(currentSort === SORT_NEW ? SORT_OLD : SORT_NEW);
}
function handleClaimClicked(e, index) {
if (onClick) {
onClick(e, index);
}
}
useEffect(() => {
const handleScroll = debounce((e) => {
if (page && pageSize && onScrollBottom) {
@@ -200,8 +191,6 @@ export default function ClaimList(props: Props) {
{injectedItem && index === 4 && <li>{injectedItem}</li>}
<ClaimPreview
uri={uri}
containerId={id}
indexInContainer={index}
type={type}
active={activeUri && uri === activeUri}
hideMenu={hideMenu}
@@ -220,7 +209,6 @@ export default function ClaimList(props: Props) {
return claim.name.length === 24 && !claim.name.includes(' ') && claim.value.author === 'Spee.ch';
}}
live={resolveLive(index)}
onClick={handleClaimClicked}
/>
</React.Fragment>
))}
+2 -2
View File
@@ -106,7 +106,7 @@ function ClaimListDiscover(props: Props) {
claimType,
pageSize,
defaultClaimType,
streamType = SIMPLE_SITE ? [CS.FILE_VIDEO, CS.FILE_AUDIO] : undefined,
streamType = SIMPLE_SITE ? CS.FILE_VIDEO : undefined,
defaultStreamType = SIMPLE_SITE ? CS.FILE_VIDEO : undefined, // add param for DEFAULT_STREAM_TYPE
freshness,
defaultFreshness = CS.FRESH_WEEK,
@@ -319,7 +319,7 @@ function ClaimListDiscover(props: Props) {
}
if (streamTypeParam && streamTypeParam !== CS.CONTENT_ALL && claimType !== CS.CLAIM_CHANNEL) {
options.stream_types = typeof streamTypeParam === 'string' ? [streamTypeParam] : streamTypeParam;
options.stream_types = [streamTypeParam];
}
if (claimTypeParam) {
+7 -12
View File
@@ -8,7 +8,6 @@ import {
makeSelectCollectionIsMine,
COLLECTIONS_CONSTS,
makeSelectEditedCollectionForId,
makeSelectClaimIsMine,
} from 'lbry-redux';
import { makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { doChannelMute, doChannelUnmute } from 'redux/actions/blocked';
@@ -25,6 +24,7 @@ import {
makeSelectChannelIsAdminBlocked,
} from 'redux/selectors/comments';
import { doToast } from 'redux/actions/notifications';
import { makeSelectSigningIsMine } from 'redux/selectors/content';
import { doChannelSubscribe, doChannelUnsubscribe } from 'redux/actions/subscriptions';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
@@ -45,18 +45,12 @@ const select = (state, props) => {
contentClaim,
contentSigningChannel,
contentChannelUri,
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
hasClaimInWatchLater: makeSelectCollectionForIdHasClaimUrl(
COLLECTIONS_CONSTS.WATCH_LATER_ID,
contentPermanentUri
)(state),
hasClaimInFavorites: makeSelectCollectionForIdHasClaimUrl(
COLLECTIONS_CONSTS.FAVORITES_ID,
contentPermanentUri
)(state),
claimIsMine: makeSelectSigningIsMine(props.uri)(state),
hasClaimInWatchLater: makeSelectCollectionForIdHasClaimUrl(COLLECTIONS_CONSTS.WATCH_LATER_ID, contentPermanentUri)(state),
hasClaimInCustom: makeSelectCollectionForIdHasClaimUrl(COLLECTIONS_CONSTS.FAVORITES_ID, contentPermanentUri)(state),
channelIsMuted: makeSelectChannelIsMuted(contentChannelUri)(state),
channelIsBlocked: makeSelectChannelIsBlocked(contentChannelUri)(state),
fileInfo: makeSelectFileInfoForUri(contentPermanentUri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
isSubscribed: makeSelectIsSubscribed(contentChannelUri, true)(state),
channelIsAdminBlocked: makeSelectChannelIsAdminBlocked(props.uri)(state),
isAdmin: selectHasAdminChannel(state),
@@ -84,7 +78,8 @@ const perform = (dispatch) => ({
doChannelUnmute: (channelUri) => dispatch(doChannelUnmute(channelUri)),
doCommentModBlock: (channelUri) => dispatch(doCommentModBlock(channelUri)),
doCommentModUnBlock: (channelUri) => dispatch(doCommentModUnBlock(channelUri)),
doCommentModBlockAsAdmin: (commenterUri, blockerId) => dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId)),
doCommentModBlockAsAdmin: (commenterUri, blockerId) =>
dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId)),
doCommentModUnBlockAsAdmin: (commenterUri, blockerId) =>
dispatch(doCommentModUnBlockAsAdmin(commenterUri, blockerId)),
doChannelSubscribe: (subscription) => dispatch(doChannelSubscribe(subscription)),
+25 -26
View File
@@ -12,7 +12,7 @@ import { useHistory } from 'react-router';
import { buildURI, parseURI, COLLECTIONS_CONSTS } from 'lbry-redux';
const SHARE_DOMAIN = SHARE_DOMAIN_URL || URL;
const PAGE_VIEW_QUERY = 'view';
const PAGE_VIEW_QUERY = `view`;
const EDIT_PAGE = 'edit';
type SubscriptionArgs = {
@@ -42,7 +42,7 @@ type Props = {
doCommentModUnBlockAsAdmin: (string, string) => void,
doCollectionEdit: (string, any) => void,
hasClaimInWatchLater: boolean,
hasClaimInFavorites: boolean,
hasClaimInCustom: boolean,
claimInCollection: boolean,
collectionId: string,
isMyCollection: boolean,
@@ -80,7 +80,7 @@ function ClaimMenuList(props: Props) {
doCommentModUnBlockAsAdmin,
doCollectionEdit,
hasClaimInWatchLater,
hasClaimInFavorites,
hasClaimInCustom,
collectionId,
isMyCollection,
doToast,
@@ -105,6 +105,8 @@ function ClaimMenuList(props: Props) {
: isSubscribed
? __('Unfollow')
: __('Follow');
const lastCollectionName = 'Favorites';
const lastCollectionId = COLLECTIONS_CONSTS.FAVORITES_ID;
const { push, replace } = useHistory();
if (!claim) {
@@ -280,23 +282,21 @@ function ClaimMenuList(props: Props) {
{/* WATCH LATER */}
<MenuItem
className="comment__menu-option"
onSelect={() =>
handleAdd(hasClaimInWatchLater, __('Watch Later'), COLLECTIONS_CONSTS.WATCH_LATER_ID)
}
onSelect={() => handleAdd(hasClaimInWatchLater, 'Watch Later', COLLECTIONS_CONSTS.WATCH_LATER_ID)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInWatchLater ? ICONS.DELETE : ICONS.TIME} />
{hasClaimInWatchLater ? __('In Watch Later') : __('Watch Later')}
</div>
</MenuItem>
{/* FAVORITES LIST */}
{/* CUSTOM LIST */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInFavorites, __('Favorites'), COLLECTIONS_CONSTS.FAVORITES_ID)}
onSelect={() => handleAdd(hasClaimInCustom, lastCollectionName, lastCollectionId)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInFavorites ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInFavorites ? __('In Favorites') : __('Favorites')}
<Icon aria-hidden icon={hasClaimInCustom ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInCustom ? __(`In ${lastCollectionName}`) : __(`${lastCollectionName}`)}
</div>
</MenuItem>
{/* CURRENTLY ONLY SUPPORT PLAYLISTS FOR PLAYABLE; LATER DIFFERENT TYPES */}
@@ -378,30 +378,22 @@ function ClaimMenuList(props: Props) {
</div>
</MenuItem>
)}
{showDelete && (
<MenuItem className="comment__menu-option" onSelect={handleDelete}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete')}
</div>
</MenuItem>
)}
</>
)}
{showDelete && (
<MenuItem className="comment__menu-option" onSelect={handleDelete}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete')}
</div>
</MenuItem>
)}
</>
)}
</>
)}
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleCopyLink}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.COPY_LINK} />
{__('Copy Link')}
</div>
</MenuItem>
{isChannelPage && IS_WEB && rssUrl && (
<MenuItem className="comment__menu-option" onSelect={handleCopyRssLink}>
<div className="menu__link">
@@ -411,6 +403,13 @@ function ClaimMenuList(props: Props) {
</MenuItem>
)}
<MenuItem className="comment__menu-option" onSelect={handleCopyLink}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SHARE} />
{__('Copy Link')}
</div>
</MenuItem>
{!claimIsMine && !isMyCollection && (
<MenuItem className="comment__menu-option" onSelect={handleReportContent}>
<div className="menu__link">
+20 -39
View File
@@ -29,7 +29,6 @@ import ClaimPreviewNoContent from './claim-preview-no-content';
import { ENABLE_NO_SOURCE_CLAIMS } from 'config';
import Button from 'component/button';
import * as ICONS from 'constants/icons';
import { CONTAINER_ID } from 'constants/navigation';
const AbandonedChannelPreview = lazyImport(() =>
import('component/abandonedChannelPreview' /* webpackChunkName: "abandonedChannelPreview" */)
@@ -46,7 +45,7 @@ type Props = {
reflectingProgress?: any, // fxme
resolveUri: (string) => void,
isResolvingUri: boolean,
history: { push: (string | any) => void },
history: { push: (string) => void },
title: string,
nsfw: boolean,
placeholder: string,
@@ -66,7 +65,7 @@ type Props = {
actions: boolean | Node | string | number,
properties: boolean | Node | string | number | ((Claim) => Node),
empty?: Node,
onClick?: (e: any, index?: number) => any,
onClick?: (any) => any,
streamingUrl: ?string,
getFile: (string) => void,
customShouldHide?: (Claim) => boolean,
@@ -89,8 +88,6 @@ type Props = {
disableNavigation?: boolean,
mediaDuration?: string,
date?: any,
containerId?: string, // ID or name of the container (e.g. ClaimList, HOC, etc.) that this is in.
indexInContainer?: number, // The index order of this component within 'containerId'.
};
const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
@@ -152,8 +149,6 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
isCollectionMine,
collectionUris,
disableNavigation,
containerId,
indexInContainer,
} = props;
const isCollection = claim && claim.value_type === 'collection';
const collectionClaimId = isCollection && claim && claim.claim_id;
@@ -202,26 +197,14 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
let ariaLabelData = isChannelUri ? title : formatClaimPreviewTitle(title, channelTitle, date, mediaDuration);
let navigateUrl = formatLbryUrlForWeb((claim && claim.canonical_url) || uri || '/');
let navigateSearch = new URLSearchParams();
if (listId) {
navigateSearch.set(COLLECTIONS_CONSTS.COLLECTION_ID, listId);
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, listId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
}
const handleNavLinkClick = (e) => {
if (onClick) {
onClick(e, indexInContainer);
}
e.stopPropagation();
};
const navLinkProps = {
to: {
pathname: navigateUrl,
search: navigateSearch.toString() ? '?' + navigateSearch.toString() : '',
state: containerId ? { [CONTAINER_ID]: containerId } : undefined,
},
onClick: (e) => handleNavLinkClick(e),
onAuxClick: (e) => handleNavLinkClick(e),
to: navigateUrl,
onClick: (e) => e.stopPropagation(),
};
// do not block abandoned and nsfw claims if showUserBlocked is passed
@@ -267,15 +250,11 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
function handleOnClick(e) {
if (onClick) {
onClick(e, indexInContainer);
onClick(e);
}
if (claim && !pending && !disableNavigation) {
history.push({
pathname: navigateUrl,
search: navigateSearch.toString() ? '?' + navigateSearch.toString() : '',
state: containerId ? { [CONTAINER_ID]: containerId } : undefined,
});
history.push(navigateUrl);
}
}
@@ -363,21 +342,23 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
{!pending ? (
<NavLink aria-hidden tabIndex={-1} {...navLinkProps}>
<FileThumbnail thumbnail={thumbnailUrl}>
<div className="claim-preview__hover-actions">
{isPlayable && <FileWatchLaterLink focusable={false} uri={uri} />}
</div>
<div className="claim-preview__hover-actions">
{/* @if TARGET='app' */}
{claim && !isCollection && (
{/* @if TARGET='app' */}
{claim && !isCollection && (
<div className="claim-preview__hover-actions">
<FileDownloadLink focusable={false} uri={canonicalUrl} hideOpenButton hideDownloadStatus />
)}
{/* @endif */}
</div>
</div>
)}
{/* @endif */}
{!isLivestream && (
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} small={type === 'small'} properties={liveProperty} />
</div>
)}
{isPlayable && (
<div className="claim-preview__hover-actions">
<FileWatchLaterLink focusable={false} uri={uri} />
</div>
)}
</FileThumbnail>
</NavLink>
) : (
+12 -11
View File
@@ -208,18 +208,19 @@ function ClaimPreviewTile(props: Props) {
<FileThumbnail thumbnail={thumbnailUrl} allowGifs>
{!isChannel && (
<React.Fragment>
<div className="claim-preview__hover-actions">
{isPlayable && (
<FileWatchLaterLink focusable={false} uri={uri} />
)}
</div>
<div className="claim-preview__hover-actions">
{/* @if TARGET='app' */}
{isStream && (
{/* @if TARGET='app' */}
{isStream && (
<div className="claim-preview__hover-actions">
<FileDownloadLink focusable={false} uri={canonicalUrl} hideOpenButton />
)}
{/* @endif */}
</div>
</div>
)}
{/* @endif */}
{isPlayable && (
<div className="claim-preview__hover-actions">
<FileWatchLaterLink focusable={false} uri={uri} />
</div>
)}
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} properties={liveProperty || properties} />
+2 -7
View File
@@ -159,12 +159,6 @@ function ClaimTilesDiscover(props: Props) {
new Set(mutedUris.concat(blockedUris).map((uri) => splitBySeparator(uri)[1]))
);
const liveUris = [];
let streamTypesParam;
if (streamTypes) {
streamTypesParam = streamTypes;
} else if (SIMPLE_SITE && !hasNoSource && streamTypes !== null) {
streamTypesParam = [CS.FILE_VIDEO, CS.FILE_AUDIO];
}
const [prevUris, setPrevUris] = React.useState([]);
@@ -198,7 +192,8 @@ function ClaimTilesDiscover(props: Props) {
channel_ids: channelIds || [],
not_channel_ids: mutedAndBlockedChannelIds,
order_by: orderBy || ['trending_group', 'trending_mixed'],
stream_types: streamTypesParam,
stream_types:
streamTypes === null ? undefined : SIMPLE_SITE && !hasNoSource ? [CS.FILE_VIDEO, CS.FILE_AUDIO] : undefined,
};
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
+15 -24
View File
@@ -131,7 +131,6 @@ export function CommentCreate(props: Props) {
return;
}
// if comment post didn't work, but tip was already made, try again to create comment
if (commentFailure && tipAmount === successTip.tipAmount) {
handleCreateComment(successTip.txid);
return;
@@ -148,19 +147,6 @@ export function CommentCreate(props: Props) {
const activeChannelName = activeChannelClaim && activeChannelClaim.name;
const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
// setup variables for tip API
let channelClaimId, tipChannelName;
// if there is a signing channel it's on a file
if (claim.signing_channel) {
channelClaimId = claim.signing_channel.claim_id;
tipChannelName = claim.signing_channel.name;
// otherwise it's on the channel page
} else {
channelClaimId = claim.claim_id;
tipChannelName = claim.name;
}
setIsSubmitting(true);
if (activeTab === TAB_LBC) {
@@ -174,14 +160,6 @@ export function CommentCreate(props: Props) {
setTimeout(() => {
handleCreateComment(txid);
}, 1500);
doToast({
message: __("You sent %tipAmount% LBRY Credits as a tip to %tipChannelName%, I'm sure they appreciate it!", {
tipAmount: tipAmount, // force show decimal places
tipChannelName,
}),
});
setSuccessTip({ txid, tipAmount });
},
() => {
@@ -190,14 +168,27 @@ export function CommentCreate(props: Props) {
}
);
} else {
// setup variables for tip API
let channelClaimId, tipChannelName;
// if there is a signing channel it's on a file
if (claim.signing_channel) {
channelClaimId = claim.signing_channel.claim_id;
tipChannelName = claim.signing_channel.name;
// otherwise it's on the channel page
} else {
channelClaimId = claim.claim_id;
tipChannelName = claim.name;
}
const sourceClaimId = claim.claim_id;
const roundedAmount = Math.round(tipAmount * 100) / 100;
Lbryio.call(
'customer',
'tip',
{ // round to deal with floating point precision
amount: Math.round(100 * roundedAmount), // convert from dollars to cents
{
amount: 100 * roundedAmount, // convert from dollars to cents
creator_channel_name: tipChannelName, // creator_channel_name
creator_channel_claim_id: channelClaimId,
tipper_channel_name: activeChannelName,
+3 -42
View File
@@ -13,7 +13,6 @@ import usePersistedState from 'effects/use-persisted-state';
import { ENABLE_COMMENT_REACTIONS } from 'config';
import Empty from 'component/common/empty';
import debounce from 'util/debounce';
import { useIsMobile } from 'effects/use-screensize';
const DEBOUNCE_SCROLL_HANDLER_MS = 200;
@@ -75,8 +74,6 @@ function CommentList(props: Props) {
const DEFAULT_SORT = ENABLE_COMMENT_REACTIONS ? SORT_BY.POPULARITY : SORT_BY.NEWEST;
const [sort, setSort] = usePersistedState('comment-sort-by', DEFAULT_SORT);
const [page, setPage] = React.useState(0);
const isMobile = useIsMobile();
const [expandedComments, setExpandedComments] = React.useState(!isMobile);
const totalFetchedComments = allCommentIds ? allCommentIds.length : 0;
// Display comments immediately if not fetching reactions
@@ -194,7 +191,7 @@ function CommentList(props: Props) {
}
const handleCommentScroll = debounce(() => {
if (!isMobile && shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
if (shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
setPage(page + 1);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
@@ -208,7 +205,6 @@ function CommentList(props: Props) {
}
}
}, [
isMobile,
page,
moreBelow,
spinnerRef,
@@ -283,13 +279,7 @@ function CommentList(props: Props) {
<Empty padded text={__('That was pretty deep. What do you think?')} />
)}
<ul
className={classnames({
comments: expandedComments,
'comments--contracted': !expandedComments,
})}
ref={commentRef}
>
<ul className="comments" ref={commentRef}>
{topLevelComments &&
displayedComments &&
displayedComments.map((comment) => {
@@ -317,36 +307,7 @@ function CommentList(props: Props) {
})}
</ul>
{isMobile && (
<div className="card__bottom-actions--comments">
{(!expandedComments || moreBelow) && (
<Button
button="link"
title={!expandedComments ? __('Expand Comments') : __('Load More')}
label={!expandedComments ? __('Expand') : __('More')}
onClick={() => {
if (!expandedComments) {
setExpandedComments(true);
} else {
setPage(page + 1);
}
}}
/>
)}
{expandedComments && (
<Button
button="link"
title={__('Collapse Thread')}
label={__('Collapse')}
onClick={() => {
setExpandedComments(false);
}}
/>
)}
</div>
)}
{(isFetchingComments || (!isMobile && moreBelow)) && (
{(isFetchingComments || moreBelow) && (
<div className="main--empty" ref={spinnerRef}>
<Spinner type="small" />
</div>
+1 -22
View File
@@ -21,22 +21,10 @@ type Props = {
stakedLevel: number,
supportAmount: number,
isFiat: boolean,
isPinned: boolean,
};
function LivestreamComment(props: Props) {
const {
claim,
uri,
authorUri,
message,
commentIsMine,
commentId,
stakedLevel,
supportAmount,
isFiat,
isPinned,
} = props;
const { claim, uri, authorUri, message, commentIsMine, commentId, stakedLevel, supportAmount, isFiat } = props;
const [mouseIsHovering, setMouseHover] = React.useState(false);
const commentByOwnerOfContent = claim && claim.signing_channel && claim.signing_channel.permanent_url === authorUri;
const { claimName } = parseURI(authorUri);
@@ -69,13 +57,6 @@ function LivestreamComment(props: Props) {
{claimName}
</Button>
{isPinned && (
<span className="comment__pin">
<Icon icon={ICONS.PIN} size={14} />
{__('Pinned')}
</span>
)}
<div className="livestream-comment__text">
<MarkdownPreview content={message} promptLinks stakedLevel={stakedLevel} />
</div>
@@ -97,8 +78,6 @@ function LivestreamComment(props: Props) {
authorUri={authorUri}
commentIsMine={commentIsMine}
disableEdit
isTopLevel
isPinned={isPinned}
disableRemove={supportAmount > 0}
/>
</Menu>
-2
View File
@@ -3,7 +3,6 @@ import { makeSelectClaimForUri, selectMyChannelClaims } from 'lbry-redux';
import { doCommentSocketConnect, doCommentSocketDisconnect } from 'redux/actions/websocket';
import { doCommentList, doSuperChatList } from 'redux/actions/comments';
import {
selectPinnedCommentsById,
makeSelectTopLevelCommentsForUri,
selectIsFetchingComments,
makeSelectSuperChatsForUri,
@@ -18,7 +17,6 @@ const select = (state, props) => ({
superChats: makeSelectSuperChatsForUri(props.uri)(state),
superChatsTotalAmount: makeSelectSuperChatTotalAmountForUri(props.uri)(state),
myChannels: selectMyChannelClaims(state),
pinnedCommentsById: selectPinnedCommentsById(state),
});
export default connect(select, {
+27 -88
View File
@@ -22,6 +22,7 @@ type Props = {
fetchingComments: boolean,
doSuperChatList: (string) => void,
superChats: Array<Comment>,
superChatsTotalAmount: number,
myChannels: ?Array<ChannelClaim>,
};
@@ -37,27 +38,38 @@ export default function LivestreamComments(props: Props) {
embed,
doCommentSocketConnect,
doCommentSocketDisconnect,
comments: commentsByChronologicalOrder,
comments,
doCommentList,
fetchingComments,
doSuperChatList,
superChats,
superChatsTotalAmount,
myChannels,
superChats: superChatsByTipAmount,
} = props;
let superChatsFiatAmount, superChatsTotalAmount;
const commentsRef = React.createRef();
const [scrollBottom, setScrollBottom] = React.useState(true);
const [viewMode, setViewMode] = React.useState(VIEW_MODE_CHAT);
const [performedInitialScroll, setPerformedInitialScroll] = React.useState(false);
const claimId = claim && claim.claim_id;
const commentsLength = commentsByChronologicalOrder && commentsByChronologicalOrder.length;
const commentsToDisplay = viewMode === VIEW_MODE_CHAT ? commentsByChronologicalOrder : superChatsByTipAmount;
const commentsLength = comments && comments.length;
const commentsToDisplay = viewMode === VIEW_MODE_CHAT ? comments : superChats;
const discussionElement = document.querySelector('.livestream__comments');
const commentElement = document.querySelector('.livestream-comment');
// todo: implement comment_list --mine in SDK so redux can grab with selectCommentIsMine
function isMyComment(channelId: string) {
if (myChannels != null && channelId != null) {
for (let i = 0; i < myChannels.length; i++) {
if (myChannels[i].claim_id === channelId) {
return true;
}
}
}
return false;
}
React.useEffect(() => {
if (claimId) {
doCommentList(uri, '', 1, 75);
@@ -103,51 +115,6 @@ export default function LivestreamComments(props: Props) {
}
}, [commentsLength, discussionElement, handleScroll, performedInitialScroll, setPerformedInitialScroll]);
// sum total amounts for fiat tips and lbc tips
if (superChatsByTipAmount) {
let fiatAmount = 0;
let LBCAmount = 0;
for (const superChat of superChatsByTipAmount) {
if (superChat.is_fiat) {
fiatAmount = fiatAmount + superChat.support_amount;
} else {
LBCAmount = LBCAmount + superChat.support_amount;
}
}
superChatsFiatAmount = fiatAmount;
superChatsTotalAmount = LBCAmount;
}
let superChatsReversed;
// array of superchats organized by fiat or not first, then support amount
if (superChatsByTipAmount) {
const clonedSuperchats = JSON.parse(JSON.stringify(superChatsByTipAmount));
// sort by fiat first then by support amount
superChatsReversed = clonedSuperchats.sort(function(a, b) {
// if both are fiat, organize by support
if (a.is_fiat === b.is_fiat) {
return b.support_amount - a.support_amount;
// otherwise, if they are not both fiat, put the fiat transaction first
} else {
return (a.is_fiat === b.is_fiat) ? 0 : a.is_fiat ? -1 : 1;
}
}).reverse();
}
// todo: implement comment_list --mine in SDK so redux can grab with selectCommentIsMine
function isMyComment(channelId: string) {
if (myChannels != null && channelId != null) {
for (let i = 0; i < myChannels.length; i++) {
if (myChannels[i].claim_id === channelId) {
return true;
}
}
}
return false;
}
if (!claim) {
return null;
}
@@ -163,55 +130,41 @@ export default function LivestreamComments(props: Props) {
<div className="card livestream__discussion">
<div className="card__header--between livestream-discussion__header">
<div className="livestream-discussion__title">{__('Live discussion')}</div>
{(superChatsTotalAmount || 0) > 0 && (
{superChatsTotalAmount > 0 && (
<div className="recommended-content__toggles">
{/* the superchats in chronological order button */}
<Button
className={classnames('button-toggle', {
'button-toggle--active': viewMode === VIEW_MODE_CHAT,
})}
label={__('Chat')}
onClick={function() {
setViewMode(VIEW_MODE_CHAT);
const livestreamCommentsDiv = document.getElementsByClassName('livestream__comments')[0];
const divHeight = livestreamCommentsDiv.scrollHeight;
livestreamCommentsDiv.scrollTop = divHeight;
}}
onClick={() => setViewMode(VIEW_MODE_CHAT)}
/>
{/* the button to show superchats listed by most to least support amount */}
<Button
className={classnames('button-toggle', {
'button-toggle--active': viewMode === VIEW_MODE_SUPER_CHAT,
})}
label={
<>
<CreditAmount amount={superChatsTotalAmount || 0} size={8} /> /
<CreditAmount amount={superChatsFiatAmount || 0} size={8} isFiat /> {' '}{__('Tipped')}
<CreditAmount amount={superChatsTotalAmount} size={8} /> {__('Tipped')}
</>
}
onClick={function() {
setViewMode(VIEW_MODE_SUPER_CHAT);
const livestreamCommentsDiv = document.getElementsByClassName('livestream__comments')[0];
const divHeight = livestreamCommentsDiv.scrollHeight;
livestreamCommentsDiv.scrollTop = divHeight * -1;
}}
onClick={() => setViewMode(VIEW_MODE_SUPER_CHAT)}
/>
</div>
)}
</div>
<>
{fetchingComments && !commentsByChronologicalOrder && (
{fetchingComments && !comments && (
<div className="main--empty">
<Spinner />
</div>
)}
<div ref={commentsRef} className="livestream__comments-wrapper">
{viewMode === VIEW_MODE_CHAT && superChatsByTipAmount && (superChatsTotalAmount || 0) > 0 && (
{viewMode === VIEW_MODE_CHAT && superChatsTotalAmount > 0 && superChats && (
<div className="livestream-superchats__wrapper">
<div className="livestream-superchats__inner">
{superChatsByTipAmount.map((superChat: Comment) => (
{superChats.map((superChat: Comment) => (
<Tooltip key={superChat.comment_id} label={superChat.comment}>
<div className="livestream-superchat">
<div className="livestream-superchat__thumbnail">
@@ -234,23 +187,9 @@ export default function LivestreamComments(props: Props) {
</div>
)}
{/* top to bottom comment display */}
{!fetchingComments && commentsByChronologicalOrder.length > 0 ? (
{!fetchingComments && comments.length > 0 ? (
<div className="livestream__comments">
{viewMode === VIEW_MODE_CHAT && commentsToDisplay.map((comment) => (
<LivestreamComment
key={comment.comment_id}
uri={uri}
authorUri={comment.channel_url}
commentId={comment.comment_id}
message={comment.comment}
supportAmount={comment.support_amount}
isFiat={comment.is_fiat}
commentIsMine={comment.channel_id && isMyComment(comment.channel_id)}
/>
))}
{viewMode === VIEW_MODE_SUPER_CHAT && superChatsReversed && superChatsReversed.map((comment) => (
{commentsToDisplay.map((comment) => (
<LivestreamComment
key={comment.comment_id}
uri={uri}
+5 -16
View File
@@ -18,16 +18,11 @@ export default function LivestreamLink(props: Props) {
const [livestreamClaim, setLivestreamClaim] = React.useState(false);
const [isLivestreaming, setIsLivestreaming] = React.useState(false);
const livestreamChannelId = (channelClaim && channelClaim.claim_id) || ''; // TODO: fail in a safer way, probably
const isChannelEmpty = !channelClaim || !channelClaim.meta || !channelClaim.meta.claims_in_channel;
React.useEffect(() => {
// Don't search empty channels
if (livestreamChannelId && !isChannelEmpty) {
if (livestreamChannelId) {
Lbry.claim_search({
channel_ids: [livestreamChannelId],
page: 1,
page_size: 1,
no_totals: true,
has_no_source: true,
claim_type: ['stream'],
order_by: CS.ORDER_BY_NEW_VALUE,
@@ -40,7 +35,7 @@ export default function LivestreamLink(props: Props) {
})
.catch(() => {});
}
}, [livestreamChannelId, isChannelEmpty]);
}, [livestreamChannelId]);
React.useEffect(() => {
function fetchIsStreaming() {
@@ -58,23 +53,17 @@ export default function LivestreamLink(props: Props) {
}
let interval;
// Only call livestream api if channel has livestream claims
if (livestreamChannelId && livestreamClaim) {
if (livestreamChannelId) {
if (!interval) fetchIsStreaming();
interval = setInterval(fetchIsStreaming, 10 * 1000);
}
// Prevent any more api calls on update
if (!livestreamChannelId || !livestreamClaim) {
if (interval) {
clearInterval(interval);
}
}
return () => {
if (interval) {
clearInterval(interval);
}
};
}, [livestreamChannelId, livestreamClaim]);
}, [livestreamChannelId]);
if (!livestreamClaim || !isLivestreaming) {
return null;
+1 -11
View File
@@ -31,17 +31,7 @@ export default function Logo(props: Props) {
if (LOGO_TEXT_LIGHT) {
return (
<>
<img className={'embed__overlay-logo'} src={LOGO_TEXT_LIGHT} />
</>
);
} else {
return defaultWithLabel;
}
} else if (type === 'embed-ended') {
if (LOGO_TEXT_LIGHT) {
return (
<>
<img className={'embed__overlay-logo'} src={LOGO_TEXT_LIGHT} />
<img className={'header__navigation-logo'} src={LOGO_TEXT_LIGHT} />
</>
);
} else {
+3 -5
View File
@@ -3,25 +3,23 @@ import {
makeSelectPublishFormValue,
selectMyClaimForUri,
selectIsResolvingPublishUris,
selectTakeOverAmount,
doUpdatePublishForm,
doPrepareEdit,
selectBalance,
} from 'lbry-redux';
import PublishPage from './view';
const select = (state) => ({
const select = state => ({
name: makeSelectPublishFormValue('name')(state),
bid: makeSelectPublishFormValue('bid')(state),
uri: makeSelectPublishFormValue('uri')(state),
isResolvingUri: selectIsResolvingPublishUris(state),
balance: selectBalance(state),
myClaimForUri: selectMyClaimForUri(state),
amountNeededForTakeover: selectTakeOverAmount(state),
});
const perform = (dispatch) => ({
updatePublishForm: (value) => dispatch(doUpdatePublishForm(value)),
const perform = dispatch => ({
updatePublishForm: value => dispatch(doUpdatePublishForm(value)),
prepareEdit: (claim, uri) => dispatch(doPrepareEdit(claim, uri)),
});
-2
View File
@@ -3,7 +3,6 @@ import {
makeSelectPublishFormValue,
selectIsStillEditing,
selectMyClaimForUri,
selectTakeOverAmount,
doUpdatePublishForm,
doPrepareEdit,
} from 'lbry-redux';
@@ -18,7 +17,6 @@ const select = (state) => ({
myClaimForUri: selectMyClaimForUri(state),
activeChannelClaim: selectActiveChannelClaim(state),
incognito: selectIncognito(state),
amountNeededForTakeover: selectTakeOverAmount(state),
});
const perform = (dispatch) => ({
-4
View File
@@ -1,6 +1,5 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsNsfw, makeSelectClaimForUri } from 'lbry-redux';
import { doRecommendationUpdate, doRecommendationClicked } from 'redux/actions/content';
import { doFetchRecommendedContent } from 'redux/actions/search';
import { makeSelectRecommendedContentForUri, selectIsSearching } from 'redux/selectors/search';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
@@ -18,9 +17,6 @@ const select = (state, props) => ({
const perform = (dispatch) => ({
doFetchRecommendedContent: (uri, mature) => dispatch(doFetchRecommendedContent(uri, mature)),
doRecommendationUpdate: (claimId, urls, id, parentId) =>
dispatch(doRecommendationUpdate(claimId, urls, id, parentId)),
doRecommendationClicked: (claimId, index) => dispatch(doRecommendationClicked(claimId, index)),
});
export default connect(select, perform)(RecommendedContent);
+14 -58
View File
@@ -1,8 +1,6 @@
// @flow
import { SHOW_ADS } from 'config';
import React from 'react';
import { useHistory } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';
import ClaimList from 'component/claimList';
import ClaimListDiscover from 'component/claimListDiscover';
import Ads from 'web/component/ads';
@@ -10,7 +8,6 @@ import Card from 'component/common/card';
import { useIsMobile, useIsMediumScreen } from 'effects/use-screensize';
import Button from 'component/button';
import classnames from 'classnames';
import { CONTAINER_ID } from 'constants/navigation';
const VIEW_ALL_RELATED = 'view_all_related';
const VIEW_MORE_FROM = 'view_more_from';
@@ -24,8 +21,6 @@ type Props = {
mature: boolean,
isAuthenticated: boolean,
claim: ?StreamClaim,
doRecommendationUpdate: (claimId: string, urls: Array<string>, id: string, parentId: string) => void,
doRecommendationClicked: (claimId: string, index: number) => void,
};
export default React.memo<Props>(function RecommendedContent(props: Props) {
@@ -38,70 +33,33 @@ export default React.memo<Props>(function RecommendedContent(props: Props) {
isSearching,
isAuthenticated,
claim,
doRecommendationUpdate,
doRecommendationClicked,
} = props;
const [viewMode, setViewMode] = React.useState(VIEW_ALL_RELATED);
const [recommendationId, setRecommendationId] = React.useState('');
const [recommendationUrls, setRecommendationUrls] = React.useState();
const history = useHistory();
const signingChannel = claim && claim.signing_channel;
const channelName = signingChannel ? signingChannel.name : null;
const isMobile = useIsMobile();
const isMedium = useIsMediumScreen();
React.useEffect(() => {
function moveAutoplayNextItemToTop(recommendedContent) {
let newList = recommendedContent;
if (newList) {
const index = newList.indexOf(nextRecommendedUri);
if (index > 0) {
const a = newList[0];
newList[0] = nextRecommendedUri;
newList[index] = a;
}
}
return newList;
}
function listEq(prev, next) {
if (prev && next) {
return prev.length === next.length && prev.every((value, index) => value === next[index]);
} else {
return prev === next;
function reorderList(recommendedContent) {
let newList = recommendedContent;
if (newList) {
const index = newList.indexOf(nextRecommendedUri);
if (index === -1) {
// This would be weird. Shouldn't happen since it is derived from the same list.
} else if (index !== 0) {
// Swap the "next" item to the top of the list
const a = newList[0];
newList[0] = nextRecommendedUri;
newList[index] = a;
}
}
const newRecommendationUrls = moveAutoplayNextItemToTop(recommendedContent);
if (claim && !listEq(recommendationUrls, newRecommendationUrls)) {
const parentId = (history.location.state && history.location.state[CONTAINER_ID]) || '';
const id = uuidv4();
setRecommendationId(id);
setRecommendationUrls(newRecommendationUrls);
doRecommendationUpdate(claim.claim_id, newRecommendationUrls, id, parentId);
}
}, [
recommendedContent,
nextRecommendedUri,
recommendationUrls,
setRecommendationUrls,
claim,
doRecommendationUpdate,
history.location.state,
]);
return newList;
}
React.useEffect(() => {
doFetchRecommendedContent(uri, mature);
}, [uri, mature, doFetchRecommendedContent]);
function handleRecommendationClicked(e: any, index: number) {
if (claim) {
doRecommendationClicked(claim.claim_id, index);
}
}
return (
<Card
isBodyList
@@ -133,14 +91,12 @@ export default React.memo<Props>(function RecommendedContent(props: Props) {
<div>
{viewMode === VIEW_ALL_RELATED && (
<ClaimList
id={recommendationId}
type="small"
loading={isSearching}
uris={recommendationUrls}
uris={reorderList(recommendedContent)}
hideMenu={isMobile}
injectedItem={SHOW_ADS && IS_WEB && !isAuthenticated && <Ads small type={'video'} />}
empty={__('No related content found')}
onClick={handleRecommendationClicked}
/>
)}
{viewMode === VIEW_MORE_FROM && signingChannel && (
+6 -7
View File
@@ -15,7 +15,6 @@ import ClaimPreview from 'component/claimPreview';
import { URL as SITE_URL, URL_LOCAL, URL_DEV } from 'config';
import HelpLink from 'component/common/help-link';
import WalletSpendableBalanceHelp from 'component/walletSpendableBalanceHelp';
import BidHelpText from 'component/publishBid/bid-help-text';
import Spinner from 'component/spinner';
type Props = {
@@ -78,6 +77,7 @@ function RepostCreate(props: Props) {
const [repostBid, setRepostBid] = React.useState(0.01);
const [repostBidError, setRepostBidError] = React.useState(undefined);
const [takeoverAmount, setTakeoverAmount] = React.useState(0);
const [enteredRepostName, setEnteredRepostName] = React.useState(defaultName);
const [available, setAvailable] = React.useState(true);
const [enteredContent, setEnteredContentUri] = React.useState(undefined);
@@ -189,9 +189,10 @@ function RepostCreate(props: Props) {
: Number(passedRepostAmount) + 0.01;
if (repostTakeoverAmount) {
setTakeoverAmount(Number(repostTakeoverAmount.toFixed(2)));
setAutoRepostBid(repostTakeoverAmount);
}
}, [enteredRepostAmount, passedRepostAmount]);
}, [setTakeoverAmount, enteredRepostAmount, passedRepostAmount]);
// repost bid error
React.useEffect(() => {
@@ -380,11 +381,9 @@ function RepostCreate(props: Props) {
error={repostBidError}
helper={
<>
<BidHelpText
uri={'lbry://' + enteredRepostName}
amountNeededForTakeover={enteredRepostAmount}
isResolvingUri={isResolvingEnteredRepost}
/>
{__('Winning amount: %amount%', {
amount: Number(takeoverAmount).toFixed(2),
})}
<WalletSpendableBalanceHelp inline />
</>
}
@@ -1,17 +0,0 @@
import { connect } from 'react-redux';
import { SETTINGS } from 'lbry-redux';
import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import SettingCommentsServer from './view';
const select = (state) => ({
customServerEnabled: makeSelectClientSetting(SETTINGS.CUSTOM_COMMENTS_SERVER_ENABLED)(state),
customServerUrl: makeSelectClientSetting(SETTINGS.CUSTOM_COMMENTS_SERVER_URL)(state),
});
const perform = (dispatch) => ({
setCustomServerEnabled: (val) => dispatch(doSetClientSetting(SETTINGS.CUSTOM_COMMENTS_SERVER_ENABLED, val, true)),
setCustomServerUrl: (url) => dispatch(doSetClientSetting(SETTINGS.CUSTOM_COMMENTS_SERVER_URL, url, true)),
});
export default connect(select, perform)(SettingCommentsServer);
@@ -1,70 +0,0 @@
// @flow
import { COMMENT_SERVER_NAME } from 'config';
import React from 'react';
import Comments from 'comments';
import { FormField } from 'component/common/form';
const DEBOUNCE_TEXT_INPUT_MS = 500;
type Props = {
customServerEnabled: boolean,
customServerUrl: string,
setCustomServerEnabled: (boolean) => void,
setCustomServerUrl: (string) => void,
};
function SettingCommentsServer(props: Props) {
const { customServerEnabled, customServerUrl, setCustomServerEnabled, setCustomServerUrl } = props;
const [customUrl, setCustomUrl] = React.useState(customServerUrl);
React.useEffect(() => {
const timer = setTimeout(() => {
setCustomServerUrl(customUrl);
Comments.url = customUrl;
}, DEBOUNCE_TEXT_INPUT_MS);
return () => clearTimeout(timer);
}, [customUrl, setCustomServerUrl]);
return (
<React.Fragment>
<fieldset-section>
<FormField
type="radio"
name="use_default_comments_server"
label={__('Default comments server (%name%)', { name: COMMENT_SERVER_NAME })}
checked={!customServerEnabled}
onChange={(e) => {
if (e.target.checked) {
setCustomServerEnabled(false);
}
}}
/>
<FormField
type="radio"
name="use_custom_comments_server"
label={__('Custom comments server')}
checked={customServerEnabled}
onChange={(e) => {
if (e.target.checked) {
setCustomServerEnabled(true);
}
}}
/>
{customServerEnabled && (
<div className="section__body">
<FormField
type="text"
placeholder="https://comment.mysite.com"
value={customUrl}
onChange={(e) => setCustomUrl(e.target.value)}
/>
</div>
)}
</fieldset-section>
</React.Fragment>
);
}
export default SettingCommentsServer;
+2 -20
View File
@@ -9,15 +9,12 @@ import { useIsMobile } from 'effects/use-screensize';
import { FormField } from 'component/common/form';
import { hmsToSeconds, secondsToHms } from 'util/time';
import { generateLbryContentUrl, generateLbryWebUrl, generateEncodedLbryURL, generateShareUrl } from 'util/url';
import { URL, TWITTER_ACCOUNT, SHARE_DOMAIN_URL } from 'config';
import { URL, SHARE_DOMAIN_URL } from 'config';
const SHARE_DOMAIN = SHARE_DOMAIN_URL || URL;
const IOS = !!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform);
const SUPPORTS_SHARE_API = typeof navigator.share !== 'undefined';
// Twitter share
const TWITTER_INTENT_API = 'https://twitter.com/intent/tweet?';
type Props = {
claim: StreamClaim,
title: ?string,
@@ -71,21 +68,6 @@ function SocialShare(props: Props) {
);
const downloadUrl = `${generateDownloadUrl(name, claimId)}`;
// Tweet params
let tweetIntentParams = {
url: shareUrl,
text: title || claim.name,
hashtags: 'LBRY',
};
if (TWITTER_ACCOUNT) {
// $FlowFixMe
tweetIntentParams.via = TWITTER_ACCOUNT;
}
// Generate twitter web intent url
const tweetIntent = TWITTER_INTENT_API + new URLSearchParams(tweetIntentParams).toString();
function handleWebShareClick() {
if (navigator.share) {
navigator.share({
@@ -133,7 +115,7 @@ function SocialShare(props: Props) {
iconSize={24}
icon={ICONS.TWITTER}
title={__('Share on Twitter')}
href={tweetIntent}
href={`https://twitter.com/intent/tweet?text=${encodedLbryURL}`}
/>
<Button
className="share"
+1 -3
View File
@@ -7,7 +7,7 @@ import { makeSelectContentPositionForUri } from 'redux/selectors/content';
import VideoViewer from './view';
import { withRouter } from 'react-router';
import { doClaimEligiblePurchaseRewards } from 'redux/actions/rewards';
import { selectDaemonSettings, makeSelectClientSetting, selectHomepageData } from 'redux/selectors/settings';
import { makeSelectClientSetting, selectHomepageData } from 'redux/selectors/settings';
import { toggleVideoTheaterMode, doSetClientSetting } from 'redux/actions/settings';
import { selectUserVerifiedEmail, selectUser } from 'redux/selectors/user';
@@ -15,7 +15,6 @@ const select = (state, props) => {
const { search } = props.location;
const urlParams = new URLSearchParams(search);
const autoplay = urlParams.get('autoplay');
// TODO: eventually this should be received from DB and not local state (https://github.com/lbryio/lbry-desktop/issues/6796)
const position = urlParams.get('t') !== null ? urlParams.get('t') : makeSelectContentPositionForUri(props.uri)(state);
const userId = selectUser(state) && selectUser(state).id;
@@ -32,7 +31,6 @@ const select = (state, props) => {
homepageData: selectHomepageData(state),
authenticated: selectUserVerifiedEmail(state),
userId: userId,
shareTelemetry: IS_WEB || selectDaemonSettings(state).share_usage_data,
};
};
@@ -1,12 +1,6 @@
// Created by xander on 6/21/2021
import videojs from 'video.js';
import {
makeSelectRecommendationId,
makeSelectRecommendationParentId,
makeSelectRecommendedClaimIds,
makeSelectRecommendationClicks,
} from 'redux/selectors/content';
import { v4 as uuidV4 } from 'uuid';
const VERSION = '0.0.1';
const recsysEndpoint = 'https://clickstream.odysee.com/log/video/view';
@@ -23,28 +17,23 @@ const RecsysData = {
};
function createRecsys(claimId, userId, events, loadedAt, isEmbed) {
// TODO: use a UUID generator
const uuid = uuidV4();
const pageLoadedAt = loadedAt;
const pageExitedAt = Date.now();
if (window.store) {
const state = window.store.getState();
return {
uuid: makeSelectRecommendationId(claimId)(state),
parentUuid: makeSelectRecommendationParentId(claimId)(state),
uid: userId,
claimId: claimId,
pageLoadedAt: pageLoadedAt,
pageExitedAt: pageExitedAt,
recsysId: recsysId,
recClaimIds: makeSelectRecommendedClaimIds(claimId)(state),
recClickedVideoIdx: makeSelectRecommendationClicks(claimId)(state),
events: events,
isEmbed: isEmbed,
};
}
return undefined;
return {
uuid: uuid,
parentUuid: null,
uid: userId,
claimId: claimId,
pageLoadedAt: pageLoadedAt,
pageExitedAt: pageExitedAt,
recsysId: recsysId,
recClaimIds: null,
recClickedVideoIdx: null,
events: events,
isEmbed: isEmbed,
};
}
function newRecsysEvent(eventType, offset, arg) {
@@ -141,10 +130,7 @@ class RecsysPlugin extends Component {
this.loadedAt,
false
);
if (event) {
sendRecsysEvents(event);
}
sendRecsysEvents(event);
}
onPlay(event) {
@@ -240,7 +226,7 @@ const onPlayerReady = (player, options) => {
* @function plugin
* @param {Object} [options={}]
*/
const plugin = function (options) {
const plugin = function(options) {
this.ready(() => {
onPlayerReady(this, videojs.mergeOptions(defaults, options));
});
@@ -0,0 +1,192 @@
// Created by xander on 7/10/2021
import videojs from 'video.js';
const VERSION = '0.0.1';
const watchmanEndpoint = 'https://watchman.na-backend.dev.odysee.com';
let previousEventTime = Date.now();
/* Watchman */
function createWatchmanData(
url,
duration,
position,
relPosition,
rebufCount,
rebufDuration,
format,
player,
userId,
device
) {
return {
url: url,
duration: duration,
rel_position: relPosition,
rebuf_count: rebufCount,
rebuf_duration: rebufDuration,
format: format,
player: player,
user_id: userId,
device: device,
};
}
function sendWatchmanData(watchmanData) {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'text/plain' }, // application/json
body: JSON.stringify(watchmanData),
};
try {
fetch(watchmanEndpoint, requestOptions)
.then((response) => response.json())
.then((data) => {
// Response data
});
} catch (error) {
// Response error
}
}
// Plugin default options
const defaults = {
endpoint: watchmanEndpoint,
reportRate: 15,
videoUrl: null,
userId: 0,
debug: false,
};
const Component = videojs.getComponent('Component');
const registerPlugin = videojs.registerPlugin || videojs.plugin;
class WatchmanPlugin extends Component {
constructor(player, options) {
super(player, options);
// Plugin started
if (options.debug) {
this.log(`Created watchman plugin for: videoUrl:${options.videoUrl}, userId:${options.userId}`);
}
// Plugin variables
this.player = player;
this.loadedAt = Date.now();
this.watchmanIntervalId = null;
this.bufferEventData = [];
// Plugin event listeners
player.on('tracking:firstplay', (event, data) => this.onTrackingFirstPlay(event, data));
player.on('tracking:buffered', (event, data) => this.onTrackingBuffered(event, data));
// Event trigger to send recsys event
player.on('dispose', (event) => this.onDispose(event));
}
sendWatchmanData() {
const processedData = this.bufferEventData.reduce((accumulator, current) => {
return {
secondsToLoad: accumulator.secondsToLoad + current.secondsToLoad,
bufferCount: accumulator.bufferCount + current.bufferCount,
};
}, {
secondsToLoad: 0,
bufferCount: 0,
});
const timeSinceLastEvent = Date.now() - previousEventTime;
previousEventTime = Date.now();
const currentTime = this.player.currentTime();
const totalTime = this.player.duration();
const event = createWatchmanData(
null,
timeSinceLastEvent,
currentTime,
currentTime / totalTime,
processedData.bufferCount,
processedData.secondsToLoad * 1000,
this.player.currentSource().type,
null,
null,
null,
);
console.log('[watchman] Data Payload', event);
// sendWatchmanData(event);
}
onTrackingFirstPlay(event, data) {
// data attr: secondsToLoad
console.log(`[watchman] First Play Data:`, data);
// Start analytics interval here
this.watchmanIntervalId = setInterval(() => this.onWatchmanInterval(), this.options_.reportRate * 1000);
}
onTrackingBuffered(event, data) {
const duration = this.player.duration();
const reportData = {
...data,
relativePosition: data.currentTime / duration,
};
// data attr: currentTime, readyState, secondsToLoad, bufferCount
console.log(`[watchman] Buffer Data:`, reportData);
this.bufferEventData.push(data);
}
onWatchmanInterval() {
// don't report while player is paused
if (this.player.paused()) return;
// process and send watchman data here
console.log('[watchman] interval', this.bufferEventData);
this.sendWatchmanData();
// clear processed data
this.bufferEventData = [];
}
onDispose(event) {
// Stop analytics interval
clearInterval(this.watchmanIntervalId);
}
log(...args) {
if (this.options_.debug) {
console.log(`[watchman] Debug:`, JSON.stringify(args));
}
}
}
videojs.registerComponent('watchman', WatchmanPlugin);
const onPlayerReady = (player, options) => {
player.recsys = new WatchmanPlugin(player, options);
};
/**
* Initialize the plugin.
*
* @function plugin
* @param {Object} [options={}]
*/
const plugin = function(options) {
this.ready(() => {
onPlayerReady(this, videojs.mergeOptions(defaults, options));
});
};
plugin.VERSION = VERSION;
registerPlugin('watchman', plugin);
export default plugin;
@@ -1,6 +1,6 @@
// @flow
import React, { useEffect, useRef, useState } from 'react';
import { SIMPLE_SITE } from 'config';
// import { SIMPLE_SITE } from 'config';
import Button from 'component/button';
import * as ICONS from 'constants/icons';
import classnames from 'classnames';
@@ -13,7 +13,7 @@ import hlsQualitySelector from './plugins/videojs-hls-quality-selector/plugin';
import recsys from './plugins/videojs-recsys/plugin';
import qualityLevels from 'videojs-contrib-quality-levels';
import isUserTyping from 'util/detect-typing';
import './plugins/videojs-aniview/plugin';
// import './plugins/videojs-aniview/plugin';
const isDev = process.env.NODE_ENV !== 'production';
@@ -56,7 +56,6 @@ type Props = {
claimId: ?string,
userId: ?number,
allowPreRoll: ?boolean,
shareTelemetry: boolean,
};
// type VideoJSOptions = {
@@ -193,8 +192,7 @@ export default React.memo<Props>(function VideoJs(props: Props) {
adUrl,
claimId,
userId,
allowPreRoll,
shareTelemetry,
// allowPreRoll,
} = props;
const [reload, setReload] = useState('initial');
@@ -566,12 +564,11 @@ export default React.memo<Props>(function VideoJs(props: Props) {
});
// Add recsys plugin
if (shareTelemetry) {
player.recsys({
videoId: claimId,
userId: userId,
});
}
// TODO: Add an if(odysee.com) around this function to only use recsys on odysee
player.recsys({
videoId: claimId,
userId: userId,
});
// set playsinline for mobile
// TODO: make this better
@@ -585,9 +582,9 @@ export default React.memo<Props>(function VideoJs(props: Props) {
// This must be initialized earlier than everything else
// otherwise a race condition occurs if we place this in the onReady call back
// allow if isDev because otherwise you'll never see ads when basing to master
if ((allowPreRoll && SIMPLE_SITE) || isDev) {
vjs.aniview();
}
// if ((allowPreRoll && SIMPLE_SITE) || isDev) {
// vjs.aniview();
// }
// fixes #3498 (https://github.com/lbryio/lbry-desktop/issues/3498)
// summary: on firefox the focus would stick to the fullscreen button which caused buggy behavior with spacebar
@@ -662,18 +659,19 @@ export default React.memo<Props>(function VideoJs(props: Props) {
}, [source, reload]);
// Load IMA3 SDK for aniview
useEffect(() => {
const script = document.createElement('script');
script.src = `https://imasdk.googleapis.com/js/sdkloader/ima3.js`;
script.async = true;
// $FlowFixMe
document.body.appendChild(script);
return () => {
// $FlowFixMe
document.body.removeChild(script);
};
});
// disabled for now
// useEffect(() => {
// const script = document.createElement('script');
// script.src = `https://imasdk.googleapis.com/js/sdkloader/ima3.js`;
// script.async = true;
// // $FlowFixMe
// document.body.appendChild(script);
//
// return () => {
// // $FlowFixMe
// document.body.removeChild(script);
// };
// });
return (
// $FlowFixMe
+2 -19
View File
@@ -51,7 +51,6 @@ type Props = {
authenticated: boolean,
userId: number,
homepageData?: { [string]: HomepageCat },
shareTelemetry: boolean,
};
/*
@@ -85,7 +84,6 @@ function VideoViewer(props: Props) {
homepageData,
authenticated,
userId,
shareTelemetry,
} = props;
const adApprovedChannelIds = homepageData ? getAllIds(homepageData) : [];
@@ -127,7 +125,7 @@ function VideoViewer(props: Props) {
}, [embedded, videoPlaybackRate]);
function doTrackingBuffered(e: Event, data: any) {
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
fetch(source, { method: 'HEAD' }).then((response) => {
data.playerPoweredBy = response.headers.get('x-powered-by');
doAnalyticsBuffer(uri, data);
});
@@ -141,20 +139,13 @@ function VideoViewer(props: Props) {
timeToStart += differenceToAdd;
}
analytics.playerStartedEvent(embedded);
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
let playerPoweredBy = response.headers.get('x-powered-by') || '';
analytics.videoStartEvent(claimId, timeToStart, playerPoweredBy, userId, claim.canonical_url, this);
});
analytics.videoStartEvent(claimId, timeToStart);
doAnalyticsView(uri, timeToStart).then(() => {
claimRewards();
});
}
const onEnded = React.useCallback(() => {
analytics.videoIsPlaying(false);
if (adUrl) {
setAdUrl(null);
return;
@@ -174,18 +165,15 @@ function VideoViewer(props: Props) {
setIsPlaying(true);
setShowAutoplayCountdown(false);
setIsEndededEmbed(false);
analytics.videoIsPlaying(true, player);
}
function onPause(event, player) {
setIsPlaying(false);
handlePosition(player);
analytics.videoIsPlaying(false, player);
}
function onDispose(event, player) {
handlePosition(player);
analytics.videoIsPlaying(false, player);
}
function handlePosition(player) {
@@ -239,16 +227,12 @@ function VideoViewer(props: Props) {
// re-factoring.
player.on('loadedmetadata', () => restorePlaybackRate(player));
// used for tracking buffering for watchman
player.on('tracking:buffered', doTrackingBuffered);
// first play tracking, used for initializing the watchman api
player.on('tracking:firstplay', doTrackingFirstPlay);
player.on('ended', onEnded);
player.on('play', onPlay);
player.on('pause', (event) => onPause(event, player));
player.on('dispose', (event) => onDispose(event, player));
player.on('error', () => {
const error = player.error();
if (error) {
@@ -335,7 +319,6 @@ function VideoViewer(props: Props) {
claimId={claimId}
userId={userId}
allowPreRoll={!embedded && !authenticated}
shareTelemetry={shareTelemetry}
/>
)}
</div>
@@ -1,40 +0,0 @@
import { connect } from 'react-redux';
import {
selectBalance,
selectClaimsBalance,
selectSupportsBalance,
selectTipsBalance,
selectIsFetchingUtxoCounts,
selectUtxoCounts,
doFetchUtxoCounts,
doUtxoConsolidate,
selectIsConsolidatingUtxos,
selectIsMassClaimingTips,
selectPendingConsolidateTxid,
selectPendingMassClaimTxid,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectSyncHash } from 'redux/selectors/sync';
import { selectClaimedRewards } from 'redux/selectors/rewards';
import WalletBalance from './view';
const select = state => ({
balance: selectBalance(state),
claimsBalance: selectClaimsBalance(state) || 0,
supportsBalance: selectSupportsBalance(state) || 0,
tipsBalance: selectTipsBalance(state) || 0,
rewards: selectClaimedRewards(state),
hasSynced: Boolean(selectSyncHash(state)),
fetchingUtxoCounts: selectIsFetchingUtxoCounts(state),
consolidatingUtxos: selectIsConsolidatingUtxos(state),
massClaimingTips: selectIsMassClaimingTips(state),
utxoCounts: selectUtxoCounts(state),
consolidateIsPending: selectPendingConsolidateTxid(state),
massClaimIsPending: selectPendingMassClaimTxid(state),
});
export default connect(select, {
doOpenModal,
doFetchUtxoCounts,
doUtxoConsolidate,
})(WalletBalance);
@@ -1,166 +0,0 @@
// @flow
import React from 'react';
import Button from 'component/button';
import Card from 'component/common/card';
import { Lbryio } from 'lbryinc';
import moment from 'moment';
type Props = {
accountDetails: any,
transactions: any,
};
const WalletBalance = (props: Props) => {
// receive transactions from parent component
let accountTransactions = props.transactions;
// reverse so most recent payments come first
if (accountTransactions) {
accountTransactions = accountTransactions.reverse();
}
if (accountTransactions && accountTransactions.length > 10) {
accountTransactions.length = 10;
}
// const [detailsExpanded, setDetailsExpanded] = React.useState(false);
const [accountStatusResponse, setAccountStatusResponse] = React.useState();
const [subscriptions, setSubscriptions] = React.useState([]);
var environment = 'test';
function getAccountStatus() {
return Lbryio.call(
'account',
'status',
{
environment,
},
'post'
);
}
React.useEffect(() => {
(async function() {
const response = await getAccountStatus();
setAccountStatusResponse(response);
console.log(response);
})();
}, []);
return (
<><Card
title={'Tip History'}
body={(
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Processing Fee')}</th>
<th>{__('Odysee Fee')}</th>
<th>{__('Received Amount')}</th>
</tr>
</thead>
<tbody>
{accountTransactions &&
accountTransactions.map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>${transaction.transaction_fee / 100}</td>
<td>${transaction.application_fee / 100}</td>
<td>${transaction.received_amount / 100}</td>
</tr>
))}
</tbody>
</table>
{!accountTransactions && <p style={{textAlign: 'center', marginTop: '20px', fontSize: '13px', color: 'rgb(171, 171, 171)'}}>No Transactions</p>}
</div>
</>
)}
/>
<Card
title={__('Subscriptions')}
body={
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Card Last 4')}</th>
<th>{__('Anonymous')}</th>
</tr>
</thead>
<tbody>
{subscriptions &&
subscriptions.reverse().map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>{lastFour}</td>
<td>{transaction.private_tip ? 'Yes' : 'No'}</td>
</tr>
))}
</tbody>
</table>
{(!subscriptions || subscriptions.length === 0) && <p style={{textAlign: 'center', marginTop: '22px', fontSize: '13px', color: 'rgb(171, 171, 171)'}}>No Subscriptions</p>}
</div>
</>
}
/></>
);
};
export default WalletBalance;
-40
View File
@@ -1,40 +0,0 @@
import { connect } from 'react-redux';
import {
selectBalance,
selectClaimsBalance,
selectSupportsBalance,
selectTipsBalance,
selectIsFetchingUtxoCounts,
selectUtxoCounts,
doFetchUtxoCounts,
doUtxoConsolidate,
selectIsConsolidatingUtxos,
selectIsMassClaimingTips,
selectPendingConsolidateTxid,
selectPendingMassClaimTxid,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectSyncHash } from 'redux/selectors/sync';
import { selectClaimedRewards } from 'redux/selectors/rewards';
import WalletBalance from './view';
const select = state => ({
balance: selectBalance(state),
claimsBalance: selectClaimsBalance(state) || 0,
supportsBalance: selectSupportsBalance(state) || 0,
tipsBalance: selectTipsBalance(state) || 0,
rewards: selectClaimedRewards(state),
hasSynced: Boolean(selectSyncHash(state)),
fetchingUtxoCounts: selectIsFetchingUtxoCounts(state),
consolidatingUtxos: selectIsConsolidatingUtxos(state),
massClaimingTips: selectIsMassClaimingTips(state),
utxoCounts: selectUtxoCounts(state),
consolidateIsPending: selectPendingConsolidateTxid(state),
massClaimIsPending: selectPendingMassClaimTxid(state),
});
export default connect(select, {
doOpenModal,
doFetchUtxoCounts,
doUtxoConsolidate,
})(WalletBalance);
-99
View File
@@ -1,99 +0,0 @@
// @flow
import * as ICONS from 'constants/icons';
import * as PAGES from 'constants/pages';
import React from 'react';
import CreditAmount from 'component/common/credit-amount';
import Button from 'component/button';
import Card from 'component/common/card';
import Icon from 'component/common/icon';
import I18nMessage from 'component/i18nMessage';
type Props = {
accountDetails: any,
};
const WalletBalance = (props: Props) => {
const {
accountDetails,
} = props;
console.log('account details');
console.log(accountDetails);
const [detailsExpanded, setDetailsExpanded] = React.useState(false);
return (
<>{<Card
title={<><Icon size="18" icon={ICONS.FINANCE} />{(accountDetails && (accountDetails.total_received_unpaid / 100)) || 0} USD</>}
subtitle={
<I18nMessage>
This is your remaining balance that can still be withdrawn to your bank account
</I18nMessage>
}
actions={
<>
<h2 className="section__title--small">
${(accountDetails && (accountDetails.total_tipped / 100)) || 0} Total Received Tips
</h2>
<h2 className="section__title--small">
${(accountDetails && (accountDetails.total_paid_out / 100)) || 0} Withdrawn
<Button
button="link"
label={detailsExpanded ? __('View less') : __('View more')}
iconRight={detailsExpanded ? ICONS.UP : ICONS.DOWN}
onClick={() => setDetailsExpanded(!detailsExpanded)}
/>
</h2>
{/* view more section */}
{detailsExpanded && (
<div className="section__subtitle">
<dl>
<dt>
<span className="dt__text">{__('Earned from uploads')}</span>
{/* <span className="help--dt">({__('Earned from channel page')})</span> */}
</dt>
<dd>
<span className="dd__text">
{Boolean(1) && (
<Button
button="link"
className="dd__button"
icon={ICONS.UNLOCK}
/>
)}
<CreditAmount amount={1} precision={4} />
</span>
</dd>
<dt>
<span className="dt__text">{__('Earned from channel page')}</span>
{/* <span className="help--dt">({__('Delete or edit past content to spend')})</span> */}
</dt>
<dd>
<CreditAmount amount={1} precision={4} />
</dd>
{/* <dt> */}
{/* <span className="dt__text">{__('...supporting content')}</span> */}
{/* <span className="help--dt">({__('Delete supports to spend')})</span> */}
{/* </dt> */}
{/* <dd> */}
{/* <CreditAmount amount={1} precision={4} /> */}
{/* </dd> */}
</dl>
</div>
)}
<div className="section__actions">
<Button button="primary" label={__('Receive Payout')} icon={ICONS.SEND} />
<Button button="secondary" label={__('Account Configuration')} icon={ICONS.SETTINGS} navigate={`/$/${PAGES.SETTINGS_STRIPE_ACCOUNT}`} />
</div>
</>
}
/>}</>
);
};
export default WalletBalance;
@@ -1,40 +0,0 @@
import { connect } from 'react-redux';
import {
selectBalance,
selectClaimsBalance,
selectSupportsBalance,
selectTipsBalance,
selectIsFetchingUtxoCounts,
selectUtxoCounts,
doFetchUtxoCounts,
doUtxoConsolidate,
selectIsConsolidatingUtxos,
selectIsMassClaimingTips,
selectPendingConsolidateTxid,
selectPendingMassClaimTxid,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectSyncHash } from 'redux/selectors/sync';
import { selectClaimedRewards } from 'redux/selectors/rewards';
import WalletBalance from './view';
const select = state => ({
balance: selectBalance(state),
claimsBalance: selectClaimsBalance(state) || 0,
supportsBalance: selectSupportsBalance(state) || 0,
tipsBalance: selectTipsBalance(state) || 0,
rewards: selectClaimedRewards(state),
hasSynced: Boolean(selectSyncHash(state)),
fetchingUtxoCounts: selectIsFetchingUtxoCounts(state),
consolidatingUtxos: selectIsConsolidatingUtxos(state),
massClaimingTips: selectIsMassClaimingTips(state),
utxoCounts: selectUtxoCounts(state),
consolidateIsPending: selectPendingConsolidateTxid(state),
massClaimIsPending: selectPendingMassClaimTxid(state),
});
export default connect(select, {
doOpenModal,
doFetchUtxoCounts,
doUtxoConsolidate,
})(WalletBalance);
@@ -1,68 +0,0 @@
// @flow
import * as ICONS from 'constants/icons';
import * as PAGES from 'constants/pages';
import React from 'react';
import Button from 'component/button';
import Card from 'component/common/card';
import Icon from 'component/common/icon';
import I18nMessage from 'component/i18nMessage';
type Props = {
totalTippedAmount: number,
accountDetails: any,
transactions: any,
};
const WalletBalance = (props: Props) => {
const {
// accountDetails,
totalTippedAmount,
transactions,
} = props;
// const [detailsExpanded, setDetailsExpanded] = React.useState(false);
const [totalCreatorsSupported, setTotalCreatorsSupported] = React.useState(false);
// calculate how many unique users tipped
React.useEffect(() => {
if (transactions) {
let channelNames = [];
for (const transaction of transactions) {
channelNames.push(transaction.channel_name);
console.log(transaction.channel_name);
}
let unique = [...new Set(channelNames)];
setTotalCreatorsSupported(unique.length);
}
}, [transactions]);
return (
<>{<Card
title={<><Icon size="18" icon={ICONS.FINANCE} />{totalTippedAmount} USD</>}
subtitle={
<I18nMessage>
The total amount you have tipped to different creators
</I18nMessage>
}
actions={
<>
<h2 className="section__title--small">
{transactions && transactions.length} Total Tips
</h2>
<h2 className="section__title--small">
{totalCreatorsSupported || 0} Creators Supported
</h2>
<div className="section__actions">
<Button button="secondary" label={__('Manage Cards')} icon={ICONS.SETTINGS} navigate={`/$/${PAGES.SETTINGS_STRIPE_CARD}`} />
</div>
</>
}
/>}</>
);
};
export default WalletBalance;
@@ -1,40 +0,0 @@
import { connect } from 'react-redux';
import {
selectBalance,
selectClaimsBalance,
selectSupportsBalance,
selectTipsBalance,
selectIsFetchingUtxoCounts,
selectUtxoCounts,
doFetchUtxoCounts,
doUtxoConsolidate,
selectIsConsolidatingUtxos,
selectIsMassClaimingTips,
selectPendingConsolidateTxid,
selectPendingMassClaimTxid,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectSyncHash } from 'redux/selectors/sync';
import { selectClaimedRewards } from 'redux/selectors/rewards';
import WalletBalance from './view';
const select = state => ({
balance: selectBalance(state),
claimsBalance: selectClaimsBalance(state) || 0,
supportsBalance: selectSupportsBalance(state) || 0,
tipsBalance: selectTipsBalance(state) || 0,
rewards: selectClaimedRewards(state),
hasSynced: Boolean(selectSyncHash(state)),
fetchingUtxoCounts: selectIsFetchingUtxoCounts(state),
consolidatingUtxos: selectIsConsolidatingUtxos(state),
massClaimingTips: selectIsMassClaimingTips(state),
utxoCounts: selectUtxoCounts(state),
consolidateIsPending: selectPendingConsolidateTxid(state),
massClaimIsPending: selectPendingMassClaimTxid(state),
});
export default connect(select, {
doOpenModal,
doFetchUtxoCounts,
doUtxoConsolidate,
})(WalletBalance);
@@ -1,203 +0,0 @@
// @flow
import React from 'react';
import Button from 'component/button';
import Card from 'component/common/card';
import { Lbryio } from 'lbryinc';
import moment from 'moment';
type Props = {
accountDetails: any,
transactions: any,
totalTippedAmount: number,
};
const WalletBalance = (props: Props) => {
// receive transactions from parent component
let accountTransactions = props.transactions;
console.log('heres transactions');
console.log(accountTransactions);
// let totalTippedAmount = props.totalTippedAmount;
// totalTippedAmount = 0;
// reverse so most recent payments come first
if (accountTransactions) {
accountTransactions = accountTransactions.reverse();
}
// const [detailsExpanded, setDetailsExpanded] = React.useState(false);
// const [accountStatusResponse, setAccountStatusResponse] = React.useState();
// const [totalTippedAmount, setTotalTippedAmount] = React.useState(0);
const [paymentHistoryTransactions, setPaymentHistoryTransactions] = React.useState();
const [subscriptions, setSubscriptions] = React.useState();
const [lastFour, setLastFour] = React.useState();
var environment = 'test';
// function getPaymentHistory() {
// return Lbryio.call(
// 'customer',
// 'list',
// {
// environment,
// },
// 'post'
// ); };
function getCustomerStatus() {
return Lbryio.call(
'customer',
'status',
{
environment,
},
'post'
);
}
React.useEffect(() => {
(async function() {
let response = accountTransactions;
console.log('payment transactions');
console.log(response);
const customerStatusResponse = await getCustomerStatus();
setLastFour(customerStatusResponse.PaymentMethods[0].card.last4);
if (response && response.length > 10) response.length = 10;
setPaymentHistoryTransactions(response);
const subscriptions = [...response];
if (subscriptions && subscriptions.length > 2) {
subscriptions.length = 2;
setSubscriptions([]);
} else {
setSubscriptions([]);
}
console.log(response);
})();
}, [accountTransactions]);
return (
<>
<Card
title={__('Payment History')}
body={
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Card Last 4')}</th>
<th>{__('Anonymous')}</th>
</tr>
</thead>
<tbody>
{accountTransactions &&
accountTransactions.map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>{lastFour}</td>
<td>{transaction.private_tip ? 'Yes' : 'No'}</td>
</tr>
))}
</tbody>
</table>
{(!accountTransactions || accountTransactions.length === 0) && <p style={{textAlign: 'center', marginTop: '20px', fontSize: '13px', color: 'rgb(171, 171, 171)'}}>No Transactions</p>}
</div>
</>
}
/>
<Card
title={__('Subscriptions')}
body={
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Card Last 4')}</th>
<th>{__('Anonymous')}</th>
</tr>
</thead>
<tbody>
{subscriptions &&
subscriptions.reverse().map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>{lastFour}</td>
<td>{transaction.private_tip ? 'Yes' : 'No'}</td>
</tr>
))}
</tbody>
</table>
{(!subscriptions || subscriptions.length === 0) && <p style={{textAlign: 'center', marginTop: '22px', fontSize: '13px', color: 'rgb(171, 171, 171)'}}>No Subscriptions</p>}
</div>
</>
}
/>
</>
);
};
export default WalletBalance;
+228 -282
View File
@@ -122,7 +122,7 @@ function WalletSendTip(props: Props) {
// check if creator has an account saved
React.useEffect(() => {
const tipInputElement = document.getElementById('tip-input');
var tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
}, []);
@@ -141,8 +141,6 @@ function WalletSendTip(props: Props) {
.then((accountCheckResponse) => {
if (accountCheckResponse === true && canReceiveFiatTip !== true) {
setCanReceiveFiatTip(true);
} else {
setCanReceiveFiatTip(false);
}
})
.catch(function (error) {
@@ -171,8 +169,7 @@ function WalletSendTip(props: Props) {
}
const claimTypeText = setClaimTypeText();
let iconToUse;
let explainerText = '';
let iconToUse, explainerText;
if (activeTab === TAB_BOOST) {
iconToUse = ICONS.LBC;
explainerText = __('This refundable boost will improve the discoverability of this %claimTypeText% while active.', {claimTypeText});
@@ -276,8 +273,8 @@ function WalletSendTip(props: Props) {
Lbryio.call(
'customer',
'tip',
{ // round to fix issues with floating point numbers
amount: Math.round(100 * tipAmount), // convert from dollars to cents
{
amount: 100 * tipAmount, // convert from dollars to cents
creator_channel_name: tipChannelName, // creator_channel_name
creator_channel_claim_id: channelClaimId,
tipper_channel_name: sendAnonymously ? '' : activeChannelName,
@@ -298,7 +295,7 @@ function WalletSendTip(props: Props) {
});
})
.catch(function(error) {
let displayError = 'Sorry, there was an error in processing your payment!';
var displayError = 'Sorry, there was an error in processing your payment!';
if (error.message !== 'payment intent failed to confirm') {
displayError = error.message;
@@ -316,53 +313,10 @@ function WalletSendTip(props: Props) {
}
}
const countDecimals = function(value) {
const text = value.toString();
const index = text.indexOf('.');
return (text.length - index - 1);
};
function handleCustomPriceChange(event: SyntheticInputEvent<*>) {
let tipAmountAsString = event.target.value;
const tipAmount = parseFloat(event.target.value);
let tipAmount = parseFloat(tipAmountAsString);
const howManyDecimals = countDecimals(tipAmountAsString);
// fiat tip input
if (activeTab === TAB_FIAT) {
if (Number.isNaN(tipAmount)) {
setCustomTipAmount('');
}
// allow maximum of two decimal places
if (howManyDecimals > 2) {
tipAmount = Math.floor(tipAmount * 100) / 100;
}
// remove decimals, and then get number of digits
const howManyDigits = Math.trunc(tipAmount).toString().length;
if (howManyDigits > 4 && tipAmount !== 1000) {
setTipError('Amount cannot be over 1000 dollars');
setCustomTipAmount(tipAmount);
} else if (tipAmount > 1000) {
setTipError('Amount cannot be over 1000 dollars');
setCustomTipAmount(tipAmount);
} else {
setCustomTipAmount(tipAmount);
}
// LBC tip input
} else {
// TODO: this is a bit buggy, needs a touchup
// if (howManyDecimals > 9) {
// // only allows up to 8 decimal places
// tipAmount = Number(tipAmount.toString().match(/^-?\d+(?:\.\d{0,8})?/)[0]);
//
// setTipError('Please only use up to 8 decimals');
// }
setCustomTipAmount(tipAmount);
}
setCustomTipAmount(tipAmount);
}
function buildButtonText() {
@@ -377,14 +331,8 @@ function WalletSendTip(props: Props) {
return false;
}
function convertToTwoDecimals(number) {
return (Math.round(number * 100) / 100).toFixed(2);
}
const amountToShow = activeTab === TAB_FIAT ? convertToTwoDecimals(tipAmount) : tipAmount;
// if it's a valid number display it, otherwise do an empty string
const displayAmount = !isNan(tipAmount) ? amountToShow : '';
const displayAmount = !isNan(tipAmount) ? tipAmount : '';
if (activeTab === TAB_BOOST) {
return (claimIsMine ? __('Boost Your %claimTypeText%', {claimTypeText}) : __('Boost This %claimTypeText%', {claimTypeText}));
@@ -414,242 +362,240 @@ function WalletSendTip(props: Props) {
return (
<Form onSubmit={handleSubmit}>
{/* if there is no LBC balance, show user frontend to get credits */}
{/* if there is lbc, the main tip/boost gui with the 3 tabs at the top */}
<Card
title={<LbcSymbol postfix={claimIsMine ? __('Boost Your %claimTypeText%', {claimTypeText}) : __('Support This %claimTypeText%', {claimTypeText})} size={22} />}
subtitle={
<React.Fragment>
{!claimIsMine && (
<div className="section">
{/* tip LBC tab button */}
<Button
key="tip"
icon={ICONS.LBC}
label={__('Tip')}
button="alt"
onClick={() => {
const tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_LBC);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_LBC })}
/>
{/* tip fiat tab button */}
{/* @if TARGET='web' */}
<Button
key="tip-fiat"
icon={ICONS.FINANCE}
label={__('Tip')}
button="alt"
onClick={() => {
const tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_FIAT);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_FIAT })}
/>
{/* @endif */}
{/* tip LBC tab button */}
<Button
key="boost"
icon={ICONS.TRENDING}
label={__('Boost')}
button="alt"
onClick={() => {
const tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_BOOST);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_BOOST })}
/>
</div>
)}
{/* short explainer under the button */}
<div className="section__subtitle">
{explainerText + ' '}
{/* {activeTab === TAB_FIAT && !hasCardSaved && <Button navigate={`/$/${PAGES.SETTINGS_STRIPE_CARD}`} label={__('Add A Card')} button="link" />} */}
{<Button label={__('Learn more')} button="link" href="https://lbry.com/faq/tipping" />}
{noBalance ? (
<Card
title={<I18nMessage tokens={{ lbc: <LbcSymbol size={22} /> }}>Supporting content requires %lbc%</I18nMessage>}
subtitle={
<I18nMessage tokens={{ lbc: <LbcSymbol /> }}>
With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to
see.
</I18nMessage>
}
actions={
<div className="section__actions">
<Button
icon={ICONS.REWARDS}
button="primary"
label={__('Earn Rewards')}
navigate={`/$/${PAGES.REWARDS}`}
/>
<Button icon={ICONS.BUY} button="secondary" label={__('Buy/Swap Credits')} navigate={`/$/${PAGES.BUY}`} />
<Button button="link" label={__('Nevermind')} onClick={closeModal} />
</div>
</React.Fragment>
}
actions={
// confirmation modal, allow user to confirm or cancel transaction
isConfirming ? (
<>
<div className="section section--padded card--inline confirm__wrapper">
}
/>
) : (
// if there is lbc, the main tip/boost gui with the 3 tabs at the top
<Card
title={<LbcSymbol postfix={claimIsMine ? __('Boost Your %claimTypeText%', {claimTypeText}) : __('Support This %claimTypeText%', {claimTypeText})} size={22} />}
subtitle={
<React.Fragment>
{!claimIsMine && (
<div className="section">
<div className="confirm__label">{__('To --[the tip recipient]--')}</div>
<div className="confirm__value">{channelName || title}</div>
<div className="confirm__label">{__('From --[the tip sender]--')}</div>
<div className="confirm__value">
{activeChannelClaim && !incognito ? activeChannelClaim.name : __('Anonymous')}
</div>
<div className="confirm__label">{setConfirmLabel()}</div>
<div className="confirm__value">
{activeTab === TAB_FIAT ? <p>$ {(Math.round(tipAmount * 100) / 100).toFixed(2)}</p> : <LbcSymbol postfix={tipAmount} size={22} />}
</div>
{/* tip LBC tab button */}
<Button
key="tip"
icon={ICONS.LBC}
label={__('Tip')}
button="alt"
onClick={() => {
var tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_LBC);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_LBC })}
/>
{/* tip fiat tab button */}
{/* @if TARGET='web' */}
<Button
key="tip-fiat"
icon={ICONS.FINANCE}
label={__('Tip')}
button="alt"
onClick={() => {
var tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_FIAT);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_FIAT })}
/>
{/* @endif */}
{/* tip LBC tab button */}
<Button
key="boost"
icon={ICONS.TRENDING}
label={__('Boost')}
button="alt"
onClick={() => {
var tipInputElement = document.getElementById('tip-input');
if (tipInputElement) { tipInputElement.focus() }
if (!isConfirming) {
setActiveTab(TAB_BOOST);
}
}}
className={classnames('button-toggle', { 'button-toggle--active': activeTab === TAB_BOOST })}
/>
</div>
</div>
<div className="section__actions">
<Button
autoFocus
onClick={handleSubmit}
button="primary"
disabled={isPending}
label={__('Confirm')}
/>
<Button button="link" label={__('Cancel')} onClick={() => setIsConfirming(false)} />
</div>
</>
// only show the prompt to earn more if its lbc or boost tab and no balance
// otherwise you can show the full prompt
) : (!((activeTab === TAB_LBC || activeTab === TAB_BOOST) && noBalance)
? <>
<div className="section">
<ChannelSelector />
</div>
{activeTab === TAB_FIAT && !hasCardSaved && (
<h3 className="add-card-prompt">
<Button navigate={`/$/${PAGES.SETTINGS_STRIPE_CARD}`} label={__('Add a Card')} button="link" />
{' '}{__('To Tip Creators')}
</h3>
)}
{/* section to pick tip/boost amount */}
<div className="section">
{DEFAULT_TIP_AMOUNTS.map((amount) => (
{/* short explainer under the button */}
<div className="section__subtitle">
{explainerText}
{/* {activeTab === TAB_FIAT && !hasCardSaved && <Button navigate={`/$/${PAGES.SETTINGS_STRIPE_CARD}`} label={__('Add A Card')} button="link" />} */}
{<Button label={__('Learn more')} button="link" href="https://lbry.com/faq/tipping" />}
</div>
</React.Fragment>
}
actions={
// confirmation modal, allow user to confirm or cancel transaction
isConfirming ? (
<>
<div className="section section--padded card--inline confirm__wrapper">
<div className="section">
<div className="confirm__label">{__('To --[the tip recipient]--')}</div>
<div className="confirm__value">{channelName || title}</div>
<div className="confirm__label">{__('From --[the tip sender]--')}</div>
<div className="confirm__value">
{activeChannelClaim && !incognito ? activeChannelClaim.name : __('Anonymous')}
</div>
<div className="confirm__label">{setConfirmLabel()}</div>
<div className="confirm__value">
{activeTab === TAB_FIAT ? <p>$ {tipAmount}</p> : <LbcSymbol postfix={tipAmount} size={22} />}
</div>
</div>
</div>
<div className="section__actions">
<Button
autoFocus
onClick={handleSubmit}
button="primary"
disabled={isPending}
label={__('Confirm')}
/>
<Button button="link" label={__('Cancel')} onClick={() => setIsConfirming(false)} />
</div>
</>
) : (
<>
<div className="section">
<ChannelSelector />
</div>
{activeTab === TAB_FIAT && !hasCardSaved && (
<h3 className="add-card-prompt">
<Button navigate={`/$/${PAGES.SETTINGS_STRIPE_CARD}`} label={__('Add a Card')} button="link" />
{' '}{__('To Tip Creators')}
</h3>
)}
{/* section to pick tip/boost amount */}
<div className="section">
{DEFAULT_TIP_AMOUNTS.map((amount) => (
<Button
key={amount}
disabled={shouldDisableAmountSelector(amount)}
button="alt"
className={classnames('button-toggle button-toggle--expandformobile', {
'button-toggle--active': tipAmount === amount && !useCustomTip,
'button-toggle--disabled': amount > balance,
})}
label={amount}
icon={iconToUse}
onClick={() => {
setPresetTipAmount(amount);
setUseCustomTip(false);
}}
/>
))}
<Button
key={amount}
disabled={shouldDisableAmountSelector(amount)}
button="alt"
className={classnames('button-toggle button-toggle--expandformobile', {
'button-toggle--active': tipAmount === amount && !useCustomTip,
'button-toggle--disabled': amount > balance,
'button-toggle--active': useCustomTip, // set as active
})}
label={amount}
icon={iconToUse}
onClick={() => {
setPresetTipAmount(amount);
setUseCustomTip(false);
}}
label={__('Custom')}
onClick={() => setUseCustomTip(true)}
// disabled if it's receive fiat and there is no card or creator can't receive tips
disabled={activeTab === TAB_FIAT && (!hasCardSaved || !canReceiveFiatTip)}
/>
))}
<Button
button="alt"
className={classnames('button-toggle button-toggle--expandformobile', {
'button-toggle--active': useCustomTip, // set as active
})}
icon={iconToUse}
label={__('Custom')}
onClick={() => setUseCustomTip(true)}
// disabled if it's receive fiat and there is no card or creator can't receive tips
disabled={activeTab === TAB_FIAT && (!hasCardSaved || !canReceiveFiatTip)}
/>
{DEFAULT_TIP_AMOUNTS.some((val) => val > balance) && activeTab !== TAB_FIAT && (
<Button
button="secondary"
className="button-toggle-group-action"
icon={ICONS.BUY}
title={__('Buy or swap more LBRY Credits')}
navigate={`/$/${PAGES.BUY}`}
/>
)}
</div>
{useCustomTip && (
<div className="section">
<FormField
autoFocus
name="tip-input"
label={
<React.Fragment>
{__('Custom support amount')}{' '}
{activeTab !== TAB_FIAT ? (
<I18nMessage
tokens={{ lbc_balance: <CreditAmount precision={4} amount={balance} showLBC={false} /> }}
>
(%lbc_balance% Credits available)
</I18nMessage>
) : (
'in USD'
)}
</React.Fragment>
}
error={tipError}
min="0"
step="any"
type="number"
style={{
width: activeTab === TAB_FIAT ? '99px' : '160px',
}}
placeholder="1.23"
value={customTipAmount}
onChange={(event) => handleCustomPriceChange(event)}
/>
{DEFAULT_TIP_AMOUNTS.some((val) => val > balance) && activeTab !== TAB_FIAT && (
<Button
button="secondary"
className="button-toggle-group-action"
icon={ICONS.BUY}
title={__('Buy or swap more LBRY Credits')}
navigate={`/$/${PAGES.BUY}`}
/>
)}
</div>
)}
{/* send tip/boost button */}
<div className="section__actions">
<Button
autoFocus
icon={isSupport ? ICONS.TRENDING : ICONS.SUPPORT}
button="primary"
type="submit"
disabled={
fetchingChannels ||
isPending ||
tipError ||
!tipAmount ||
(activeTab === TAB_FIAT && (!hasCardSaved || !canReceiveFiatTip))
}
label={buildButtonText()}
/>
{fetchingChannels && <span className="help">{__('Loading your channels...')}</span>}
</div>
{activeTab !== TAB_FIAT ? (
<WalletSpendableBalanceHelp />
) : !canReceiveFiatTip ? (
<div className="help">{__('Only select creators can receive tips at this time')}</div>
) : (
<div className="help">{__('The payment will be made from your saved card')}</div>
)}
</>
// if it's LBC and there is no balance, you can prompt to purchase LBC
: <Card
title={<I18nMessage tokens={{ lbc: <LbcSymbol size={22} /> }}>Supporting content requires %lbc%</I18nMessage>}
subtitle={
<I18nMessage tokens={{ lbc: <LbcSymbol /> }}>
With %lbc%, you can send tips to your favorite creators, or help boost their content for more people to
see.
</I18nMessage>
}
actions={
<div className="section__actions">
<Button
icon={ICONS.REWARDS}
button="primary"
label={__('Earn Rewards')}
navigate={`/$/${PAGES.REWARDS}`}
/>
<Button icon={ICONS.BUY} button="secondary" label={__('Buy/Swap Credits')} navigate={`/$/${PAGES.BUY}`} />
<Button button="link" label={__('Nevermind')} onClick={closeModal} />
</div>
}
/>
)
}
/>
{useCustomTip && (
<div className="section">
<FormField
autoFocus
name="tip-input"
label={
<React.Fragment>
{__('Custom support amount')}{' '}
{activeTab !== TAB_FIAT ? (
<I18nMessage
tokens={{ lbc_balance: <CreditAmount precision={4} amount={balance} showLBC={false} /> }}
>
(%lbc_balance% Credits available)
</I18nMessage>
) : (
'in USD'
)}
</React.Fragment>
}
className="form-field--price-amount"
error={tipError}
min="0"
step="any"
type="number"
placeholder="1.23"
value={customTipAmount}
onChange={(event) => handleCustomPriceChange(event)}
/>
</div>
)}
{/* send tip/boost button */}
<div className="section__actions">
<Button
autoFocus
icon={isSupport ? ICONS.TRENDING : ICONS.SUPPORT}
button="primary"
type="submit"
disabled={
fetchingChannels ||
isPending ||
tipError ||
!tipAmount ||
(activeTab === TAB_FIAT && (!hasCardSaved || !canReceiveFiatTip))
}
label={buildButtonText()}
/>
{fetchingChannels && <span className="help">{__('Loading your channels...')}</span>}
</div>
{activeTab !== TAB_FIAT ? (
<WalletSpendableBalanceHelp />
) : !canReceiveFiatTip ? (
<div className="help">{__('Only select creators can receive tips at this time')}</div>
) : (
<div className="help">{__('The payment will be made from your saved card')}</div>
)}
</>
)
}
/>
)}
</Form>
);
}
@@ -263,6 +263,7 @@ function WalletTipAmountSelector(props: Props) {
// </div>
// </>
}
className="form-field--price-amount"
error={tipError}
min="0"
step="any"
-2
View File
@@ -98,8 +98,6 @@ export const CLEAR_CONTENT_POSITION = 'CLEAR_CONTENT_POSITION';
export const SET_CONTENT_LAST_VIEWED = 'SET_CONTENT_LAST_VIEWED';
export const CLEAR_CONTENT_HISTORY_URI = 'CLEAR_CONTENT_HISTORY_URI';
export const CLEAR_CONTENT_HISTORY_ALL = 'CLEAR_CONTENT_HISTORY_ALL';
export const RECOMMENDATION_UPDATED = 'RECOMMENDATION_UPDATED';
export const RECOMMENDATION_CLICKED = 'RECOMMENDATION_CLICKED';
// Files
export const FILE_LIST_STARTED = 'FILE_LIST_STARTED';
+1 -1
View File
@@ -9,7 +9,7 @@ export const PAGE_PARAM = 'page';
export const PAGE_SIZE_PARAM = 'page_size';
export const INVALID_NAME_ERROR =
__('LBRY names cannot contain spaces or reserved symbols') + ' ' + '(?$#@;:/\\="<>%{}|^~[]`)';
__('LBRY names cannot contain spaces or reserved symbols') + ' ' + '(?$#@;:/"<>%{}|^~[]`)';
export const FORCE_CONTENT_TYPE_PLAYER = [
'video/quicktime',
-1
View File
@@ -1 +0,0 @@
export const CONTAINER_ID = 'CONTAINER_ID';
+2 -2
View File
@@ -5,13 +5,13 @@ import {
doResolveUri,
makeSelectClaimForUri,
makeSelectIsAbandoningClaimForUri,
makeSelectClaimIsMine,
} from 'lbry-redux';
import { doHideModal } from 'redux/actions/app';
import ModalRemoveFile from './view';
import { makeSelectSigningIsMine } from 'redux/selectors/content';
const select = (state, props) => ({
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
claimIsMine: makeSelectSigningIsMine(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
isAbandoning: makeSelectIsAbandoningClaimForUri(props.uri)(state),
+1 -3
View File
@@ -125,11 +125,9 @@ function DiscoverPage(props: Props) {
// Assume wild west page if no dynamicRouteProps
// Not a very good solution, but just doing it for now
// until we are sure this page will stay around
// TODO: find a better way to determine discover / wild west vs other modes release times
// for now including && !tags so that
releaseTime={
SIMPLE_SITE
? !dynamicRouteProps && !tags && `>${Math.floor(moment().subtract(1, 'day').startOf('week').unix())}`
? !dynamicRouteProps && `>${Math.floor(moment().subtract(1, 'day').startOf('week').unix())}`
: undefined
}
feeAmount={SIMPLE_SITE ? !dynamicRouteProps && CS.FEE_AMOUNT_ANY : undefined}
+1 -1
View File
@@ -1,6 +1,6 @@
import { connect } from 'react-redux';
import { doSetContentHistoryItem, doSetPrimaryUri } from 'redux/actions/content';
import { withRouter } from 'react-router-dom';
import { withRouter } from 'react-router';
import {
doFetchFileInfo,
makeSelectFileInfoForUri,
-5
View File
@@ -5,7 +5,6 @@ import { FormField, FormFieldPrice } from 'component/common/form';
import Button from 'component/button';
import I18nMessage from 'component/i18nMessage';
import Page from 'component/page';
import SettingCommentsServer from 'component/settingCommentsServer';
import SettingWalletServer from 'component/settingWalletServer';
import SettingAutoLaunch from 'component/settingAutoLaunch';
import SettingClosingBehavior from 'component/settingClosingBehavior';
@@ -508,10 +507,6 @@ class SettingsAdvancedPage extends React.PureComponent<Props, State> {
/>
)}
{/* @if TARGET='app' */}
<Card title={__('Comments server')} actions={<SettingCommentsServer />} />
{/* @endif */}
<Card title={__('Upload settings')} actions={<PublishSettings />} />
{/* @if TARGET='app' */}
+3 -5
View File
@@ -2,14 +2,12 @@ import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import StripeAccountConnection from './view';
import { selectUser } from 'redux/selectors/user';
import { doToast } from 'redux/actions/notifications';
// function that receives state parameter and returns object of functions that accept state
const select = (state) => ({
user: selectUser(state),
});
const perform = (dispatch) => ({
doToast: (options) => dispatch(doToast(options)),
});
// const perform = (dispatch) => ({});
export default withRouter(connect(select, perform)(StripeAccountConnection));
export default withRouter(connect(select)(StripeAccountConnection));
+78 -20
View File
@@ -1,13 +1,12 @@
// @flow
import * as ICONS from 'constants/icons';
import * as PAGES from 'constants/pages';
import React from 'react';
import Button from 'component/button';
import Card from 'component/common/card';
import Page from 'component/page';
import { Lbryio } from 'lbryinc';
import { URL, WEBPACK_WEB_PORT, STRIPE_PUBLIC_KEY } from 'config';
import moment from 'moment';
const isDev = process.env.NODE_ENV !== 'production';
@@ -32,8 +31,6 @@ if (isDev) {
type Props = {
source: string,
user: User,
doOpenModal: (string, {}) => void,
doToast: ({ message: string }) => void,
};
type State = {
@@ -71,8 +68,6 @@ class StripeAccountConnection extends React.Component<Props, State> {
componentDidMount() {
const { user } = this.props;
let doToast = this.props.doToast;
// $FlowFixMe
this.experimentalUiEnabled = user && user.experimental_ui;
@@ -132,8 +127,10 @@ class StripeAccountConnection extends React.Component<Props, State> {
).then((accountListResponse: any) => {
// TODO type this
that.setState({
accountTransactions: accountListResponse.reverse(),
accountTransactions: accountListResponse,
});
console.log(accountListResponse);
});
}
@@ -168,9 +165,6 @@ class StripeAccountConnection extends React.Component<Props, State> {
// get stripe link and set it on the frontend
getAndSetAccountLink(true);
} else {
// probably an error from stripe
const displayString = 'There was an error getting your account setup, please let support know';
doToast({ message: displayString, isError: true });
// not an error from Beamer, throw it
throw new Error(error);
}
@@ -185,7 +179,7 @@ class StripeAccountConnection extends React.Component<Props, State> {
unpaidBalance,
accountNotConfirmedButReceivedTips,
pageTitle,
// accountTransactions,
accountTransactions,
} = this.state;
const { user } = this.props;
@@ -229,11 +223,25 @@ class StripeAccountConnection extends React.Component<Props, State> {
<div>
<div>
<h3>{__('Congratulations! Your account has been connected with Odysee.')}</h3>
{unpaidBalance > 0 ? (
<div>
<br />
<h3>
{__('Your pending account balance is $%balance% USD.', { balance: unpaidBalance / 100 })}
</h3>
</div>
) : (
<div>
<br />
<h3>
{__('Your account balance is $0 USD. When you receive a tip you will see it here.')}
</h3>
</div>
)}
</div>
</div>
</div>
)}
{/* TODO: hopefully we won't be using this anymore and can remove it */}
{accountNotConfirmedButReceivedTips && (
<div className="card__body-actions">
<div>
@@ -264,16 +272,66 @@ class StripeAccountConnection extends React.Component<Props, State> {
)}
</div>
}
actions={
<Button
button="primary"
label={__('View Transactions')}
icon={ICONS.SETTINGS}
navigate={`/$/${PAGES.WALLET}?tab=account-history`}
/>
}
/>
<br />
{/* customer already has transactions */}
{accountTransactions && accountTransactions.length > 0 && (
<Card
title={__('Tip History')}
body={
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Processing Fee')}</th>
<th>{__('Odysee Fee')}</th>
<th>{__('Received Amount')}</th>
</tr>
</thead>
<tbody>
{accountTransactions &&
accountTransactions.reverse().map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>${transaction.transaction_fee / 100}</td>
<td>${transaction.application_fee / 100}</td>
<td>${transaction.received_amount / 100}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
}
/>
)}
</Page>
);
} else {
+69 -17
View File
@@ -6,11 +6,11 @@ import Page from 'component/page';
import Card from 'component/common/card';
import { Lbryio } from 'lbryinc';
import { STRIPE_PUBLIC_KEY } from 'config';
import moment from 'moment';
import Plastic from 'react-plastic';
import Button from 'component/button';
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
import * as PAGES from 'constants/pages';
let stripeEnvironment = 'test';
// if the key contains pk_live it's a live key
@@ -19,9 +19,6 @@ if (STRIPE_PUBLIC_KEY.indexOf('pk_live') > -1) {
stripeEnvironment = 'live';
}
const APIS_DOWN_ERROR_RESPONSE = 'There was an error from the server, please let support know';
const CARD_SETUP_ERROR_RESPONSE = 'There was an error getting your card setup, please let support know';
// eslint-disable-next-line flowtype/no-types-missing-file-annotation
type Props = {
disabled: boolean,
@@ -184,17 +181,18 @@ class SettingsStripeCard extends React.Component<Props, State> {
},
'post'
).then((customerSetupResponse) => {
console.log(customerSetupResponse);
clientSecret = customerSetupResponse.client_secret;
// instantiate stripe elements
setupStripe();
});
// 500 error from the backend being down
} else if (error === 'internal_apis_down') {
doToast({ message: APIS_DOWN_ERROR_RESPONSE, isError: true });
var displayString = 'There was an error from the server, please let support know';
doToast({ message: displayString, isError: true });
} else {
// probably an error from stripe
doToast({ message: CARD_SETUP_ERROR_RESPONSE, isError: true });
console.log('Unseen before error');
}
});
}, 250);
@@ -368,7 +366,7 @@ class SettingsStripeCard extends React.Component<Props, State> {
const { scriptFailedToLoad, openModal } = this.props;
const { currentFlowStage, pageTitle, userCardDetails, paymentMethodId } = this.state;
const { currentFlowStage, customerTransactions, pageTitle, userCardDetails, paymentMethodId } = this.state;
return (
<Page backout={{ title: pageTitle, backLabel: __('Done') }} noFooter noSideNavigation>
@@ -432,18 +430,72 @@ class SettingsStripeCard extends React.Component<Props, State> {
/>
</>
}
actions={
<Button
button="primary"
label={__('View Transactions')}
icon={ICONS.SETTINGS}
navigate={`/$/${PAGES.WALLET}?tab=payment-history`}
/>
}
/>
<br />
{/* if a user has no transactions yet */}
{(!customerTransactions || customerTransactions.length === 0) && (
<Card
title={__('Tip History')}
subtitle={__('You have not sent any tips yet. When you do they will appear here. ')}
/>
)}
</div>
)}
{/* customer already has transactions */}
{customerTransactions && customerTransactions.length > 0 && (
<Card
title={__('Tip History')}
body={
<>
<div className="table__wrapper">
<table className="table table--transactions">
<thead>
<tr>
<th className="date-header">{__('Date')}</th>
<th>{<>{__('Receiving Channel Name')}</>}</th>
<th>{__('Tip Location')}</th>
<th>{__('Amount (USD)')} </th>
<th>{__('Anonymous')}</th>
</tr>
</thead>
<tbody>
{customerTransactions &&
customerTransactions.reverse().map((transaction) => (
<tr key={transaction.name + transaction.created_at}>
<td>{moment(transaction.created_at).format('LLL')}</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.channel_claim_id}
label={transaction.channel_name}
button="link"
/>
</td>
<td>
<Button
className="stripe__card-link-text"
navigate={'/' + transaction.channel_name + ':' + transaction.source_claim_id}
label={
transaction.channel_claim_id === transaction.source_claim_id
? 'Channel Page'
: 'File Page'
}
button="link"
/>
</td>
<td>${transaction.tipped_amount / 100}</td>
<td>{transaction.private_tip ? 'Yes' : 'No'}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
}
/>
)}
</Page>
);
}
+2 -6
View File
@@ -12,13 +12,10 @@ import Card from 'component/common/card';
import { formatLbryUrlForWeb } from 'util/url';
import { parseURI, COLLECTIONS_CONSTS } from 'lbry-redux';
const AbandonedChannelPreview = lazyImport(() =>
import('component/abandonedChannelPreview' /* webpackChunkName: "abandonedChannelPreview" */)
);
const AbandonedChannelPreview = lazyImport(() => import('component/abandonedChannelPreview' /* webpackChunkName: "abandonedChannelPreview" */));
const FilePage = lazyImport(() => import('page/file' /* webpackChunkName: "filePage" */));
const LivestreamPage = lazyImport(() => import('page/livestream' /* webpackChunkName: "livestream" */));
const Yrbl = lazyImport(() => import('component/yrbl' /* webpackChunkName: "yrbl" */));
const isDev = process.env.NODE_ENV !== 'production';
type Props = {
isResolvingUri: boolean,
@@ -88,8 +85,7 @@ function ShowPage(props: Props) {
const canonicalUrlPath = '/' + canonicalUrl.replace(/^lbry:\/\//, '').replace(/#/g, ':');
// Only redirect if we are in lbry.tv land
// replaceState will fail if on a different domain (like webcache.googleusercontent.com)
const hostname = isDev ? 'localhost' : DOMAIN;
if (canonicalUrlPath !== window.location.pathname && hostname === window.location.hostname) {
if (canonicalUrlPath !== window.location.pathname && DOMAIN === window.location.hostname) {
const urlParams = new URLSearchParams(search);
if (urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID)) {
const listId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID) || '';
+1 -3
View File
@@ -40,9 +40,7 @@ function TopPage(props: Props) {
label={__('Repost Here')}
/>
),
publish: (
<Button button="secondary" onClick={() => beginPublish(queryName)} label={__('Publish Here')} />
),
publish: <Button button="secondary" onClick={() => beginPublish(queryName)} label={'Publish Here'} />,
}}
>
%repost% %publish%
+17 -202
View File
@@ -2,15 +2,10 @@
import React from 'react';
import { withRouter } from 'react-router';
import WalletBalance from 'component/walletBalance';
import WalletFiatBalance from 'component/walletFiatBalance';
import WalletFiatPaymentBalance from 'component/walletFiatPaymentBalance';
import WalletFiatAccountHistory from 'component/walletFiatAccountHistory';
import WalletFiatPaymentHistory from 'component/walletFiatPaymentHistory';
import TxoList from 'component/txoList';
import Page from 'component/page';
import Spinner from 'component/spinner';
import YrblWalletEmpty from 'component/yrblWalletEmpty';
import { Lbryio } from 'lbryinc';
type Props = {
history: { action: string, push: (string) => void, replace: (string) => void },
@@ -19,143 +14,6 @@ type Props = {
};
const WalletPage = (props: Props) => {
console.log(props);
const stripeEnvironment = 'test';
const tab = new URLSearchParams(props.location.search).get('tab');
const [accountStatusResponse, setAccountStatusResponse] = React.useState();
const [accountTransactionResponse, setAccountTransactionResponse] = React.useState();
const [customerTransactions, setCustomerTransactions] = React.useState();
const [totalTippedAmount, setTotalTippedAmount] = React.useState(0);
function getPaymentHistory() {
return Lbryio.call(
'customer',
'list',
{
environment: stripeEnvironment,
},
'post'
); };
// function getCustomerStatus() {
// return Lbryio.call(
// 'customer',
// 'status',
// {
// environment: stripeEnvironment,
// },
// 'post'
// );
// }
function getAccountStatus() {
return Lbryio.call(
'account',
'status',
{
environment: stripeEnvironment,
},
'post'
);
}
function getAccountTransactionsa() {
return Lbryio.call(
'account',
'list',
{
environment: stripeEnvironment,
},
'post'
);
}
// calculate account transactions section
React.useEffect(() => {
(async function() {
try {
const response = await getAccountStatus();
setAccountStatusResponse(response);
// TODO: some weird naming clash hence getAccountTransactionsa
const getAccountTransactions = await getAccountTransactionsa();
setAccountTransactionResponse(getAccountTransactions);
} catch (err) {
console.log(err);
}
})();
}, []);
// populate customer payment data
React.useEffect(() => {
(async function() {
try {
// get card payments customer has made
const customerTransactionResponse = await getPaymentHistory();
let totalTippedAmount = 0;
for (const transaction of customerTransactionResponse) {
totalTippedAmount = totalTippedAmount + transaction.tipped_amount;
}
setTotalTippedAmount(totalTippedAmount / 100);
setCustomerTransactions(customerTransactionResponse);
} catch (err) {
console.log(err);
}
})();
}, []);
function focusLBCTab() {
document.getElementsByClassName('lbc-transactions')[0].style.display = 'inline';
document.getElementsByClassName('fiat-transactions')[0].style.display = 'none';
document.getElementsByClassName('payment-history-tab')[0].style.display = 'none';
document.getElementsByClassName('lbc-tab-switcher')[0].style.textDecoration = 'underline';
document.getElementsByClassName('fiat-tab-switcher')[0].style.textDecoration = 'none';
document.getElementsByClassName('fiat-payment-history-switcher')[0].style.textDecoration = 'none';
}
function focusAccountHistoryTab() {
document.getElementsByClassName('lbc-transactions')[0].style.display = 'none';
document.getElementsByClassName('payment-history-tab')[0].style.display = 'none';
document.getElementsByClassName('fiat-transactions')[0].style.display = 'inline';
document.getElementsByClassName('lbc-tab-switcher')[0].style.textDecoration = 'none';
document.getElementsByClassName('fiat-tab-switcher')[0].style.textDecoration = 'underline';
document.getElementsByClassName('fiat-payment-history-switcher')[0].style.textDecoration = 'none';
}
function focusPaymentHistoryTab() {
document.getElementsByClassName('lbc-transactions')[0].style.display = 'none';
document.getElementsByClassName('fiat-transactions')[0].style.display = 'none';
document.getElementsByClassName('payment-history-tab')[0].style.display = 'inline';
document.getElementsByClassName('lbc-tab-switcher')[0].style.textDecoration = 'none';
document.getElementsByClassName('fiat-tab-switcher')[0].style.textDecoration = 'none';
document.getElementsByClassName('fiat-payment-history-switcher')[0].style.textDecoration = 'underline';
}
// select the first tab
React.useEffect(() => {
if (tab === 'account-history') {
// if (1 === 2) {
focusAccountHistoryTab();
} else if (tab === 'payment-history') {
// } else if (1 === 2){
focusPaymentHistoryTab();
} else {
focusLBCTab();
}
}, []);
const { location, totalBalance } = props;
const { search } = location;
const showIntro = totalBalance === 0;
@@ -163,66 +21,23 @@ const WalletPage = (props: Props) => {
return (
<Page>
{/* tabs to switch between fiat and lbc */}
{/* lbc button */}
<h2 className="lbc-tab-switcher"
style={{display: 'inline-block', paddingBottom: '16px', marginRight: '14px', textUnderlineOffset: '4px', fontSize: '18px', marginLeft: '3px'}}
onClick={() => {
focusLBCTab();
}}
>LBC Wallet</h2>
{/* account history button */}
<h2 className="fiat-tab-switcher"
style={{display: 'inline-block', textUnderlineOffset: '4px', fontSize: '18px', marginRight: '14px'}}
onClick={() => {
focusAccountHistoryTab();
}}
>Account History</h2>
{/* payment history button */}
<h2 className="fiat-payment-history-switcher"
style={{display: 'inline-block', textUnderlineOffset: '4px', fontSize: '18px'}}
onClick={() => {
focusPaymentHistoryTab();
}}
>Payment History</h2>
{/* lbc wallet section */}
<div className="lbc-transactions">
{/* if the transactions are loading */}
{ loading && (
<div className="main--empty">
<Spinner delayed />
</div>
)}
{/* when the transactions are finished loading */}
{ !loading && (
<>
{showIntro ? (
<YrblWalletEmpty includeWalletLink />
) : (
<div className="card-stack">
<WalletBalance />
<TxoList search={search} />
</div>
)}
</>
)}
</div>
{/* account received transactions section */}
<div className="fiat-transactions" style={{display: 'none'}}>
<WalletFiatBalance accountDetails={accountStatusResponse} />
<div style={{paddingTop: '25px'}} />
<WalletFiatAccountHistory transactions={accountTransactionResponse} />
</div>
{/* fiat payment history for tips made by user */}
<div className="payment-history-tab" style={{display: 'none'}}>
<WalletFiatPaymentBalance transactions={customerTransactions} totalTippedAmount={totalTippedAmount} accountDetails={accountStatusResponse} />
<div style={{paddingTop: '25px'}} />
<WalletFiatPaymentHistory transactions={customerTransactions} />
</div>
{loading && (
<div className="main--empty">
<Spinner delayed />
</div>
)}
{!loading && (
<>
{showIntro ? (
<YrblWalletEmpty includeWalletLink />
) : (
<div className="card-stack">
<WalletBalance />
<TxoList search={search} />
</div>
)}
</>
)}
</Page>
);
};
+57 -67
View File
@@ -28,22 +28,6 @@ import { selectPrefsReady } from 'redux/selectors/sync';
import { doAlertWaitingForSync } from 'redux/actions/app';
const isDev = process.env.NODE_ENV !== 'production';
const FETCH_API_FAILED_TO_FETCH = 'Failed to fetch';
const COMMENTRON_MSG_REMAP = {
// <-- Commentron msg --> : <-- App msg -->
'channel is blocked by publisher': 'Unable to comment. This channel has blocked you.',
'channel is not allowed to post comments': 'Unable to comment. Your channel has been blocked by an admin.',
'comments are disabled by the creator': 'Unable to comment. The content owner has disabled comments.',
'duplicate comment!': 'Please do not spam.',
};
const COMMENTRON_REGEX_MAP = {
// <-- App msg --> : <-- Regex of Commentron msg -->
'Your user name "%1%" is too close to the creator\'s user name "%2%" and may cause confusion. Please use another identity.': /^your user name (.*) is too close to the creator's user name (.*) and may cause confusion. Please use another identity.$/,
'Slow mode is on. Please wait up to %1% seconds before commenting again.': /^Slow mode is on. Please wait at most (.*) seconds before commenting again.$/,
'The comment contains contents that are blocked by %1%.': /^the comment contents are blocked by (.*)$/,
};
function devToast(dispatch, msg) {
if (isDev) {
@@ -112,32 +96,20 @@ export function doCommentList(
return result;
})
.catch((error) => {
switch (error.message) {
case 'comments are disabled by the creator':
dispatch({
type: ACTIONS.COMMENT_LIST_COMPLETED,
data: {
authorClaimId: authorChannelClaim ? authorChannelClaim.claim_id : undefined,
disabled: true,
},
});
break;
case FETCH_API_FAILED_TO_FETCH:
dispatch(
doToast({
isError: true,
message: Comments.isCustomServer
? __('Failed to fetch comments. Verify custom server settings.')
: __('Failed to fetch comments.'),
})
);
dispatch({ type: ACTIONS.COMMENT_LIST_FAILED, data: error });
break;
default:
dispatch(doToast({ isError: true, message: `${error.message}` }));
dispatch({ type: ACTIONS.COMMENT_LIST_FAILED, data: error });
if (error.message === 'comments are disabled by the creator') {
dispatch({
type: ACTIONS.COMMENT_LIST_COMPLETED,
data: {
authorClaimId: authorChannelClaim ? authorChannelClaim.claim_id : undefined,
disabled: true,
},
});
} else {
devToast(dispatch, `doCommentList: ${error.message}`);
dispatch({
type: ACTIONS.COMMENT_LIST_FAILED,
data: error,
});
}
});
};
@@ -274,6 +246,7 @@ export function doCommentReactList(commentIds: Array<string>) {
});
})
.catch((error) => {
devToast(dispatch, `doCommentReactList: ${error.message}`);
dispatch({
type: ACTIONS.COMMENT_REACTION_LIST_FAILED,
data: error,
@@ -475,40 +448,57 @@ export function doCommentCreate(
return result;
})
.catch((error) => {
dispatch({ type: ACTIONS.COMMENT_CREATE_FAILED, data: error });
dispatch({
type: ACTIONS.COMMENT_CREATE_FAILED,
data: error,
});
let toastMessage;
for (const commentronMsg in COMMENTRON_MSG_REMAP) {
if (error.message === commentronMsg) {
toastMessage = __(COMMENTRON_MSG_REMAP[commentronMsg]);
break;
}
let toastMessage = __('Unable to create comment, please try again later.');
if (error && error.message === 'channel is blocked by publisher') {
toastMessage = __('Unable to comment. This channel has blocked you.');
}
if (!toastMessage) {
for (const i18nStr in COMMENTRON_REGEX_MAP) {
const regex = COMMENTRON_REGEX_MAP[i18nStr];
const match = error.message.match(regex);
if (match) {
const subs = {};
for (let i = 1; i < match.length; ++i) {
subs[`${i}`] = match[i];
if (error) {
// TODO: Use error codes when commentron implements it.
switch (error.message) {
case 'channel is blocked by publisher':
toastMessage = __('Unable to comment. This channel has blocked you.');
break;
case 'channel is not allowed to post comments':
toastMessage = __('Unable to comment. Your channel has been blocked by an admin.');
break;
case 'comments are disabled by the creator':
toastMessage = __('Unable to comment. The content owner has disabled comments.');
break;
case 'duplicate comment!':
toastMessage = __('Please do not spam.');
break;
default:
const BLOCKED_WORDS_ERR_MSG = 'the comment contents are blocked by';
const SLOW_MODE_PARTIAL_ERR_MSG = 'Slow mode is on. Please wait at most';
if (error.message.startsWith(BLOCKED_WORDS_ERR_MSG)) {
const channelName = error.message.substring(BLOCKED_WORDS_ERR_MSG.length);
toastMessage = __('The comment contains contents that are blocked by %author%', {
author: channelName,
});
} else if (error.message.startsWith(SLOW_MODE_PARTIAL_ERR_MSG)) {
const value = error.message.replace(/\D/g, '');
toastMessage = __('Slow mode is on. Please wait up to %value% seconds before commenting again.', {
value,
});
}
toastMessage = __(i18nStr, subs);
break;
}
}
}
if (!toastMessage) {
// Fallback to commentron original message. It will be in English
// only and most likely not capitalized correctly.
toastMessage = error.message;
}
dispatch(
doToast({
message: toastMessage,
isError: true,
})
);
dispatch(doToast({ message: toastMessage, isError: true }));
return Promise.reject(error);
});
};
+1 -19
View File
@@ -43,7 +43,7 @@ export function doUpdateLoadStatus(uri: string, outpoint: string) {
full_status: true,
page: 1,
page_size: 1,
}).then((result) => {
}).then(result => {
const { items: fileInfos } = result;
const fileInfo = fileInfos[0];
if (!fileInfo || fileInfo.written_bytes === 0) {
@@ -261,21 +261,3 @@ export function doClearContentHistoryAll() {
dispatch({ type: ACTIONS.CLEAR_CONTENT_HISTORY_ALL });
};
}
export const doRecommendationUpdate = (claimId: string, urls: Array<string>, id: string, parentId: string) => (
dispatch: Dispatch
) => {
dispatch({
type: ACTIONS.RECOMMENDATION_UPDATED,
data: { claimId, urls, id, parentId },
});
};
export const doRecommendationClicked = (claimId: string, index: number) => (dispatch: Dispatch) => {
if (index !== undefined && index !== null) {
dispatch({
type: ACTIONS.RECOMMENDATION_CLICKED,
data: { claimId, index },
});
}
};
+2 -14
View File
@@ -1,10 +1,9 @@
import * as ACTIONS from 'constants/action_types';
import { getAuthToken } from 'util/saved-passwords';
import { doNotificationList } from 'redux/actions/notifications';
import { SOCKETY_SERVER_API } from 'config';
const NOTIFICATION_WS_URL = `${SOCKETY_SERVER_API}/internal?id=`;
const COMMENT_WS_URL = `${SOCKETY_SERVER_API}/commentron?id=`;
const NOTIFICATION_WS_URL = 'wss://sockety.lbry.com/ws/internal?id=';
const COMMENT_WS_URL = 'wss://sockety.lbry.com/ws/commentron?id=';
let sockets = {};
let closingSockets = {};
@@ -110,17 +109,6 @@ export const doCommentSocketConnect = (uri, claimId) => (dispatch) => {
data: { connected, claimId },
});
}
if (response.type === 'pinned') {
const pinnedComment = response.data.comment;
dispatch({
type: ACTIONS.COMMENT_PIN_COMPLETED,
data: {
pinnedComment: pinnedComment,
claimId,
unpin: !pinnedComment.is_pinned,
},
});
}
});
};
+1 -33
View File
@@ -19,7 +19,6 @@ const defaultState: CommentsState = {
commentsByUri: {}, // URI -> claimId
linkedCommentAncestors: {}, // {"linkedCommentId": ["parentId", "grandParentId", ...]}
superChatsByUri: {},
pinnedCommentsById: {}, // ClaimId -> array of pinned comment IDs
isLoading: false,
isLoadingByParentId: {},
isCommenting: false,
@@ -286,7 +285,6 @@ export default handleActions(
const commentsByUri = Object.assign({}, state.commentsByUri);
const repliesByParentId = Object.assign({}, state.repliesByParentId);
const totalCommentsById = Object.assign({}, state.totalCommentsById);
const pinnedCommentsById = Object.assign({}, state.pinnedCommentsById);
const totalRepliesByParentId = Object.assign({}, state.totalRepliesByParentId);
const isLoadingByParentId = Object.assign({}, state.isLoadingByParentId);
@@ -317,9 +315,6 @@ export default handleActions(
const comment = comments[i];
commonUpdateAction(comment, commentById, commentIds, i);
pushToArrayInObject(topLevelCommentsById, claimId, comment.comment_id);
if (comment.is_pinned) {
pushToArrayInObject(pinnedCommentsById, claimId, comment.comment_id);
}
}
}
// --- Replies ---
@@ -342,7 +337,6 @@ export default handleActions(
topLevelTotalPagesById,
repliesByParentId,
totalCommentsById,
pinnedCommentsById,
totalRepliesByParentId,
byId,
commentById,
@@ -627,20 +621,12 @@ export default handleActions(
const { pinnedComment, claimId, unpin } = action.data;
const commentById = Object.assign({}, state.commentById);
const topLevelCommentsById = Object.assign({}, state.topLevelCommentsById);
const pinnedCommentsById = Object.assign({}, state.pinnedCommentsById);
if (pinnedComment && topLevelCommentsById[claimId]) {
const index = topLevelCommentsById[claimId].indexOf(pinnedComment.comment_id);
if (index > -1) {
topLevelCommentsById[claimId].splice(index, 1);
if (pinnedCommentsById[claimId]) {
// Remove here so that the 'unshift' below will be a unique entry.
pinnedCommentsById[claimId] = pinnedCommentsById[claimId].filter((x) => x !== pinnedComment.comment_id);
} else {
pinnedCommentsById[claimId] = [];
}
if (unpin) {
// Without the sort score, I have no idea where to put it. Just
// dump it at the bottom. Users can refresh if they want it back to
@@ -648,26 +634,9 @@ export default handleActions(
topLevelCommentsById[claimId].push(pinnedComment.comment_id);
} else {
topLevelCommentsById[claimId].unshift(pinnedComment.comment_id);
pinnedCommentsById[claimId].unshift(pinnedComment.comment_id);
}
if (commentById[pinnedComment.comment_id]) {
// Commentron's `comment.Pin` response places the creator's credentials
// in the 'channel_*' fields, which doesn't make sense. Maybe it is to
// show who signed/pinned it, but even if so, it shouldn't overload
// these variables which are already used by existing comment data structure.
// Ensure we don't override the existing/correct values, but fallback
// to whatever was given.
const { channel_id, channel_name, channel_url } = commentById[pinnedComment.comment_id];
commentById[pinnedComment.comment_id] = {
...pinnedComment,
channel_id: channel_id || pinnedComment.channel_id,
channel_name: channel_name || pinnedComment.channel_name,
channel_url: channel_url || pinnedComment.channel_url,
};
} else {
commentById[pinnedComment.comment_id] = pinnedComment;
}
commentById[pinnedComment.comment_id] = pinnedComment;
}
}
@@ -675,7 +644,6 @@ export default handleActions(
...state,
commentById,
topLevelCommentsById,
pinnedCommentsById,
};
},
+3 -44
View File
@@ -7,10 +7,6 @@ const defaultState = {
channelClaimCounts: {},
positions: {},
history: [],
recommendationId: {}, // { "claimId": "recommendationId" }
recommendationParentId: {}, // { "claimId": "referrerId" }
recommendationUrls: {}, // { "claimId": [lbryUrls...] }
recommendationClicks: {}, // { "claimId": [clicked indices...] }
};
reducers[ACTIONS.SET_PRIMARY_URI] = (state, action) =>
@@ -77,7 +73,7 @@ reducers[ACTIONS.SET_CONTENT_LAST_VIEWED] = (state, action) => {
const { uri, lastViewed } = action.data;
const { history } = state;
const historyObj = { uri, lastViewed };
const index = history.findIndex((i) => i.uri === uri);
const index = history.findIndex(i => i.uri === uri);
const newHistory =
index === -1
? [historyObj].concat(history)
@@ -88,7 +84,7 @@ reducers[ACTIONS.SET_CONTENT_LAST_VIEWED] = (state, action) => {
reducers[ACTIONS.CLEAR_CONTENT_HISTORY_URI] = (state, action) => {
const { uri } = action.data;
const { history } = state;
const index = history.findIndex((i) => i.uri === uri);
const index = history.findIndex(i => i.uri === uri);
return index === -1
? state
: {
@@ -97,44 +93,7 @@ reducers[ACTIONS.CLEAR_CONTENT_HISTORY_URI] = (state, action) => {
};
};
reducers[ACTIONS.CLEAR_CONTENT_HISTORY_ALL] = (state) => ({ ...state, history: [] });
reducers[ACTIONS.RECOMMENDATION_UPDATED] = (state, action) => {
const { claimId, urls, id, parentId } = action.data;
const recommendationId = Object.assign({}, state.recommendationId);
const recommendationParentId = Object.assign({}, state.recommendationParentId);
const recommendationUrls = Object.assign({}, state.recommendationUrls);
const recommendationClicks = Object.assign({}, state.recommendationClicks);
if (urls && urls.length > 0) {
recommendationId[claimId] = id;
recommendationParentId[claimId] = parentId;
recommendationUrls[claimId] = urls;
recommendationClicks[claimId] = [];
} else {
delete recommendationId[claimId];
delete recommendationParentId[claimId];
delete recommendationUrls[claimId];
delete recommendationClicks[claimId];
}
return { ...state, recommendationId, recommendationParentId, recommendationUrls, recommendationClicks };
};
reducers[ACTIONS.RECOMMENDATION_CLICKED] = (state, action) => {
const { claimId, index } = action.data;
const recommendationClicks = Object.assign({}, state.recommendationClicks);
if (state.recommendationUrls[claimId] && index >= 0 && index < state.recommendationUrls[claimId].length) {
if (recommendationClicks[claimId]) {
recommendationClicks[claimId].push(index);
} else {
recommendationClicks[claimId] = [index];
}
}
return { ...state, recommendationClicks };
};
reducers[ACTIONS.CLEAR_CONTENT_HISTORY_ALL] = state => ({ ...state, history: [] });
// reducers[LBRY_REDUX_ACTIONS.PURCHASE_URI_FAILED] = (state, action) => {
// return {
-10
View File
@@ -4,7 +4,6 @@ import { ACTIONS as LBRY_REDUX_ACTIONS, SETTINGS, SHARED_PREFERENCES } from 'lbr
import { getSubsetFromKeysArray } from 'util/sync-settings';
import { getDefaultLanguage } from 'util/default-languages';
import { UNSYNCED_SETTINGS, SIMPLE_SITE } from 'config';
import Comments from 'comments';
const { CLIENT_SYNC_KEYS } = SHARED_PREFERENCES;
const settingsToIgnore = (UNSYNCED_SETTINGS && UNSYNCED_SETTINGS.trim().split(' ')) || [];
@@ -52,8 +51,6 @@ const defaultState = {
[SETTINGS.VIDEO_THEATER_MODE]: false,
[SETTINGS.VIDEO_PLAYBACK_RATE]: 1,
[SETTINGS.DESKTOP_WINDOW_ZOOM]: 1,
[SETTINGS.CUSTOM_COMMENTS_SERVER_ENABLED]: false,
[SETTINGS.CUSTOM_COMMENTS_SERVER_URL]: '',
[SETTINGS.DARK_MODE_TIMES]: {
from: { hour: '21', min: '00', formattedTime: '21:00' },
@@ -172,13 +169,6 @@ reducers[LBRY_REDUX_ACTIONS.USER_STATE_POPULATE] = (state, action) => {
const selectedSettings = sharedPreferences ? getSubsetFromKeysArray(sharedPreferences, clientSyncKeys) : {};
const mergedClientSettings = { ...currentClientSettings, ...selectedSettings };
const newSharedPreferences = sharedPreferences || {};
Comments.setServerUrl(
mergedClientSettings[SETTINGS.CUSTOM_COMMENTS_SERVER_ENABLED]
? mergedClientSettings[SETTINGS.CUSTOM_COMMENTS_SERVER_URL]
: undefined
);
return Object.assign({}, state, {
sharedPreferences: newSharedPreferences,
clientSettings: mergedClientSettings,
-1
View File
@@ -17,7 +17,6 @@ export const selectCommentsDisabledChannelIds = createSelector(
(state) => state.commentsDisabledChannelIds
);
export const selectOthersReactsById = createSelector(selectState, (state) => state.othersReactsByCommentId);
export const selectPinnedCommentsById = createSelector(selectState, (state) => state.pinnedCommentsById);
export const selectModerationBlockList = createSelector(selectState, (state) =>
state.moderationBlockList ? state.moderationBlockList.reverse() : []
+17 -16
View File
@@ -11,7 +11,8 @@ import {
parseURI,
makeSelectContentTypeForUri,
makeSelectFileNameForUri,
selectClaimIdsByUri,
normalizeURI,
selectMyActiveClaims,
} from 'lbry-redux';
import { makeSelectRecommendedContentForUri } from 'redux/selectors/search';
import { selectMutedChannels } from 'redux/selectors/blocked';
@@ -245,20 +246,20 @@ export const makeSelectInsufficientCreditsForUri = (uri: string) =>
}
);
export const makeSelectRecommendationId = (claimId: string) =>
createSelector(selectState, (state) => state.recommendationId[claimId]);
export const makeSelectSigningIsMine = (rawUri: string) => {
let uri;
try {
uri = normalizeURI(rawUri);
} catch (e) { }
export const makeSelectRecommendationParentId = (claimId: string) =>
createSelector(selectState, (state) => state.recommendationParentId[claimId]);
return createSelector(selectClaimsByUri, selectMyActiveClaims, (claims, myClaims) => {
try {
parseURI(uri);
} catch (e) {
return false;
}
const signingChannel = claims && claims[uri] && (claims[uri].signing_channel || claims[uri]);
export const makeSelectRecommendedClaimIds = (claimId: string) =>
createSelector(selectState, selectClaimIdsByUri, (state, claimIdsByUri) => {
const recommendationUrls = state.recommendationUrls[claimId];
if (recommendationUrls) {
return recommendationUrls.map((url) => claimIdsByUri[url]);
}
return undefined;
});
export const makeSelectRecommendationClicks = (claimId: string) =>
createSelector(selectState, (state) => state.recommendationClicks[claimId]);
return signingChannel && myClaims.has(signingChannel.claim_id);
});
};
+3 -2
View File
@@ -54,10 +54,11 @@ export const makeSelectLikeCountForUri = (uri) =>
export const makeSelectDislikeCountForUri = (uri) =>
createSelector(makeSelectClaimForUri(uri), makeSelectReactionsForUri(uri), (claim, reactions) => {
if (!claim || !reactions || reactions.my_reactions === null || reactions.others_reactions === null) {
const claimId = claim.claim_id;
if (!reactions || reactions.my_reactions === null || reactions.others_reactions === null) {
return 0;
}
const claimId = claim.claim_id;
let count = 0;
if (reactions.others_reactions) {
+1 -1
View File
@@ -135,7 +135,7 @@
.button--link {
color: var(--color-link);
transition: color 0.2s;
word-break: break-word;
word-break: break-all;
font-weight: var(--font-weight-bold);
&:hover {
-5
View File
@@ -391,11 +391,6 @@
align-items: center;
}
.card__bottom-actions--comments {
@extend .card__bottom-actions;
margin-top: var(--spacing-s);
}
.card__multi-pane {
display: flex;
+1 -1
View File
@@ -165,7 +165,7 @@ $actions-z-index: 2;
}
.channel__title {
display: flex;
display: inline;
margin-right: var(--spacing-s);
overflow: hidden;
text-overflow: ellipsis;
+3 -5
View File
@@ -669,13 +669,12 @@
.claim-preview__hover-actions {
display: none;
position: relative;
float: right;
position: absolute;
top: var(--spacing-xxs);
margin-right: var(--spacing-xxs);
right: var(--spacing-xxs);
& > * {
color: var(--color-text);
color: var(--color-black);
background-color: var(--color-black);
border-radius: var(--border-radius);
padding: var(--spacing-xxs);
@@ -686,7 +685,6 @@
}
.button--file-action {
display: block;
margin: 0 0;
padding: var(--spacing-xxs) var(--spacing-xxs);
height: unset;
-9
View File
@@ -7,14 +7,6 @@ $thumbnailWidthSmall: 1rem;
margin-top: var(--spacing-l);
}
.comments--contracted {
@extend .comments;
max-height: 5rem;
overflow: hidden;
-webkit-mask-image: -webkit-gradient(linear, left 30%, left bottom, from(rgba(0, 0, 0, 1)), to(rgba(0, 0, 0, 0)));
overflow-wrap: anywhere;
}
.comments--replies {
list-style-type: none;
margin-left: var(--spacing-s);
@@ -217,7 +209,6 @@ $thumbnailWidthSmall: 1rem;
.comment__pin {
margin-left: var(--spacing-s);
font-size: var(--font-xsmall);
.icon {
padding-top: 1px;
-5
View File
@@ -60,8 +60,3 @@
font-size: var(--font-large);
}
}
.embed__overlay-logo {
max-height: 3.5rem;
max-width: 12rem;
}
-2
View File
@@ -73,8 +73,6 @@
.header__navigation-logo {
height: var(--height-button);
max-width: -webkit-fit-content;
max-width: -moz-fit-content;
max-width: fit-content;
}
+1 -22
View File
@@ -223,27 +223,6 @@ $discussion-header__height: 3rem;
}
}
.livestream-pinned__wrapper {
flex-shrink: 0;
position: relative;
padding: var(--spacing-s) var(--spacing-xs);
border-bottom: 1px solid var(--color-border);
font-size: var(--font-small);
background-color: var(--color-card-background-highlighted);
width: 100%;
.livestream-comment {
padding-top: var(--spacing-xs);
max-height: 6rem;
overflow-y: scroll;
}
@media (min-width: $breakpoint-small) {
padding: var(--spacing-xs);
width: var(--livestream-comments-width);
}
}
.livestream-superchat__amount-large {
.credit-amount {
display: flex;
@@ -335,7 +314,7 @@ $discussion-header__height: 3rem;
}
.livestream-comment__text {
padding-right: var(--spacing-xl);
padding-right: var(--spacing-xxs);
padding-bottom: var(--spacing-xxs);
.markdown-preview {
p {
-1
View File
@@ -178,7 +178,6 @@ const sharedStateFilters = {
app_welcome_version: { source: 'app', property: 'welcomeVersion' },
sharing_3P: { source: 'app', property: 'allowAnalytics' },
builtinCollections: { source: 'collections', property: 'builtin' },
editedCollections: { source: 'collections', property: 'edited' },
// savedCollections: { source: 'collections', property: 'saved' },
unpublishedCollections: { source: 'collections', property: 'unpublished' },
};
+1 -1
View File
@@ -286,7 +286,7 @@ export function GetLinksData(
? `>${Math.floor(moment().subtract(9, 'months').startOf('week').unix())}`
: `>${Math.floor(moment().subtract(1, 'year').startOf('week').unix())}`,
pageSize: getPageSize(subscribedChannels.length > 3 ? (subscribedChannels.length > 6 ? 16 : 8) : 4),
streamTypes: null,
streamTypes: CS.FILE_TYPES,
channelIds: subscribedChannels.map((subscription: Subscription) => {
const { channelClaimId } = parseURI(subscription.uri);
return channelClaimId;
+2 -8
View File
@@ -3,10 +3,7 @@ const { URL, LBRY_WEB_STREAMING_API } = require('../../config');
const CONTINENT_COOKIE = 'continent';
function generateStreamUrl(claimName, claimId) {
return `${LBRY_WEB_STREAMING_API}/content/claims/${encodeURIComponent(claimName)
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')}/${claimId}/stream`;
return `${LBRY_WEB_STREAMING_API}/content/claims/${claimName}/${claimId}/stream`;
}
function generateEmbedUrl(claimName, claimId, includeStartTime, startTime, referralLink) {
@@ -19,10 +16,7 @@ function generateEmbedUrl(claimName, claimId, includeStartTime, startTime, refer
urlParams.append('r', referralLink);
}
return `${URL}/$/embed/${encodeURIComponent(claimName)
.replace(/'/g, '%27')
.replace(/\(/g, '%28')
.replace(/\)/g, '%29')}/${claimId}?${urlParams.toString()}`;
return `${URL}/$/embed/${encodeURIComponent(claimName).replace(/'/g, '%27')}/${claimId}?${urlParams.toString()}`;
}
function generateDownloadUrl(claimName, claimId) {
@@ -38,7 +38,7 @@ function FileViewerEmbeddedEnded(props: Props) {
<div className="file-viewer__overlay">
<div className="file-viewer__overlay-secondary">
<Button className="file-viewer__overlay-logo" href={URL}>
<Logo type={'embed-ended'} />
<Logo type={'embed'} />
</Button>
</div>
<div className="file-viewer__overlay-title">{prompt}</div>
-38
View File
@@ -1,38 +0,0 @@
// @flow
import React from 'react';
import Nag from 'component/common/nag';
import I18nMessage from 'component/i18nMessage';
import * as PAGES from 'constants/pages';
import { useHistory } from 'react-router';
import Button from '../../ui/component/button';
type Props = {
email?: User,
onClose: () => void,
};
export default function NagSunset(props: Props) {
const { email, onClose } = props;
const { push } = useHistory();
const handleOnClick = () => {
onClose();
push(`/$/${PAGES.AUTH_SIGNIN}`);
};
return (
<Nag
type="helpful"
message={
<I18nMessage
tokens={{
more: <Button button={'link'} label={__('more')} href="https://odysee.com/@lbry:3f/retirement" />,
}}
>
lbry.tv has been retired (%more%). You have been magically transported to Odysee.com
</I18nMessage>
}
actionText={__('Sign In')}
onClick={!email ? handleOnClick : undefined}
onClose={onClose}
/>
);
}
+75 -104
View File
@@ -9,49 +9,31 @@ const {
SITE_DESCRIPTION,
SITE_NAME,
FAVICON,
LBRY_WEB_API,
} = require('../../config.js');
const { Lbry } = require('lbry-redux');
const { generateEmbedUrl, generateStreamUrl, generateDirectUrl } = require('../../ui/util/web');
const PAGES = require('../../ui/constants/pages');
const { CATEGORY_METADATA } = require('./category-metadata');
const { parseURI, normalizeURI } = require('lbry-redux');
const { getClaim } = require('./chainquery');
const { parseURI } = require('lbry-redux');
const fs = require('fs');
const path = require('path');
const moment = require('moment');
const removeMd = require('remove-markdown');
const { getJsBundleId } = require('../bundle-id.js');
const jsBundleId = getJsBundleId();
const SDK_API_PATH = `${LBRY_WEB_API}/api/v1`;
const PROXY_URL = `${SDK_API_PATH}/proxy`;
Lbry.setDaemonConnectionString(PROXY_URL);
function insertToHead(fullHtml, htmlToInsert) {
const beginStr = '<!-- VARIABLE_HEAD_BEGIN -->';
const finalStr = '<!-- VARIABLE_HEAD_END -->';
const beginIndex = fullHtml.indexOf(beginStr);
const finalIndex = fullHtml.indexOf(finalStr);
if (beginIndex > -1 && finalIndex > -1 && finalIndex > beginIndex) {
return `${fullHtml.slice(0, beginIndex)}${
htmlToInsert || buildOgMetadata()
}<script src="/public/ui-${jsBundleId}.js" async></script>${fullHtml.slice(finalIndex + finalStr.length)}`;
}
return fullHtml.replace(
/<!-- VARIABLE_HEAD_BEGIN -->.*<!-- VARIABLE_HEAD_END -->/s,
`
${htmlToInsert || buildOgMetadata()}
<script src="/public/ui-${jsBundleId}.js" async></script>
`
);
}
function truncateDescription(description, maxChars = 200) {
// Get list of single-codepoint strings
const chars = [...description];
// Use slice array instead of substring to prevent breaking emojis
let truncated = chars.slice(0, maxChars).join('');
// Format truncated string
return (chars.length > maxChars) ? truncated + '...' : truncated;
}
function normalizeClaimUrl(url) {
return normalizeURI(url.replace(/:/g, '#'));
function truncateDescription(description) {
return description.length > 200 ? description.substr(0, 200) + '...' : description;
}
function escapeHtmlProperty(property) {
@@ -136,33 +118,20 @@ function buildBasicOgMetadata() {
function buildClaimOgMetadata(uri, claim, overrideOptions = {}) {
// Initial setup for claim based og metadata
const { claimName } = parseURI(uri);
const { meta, value, signing_channel } = claim;
const fee = value && value.fee && (Number(value.fee.amount) || 0);
const tags = value && value.tags;
const media = value && (value.video || value.audio || value.image);
const source = value && value.source;
const channel = signing_channel && signing_channel.name;
const thumbnail = value && value.thumbnail && value.thumbnail.url;
const mediaType = source && source.media_type;
const mediaDuration = media && media.duration;
const claimTitle = escapeHtmlProperty((value && value.title) || claimName);
const releaseTime = (value && value.release_time) || (meta && meta.creation_timestamp) || 0;
const claimTitle = escapeHtmlProperty(claim.title ? claim.title : claimName);
const claimDescription =
value && value.description && value.description.length > 0
? escapeHtmlProperty(truncateDescription(value.description))
claim.description && claim.description.length > 0
? escapeHtmlProperty(truncateDescription(claim.description))
: `View ${claimTitle} on ${SITE_NAME}`;
const claimLanguage =
value && value.languages && value.languages.length > 0 ? escapeHtmlProperty(value.languages[0]) : 'en_US';
const claimLanguage = escapeHtmlProperty(claim.language) || 'en_US';
let imageThumbnail;
if (fee <= 0 && mediaType && mediaType.startsWith('image/')) {
if (Number(claim.fee) <= 0 && claim.source_media_type && claim.source_media_type.startsWith('image/')) {
imageThumbnail = generateStreamUrl(claim.name, claim.claim_id);
}
const claimThumbnail = escapeHtmlProperty(thumbnail) || imageThumbnail || OG_IMAGE_URL || `${URL}/public/v2-og.png`;
const claimThumbnail =
escapeHtmlProperty(claim.thumbnail_url) || imageThumbnail || OG_IMAGE_URL || `${URL}/public/v2-og.png`;
// Allow for ovverriding default claim based og metadata
const title = overrideOptions.title || claimTitle;
@@ -175,9 +144,8 @@ function buildClaimOgMetadata(uri, claim, overrideOptions = {}) {
head += '<meta charset="utf8"/>';
head += `<title>${title}</title>`;
head += `<meta name="description" content="${cleanDescription}"/>`;
if (tags && tags.length > 0) {
head += `<meta name="keywords" content="${tags.toString()}"/>`;
if (claim.tags) {
head += `<meta name="keywords" content="${claim.tags.toString()}"/>`;
}
head += `<meta name="twitter:image" content="${claimThumbnail}"/>`;
@@ -193,28 +161,33 @@ function buildClaimOgMetadata(uri, claim, overrideOptions = {}) {
head += `<meta name="twitter:url" content="${URL}/${claim.name}:${claim.claim_id}"/>`;
head += `<link rel="canonical" content="${SITE_CANONICAL_URL || URL}/${claim.name}:${claim.claim_id}"/>`;
if (mediaType && (mediaType.startsWith('video/') || mediaType.startsWith('audio/'))) {
if (
claim.source_media_type &&
(claim.source_media_type.startsWith('video/') || claim.source_media_type.startsWith('audio/'))
) {
const videoUrl = generateEmbedUrl(claim.name, claim.claim_id);
head += `<meta property="og:video" content="${videoUrl}" />`;
head += `<meta property="og:video:secure_url" content="${videoUrl}" />`;
head += `<meta property="og:video:type" content="${mediaType}" />`;
if (channel) {
head += `<meta name="og:video:series" content="${channel}"/>`;
head += `<meta property="og:video:type" content="${claim.source_media_type}" />`;
if (claim.channel) {
head += `<meta name="og:video:series" content="${claim.channel}"/>`;
}
head += `<meta name="twitter:card" content="player"/>`;
head += `<meta name="twitter:player" content="${videoUrl}" />`;
if (releaseTime) {
var release = new Date(releaseTime * 1000).toISOString();
if (claim.release_time) {
var release = new Date(claim.release_time * 1000).toISOString();
head += `<meta property="og:video:release_date" content="${release}"/>`;
}
if (mediaDuration) {
head += `<meta property="og:video:duration" content="${mediaDuration}"/>`;
if (claim.duration) {
head += `<meta property="og:video:duration" content="${claim.duration}"/>`;
} else if (claim.audio_duration) {
head += `<meta property="og:video:duration" content="${claim.audio_duration}"/>`;
}
if (media && media.width && media.height) {
head += `<meta property="og:video:width" content="${media.width}"/>`;
head += `<meta property="og:video:height" content="${media.height}"/>`;
head += `<meta name="twitter:player:width" content="${media.width}">`;
head += `<meta name="twitter:player:height" content="${media.height}">`;
if (claim.frame_width && claim.frame_height) {
head += `<meta property="og:video:width" content="${claim.frame_width}"/>`;
head += `<meta property="og:video:height" content="${claim.frame_height}"/>`;
head += `<meta name="twitter:player:width" content="${claim.frame_width}">`;
head += `<meta name="twitter:player:height" content="${claim.frame_height}">`;
}
} else {
head += `<meta name="twitter:card" content="summary_large_image"/>`;
@@ -223,27 +196,19 @@ function buildClaimOgMetadata(uri, claim, overrideOptions = {}) {
return head;
}
function buildGoogleVideoMetadata(uri, claim) {
const { claimName } = parseURI(uri);
const { meta, value } = claim;
const media = value && value.video;
const source = value && value.source;
const thumbnail = value && value.thumbnail && value.thumbnail.url;
const mediaType = source && source.media_type;
const mediaDuration = media && media.duration;
const claimTitle = escapeHtmlProperty((value && value.title) || claimName);
const releaseTime = (value && value.release_time) || (meta && meta.creation_timestamp) || 0;
const claimDescription =
value && value.description && value.description.length > 0
? escapeHtmlProperty(truncateDescription(value.description))
: `View ${claimTitle} on ${SITE_NAME}`;
if (!mediaType || !mediaType.startsWith('video/')) {
function buildGoogleVideoMetadata(claimUri, claim) {
if (!claim.source_media_type || !claim.source_media_type.startsWith('video/')) {
return '';
}
const claimThumbnail = escapeHtmlProperty(thumbnail) || OG_IMAGE_URL || `${URL}/public/v2-og.png`;
const { claimName } = parseURI(claimUri);
const claimTitle = escapeHtmlProperty(claim.title ? claim.title : claimName);
const claimDescription =
claim.description && claim.description.length > 0
? escapeHtmlProperty(truncateDescription(claim.description))
: `View ${claimTitle} on ${SITE_NAME}`;
const claimThumbnail = escapeHtmlProperty(claim.thumbnail_url) || OG_IMAGE_URL || `${URL}/public/v2-og.png`;
const releaseTime = claim.release_time || 0;
// https://developers.google.com/search/docs/data-types/video
const googleVideoMetadata = {
@@ -255,7 +220,7 @@ function buildGoogleVideoMetadata(uri, claim) {
thumbnailUrl: `${claimThumbnail}`,
uploadDate: `${new Date(releaseTime * 1000).toISOString()}`,
// --- Recommended ---
duration: mediaDuration ? moment.duration(mediaDuration * 1000).toISOString() : undefined,
duration: claim.duration ? moment.duration(claim.duration * 1000).toISOString() : undefined,
contentUrl: generateDirectUrl(claim.name, claim.claim_id),
embedUrl: generateEmbedUrl(claim.name, claim.claim_id),
};
@@ -273,20 +238,24 @@ function buildGoogleVideoMetadata(uri, claim) {
);
}
async function resolveClaimOrRedirect(ctx, url, ignoreRedirect = false) {
let claim;
try {
const response = await Lbry.resolve({ urls: [url] });
if (response && response[url] && !response[url].error) {
claim = response && response[url];
const isRepost = claim.reposted_claim && claim.reposted_claim.name && claim.reposted_claim.claim_id;
if (isRepost && !ignoreRedirect) {
ctx.redirect(`/${claim.reposted_claim.name}:${claim.reposted_claim.claim_id}`);
return;
}
async function getClaimFromChainqueryOrRedirect(ctx, url, ignoreRedirect = false) {
const { isChannel, streamName, channelName, channelClaimId, streamClaimId } = parseURI(url);
const claimName = isChannel ? '@' + channelName : streamName;
const claimId = isChannel ? channelClaimId : streamClaimId;
const rows = await getClaim(claimName, claimId, channelName, channelClaimId);
if (rows && rows.length) {
const claim = rows[0];
if (claim.reposted_name && claim.reposted_claim_id && !ignoreRedirect) {
ctx.redirect(`/${claim.reposted_name}:${claim.reposted_claim_id}`);
return;
}
} catch {}
return claim;
return claim;
}
return undefined;
}
let html;
@@ -305,10 +274,12 @@ async function getHtml(ctx) {
const embedPath = `/$/${PAGES.EMBED}/`;
if (requestPath.includes(invitePath)) {
const inviteChannel = requestPath.slice(invitePath.length).replace(/:/g, '#');
const inviteChannelUrl = `lbry://${inviteChannel}`;
try {
const inviteChannel = requestPath.slice(invitePath.length);
const inviteChannelUrl = normalizeClaimUrl(inviteChannel);
const claim = await resolveClaimOrRedirect(ctx, inviteChannelUrl);
parseURI(inviteChannelUrl);
const claim = await getClaimFromChainqueryOrRedirect(ctx, inviteChannelUrl);
const invitePageMetadata = buildClaimOgMetadata(inviteChannelUrl, claim, {
title: `Join ${claim.name} on ${SITE_NAME}`,
description: `Join ${claim.name} on ${SITE_NAME}, a content wonderland owned by everyone (and no one).`,
@@ -327,8 +298,8 @@ async function getHtml(ctx) {
}
if (requestPath.includes(embedPath)) {
const claimUri = normalizeClaimUrl(requestPath.replace(embedPath, '').replace('/', '#'));
const claim = await resolveClaimOrRedirect(ctx, claimUri, true);
const claimUri = requestPath.replace(embedPath, '').replace(/:/g, '#');
const claim = await getClaimFromChainqueryOrRedirect(ctx, claimUri, true);
if (claim) {
const ogMetadata = buildClaimOgMetadata(claimUri, claim);
@@ -350,8 +321,8 @@ async function getHtml(ctx) {
}
if (!requestPath.includes('$')) {
const claimUri = normalizeClaimUrl(requestPath.slice(1));
const claim = await resolveClaimOrRedirect(ctx, claimUri);
const claimUri = requestPath.slice(1).replace(/:/g, '#');
const claim = await getClaimFromChainqueryOrRedirect(ctx, claimUri);
if (claim) {
const ogMetadata = buildClaimOgMetadata(claimUri, claim);
+3 -5
View File
@@ -19,11 +19,9 @@ function getStreamUrl(ctx) {
}
const rssMiddleware = async (ctx) => {
const rss = await getRss(ctx);
if (rss.startsWith('<?xml')) {
ctx.set('Content-Type', 'application/xml');
}
ctx.body = rss;
const xml = await getRss(ctx);
ctx.set('Content-Type', 'application/rss+xml');
ctx.body = xml;
};
router.get(`/$/api/content/v1/get`, async (ctx) => {
+75 -228
View File
@@ -1,8 +1,7 @@
const { generateStreamUrl } = require('../../ui/util/web');
const { URL, SITE_NAME, LBRY_WEB_API } = require('../../config.js');
const { generateDownloadUrl } = require('../../ui/util/web');
const { URL, SITE_NAME, LBRY_WEB_API, FAVICON } = require('../../config.js');
const { Lbry } = require('lbry-redux');
const Rss = require('rss');
const Mime = require('mime-types');
const Feed = require('feed').Feed;
const SDK_API_PATH = `${LBRY_WEB_API}/api/v1`;
const proxyURL = `${SDK_API_PATH}/proxy`;
@@ -10,10 +9,6 @@ Lbry.setDaemonConnectionString(proxyURL);
const NUM_ENTRIES = 500;
// ****************************************************************************
// Fetch claim info
// ****************************************************************************
async function doClaimSearch(options) {
let results;
try {
@@ -24,21 +19,15 @@ async function doClaimSearch(options) {
async function getChannelClaim(name, claimId) {
let claim;
let error;
try {
const url = `lbry://${name}#${claimId}`;
const response = await Lbry.resolve({ urls: [url] });
if (response && response[url] && !response[url].error) {
claim = response && response[url];
}
} catch {}
if (!claim) {
error = 'The RSS URL is invalid or is not associated with any channel.';
}
return { claim, error };
return claim || 'The RSS URL is invalid or is not associated with any channel.';
}
async function getClaimsFromChannel(claimId, count) {
@@ -47,252 +36,110 @@ async function getClaimsFromChannel(claimId, count) {
page_size: count,
has_source: true,
claim_type: 'stream',
order_by: ['release_time'],
order_by: ['creation_timestamp'],
no_totals: true,
};
return await doClaimSearch(options);
}
// ****************************************************************************
// Helpers
// ****************************************************************************
async function getFeed(channelClaim, feedLink) {
const replaceLineFeeds = (str) => str.replace(/(?:\r\n|\r|\n)/g, '<br />');
function encodeWithSpecialCharEncode(string) {
// encodeURIComponent doesn't encode `'` and others
// which other services may not like
return encodeURIComponent(string).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
}
const fmtDescription = (description) => replaceLineFeeds(description);
const generateEnclosureForClaimContent = (claim) => {
const value = claim.value;
if (!value || !value.stream_type) {
return undefined;
}
const fileExt = value.source && value.source.media_type && '.' + Mime.extension(value.source.media_type);
switch (value.stream_type) {
case 'video':
return {
url: generateStreamUrl(claim.name, claim.claim_id) + (fileExt || '.mp4'),
type: (value.source && value.source.media_type) || 'video/mp4',
size: (value.source && value.source.size) || 0, // Per spec, 0 is a valid fallback.
};
case 'audio':
return {
url: generateStreamUrl(claim.name, claim.claim_id) + (fileExt || '.mp3'),
type: (value.source && value.source.media_type) || 'audio/mpeg',
size: (value.source && value.source.size) || 0, // Per spec, 0 is a valid fallback.
};
case 'image':
return {
url: generateStreamUrl(claim.name, claim.claim_id) + (fileExt || '.jpeg'),
type: (value.source && value.source.media_type) || 'image/jpeg',
size: (value.source && value.source.size) || 0, // Per spec, 0 is a valid fallback.
};
case 'document':
case 'software':
return {
url: generateStreamUrl(claim.name, claim.claim_id),
type: (value.source && value.source.media_type) || undefined,
size: (value.source && value.source.size) || 0, // Per spec, 0 is a valid fallback.
};
default:
return undefined;
}
};
const getLanguageValue = (claim) => {
if (claim && claim.value && claim.value.languages && claim.value.languages.length > 0) {
return claim.value.languages[0];
}
return 'en';
};
const replaceLineFeeds = (str) => str.replace(/(?:\r\n|\r|\n)/g, '<br />');
const isEmailRoughlyValid = (email) => /^\S+@\S+$/.test(email);
/**
* 'itunes:owner' is required by castfeedvalidator (w3c allows omission), and
* both name and email must be defined. The email must also be a "valid" one.
*
* Use a fallback email when the creator did not specify one. The email will not
* be shown to the user; it is just used for administrative purposes.
*
* @param claim
* @returns any
*/
const generateItunesOwnerElement = (claim) => {
let email = 'no-reply@odysee.com';
let name = claim && (claim.value && claim.value.title ? claim.value.title : claim.name);
if (claim && claim.value) {
if (isEmailRoughlyValid(claim.value.email)) {
email = claim.value.email;
const sanitizeThumbsUrl = (url) => {
if (typeof url === 'string' && url.startsWith('https://')) {
return encodeURI(url).replace(/&/g, '%26');
}
}
return {
'itunes:owner': [{ 'itunes:name': name }, { 'itunes:email': email }],
return '';
};
};
const generateItunesExplicitElement = (claim) => {
const tags = (claim && claim.value && claim.value.tags) || [];
return { 'itunes:explicit': tags.includes('mature') ? 'yes' : 'no' };
};
const getItunesCategory = (claim) => {
const itunesCategories = [
'Arts',
'Business',
'Comedy',
'Education',
'Fiction',
'Government',
'History',
'Health & Fitness',
'Kids & Family',
'Leisure',
'Music',
'News',
'Religion & Spirituality',
'Science',
'Society & Culture',
'Sports',
'Technology',
'True Crime',
'TV & Film',
];
const tags = (claim && claim.value && claim.value.tags) || [];
for (let i = 0; i < itunesCategories.length; ++i) {
const itunesCategory = itunesCategories[i];
if (tags.includes(itunesCategory.toLowerCase())) {
// "Note: Although you can specify more than one category and subcategory
// in your RSS feed, Apple Podcasts only recognizes the first category and
// subcategory."
// --> The only parse the first found tag.
return itunesCategory.replace('&', '&amp;');
const getEnclosure = (claim) => {
const value = claim.value;
if (!value || !value.stream_type || !value.source || !value.source.media_type) {
return undefined;
}
}
// itunes will not accept any other categories, and the element is required
// to pass castfeedvalidator. So, fallback to 'Leisure' (closes to "General")
// if the creator did not specify a tag.
return 'Leisure';
};
switch (value.stream_type) {
case 'video':
case 'audio':
case 'image':
case 'document':
case 'software':
return {
url: encodeURI(generateDownloadUrl(claim.name, claim.claim_id)),
type: value.source.media_type,
length: value.source.size || 0, // Per spec, 0 is a valid fallback.
};
const generateItunesDurationElement = (claim) => {
let duration;
if (claim && claim.value) {
if (claim.value.video) {
duration = claim.value.video.duration;
} else if (claim.value.audio) {
duration = claim.value.audio.duration;
default:
return undefined;
}
}
};
if (duration) {
return { 'itunes:duration': `${duration}` };
}
};
const value = channelClaim.value;
const title = value ? value.title : channelClaim.name;
const generateItunesImageElement = (claim) => {
const thumbnailUrl = (claim && claim.value && claim.value.thumbnail && claim.value.thumbnail.url) || '';
if (thumbnailUrl) {
return {
'itunes:image': { _attr: { href: thumbnailUrl } },
};
}
};
const options = {
favicon: FAVICON || URL + '/public/favicon.png',
generator: SITE_NAME + ' RSS Feed',
title: title + ' on ' + SITE_NAME,
description: fmtDescription(value && value.description ? value.description : ''),
link: encodeURI(`${URL}/${channelClaim.name}:${channelClaim.claim_id}`),
image: sanitizeThumbsUrl(value && value.thumbnail ? value.thumbnail.url : ''),
feedLinks: {
rss: encodeURI(feedLink),
},
author: {
name: encodeURI(channelClaim.name),
link: encodeURI(URL + '/' + channelClaim.name + ':' + channelClaim.claim_id),
},
};
const getFormattedDescription = (claim) => {
return replaceLineFeeds((claim && claim.value && claim.value.description) || '');
};
const feed = new Feed(options);
const latestClaims = await getClaimsFromChannel(channelClaim.claim_id, NUM_ENTRIES);
// ****************************************************************************
// Generate
// ****************************************************************************
latestClaims.forEach((c) => {
const meta = c.meta;
const value = c.value;
function generateFeed(feedLink, channelClaim, claimsInChannel) {
// --- Channel ---
let channelTitle = (channelClaim.value && channelClaim.value.title) || channelClaim.name;
const feed = new Rss({
title: channelTitle + ' on ' + SITE_NAME,
description: getFormattedDescription(channelClaim),
feed_url: feedLink,
site_url: (channelClaim.value && channelClaim.value.website_url) || URL,
image_url: (channelClaim.value && channelClaim.value.thumbnail && channelClaim.value.thumbnail.url) || undefined,
language: getLanguageValue(channelClaim),
custom_namespaces: { itunes: 'http://www.itunes.com/dtds/podcast-1.0.dtd' },
custom_elements: [
{ 'itunes:author': channelTitle },
{
'itunes:category': [
{
_attr: {
text: getItunesCategory(channelClaim),
},
},
],
},
generateItunesImageElement(channelClaim),
generateItunesOwnerElement(channelClaim),
generateItunesExplicitElement(channelClaim),
],
});
const title = value && value.title ? value.title : c.name;
const thumbnailUrl = value && value.thumbnail ? value.thumbnail.url : '';
const thumbnailHtml = thumbnailUrl ? `<p><img src="${thumbnailUrl}" alt="thumbnail" title="${title}" /></p>` : '';
// --- Content ---
claimsInChannel.forEach((c) => {
const title = (c.value && c.value.title) || c.name;
const thumbnailUrl = (c.value && c.value.thumbnail && c.value.thumbnail.url) || '';
const thumbnailHtml = thumbnailUrl
? `<p><img src="${thumbnailUrl}" width="480" alt="thumbnail" title="${title}" /></p>`
: '';
const description = thumbnailHtml + getFormattedDescription(c);
const url = `${URL}/${encodeWithSpecialCharEncode(c.name)}:${c.claim_id}`;
const date = c.release_time ? c.release_time * 1000 : c.meta && c.meta.creation_timestamp * 1000;
feed.item({
title: title,
description: description,
url: url,
guid: undefined, // defaults to 'url'
author: undefined, // defaults feed author property
date: new Date(date),
enclosure: generateEnclosureForClaimContent(c),
custom_elements: [
{ 'itunes:title': title },
{ 'itunes:author': channelTitle },
generateItunesImageElement(c),
generateItunesDurationElement(c),
generateItunesExplicitElement(c),
],
feed.addItem({
id: c.claim_id,
guid: encodeURI(URL + '/' + c.name + ':' + c.claim_id),
title: value && value.title ? value.title : c.name,
description: thumbnailHtml + fmtDescription(value && value.description ? value.description : ''),
link: encodeURI(URL + '/' + c.name + ':' + c.claim_id),
date: new Date(meta ? meta.creation_timestamp * 1000 : null),
enclosure: getEnclosure(c),
});
});
return feed;
}
function postProcess(feed) {
// Handle 'Feed' creating an invalid MIME type when trying to guess
// from 'https://thumbnails.lbry.com/UCgQ8eREJzR1dO' style of URLs.
return feed.replace(/type="image\/\/.*"\/>/g, 'type="image/*"/>');
}
async function getRss(ctx) {
if (!ctx.params.claimName || !ctx.params.claimId) {
return 'Invalid URL';
}
const { claim: channelClaim, error } = await getChannelClaim(ctx.params.claimName, ctx.params.claimId);
if (error) {
return error;
const channelClaim = await getChannelClaim(ctx.params.claimName, ctx.params.claimId);
if (typeof channelClaim === 'string' || !channelClaim) {
return channelClaim;
}
const latestClaimsInChannel = await getClaimsFromChannel(channelClaim.claim_id, NUM_ENTRIES);
const feed = generateFeed(`${URL}${ctx.request.url}`, channelClaim, latestClaimsInChannel);
return feed.xml();
const feed = await getFeed(channelClaim, `${URL}${ctx.request.url}`);
return postProcess(feed.rss2());
}
module.exports = { getRss };
+21 -21
View File
@@ -1548,9 +1548,9 @@ chokidar@^2.0.2, chokidar@^2.1.8:
fsevents "^1.2.7"
chownr@^1.1.1:
version "1.1.4"
resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b"
integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==
version "1.1.3"
resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.3.tgz#42d837d5239688d55f303003a508230fa6727142"
integrity sha512-i70fVHhmV3DtTl6nqvZOnIjbY0Pe4kAUjwHj8z0zAdgBtYrJyYwLKCCuRBQ5ppkyL0AkN7HKRnETdmdp1zqNXw==
chrome-trace-event@^1.0.2:
version "1.0.2"
@@ -3589,16 +3589,16 @@ minimatch@^3.0.4:
dependencies:
brace-expansion "^1.1.7"
minimist@0.0.8:
version "0.0.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
integrity sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=
minimist@^1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.0.tgz#a35008b20f41383eec1fb914f4cd5df79a264284"
integrity sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=
minimist@^1.2.5:
version "1.2.5"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.5.tgz#67d66014b66a6a8aaa0c083c5fd58df4e4e97602"
integrity sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==
minipass@^2.6.0, minipass@^2.8.6, minipass@^2.9.0:
version "2.9.0"
resolved "https://registry.yarnpkg.com/minipass/-/minipass-2.9.0.tgz#e713762e7d3e32fed803115cf93e04bca9fcc9a6"
@@ -3639,11 +3639,11 @@ mixin-deep@^1.2.0:
is-extendable "^1.0.1"
mkdirp@^0.5.0, mkdirp@^0.5.1:
version "0.5.5"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def"
integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
integrity sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=
dependencies:
minimist "^1.2.5"
minimist "0.0.8"
moment@^2.22.1:
version "2.27.0"
@@ -4173,9 +4173,9 @@ path-key@^3.1.0:
integrity sha512-8cChqz0RP6SHJkMt48FW0A7+qUOn+OsnOsVtzI59tZ8m+5bCSk7hzwET0pulwOM2YMn9J1efb07KB9l9f30SGg==
path-parse@^1.0.6:
version "1.0.7"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"
integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==
version "1.0.6"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
integrity sha512-GSmOT2EbHrINBf9SR7CDELwlJ8AENk3Qn7OikK4nFYAu3Ote2+JYNVvkpAEQm3/TLNEJFD/xZJjzyxg3KBWOzw==
path-to-regexp@0.1.7:
version "0.1.7"
@@ -5080,9 +5080,9 @@ tapable@^1.0.0, tapable@^1.1.3:
integrity sha512-4WK/bYZmj8xLr+HUCODHGF1ZFzsYffasLUgEiMBY4fgtltdO6B4WJtlSbPaDTLpYTcGVwM2qLnFTICEcNxs3kA==
tar@^4:
version "4.4.15"
resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.15.tgz#3caced4f39ebd46ddda4d6203d48493a919697f8"
integrity sha512-ItbufpujXkry7bHH9NpQyTXPbJ72iTlXgkBAYsAjDXk3Ds8t/3NfO5P4xZGy7u+sYuQUbimgzswX4uQIEeNVOA==
version "4.4.13"
resolved "https://registry.yarnpkg.com/tar/-/tar-4.4.13.tgz#43b364bc52888d555298637b10d60790254ab525"
integrity sha512-w2VwSrBoHa5BsSyH+KxEqeQBAllHhccyMFVHtGtdMpF4W7IRWfZjFiQceJPChOeTsSDVUpER2T8FA93pr0L+QA==
dependencies:
chownr "^1.1.1"
fs-minipass "^1.2.5"
@@ -5367,9 +5367,9 @@ url-parse-lax@^1.0.0:
prepend-http "^1.0.1"
url-parse@^1.4.3:
version "1.5.3"
resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.3.tgz#71c1303d38fb6639ade183c2992c8cc0686df862"
integrity sha512-IIORyIQD9rvj0A4CLWsHkBBJuNqWpFQe224b6j9t/ABmquIS0qDU2pY6kl6AuOrL5OkCXHMCFNe1jBcuAggjvQ==
version "1.5.1"
resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.1.tgz#d5fa9890af8a5e1f274a2c98376510f6425f6e3b"
integrity sha512-HOfCOUJt7iSYzEx/UqgtwKRMC6EU91NFhsCHMv9oM03VJcVo2Qrp8T8kI9D7amFf1cu+/3CEhgb3rF9zL7k85Q==
dependencies:
querystringify "^2.1.1"
requires-port "^1.0.0"
+21 -28
View File
@@ -7205,6 +7205,13 @@ fd-slicer@~1.1.0:
dependencies:
pend "~1.2.0"
feed@^4.2.2:
version "4.2.2"
resolved "https://registry.yarnpkg.com/feed/-/feed-4.2.2.tgz#865783ef6ed12579e2c44bbef3c9113bc4956a7e"
integrity sha512-u5/sxGfiMfZNtJ3OvQpXcvotFpYkL0n9u9mM2vkui2nGo8b4wvDkJ8gAkYqbA8QpGyFCv3RK0Z+Iv+9veCS9bQ==
dependencies:
xml-js "^1.6.11"
figgy-pudding@^3.5.1:
version "3.5.2"
resolved "https://registry.yarnpkg.com/figgy-pudding/-/figgy-pudding-3.5.2.tgz#b4eee8148abb01dcf1d1ac34367d59e12fa61d6e"
@@ -10129,9 +10136,9 @@ lazy-val@^1.0.4:
yargs "^13.2.2"
zstd-codec "^0.1.1"
lbry-redux@lbryio/lbry-redux#e4d0662100a5f4b28bb1bf3cbc1e51b2eebab5b6:
lbry-redux@lbryio/lbry-redux#a327385cdf71568dbd15a17f3dcf5f4b83e0966d:
version "0.0.1"
resolved "https://codeload.github.com/lbryio/lbry-redux/tar.gz/e4d0662100a5f4b28bb1bf3cbc1e51b2eebab5b6"
resolved "https://codeload.github.com/lbryio/lbry-redux/tar.gz/a327385cdf71568dbd15a17f3dcf5f4b83e0966d"
dependencies:
proxy-polyfill "0.1.6"
reselect "^3.0.0"
@@ -10901,18 +10908,6 @@ mime-db@1.48.0:
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.48.0.tgz#e35b31045dd7eada3aaad537ed88a33afbef2d1d"
integrity sha512-FM3QwxV+TnZYQ2aRqhlKBMHxk10lTbMt3bBkMAp54ddrNeVSfcQYOOKuGuy3Ddrm38I04If834fOUSq1yzslJQ==
mime-db@~1.25.0:
version "1.25.0"
resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.25.0.tgz#c18dbd7c73a5dbf6f44a024dc0d165a1e7b1c392"
integrity sha1-wY29fHOl2/b0SgJNwNFloeexw5I=
mime-types@2.1.13:
version "2.1.13"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.13.tgz#e07aaa9c6c6b9a7ca3012c69003ad25a39e92a88"
integrity sha1-4HqqnGxrmnyjASxpADrSWjnpKog=
dependencies:
mime-db "~1.25.0"
mime-types@^2.1.12, mime-types@~2.1.19:
version "2.1.31"
resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.31.tgz#a00d76b74317c61f9c2db2218b8e9f8e9c5c9e6b"
@@ -12020,11 +12015,15 @@ path-key@^3.1.0:
resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375"
integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==
path-parse@^1.0.5, path-parse@^1.0.6:
path-parse@^1.0.5:
version "1.0.7"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"
integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==
path-parse@^1.0.6:
version "1.0.6"
resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.6.tgz#d62dbb5679405d72c4737ec58600e9ddcf06d24c"
path-to-regexp@0.1.7:
version "0.1.7"
resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c"
@@ -14308,14 +14307,6 @@ roarr@^2.15.3:
semver-compare "^1.0.0"
sprintf-js "^1.1.2"
rss@^1.2.2:
version "1.2.2"
resolved "https://registry.yarnpkg.com/rss/-/rss-1.2.2.tgz#50a1698876138133a74f9a05d2bdc8db8d27a921"
integrity sha1-UKFpiHYTgTOnT5oF0r3I240nqSE=
dependencies:
mime-types "2.1.13"
xml "1.0.1"
rtlcss@2.5.0:
version "2.5.0"
resolved "https://registry.yarnpkg.com/rtlcss/-/rtlcss-2.5.0.tgz#455549e49113f9e1cf83169a44de526c816de8a4"
@@ -17217,16 +17208,18 @@ xdg-basedir@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/xdg-basedir/-/xdg-basedir-4.0.0.tgz#4bc8d9984403696225ef83a1573cbbcb4e79db13"
xml-js@^1.6.11:
version "1.6.11"
resolved "https://registry.yarnpkg.com/xml-js/-/xml-js-1.6.11.tgz#927d2f6947f7f1c19a316dd8eea3614e8b18f8e9"
integrity sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==
dependencies:
sax "^1.2.4"
xml-name-validator@^2.0.1:
version "2.0.1"
resolved "https://registry.yarnpkg.com/xml-name-validator/-/xml-name-validator-2.0.1.tgz#4d8b8f1eccd3419aa362061becef515e1e559635"
integrity sha1-TYuPHszTQZqjYgYb7O9RXh5VljU=
xml@1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/xml/-/xml-1.0.1.tgz#78ba72020029c5bc87b8a81a3cfcd74b4a2fc1e5"
integrity sha1-eLpyAgApxbyHuKgaPPzXS0ovweU=
xmlbuilder@^10.0.0:
version "10.1.1"
resolved "https://registry.yarnpkg.com/xmlbuilder/-/xmlbuilder-10.1.1.tgz#8cae6688cc9b38d850b7c8d3c0a4161dcaf475b0"