feed_query_builder.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. "strconv"
  8. "strings"
  9. "miniflux.app/v2/internal/model"
  10. "miniflux.app/v2/internal/timezone"
  11. )
  12. // FeedQueryBuilder builds a SQL query to fetch feeds.
  13. type FeedQueryBuilder struct {
  14. store *Storage
  15. args []any
  16. conditions []string
  17. sortExpressions []string
  18. limit int
  19. offset int
  20. withCounters bool
  21. counterJoinFeeds bool
  22. counterArgs []any
  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: []any{userID},
  30. conditions: []string{"f.user_id = $1"},
  31. counterArgs: []any{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, "f.category_id = $"+strconv.Itoa(len(f.args)+1))
  39. f.args = append(f.args, categoryID)
  40. f.counterConditions = append(f.counterConditions, "f.category_id = $"+strconv.Itoa(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, "f.id = $"+strconv.Itoa(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, 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 += " ORDER BY " + strings.Join(f.sortExpressions, ", ")
  84. }
  85. if len(parts) > 0 {
  86. parts += ", lower(f.title) ASC"
  87. }
  88. if f.limit > 0 {
  89. parts += " LIMIT " + strconv.Itoa(f.limit)
  90. }
  91. if f.offset > 0 {
  92. parts += " OFFSET " + strconv.Itoa(f.offset)
  93. }
  94. return 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.description,
  117. f.etag_header,
  118. f.last_modified_header,
  119. f.user_id,
  120. f.checked_at at time zone u.timezone,
  121. f.next_check_at at time zone u.timezone,
  122. f.parsing_error_count,
  123. f.parsing_error_msg,
  124. f.scraper_rules,
  125. f.rewrite_rules,
  126. f.url_rewrite_rules,
  127. f.blocklist_rules,
  128. f.keeplist_rules,
  129. f.block_filter_entry_rules,
  130. f.keep_filter_entry_rules,
  131. f.crawler,
  132. f.user_agent,
  133. f.cookie,
  134. f.username,
  135. f.password,
  136. f.ignore_http_cache,
  137. f.allow_self_signed_certificates,
  138. f.fetch_via_proxy,
  139. f.disabled,
  140. f.no_media_player,
  141. f.hide_globally,
  142. f.category_id,
  143. c.title as category_title,
  144. c.hide_globally as category_hidden,
  145. fi.icon_id,
  146. i.external_id,
  147. u.timezone,
  148. f.apprise_service_urls,
  149. f.webhook_url,
  150. f.disable_http2,
  151. f.ntfy_enabled,
  152. f.ntfy_priority,
  153. f.ntfy_topic,
  154. f.pushover_enabled,
  155. f.pushover_priority,
  156. f.proxy_url
  157. FROM
  158. feeds f
  159. LEFT JOIN
  160. categories c ON c.id=f.category_id
  161. LEFT JOIN
  162. feed_icons fi ON fi.feed_id=f.id
  163. LEFT JOIN
  164. icons i ON i.id=fi.icon_id
  165. LEFT JOIN
  166. users u ON u.id=f.user_id
  167. WHERE %s
  168. %s
  169. `
  170. query = fmt.Sprintf(query, f.buildCondition(), f.buildSorting())
  171. rows, err := f.store.db.Query(query, f.args...)
  172. if err != nil {
  173. return nil, fmt.Errorf(`store: unable to fetch feeds: %w`, err)
  174. }
  175. defer rows.Close()
  176. readCounters, unreadCounters, err := f.fetchFeedCounter()
  177. if err != nil {
  178. return nil, err
  179. }
  180. feeds := make(model.Feeds, 0)
  181. for rows.Next() {
  182. var feed model.Feed
  183. var iconID sql.NullInt64
  184. var externalIconID sql.NullString
  185. var tz string
  186. feed.Category = &model.Category{}
  187. err := rows.Scan(
  188. &feed.ID,
  189. &feed.FeedURL,
  190. &feed.SiteURL,
  191. &feed.Title,
  192. &feed.Description,
  193. &feed.EtagHeader,
  194. &feed.LastModifiedHeader,
  195. &feed.UserID,
  196. &feed.CheckedAt,
  197. &feed.NextCheckAt,
  198. &feed.ParsingErrorCount,
  199. &feed.ParsingErrorMsg,
  200. &feed.ScraperRules,
  201. &feed.RewriteRules,
  202. &feed.UrlRewriteRules,
  203. &feed.BlocklistRules,
  204. &feed.KeeplistRules,
  205. &feed.BlockFilterEntryRules,
  206. &feed.KeepFilterEntryRules,
  207. &feed.Crawler,
  208. &feed.UserAgent,
  209. &feed.Cookie,
  210. &feed.Username,
  211. &feed.Password,
  212. &feed.IgnoreHTTPCache,
  213. &feed.AllowSelfSignedCertificates,
  214. &feed.FetchViaProxy,
  215. &feed.Disabled,
  216. &feed.NoMediaPlayer,
  217. &feed.HideGlobally,
  218. &feed.Category.ID,
  219. &feed.Category.Title,
  220. &feed.Category.HideGlobally,
  221. &iconID,
  222. &externalIconID,
  223. &tz,
  224. &feed.AppriseServiceURLs,
  225. &feed.WebhookURL,
  226. &feed.DisableHTTP2,
  227. &feed.NtfyEnabled,
  228. &feed.NtfyPriority,
  229. &feed.NtfyTopic,
  230. &feed.PushoverEnabled,
  231. &feed.PushoverPriority,
  232. &feed.ProxyURL,
  233. )
  234. if err != nil {
  235. return nil, fmt.Errorf(`store: unable to fetch feeds row: %w`, err)
  236. }
  237. if iconID.Valid && externalIconID.Valid {
  238. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: iconID.Int64, ExternalIconID: externalIconID.String}
  239. } else {
  240. feed.Icon = &model.FeedIcon{FeedID: feed.ID, IconID: 0, ExternalIconID: ""}
  241. }
  242. if readCounters != nil {
  243. if count, found := readCounters[feed.ID]; found {
  244. feed.ReadCount = count
  245. }
  246. }
  247. if unreadCounters != nil {
  248. if count, found := unreadCounters[feed.ID]; found {
  249. feed.UnreadCount = count
  250. }
  251. }
  252. feed.NumberOfVisibleEntries = feed.ReadCount + feed.UnreadCount
  253. feed.CheckedAt = timezone.Convert(tz, feed.CheckedAt)
  254. feed.NextCheckAt = timezone.Convert(tz, feed.NextCheckAt)
  255. feed.Category.UserID = feed.UserID
  256. feeds = append(feeds, &feed)
  257. }
  258. return feeds, nil
  259. }
  260. func (f *FeedQueryBuilder) fetchFeedCounter() (unreadCounters map[int64]int, readCounters map[int64]int, err error) {
  261. if !f.withCounters {
  262. return nil, nil, nil
  263. }
  264. query := `
  265. SELECT
  266. e.feed_id,
  267. e.status,
  268. count(*)
  269. FROM
  270. entries e
  271. %s
  272. WHERE
  273. %s
  274. GROUP BY
  275. e.feed_id, e.status
  276. `
  277. join := ""
  278. if f.counterJoinFeeds {
  279. join = "LEFT JOIN feeds f ON f.id=e.feed_id"
  280. }
  281. query = fmt.Sprintf(query, join, f.buildCounterCondition())
  282. rows, err := f.store.db.Query(query, f.counterArgs...)
  283. if err != nil {
  284. return nil, nil, fmt.Errorf(`store: unable to fetch feed counts: %w`, err)
  285. }
  286. defer rows.Close()
  287. readCounters = make(map[int64]int)
  288. unreadCounters = make(map[int64]int)
  289. for rows.Next() {
  290. var feedID int64
  291. var status string
  292. var count int
  293. if err := rows.Scan(&feedID, &status, &count); err != nil {
  294. return nil, nil, fmt.Errorf(`store: unable to fetch feed counter row: %w`, err)
  295. }
  296. switch status {
  297. case model.EntryStatusRead:
  298. readCounters[feedID] = count
  299. case model.EntryStatusUnread:
  300. unreadCounters[feedID] = count
  301. }
  302. }
  303. return readCounters, unreadCounters, nil
  304. }