Compare commits
40 Commits
f1a30d0af2
...
6a329e3ba9
| Author | SHA1 | Date | |
|---|---|---|---|
| 6a329e3ba9 | |||
| 3acaf230c4 | |||
| 7b84573dd8 | |||
| 7523426f15 | |||
| b2ec85cfa5 | |||
| 8c201d5c2e | |||
| a21c84efc6 | |||
| 15aa413584 | |||
| e9ee231954 | |||
| 62d5915133 | |||
| 61ec583882 | |||
| 1443fdcc32 | |||
| f2310b6925 | |||
| aa80570da4 | |||
| 7d0e60f5f0 | |||
| 21b5d67052 | |||
| 53468c8ccd | |||
| 6cfb4b317f | |||
| f08202d592 | |||
| 5a7f55184d | |||
| e84062394b | |||
| e867d5d868 | |||
| 845d87ec55 | |||
| e18aaad741 | |||
| 02e86efb4f | |||
| b85d879ae7 | |||
| 55bf75742e | |||
| 83cb6fc0ae | |||
| 667c2c5eaf | |||
| 1df1c59d61 | |||
| c4f2e7d595 | |||
| f61cfc09b0 | |||
| 366e76e25d | |||
| 6f1811c564 | |||
| 443115ac0f | |||
| 034c440e46 | |||
| 26a6353ca5 | |||
| 7ac4dfa01c | |||
| 633429c976 | |||
| 5cdbf6ef54 |
1
.gitignore
vendored
Normal file
1
.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
.aider*
|
||||
@@ -146,6 +146,9 @@ def story(ref):
|
||||
return False
|
||||
|
||||
|
||||
if not s['title']:
|
||||
return False
|
||||
|
||||
if s['score'] < 25 and s['num_comments'] < 10:
|
||||
logging.info('Score ({}) or num comments ({}) below threshold.'.format(s['score'], s['num_comments']))
|
||||
return False
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import logging
|
||||
import os, logging
|
||||
DEBUG = os.environ.get('DEBUG')
|
||||
logging.basicConfig(
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
level=logging.INFO)
|
||||
level=logging.DEBUG if DEBUG else logging.INFO)
|
||||
|
||||
import gevent
|
||||
from gevent import monkey
|
||||
@@ -19,7 +20,7 @@ import settings
|
||||
import database
|
||||
import search
|
||||
import feed
|
||||
from utils import gen_rand_id
|
||||
from utils import gen_rand_id, NUM_ID_CHARS
|
||||
|
||||
from flask import abort, Flask, request, render_template, stream_with_context, Response
|
||||
from werkzeug.exceptions import NotFound
|
||||
@@ -29,6 +30,8 @@ database.init()
|
||||
search.init()
|
||||
|
||||
news_index = 0
|
||||
ref_list = []
|
||||
current_item = {}
|
||||
|
||||
def new_id():
|
||||
nid = gen_rand_id()
|
||||
@@ -50,6 +53,20 @@ def api():
|
||||
res.headers['content-type'] = 'application/json'
|
||||
return res
|
||||
|
||||
@flask_app.route('/api/stats', strict_slashes=False)
|
||||
def apistats():
|
||||
stats = {
|
||||
'news_index': news_index,
|
||||
'ref_list': ref_list,
|
||||
'len_ref_list': len(ref_list),
|
||||
'current_item': current_item,
|
||||
'total_stories': database.count_stories(),
|
||||
'id_space': 26**NUM_ID_CHARS,
|
||||
}
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
@flask_app.route('/api/search', strict_slashes=False)
|
||||
def apisearch():
|
||||
q = request.args.get('q', '')
|
||||
@@ -61,10 +78,17 @@ def apisearch():
|
||||
res.headers['content-type'] = 'application/json'
|
||||
return res
|
||||
|
||||
|
||||
@flask_app.route('/api/submit', methods=['POST'], strict_slashes=False)
|
||||
def submit():
|
||||
try:
|
||||
url = request.form['url']
|
||||
for prefix in ['http://', 'https://']:
|
||||
if url.lower().startswith(prefix):
|
||||
break
|
||||
else: # for
|
||||
url = 'http://' + url
|
||||
|
||||
nid = new_id()
|
||||
|
||||
logging.info('Manual submission: ' + url)
|
||||
@@ -89,6 +113,11 @@ def submit():
|
||||
ref = url
|
||||
|
||||
existing = database.get_story_by_ref(ref)
|
||||
|
||||
if existing and DEBUG:
|
||||
ref = ref + '#' + str(time.time())
|
||||
existing = False
|
||||
|
||||
if existing:
|
||||
return {'nid': existing.sid}
|
||||
else:
|
||||
@@ -97,14 +126,20 @@ def submit():
|
||||
if valid:
|
||||
database.put_story(story)
|
||||
search.put_story(story)
|
||||
|
||||
if DEBUG:
|
||||
logging.info('Adding manual ref: {}, id: {}, source: {}'.format(ref, nid, source))
|
||||
database.put_ref(ref, nid, source)
|
||||
|
||||
return {'nid': nid}
|
||||
else:
|
||||
raise Exception('Invalid article')
|
||||
|
||||
except BaseException as e:
|
||||
logging.error('Problem with article submission: {} - {}'.format(e.__class__.__name__, str(e)))
|
||||
except Exception as e:
|
||||
msg = 'Problem with article submission: {} - {}'.format(e.__class__.__name__, str(e))
|
||||
logging.error(msg)
|
||||
print(traceback.format_exc())
|
||||
abort(400)
|
||||
return {'error': msg.split('\n')[0]}, 400
|
||||
|
||||
|
||||
@flask_app.route('/api/<sid>')
|
||||
@@ -160,7 +195,7 @@ def static_story(sid):
|
||||
http_server = WSGIServer(('', 33842), flask_app)
|
||||
|
||||
def feed_thread():
|
||||
global news_index
|
||||
global news_index, ref_list, current_item
|
||||
|
||||
try:
|
||||
while True:
|
||||
@@ -181,13 +216,13 @@ def feed_thread():
|
||||
|
||||
# update current stories
|
||||
if news_index < len(ref_list):
|
||||
item = ref_list[news_index]
|
||||
current_item = ref_list[news_index]
|
||||
|
||||
try:
|
||||
story_json = database.get_story(item['sid']).full_json
|
||||
story_json = database.get_story(current_item['sid']).full_json
|
||||
story = json.loads(story_json)
|
||||
except AttributeError:
|
||||
story = dict(id=item['sid'], ref=item['ref'], source=item['source'])
|
||||
story = dict(id=current_item['sid'], ref=current_item['ref'], source=current_item['source'])
|
||||
|
||||
logging.info('Updating {} story: {}, index: {}'.format(story['source'], story['ref'], news_index))
|
||||
|
||||
@@ -196,8 +231,8 @@ def feed_thread():
|
||||
database.put_story(story)
|
||||
search.put_story(story)
|
||||
else:
|
||||
database.del_ref(item['ref'])
|
||||
logging.info('Removed ref {}'.format(item['ref']))
|
||||
database.del_ref(current_item['ref'])
|
||||
logging.info('Removed ref {}'.format(current_item['ref']))
|
||||
else:
|
||||
logging.info('Skipping index: ' + str(news_index))
|
||||
|
||||
|
||||
@@ -16,8 +16,9 @@ def alert_tanner(message):
|
||||
except BaseException as e:
|
||||
logging.error('Problem alerting Tanner: ' + str(e))
|
||||
|
||||
NUM_ID_CHARS = 4
|
||||
def gen_rand_id():
|
||||
return ''.join(random.choice(string.ascii_uppercase) for _ in range(4))
|
||||
return ''.join(random.choice(string.ascii_uppercase) for _ in range(NUM_ID_CHARS))
|
||||
|
||||
def render_md(md):
|
||||
if md:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { BrowserRouter as Router, Route, Link, Switch } from 'react-router-dom';
|
||||
import localForage from 'localforage';
|
||||
import './Style-light.css';
|
||||
@@ -15,70 +15,63 @@ import Submit from './Submit.js';
|
||||
import Results from './Results.js';
|
||||
import ScrollToTop from './ScrollToTop.js';
|
||||
|
||||
class App extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function App() {
|
||||
const [theme, setTheme] = useState(localStorage.getItem('theme') || '');
|
||||
const cache = useRef({});
|
||||
const [isFullScreen, setIsFullScreen] = useState(!!document.fullscreenElement);
|
||||
|
||||
this.state = {
|
||||
theme: localStorage.getItem('theme') || '',
|
||||
const updateCache = useCallback((key, value) => {
|
||||
cache.current[key] = value;
|
||||
}, []);
|
||||
|
||||
const light = () => {
|
||||
setTheme('');
|
||||
localStorage.setItem('theme', '');
|
||||
};
|
||||
|
||||
this.cache = {};
|
||||
}
|
||||
|
||||
updateCache = (key, value) => {
|
||||
this.cache[key] = value;
|
||||
}
|
||||
|
||||
light() {
|
||||
this.setState({ theme: '' });
|
||||
localStorage.setItem('theme', '');
|
||||
}
|
||||
|
||||
dark() {
|
||||
this.setState({ theme: 'dark' });
|
||||
const dark = () => {
|
||||
setTheme('dark');
|
||||
localStorage.setItem('theme', 'dark');
|
||||
}
|
||||
};
|
||||
|
||||
black() {
|
||||
this.setState({ theme: 'black' });
|
||||
const black = () => {
|
||||
setTheme('black');
|
||||
localStorage.setItem('theme', 'black');
|
||||
}
|
||||
};
|
||||
|
||||
red() {
|
||||
this.setState({ theme: 'red' });
|
||||
const red = () => {
|
||||
setTheme('red');
|
||||
localStorage.setItem('theme', 'red');
|
||||
}
|
||||
};
|
||||
|
||||
componentDidMount() {
|
||||
if (!this.cache.length) {
|
||||
useEffect(() => {
|
||||
if (Object.keys(cache.current).length === 0) {
|
||||
localForage.iterate((value, key) => {
|
||||
this.updateCache(key, value);
|
||||
});
|
||||
updateCache(key, value);
|
||||
}).then(() => {
|
||||
console.log('loaded cache from localforage');
|
||||
});
|
||||
}
|
||||
}
|
||||
}, [updateCache]);
|
||||
|
||||
goFullScreen() {
|
||||
const goFullScreen = () => {
|
||||
if ('wakeLock' in navigator) {
|
||||
navigator.wakeLock.request('screen');
|
||||
}
|
||||
|
||||
document.body.requestFullscreen({ navigationUI: 'hide' }).then(() => {
|
||||
window.addEventListener('resize', () => this.forceUpdate());
|
||||
this.forceUpdate();
|
||||
});
|
||||
document.body.requestFullscreen({ navigationUI: 'hide' });
|
||||
};
|
||||
|
||||
exitFullScreen() {
|
||||
document.exitFullscreen().then(() => {
|
||||
this.forceUpdate();
|
||||
});
|
||||
const exitFullScreen = () => {
|
||||
document.exitFullscreen();
|
||||
};
|
||||
|
||||
render() {
|
||||
const theme = this.state.theme;
|
||||
useEffect(() => {
|
||||
const onFullScreenChange = () => setIsFullScreen(!!document.fullscreenElement);
|
||||
document.addEventListener('fullscreenchange', onFullScreenChange);
|
||||
return () => document.removeEventListener('fullscreenchange', onFullScreenChange);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (theme === 'dark') {
|
||||
document.body.style.backgroundColor = '#1a1a1a';
|
||||
} else if (theme === 'black') {
|
||||
@@ -88,6 +81,7 @@ class App extends React.Component {
|
||||
} else {
|
||||
document.body.style.backgroundColor = '#eeeeee';
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const fullScreenAvailable = document.fullscreenEnabled ||
|
||||
document.mozFullscreenEnabled ||
|
||||
@@ -101,27 +95,27 @@ class App extends React.Component {
|
||||
<p>
|
||||
<Link to='/'>QotNews</Link>
|
||||
|
||||
<span className='theme'><a href='#' onClick={() => this.light()}>Light</a> - <a href='#' onClick={() => this.dark()}>Dark</a> - <a href='#' onClick={() => this.black()}>Black</a> - <a href='#' onClick={() => this.red()}>Red</a></span>
|
||||
<span className='theme'><a href='#' onClick={() => light()}>Light</a> - <a href='#' onClick={() => dark()}>Dark</a> - <a href='#' onClick={() => black()}>Black</a> - <a href='#' onClick={() => red()}>Red</a></span>
|
||||
<br />
|
||||
<span className='slogan'>Hacker News, Reddit, Lobsters, and Tildes articles rendered in reader mode.</span>
|
||||
</p>
|
||||
<Route path='/(|search)' component={Search} />
|
||||
<Route path='/(|search)' component={Submit} />
|
||||
{fullScreenAvailable &&
|
||||
<Route path='/(|search)' render={() => !document.fullscreenElement ?
|
||||
<button className='fullscreen' onClick={() => this.goFullScreen()}>Enter Fullscreen</button>
|
||||
<Route path='/(|search)' render={() => !isFullScreen ?
|
||||
<button className='fullscreen' onClick={() => goFullScreen()}>Enter Fullscreen</button>
|
||||
:
|
||||
<button className='fullscreen' onClick={() => this.exitFullScreen()}>Exit Fullscreen</button>
|
||||
<button className='fullscreen' onClick={() => exitFullScreen()}>Exit Fullscreen</button>
|
||||
} />
|
||||
}
|
||||
<Route path='/(|search)' component={Search} />
|
||||
<Route path='/(|search)' component={Submit} />
|
||||
</div>
|
||||
|
||||
<Route path='/' exact render={(props) => <Feed {...props} updateCache={this.updateCache} />} />
|
||||
<Route path='/' exact render={(props) => <Feed {...props} updateCache={updateCache} />} />
|
||||
<Switch>
|
||||
<Route path='/search' component={Results} />
|
||||
<Route path='/:id' exact render={(props) => <Article {...props} cache={this.cache} />} />
|
||||
<Route path='/:id' exact render={(props) => <Article {...props} cache={cache.current} />} />
|
||||
</Switch>
|
||||
<Route path='/:id/c' exact render={(props) => <Comments {...props} cache={this.cache} />} />
|
||||
<Route path='/:id/c' exact render={(props) => <Comments {...props} cache={cache.current} />} />
|
||||
|
||||
<BackwardDot />
|
||||
<ForwardDot />
|
||||
@@ -130,7 +124,6 @@ class App extends React.Component {
|
||||
</Router>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default App;
|
||||
|
||||
@@ -1,69 +1,69 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect, useMemo } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import localForage from 'localforage';
|
||||
import { sourceLink, infoLine, ToggleDot } from './utils.js';
|
||||
|
||||
class Article extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
|
||||
const id = this.props.match ? this.props.match.params.id : 'CLOL';
|
||||
const cache = this.props.cache;
|
||||
function Article({ cache }) {
|
||||
const { id } = useParams();
|
||||
|
||||
if (id in cache) console.log('cache hit');
|
||||
|
||||
this.state = {
|
||||
story: cache[id] || false,
|
||||
error: false,
|
||||
pConv: [],
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const id = this.props.match ? this.props.match.params.id : 'CLOL';
|
||||
const [story, setStory] = useState(cache[id] || false);
|
||||
const [error, setError] = useState('');
|
||||
const [pConv, setPConv] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
localForage.getItem(id)
|
||||
.then(
|
||||
(value) => {
|
||||
if (value) {
|
||||
this.setState({ story: value });
|
||||
setStory(value);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fetch('/api/' + id)
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
}
|
||||
return res.json();
|
||||
})
|
||||
.then(
|
||||
(result) => {
|
||||
this.setState({ story: result.story });
|
||||
setStory(result.story);
|
||||
localForage.setItem(id, result.story);
|
||||
},
|
||||
(error) => {
|
||||
this.setState({ error: true });
|
||||
const errorMessage = `Failed to fetch new article content (ID: ${id}). Your connection may be down or the server might be experiencing issues. ${error.toString()}.`;
|
||||
setError(errorMessage);
|
||||
}
|
||||
);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
pConvert = (n) => {
|
||||
this.setState({ pConv: [...this.state.pConv, n]});
|
||||
}
|
||||
const pConvert = (n) => {
|
||||
setPConv(prevPConv => [...prevPConv, n]);
|
||||
};
|
||||
|
||||
render() {
|
||||
const id = this.props.match ? this.props.match.params.id : 'CLOL';
|
||||
const story = this.state.story;
|
||||
const error = this.state.error;
|
||||
const pConv = this.state.pConv;
|
||||
let nodes = null;
|
||||
|
||||
if (story.text) {
|
||||
const nodes = useMemo(() => {
|
||||
if (story && story.text) {
|
||||
let div = document.createElement('div');
|
||||
div.innerHTML = story.text;
|
||||
nodes = div.childNodes;
|
||||
return div.childNodes;
|
||||
}
|
||||
return null;
|
||||
}, [story]);
|
||||
|
||||
return (
|
||||
<div className='article-container'>
|
||||
{error && <p>Connection error?</p>}
|
||||
{error &&
|
||||
<details style={{marginBottom: '1rem'}}>
|
||||
<summary>Connection error? Click to expand.</summary>
|
||||
<p>{error}</p>
|
||||
{story && <p>Loaded article from cache.</p>}
|
||||
</details>
|
||||
}
|
||||
{story ?
|
||||
<div className='article'>
|
||||
<Helmet>
|
||||
@@ -83,17 +83,19 @@ class Article extends React.Component {
|
||||
<div className='story-text'>
|
||||
{Object.entries(nodes).map(([k, v]) =>
|
||||
pConv.includes(k) ?
|
||||
v.innerHTML.split('\n\n').map(x =>
|
||||
<p dangerouslySetInnerHTML={{ __html: x }} />
|
||||
)
|
||||
<React.Fragment key={k}>
|
||||
{v.innerHTML.split('\n\n').map((x, i) =>
|
||||
<p key={i} dangerouslySetInnerHTML={{ __html: x }} />
|
||||
)}
|
||||
</React.Fragment>
|
||||
:
|
||||
(v.nodeName === '#text' ?
|
||||
<p>{v.data}</p>
|
||||
<p key={k}>{v.data}</p>
|
||||
:
|
||||
<>
|
||||
<React.Fragment key={k}>
|
||||
<v.localName dangerouslySetInnerHTML={v.innerHTML ? { __html: v.innerHTML } : null} />
|
||||
{v.localName == 'pre' && <button onClick={() => this.pConvert(k)}>Convert Code to Paragraph</button>}
|
||||
</>
|
||||
{v.localName === 'pre' && <button onClick={() => pConvert(k)}>Convert Code to Paragraph</button>}
|
||||
</React.Fragment>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
@@ -102,12 +104,11 @@ class Article extends React.Component {
|
||||
}
|
||||
</div>
|
||||
:
|
||||
<p>loading...</p>
|
||||
<p>Loading...</p>
|
||||
}
|
||||
<ToggleDot id={id} article={false} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Article;
|
||||
|
||||
@@ -1,83 +1,80 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { HashLink } from 'react-router-hash-link';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import moment from 'moment';
|
||||
import localForage from 'localforage';
|
||||
import { infoLine, ToggleDot } from './utils.js';
|
||||
|
||||
class Article extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function countComments(c) {
|
||||
return c.comments.reduce((sum, x) => sum + countComments(x), 1);
|
||||
}
|
||||
|
||||
const id = this.props.match.params.id;
|
||||
const cache = this.props.cache;
|
||||
function Comments({ cache }) {
|
||||
const { id } = useParams();
|
||||
|
||||
if (id in cache) console.log('cache hit');
|
||||
|
||||
this.state = {
|
||||
story: cache[id] || false,
|
||||
error: false,
|
||||
collapsed: [],
|
||||
expanded: [],
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
const id = this.props.match.params.id;
|
||||
const [story, setStory] = useState(cache[id] || false);
|
||||
const [error, setError] = useState('');
|
||||
const [collapsed, setCollapsed] = useState([]);
|
||||
const [expanded, setExpanded] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
localForage.getItem(id)
|
||||
.then(
|
||||
(value) => {
|
||||
this.setState({ story: value });
|
||||
if (value) {
|
||||
setStory(value);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
fetch('/api/' + id)
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
}
|
||||
return res.json();
|
||||
})
|
||||
.then(
|
||||
(result) => {
|
||||
this.setState({ story: result.story }, () => {
|
||||
setStory(result.story);
|
||||
localForage.setItem(id, result.story);
|
||||
const hash = window.location.hash.substring(1);
|
||||
if (hash) {
|
||||
document.getElementById(hash).scrollIntoView();
|
||||
setTimeout(() => {
|
||||
const element = document.getElementById(hash);
|
||||
if (element) {
|
||||
element.scrollIntoView();
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
});
|
||||
localForage.setItem(id, result.story);
|
||||
},
|
||||
(error) => {
|
||||
this.setState({ error: true });
|
||||
const errorMessage = `Failed to fetch comments (ID: ${id}). Your connection may be down or the server might be experiencing issues. ${error.toString()}.`;
|
||||
setError(errorMessage);
|
||||
}
|
||||
);
|
||||
}
|
||||
}, [id]);
|
||||
|
||||
collapseComment(cid) {
|
||||
this.setState(prevState => ({
|
||||
...prevState,
|
||||
collapsed: [...prevState.collapsed, cid],
|
||||
expanded: prevState.expanded.filter(x => x !== cid),
|
||||
}));
|
||||
}
|
||||
const collapseComment = useCallback((cid) => {
|
||||
setCollapsed(prev => [...prev, cid]);
|
||||
setExpanded(prev => prev.filter(x => x !== cid));
|
||||
}, []);
|
||||
|
||||
expandComment(cid) {
|
||||
this.setState(prevState => ({
|
||||
...prevState,
|
||||
collapsed: prevState.collapsed.filter(x => x !== cid),
|
||||
expanded: [...prevState.expanded, cid],
|
||||
}));
|
||||
}
|
||||
const expandComment = useCallback((cid) => {
|
||||
setCollapsed(prev => prev.filter(x => x !== cid));
|
||||
setExpanded(prev => [...prev, cid]);
|
||||
}, []);
|
||||
|
||||
countComments(c) {
|
||||
return c.comments.reduce((sum, x) => sum + this.countComments(x), 1);
|
||||
}
|
||||
|
||||
displayComment(story, c, level) {
|
||||
const displayComment = useCallback((story, c, level) => {
|
||||
const cid = c.author+c.date;
|
||||
|
||||
const collapsed = this.state.collapsed.includes(cid);
|
||||
const expanded = this.state.expanded.includes(cid);
|
||||
const isCollapsed = collapsed.includes(cid);
|
||||
const isExpanded = expanded.includes(cid);
|
||||
|
||||
const hidden = collapsed || (level == 4 && !expanded);
|
||||
const hidden = isCollapsed || (level == 4 && !isExpanded);
|
||||
const hasChildren = c.comments.length !== 0;
|
||||
|
||||
return (
|
||||
@@ -88,30 +85,31 @@ class Article extends React.Component {
|
||||
{' '} | <HashLink to={'#'+cid} id={cid}>{moment.unix(c.date).fromNow()}</HashLink>
|
||||
|
||||
{hidden || hasChildren &&
|
||||
<span className='collapser pointer' onClick={() => this.collapseComment(cid)}>–</span>
|
||||
<span className='collapser pointer' onClick={() => collapseComment(cid)}>–</span>
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className={collapsed ? 'text hidden' : 'text'} dangerouslySetInnerHTML={{ __html: c.text }} />
|
||||
<div className={isCollapsed ? 'text hidden' : 'text'} dangerouslySetInnerHTML={{ __html: c.text }} />
|
||||
|
||||
{hidden && hasChildren ?
|
||||
<div className='comment lined info pointer' onClick={() => this.expandComment(cid)}>[show {this.countComments(c)-1} more]</div>
|
||||
<div className='comment lined info pointer' onClick={() => expandComment(cid)}>[show {countComments(c)-1} more]</div>
|
||||
:
|
||||
c.comments.map(i => this.displayComment(story, i, level + 1))
|
||||
c.comments.map(i => displayComment(story, i, level + 1))
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const id = this.props.match.params.id;
|
||||
const story = this.state.story;
|
||||
const error = this.state.error;
|
||||
}, [collapsed, expanded, collapseComment, expandComment]);
|
||||
|
||||
return (
|
||||
<div className='container'>
|
||||
{error && <p>Connection error?</p>}
|
||||
{error &&
|
||||
<details style={{marginBottom: '1rem'}}>
|
||||
<summary>Connection error? Click to expand.</summary>
|
||||
<p>{error}</p>
|
||||
{story && <p>Loaded comments from cache.</p>}
|
||||
</details>
|
||||
}
|
||||
{story ?
|
||||
<div className='article'>
|
||||
<Helmet>
|
||||
@@ -128,7 +126,7 @@ class Article extends React.Component {
|
||||
{infoLine(story)}
|
||||
|
||||
<div className='comments'>
|
||||
{story.comments.map(c => this.displayComment(story, c, 0))}
|
||||
{story.comments.map(c => displayComment(story, c, 0))}
|
||||
</div>
|
||||
</div>
|
||||
:
|
||||
@@ -137,7 +135,6 @@ class Article extends React.Component {
|
||||
<ToggleDot id={id} article={true} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Article;
|
||||
export default Comments;
|
||||
|
||||
@@ -1,53 +1,94 @@
|
||||
import React from 'react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import localForage from 'localforage';
|
||||
import { sourceLink, infoLine, logos } from './utils.js';
|
||||
|
||||
class Feed extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function Feed({ updateCache }) {
|
||||
const [stories, setStories] = useState(() => JSON.parse(localStorage.getItem('stories')) || false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
this.state = {
|
||||
stories: JSON.parse(localStorage.getItem('stories')) || false,
|
||||
error: false,
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
useEffect(() => {
|
||||
fetch('/api')
|
||||
.then(res => res.json())
|
||||
.then(
|
||||
(result) => {
|
||||
const updated = !this.state.stories || this.state.stories[0].id !== result.stories[0].id;
|
||||
console.log('updated:', updated);
|
||||
|
||||
this.setState({ stories: result.stories });
|
||||
localStorage.setItem('stories', JSON.stringify(result.stories));
|
||||
|
||||
if (updated) {
|
||||
localForage.clear();
|
||||
result.stories.forEach((x, i) => {
|
||||
fetch('/api/' + x.id)
|
||||
.then(res => res.json())
|
||||
.then(result => {
|
||||
localForage.setItem(x.id, result.story)
|
||||
.then(console.log('preloaded', x.id, x.title));
|
||||
this.props.updateCache(x.id, result.story);
|
||||
}, error => {}
|
||||
);
|
||||
});
|
||||
.then(res => {
|
||||
if (!res.ok) {
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
}
|
||||
return res.json();
|
||||
})
|
||||
.then(
|
||||
async (result) => {
|
||||
const newApiStories = result.stories;
|
||||
|
||||
const updated = !stories || !stories.length || stories[0].id !== newApiStories[0].id;
|
||||
console.log('New stories available:', updated);
|
||||
|
||||
if (!updated) return;
|
||||
|
||||
if (!stories || !stories.length) {
|
||||
setStories(newApiStories);
|
||||
localStorage.setItem('stories', JSON.stringify(newApiStories));
|
||||
}
|
||||
|
||||
let currentStories = Array.isArray(stories) ? [...stories] : [];
|
||||
let preloadedCount = 0;
|
||||
|
||||
for (const newStory of [...newApiStories].reverse()) {
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 10000); // 10-second timeout
|
||||
const storyRes = await fetch('/api/' + newStory.id, { signal: controller.signal });
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!storyRes.ok) {
|
||||
throw new Error(`Server responded with ${storyRes.status} ${storyRes.statusText}`);
|
||||
}
|
||||
const storyResult = await storyRes.json();
|
||||
const fullStory = storyResult.story;
|
||||
|
||||
await localForage.setItem(fullStory.id, fullStory);
|
||||
console.log('Preloaded story:', fullStory.id, fullStory.title);
|
||||
updateCache(fullStory.id, fullStory);
|
||||
preloadedCount++;
|
||||
|
||||
const existingStoryIndex = currentStories.findIndex(s => s.id === newStory.id);
|
||||
if (existingStoryIndex > -1) {
|
||||
currentStories.splice(existingStoryIndex, 1);
|
||||
}
|
||||
currentStories.unshift(newStory);
|
||||
|
||||
localStorage.setItem('stories', JSON.stringify(currentStories));
|
||||
setStories(currentStories);
|
||||
} catch (error) {
|
||||
let errorMessage;
|
||||
if (error.name === 'AbortError') {
|
||||
errorMessage = `The request to fetch story '${newStory.title}' (${newStory.id}) timed out after 10 seconds. Your connection may be unstable. (${preloadedCount} / ${newApiStories.length} stories preloaded)`;
|
||||
console.log('Fetch timed out for story:', newStory.id);
|
||||
} else {
|
||||
errorMessage = `An error occurred while fetching story '${newStory.title}' (ID: ${newStory.id}): ${error.toString()}. (${preloadedCount} / ${newApiStories.length} stories preloaded)`;
|
||||
console.log('Fetch failed for story:', newStory.id, error);
|
||||
}
|
||||
setError(errorMessage);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const finalStories = currentStories.slice(0, newApiStories.length);
|
||||
const removedStories = currentStories.slice(newApiStories.length);
|
||||
for (const story of removedStories) {
|
||||
console.log('Removed story:', story.id, story.title);
|
||||
localForage.removeItem(story.id);
|
||||
}
|
||||
|
||||
localStorage.setItem('stories', JSON.stringify(finalStories));
|
||||
setStories(finalStories);
|
||||
},
|
||||
(error) => {
|
||||
this.setState({ error: true });
|
||||
const errorMessage = `Failed to fetch the main story list from the API. Your connection may be down or the server might be experiencing issues. ${error.toString()}.`;
|
||||
setError(errorMessage);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
render() {
|
||||
const stories = this.state.stories;
|
||||
const error = this.state.error;
|
||||
}, [updateCache]);
|
||||
|
||||
return (
|
||||
<div className='container'>
|
||||
@@ -55,7 +96,13 @@ class Feed extends React.Component {
|
||||
<title>QotNews</title>
|
||||
<meta name="robots" content="index" />
|
||||
</Helmet>
|
||||
{error && <p>Connection error?</p>}
|
||||
{error &&
|
||||
<details style={{marginBottom: '1rem'}}>
|
||||
<summary>Connection error? Click to expand.</summary>
|
||||
<p>{error}</p>
|
||||
{stories && <p>Loaded feed from cache.</p>}
|
||||
</details>
|
||||
}
|
||||
{stories ?
|
||||
<div>
|
||||
{stories.map(x =>
|
||||
@@ -75,11 +122,10 @@ class Feed extends React.Component {
|
||||
)}
|
||||
</div>
|
||||
:
|
||||
<p>loading...</p>
|
||||
<p>Loading...</p>
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Feed;
|
||||
|
||||
@@ -1,57 +1,36 @@
|
||||
import React from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { Helmet } from 'react-helmet';
|
||||
import { sourceLink, infoLine, logos } from './utils.js';
|
||||
import AbortController from 'abort-controller';
|
||||
|
||||
class Results extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function Results() {
|
||||
const [stories, setStories] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const location = useLocation();
|
||||
|
||||
this.state = {
|
||||
stories: false,
|
||||
error: false,
|
||||
};
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
|
||||
this.controller = null;
|
||||
}
|
||||
|
||||
performSearch = () => {
|
||||
if (this.controller) {
|
||||
this.controller.abort();
|
||||
}
|
||||
|
||||
this.controller = new AbortController();
|
||||
const signal = this.controller.signal;
|
||||
|
||||
const search = this.props.location.search;
|
||||
const search = location.search;
|
||||
fetch('/api/search' + search, { method: 'get', signal: signal })
|
||||
.then(res => res.json())
|
||||
.then(
|
||||
(result) => {
|
||||
this.setState({ stories: result.hits });
|
||||
setStories(result.hits);
|
||||
},
|
||||
(error) => {
|
||||
if (error.message !== 'The operation was aborted. ') {
|
||||
this.setState({ error: true });
|
||||
setError(true);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
this.performSearch();
|
||||
}
|
||||
|
||||
componentDidUpdate(prevProps) {
|
||||
if (this.props.location.search !== prevProps.location.search) {
|
||||
this.performSearch();
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
const stories = this.state.stories;
|
||||
const error = this.state.error;
|
||||
return () => {
|
||||
controller.abort();
|
||||
};
|
||||
}, [location.search]);
|
||||
|
||||
return (
|
||||
<div className='container'>
|
||||
@@ -89,7 +68,6 @@ class Results extends React.Component {
|
||||
}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default Results;
|
||||
|
||||
@@ -1,14 +1,10 @@
|
||||
import React from 'react';
|
||||
import { withRouter } from 'react-router-dom';
|
||||
import { useEffect } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
|
||||
class ScrollToTop extends React.Component {
|
||||
componentDidUpdate(prevProps) {
|
||||
//console.log(this.props.location.pathname, prevProps.location.pathname);
|
||||
|
||||
if (this.props.location.pathname === prevProps.location.pathname) {
|
||||
return;
|
||||
}
|
||||
function ScrollToTop() {
|
||||
const { pathname } = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
if (localStorage.getItem('scrollLock') === 'True') {
|
||||
localStorage.setItem('scrollLock', 'False');
|
||||
return;
|
||||
@@ -16,11 +12,9 @@ class ScrollToTop extends React.Component {
|
||||
|
||||
window.scrollTo(0, 0);
|
||||
document.body.scrollTop = 0;
|
||||
}
|
||||
}, [pathname]);
|
||||
|
||||
render() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(ScrollToTop);
|
||||
export default ScrollToTop;
|
||||
|
||||
@@ -1,51 +1,46 @@
|
||||
import React, { Component } from 'react';
|
||||
import { withRouter } from 'react-router-dom';
|
||||
import React, { useState, useRef } from 'react';
|
||||
import { useHistory, useLocation } from 'react-router-dom';
|
||||
import queryString from 'query-string';
|
||||
|
||||
const getSearch = props => queryString.parse(props.location.search).q;
|
||||
const getSearch = location => queryString.parse(location.search).q || '';
|
||||
|
||||
class Search extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function Search() {
|
||||
const history = useHistory();
|
||||
const location = useLocation();
|
||||
|
||||
this.state = {search: getSearch(this.props)};
|
||||
this.inputRef = React.createRef();
|
||||
}
|
||||
const [search, setSearch] = useState(getSearch(location));
|
||||
const inputRef = useRef(null);
|
||||
|
||||
searchArticles = (event) => {
|
||||
const search = event.target.value;
|
||||
this.setState({search: search});
|
||||
if (search.length >= 3) {
|
||||
const searchQuery = queryString.stringify({ 'q': search });
|
||||
this.props.history.replace('/search?' + searchQuery);
|
||||
const searchArticles = (event) => {
|
||||
const newSearch = event.target.value;
|
||||
setSearch(newSearch);
|
||||
if (newSearch.length >= 3) {
|
||||
const searchQuery = queryString.stringify({ 'q': newSearch });
|
||||
history.replace('/search?' + searchQuery);
|
||||
} else {
|
||||
this.props.history.replace('/');
|
||||
history.replace('/');
|
||||
}
|
||||
}
|
||||
|
||||
searchAgain = (event) => {
|
||||
const searchAgain = (event) => {
|
||||
event.preventDefault();
|
||||
const searchString = queryString.stringify({ 'q': event.target[0].value });
|
||||
this.props.history.push('/search?' + searchString);
|
||||
this.inputRef.current.blur();
|
||||
history.push('/search?' + searchString);
|
||||
inputRef.current.blur();
|
||||
}
|
||||
|
||||
render() {
|
||||
const search = this.state.search;
|
||||
|
||||
return (
|
||||
<span className='search'>
|
||||
<form onSubmit={this.searchAgain}>
|
||||
<form onSubmit={searchAgain}>
|
||||
<input
|
||||
placeholder='Search...'
|
||||
value={search}
|
||||
onChange={this.searchArticles}
|
||||
ref={this.inputRef}
|
||||
onChange={searchArticles}
|
||||
ref={inputRef}
|
||||
/>
|
||||
</form>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(Search);
|
||||
export default Search;
|
||||
|
||||
@@ -1,54 +1,53 @@
|
||||
import React, { Component } from 'react';
|
||||
import { withRouter } from 'react-router-dom';
|
||||
import React, { useState, useRef } from 'react';
|
||||
import { useHistory } from 'react-router-dom';
|
||||
|
||||
class Submit extends Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
function Submit() {
|
||||
const [progress, setProgress] = useState(null);
|
||||
const inputRef = useRef(null);
|
||||
const history = useHistory();
|
||||
|
||||
this.state = {
|
||||
progress: null,
|
||||
};
|
||||
|
||||
this.inputRef = React.createRef();
|
||||
}
|
||||
|
||||
submitArticle = (event) => {
|
||||
const submitArticle = async (event) => {
|
||||
event.preventDefault();
|
||||
const url = event.target[0].value;
|
||||
this.inputRef.current.blur();
|
||||
inputRef.current.blur();
|
||||
|
||||
this.setState({ progress: 'Submitting...' });
|
||||
setProgress('Submitting...');
|
||||
|
||||
let data = new FormData();
|
||||
data.append('url', url);
|
||||
|
||||
fetch('/api/submit', { method: 'POST', body: data })
|
||||
.then(res => res.json())
|
||||
.then(
|
||||
(result) => {
|
||||
this.props.history.replace('/' + result.nid);
|
||||
},
|
||||
(error) => {
|
||||
this.setState({ progress: 'Error' });
|
||||
}
|
||||
);
|
||||
}
|
||||
try {
|
||||
const res = await fetch('/api/submit', { method: 'POST', body: data });
|
||||
|
||||
render() {
|
||||
const progress = this.state.progress;
|
||||
if (res.ok) {
|
||||
const result = await res.json();
|
||||
history.replace('/' + result.nid);
|
||||
} else {
|
||||
let errorData;
|
||||
try {
|
||||
errorData = await res.json();
|
||||
} catch (jsonError) {
|
||||
// Not a JSON error from our API, so it's a server issue
|
||||
throw new Error(`Server responded with ${res.status} ${res.statusText}`);
|
||||
}
|
||||
setProgress(errorData.error || 'An unknown error occurred.');
|
||||
}
|
||||
} catch (error) {
|
||||
setProgress(`Error: ${error.toString()}`);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<span className='search'>
|
||||
<form onSubmit={this.submitArticle}>
|
||||
<form onSubmit={submitArticle}>
|
||||
<input
|
||||
placeholder='Submit URL'
|
||||
ref={this.inputRef}
|
||||
ref={inputRef}
|
||||
/>
|
||||
</form>
|
||||
{progress ? progress : ''}
|
||||
{progress && <p>{progress}</p>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export default withRouter(Submit);
|
||||
export default Submit;
|
||||
|
||||
@@ -21,12 +21,7 @@ export const infoLine = (story) =>
|
||||
</div>
|
||||
;
|
||||
|
||||
export class ToggleDot extends React.Component {
|
||||
render() {
|
||||
const id = this.props.id;
|
||||
const article = this.props.article;
|
||||
|
||||
return (
|
||||
export const ToggleDot = ({ id, article }) => (
|
||||
<div className='dot toggleDot'>
|
||||
<div className='button'>
|
||||
<Link to={'/' + id + (article ? '' : '/c')}>
|
||||
@@ -34,50 +29,44 @@ export class ToggleDot extends React.Component {
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export class BackwardDot extends React.Component {
|
||||
goBackward() {
|
||||
export const BackwardDot = () => {
|
||||
const goBackward = () => {
|
||||
localStorage.setItem('scrollLock', 'True');
|
||||
window.history.back();
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
|
||||
if (!isMobile) return null;
|
||||
if (!document.fullscreenElement) return null;
|
||||
|
||||
return (
|
||||
<div className='dot backwardDot' onClick={this.goBackward}>
|
||||
<div className='dot backwardDot' onClick={goBackward}>
|
||||
<div className='button'>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export class ForwardDot extends React.Component {
|
||||
goForward() {
|
||||
export const ForwardDot = () => {
|
||||
const goForward = () => {
|
||||
localStorage.setItem('scrollLock', 'True');
|
||||
window.history.forward();
|
||||
}
|
||||
};
|
||||
|
||||
render() {
|
||||
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
|
||||
if (!isMobile) return null;
|
||||
|
||||
return (
|
||||
<div className='dot forwardDot' onClick={this.goForward}>
|
||||
<div className='dot forwardDot' onClick={goForward}>
|
||||
<div className='button'>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export const logos = {
|
||||
hackernews: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH4wgeBhwhciGZUAAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAGCSURBVFjD7Za/S0JRFMc/+oSgLWjLH/2AIKEhC2opIp1amqw/INCo9lbHghCnKDdpN5OoIGhISSLwx2RCEYSjUWhWpO+9hicopCHh8w29Mx3u/XLv95z7Pedcg+y1VQEBbUw0ang5gGBEY9MJ6ARMbaH6HdBnBlmC+5PfsVYX9PTCSx4KyQ4RsI6DxwcYIGSFxF5znHkOtvZBECDoa4tAe0+QDMFDVvFd7ta4pU0QTAo2GeqwBqIHIEkwMAQzaz/3LfNgn1Qw0aAKIswdQzZVy8Jyk+g3lNTfpSEXUakKjgJQrYB5GKY9DRpZALsDxCqEAyqWYT4G6etaFlYaol8HowCZBOSvVO4DR374+gTLCEytgs0JYxPKWtivUh9otOcM3FzC7CI43fBWVKK/vYBCqkudMLIN7yUYHFXe/qMMkZ0utuLyE8ROwWBU6j5+BqXHLs+C+GHdP9/VYBhJ1bpfedXHsU5A5Q9JKxEWa+KT5T8fY5C9NlnXgE7g3xMQNbxf/AZyEGqvyYs/dQAAAABJRU5ErkJggg==',
|
||||
|
||||
8149
webclient/yarn.lock
8149
webclient/yarn.lock
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user