feature/logging #5

Merged
cameron merged 4 commits from feature/logging into master 2021-02-25 15:26:48 +00:00
2 changed files with 61 additions and 53 deletions
Showing only changes of commit 8b5ba9d48c - Show all commits

43
src/auth.rs Normal file
View File

@@ -0,0 +1,43 @@
use actix_web::web::{HttpResponse, Json};
use actix_web::{post, Responder};
use chrono::{Duration, Utc};
use jsonwebtoken::{encode, EncodingKey, Header};
use crate::data::LoginRequest;
use crate::data::{secret_key, Claims, CreateAccountRequest, Token};
use crate::database::{create_user, get_user, user_exists};
#[post("/register")]
async fn register(user: Json<CreateAccountRequest>) -> impl Responder {
if !user.username.is_empty() && user.password.len() > 5 && user.password == user.confirmation {
if user_exists(&user.username) {
HttpResponse::BadRequest()
} else if let Some(_user) = create_user(&user.username, &user.password) {
HttpResponse::Ok()
} else {
HttpResponse::InternalServerError()
}
} else {
HttpResponse::BadRequest()
}
}
#[post("/login")]
async fn login(creds: Json<LoginRequest>) -> impl Responder {
println!("Logging in: {}", creds.username);
if let Some(user) = get_user(&creds.username, &creds.password) {
let claims = Claims {
sub: user.id.to_string(),
exp: (Utc::now() + Duration::days(5)).timestamp(),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret_key().as_bytes()),
)
.unwrap();
HttpResponse::Ok().json(Token { token: &token })
} else {
HttpResponse::NotFound().finish()
}
}

View File

@@ -2,71 +2,36 @@
extern crate diesel; extern crate diesel;
extern crate rayon; extern crate rayon;
use crate::auth::login;
use futures::stream::StreamExt;
use std::fs::File; use std::fs::File;
use std::io::prelude::*; use std::io::prelude::*;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::{Arc};
use std::sync::mpsc::channel; use std::sync::mpsc::channel;
use std::sync::Arc;
use actix::{Actor, Addr}; use actix::{Actor, Addr};
use actix_files::NamedFile; use actix_files::NamedFile;
use actix_multipart as mp; use actix_multipart as mp;
use actix_web::{App, get, HttpServer, post, Responder, web};
use actix_web::web::{HttpRequest, HttpResponse, Json}; use actix_web::web::{HttpRequest, HttpResponse, Json};
use chrono::{Duration, Utc}; use actix_web::{get, post, web, App, HttpServer, Responder};
use futures::stream::StreamExt; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher};
use jsonwebtoken::{encode, EncodingKey, Header};
use notify::{DebouncedEvent, RecursiveMode, watcher, Watcher};
use rayon::prelude::*; use rayon::prelude::*;
use serde::Serialize; use serde::Serialize;
use data::{AddFavoriteRequest, LoginRequest, ThumbnailRequest}; use data::{AddFavoriteRequest, ThumbnailRequest};
use crate::data::{Claims, CreateAccountRequest, secret_key, Token}; use crate::data::Claims;
use crate::database::{add_favorite, create_user, get_favorites, get_user, user_exists}; use crate::database::{add_favorite, get_favorites};
use crate::files::{is_valid_path, list_files}; use crate::files::{is_valid_path, list_files};
use crate::video::*; use crate::video::*;
mod auth;
mod data; mod data;
mod database; mod database;
mod files; mod files;
mod video; mod video;
#[post("/register")]
async fn register(user: Json<CreateAccountRequest>) -> impl Responder {
if !user.username.is_empty() && user.password.len() > 5 && user.password == user.confirmation {
if user_exists(&user.username) {
HttpResponse::BadRequest()
} else if let Some(_user) = create_user(&user.username, &user.password) {
HttpResponse::Ok()
} else {
HttpResponse::InternalServerError()
}
} else {
HttpResponse::BadRequest()
}
}
#[post("/login")]
async fn login(creds: Json<LoginRequest>) -> impl Responder {
println!("Logging in: {}", creds.username);
if let Some(user) = get_user(&creds.username, &creds.password) {
let claims = Claims {
sub: user.id.to_string(),
exp: (Utc::now() + Duration::days(5)).timestamp(),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret_key().as_bytes()),
)
.unwrap();
HttpResponse::Ok().json(Token { token: &token })
} else {
HttpResponse::NotFound().finish()
}
}
#[post("/photos")] #[post("/photos")]
async fn list_photos(_claims: Claims, req: Json<ThumbnailRequest>) -> impl Responder { async fn list_photos(_claims: Claims, req: Json<ThumbnailRequest>) -> impl Responder {
println!("{}", req.path); println!("{}", req.path);
@@ -187,7 +152,8 @@ async fn generate_video(
let playlist = format!("tmp/{}.m3u8", filename); let playlist = format!("tmp/{}.m3u8", filename);
if let Some(path) = is_valid_path(&body.path) { if let Some(path) = is_valid_path(&body.path) {
if let Ok(child) = create_playlist(&path.to_str().unwrap(), &playlist) { if let Ok(child) = create_playlist(&path.to_str().unwrap(), &playlist) {
data.stream_manager.do_send(ProcessMessage(playlist.clone(), child)); data.stream_manager
.do_send(ProcessMessage(playlist.clone(), child));
} }
} else { } else {
return HttpResponse::BadRequest().finish(); return HttpResponse::BadRequest().finish();
@@ -291,7 +257,7 @@ fn create_thumbnails() {
.filter(|entry| { .filter(|entry| {
let path = entry.path(); let path = entry.path();
let relative_path = &path.strip_prefix(&images).unwrap(); let relative_path = &path.strip_prefix(&images).unwrap();
let thumb_path = Path::new(thumbnail_directory).join(relative_path); let thumb_path = Path::new(thumbnail_directory).join(dbg!(relative_path));
!thumb_path.exists() !thumb_path.exists()
}) })
.map(|entry| (image::open(entry.path()), entry.path().to_path_buf())) .map(|entry| (image::open(entry.path()), entry.path().to_path_buf()))
@@ -303,7 +269,7 @@ fn create_thumbnails() {
let thumb_path = Path::new(thumbnail_directory).join(relative_path); let thumb_path = Path::new(thumbnail_directory).join(relative_path);
std::fs::create_dir_all(&thumb_path.parent().unwrap()) std::fs::create_dir_all(&thumb_path.parent().unwrap())
.expect("There was an issue creating directory"); .expect("There was an issue creating directory");
println!("{:?}", thumb_path); println!("Saving thumbnail: {:?}", thumb_path);
image.save(thumb_path).expect("Failure saving thumbnail"); image.save(thumb_path).expect("Failure saving thumbnail");
}) })
.for_each(drop); .for_each(drop);
@@ -322,11 +288,10 @@ fn main() -> std::io::Result<()> {
.unwrap(); .unwrap();
loop { loop {
let ev = wrx.recv_timeout(std::time::Duration::from_secs(10)); let ev = wrx.recv();
if let Ok(event) = ev { if let Ok(event) = ev {
match event { match event {
DebouncedEvent::Create(_) => create_thumbnails(), DebouncedEvent::Create(_) | DebouncedEvent::Rename(_, _) => create_thumbnails(),
DebouncedEvent::Rename(_, _) => create_thumbnails(),
_ => continue, _ => continue,
}; };
} }