feed_query_builder.go 7.2 KB

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