1// Copyright 2018 Frédéric Guillot. All rights reserved.
2// Use of this source code is governed by the Apache 2.0
3// license that can be found in the LICENSE file.
4
5package ui // import "miniflux.app/ui"
6
7import (
8	"net/http"
9
10	"miniflux.app/http/request"
11	"miniflux.app/http/response/html"
12	"miniflux.app/http/route"
13	"miniflux.app/model"
14	"miniflux.app/storage"
15	"miniflux.app/ui/session"
16	"miniflux.app/ui/view"
17)
18
19func (h *handler) showSearchEntryPage(w http.ResponseWriter, r *http.Request) {
20	user, err := h.store.UserByID(request.UserID(r))
21	if err != nil {
22		html.ServerError(w, r, err)
23		return
24	}
25
26	entryID := request.RouteInt64Param(r, "entryID")
27	searchQuery := request.QueryStringParam(r, "q", "")
28	builder := h.store.NewEntryQueryBuilder(user.ID)
29	builder.WithSearchQuery(searchQuery)
30	builder.WithEntryID(entryID)
31	builder.WithoutStatus(model.EntryStatusRemoved)
32
33	entry, err := builder.GetEntry()
34	if err != nil {
35		html.ServerError(w, r, err)
36		return
37	}
38
39	if entry == nil {
40		html.NotFound(w, r)
41		return
42	}
43
44	if entry.Status == model.EntryStatusUnread {
45		err = h.store.SetEntriesStatus(user.ID, []int64{entry.ID}, model.EntryStatusRead)
46		if err != nil {
47			html.ServerError(w, r, err)
48			return
49		}
50
51		entry.Status = model.EntryStatusRead
52	}
53
54	entryPaginationBuilder := storage.NewEntryPaginationBuilder(h.store, user.ID, entry.ID, user.EntryOrder, user.EntryDirection)
55	entryPaginationBuilder.WithSearchQuery(searchQuery)
56	prevEntry, nextEntry, err := entryPaginationBuilder.Entries()
57	if err != nil {
58		html.ServerError(w, r, err)
59		return
60	}
61
62	nextEntryRoute := ""
63	if nextEntry != nil {
64		nextEntryRoute = route.Path(h.router, "searchEntry", "entryID", nextEntry.ID)
65	}
66
67	prevEntryRoute := ""
68	if prevEntry != nil {
69		prevEntryRoute = route.Path(h.router, "searchEntry", "entryID", prevEntry.ID)
70	}
71
72	sess := session.New(h.store, request.SessionID(r))
73	view := view.New(h.tpl, r, sess)
74	view.Set("searchQuery", searchQuery)
75	view.Set("entry", entry)
76	view.Set("prevEntry", prevEntry)
77	view.Set("nextEntry", nextEntry)
78	view.Set("nextEntryRoute", nextEntryRoute)
79	view.Set("prevEntryRoute", prevEntryRoute)
80	view.Set("menu", "search")
81	view.Set("user", user)
82	view.Set("countUnread", h.store.CountUnreadEntries(user.ID))
83	view.Set("countErrorFeeds", h.store.CountUserFeedsWithErrors(user.ID))
84	view.Set("hasSaveEntry", h.store.HasSaveEntry(user.ID))
85
86	html.OK(w, r, view.Render("entry"))
87}
88