utils.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. import { Model, Sequelize } from 'sequelize-typescript'
  2. import * as validator from 'validator'
  3. import { Col } from 'sequelize/types/lib/utils'
  4. import { literal, OrderItem } from 'sequelize'
  5. type SortType = { sortModel: string, sortValue: string }
  6. // Translate for example "-name" to [ [ 'name', 'DESC' ], [ 'id', 'ASC' ] ]
  7. function getSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
  8. const { direction, field } = buildDirectionAndField(value)
  9. let finalField: string | Col
  10. if (field.toLowerCase() === 'match') { // Search
  11. finalField = Sequelize.col('similarity')
  12. } else if (field === 'videoQuotaUsed') { // Users list
  13. finalField = Sequelize.col('videoQuotaUsed')
  14. } else {
  15. finalField = field
  16. }
  17. return [ [ finalField, direction ], lastSort ]
  18. }
  19. function getVideoSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
  20. const { direction, field } = buildDirectionAndField(value)
  21. if (field.toLowerCase() === 'trending') { // Sort by aggregation
  22. return [
  23. [ Sequelize.fn('COALESCE', Sequelize.fn('SUM', Sequelize.col('VideoViews.views')), '0'), direction ],
  24. [ Sequelize.col('VideoModel.views'), direction ],
  25. lastSort
  26. ]
  27. }
  28. let finalField: string | Col
  29. // Alias
  30. if (field.toLowerCase() === 'match') { // Search
  31. finalField = Sequelize.col('similarity')
  32. } else {
  33. finalField = field
  34. }
  35. const firstSort = typeof finalField === 'string'
  36. ? finalField.split('.').concat([ direction ]) as any // FIXME: sequelize typings
  37. : [ finalField, direction ]
  38. return [ firstSort, lastSort ]
  39. }
  40. function getBlacklistSort (model: any, value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
  41. const [ firstSort ] = getSort(value)
  42. if (model) return [ [ literal(`"${model}.${firstSort[ 0 ]}" ${firstSort[ 1 ]}`) ], lastSort ] as any[] // FIXME: typings
  43. return [ firstSort, lastSort ]
  44. }
  45. function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
  46. const now = Date.now()
  47. const createdAtTime = model.createdAt.getTime()
  48. const updatedAtTime = model.updatedAt.getTime()
  49. return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
  50. }
  51. function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
  52. if (nullable && (value === null || value === undefined)) return
  53. if (validator(value) === false) {
  54. throw new Error(`"${value}" is not a valid ${fieldName}.`)
  55. }
  56. }
  57. function buildTrigramSearchIndex (indexName: string, attribute: string) {
  58. return {
  59. name: indexName,
  60. fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
  61. using: 'gin',
  62. operator: 'gin_trgm_ops'
  63. }
  64. }
  65. function createSimilarityAttribute (col: string, value: string) {
  66. return Sequelize.fn(
  67. 'similarity',
  68. searchTrigramNormalizeCol(col),
  69. searchTrigramNormalizeValue(value)
  70. )
  71. }
  72. function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
  73. const blockerIds = [ serverAccountId ]
  74. if (userAccountId) blockerIds.push(userAccountId)
  75. const blockerIdsString = blockerIds.join(', ')
  76. return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
  77. ' UNION ALL ' +
  78. 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
  79. 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
  80. 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
  81. }
  82. function buildServerIdsFollowedBy (actorId: any) {
  83. const actorIdNumber = parseInt(actorId + '', 10)
  84. return '(' +
  85. 'SELECT "actor"."serverId" FROM "actorFollow" ' +
  86. 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
  87. 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
  88. ')'
  89. }
  90. function buildWhereIdOrUUID (id: number | string) {
  91. return validator.isInt('' + id) ? { id } : { uuid: id }
  92. }
  93. function parseAggregateResult (result: any) {
  94. if (!result) return 0
  95. const total = parseInt(result + '', 10)
  96. if (isNaN(total)) return 0
  97. return total
  98. }
  99. const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
  100. return stringArr.map(t => model.sequelize.escape('' + t))
  101. .join(', ')
  102. }
  103. function buildLocalAccountIdsIn () {
  104. return literal(
  105. '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
  106. )
  107. }
  108. function buildLocalActorIdsIn () {
  109. return literal(
  110. '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
  111. )
  112. }
  113. // ---------------------------------------------------------------------------
  114. export {
  115. buildBlockedAccountSQL,
  116. buildLocalActorIdsIn,
  117. SortType,
  118. buildLocalAccountIdsIn,
  119. getSort,
  120. getVideoSort,
  121. getBlacklistSort,
  122. createSimilarityAttribute,
  123. throwIfNotValid,
  124. buildServerIdsFollowedBy,
  125. buildTrigramSearchIndex,
  126. buildWhereIdOrUUID,
  127. isOutdated,
  128. parseAggregateResult,
  129. createSafeIn
  130. }
  131. // ---------------------------------------------------------------------------
  132. function searchTrigramNormalizeValue (value: string) {
  133. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
  134. }
  135. function searchTrigramNormalizeCol (col: string) {
  136. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
  137. }
  138. function buildDirectionAndField (value: string) {
  139. let field: string
  140. let direction: 'ASC' | 'DESC'
  141. if (value.substring(0, 1) === '-') {
  142. direction = 'DESC'
  143. field = value.substring(1)
  144. } else {
  145. direction = 'ASC'
  146. field = value
  147. }
  148. return { direction, field }
  149. }