feed_query_builder.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package storage // import "miniflux.app/v2/internal/storage"
  4. import (
  5. "database/sql"
  6. "fmt"
  7. "strings"
  8. "miniflux.app/v2/internal/model"
  9. "miniflux.app/v2/internal/timezone"
  10. )
  11. // FeedQueryBuilder builds a SQL query to fetch feeds.
  12. type FeedQueryBuilder struct {
  13. store *Storage
  14. args []interface{}
  15. conditions []string
  16. sortExpressions []string
  17. limit int
  18. offset int
  19. withCounters bool
  20. counterJoinFeeds bool
  21. counterArgs []interface{}
  22. counterConditions []string
  23. }
  24. // NewFeedQueryBuilder returns a new FeedQueryBuilder.
  25. func NewFeedQueryBuilder(store *Storage, userID int64) *FeedQueryBuilder {
  26. return &FeedQueryBuilder{
  27. store: store,
  28. args: []interface{}{userID},
  29. conditions: []string{"f.user_id = $1"},
  30. counterArgs: []interface{}{userID, model.EntryStatusRead, model.EntryStatusUnread},
  31. counterConditions: []string{"e.user_id = $1", "e.status IN ($2, $3)"},
  32. }
  33. }
  34. // WithCategoryID filter by category ID.
  35. func (f *FeedQueryBuilder) WithCategoryID(categoryID int64) *FeedQueryBuilder {
  36. if categoryID > 0 {
  37. f.conditions = append(f.conditions, fmt.Sprintf("f.category_id = $%d", len(f.args)+1))
  38. f.args = append(f.args, categoryID)
  39. f.counterConditions = append(f.counterConditions, fmt.Sprintf("f.category_id = $%d", len(f.counterArgs)+1))
  40. f.counterArgs = append(f.counterArgs, categoryID)
  41. f.counterJoinFeeds = true
  42. }
  43. return f
  44. }
  45. // WithFeedID filter by feed ID.
  46. func (f *FeedQueryBuilder) WithFeedID(feedID int64) *FeedQueryBuilder {
  47. if feedID > 0 {
  48. f.conditions = append(f.conditions, fmt.Sprintf("f.id = $%d", len(f.args)+1))
  49. f.args = append(f.args, feedID)
  50. }
  51. return f
  52. }
  53. // WithCounters let the builder return feeds with counters of statuses of entries.
  54. func (f *FeedQueryBuilder) WithCounters() *FeedQueryBuilder {
  55. f.withCounters = true
  56. return f
  57. }
  58. // WithSorting add a sort expression.
  59. func (f *FeedQueryBuilder) WithSorting(column, direction string) *FeedQueryBuilder {
  60. f.sortExpressions = append(f.sortExpressions, fmt.Sprintf("%s %s", column, direction))
  61. return f
  62. }
  63. // WithLimit set the limit.
  64. func (f *FeedQueryBuilder) WithLimit(limit int) *FeedQueryBuilder {
  65. f.limit = limit
  66. return f
  67. }
  68. // WithOffset set the offset.
  69. func (f *FeedQueryBuilder) WithOffset(offset int) *FeedQueryBuilder {
  70. f.offset = offset
  71. return f
  72. }
  73. func (f *FeedQueryBuilder) buildCondition() string {
  74. return strings.Join(f.conditions, " AND ")
  75. }
  76. func (f *FeedQueryBuilder) buildCounterCondition() string {
  77. return strings.Join(f.counterConditions, " AND ")
  78. }
  79. func (f *FeedQueryBuilder) buildSorting() string {
  80. var parts []string
  81. if len(f.sortExpressions) > 0 {
  82. parts = append(parts, fmt.Sprintf(`ORDER BY %s`, strings.Join(f.sortExpressions, ", ")))
  83. }
  84. if len(parts) > 0 {
  85. parts = append(parts, ", lower(f.title) ASC")
  86. }
  87. if f.limit > 0 {
  88. parts = append(parts, fmt.Sprintf(`LIMIT %d`, f.limit))
  89. }
  90. if f.offset > 0 {
  91. parts = append(parts, fmt.Sprintf(`OFFSET %d`, f.offset))
  92. }
  93. return strings.Join(parts, " ")
  94. }
  95. // GetFeed returns a single feed that match the condition.
  96. func (f *FeedQueryBuilder) GetFeed() (*model.Feed, error) {
  97. f.limit = 1
  98. feeds, err := f.GetFeeds()
  99. if err != nil {
  100. return nil, err
  101. }
  102. if len(feeds) != 1 {
  103. return nil, nil
  104. }
  105. return feeds[0], nil
  106. }
  107. // GetFeeds returns a list of feeds that match the condition.
  108. func (f *FeedQueryBuilder) GetFeeds() (model.Feeds, error) {
  109. var query = `
  110. SELECT
  111. f.id,
  112. f.feed_url,
  113. f.site_url,
  114. f.title,
  115. f.etag_header,
  116. f.last_modified_header,
  117. f.user_id,
  118. f.checked_at at time zone u.timezone,
  119. f.next_check_at at time zone u.timezone,
  120. f.parsing_error_count,
  121. f.parsing_error_msg,
  122. f.scraper_rules,
  123. f.rewrite_rules,
  124. f.blocklist_rules,
  125. f.keeplist_rules,
  126. f.url_rewrite_rules,
  127. f.crawler,
  128. f.user_agent,
  129. f.cookie,
  130. f.username,
  131. f.password,
  132. f.ignore_http_cache,
  133. f.allow_self_signed_certificates,
  134. f.fetch_via_proxy,
  135. f.disabled,
  136. f.no_media_player,
  137. f.hide_globally,
  138. f.category_id,
  139. c.title as category_title,
  140. c.hide_globally as category_hidden,
  141. fi.icon_id,
  142. u.timezone,
  143. f.apprise_service_urls
  144. FROM
  145. feeds f
  146. LEFT JOIN
  147. categories c ON c.id=f.category_id
  148. LEFT JOIN
  149. feed_icons fi ON fi.feed_id=f.id
  150. LEFT JOIN
  151. users u ON u.id=f.user_id
  152. WHERE %s
  153. %s
  154. `
  155. query = fmt.Sprintf(query, f.buildCondition(), f.buildSorting())
  156. rows, err := f.store.db.Query(query, f.args...)
  157. if err != nil {
  158. return nil, fmt.Errorf(`store: unable to fetch feeds: %w`, err)
  159. }
  160. defer rows.Close()
  161. readCounters, unreadCounters, err := f.fetchFeedCounter()
  162. if err != nil {
  163. return nil, err
  164. }
  165. feeds := make(model.Feeds, 0)
  166. for rows.Next() {
  167. var feed model.Feed
  168. var iconID sql.NullInt64
  169. var tz string
  170. feed.Category = &model.Category{}
  171. err := rows.Scan(
  172. &feed.ID,
  173. &feed.FeedURL,
  174. &feed.SiteURL,
  175. &feed.Title,
  176. &feed.EtagHeader,
  177. &feed.LastModifiedHeader,
  178. &feed.UserID,
  179. &feed.CheckedAt,
  180. &feed.NextCheckAt,
  181. &feed.ParsingErrorCount,
  182. &feed.ParsingErrorMsg,
  183. &feed.ScraperRules,
  184. &feed.RewriteRules,
  185. &feed.BlocklistRules,
  186. &feed.KeeplistRules,
  187. &feed.UrlRewriteRules,
  188. &feed.Crawler,
  189. &feed.UserAgent,
  190. &feed.Cookie,
  191. &feed.Username,
  192. &feed.Password,
  193. &feed.IgnoreHTTPCache,
  194. &feed.AllowSelfSignedCertificates,
  195. &feed.FetchViaProxy,
  196. &feed.Disabled,
  197. &feed.NoMediaPlayer,
  198. &feed.HideGlobally,
  199. &feed.Category.ID,
  200. &feed.Category.Title,
  201. &feed.Category.HideGlobally,
  202. &iconID,
  203. &tz,
  204. &feed.AppriseServiceURLs,
  205. )
  206. if err != nil {
  207. return nil, fmt.Errorf(`store: unable to fetch feeds row: %w`, err)
  208. }
  209. if iconID.Valid {
  210. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: iconID.Int64}
  211. } else {
  212. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: 0}
  213. }
  214. if readCounters != nil {
  215. if count, found := readCounters[feed.ID]; found {
  216. feed.ReadCount = count
  217. }
  218. }
  219. if unreadCounters != nil {
  220. if count, found := unreadCounters[feed.ID]; found {
  221. feed.UnreadCount = count
  222. }
  223. }
  224. feed.NumberOfVisibleEntries = feed.ReadCount + feed.UnreadCount
  225. feed.CheckedAt = timezone.Convert(tz, feed.CheckedAt)
  226. feed.NextCheckAt = timezone.Convert(tz, feed.NextCheckAt)
  227. feed.Category.UserID = feed.UserID
  228. feeds = append(feeds, &feed)
  229. }
  230. return feeds, nil
  231. }
  232. func (f *FeedQueryBuilder) fetchFeedCounter() (unreadCounters map[int64]int, readCounters map[int64]int, err error) {
  233. if !f.withCounters {
  234. return nil, nil, nil
  235. }
  236. query := `
  237. SELECT
  238. e.feed_id,
  239. e.status,
  240. count(*)
  241. FROM
  242. entries e
  243. %s
  244. WHERE
  245. %s
  246. GROUP BY
  247. e.feed_id, e.status
  248. `
  249. join := ""
  250. if f.counterJoinFeeds {
  251. join = "LEFT JOIN feeds f ON f.id=e.feed_id"
  252. }
  253. query = fmt.Sprintf(query, join, f.buildCounterCondition())
  254. rows, err := f.store.db.Query(query, f.counterArgs...)
  255. if err != nil {
  256. return nil, nil, fmt.Errorf(`store: unable to fetch feed counts: %w`, err)
  257. }
  258. defer rows.Close()
  259. readCounters = make(map[int64]int)
  260. unreadCounters = make(map[int64]int)
  261. for rows.Next() {
  262. var feedID int64
  263. var status string
  264. var count int
  265. if err := rows.Scan(&feedID, &status, &count); err != nil {
  266. return nil, nil, fmt.Errorf(`store: unable to fetch feed counter row: %w`, err)
  267. }
  268. if status == model.EntryStatusRead {
  269. readCounters[feedID] = count
  270. } else if status == model.EntryStatusUnread {
  271. unreadCounters[feedID] = count
  272. }
  273. }
  274. return readCounters, unreadCounters, nil
  275. }