-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathblog.rs
1454 lines (1278 loc) · 55.4 KB
/
blog.rs
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::fmt::Display;
use std::time::Instant;
use rocket;
use ::rocket::Request;
use ::rocket::request::{FromRequest, FromForm, FormItems, FromFormValue, FromParam};
use ::rocket::outcome::Outcome;
use ::rocket::config::{Config, Environment};
use rocket::http::RawStr;
// use rocket::request::{FromFormValue, FromParam};
use titlecase::titlecase;
use regex::Regex;
use chrono::prelude::*;
use chrono::{NaiveDate, NaiveDateTime};
use htmlescape::*;
use postgres::{Connection};
use super::{BLOG_URL, MAX_CREATE_TITLE, MAX_CREATE_DESCRIPTION, MAX_CREATE_TAGS, DESC_LIMIT};
use rocket_auth_login::sanitization;
// not used anymore
// use users::*;
use data::*;
use sanitize::*;
use evmap::*;
// pub const DESC_LIMIT: usize = 300;
// type ArticleId = u32;
#[derive(Debug, Clone)]
pub struct ArticleId {
pub aid: u32,
}
// used for retrieving a GET url tag
#[derive(Debug, Clone)]
pub struct Tag {
pub tag: String,
}
#[derive(Debug, Clone)]
pub struct Article {
pub aid: u32,
pub title: String,
pub posted: NaiveDateTime,
pub modified: NaiveDateTime,
pub userid: u32,
pub username: String,
pub body: String,
pub tags: Vec<String>,
pub description: String,
pub markdown: String,
pub image: String,
// pub author_id: u32,
// pub author_name: String,
}
// AritlceSource contains the original markdown code if it was used to create the article body (html)
// #[derive(Debug, Clone)]
// pub struct ArticleSource {
// pub aid: u32,
// pub title: String,
// pub posted: NaiveDateTime,
// pub userid: u32,
// pub username: String,
// pub body: String,
// pub markdown: String,
// pub tags: Vec<String>,
// pub description: String,
// }
// #[derive(Debug, Clone, FromForm)]
// The /edit route is the only page module route this struct is used in
#[derive(Debug, Clone)]
pub struct ArticleWrapper {
pub aid: u32,
pub title: String,
pub posted: NaiveDateTimeWrapper,
pub modified: NaiveDateTimeWrapper,
pub userid: u32,
pub username: String,
pub body: String,
pub tags: String,
pub description: String,
pub markdown: String,
pub image: String,
// pub author_id: u32,
// pub author_name: String,
}
// #[derive(Debug, Clone, FromForm)]
// pub struct ArticleSourceWrapper {
// pub aid: u32,
// pub title: String,
// pub posted: NaiveDateTimeWrapper,
// pub userid: u32,
// pub username: String,
// pub body: String,
// pub markdown: String,
// pub tags: String,
// pub description: String,
// // pub author_id: u32,
// // pub author_name: String,
// }
#[derive(Debug, Clone, Serialize)]
pub struct ArticleDisplay {
pub aid: u32,
pub title: String,
pub posted_machine: String,
pub posted_human: String,
pub modified_machine: String,
pub modified_human: String,
pub userid: u32,
pub username: String,
pub body: String,
pub tags: Vec<String>,
pub description: String,
pub markdown: String,
pub image: String,
// pub author_id: u32,
// pub author_name: String,
}
// #[derive(Debug, Clone, Serialize)]
// pub struct ArticleSourceDisplay {
// pub aid: u32,
// pub title: String,
// pub posted_machine: String,
// pub posted_human: String,
// pub userid: u32,
// pub username: String,
// pub body: String,
// pub markdown: String,
// pub tags: Vec<String>,
// pub description: String,
// // pub author_id: u32,
// // pub author_name: String,
// }
// Used for creating a new article
#[derive(Debug, Clone)]
pub struct ArticleForm {
// pub userid: u32,
pub title: String,
pub body: String,
pub markdown: String,
pub tags: String,
pub description: String,
pub image: String,
}
#[derive(Debug, Clone)]
pub struct Search {
pub limit: Option<u16>, // use u16 as limit as u16 does not implement FromSql
pub o: Option<String>, // opposite / negated
pub p: Option<String>, // possible words, or'd
pub q: Option<String>, // query, and'd together
pub min: Option<NaiveDateTimeWrapper>, // min
pub max: Option<NaiveDateTimeWrapper>, // min
}
#[derive(Serialize)]
pub struct SearchDisplay {
pub limit: u16,
pub q: String,
pub min: String,
pub max: String,
}
#[derive(FromForm)]
pub struct ViewPage {
pub page: u32,
// Articles Per Page
pub app: Option<u8>,
}
pub struct ArticleSearch {
// pub min_date: NaiveDate,
// pub max_date: NaiveDate,
pub keywords: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct User {
pub userid: u32,
pub username: String,
pub display: Option<String>,
pub email: Option<String>,
pub password: String,
pub is_admin: bool,
pub is_public: bool,
}
#[derive(Debug, Clone)]
pub struct GenTimer (pub Instant);
#[derive(Debug, Clone)]
pub struct NaiveDateTimeWrapper(pub NaiveDateTime);
pub type Descending = bool;
#[derive(Debug, Clone, Serialize)]
pub enum Sort {
Title(Descending),
Date(Descending),
}
#[derive(Debug, Clone, Serialize)]
pub struct SortDisplay {
sort_title: bool,
sort_date: bool,
sort_desc: bool,
sort_asc: bool,
}
#[derive(Debug, Clone, )]
pub struct QueryUser {
pub user: String,
}
#[derive(Debug, Clone, )]
pub struct QueryUserRedir {
pub user: String,
pub referrer: String,
}
#[derive(Debug, Clone, )]
pub struct QueryRedir {
// pub user: String,
pub referrer: String,
}
impl<'f> FromForm<'f> for QueryUser {
type Error = &'static str;
fn from_form(form_items: &mut FormItems<'f>, _strict: bool) -> Result<Self, Self::Error> {
let mut user: String = String::new();
for (field, value) in form_items {
match field.as_str() {
"user" => { user = value.url_decode().unwrap_or( String::new() ); },
_ => {},
}
}
if &user != "" {
Ok( QueryUser {
user,
} )
} else {
println!("QueryRedir is not valid. user: {}", user);
Err( "There was a missing field in QueryUser" )
}
}
}
impl<'f> FromForm<'f> for QueryUserRedir {
type Error = &'static str;
fn from_form(form_items: &mut FormItems<'f>, _strict: bool) -> Result<Self, Self::Error> {
let mut user: String = String::new();
let mut referrer: String = String::new();
for (field, value) in form_items {
match field.as_str() {
"user" => { user = value.url_decode().unwrap_or( String::new() ); },
"referrer" | "redir" | "redirect" => { referrer = value.url_decode().unwrap_or( String::new() ); },
_ => {},
}
}
if &user != "" && &referrer != "" {
Ok( QueryUserRedir {
user,
referrer,
} )
} else {
println!("QueryRedir is not valid. user: {}, referrer: {}", user, referrer);
Err( "There was a missing field in QueryUserRedir" )
}
}
}
impl<'f> FromForm<'f> for QueryRedir {
type Error = &'static str;
fn from_form(form_items: &mut FormItems<'f>, _strict: bool) -> Result<Self, Self::Error> {
let mut referrer: String = String::new();
for (field, value) in form_items {
match field.as_str() {
"referrer" | "redir" | "redirect" => { referrer = value.url_decode().unwrap_or( String::new() ); },
_ => {},
}
}
if &referrer != "" {
Ok( QueryRedir {
referrer,
} )
} else {
println!("QueryRedir is not valid. referrer: {}", referrer);
Err( "There was a missing field in QueryRedir" )
}
}
}
pub fn now() -> NaiveDateTime {
Local::now().naive_local()
}
pub fn opt_col<T>(rst: Option<Result<T, T>>) -> T where T: Display + Default {
match rst {
Some(Ok(d)) => d,
Some(Err(e)) => { println!("Encountered an error retrieving the description. Error: {}", e); T::default() },
None => T::default(),
}
}
impl Sort {
pub fn to_display(&self) -> SortDisplay {
match self {
&Sort::Title(desc) if desc == true => SortDisplay { sort_title: true, sort_date: false, sort_desc: true, sort_asc: false },
&Sort::Title(desc) => SortDisplay { sort_title: true, sort_date: false, sort_desc: false, sort_asc: true },
&Sort::Date(desc) if desc == true => SortDisplay { sort_title: false, sort_date: true, sort_desc: true, sort_asc: false },
&Sort::Date(desc) => SortDisplay { sort_title: false, sort_date: true, sort_desc: false, sort_asc: true },
_ => SortDisplay { sort_title: true, sort_date: false, sort_desc: true, sort_asc: false },
}
}
}
impl SearchDisplay {
pub fn default() -> SearchDisplay {
SearchDisplay {
limit: 0,
q: String::new(),
min: String::new(),
max: String::new(),
}
}
}
impl Search {
pub fn to_query(&self) -> String {
let mut output: String = String::with_capacity(120);
let mut empty = true;
if let Some(ref q) = self.q {
if empty {
output.push_str("q=");
output.push_str(&q);
} else {
output.push_str("&q=");
output.push_str(&q);
empty = false;
}
}
if let Some(ref min) = self.min {
if empty {
output.push_str("min=");
output.push_str( &format!("{}", min.0.format("%Y-%m-%d %H:%M:%S")) );
} else {
output.push_str("&min=");
output.push_str( &format!("{}", min.0.format("%Y-%m-%d %H:%M:%S")) );
empty = false;
}
}
if let Some(ref max) = self.max {
if empty {
output.push_str("max=");
output.push_str( &format!("{}", max.0.format("%Y-%m-%d %H:%M:%S")) );
} else {
output.push_str("&max=");
output.push_str( &format!("{}", max.0.format("%Y-%m-%d %H:%M:%S")) );
empty = false;
}
}
output
}
pub fn to_display(&self) -> SearchDisplay {
SearchDisplay {
limit: if let Some(limit) = self.limit { limit } else { 0 },
q: if let Some(ref q) = self.q { q.to_string() } else { String::new() },
min: if let Some(ref min) = self.min { format!("{}", min.0.format("%Y-%m-%d %H:%M:%S")) } else { String::new() },
max: if let Some(ref max) = self.max { format!("{}", max.0.format("%Y-%m-%d %H:%M:%S")) } else { String::new() },
}
}
pub fn default() -> Search {
Search {
limit: None,
o: None,
p: None,
q: None,
min: None,
max: None,
}
}
}
impl ArticleWrapper {
pub fn to_article(self) -> Article {
// let tags: Vec<String> = self.tags.split(",").map(|t| ).collect();
Article {
aid: self.aid,
title: self.title,
posted: self.posted.0.clone(),
userid: self.userid,
username: self.username,
body: self.body,
tags: split_tags(self.tags),
description: self.description,
markdown: self.markdown,
image: self.image,
modified: self.posted.0,
}
}
pub fn is_valid(&self) -> bool {
self.aid != 0
&& &self.title != ""
&& self.userid != 0
// && ( &self.body != "" || &self.markdown != "" )
}
}
// impl ArticleSourceWrapper {
// pub fn to_article(self) -> ArticleSource {
// // let tags: Vec<String> = self.tags.split(",").map(|t| ).collect();
// ArticleSource {
// aid: self.aid,
// title: self.title,
// posted: self.posted.0,
// userid: self.userid,
// username: self.username,
// body: self.body,
// markdown: self.markdown,
// tags: split_tags(self.tags),
// description: self.description,
// }
// }
// }
// use rocket::request::FromRequest;
impl<'a, 'r> FromRequest<'a, 'r> for GenTimer {
type Error = ();
fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<GenTimer,Self::Error> {
Outcome::Success( GenTimer( Instant::now() ) )
}
}
// // use rocket::request::FromRequest;
// impl<'a, 'r> FromRequest<'a, 'r> for GenTimer {
// type Error = ();
// fn from_request(request: &'a Request<'r>) -> ::rocket::request::Outcome<GenTimer,Self::Error>{
// Outcome::Success( )
// match cookies.get_private(cid) {
// Some(cookie) => {
// if let Some(cookie_deserialized) = GenTimer::retrieve_cookie(cookie.value().to_string()) {
// Outcome::Success(
// cookie_deserialized
// )
// } else {
// Outcome::Forward(())
// }
// },
// None => Outcome::Forward(())
// }
// }
// }
impl ArticleId {
pub fn new(aid: u32) -> ArticleId {
ArticleId {
aid
}
}
pub fn exists(&self) -> bool {
unimplemented!()
}
// Retrieve with a new connection - not a pooled connection
// Do not use unless you have to - unless you have no db connection
pub fn retrieve(&self) -> Option<Article> {
let pgconn = establish_connection();
// let rawqry = pgconn.query(&format!("SELECT aid, title, posted, body, tag, description FROM articles WHERE aid = {id}", id=self.aid), &[]);
let rawqry = pgconn.query(&format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON (a.author = u.userid) WHERE a.aid = {id}", id=self.aid), &[]);
if let Ok(aqry) = rawqry {
// println!("Querying articles: found {} rows", aqry.len());
if !aqry.is_empty() && aqry.len() == 1 {
let row = aqry.get(0); // get first row
let display: Option<String> = row.get(7);
let username: String = if let Some(disp) = display { disp } else { row.get(8) };
// let username: String = row.get_opt(7).unwrap_or(Ok(row.get(8))).unwrap_or(row.get(8)).to_string();
// row.get_opt(7).unwrap_or(Ok(row.get(8))).unwrap_or(row.get(8));
let image: String = row.get_opt(9).unwrap_or(Ok(String::new())).unwrap_or(String::new());
Some( Article {
aid: row.get(0),
title: row.get(1), // todo: call sanitize title here
posted: row.get(2),
body: row.get(3), // Todo: call sanitize body here
tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim_matches('\'').trim().to_string()).filter(|s| s.as_str() != "").collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'')).filter(|s| *s != "").map(|s| s.to_string()).collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'').to_string()).collect(),
// description: opt_col(row.get_opt(5)),
description: row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
// author_id: row.get(6),
// author_name: row.get_opt(7).unwrap_or(Ok(row.get(8))).unwrap_or(String::new()),
userid: row.get(6),
username: titlecase( &sanitization::sanitize(&username) ),
markdown: row.get_opt(10).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
image,
modified: row.get(11),
})
} else { None }
} else { None }
}
// Prefer to use this over retrieve()
pub fn retrieve_with_conn(&self, pgconn: DbConn) -> Option<Article> {
// let rawqry = pgconn.query(&format!("SELECT aid, title, posted, body, tag, description FROM articles WHERE aid = {id}", id=self.aid), &[]);
// let rawqry = pgconn.query(&format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid))) WHERE a.aid = {id}", id=self.aid), &[]);
let qrystr = format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON (a.author = u.userid) WHERE a.aid = {id}", id=self.aid);
let rawqry = pgconn.query(&qrystr, &[]);
// println!("Running query:\n{}", qrystr);
if let Ok(aqry) = rawqry {
// userid 6
// display 7
// username 8
println!("Querying articles: found {} rows", aqry.len());
if !aqry.is_empty() && aqry.len() == 1 {
let row = aqry.get(0); // get first row
let display: Option<String> = row.get(7);
let username: String = if let Some(disp) = display { disp } else { row.get(8) };
let image: String = row.get_opt(9).unwrap_or(Ok(String::new())).unwrap_or(String::new());
Some( Article {
aid: row.get(0),
title: row.get(1), // todo: call sanitize title here
posted: row.get(2),
body: row.get(3), // Todo: call sanitize body here
tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim_matches('\'').trim().to_string()).filter(|s| s.as_str() != "").collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'')).filter(|s| *s != "").map(|s| s.to_string()).collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'').to_string()).collect(),
description: row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
userid: row.get(6),
username: titlecase( &sanitization::sanitize(&username) ),
markdown: row.get_opt(10).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
image,
modified: row.get(11),
// author_id: row.get(6),
// author_name: row.get_opt(7).unwrap_or(Ok(row.get(8))).unwrap_or(String::new()),
})
} else { None }
} else { None }
}
// use the description field to store the markdown and body to store the original body (html)
// pub fn retrieve_markdown(&self, pgconn: DbConn) -> Option<ArticleSource> {
// // let rawqry = pgconn.query(&format!("SELECT aid, title, posted, body, tag, description FROM articles WHERE aid = {id}", id=self.aid), &[]);
// // let rawqry = pgconn.query(&format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid))) WHERE a.aid = {id}", id=self.aid), &[]);
// let qrystr = format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, a.markdown, u.userid, u.display, u.username FROM articles a JOIN users u ON (a.author = u.userid) WHERE a.aid = {id}", id=self.aid);
// let rawqry = pgconn.query(&qrystr, &[]);
// println!("Running query:\n{}", qrystr);
// if let Ok(aqry) = rawqry {
// println!("Querying articles: found {} rows", aqry.len());
// if !aqry.is_empty() && aqry.len() == 1 {
// let row = aqry.get(0); // get first row
// let display: Option<String> = row.get(8);
// let md: String = row.get_opt(6).unwrap_or(Ok(String::new())).unwrap_or(String::new());
// let markdown: String = if &md == "" { row.get(3) } else { md };
// let username: String = if let Some(disp) = display { disp } else { row.get(8) };
// Some( ArticleSource {
// aid: row.get(0),
// title: row.get(1), // todo: call sanitize title here
// posted: row.get(2),
// body: row.get(3), // Todo: call sanitize body here
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'').to_string()).collect(),
// description: row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
// markdown,
// userid: row.get(7),
// username: titlecase( &sanitization::sanitize(&username) ),
// // author_id: row.get(6),
// // author_name: row.get_opt(7).unwrap_or(Ok(row.get(8))).unwrap_or(String::new()),
// })
// } else { None }
// } else { None }
// }
// Possible Functions:
// pub fn last_id() -> u32 {
// unimplemented!()
// }
// pub fn next_id() -> u32 {
// unimplemented!()
// }
}
impl Search {
pub fn search() -> Vec<Article> {
unimplemented!()
}
}
pub fn get_len<T>(input: &Option<Vec<T>>) -> usize {
if let &Some(ref inner) = input {
inner.len()
} else {
0
}
}
pub fn slash_quotes(text: &str) -> String {
// text.replace("\\", "").replace("'", "\\'").replace("\"", "\\\"")
text.replace("'", "''")
}
// impl ArticleSource {
// pub fn to_display(self) -> ArticleSourceDisplay {
// ArticleSourceDisplay {
// aid: self.aid,
// title: self.title,
// posted_machine: self.posted.format("%Y-%m-%dT%H:%M:%S").to_string(),
// posted_human: self.posted.format("%Y-%m-%d @ %I:%M%P").to_string(),
// body: self.body,
// markdown: self.markdown,
// tags: self.tags,
// description: self.description,
// userid: self.userid,
// username: self.username,
// // author_id: self.author_id,
// // author_name: self.author_name.clone(),
// }
// }
// pub fn to_article(self) -> Article {
// Article {
// aid: self.aid,
// title: self.title,
// posted: self.posted,
// userid: self.userid,
// username: self.username,
// body: self.body,
// tags: self.tags,
// description: self.description,
// // =====Update-image===== --maybe
// image: String::new(),
// }
// }
// pub fn save(&self, conn: DbConn) -> Result<String, String> {
// let vtags: Vec<String> = self.tags.clone();
// let tagstr = format!(
// "{{{}}}", vtags
// .iter()
// // .split(",")
// .map(
// |s| format!("\"{}\"", s.trim().to_lowercase())
// ).collect::<Vec<_>>()
// .join(",")
// // .replace(",''")
// );
// let qrystr = format!("
// UPDATE articles
// SET title = '{title}',
// body = '{body}',
// markdown = '{src}',
// tag = '{tag}',
// description = '{desc}'
// WHERE aid = {aid}
// ",
// // posted = '{posted}',
// title=slash_quotes(&self.title),
// // posted=slash_quotes(self.posted),
// body=slash_quotes(&self.body),
// src=slash_quotes(&self.markdown),
// tag=tagstr,
// desc=slash_quotes(&self.description),
// aid=self.aid
// );
// println!("Generated update query:\n{}", qrystr);
// if let Ok(num) = conn.execute(&qrystr, &[]) {
// if num == 1 {
// Ok(format!("Article {} successfully updated", self.aid))
// } else if num > 1 {
// println!("Update query updated too many rows.");
// Err("Multiple rows updated".to_string())
// } else {
// println!("Update query updated no rows.");
// Err(String::new())
// }
// } else {
// println!("Update query failed.");
// Err(String::new())
// }
// }
// pub fn info(&self) -> String {
// format!("Aid: {aid}, Title: {title}, Posted on: {posted}, Description:<br>\n{desc}<br>\nSource:<br>{src}\n<br>\nBody:<br>\n{body}<br>\ntags: {tags:#?}", aid=self.aid, title=self.title, posted=self.posted, src=self.markdown, body=self.body, tags=self.tags, desc=self.description)
// }
// }
impl Article {
pub fn to_display(&self) -> ArticleDisplay {
ArticleDisplay {
aid: self.aid.clone(),
title: self.title.clone(),
posted_machine: self.posted.format("%Y-%m-%dT%H:%M:%S").to_string(),
posted_human: self.posted.format("%Y-%m-%d @ %I:%M%P").to_string(),
body: self.body.clone().replace("{{base_url}}", BLOG_URL),
tags: self.tags.clone(),
description: self.description.clone(),
userid: self.userid,
username: self.username.clone(),
markdown: self.markdown.clone(),
image: self.image.clone(),
modified_machine: if &self.posted != &self.modified { self.modified.format("%Y-%m-%dT%H:%M:%S").to_string() } else { String::new() },
modified_human: if &self.posted != &self.modified { self.modified.format("%Y-%m-%d @ %I:%M%P").to_string() } else { String::new() },
// author_id: self.author_id,
// author_name: self.author_name.clone(),
}
}
pub fn split_tags(string: String) -> Vec<String> {
// Todo: call sanitize tags before splitting:
let tags: Vec<String> = string.split(',')
.map( |s| sanitize_tag(s.trim()) )
.filter(|s| s.as_str() != "" && s.as_str() != " ")
.collect();
tags
}
pub fn retrieve(aid: u32) -> Option<Article> {
let pgconn = establish_connection();
let rawqry = pgconn.query(&format!("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON (a.author = u.userid) WHERE aid = {id}", id=aid), &[]);
if let Ok(aqry) = rawqry {
// println!("Querying articles: found {} rows", aqry.len());
if !aqry.is_empty() && aqry.len() == 1 {
let row = aqry.get(0); // get first row
let display: Option<String> = row.get(7);
let username: String = if let Some(disp) = display { disp } else { row.get(8) };
let image: String = row.get_opt(9).unwrap_or(Ok(String::new())).unwrap_or(String::new());
Some( Article {
aid: row.get(0),
title: row.get(1), // todo: call sanitize title here
posted: row.get(2),
body: row.get(3), // Todo: call sanitize body here
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'').to_string()).collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'')).filter(|s| *s != "").map(|s| s.to_string()).collect(),
tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim_matches('\'').trim().to_string()).filter(|s| s.as_str() != "").collect(),
description: row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
userid: row.get(6),
username: titlecase( &sanitization::sanitize(&username) ),
markdown: row.get_opt(10).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
image,
modified: row.get(11),
})
} else { None }
} else { None }
}
// =====Update-image=====
pub fn save(&self, conn: DbConn) -> Result<String, String> {
let vtags: Vec<String> = self.tags.clone();
let tagstr = format!(
"{{{}}}", vtags
.iter()
// .split(",")
.map(|s| s.trim().to_lowercase())
.filter(|s| s.as_str() != "")
.map(|s| format!("\"{}\"", s))
// .map(|s| format!("\"{}\"", s.trim().to_lowercase()))
.collect::<Vec<_>>()
.join(",")
// .replace(",''")
);
let now = Local::now().naive_local();
let qrystr = format!("
UPDATE articles
SET title = '{title}',
body = '{body}',
tag = '{tag}',
description = '{desc}',
markdown = '{src}',
image = '{img}',
modified = '{modified}'
WHERE aid = {aid}
",
// posted = '{posted}',
title=&self.title,
// posted=slash_quotes(self.posted),
body=&self.body,
tag=tagstr,
desc=&self.description,
src=&self.markdown,
img=&self.image,
aid=self.aid,
modified=&now
);
// println!("Generated update query:\n{}", qrystr);
if let Ok(num) = conn.execute(&qrystr, &[]) {
if num == 1 {
Ok(format!("Article {} successfully updated", self.aid))
} else if num > 1 {
println!("Update query updated too many rows.");
Err("Multiple rows updated".to_string())
} else {
println!("Update query updated no rows.");
Err(String::new())
}
} else {
println!("Update query failed.");
Err(String::new())
}
}
pub fn info(&self) -> String {
format!("Aid: {aid}, Title: {title}, Posted on: {posted}, Description:<br>\n{desc}<br>\nBody:<br>\n{body}<br>\ntags: {tags:#?}", aid=self.aid, title=self.title, posted=self.posted, body=self.body, tags=self.tags, desc=self.description)
}
/// Description: Some(50) displays 50 characters of body text
/// Some(-1) displays the description field as the body
/// None displays all of the body text
pub fn retrieve_all(pgconn: DbConn, limit: u32, description: Option<i32>, min_date: Option<NaiveDate>, max_date: Option<NaiveDate>, tag: Option<Vec<String>>, search: Option<Vec<String>>) -> Vec<Article> {
let mut show_desc = false;
let mut qrystr: String = if let Some(summary) = description {
if summary < 1 {
show_desc = true;
format!("SELECT a.aid, a.title, a.posted, LEFT(a.body, {}) as body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON(a.author = u.userid)", DESC_LIMIT)
} else {
format!("SELECT a.aid, a.title, a.posted, LEFT(a.body, {}) AS body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON(a.author = u.userid)", summary)
}
} else {
String::from("SELECT a.aid, a.title, a.posted, a.body, a.tag, a.description, u.userid, u.display, u.username, a.image, a.markdown, a.modified FROM articles a JOIN users u ON(a.author = u.userid)")
};
if min_date.is_some() || max_date.is_some() || (tag.is_some() && get_len(&tag) != 0) || (search.is_some() && get_len(&search) != 0) {
qrystr.push_str(" WHERE");
let mut where_str = String::from("");
if let Some(date_min) = min_date {
where_str.push_str( &format!(" posted >= '{}'", date_min.format("%Y-%m-%d %H:%M:%S")) );
}
if let Some(date_max) = max_date {
if &where_str != "" { where_str.push_str(" AND "); }
where_str.push_str( &format!(" posted <= '{}'", date_max.format("%Y-%m-%d %H:%M:%S")) );
}
if let Some(v) = tag {
if &where_str != "" { where_str.push_str(" AND "); }
let mut tag_str = String::new();
let mut first: bool = true;
for t in v {
if first { first = false; } else { tag_str.push_str(" AND "); }
// tag_str.push_str( &format!(" tags LIKE '%{}%'", t) );
tag_str.push_str( &format!(" '{}' = ANY(tag)", t) );
}
if &tag_str != "" { where_str.push_str(&tag_str); }
}
if let Some(strings) = search {
if &where_str != "" { where_str.push_str(" AND "); }
let mut search_str = String::new();
let mut first: bool = true;
for string in strings {
if first { first = false; } else { search_str.push_str(" AND ") }
search_str.push_str( &format!(" (title LIKE '%{s}%' OR body LIKE '%{s}%')", s=string) );
}
if &search_str != "" { where_str.push_str(&search_str); }
}
qrystr.push_str(&where_str);
}
qrystr.push_str(" ORDER BY posted DESC");
if limit != 0 { qrystr.push_str(&format!(" LIMIT {}", limit)); }
// println!("Query: {}", qrystr);
let qryrst = pgconn.query(&qrystr, &[]);
if let Ok(result) = qryrst {
let mut articles: Vec<Article> = Vec::new();
for row in &result {
let display: Option<String> = row.get(7);
let username: String = if let Some(disp) = display { disp } else { row.get(8) };
let image: String = row.get_opt(9).unwrap_or(Ok(String::new())).unwrap_or(String::new());
let a = Article {
aid: row.get(0),
title: row.get(1),
posted: row.get(2),
body: if show_desc { // show the truncated body if there is no description when show_desc is true
let d = row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new());
if &d == "" { row.get(3) }
else { d }
} else { row.get(3) },
tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim_matches('\'').trim().to_string()).filter(|s| s.as_str() != "").collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'')).filter(|s| *s != "").map(|s| s.to_string()).collect(),
// tags: row.get_opt(4).unwrap_or(Ok(Vec::<String>::new())).unwrap_or(Vec::<String>::new()).into_iter().map(|s| s.trim().trim_matches('\'').to_string()).collect(),
// description: if show_desc { String::new() } else { String::new() },
// show_desc moves the description to the body
description: if show_desc {
String::new()
} else {
row.get_opt(5).unwrap_or(Ok(String::new())).unwrap_or(String::new())
},
userid: row.get(6),
username: titlecase( &sanitization::sanitize(&username) ),
markdown: row.get_opt(10).unwrap_or(Ok(String::new())).unwrap_or(String::new()),
image,
modified: row.get(11)
};
articles.push(a);
}
// println!("Found {} articles with the specified query.", articles.len());
articles
} else {
println!("Query failed.");
Vec::<Article>::new()
}
}
}
impl PartialEq for Article {
fn eq(&self, other: &Article) -> bool {
self.aid == other.aid
}
}
impl Eq for Article {}
impl ShallowCopy for Article {
unsafe fn shallow_copy(&mut self) -> Self {
self.clone()
}
}
// the &T version of ShallowCopy
// impl<'a> ShallowCopy for &'a Article
// // where
// // T: ?Sized,
// {
// unsafe fn shallow_copy(&mut self) -> Article {
// &*self
// }
// }
// the mut version works
/* impl<'b> ShallowCopy for &'b mut Article {
// impl<'b> ShallowCopy for &'b Article {
unsafe fn shallow_copy(&mut self) -> Self {
& mut *self
}
} */
impl ArticleForm {
pub fn new(title: String, body: String, tags: String, description: String, markdown: String, image: String) -> ArticleForm {
ArticleForm {
title,
body,
markdown,
tags,
description,
image,
}
}
pub fn is_valid(&self) -> bool {
&self.title != ""
&& ( &self.markdown != "" || &self.body != "" )
}
// pub fn to_source(&self, userid: u32, username: &str) -> ArticleSource {