Merge branch 'dev' and similar_post_fetch

- Fixes #131
This commit is contained in:
Dessalines 2019-08-22 16:18:26 -07:00
commit 77bba69eab
15 changed files with 191 additions and 46 deletions

View File

@ -254,6 +254,7 @@ impl Perform<GetPostsResponse> for Oper<GetPosts> {
data.community_id, data.community_id,
None, None,
None, None,
None,
user_id, user_id,
show_nsfw, show_nsfw,
false, false,

View File

@ -23,6 +23,7 @@ pub struct Search {
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct SearchResponse { pub struct SearchResponse {
op: String, op: String,
type_: String,
comments: Vec<CommentView>, comments: Vec<CommentView>,
posts: Vec<PostView>, posts: Vec<PostView>,
communities: Vec<CommunityView>, communities: Vec<CommunityView>,
@ -289,6 +290,7 @@ impl Perform<SearchResponse> for Oper<Search> {
None, None,
Some(data.q.to_owned()), Some(data.q.to_owned()),
None, None,
None,
true, true,
false, false,
false, false,
@ -334,6 +336,7 @@ impl Perform<SearchResponse> for Oper<Search> {
None, None,
Some(data.q.to_owned()), Some(data.q.to_owned()),
None, None,
None,
true, true,
false, false,
false, false,
@ -363,6 +366,22 @@ impl Perform<SearchResponse> for Oper<Search> {
Some(data.q.to_owned()), Some(data.q.to_owned()),
data.page, data.page,
data.limit)?; data.limit)?;
},
SearchType::Url => {
posts = PostView::list(
&conn,
PostListingType::All,
&sort,
data.community_id,
None,
None,
Some(data.q.to_owned()),
None,
true,
false,
false,
data.page,
data.limit)?;
} }
}; };
@ -371,6 +390,7 @@ impl Perform<SearchResponse> for Oper<Search> {
Ok( Ok(
SearchResponse { SearchResponse {
op: self.op.to_string(), op: self.op.to_string(),
type_: data.type_.to_owned(),
comments: comments, comments: comments,
posts: posts, posts: posts,
communities: communities, communities: communities,

View File

@ -318,6 +318,7 @@ impl Perform<GetUserDetailsResponse> for Oper<GetUserDetails> {
data.community_id, data.community_id,
None, None,
None, None,
None,
Some(user_details_id), Some(user_details_id),
show_nsfw, show_nsfw,
data.saved_only, data.saved_only,
@ -332,6 +333,7 @@ impl Perform<GetUserDetailsResponse> for Oper<GetUserDetails> {
data.community_id, data.community_id,
Some(user_details_id), Some(user_details_id),
None, None,
None,
user_id, user_id,
show_nsfw, show_nsfw,
data.saved_only, data.saved_only,

View File

@ -67,7 +67,7 @@ pub enum SortType {
#[derive(EnumString,ToString,Debug, Serialize, Deserialize)] #[derive(EnumString,ToString,Debug, Serialize, Deserialize)]
pub enum SearchType { pub enum SearchType {
All, Comments, Posts, Communities, Users All, Comments, Posts, Communities, Users, Url
} }
pub fn fuzzy_search(q: &str) -> String { pub fn fuzzy_search(q: &str) -> String {

View File

@ -79,6 +79,7 @@ impl PostView {
for_community_id: Option<i32>, for_community_id: Option<i32>,
for_creator_id: Option<i32>, for_creator_id: Option<i32>,
search_term: Option<String>, search_term: Option<String>,
url_search: Option<String>,
my_user_id: Option<i32>, my_user_id: Option<i32>,
show_nsfw: bool, show_nsfw: bool,
saved_only: bool, saved_only: bool,
@ -104,6 +105,10 @@ impl PostView {
query = query.filter(name.ilike(fuzzy_search(&search_term))); query = query.filter(name.ilike(fuzzy_search(&search_term)));
}; };
if let Some(url_search) = url_search {
query = query.filter(url.eq(url_search));
};
// TODO these are wrong, bc they'll only show saved for your logged in user, not theirs // TODO these are wrong, bc they'll only show saved for your logged in user, not theirs
if saved_only { if saved_only {
query = query.filter(saved.eq(true)); query = query.filter(saved.eq(true));
@ -326,9 +331,12 @@ mod tests {
}; };
let read_post_listings_with_user = PostView::list(&conn, let read_post_listings_with_user = PostView::list(
&conn,
PostListingType::Community, PostListingType::Community,
&SortType::New, Some(inserted_community.id), &SortType::New,
Some(inserted_community.id),
None,
None, None,
None, None,
Some(inserted_user.id), Some(inserted_user.id),
@ -337,13 +345,15 @@ mod tests {
false, false,
None, None,
None).unwrap(); None).unwrap();
let read_post_listings_no_user = PostView::list(&conn, let read_post_listings_no_user = PostView::list(
&conn,
PostListingType::Community, PostListingType::Community,
&SortType::New, &SortType::New,
Some(inserted_community.id), Some(inserted_community.id),
None, None,
None, None,
None, None,
None,
false, false,
false, false,
false, false,

View File

@ -142,6 +142,7 @@ impl ChatServer {
None, None,
None, None,
None, None,
None,
false, false,
false, false,
false, false,

View File

@ -1,6 +1,7 @@
import { Component } from 'inferno'; import { Component } from 'inferno';
import { PostForm } from './post-form'; import { PostForm } from './post-form';
import { WebSocketService } from '../services'; import { WebSocketService } from '../services';
import { PostFormParams } from '../interfaces';
import { i18n } from '../i18next'; import { i18n } from '../i18next';
import { T } from 'inferno-i18next'; import { T } from 'inferno-i18next';
@ -21,13 +22,25 @@ export class CreatePost extends Component<any, any> {
<div class="row"> <div class="row">
<div class="col-12 col-lg-6 offset-lg-3 mb-4"> <div class="col-12 col-lg-6 offset-lg-3 mb-4">
<h5><T i18nKey="create_post">#</T></h5> <h5><T i18nKey="create_post">#</T></h5>
<PostForm onCreate={this.handlePostCreate} prevCommunityName={this.prevCommunityName} /> <PostForm onCreate={this.handlePostCreate} params={this.params} />
</div> </div>
</div> </div>
</div> </div>
) )
} }
get params(): PostFormParams {
let urlParams = new URLSearchParams(this.props.location.search);
let params: PostFormParams = {
name: urlParams.get("name"),
community: urlParams.get("community") || this.prevCommunityName,
body: urlParams.get("body"),
url: urlParams.get("url"),
};
return params;
}
get prevCommunityName(): string { get prevCommunityName(): string {
if (this.props.match.params.name) { if (this.props.match.params.name) {
return this.props.match.params.name; return this.props.match.params.name;

View File

@ -2,7 +2,7 @@ import { Component, linkEvent } from 'inferno';
import { PostListings } from './post-listings'; import { PostListings } from './post-listings';
import { Subscription } from "rxjs"; import { Subscription } from "rxjs";
import { retryWhen, delay, take } from 'rxjs/operators'; import { retryWhen, delay, take } from 'rxjs/operators';
import { PostForm as PostFormI, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse, ListCommunitiesForm, SortType, SearchForm, SearchType, SearchResponse } from '../interfaces'; import { PostForm as PostFormI, PostFormParams, Post, PostResponse, UserOperation, Community, ListCommunitiesResponse, ListCommunitiesForm, SortType, SearchForm, SearchType, SearchResponse } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { msgOp, getPageTitle, debounce, validURL, capitalizeFirstLetter } from '../utils'; import { msgOp, getPageTitle, debounce, validURL, capitalizeFirstLetter } from '../utils';
import * as autosize from 'autosize'; import * as autosize from 'autosize';
@ -11,7 +11,7 @@ import { T } from 'inferno-i18next';
interface PostFormProps { interface PostFormProps {
post?: Post; // If a post is given, that means this is an edit post?: Post; // If a post is given, that means this is an edit
prevCommunityName?: string; params?: PostFormParams;
onCancel?(): any; onCancel?(): any;
onCreate?(id: number): any; onCreate?(id: number): any;
onEdit?(post: Post): any; onEdit?(post: Post): any;
@ -23,6 +23,7 @@ interface PostFormState {
loading: boolean; loading: boolean;
suggestedTitle: string; suggestedTitle: string;
suggestedPosts: Array<Post>; suggestedPosts: Array<Post>;
crossPosts: Array<Post>;
} }
export class PostForm extends Component<PostFormProps, PostFormState> { export class PostForm extends Component<PostFormProps, PostFormState> {
@ -40,6 +41,7 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
loading: false, loading: false,
suggestedTitle: undefined, suggestedTitle: undefined,
suggestedPosts: [], suggestedPosts: [],
crossPosts: [],
} }
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -60,6 +62,16 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
} }
} }
if (this.props.params) {
this.state.postForm.name = this.props.params.name;
if (this.props.params.url) {
this.state.postForm.url = this.props.params.url;
}
if (this.props.params.body) {
this.state.postForm.body = this.props.params.body;
}
}
this.subscription = WebSocketService.Instance.subject this.subscription = WebSocketService.Instance.subject
.pipe(retryWhen(errors => errors.pipe(delay(3000), take(10)))) .pipe(retryWhen(errors => errors.pipe(delay(3000), take(10))))
.subscribe( .subscribe(
@ -95,6 +107,12 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
{this.state.suggestedTitle && {this.state.suggestedTitle &&
<div class="mt-1 text-muted small font-weight-bold pointer" onClick={linkEvent(this, this.copySuggestedTitle)}><T i18nKey="copy_suggested_title" interpolation={{title: this.state.suggestedTitle}}>#</T></div> <div class="mt-1 text-muted small font-weight-bold pointer" onClick={linkEvent(this, this.copySuggestedTitle)}><T i18nKey="copy_suggested_title" interpolation={{title: this.state.suggestedTitle}}>#</T></div>
} }
{this.state.crossPosts.length > 0 &&
<>
<div class="my-1 text-muted small font-weight-bold"><T i18nKey="cross_posts">#</T></div>
<PostListings showCommunity posts={this.state.crossPosts} />
</>
}
</div> </div>
</div> </div>
<div class="form-group row"> <div class="form-group row">
@ -115,7 +133,6 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
<textarea value={this.state.postForm.body} onInput={linkEvent(this, this.handlePostBodyChange)} class="form-control" rows={4} maxLength={10000} /> <textarea value={this.state.postForm.body} onInput={linkEvent(this, this.handlePostBodyChange)} class="form-control" rows={4} maxLength={10000} />
</div> </div>
</div> </div>
{/* Cant change a community from an edit */}
{!this.props.post && {!this.props.post &&
<div class="form-group row"> <div class="form-group row">
<label class="col-sm-2 col-form-label"><T i18nKey="community">#</T></label> <label class="col-sm-2 col-form-label"><T i18nKey="community">#</T></label>
@ -170,13 +187,27 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
handlePostUrlChange(i: PostForm, event: any) { handlePostUrlChange(i: PostForm, event: any) {
i.state.postForm.url = event.target.value; i.state.postForm.url = event.target.value;
if (validURL(i.state.postForm.url)) { if (validURL(i.state.postForm.url)) {
let form: SearchForm = {
q: i.state.postForm.url,
type_: SearchType[SearchType.Url],
sort: SortType[SortType.TopAll],
page: 1,
limit: 6,
};
WebSocketService.Instance.search(form);
// Fetch the page title
getPageTitle(i.state.postForm.url).then(d => { getPageTitle(i.state.postForm.url).then(d => {
i.state.suggestedTitle = d; i.state.suggestedTitle = d;
i.setState(i.state); i.setState(i.state);
}); });
} else { } else {
i.state.suggestedTitle = undefined; i.state.suggestedTitle = undefined;
i.state.crossPosts = [];
} }
i.setState(i.state); i.setState(i.state);
} }
@ -231,8 +262,8 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
this.state.communities = res.communities; this.state.communities = res.communities;
if (this.props.post) { if (this.props.post) {
this.state.postForm.community_id = this.props.post.community_id; this.state.postForm.community_id = this.props.post.community_id;
} else if (this.props.prevCommunityName) { } else if (this.props.params && this.props.params.community) {
let foundCommunityId = res.communities.find(r => r.name == this.props.prevCommunityName).id; let foundCommunityId = res.communities.find(r => r.name == this.props.params.community).id;
this.state.postForm.community_id = foundCommunityId; this.state.postForm.community_id = foundCommunityId;
} else { } else {
this.state.postForm.community_id = res.communities[0].id; this.state.postForm.community_id = res.communities[0].id;
@ -248,7 +279,12 @@ export class PostForm extends Component<PostFormProps, PostFormState> {
this.props.onEdit(res.post); this.props.onEdit(res.post);
} else if (op == UserOperation.Search) { } else if (op == UserOperation.Search) {
let res: SearchResponse = msg; let res: SearchResponse = msg;
if (res.type_ == SearchType[SearchType.Posts]) {
this.state.suggestedPosts = res.posts; this.state.suggestedPosts = res.posts;
} else if (res.type_ == SearchType[SearchType.Url]) {
this.state.crossPosts = res.posts;
}
this.setState(this.state); this.setState(this.state);
} }
} }

View File

@ -150,6 +150,9 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
<li className="list-inline-item mr-2"> <li className="list-inline-item mr-2">
<span class="pointer" onClick={linkEvent(this, this.handleSavePostClick)}>{post.saved ? i18n.t('unsave') : i18n.t('save')}</span> <span class="pointer" onClick={linkEvent(this, this.handleSavePostClick)}>{post.saved ? i18n.t('unsave') : i18n.t('save')}</span>
</li> </li>
<li className="list-inline-item mr-2">
<Link className="text-muted" to={`/create_post${this.crossPostParams}`}><T i18nKey="cross_post">#</T></Link>
</li>
{this.myPost && {this.myPost &&
<> <>
<li className="list-inline-item"> <li className="list-inline-item">
@ -270,6 +273,17 @@ export class PostListing extends Component<PostListingProps, PostListingState> {
WebSocketService.Instance.savePost(form); WebSocketService.Instance.savePost(form);
} }
get crossPostParams(): string {
let params = `?name=${this.props.post.name}`;
if (this.props.post.url) {
params += `&url=${this.props.post.url}`;
}
if (this.props.post.body) {
params += `&body=${this.props.post.body}`;
}
return params;
}
handleModRemoveShow(i: PostListing) { handleModRemoveShow(i: PostListing) {
i.state.showRemoveDialog = true; i.state.showRemoveDialog = true;
i.setState(i.state); i.setState(i.state);

View File

@ -1,10 +1,11 @@
import { Component, linkEvent } from 'inferno'; import { Component, linkEvent } from 'inferno';
import { Subscription } from "rxjs"; import { Subscription } from "rxjs";
import { retryWhen, delay, take } from 'rxjs/operators'; import { retryWhen, delay, take } from 'rxjs/operators';
import { UserOperation, Community, Post as PostI, GetPostResponse, PostResponse, Comment, CommentForm as CommentFormI, CommentResponse, CommentSortType, CreatePostLikeResponse, CommunityUser, CommunityResponse, CommentNode as CommentNodeI, BanFromCommunityResponse, BanUserResponse, AddModToCommunityResponse, AddAdminResponse, UserView } from '../interfaces'; import { UserOperation, Community, Post as PostI, GetPostResponse, PostResponse, Comment, CommentForm as CommentFormI, CommentResponse, CommentSortType, CreatePostLikeResponse, CommunityUser, CommunityResponse, CommentNode as CommentNodeI, BanFromCommunityResponse, BanUserResponse, AddModToCommunityResponse, AddAdminResponse, UserView, SearchType, SortType, SearchForm, SearchResponse } from '../interfaces';
import { WebSocketService, UserService } from '../services'; import { WebSocketService, UserService } from '../services';
import { msgOp, hotRank } from '../utils'; import { msgOp, hotRank } from '../utils';
import { PostListing } from './post-listing'; import { PostListing } from './post-listing';
import { PostListings } from './post-listings';
import { Sidebar } from './sidebar'; import { Sidebar } from './sidebar';
import { CommentForm } from './comment-form'; import { CommentForm } from './comment-form';
import { CommentNodes } from './comment-nodes'; import { CommentNodes } from './comment-nodes';
@ -22,6 +23,7 @@ interface PostState {
scrolled?: boolean; scrolled?: boolean;
scrolled_comment_id?: number; scrolled_comment_id?: number;
loading: boolean; loading: boolean;
crossPosts: Array<PostI>;
} }
export class Post extends Component<any, PostState> { export class Post extends Component<any, PostState> {
@ -35,7 +37,8 @@ export class Post extends Component<any, PostState> {
moderators: [], moderators: [],
admins: [], admins: [],
scrolled: false, scrolled: false,
loading: true loading: true,
crossPosts: [],
} }
constructor(props: any, context: any) { constructor(props: any, context: any) {
@ -75,6 +78,19 @@ export class Post extends Component<any, PostState> {
this.state.scrolled = true; this.state.scrolled = true;
this.markScrolledAsRead(this.state.scrolled_comment_id); this.markScrolledAsRead(this.state.scrolled_comment_id);
} }
// Necessary if you are on a post and you click another post (same route)
if (_lastProps.location.pathname !== _lastProps.history.location.pathname) {
// Couldnt get a refresh working. This does for now.
location.reload();
// let currentId = this.props.match.params.id;
// WebSocketService.Instance.getPost(currentId);
// this.context.router.history.push('/sponsors');
// this.context.refresh();
// this.context.router.history.push(_lastProps.location.pathname);
}
} }
markScrolledAsRead(commentId: number) { markScrolledAsRead(commentId: number) {
@ -112,6 +128,12 @@ export class Post extends Component<any, PostState> {
moderators={this.state.moderators} moderators={this.state.moderators}
admins={this.state.admins} admins={this.state.admins}
/> />
{this.state.crossPosts.length > 0 &&
<>
<div class="my-1 text-muted small font-weight-bold"><T i18nKey="cross_posts">#</T></div>
<PostListings showCommunity posts={this.state.crossPosts} />
</>
}
<div className="mb-2" /> <div className="mb-2" />
<CommentForm postId={this.state.post.id} disabled={this.state.post.locked} /> <CommentForm postId={this.state.post.id} disabled={this.state.post.locked} />
{this.sortRadios()} {this.sortRadios()}
@ -249,13 +271,25 @@ export class Post extends Component<any, PostState> {
} else if (op == UserOperation.GetPost) { } else if (op == UserOperation.GetPost) {
let res: GetPostResponse = msg; let res: GetPostResponse = msg;
this.state.post = res.post; this.state.post = res.post;
this.state.post = res.post;
this.state.comments = res.comments; this.state.comments = res.comments;
this.state.community = res.community; this.state.community = res.community;
this.state.moderators = res.moderators; this.state.moderators = res.moderators;
this.state.admins = res.admins; this.state.admins = res.admins;
this.state.loading = false; this.state.loading = false;
document.title = `${this.state.post.name} - ${WebSocketService.Instance.site.name}`; document.title = `${this.state.post.name} - ${WebSocketService.Instance.site.name}`;
// Get cross-posts
if (this.state.post.url) {
let form: SearchForm = {
q: this.state.post.url,
type_: SearchType[SearchType.Url],
sort: SortType[SortType.TopAll],
page: 1,
limit: 6,
};
WebSocketService.Instance.search(form);
}
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.CreateComment) { } else if (op == UserOperation.CreateComment) {
let res: CommentResponse = msg; let res: CommentResponse = msg;
@ -332,6 +366,10 @@ export class Post extends Component<any, PostState> {
let res: AddAdminResponse = msg; let res: AddAdminResponse = msg;
this.state.admins = res.admins; this.state.admins = res.admins;
this.setState(this.state); this.setState(this.state);
} else if (op == UserOperation.Search) {
let res: SearchResponse = msg;
this.state.crossPosts = res.posts.filter(p => p.id != this.state.post.id);
this.setState(this.state);
} }
} }

View File

@ -29,6 +29,7 @@ export class Search extends Component<any, SearchState> {
page: 1, page: 1,
searchResponse: { searchResponse: {
op: null, op: null,
type_: null,
posts: [], posts: [],
comments: [], comments: [],
communities: [], communities: [],

View File

@ -121,7 +121,7 @@ export class Sidebar extends Component<SidebarProps, SidebarState> {
)} )}
</ul> </ul>
<Link class={`btn btn-sm btn-secondary btn-block mb-3 ${(community.deleted || community.removed) && 'no-click'}`} <Link class={`btn btn-sm btn-secondary btn-block mb-3 ${(community.deleted || community.removed) && 'no-click'}`}
to={`/create_post/c/${community.name}`}><T i18nKey="create_a_post">#</T></Link> to={`/create_post?community=${community.name}`}><T i18nKey="create_a_post">#</T></Link>
<div> <div>
{community.subscribed {community.subscribed
? <button class="btn btn-sm btn-secondary btn-block" onClick={linkEvent(community.id, this.handleUnsubscribe)}><T i18nKey="unsubscribe">#</T></button> ? <button class="btn btn-sm btn-secondary btn-block" onClick={linkEvent(community.id, this.handleUnsubscribe)}><T i18nKey="unsubscribe">#</T></button>

View File

@ -44,7 +44,6 @@ class Index extends Component<any, any> {
<Route path={`/home/type/:type/sort/:sort/page/:page`} component={Main} /> <Route path={`/home/type/:type/sort/:sort/page/:page`} component={Main} />
<Route exact path={`/`} component={Main} /> <Route exact path={`/`} component={Main} />
<Route path={`/login`} component={Login} /> <Route path={`/login`} component={Login} />
<Route path={`/create_post/c/:name`} component={CreatePost} />
<Route path={`/create_post`} component={CreatePost} /> <Route path={`/create_post`} component={CreatePost} />
<Route path={`/create_community`} component={CreateCommunity} /> <Route path={`/create_community`} component={CreateCommunity} />
<Route path={`/communities/page/:page`} component={Communities} /> <Route path={`/communities/page/:page`} component={Communities} />

View File

@ -15,7 +15,7 @@ export enum SortType {
} }
export enum SearchType { export enum SearchType {
All, Comments, Posts, Communities, Users All, Comments, Posts, Communities, Users, Url
} }
export interface User { export interface User {
@ -412,6 +412,13 @@ export interface PostForm {
auth: string; auth: string;
} }
export interface PostFormParams {
name: string;
url?: string;
body?: string;
community?: string;
}
export interface GetPostResponse { export interface GetPostResponse {
op: string; op: string;
post: Post; post: Post;
@ -551,6 +558,7 @@ export interface SearchForm {
export interface SearchResponse { export interface SearchResponse {
op: string; op: string;
type_: string;
posts?: Array<Post>; posts?: Array<Post>;
comments?: Array<Comment>; comments?: Array<Comment>;
communities: Array<Community>; communities: Array<Community>;

View File

@ -8,6 +8,8 @@ export const en = {
number_of_posts:'{{count}} Posts', number_of_posts:'{{count}} Posts',
posts: 'Posts', posts: 'Posts',
related_posts: 'These posts might be related', related_posts: 'These posts might be related',
cross_posts: 'This link has also been posted to:',
cross_post: 'cross-post',
comments: 'Comments', comments: 'Comments',
number_of_comments:'{{count}} Comments', number_of_comments:'{{count}} Comments',
remove_comment: 'Remove Comment', remove_comment: 'Remove Comment',