Adding initial UI and Websocket server.

This commit is contained in:
Dessalines 2019-03-20 18:22:31 -07:00
parent 064d7f84b2
commit 816aa0b15f
28 changed files with 5803 additions and 11 deletions

3
API.md
View File

@ -147,13 +147,11 @@
}
```
## Actions
- These are all posts to a user's outbox.
- The server then creates a post to the necessary inbox of the recipient, or the followers.
- Whenever a user accesses the site, they do a get from their inbox.
### Comments
#### [Create](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-create)
```
{
@ -163,7 +161,6 @@
"object": comment_id, or post_id
}
```
#### [Delete](https://www.w3.org/TR/activitystreams-vocabulary/#dfn-delete)
```
{

View File

@ -33,8 +33,12 @@ We have a twitter alternative (mastodon), a facebook alternative (friendica), so
- [helpful diesel examples](http://siciarz.net/24-days-rust-diesel/)
- [Mastodan public key server example](https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/)
- [Recursive query for adjacency list for nested comments](https://stackoverflow.com/questions/192220/what-is-the-most-efficient-elegant-way-to-parse-a-flat-table-into-a-tree/192462#192462)
- https://github.com/sparksuite/simplemde-markdown-editor
- [Sticky Sidebar](https://stackoverflow.com/questions/38382043/how-to-use-css-position-sticky-to-keep-a-sidebar-visible-with-bootstrap-4/49111934)
## TODOs
- Endpoints
- DB
- Followers / following

1450
server/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -11,3 +11,10 @@ activitypub = "0.1.4"
chrono = { version = "0.4", features = ["serde"] }
failure = "0.1.5"
serde_json = "*"
serde = { version = "1.0", features = ["derive"] }
actix = "*"
actix-web = "*"
env_logger = "*"
rand = "0.6.5"
strum = "0.14.0"
strum_macros = "0.14.0"

View File

@ -4,6 +4,13 @@ use diesel::*;
use diesel::result::Error;
use {Crud, Likeable};
// WITH RECURSIVE MyTree AS (
// SELECT * FROM comment WHERE parent_id IS NULL
// UNION ALL
// SELECT m.* FROM comment AS m JOIN MyTree AS t ON m.parent_id = t.id
// )
// SELECT * FROM MyTree;
#[derive(Queryable, Identifiable, PartialEq, Debug)]
#[table_name="comment"]
pub struct Comment {

270
server/src/bin/main.rs Normal file
View File

@ -0,0 +1,270 @@
extern crate server;
use std::time::{Instant, Duration};
use server::actix::*;
use server::actix_web::server::HttpServer;
use server::actix_web::{fs, http, ws, App, Error, HttpRequest, HttpResponse};
/// How often heartbeat pings are sent
const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
/// How long before lack of client response causes a timeout
const CLIENT_TIMEOUT: Duration = Duration::from_secs(10);
use server::websocket_server::server::*;
use std::str::FromStr;
// use server::websocket_server::server::UserOperation::from_str;
/// This is our websocket route state, this state is shared with all route
/// instances via `HttpContext::state()`
struct WsChatSessionState {
addr: Addr<ChatServer>,
}
/// Entry point for our route
fn chat_route(req: &HttpRequest<WsChatSessionState>) -> Result<HttpResponse, Error> {
ws::start(
req,
WSSession {
id: 0,
hb: Instant::now()
},
)
}
struct WSSession {
/// unique session id
id: usize,
/// Client must send ping at least once per 10 seconds (CLIENT_TIMEOUT),
/// otherwise we drop connection.
hb: Instant
}
impl Actor for WSSession {
type Context = ws::WebsocketContext<Self, WsChatSessionState>;
/// Method is called on actor start.
/// We register ws session with ChatServer
fn started(&mut self, ctx: &mut Self::Context) {
// we'll start heartbeat process on session start.
self.hb(ctx);
// register self in chat server. `AsyncContext::wait` register
// future within context, but context waits until this future resolves
// before processing any other events.
// HttpContext::state() is instance of WsChatSessionState, state is shared
// across all routes within application
let addr = ctx.address();
ctx.state()
.addr
.send(Connect {
addr: addr.recipient(),
})
.into_actor(self)
.then(|res, act, ctx| {
match res {
Ok(res) => act.id = res,
// something is wrong with chat server
_ => ctx.stop(),
}
fut::ok(())
})
.wait(ctx);
}
fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
// notify chat server
ctx.state().addr.do_send(Disconnect { id: self.id });
Running::Stop
}
}
/// Handle messages from chat server, we simply send it to peer websocket
impl Handler<WSMessage> for WSSession {
type Result = ();
fn handle(&mut self, msg: WSMessage, ctx: &mut Self::Context) {
ctx.text(msg.0);
}
}
use server::serde_json::Value;
/// WebSocket message handler
impl StreamHandler<ws::Message, ws::ProtocolError> for WSSession {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
// println!("WEBSOCKET MESSAGE: {:?}", msg);
match msg {
ws::Message::Ping(msg) => {
self.hb = Instant::now();
ctx.pong(&msg);
}
ws::Message::Pong(_) => {
self.hb = Instant::now();
}
ws::Message::Text(text) => {
let m = text.trim();
let json: Value = serde_json::from_str(m).unwrap();
// Get the OP command, and its data
let op: &str = &json["op"].as_str().unwrap();
let data: &Value = &json["data"];
let user_operation: UserOperation = UserOperation::from_str(op).unwrap();
match user_operation {
UserOperation::Login => {
let login: Login = serde_json::from_str(&data.to_string()).unwrap();
ctx.state()
.addr
.do_send(login);
},
UserOperation::Register => {
let register: Register = serde_json::from_str(&data.to_string()).unwrap();
ctx.state()
.addr
.send(register)
.into_actor(self)
.then(|res, _, ctx| {
match res {
Ok(wut) => ctx.text(wut),
_ => println!("Something is wrong"),
}
fut::ok(())
})
.wait(ctx)
}
_ => ctx.text(format!("!!! unknown command: {:?}", m)),
}
// we check for /sss type of messages
// if m.starts_with('/') {
// let v: Vec<&str> = m.splitn(2, ' ').collect();
// match v[0] {
// "/list" => {
// // Send ListRooms message to chat server and wait for
// // response
// println!("List rooms");
// ctx.state()
// .addr
// .send(ListRooms)
// .into_actor(self)
// .then(|res, _, ctx| {
// match res {
// Ok(rooms) => {
// for room in rooms {
// ctx.text(room);
// }
// }
// _ => println!("Something is wrong"),
// }
// fut::ok(())
// })
// .wait(ctx)
// .wait(ctx) pauses all events in context,
// so actor wont receive any new messages until it get list
// of rooms back
// }
// "/join" => {
// if v.len() == 2 {
// self.room = v[1].to_owned();
// ctx.state().addr.do_send(Join {
// id: self.id,
// name: self.room.clone(),
// });
// ctx.text("joined");
// } else {
// ctx.text("!!! room name is required");
// }
// }
// "/name" => {
// if v.len() == 2 {
// self.name = Some(v[1].to_owned());
// } else {
// ctx.text("!!! name is required");
// }
// }
// _ => ctx.text(format!("!!! unknown command: {:?}", m)),
// }
// } else {
// let msg = if let Some(ref name) = self.name {
// format!("{}: {}", name, m)
// } else {
// m.to_owned()
// };
// send message to chat server
// ctx.state().addr.do_send(ClientMessage {
// id: self.id,
// msg: msg,
// room: self.room.clone(),
// })
// }
}
ws::Message::Binary(_bin) => println!("Unexpected binary"),
ws::Message::Close(_) => {
ctx.stop();
},
}
}
}
impl WSSession {
/// helper method that sends ping to client every second.
///
/// also this method checks heartbeats from client
fn hb(&self, ctx: &mut ws::WebsocketContext<Self, WsChatSessionState>) {
ctx.run_interval(HEARTBEAT_INTERVAL, |act, ctx| {
// check client heartbeats
if Instant::now().duration_since(act.hb) > CLIENT_TIMEOUT {
// heartbeat timed out
println!("Websocket Client heartbeat failed, disconnecting!");
// notify chat server
ctx.state()
.addr
.do_send(Disconnect { id: act.id });
// stop actor
ctx.stop();
// don't try to send a ping
return;
}
ctx.ping("");
});
}
}
fn main() {
let _ = env_logger::init();
let sys = actix::System::new("rust-reddit-fediverse-server");
// Start chat server actor in separate thread
let server = Arbiter::start(|_| ChatServer::default());
// Create Http server with websocket support
HttpServer::new(move || {
// Websocket sessions state
let state = WsChatSessionState {
addr: server.clone(),
};
App::with_state(state)
// redirect to websocket.html
// .resource("/", |r| r.method(http::Method::GET).f(|_| {
// HttpResponse::Found()
// .header("LOCATION", "/static/websocket.html")
// .finish()
// }))
// // websocket
.resource("/service/ws", |r| r.route().f(chat_route))
// static resources
// .handler("/static/", fs::StaticFiles::new("static/").unwrap())
}).bind("127.0.0.1:8080")
.unwrap()
.start();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}

View File

@ -1,7 +1,19 @@
#[macro_use]
extern crate diesel;
extern crate dotenv;
extern crate chrono;
pub extern crate diesel;
pub extern crate dotenv;
pub extern crate chrono;
pub extern crate serde;
pub extern crate serde_json;
pub extern crate actix;
pub extern crate actix_web;
pub extern crate rand;
pub extern crate strum;
#[macro_use] pub extern crate strum_macros;
pub mod schema;
pub mod apub;
pub mod actions;
pub mod websocket_server;
use diesel::*;
use diesel::pg::PgConnection;
@ -9,11 +21,7 @@ use diesel::result::Error;
use dotenv::dotenv;
use std::env;
pub mod schema;
pub mod apub;
pub mod actions;
// pub trait Likeable;
pub trait Crud<T> {
fn create(conn: &PgConnection, form: T) -> Result<Self, Error> where Self: Sized;
fn read(conn: &PgConnection, id: i32) -> Self;

View File

@ -0,0 +1 @@
pub mod server;

View File

@ -0,0 +1,269 @@
//! `ChatServer` is an actor. It maintains list of connection client session.
//! And manages available rooms. Peers send messages to other peers in same
//! room through `ChatServer`.
use actix::prelude::*;
use rand::{rngs::ThreadRng, Rng};
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use {Crud,establish_connection};
#[derive(EnumString,ToString,Debug)]
pub enum UserOperation {
Login, Register, Logout, Join, Edit, Reply, Vote, Delete, NextPage, Sticky
}
pub enum MessageType {
Comments, Users, Ping, Pong
}
/// Chat server sends this messages to session
#[derive(Message)]
pub struct WSMessage(pub String);
/// Message for chat server communications
/// New chat session is created
#[derive(Message)]
#[rtype(usize)]
pub struct Connect {
pub addr: Recipient<WSMessage>,
}
/// Session is disconnected
#[derive(Message)]
pub struct Disconnect {
pub id: usize,
}
/// Send message to specific room
#[derive(Message)]
pub struct ClientMessage {
/// Id of the client session
pub id: usize,
/// Peer message
pub msg: String,
/// Room name
pub room: String,
}
/// List of available rooms
pub struct ListRooms;
impl actix::Message for ListRooms {
type Result = Vec<String>;
}
/// Join room, if room does not exists create new one.
#[derive(Message)]
pub struct Join {
/// Client id
pub id: usize,
/// Room name
pub name: String,
}
#[derive(Message)]
#[derive(Serialize, Deserialize)]
pub struct Login {
pub username: String,
pub password: String
}
// #[derive(Message)]
#[derive(Serialize, Deserialize)]
pub struct Register {
username: String,
email: Option<String>,
password: String,
password_verify: String
}
impl actix::Message for Register {
type Result = String;
}
/// `ChatServer` manages chat rooms and responsible for coordinating chat
/// session. implementation is super primitive
pub struct ChatServer {
sessions: HashMap<usize, Recipient<WSMessage>>, // A map from generated random ID to session addr
rooms: HashMap<String, HashSet<usize>>, // A map from room name to set of connectionIDs
rng: ThreadRng,
}
impl Default for ChatServer {
fn default() -> ChatServer {
// default room
let mut rooms = HashMap::new();
rooms.insert("Main".to_owned(), HashSet::new());
ChatServer {
sessions: HashMap::new(),
rooms: rooms,
rng: rand::thread_rng(),
}
}
}
impl ChatServer {
/// Send message to all users in the room
fn send_room_message(&self, room: &str, message: &str, skip_id: usize) {
if let Some(sessions) = self.rooms.get(room) {
for id in sessions {
if *id != skip_id {
if let Some(addr) = self.sessions.get(id) {
let _ = addr.do_send(WSMessage(message.to_owned()));
}
}
}
}
}
}
/// Make actor from `ChatServer`
impl Actor for ChatServer {
/// We are going to use simple Context, we just need ability to communicate
/// with other actors.
type Context = Context<Self>;
}
/// Handler for Connect message.
///
/// Register new session and assign unique id to this session
impl Handler<Connect> for ChatServer {
type Result = usize;
fn handle(&mut self, msg: Connect, _: &mut Context<Self>) -> Self::Result {
println!("Someone joined");
// notify all users in same room
self.send_room_message(&"Main".to_owned(), "Someone joined", 0);
// register session with random id
let id = self.rng.gen::<usize>();
self.sessions.insert(id, msg.addr);
// auto join session to Main room
self.rooms.get_mut(&"Main".to_owned()).unwrap().insert(id);
// send id back
id
}
}
/// Handler for Disconnect message.
impl Handler<Disconnect> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Disconnect, _: &mut Context<Self>) {
println!("Someone disconnected");
let mut rooms: Vec<String> = Vec::new();
// remove address
if self.sessions.remove(&msg.id).is_some() {
// remove session from all rooms
for (name, sessions) in &mut self.rooms {
if sessions.remove(&msg.id) {
rooms.push(name.to_owned());
}
}
}
// send message to other users
for room in rooms {
self.send_room_message(&room, "Someone disconnected", 0);
}
}
}
/// Handler for Message message.
impl Handler<ClientMessage> for ChatServer {
type Result = ();
fn handle(&mut self, msg: ClientMessage, _: &mut Context<Self>) {
self.send_room_message(&msg.room, msg.msg.as_str(), msg.id);
}
}
/// Handler for `ListRooms` message.
impl Handler<ListRooms> for ChatServer {
type Result = MessageResult<ListRooms>;
fn handle(&mut self, _: ListRooms, _: &mut Context<Self>) -> Self::Result {
let mut rooms = Vec::new();
for key in self.rooms.keys() {
rooms.push(key.to_owned())
}
MessageResult(rooms)
}
}
/// Join room, send disconnect message to old room
/// send join message to new room
impl Handler<Join> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Join, _: &mut Context<Self>) {
let Join { id, name } = msg;
let mut rooms = Vec::new();
// remove session from all rooms
for (n, sessions) in &mut self.rooms {
if sessions.remove(&id) {
rooms.push(n.to_owned());
}
}
// send message to other users
for room in rooms {
self.send_room_message(&room, "Someone disconnected", 0);
}
if self.rooms.get_mut(&name).is_none() {
self.rooms.insert(name.clone(), HashSet::new());
}
self.send_room_message(&name, "Someone connected", id);
self.rooms.get_mut(&name).unwrap().insert(id);
}
}
impl Handler<Login> for ChatServer {
type Result = ();
fn handle(&mut self, msg: Login, _: &mut Context<Self>) {
println!("{}", msg.password);
}
}
impl Handler<Register> for ChatServer {
type Result = MessageResult<Register>;
fn handle(&mut self, msg: Register, _: &mut Context<Self>) -> Self::Result {
use actions::user::*;
let conn = establish_connection();
// TODO figure out how to return values, and throw errors
// Register the new user
let user_form = UserForm {
name: &msg.username,
email: msg.email.as_ref().map(|x| &**x),
password_encrypted: &msg.password,
preferred_username: None,
updated: None
};
let inserted_user = User_::create(&conn, user_form).unwrap();
// Return the jwt
MessageResult("hi".to_string())
}
}

30
ui/.gitignore vendored Normal file
View File

@ -0,0 +1,30 @@
dist
.fusebox
_site
.alm
.history
.git
build
.build
.git
.history
.idea
.jshintrc
.nyc_output
.sass-cache
.vscode
build
coverage
jsconfig.json
Gemfile.lock
node_modules
.DS_Store
*.map
*.log
*.swp
*~
test/data/result.json
package-lock.json
*.orig

BIN
ui/assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

55
ui/fuse.js Normal file
View File

@ -0,0 +1,55 @@
const {
FuseBox,
Sparky,
EnvPlugin,
CSSPlugin,
WebIndexPlugin,
QuantumPlugin
} = require('fuse-box');
// const transformInferno = require('../../dist').default
const transformInferno = require('ts-transform-inferno').default;
const transformClasscat = require('ts-transform-classcat').default;
let fuse, app;
let isProduction = false;
Sparky.task('config', _ => {
fuse = new FuseBox({
homeDir: 'src',
hash: isProduction,
output: 'dist/$name.js',
experimentalFeatures: true,
cache: !isProduction,
sourceMaps: !isProduction,
transformers: {
before: [transformClasscat(), transformInferno()],
},
plugins: [
EnvPlugin({ NODE_ENV: isProduction ? 'production' : 'development' }),
CSSPlugin(),
WebIndexPlugin({
title: 'Inferno Typescript FuseBox Example',
template: 'src/index.html',
path: isProduction ? "/static" : "/"
}),
isProduction &&
QuantumPlugin({
bakeApiIntoBundle: 'app',
treeshake: true,
uglify: true,
}),
],
});
app = fuse.bundle('app').instructions('>index.tsx');
});
Sparky.task('clean', _ => Sparky.src('dist/').clean('dist/'));
Sparky.task('env', _ => (isProduction = true));
Sparky.task('copy-assets', () => Sparky.src('assets/*.ico').dest('dist/'));
Sparky.task('dev', ['clean', 'config', 'copy-assets'], _ => {
fuse.dev();
app.hmr().watch();
return fuse.run();
});
Sparky.task('prod', ['clean', 'env', 'config', 'copy-assets'], _ => {
// fuse.dev({ reload: true }); // remove after demo
return fuse.run();
});

31
ui/package.json Normal file
View File

@ -0,0 +1,31 @@
{
"name": "rust_reddit_fediverse",
"version": "1.0.0",
"description": "A simple UI for rust_reddit_fediverse",
"main": "index.js",
"scripts": {
"start": "node fuse dev",
"build": "node fuse prod"
},
"keywords": [],
"author": "Dessalines",
"license": "GPL-2.0-or-later",
"engines": {
"node": ">=8.9.0"
},
"engineStrict": true,
"dependencies": {
"classcat": "^1.1.3",
"dotenv": "^6.1.0",
"inferno": "^7.0.1",
"inferno-router": "^7.0.1",
"moment": "^2.22.2"
},
"devDependencies": {
"fuse-box": "3.1.3",
"ts-transform-classcat": "^0.0.2",
"ts-transform-inferno": "^4.0.2",
"typescript": "^3.3.3333",
"uglify-es": "^3.3.9"
}
}

View File

@ -0,0 +1,14 @@
import { Component } from 'inferno';
import { repoUrl } from '../utils';
export class Home extends Component<any, any> {
render() {
return (
<div class="container">
hola this is me.
</div>
)
}
}

145
ui/src/components/login.tsx Normal file
View File

@ -0,0 +1,145 @@
import { Component, linkEvent } from 'inferno';
import { LoginForm, RegisterForm } from '../interfaces';
import { WebSocketService } from '../services';
interface State {
loginForm: LoginForm;
registerForm: RegisterForm;
}
let emptyState: State = {
loginForm: {
username: null,
password: null
},
registerForm: {
username: null,
password: null,
password_verify: null
}
}
export class Login extends Component<any, State> {
constructor(props, context) {
super(props, context);
this.state = emptyState;
}
render() {
return (
<div class="container">
<div class="row">
<div class="col-12 col-lg-6 mb-4">
{this.loginForm()}
</div>
<div class="col-12 col-lg-6">
{this.registerForm()}
</div>
</div>
</div>
)
}
loginForm() {
return (
<div>
<form onSubmit={linkEvent(this, this.handleLoginSubmit)}>
<h3>Login</h3>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Email or Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" value={this.state.loginForm.username} onInput={linkEvent(this, this.handleLoginUsernameChange)} required minLength={3} />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" value={this.state.loginForm.password} onInput={linkEvent(this, this.handleLoginPasswordChange)} class="form-control" required />
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-secondary">Login</button>
</div>
</div>
</form>
Forgot your password or deleted your account? Reset your password. TODO
</div>
);
}
registerForm() {
return (
<form onSubmit={linkEvent(this, this.handleRegisterSubmit)}>
<h3>Sign Up</h3>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" value={this.state.registerForm.username} onInput={linkEvent(this, this.handleRegisterUsernameChange)} required minLength={3} />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" value={this.state.registerForm.email} onInput={linkEvent(this, this.handleRegisterEmailChange)} minLength={3} />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" value={this.state.registerForm.password} onInput={linkEvent(this, this.handleRegisterPasswordChange)} class="form-control" required />
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Verify Password</label>
<div class="col-sm-10">
<input type="password" value={this.state.registerForm.password_verify} onInput={linkEvent(this, this.handleRegisterPasswordVerifyChange)} class="form-control" required />
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-secondary">Sign Up</button>
</div>
</div>
</form>
);
}
handleLoginSubmit(i: Login, event) {
console.log(i.state);
event.preventDefault();
WebSocketService.Instance.login(i.state.loginForm);
}
handleLoginUsernameChange(i: Login, event) {
i.state.loginForm.username = event.target.value;
}
handleLoginPasswordChange(i: Login, event) {
i.state.loginForm.password = event.target.value;
}
handleRegisterSubmit(i: Login, event) {
console.log(i.state);
event.preventDefault();
WebSocketService.Instance.register(i.state.registerForm);
}
handleRegisterUsernameChange(i: Login, event) {
i.state.registerForm.username = event.target.value;
}
handleRegisterEmailChange(i: Login, event) {
i.state.registerForm.email = event.target.value;
}
handleRegisterPasswordChange(i: Login, event) {
i.state.registerForm.password = event.target.value;
}
handleRegisterPasswordVerifyChange(i: Login, event) {
i.state.registerForm.password_verify = event.target.value;
}
}

View File

@ -0,0 +1,38 @@
import { Component, linkEvent } from 'inferno';
import { Link } from 'inferno-router';
import { repoUrl } from '../utils';
export class Navbar extends Component<any, any> {
constructor(props, context) {
super(props, context);
}
render() {
return (
<div class="sticky-top">{this.navbar()}</div>
)
}
// TODO class active corresponding to current page
navbar() {
return (
<nav class="navbar navbar-light bg-light p-0 px-3 shadow">
<a class="navbar-brand mx-1" href="#">
rrf
</a>
<ul class="navbar-nav mr-auto">
<li class="nav-item">
<a class="nav-item nav-link" href={repoUrl}>github</a>
</li>
</ul>
<ul class="navbar-nav ml-auto mr-2">
<li class="nav-item">
<Link class="nav-item nav-link" to="/login">Login</Link>
</li>
</ul>
</nav>
);
}
}

View File

@ -0,0 +1,205 @@
import { Component, linkEvent } from 'inferno';
import * as moment from 'moment';
import { endpoint } from '../env';
import { SearchParams, Results, Torrent } from '../interfaces';
import { humanFileSize, magnetLink, getFileName } from '../utils';
interface State {
results: Results;
searchParams: SearchParams;
searching: Boolean;
}
export class Search extends Component<any, State> {
state: State = {
results: {
torrents: []
},
searchParams: {
q: "",
page: 1,
type_: 'torrent'
},
searching: false
};
constructor(props, context) {
super(props, context);
}
componentDidMount() {
this.state.searchParams = {
page: Number(this.props.match.params.page),
q: this.props.match.params.q,
type_: this.props.match.params.type_
}
this.search();
}
// Re-do search if the props have changed
componentDidUpdate(lastProps, lastState, snapshot) {
if (lastProps.match && lastProps.match.params !== this.props.match.params) {
this.state.searchParams = {
page: Number(this.props.match.params.page),
q: this.props.match.params.q,
type_: this.props.match.params.type_
}
this.search();
}
}
search() {
if (!!this.state.searchParams.q) {
this.setState({ searching: true, results: { torrents: [] } });
this.fetchData(this.state.searchParams)
.then(torrents => {
if (!!torrents) {
this.setState({
results: {
torrents: torrents
}
});
}
}).catch(error => {
console.error('request failed', error);
}).then(() => this.setState({ searching: false }));
} else {
this.setState({ results: { torrents: [] } });
}
}
fetchData(searchParams: SearchParams): Promise<Array<Torrent>> {
let q = encodeURI(searchParams.q);
return fetch(`${endpoint}/service/search?q=${q}&page=${searchParams.page}&type_=${searchParams.type_}`)
.then(data => data.json());
}
render() {
return (
<div>
{
this.state.searching ?
this.spinner() : this.state.results.torrents[0] ?
this.torrentsTable()
: this.noResults()
}
</div>
);
}
spinner() {
return (
<div class="text-center m-5 p-5">
<svg class="icon icon-spinner spinner"><use xlinkHref="#icon-spinner"></use></svg>
</div>
);
}
noResults() {
return (
<div class="text-center m-5 p-5">
<h1>No Results</h1>
</div>
)
}
torrentsTable() {
return (
<div>
<table class="table table-fixed table-hover table-sm table-striped table-hover-purple table-padding">
<thead>
<tr>
<th class="search-name-col">Name</th>
<th class="text-right">Size</th>
<th class="text-right">Seeds</th>
<th class="text-right d-none d-md-table-cell">Leeches</th>
<th class="text-right d-none d-md-table-cell">Created</th>
<th></th>
</tr>
</thead>
<tbody>
{this.state.results.torrents.map(torrent => (
<tr>
{ !torrent.name ? (
<td className="path_column">
<a class="text-body"
href={magnetLink(torrent.infohash, torrent.path, torrent.index_)}>
{getFileName(torrent.path)}
</a>
</td>
) : (
<td class="search-name-cell">
<a class="text-body"
href={magnetLink(torrent.infohash, torrent.name, torrent.index_)}>
{torrent.name}
</a>
</td>
)}
<td class="text-right text-muted">{humanFileSize(torrent.size_bytes, true)}</td>
<td class="text-right text-success">
<svg class="icon icon-arrow-up d-none d-sm-inline mr-1"><use xlinkHref="#icon-arrow-up"></use></svg>
{torrent.seeders}
</td>
<td class="text-right text-danger d-none d-md-table-cell">
<svg class="icon icon-arrow-down mr-1"><use xlinkHref="#icon-arrow-down"></use></svg>
{torrent.leechers}
</td>
<td class="text-right text-muted d-none d-md-table-cell"
data-balloon={`Scraped ${moment(torrent.scraped_date * 1000).fromNow()}`}
data-balloon-pos="down">
{moment(torrent.created_unix * 1000).fromNow()}
</td>
<td class="text-right">
<a class="btn btn-sm no-outline p-1"
href={magnetLink(torrent.infohash, (torrent.name) ? torrent.name : torrent.path, torrent.index_)}
data-balloon="Magnet link"
data-balloon-pos="left">
<svg class="icon icon-magnet"><use xlinkHref="#icon-magnet"></use></svg>
</a>
<a class="btn btn-sm no-outline p-1 d-none d-sm-inline"
href={`https://gitlab.com/dessalines/torrents.csv/issues/new?issue[title]=Report%20Torrent%20infohash%20${torrent.infohash}`}
target="_blank"
data-balloon="Report Torrent"
data-balloon-pos="left">
<svg class="icon icon-flag"><use xlinkHref="#icon-flag"></use></svg>
</a>
</td>
</tr>
))}
</tbody>
</table>
{this.paginator()}
</div>
);
}
paginator() {
return (
<nav>
<ul class="pagination justify-content-center">
<li className={(this.state.searchParams.page == 1) ? "page-item disabled" : "page-item"}>
<button class="page-link"
onClick={linkEvent({ i: this, nextPage: false }, this.switchPage)}>
Previous
</button>
</li>
<li class="page-item">
<button class="page-link"
onClick={linkEvent({ i: this, nextPage: true }, this.switchPage)}>
Next
</button>
</li>
</ul>
</nav>
);
}
switchPage(a: { i: Search, nextPage: boolean }, event) {
let newSearch = a.i.state.searchParams;
newSearch.page += (a.nextPage) ? 1 : -1;
a.i.props.history.push(`/search/${newSearch.type_}/${newSearch.q}/${newSearch.page}`);
}
}

3
ui/src/env.ts Normal file
View File

@ -0,0 +1,3 @@
// export const endpoint = window.location.origin;
export const endpoint = "http://localhost:8080";
export let wsUri = (window.location.protocol=='https:') ? 'wss://' : 'ws://' + endpoint.substr(7) + '/service/ws';

19
ui/src/index.html Normal file
View File

@ -0,0 +1,19 @@
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="shortcut icon" type="image/ico" href="/static/assets/favicon.ico" />
<title>rust-reddit-fediverse</title>
<link rel="stylesheet" href="https://bootswatch.com/4/darkly/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/balloon-css/0.5.0/balloon.min.css">
</head>
<body>
<div id="app"></div>
$bundles
</body>
</html>

42
ui/src/index.tsx Normal file
View File

@ -0,0 +1,42 @@
import { render, Component } from 'inferno';
import { HashRouter, Route, Switch } from 'inferno-router';
import { Navbar } from './components/navbar';
import { Home } from './components/home';
import { Login } from './components/login';
import './main.css';
import { WebSocketService } from './services';
const container = document.getElementById('app');
class Index extends Component<any, any> {
constructor(props, context) {
super(props, context);
WebSocketService.Instance;
}
render() {
return (
<HashRouter>
<Navbar />
<div class="mt-3 p-0">
<Switch>
<Route exact path="/" component={Home} />
<Route path={`/login`} component={Login} />
{/*
<Route path={`/search/:type_/:q/:page`} component={Search} />
<Route path={`/submit`} component={Submit} />
<Route path={`/user/:id`} component={Login} />
<Route path={`/community/:id`} component={Login} />
*/}
</Switch>
</div>
</HashRouter>
);
}
}
render(<Index />, container);

14
ui/src/interfaces.ts Normal file
View File

@ -0,0 +1,14 @@
export interface LoginForm {
username: string;
password: string;
}
export interface RegisterForm {
username: string;
email?: string;
password: string;
password_verify: string;
}
export enum UserOperation {
Login, Register
}

0
ui/src/main.css Normal file
View File

57
ui/src/services.ts Normal file
View File

@ -0,0 +1,57 @@
import { wsUri } from './env';
import { LoginForm, RegisterForm, UserOperation } from './interfaces';
export class WebSocketService {
private static _instance: WebSocketService;
private _ws;
private conn: WebSocket;
private constructor() {
console.log("Creating WSS");
this.connect();
console.log(wsUri);
}
public static get Instance(){
return this._instance || (this._instance = new this());
}
private connect() {
this.disconnect();
this.conn = new WebSocket(wsUri);
console.log('Connecting...');
this.conn.onopen = (() => {
console.log('Connected.');
});
this.conn.onmessage = (e => {
console.log('Received: ' + e.data);
});
this.conn.onclose = (() => {
console.log('Disconnected.');
this.conn = null;
});
}
private disconnect() {
if (this.conn != null) {
console.log('Disconnecting...');
this.conn.close();
this.conn = null;
}
}
public login(loginForm: LoginForm) {
this.conn.send(this.wsSendWrapper(UserOperation.Login, loginForm));
}
public register(registerForm: RegisterForm) {
this.conn.send(this.wsSendWrapper(UserOperation.Register, registerForm));
}
private wsSendWrapper(op: UserOperation, data: any): string {
let send = { op: UserOperation[op], data: data };
console.log(send);
return JSON.stringify(send);
}
}

2
ui/src/utils.ts Normal file
View File

@ -0,0 +1,2 @@
export let repoUrl = 'https://github.com/dessalines/rust-reddit-fediverse';
export let wsUri = (window.location.protocol=='https:'&&'wss://'||'ws://')+window.location.host + '/service/ws/';

12
ui/tsconfig.json Normal file
View File

@ -0,0 +1,12 @@
{
"compilerOptions": {
"module": "commonjs",
"target": "es2015",
"sourceMap": true,
"inlineSources": true,
"jsx": "preserve",
"importHelpers": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
}
}

28
ui/tslint.json Normal file
View File

@ -0,0 +1,28 @@
{
"extends": "tslint:recommended",
"rules": {
"forin": false,
"indent": [ true, "tabs" ],
"interface-name": false,
"ban-types": true,
"max-classes-per-file": true,
"max-line-length": false,
"member-access": true,
"member-ordering": false,
"no-bitwise": false,
"no-conditional-assignment": false,
"no-debugger": false,
"no-empty": true,
"no-namespace": false,
"no-unused-expression": true,
"object-literal-sort-keys": true,
"one-variable-per-declaration": [true, "ignore-for-loop"],
"only-arrow-functions": [false],
"ordered-imports": true,
"prefer-const": true,
"prefer-for-of": false,
"quotemark": [ true, "single", "jsx-double" ],
"trailing-comma": [true, {"multiline": "never", "singleline": "never"}],
"variable-name": false
}
}

3084
ui/yarn.lock Normal file

File diff suppressed because it is too large Load Diff