Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

News Feed #598

Merged
merged 6 commits into from
Oct 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
"@types/react-select": "3.0.5",
"@types/socket.io": "2.1.3",
"@types/socket.io-client": "1.4.32",
"@types/superagent": "4.1.3",
"awesome-typescript-loader": "5.2.1",
"source-map-loader": "0.2.4",
"tslint": "5.20.0"
Expand Down
11 changes: 7 additions & 4 deletions src/Components/Cards/Base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ import CloseIcon from '@material-ui/icons/Close';
import DeleteIcon from '@material-ui/icons/Delete';
import EditIcon from '@material-ui/icons/Edit';

import { CardProps } from '../Configuration/Config';
import { CardProps, ConfigurationProps } from '../Configuration/Config';
import {
HomeAssistantChangeProps,
entitySizes
} from '../HomeAssistant/HomeAssistant';
import ConfirmDialog from '../Utils/ConfirmDialog';
import EditCard from '../Configuration/EditCard/EditCard';
import Entity from '../HomeAssistant/Cards/Entity';
import News from './News';
import Frame from './Frame';
import Image from './Image';
import Markdown from './Markdown';
Expand Down Expand Up @@ -82,6 +83,7 @@ export interface BaseProps
extends RouteComponentProps,
HomeAssistantChangeProps {
card: CardProps;
config: ConfigurationProps;
editing: number;
expandable: boolean;
handleCloseExpand?: () => void;
Expand Down Expand Up @@ -111,9 +113,9 @@ function Base(props: BaseProps) {
? entitySizes[entitySizeKey].height * cardSize
: props.editing === 2 || !props.card.height
? 'initial'
: isNaN(props.card.height)
? props.card.height
: props.card.height * cardSize || cardSize;
: !isNaN(Number(props.card.height))
? Number(props.card.height) * cardSize || cardSize
: props.card.height;
if (h) setHeight(h);
},
[props.card.height, props.editing, props.expandable]
Expand Down Expand Up @@ -337,6 +339,7 @@ function Base(props: BaseProps) {
handleHassToggle={handleHassToggle}
/>
)}
{props.card.type === 'news' && <News {...props} />}
{props.card.type === 'iframe' && <Frame {...props} />}
{props.card.type === 'image' && <Image {...props} />}
{props.card.type === 'markdown' && <Markdown {...props} />}
Expand Down
176 changes: 176 additions & 0 deletions src/Components/Cards/News.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// @flow
import React, { useState, useEffect, useCallback } from 'react';
import PropTypes from 'prop-types';
import request from 'superagent';
import moment from 'moment';
import { makeStyles, Theme } from '@material-ui/core/styles';
import Divider from '@material-ui/core/Divider';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';

import { BaseProps } from './Base';
import MarkdownText from 'Components/Utils/MarkdownText';

type ArticleData = {
source: string;
author: string;
title: string;
description: string;
url: string;
urlToImage: string;
publishedAt: string;
content: string;
};

type FeedData = {
heading: string;
title: string;
url: string;
meta?: string;
imageURL?: string;
content?: string;
};

const useStyles = makeStyles((theme: Theme) => ({
root: {
height: '100%',
overflowY: 'auto'
},
divider: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1)
},
mediaContainer: {
marginRight: theme.spacing(1)
},
media: {
height: `calc(100% - ${theme.spacing(2)}px)`,
width: '100%'
}
}));

interface NewsProps extends BaseProps {}

let feedInterval: NodeJS.Timeout;
function News(props: NewsProps) {
const [data, setData] = useState();
const [error, setError] = useState();

const classes = useStyles();

const handleGetData = useCallback(() => {
if (props.config.news && props.config.news.news_api_key && props.card.url) {
setError(undefined);
console.log('Update News Feed for', props.card.url);
request
.get(
`https://newsapi.org/v2/top-headlines?sources=${props.card.url}&apiKey=${props.config.news.news_api_key}`
)
.then(res => {
const feed: ArticleData = res.body.articles.map(
(article: ArticleData) => ({
heading: `[${article.title}](${article.url})`,
title: article.title,
url: article.url,
meta: `${moment(article.publishedAt).format(
`${props.config.header.time_military ? 'HH:mm' : 'hh:mm a'} ${
props.config.header.date_format
}`
)} - ${article.author}`,
imageURL: article.urlToImage,
content: article.description
})
);
setData(feed);
props.card.disabled = false;
})
.catch(err => {
console.error(err);
setError('An error occured when getting the sources for News API.');
props.card.disabled = true;
});
} else {
setError('You do not have a News API key set in your config.');
props.card.disabled = true;
}
}, [
props.config.news,
props.card.disabled,
props.card.url,
props.config.header.date_format,
props.config.header.time_military
]);

useEffect(() => {
handleGetData();
if (feedInterval) clearInterval(feedInterval);
feedInterval = setInterval(() => handleGetData, 120000);
return () => {
if (feedInterval) clearInterval(feedInterval);
};
}, [props.card.disabled, handleGetData]);

return (
<div className={classes.root}>
{error ? (
<Typography variant="subtitle1" component="h3">
{error}
</Typography>
) : (
data &&
data.map((item: FeedData, key: number) => (
<article key={key}>
<Grid
container
direction="row"
justify="center"
alignContent="center"
alignItems="center">
{props.card.width! > 2 && item.imageURL && (
<Grid className={classes.mediaContainer} item xs={3}>
<a href={item.url} target="_blank" rel="noopener noreferrer">
<img
className={classes.media}
alt={item.title}
src={item.imageURL}
/>
</a>
</Grid>
)}
<Grid item xs>
<Typography variant="subtitle1" component="h3">
<MarkdownText text={item.heading} />
</Typography>
{item.meta && (
<Typography
variant="caption"
component="h5"
gutterBottom
noWrap>
<MarkdownText text={item.meta} />
</Typography>
)}
{item.content && (
<Typography variant="body2" component="span">
<MarkdownText text={item.content} />
</Typography>
)}
</Grid>
</Grid>
{key !== data.length - 1 && (
<Divider className={classes.divider} light variant="middle" />
)}
</article>
))
)}
</div>
);
}

News.propTypes = {
card: PropTypes.any.isRequired,
editing: PropTypes.number,
handleChange: PropTypes.func
};

export default News;
67 changes: 50 additions & 17 deletions src/Components/Configuration/Config.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ export type ConfigurationProps = {
general: GeneralProps;
theme: ThemeProps;
header: HeaderProps;
pages: [PageProps];
groups: [GroupProps];
cards: [CardProps];
pages: PageProps[];
groups: GroupProps[];
cards: CardProps[];
news: NewsProps;
};

export type GeneralProps = {
Expand Down Expand Up @@ -71,7 +72,7 @@ export type CardProps = {
group: string;
type: string;
width?: number;
height?: number;
height?: number | string;
square?: boolean;
padding?: number | string;
elevation?: number;
Expand All @@ -95,6 +96,10 @@ export type CardProps = {
chart_labels?: boolean;
};

export type NewsProps = {
news_api_key: string;
};

export type CardType = {
name: string;
title: string;
Expand Down Expand Up @@ -149,14 +154,15 @@ export const cardTypes: CardType[] = [
{ name: 'entity', title: 'Entity' },
{ name: 'iframe', title: 'iFrame' },
{ name: 'image', title: 'Image' },
{ name: 'markdown', title: 'Markdown' }
{ name: 'markdown', title: 'Markdown' },
{ name: 'news', title: 'News Feed' }
];

export const cardTypeDefaults: { [type: string]: CardProps } = {
entity: {
key: '',
group: '',
title: 'Card',
title: cardTypes[0].title,
type: 'entity',
elevation: 1,
background: '',
Expand All @@ -170,40 +176,53 @@ export const cardTypeDefaults: { [type: string]: CardProps } = {
iframe: {
key: '',
group: '',
title: 'Card',
title: '',
type: 'iframe',
elevation: 1,
background: '',
padding: '',
padding: '0px',
square: false,
width: 1,
height: 1,
url: ''
width: 2,
height: 'auto',
url: 'https://www.youtube.com/embed/dQw4w9WgXcQ'
},
image: {
key: '',
group: '',
title: 'Card',
title: '',
type: 'image',
elevation: 1,
background: '',
padding: '',
padding: '0px',
square: false,
width: 1,
url: ''
width: 2,
url: 'https://source.unsplash.com/daily'
},
markdown: {
key: '',
group: '',
title: 'Card',
title: cardTypes[3].title,
type: 'markdown',
elevation: 1,
background: '',
padding: '',
square: false,
width: 1,
width: 2,
height: 1,
content: ''
},
news: {
key: '',
group: '',
title: cardTypes[4].title,
type: 'news',
elevation: 1,
background: '',
padding: '',
square: false,
width: 2,
height: 3,
url: ''
}
};

Expand Down Expand Up @@ -251,6 +270,20 @@ export const items = [
}
]
},
{
name: 'news',
title: 'News Feed',
items: [
{
name: 'news_api_key',
title: 'News API Key',
description: 'Your [News API](https://newsapi.org) key.',
icon: 'mdi-page-layout-header',
type: 'input_password',
default: ''
}
]
},
{
name: 'theme',
title: 'Theme',
Expand Down
5 changes: 4 additions & 1 deletion src/Components/Configuration/EditCard/Base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import Select from '@material-ui/core/Select';
import Switch from '@material-ui/core/Switch';
import TextField from '@material-ui/core/TextField';

import { CardProps, cardTypes, CardType } from '../Config';
import { CardProps, cardTypes, CardType, ConfigurationProps } from '../Config';
import { Color } from '../../Utils/ColorWheel';
import { HomeAssistantChangeProps } from 'Components/HomeAssistant/HomeAssistant';
import ColorAdornment from '../ColorAdornment';
import Entity from './Entity';
import News from './News';
import Frame from './Frame';
import Image from './Image';
import Markdown from './Markdown';
Expand All @@ -44,6 +45,7 @@ export interface BaseProps
extends RouteComponentProps,
HomeAssistantChangeProps {
card: CardProps;
config: ConfigurationProps;
handleManualChange?: (name: string, value: string) => void;
handleChange?: (
name: string
Expand Down Expand Up @@ -237,6 +239,7 @@ function Base(props: BaseProps) {
)}
</Grid>
{props.card.type === 'entity' && <Entity {...props} />}
{props.card.type === 'news' && <News {...props} />}
{props.card.type === 'iframe' && <Frame {...props} />}
{props.card.type === 'image' && <Image {...props} />}
{props.card.type === 'markdown' && <Markdown {...props} />}
Expand Down
Loading