feed_query_builder.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. f.disable_http2
  145. FROM
  146. feeds f
  147. LEFT JOIN
  148. categories c ON c.id=f.category_id
  149. LEFT JOIN
  150. feed_icons fi ON fi.feed_id=f.id
  151. LEFT JOIN
  152. users u ON u.id=f.user_id
  153. WHERE %s
  154. %s
  155. `
  156. query = fmt.Sprintf(query, f.buildCondition(), f.buildSorting())
  157. rows, err := f.store.db.Query(query, f.args...)
  158. if err != nil {
  159. return nil, fmt.Errorf(`store: unable to fetch feeds: %w`, err)
  160. }
  161. defer rows.Close()
  162. readCounters, unreadCounters, err := f.fetchFeedCounter()
  163. if err != nil {
  164. return nil, err
  165. }
  166. feeds := make(model.Feeds, 0)
  167. for rows.Next() {
  168. var feed model.Feed
  169. var iconID sql.NullInt64
  170. var tz string
  171. feed.Category = &model.Category{}
  172. err := rows.Scan(
  173. &feed.ID,
  174. &feed.FeedURL,
  175. &feed.SiteURL,
  176. &feed.Title,
  177. &feed.EtagHeader,
  178. &feed.LastModifiedHeader,
  179. &feed.UserID,
  180. &feed.CheckedAt,
  181. &feed.NextCheckAt,
  182. &feed.ParsingErrorCount,
  183. &feed.ParsingErrorMsg,
  184. &feed.ScraperRules,
  185. &feed.RewriteRules,
  186. &feed.BlocklistRules,
  187. &feed.KeeplistRules,
  188. &feed.UrlRewriteRules,
  189. &feed.Crawler,
  190. &feed.UserAgent,
  191. &feed.Cookie,
  192. &feed.Username,
  193. &feed.Password,
  194. &feed.IgnoreHTTPCache,
  195. &feed.AllowSelfSignedCertificates,
  196. &feed.FetchViaProxy,
  197. &feed.Disabled,
  198. &feed.NoMediaPlayer,
  199. &feed.HideGlobally,
  200. &feed.Category.ID,
  201. &feed.Category.Title,
  202. &feed.Category.HideGlobally,
  203. &iconID,
  204. &tz,
  205. &feed.AppriseServiceURLs,
  206. &feed.DisableHTTP2,
  207. )
  208. if err != nil {
  209. return nil, fmt.Errorf(`store: unable to fetch feeds row: %w`, err)
  210. }
  211. if iconID.Valid {
  212. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: iconID.Int64}
  213. } else {
  214. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: 0}
  215. }
  216. if readCounters != nil {
  217. if count, found := readCounters[feed.ID]; found {
  218. feed.ReadCount = count
  219. }
  220. }
  221. if unreadCounters != nil {
  222. if count, found := unreadCounters[feed.ID]; found {
  223. feed.UnreadCount = count
  224. }
  225. }
  226. feed.NumberOfVisibleEntries = feed.ReadCount + feed.UnreadCount
  227. feed.CheckedAt = timezone.Convert(tz, feed.CheckedAt)
  228. feed.NextCheckAt = timezone.Convert(tz, feed.NextCheckAt)
  229. feed.Category.UserID = feed.UserID
  230. feeds = append(feeds, &feed)
  231. }
  232. return feeds, nil
  233. }
  234. func (f *FeedQueryBuilder) fetchFeedCounter() (unreadCounters map[int64]int, readCounters map[int64]int, err error) {
  235. if !f.withCounters {
  236. return nil, nil, nil
  237. }
  238. query := `
  239. SELECT
  240. e.feed_id,
  241. e.status,
  242. count(*)
  243. FROM
  244. entries e
  245. %s
  246. WHERE
  247. %s
  248. GROUP BY
  249. e.feed_id, e.status
  250. `
  251. join := ""
  252. if f.counterJoinFeeds {
  253. join = "LEFT JOIN feeds f ON f.id=e.feed_id"
  254. }
  255. query = fmt.Sprintf(query, join, f.buildCounterCondition())
  256. rows, err := f.store.db.Query(query, f.counterArgs...)
  257. if err != nil {
  258. return nil, nil, fmt.Errorf(`store: unable to fetch feed counts: %w`, err)
  259. }
  260. defer rows.Close()
  261. readCounters = make(map[int64]int)
  262. unreadCounters = make(map[int64]int)
  263. for rows.Next() {
  264. var feedID int64
  265. var status string
  266. var count int
  267. if err := rows.Scan(&feedID, &status, &count); err != nil {
  268. return nil, nil, fmt.Errorf(`store: unable to fetch feed counter row: %w`, err)
  269. }
  270. if status == model.EntryStatusRead {
  271. readCounters[feedID] = count
  272. } else if status == model.EntryStatusUnread {
  273. unreadCounters[feedID] = count
  274. }
  275. }
  276. return readCounters, unreadCounters, nil
  277. }