1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
//! ## model
//!
//! Any changes in these tables should be handled with care and usually
//! involve data migration, otherwise data might be lost.
//!
//! ### user
//! | tree | key | value |
//! |------------------|----------------------|------------------|
//! | default | "users_count" | N |
//! | "users" | `uid` | [`User`] |
//! | "usernames" | `username` | `uid` |
//! | "user_following" | `uid#uid` | `&[]` |
//! | "user_followers" | `uid#uid` | `&[]` |
//! | "user_stats" | `timestamp_uid_type` | N |
//! | "user_uploads" | `uid#img_id` | `image_hash.ext` |
//! | default | "imgs_count" | N |
//! | "home_pages" | `uid` | `u8` |
//! | "tan" | `ctype#id` | `&[]` |
//!
//! ### notification
//! | tree | key | value |
//! |-----------------|-----------------------|-------------------|
//! | default | "notifications_count" | N |
//! | "notifications" | `uid#nid#nt_type` | `id1#id2#is_read` |
//!
//! ### captcha
//!
//! | tree | key | value |
//! |-------------|--------------------|---------------|
//! | "captcha" | `timestamp_nanoid` | captcha_chars |
//!
//! ### solo
//! | tree | key | value |
//! |--------------------|---------------|------------------|
//! | default | "solos_count" | N |
//! | "solos" | `sid` | [`Solo`] |
//! | "user_solos" | `uid#sid` | `solo_type` |
//! | "user_solos_like" | `uid#sid` | `&[]` |
//! | "solo_users_like" | `sid#uid` | `&[]` |
//! | "solo_timeline" | `sid` | `uid#solo_type` |
//! | "hashtags" | `hashtag#sid` | `&[]` |
//!
//! ### session
//! | tree | key | value |
//! |------------|--------------------|-----------|
//! | "sessions" | `timestamp_nanoid` | [`Claim`] |
//!
//! ### site config
//! | tree | key | value |
//! |-----------|---------------|----------------|
//! | default | "site_config" | [`SiteConfig`] |
//!
//! ### inn
//! | tree | key | value |
//! |-----------------|---------------|---------------------|
//! | default | "inns_count" | N |
//! | "inns" | `iid` | [`Inn`] |
//! | "inn_names" | `inn_name` | `iid` |
//! | "topics" | `topic#iid` | `&[]` |
//! | "mod_inns" | `uid#iid` | `&[]` |
//! | "user_inns" | `uid#iid` | `&[]` |
//! | "inn_apply" | `iid#uid` | `&[]` |
//! | "inn_users" | `iid#uid` | `&[1/2/3/4/5/8/10]` |
//! | "inns_private" | `iid` | `&[]` |
//! | "drafts" | `uid` | [`FormPost`] |
//! | "inn_feeds" | `iid#feed_id` | `uid` |
//! | "inn_items" | `iid#item_id` | `&[]` |
//!
//! ### post
//! | tree | key | value |
//! |-------------------- |---------------------|----------------------|
//! | default | "posts_count" | N |
//! | "posts" | `pid` | [`Post`] |
//! | "inn_posts" | `iid#pid` | `&[]` |
//! | "user_posts" | `uid#pid` | `iid#inn_type` |
//! | "tags" | `tag#pid` | `&[]` |
//! | "post_upvotes" | `pid#uid` | `&[]` |
//! | "post_downvotes" | `pid#uid` | `&[]` |
//! | "post_timeline_idx" | `iid#pid` | `timestamp#inn_type` |
//! | "post_timeline" | `timestamp#iid#pid` | `inn_type` |
//! | "post_pageviews" | `pid` | N |
//! | "post_pins" | `iid#pid` | `&[]` |
//!
//! ### comment
//! | tree | key | value |
//! |-----------------------|----------------------|-------------|
//! | "post_comments_count" | `pid` | N |
//! | "post_comments" | `pid#cid` | [`Comment`] |
//! | "user_comments" | `uid#pid#cid` | `&[]` |
//! | "comment_upvotes" | `pid#cid#uid` | `&[]` |
//! | "comment_downvotes" | `pid#cid#uid` | `&[]` |
//!
//! ### rss
//! | tree | key | value |
//! |-----------------------|----------------------|-------------|
//! | default | "feeds_count" | N |
//! | default | "items_count" | N |
//! | "user_folders" | `uid#folder#feed_id` | `&[0/1]` |
//! | "feeds" | `feed_id` | [`Feed`] |
//! | "feed_errs" | `feed_id` | "error msg" |
//! | "feed_items" | `feed_id#item_id` | `timestamp` |
//! | "feed_links" | `feed_link` | `feed_id` |
//! | "item_links" | `item_link` | `item_id` |
//! | "items" | `item_id` | [`Item`] |
//! | "read" | `uid#item_id` | `&[]` |
//! | "star" | `uid#item_id` | `timestamp` |
//!
//! ### e2ee message
//! | tree | key | value |
//! |-----------------------|------------------|--------------------|
//! | default | "messages_count" | N |
//! | "messages" | `mid` | `#uid#uid#message` |
//! | "pub_keys" | `uid` | `pub_key` |
//! | "user_messages" | `uid#mid` | `&[]` |
pub(super) mod db_utils;
pub(super) mod feed;
pub(super) mod meta_handler;
pub(super) mod notification;
pub(super) mod tantivy;
pub(super) mod admin;
pub(super) mod inn;
pub(super) mod message;
pub(super) mod solo;
pub(super) mod upload;
pub(super) mod user;
mod fmt;
use self::db_utils::{
get_ids_by_prefix, get_one, incr_id, ivec_to_u32, u32_to_ivec, u8_slice_to_u32,
};
use self::fmt::md2html;
use self::tantivy::{ToDoc, FIELDS};
use self::user::Role;
use crate::{controller::meta_handler::into_response, error::AppError};
use ::tantivy::TantivyDocument;
use bincode::config::standard;
use bincode::{Decode, Encode};
use chrono::{Days, Utc};
use serde::{Deserialize, Serialize};
use sled::Db;
use std::fmt::Display;
use validator::Validate;
/// user
///
/// ### Permissions
/// | role | post/solo | creat inn | site admin |
/// |----------|:---------:|:---------:|:----------:|
/// | Banned | | | |
/// | Standard | ✅ | | |
/// | Senior | ✅ | ✅ | |
/// | Admin | ✅ | ✅ | ✅ |
#[derive(Default, Encode, Decode, Serialize, Debug)]
struct User {
uid: u32,
username: String,
password_hash: String,
recovery_hash: Option<String>,
created_at: i64,
role: u8,
url: String,
about: String,
}
impl User {
fn is_mod(db: &Db, uid: u32, iid: u32) -> Result<bool, AppError> {
let k = [&u32_to_ivec(uid), &u32_to_ivec(iid)].concat();
Ok(db.open_tree("mod_inns")?.contains_key(k)?)
}
fn is_admin(db: &Db, uid: u32) -> Result<bool, AppError> {
let user: User = get_one(db, "users", uid)?;
Ok(Role::from(user.role) == Role::Admin)
}
/// check if the user has unread notifications
fn has_unread(db: &Db, uid: u32) -> Result<bool, AppError> {
let prefix = u32_to_ivec(uid);
let iter = db.open_tree("notifications")?.scan_prefix(&prefix);
for i in iter {
let (_, v) = i?;
if v[8] == 0 {
return Ok(true);
}
}
let mod_inns = get_ids_by_prefix(db, "mod_inns", &prefix, None)?;
for i in mod_inns {
if db
.open_tree("inn_apply")?
.scan_prefix(u32_to_ivec(i))
.next()
.is_some()
{
return Ok(true);
}
}
Ok(false)
}
fn update_stats(db: &Db, uid: u32, stat_type: &str) -> Result<(), AppError> {
let expire = Utc::now()
.date_naive()
.checked_add_days(Days::new(3))
.unwrap()
.and_hms_opt(0, 0, 0)
.unwrap()
.and_utc()
.timestamp();
let key = format!("{expire:x}_{uid}_{stat_type}");
incr_id(&db.open_tree("user_stats")?, key)?;
Ok(())
}
}
#[derive(PartialEq, Clone, Copy)]
enum SoloType {
Public = 0,
Following = 10,
Private = 20,
}
impl From<u32> for SoloType {
fn from(value: u32) -> Self {
match value {
0 => SoloType::Public,
10 => SoloType::Following,
20 => SoloType::Private,
_ => SoloType::Private,
}
}
}
#[derive(Encode, Decode, Serialize, Debug)]
struct Solo {
sid: u32,
uid: u32,
solo_type: u32,
content: String,
hashtags: Vec<String>,
created_at: i64,
reply_to: Option<u32>,
replies: Vec<u32>,
}
impl ToDoc for Solo {
fn to_doc(&self, _id: Option<u32>) -> TantivyDocument {
let mut doc = TantivyDocument::default();
doc.add_text(FIELDS.id, format!("solo{}", self.sid));
doc.add_text(FIELDS.title, &self.content);
doc.add_u64(FIELDS.uid, self.uid as u64);
doc.add_text(FIELDS.ctype, "solo");
doc
}
}
#[derive(PartialEq, Clone, Copy)]
enum InnType {
Public = 0,
Apply = 5,
Private = 10,
Hidden = 20,
PrivateHidden = 30,
}
impl From<u8> for InnType {
fn from(value: u8) -> Self {
match value {
0 => InnType::Public,
5 => InnType::Apply,
10 => InnType::Private,
20 => InnType::Hidden,
30 => InnType::PrivateHidden,
_ => InnType::Hidden,
}
}
}
#[derive(Encode, Decode, Serialize, Debug)]
struct Inn {
iid: u32,
inn_name: String,
about: String,
description: String,
topics: Vec<String>,
inn_type: u8,
early_birds: u32,
created_at: i64,
limit_edit_seconds: u32,
}
impl Inn {
fn is_open_access(&self) -> bool {
InnType::from(self.inn_type) == InnType::Public
|| InnType::from(self.inn_type) == InnType::Apply
}
fn is_closed(&self) -> bool {
InnType::from(self.inn_type) == InnType::Hidden
|| InnType::from(self.inn_type) == InnType::PrivateHidden
}
}
#[derive(Encode, Decode, Serialize, PartialEq, PartialOrd, Debug, Clone)]
pub(super) enum PostStatus {
Normal,
LockedByUser,
HiddenByUser,
LockedByMod,
HiddenByMod,
}
impl Display for PostStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", self)
}
}
#[derive(Encode, Decode, Serialize, Debug)]
pub(super) enum PostContent {
Markdown(String),
FeedItemId(u32),
}
impl PostContent {
fn to_html(&self, db: &Db) -> Result<String, AppError> {
match self {
PostContent::Markdown(md) => Ok(md2html(md)),
PostContent::FeedItemId(id) => {
let item: Item = get_one(db, "items", *id)?;
let mut content = format!(
r#"
<article class="message is-info">
<div class="message-header">
<p>Info</p>
</div>
<div class="message-body">
This post is auto-generated from RSS feed <b>{}</b>. Source: <a href="{}">{}</a>
</div>
</article>
"#,
item.feed_title, item.link, item.title
);
content.push_str(&item.content);
Ok(content)
}
}
}
}
impl Display for PostContent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PostContent::Markdown(c) => write!(f, "{c}"),
PostContent::FeedItemId(id) => write!(f, "From item_id: {id}"),
}
}
}
#[derive(Encode, Decode, Serialize, Debug)]
struct Post {
pid: u32,
uid: u32,
iid: u32,
title: String,
tags: Vec<String>,
content: PostContent,
created_at: i64,
status: PostStatus,
}
impl ToDoc for Post {
fn to_doc(&self, _id: Option<u32>) -> TantivyDocument {
let mut doc = TantivyDocument::default();
doc.add_text(FIELDS.id, format!("post{}", self.pid));
doc.add_text(FIELDS.title, &self.title);
doc.add_u64(FIELDS.uid, self.uid as u64);
doc.add_text(FIELDS.content, &self.content);
doc.add_text(FIELDS.ctype, "post");
doc
}
}
/// Form data: `/inn/:iid/post/:pid` post create/edit page
#[derive(Debug, Default, Deserialize, Validate, Encode, Decode)]
pub(super) struct FormPost {
iid: u32,
#[validate(length(min = 1, max = 256))]
title: String,
#[validate(length(min = 1, max = 128))]
tags: String,
#[validate(length(min = 1, max = 65535))]
content: String,
is_draft: Option<bool>,
delete_draft: Option<bool>,
}
#[derive(Encode, Decode, Serialize, Debug)]
struct Comment {
cid: u32,
pid: u32,
uid: u32,
reply_to: Option<u32>,
content: String,
created_at: i64,
is_hidden: bool,
}
impl ToDoc for Comment {
fn to_doc(&self, _id: Option<u32>) -> TantivyDocument {
let mut doc = TantivyDocument::default();
doc.add_text(FIELDS.id, format!("comt{}/{}", self.pid, self.cid));
doc.add_text(FIELDS.title, &self.content);
doc.add_u64(FIELDS.uid, self.uid as u64);
doc.add_text(FIELDS.ctype, "comt");
doc
}
}
#[derive(Encode, Decode, Debug)]
struct Feed {
link: String,
title: String,
}
#[derive(Encode, Decode, Debug)]
struct Item {
link: String,
title: String,
feed_title: String,
updated: i64,
content: String,
}
impl ToDoc for Item {
fn to_doc(&self, id: Option<u32>) -> TantivyDocument {
let mut doc = TantivyDocument::default();
doc.add_text(FIELDS.id, format!("item{}", id.unwrap()));
doc.add_text(FIELDS.title, &self.title);
doc.add_text(FIELDS.content, &self.content);
doc.add_text(FIELDS.ctype, "item");
doc
}
}
/// Go to source code to see default value: [SiteConfig::default()]
#[derive(Serialize, Deserialize, Encode, Decode, Validate, Debug)]
pub(super) struct SiteConfig {
#[validate(length(max = 64))]
site_name: String,
// domain only used for inn feed
domain: String,
#[validate(length(max = 512))]
description: String,
read_only: bool,
#[validate(range(max = 32))]
inn_mod_max: usize,
#[validate(range(max = 256))]
title_max_length: usize,
#[validate(range(max = 65535))]
article_max_length: usize,
#[validate(range(max = 65535))]
comment_max_length: usize,
#[validate(range(max = 3600))]
solo_interval: i64,
#[validate(range(max = 3600))]
post_interval: i64,
#[validate(range(max = 3600))]
comment_interval: i64,
#[validate(range(max = 100))]
per_page: usize,
captcha_difficulty: String,
captcha_name: String,
home_page: u8,
spam_regex: Option<String>,
}
impl SiteConfig {
/// get [SiteConfig]
fn get(db: &Db) -> Result<SiteConfig, AppError> {
let site_config = &db.get("site_config")?.unwrap_or_default();
let (site_config, _): (SiteConfig, usize) =
bincode::decode_from_slice(site_config, standard()).unwrap_or_default();
Ok(site_config)
}
}
#[derive(Encode, Decode)]
struct Claim {
uid: u32,
username: String,
role: u8,
last_write: i64,
session_id: String,
}