From 2a14417146fa67794f51d2f166f8a3be667db86a Mon Sep 17 00:00:00 2001 From: dverves Date: Mon, 8 Jan 2024 23:02:29 +0200 Subject: [PATCH 1/5] privat messages from user to user almost done --- cmd/web/routes.go | 2 + internal/handler/staticHelperHendlers.go | 57 +++++++ internal/models/models.go | 8 + internal/models/validation.go | 23 +++ internal/repository/dbrepo/sqllite.go | 40 +++++ internal/repository/repository.go | 2 + internal/repository/sql.go | 11 ++ mainDB.db | Bin 327680 -> 327680 bytes template/personal.page.html | 189 ++++++++++++++--------- template/theme.page.html | 2 + 10 files changed, 261 insertions(+), 73 deletions(-) diff --git a/cmd/web/routes.go b/cmd/web/routes.go index 1e3b6b7..5f6c390 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -49,6 +49,8 @@ func routes(a *config.AppConfig) http.Handler { mux.HandleFunc("/moder_panel", handler.Repo.ModerPanelHandler) + mux.HandleFunc("/send-pm", handler.Repo.SendPMHandler) + return mux diff --git a/internal/handler/staticHelperHendlers.go b/internal/handler/staticHelperHendlers.go index 074026b..4432806 100644 --- a/internal/handler/staticHelperHendlers.go +++ b/internal/handler/staticHelperHendlers.go @@ -1,11 +1,14 @@ package handler import ( + "fmt" "log" "net/http" "strconv" + "strings" "github.com/Pomog/ForumFFF/internal/config" + "github.com/Pomog/ForumFFF/internal/helper" "github.com/Pomog/ForumFFF/internal/models" "github.com/Pomog/ForumFFF/internal/renderer" "github.com/Pomog/ForumFFF/internal/repository" @@ -329,6 +332,60 @@ func (m *Repository) GetAllLikedPostsByUserIDHandler(w http.ResponseWriter, r *h } } +// SendPMHandler hanles sending of personal message. +func (m *Repository) SendPMHandler(w http.ResponseWriter, r *http.Request) { + senderID := m.GetLoggedUser(w, r) + if senderID == 0 { + setErrorAndRedirect(w, r, "unautorized", "/error-page") + return + } + + if r.Method == http.MethodPost { + receiverID, _ := strconv.Atoi(r.FormValue("receiverID")) + content := r.FormValue("pm-text") + + content = strings.TrimSpace(content) + content = helper.CorrectPunctuationsSpaces(content) + + // Validation of privat message + validationParameters := models.ValidationConfig{ + MinSubjectLen: m.App.MinSubjectLen, + MaxSubjectLen: m.App.MaxSubjectLen, + SingleWordMaxLen: len(m.App.LongestSingleWord), + } + + if senderID == 1 || receiverID == 1 || senderID == receiverID { + setErrorAndRedirect(w, r, "Wrong receiver!", "/error-page") + return + } + p_message := models.PM{ + Content: content, + SenderUserID: senderID, + ReceiverUserID: receiverID, + } + + validationsErrors := p_message.ValidatePM(validationParameters) + if len(validationsErrors) > 0 { + // prepare error msg + var errorMsg string + for _, err := range validationsErrors { + errorMsg += err.Error() + "\n" + } + setErrorAndRedirect(w, r, errorMsg, "/error-page") + return + } + + err := m.DB.CreatePM(p_message) + if err != nil { + setErrorAndRedirect(w, r, "Could not created a PM "+err.Error(), "/error-page") + return + } + http.Redirect(w, r, fmt.Sprintf("/personal_cabinet?userID=%v", receiverID), http.StatusSeeOther) + } else { + http.Error(w, "No such method", http.StatusMethodNotAllowed) + } +} + // shortenerOfSubject helper function to squeeze theme name func ShortenerOfSubject(input string) string { if len(input) <= 80 { diff --git a/internal/models/models.go b/internal/models/models.go index bce9ee0..88041da 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -86,3 +86,11 @@ var Classifications = []TextClassification{"irrelevant", "unsorted", "approved", } + +type PM struct { + ID int + Content string + Created time.Time + SenderUserID int + ReceiverUserID int +} diff --git a/internal/models/validation.go b/internal/models/validation.go index 8c3537a..9f5de9e 100644 --- a/internal/models/validation.go +++ b/internal/models/validation.go @@ -143,6 +143,29 @@ func (post *Post) Validate(config ValidationConfig) []error { return validationErrors } +func (pm *PM) ValidatePM(config ValidationConfig) []error { + var validationErrors []error + + // Validate Content + if err := ValidateRequired("Content", pm.Content); err != nil { + validationErrors = append(validationErrors, err) + } else { + if err := ValidateLength("Content", pm.Content, config.MinSubjectLen, config.MaxSubjectLen); err != nil { + validationErrors = append(validationErrors, err) + } else { + if !forms.CheckSingleWordLen(pm.Content, config.SingleWordMaxLen) { + err := fmt.Errorf("the Content without spaces is not allowed, max len of each word (without spaces) is %d", config.SingleWordMaxLen) + validationErrors = append(validationErrors, err) + } + } + } + + // Add more validation logic for other fields + + return validationErrors +} + + // ValidateRequired checks if the field is required and not empty. func ValidateRequired(fieldName string, fieldValue string) error { if fieldValue == "" { diff --git a/internal/repository/dbrepo/sqllite.go b/internal/repository/dbrepo/sqllite.go index a50437e..1daddd1 100644 --- a/internal/repository/dbrepo/sqllite.go +++ b/internal/repository/dbrepo/sqllite.go @@ -825,3 +825,43 @@ func (m *SqliteBDRepo) EditPostClassification(post models.Post, classification m } return nil } + +// CreatePM insert post into SQLite DB +func (m *SqliteBDRepo) CreatePM(pm models.PM) error { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + stmt := `insert into pm + (content, senderUserID, receiverUserID) + values ($1, $2, $3) + ` + + _, err := m.DB.ExecContext(ctx, stmt, + pm.Content, + pm.SenderUserID, + pm.ReceiverUserID, + ) + + if err != nil { + return err + } + return nil +} + +// DeletePM deletes pm +func (m *SqliteBDRepo) DeletePM(pm models.PM) error { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + stmt := `DELETE FROM pm + WHERE id = $1; + ` + _, err := m.DB.ExecContext(ctx, stmt, + pm.ID, + ) + + if err != nil { + return err + } + return nil +} diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 8efa3d2..7447b7f 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -36,4 +36,6 @@ type DatabaseInt interface { EditTopicClassification(topic models.Thread, classification models.TextClassification) error GetAllPostsByClassification(classification models.TextClassification) ([]models.Post, error) GetAllThreadsByClassification(classification models.TextClassification) ([]models.Thread, error) + CreatePM(pm models.PM) error + DeletePM(pm models.PM) error } diff --git a/internal/repository/sql.go b/internal/repository/sql.go index 1aad0dd..8877217 100644 --- a/internal/repository/sql.go +++ b/internal/repository/sql.go @@ -51,6 +51,16 @@ var sessionIdTable = `CREATE TABLE IF NOT EXISTS sessionId ( FOREIGN KEY (userID) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE );` +var privateMessageTable = `CREATE TABLE IF NOT EXISTS pm ( + id INTEGER PRIMARY KEY, + content TEXT, + created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + senderUserID INTEGER, + receiverUserID INTEGER, + FOREIGN KEY (senderUserID) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE + FOREIGN KEY (receiverUserID) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE +);` + var guestUser = `INSERT INTO users (username, password, first_name, last_name, email, type) VALUES ('guest', '123456', 'Guest', 'User', 'guest@gmail.com', 'guest');` @@ -70,6 +80,7 @@ func getQuerys() []string { sqlQuerys = append(sqlQuerys, postTable) sqlQuerys = append(sqlQuerys, votesTable) sqlQuerys = append(sqlQuerys, sessionIdTable) + sqlQuerys = append(sqlQuerys, privateMessageTable) sqlQuerys = append(sqlQuerys, addClassificationToPost) sqlQuerys = append(sqlQuerys, addClassificationToThread) diff --git a/mainDB.db b/mainDB.db index 1829a0eec29782e4b41751ac911408bb0e4ee9f2..51a6320e312779e7913551d68a926202c473bc01 100644 GIT binary patch delta 527 zcmY+8O=}ZT6o&7e40mQy<4s7hQ9*90Xsgb2W^yN)$ttmqr5J1osbDu{KJLU&r-t|i zE_9-Z;HqU7SqZM)#aXy==})N3uEj!sgSWL*Jn+DK&Up{-Ns`$lncclyIsyQ6I10z* z6!&gbFCGDH^tm9H0TK@YYRmn?Tz;bb5D%u~NL+Zkjik9!3BGSV^Zdtb7!PAfDK-pcIo$Xg|qE+rg@3*y1U+W*H-V7 zd+tNB_|HC_X=QCx7G#7Fe-VJJFMq1%Fpg8Hc?HJVwdN|$%S8kf8NwV&U#@?|_zMv6 z62$xX4esHktk@y=s!_98NP|eFwr{Jn8U?D&!n#U*)36-JiCAQ%y{!i~dB_cA!}BfQ z34BvEm=&tjG7Q!8EJKZ0Jz$|9L{7kHy1%t73wRUYpLjECHGiMq+YOgr2@)8uRUy<3 zvr4U6-PVY6rjM0I{?579$izDoFHE)%McmcMvHQfUk&{cu)J>}DhN|1d)Em@kRB2gQ zga};c0gnd6f8rCb?+te5|96_T2Gx=9bto0#olH(Jgq?Sl@rTM7as*E9TV*W%di@9W C1ccE5 delta 2554 zcmX9=O^;ni5uLGTJnzlSo9AGI4S^6s2>0Stra!8yyCoK80oho>3kQ^d2>ls}1ww4H zTO15;Sy6T)$r{3eow;w;g{lW9k zeYCf?_YmJ2-?#8>fA^}r^U>aGKmFrob!+eN#)G{Z4_5DN?i~Mq{g2CU-2dm{<%1iy zu3db6v$}j|^#_0bZ2RuT(ft?p?_Iuf|Ml(h{^>Oo`Cz@;zj*iC?{D$%gYBce?Z?|c zZFk#8mp322xP95D6nw9Zx(l7SXQ3EasN0rIcG;`aE*`!8oqO}OgT4JXZl%~-2~m;i z$^fqoWg8o{7Q3pZ6>jn3*F6B+vD~6-|N4x z-(UZ5?bau&|E!*_e!D8Gu-Y8`_vq=-Z!UlQ@aEC3QO?dQZ_s-exvmia)L^15=6_+&@MUCNo&oq)YzNR6Afr-J$7A~6viWNG6w7s z|II!auZ*d7dUYVJDiyqd90wMdo1##(C2>(gG}1~c)4hQVUV4$-$QgzQ;1J3?iH@|Z zp;a{MVwt|SbPAdh$fwl74=1#nTl3R`wAx8VCw`D+O4dj4v!+MTPF? zSFY%{Sy?l5tW-rwZ?T1>t;;(Q-A>x9Q~p zRj37JBH3mdu@0HCbSBue_@JzD*3MsE-j`ODvuM>P4NOHr3} z_K;tk9!fcn_fd>&38gu)wX`^YX{p*wZp~t~L&zYYvZbuC3$b|{VL*W|rx!<6Uri~s zfFR`qaS%(fMN43V6iwk zN);OPZbSk&1V8gESy%2bm0p%gkEn8jno^7EvFTX*{Fy6GD_Co#{rm#Vrqg^r zy6Wk<(QDI2jO~rU67tViN1=n&8brpm!hetfQ^Qsq{G!An;jvgG&xmZK?EX4 zp0^9u^c(U?Pqlq&IjvQ+Ji zi>fS4;@WU_9Ase;gSOpTga8tBK3<@?B!mTasy7Y4?ke;`$YK@2iAzZb<?!v$He@E!K7xnlg9 z+Tav6lZsp|IF2|02Lss|Z%M|EfG*t1xWipT>?2oju-(;#o~{pQi4~EIpu`5k*9is- zO*%PohzA yV2D4Q0Q{&Znngwbx1Su{-2dj~>hX4e|LEs;pZx0XlYM;G@Lhj;_sPNke)fON@?l>9 diff --git a/template/personal.page.html b/template/personal.page.html index aa3c2a6..0bd288e 100644 --- a/template/personal.page.html +++ b/template/personal.page.html @@ -1,81 +1,124 @@ {{template "body" .}} {{define "centralPart"}} -
- {{$person := index .Data "personal"}} -

User Profile

-
- - - - - - - - - - {{if ne $person.UserName "guest"}} - - - - - - - - - - - - - - - - - - - - - - - - {{$totalP := index .Data "totalPosts"}} - - - - - - - - - - - - - - {{if eq $person.Type "moder"}} +{{$person := index .Data "personal"}} +{{$loggedID := index .Data "loggedAsID"}} + + + + +
+ +

User Profile

+
+
+ + + + + + + + + {{if ne $person.UserName "guest"}} + + + + + + + + + + + + + + + + + + + + + + + + {{$totalP := index .Data "totalPosts"}} + + + + + + + + + + + + + {{ end }} + + + + {{if eq $person.Type "moder"}} + {{end}} - - -
+ + {{end}} + +
-{{end}} - + +{{end}} \ No newline at end of file diff --git a/template/theme.page.html b/template/theme.page.html index 4204bf2..013ca19 100644 --- a/template/theme.page.html +++ b/template/theme.page.html @@ -62,6 +62,8 @@

Type your post and cli
 {{$creatorName}}
Date of Registration:
{{index .Data "creatorRegistrationDate"}}
Total Messages: {{index .Data "creatorPostsAmmount"}} +
+ From 7b1e6f26d7a8f85e8c2ecab69ad70ada797e9a28 Mon Sep 17 00:00:00 2001 From: dverves Date: Thu, 18 Jan 2024 19:12:43 +0200 Subject: [PATCH 2/5] fixed testDB --- internal/repository/db_funcs_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/repository/db_funcs_test.go b/internal/repository/db_funcs_test.go index 5b9ee13..c9a542d 100644 --- a/internal/repository/db_funcs_test.go +++ b/internal/repository/db_funcs_test.go @@ -6,7 +6,7 @@ import ( ) var ObligatoryTables = []string{ - "users", "thread", "votes", "post", "sessionId", + "users", "thread", "votes", "post", "sessionId", "pm", } func Test_GetDB(t *testing.T) { From fafb618c5ae365d1dbcc61dc7919f8781040e1c1 Mon Sep 17 00:00:00 2001 From: Pomog Date: Thu, 18 Jan 2024 19:39:19 +0200 Subject: [PATCH 3/5] fixed get T P L from the PS --- cmd/web/routes.go | 2 -- internal/handler/staticHelperHendlers.go | 21 +++++++++++++++++++++ mainDB.db | Bin 327680 -> 327680 bytes template/home.page.html | 1 + template/theme.page.html | 1 + 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/cmd/web/routes.go b/cmd/web/routes.go index 5f6c390..a30da65 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -51,8 +51,6 @@ func routes(a *config.AppConfig) http.Handler { mux.HandleFunc("/send-pm", handler.Repo.SendPMHandler) - - return mux } diff --git a/internal/handler/staticHelperHendlers.go b/internal/handler/staticHelperHendlers.go index 4432806..7139b72 100644 --- a/internal/handler/staticHelperHendlers.go +++ b/internal/handler/staticHelperHendlers.go @@ -130,6 +130,11 @@ func (m *Repository) PersonaCabinetHandler(w http.ResponseWriter, r *http.Reques // GetAllThreadsForUserHandler gets all threads from user (user id) func (m *Repository) GetAllThreadsForUserHandler(w http.ResponseWriter, r *http.Request) { + sessionUserID := m.GetLoggedUser(w, r) + if sessionUserID == 0 { + setErrorAndRedirect(w, r, "unautorized", "/error-page") + return + } if r.Method == http.MethodGet { userID, _ := strconv.Atoi(r.URL.Query().Get("userID")) user, errUser := m.DB.GetUserByID(userID) @@ -163,6 +168,7 @@ func (m *Repository) GetAllThreadsForUserHandler(w http.ResponseWriter, r *http. info.Subject = thread.Subject info.Created = thread.Created.Format("2006-01-02 15:04:05") info.Category = thread.Category + info.UserID = thread.UserID info.PictureUserWhoCreatedThread = user.Picture info.UserNameWhoCreatedThread = user.UserName @@ -195,6 +201,7 @@ func (m *Repository) GetAllThreadsForUserHandler(w http.ResponseWriter, r *http. data["games"] = m.App.GamesList data["threads"] = threadsInfo + data["loggedAsID"] = sessionUserID renderer.RendererTemplate(w, "home.page.html", &models.TemplateData{ Data: data, @@ -207,6 +214,12 @@ func (m *Repository) GetAllThreadsForUserHandler(w http.ResponseWriter, r *http. // GetAllPostsForUserHandler gets all posts from user (user id) func (m *Repository) GetAllPostsForUserHandler(w http.ResponseWriter, r *http.Request) { + sessionUserID := m.GetLoggedUser(w, r) + if sessionUserID == 0 { + setErrorAndRedirect(w, r, "unautorized", "/error-page") + return + } + if r.Method == http.MethodGet { userID, _ := strconv.Atoi(r.URL.Query().Get("userID")) user, errUser := m.DB.GetUserByID(userID) @@ -262,6 +275,7 @@ func (m *Repository) GetAllPostsForUserHandler(w http.ResponseWriter, r *http.Re data["posts"] = postsInfo data["games"] = m.App.GamesList + data["loggedAsID"] = sessionUserID renderer.RendererTemplate(w, "theme.page.html", &models.TemplateData{ Data: data, @@ -270,6 +284,12 @@ func (m *Repository) GetAllPostsForUserHandler(w http.ResponseWriter, r *http.Re } func (m *Repository) GetAllLikedPostsByUserIDHandler(w http.ResponseWriter, r *http.Request) { + sessionUserID := m.GetLoggedUser(w, r) + if sessionUserID == 0 { + setErrorAndRedirect(w, r, "unautorized", "/error-page") + return + } + if r.Method == http.MethodGet { userID, _ := strconv.Atoi(r.URL.Query().Get("userID")) user, errUser := m.DB.GetUserByID(userID) @@ -325,6 +345,7 @@ func (m *Repository) GetAllLikedPostsByUserIDHandler(w http.ResponseWriter, r *h data["posts"] = postsInfo data["games"] = m.App.GamesList + data["loggedAsID"] = sessionUserID renderer.RendererTemplate(w, "theme.page.html", &models.TemplateData{ Data: data, diff --git a/mainDB.db b/mainDB.db index 51a6320e312779e7913551d68a926202c473bc01..9a2d27bc08f4f748073e4432ff06b034aa40f063 100644 GIT binary patch delta 387 zcmY+AKTpC?6vf-pKp&CTAc+GINlY{idGP*$Z6}G76KH_AVascc3mCz@#DP&w7j|7- zOh^Z3KY*LW(J$cc0>p}O@Fc(FCgCjKwL~uAIfX8G?!vy?Okb0 z^XceQ+88PEq%f*wsVJuM&HlxC*9uOYDfcGqlElQ>IRd3M0 z9J)Ll({@e*O7KzNUT+F9O&7J9rfZMtQe6gxMm;Du)Ue;UQH#1F3t}scTx4UyDv+2S zg3Q4#w0Rdp>KP2Vri+ka2YRO{3xd!JPC7enJ+WHkHo_hw6e81RkadXx9fL$T+8DVweCr^z9#71qxJ#eUi#4N1s sza$vRDZ&;NQ=9pp|9|zb1zfc-ORtQ-Ca%F`3?^cP6cKv{6Zz}x8wlQKMgRZ+ delta 266 zcmWN~ze>YE0D$qkBx0^ZPPCgH1VK2<(YrKha+~7h)F39f#oRwPot=z0WUP`U58&h= zlnlOz;^-T6?P`YK_Q6-zUGro$(t;9tL3KR>#CGcP8NkJ`WG z@!kjUFoF07KjCXkFlmpnWjo7){vlfhQvjd?^8+my(>&GGR-Dr)6^cs14Asmi7A=HL zD%p~9>JiTa?M-=7DB^km=KIM!(l(TaD$6yEY$#~TIioCMY!U0!D60Vgrzo#vEQOLG zWhat this topic will {{$threadinfo := index .Data "threads"}} {{ range $threadinfo }} + {{ if or (eq .UserID $loggedID) (eq .Classification "approved") }} diff --git a/template/theme.page.html b/template/theme.page.html index 013ca19..adbf1ff 100644 --- a/template/theme.page.html +++ b/template/theme.page.html @@ -101,6 +101,7 @@

Topic:

{{$postinfo := index .Data "posts"}} {{ range $postinfo }} {{$postCreatorID := .UserIDWhoCreatedPost}} + {{ if or (eq $postCreatorID $loggedID) (eq .Classification "approved") }} From 60fbfbd7ba254e02697b3b0579a302a5b221c69d Mon Sep 17 00:00:00 2001 From: Pomog Date: Thu, 18 Jan 2024 20:14:32 +0200 Subject: [PATCH 4/5] get receivedPMS --- internal/handler/staticHelperHendlers.go | 10 +++- internal/handler/themeHandler.go | 1 + internal/repository/dbrepo/sqllite.go | 60 +++++++++++++++++++++++ internal/repository/repository.go | 2 + mainDB.db | Bin 327680 -> 327680 bytes template/theme.page.html | 3 ++ 6 files changed, 75 insertions(+), 1 deletion(-) diff --git a/internal/handler/staticHelperHendlers.go b/internal/handler/staticHelperHendlers.go index 7139b72..6a7d5c9 100644 --- a/internal/handler/staticHelperHendlers.go +++ b/internal/handler/staticHelperHendlers.go @@ -114,10 +114,18 @@ func (m *Repository) PersonaCabinetHandler(w http.ResponseWriter, r *http.Reques personalInfo.UserName = user.UserName personalInfo.Type = user.Type //will show type of user in personal cabinet totalPosts, _ := m.DB.GetTotalPostsAmmountByUserID(personalInfo.ID) + + receivedPMS, err := m.DB.GetPMbyReceiverUserID(sessionUserID) + if err != nil { + setErrorAndRedirect(w, r, "Could not get received PMS"+err.Error(), "/error-page") + return + } + data := make(map[string]interface{}) data["personal"] = personalInfo data["totalPosts"] = totalPosts data["loggedAsID"] = sessionUserID + data["receivedPMS"] = receivedPMS renderer.RendererTemplate(w, "personal.page.html", &models.TemplateData{ Data: data, @@ -219,7 +227,7 @@ func (m *Repository) GetAllPostsForUserHandler(w http.ResponseWriter, r *http.Re setErrorAndRedirect(w, r, "unautorized", "/error-page") return } - + if r.Method == http.MethodGet { userID, _ := strconv.Atoi(r.URL.Query().Get("userID")) user, errUser := m.DB.GetUserByID(userID) diff --git a/internal/handler/themeHandler.go b/internal/handler/themeHandler.go index 16f0865..b6a8861 100644 --- a/internal/handler/themeHandler.go +++ b/internal/handler/themeHandler.go @@ -292,6 +292,7 @@ func prepareDataForThemePage(m *Repository, w http.ResponseWriter, r *http.Reque data["creatorPostsAmount"] = creatorPostsAmount data["creatorImg"] = creator.Picture data["mainThreadName"] = mainThread.Subject + data["mainThreadCategory"] = mainThread.Category data["mainThreadID"] = mainThread.ID data["mainThreadCreatedTime"] = mainThread.Created.Format("2006-01-02 15:04:05") data["games"] = m.App.GamesList diff --git a/internal/repository/dbrepo/sqllite.go b/internal/repository/dbrepo/sqllite.go index 1daddd1..d33a893 100644 --- a/internal/repository/dbrepo/sqllite.go +++ b/internal/repository/dbrepo/sqllite.go @@ -865,3 +865,63 @@ func (m *SqliteBDRepo) DeletePM(pm models.PM) error { } return nil } + +// GetPMbyReceiverUserID insert post into SQLite DB +func (m *SqliteBDRepo) GetPMbyReceiverUserID(userID int) ([]models.PM, error) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + query := `select * from pm + where receiverUserID = $1 + ` + + rows, err := m.DB.QueryContext(ctx, query, userID) + if err != nil { + return nil, err + } + defer rows.Close() + + var pms []models.PM + + for rows.Next() { + var pm models.PM + err := rows.Scan(&pm.ID, &pm.Content, &pm.Created, &pm.SenderUserID, &pm.ReceiverUserID) + if err != nil { + return nil, err + } + pms = append(pms, pm) + } + + return pms, nil +} + +// GetPMbysenderUserID insert post into SQLite DB +func (m *SqliteBDRepo) GetPMbysenderUserID(userID int) ([]models.PM, error) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + query := `select * from pm + where senderUserID = $1 + ` + + rows, err := m.DB.QueryContext(ctx, query, userID) + if err != nil { + return nil, err + } + defer rows.Close() + + var pms []models.PM + + for rows.Next() { + var pm models.PM + err := rows.Scan(&pm.ID, &pm.Content, &pm.Created, &pm.SenderUserID, &pm.ReceiverUserID) + if err != nil { + return nil, err + } + pms = append(pms, pm) + } + + return pms, nil +} + + diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 7447b7f..3099971 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -38,4 +38,6 @@ type DatabaseInt interface { GetAllThreadsByClassification(classification models.TextClassification) ([]models.Thread, error) CreatePM(pm models.PM) error DeletePM(pm models.PM) error + GetPMbyReceiverUserID(userID int) ([]models.PM, error) + GetPMbysenderUserID(userID int) ([]models.PM, error) } diff --git a/mainDB.db b/mainDB.db index 9a2d27bc08f4f748073e4432ff06b034aa40f063..04e8c90e7f1ea875b678b498f83a28f1f6880d4a 100644 GIT binary patch delta 150 zcmZo@5NT)-nIOf)!a7mL2}o{CSm)2gU$P1hpPBvm)X+}P5< yFflnTC2jKMctZ|G{%Z{U*Z8A03nqB-PYhsfj>>P3%4Y;(CLm_s9+l6sYytqkgeq?U delta 150 zcmZo@5NT)-nIOf){CA>^6Oi1Pu+E=}@84#DfKqType your post and cli

Topic:

+

+ {{index .Data "mainThreadCategory"}} +


{{$threadImage := index .Data "threadImg"}} {{ if $threadImage }} From 03aa7dbfbb6a7879ac3f45e80e61642374bee235 Mon Sep 17 00:00:00 2001 From: dverves Date: Mon, 8 Jan 2024 23:02:29 +0200 Subject: [PATCH 5/5] privat messages from user to user almost done --- cmd/web/routes.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/web/routes.go b/cmd/web/routes.go index a30da65..5f6c390 100644 --- a/cmd/web/routes.go +++ b/cmd/web/routes.go @@ -51,6 +51,8 @@ func routes(a *config.AppConfig) http.Handler { mux.HandleFunc("/send-pm", handler.Repo.SendPMHandler) + + return mux }