utils.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 getFollowsSort (value: string, lastSort: OrderItem = [ 'id', 'ASC' ]): OrderItem[] {
  46. const { direction, field } = buildDirectionAndField(value)
  47. if (field === 'redundancyAllowed') {
  48. return [
  49. [ 'ActorFollowing', 'Server', 'redundancyAllowed', direction ],
  50. lastSort
  51. ]
  52. }
  53. return getSort(value, lastSort)
  54. }
  55. function isOutdated (model: { createdAt: Date, updatedAt: Date }, refreshInterval: number) {
  56. const now = Date.now()
  57. const createdAtTime = model.createdAt.getTime()
  58. const updatedAtTime = model.updatedAt.getTime()
  59. return (now - createdAtTime) > refreshInterval && (now - updatedAtTime) > refreshInterval
  60. }
  61. function throwIfNotValid (value: any, validator: (value: any) => boolean, fieldName = 'value', nullable = false) {
  62. if (nullable && (value === null || value === undefined)) return
  63. if (validator(value) === false) {
  64. throw new Error(`"${value}" is not a valid ${fieldName}.`)
  65. }
  66. }
  67. function buildTrigramSearchIndex (indexName: string, attribute: string) {
  68. return {
  69. name: indexName,
  70. fields: [ Sequelize.literal('lower(immutable_unaccent(' + attribute + '))') as any ],
  71. using: 'gin',
  72. operator: 'gin_trgm_ops'
  73. }
  74. }
  75. function createSimilarityAttribute (col: string, value: string) {
  76. return Sequelize.fn(
  77. 'similarity',
  78. searchTrigramNormalizeCol(col),
  79. searchTrigramNormalizeValue(value)
  80. )
  81. }
  82. function buildBlockedAccountSQL (serverAccountId: number, userAccountId?: number) {
  83. const blockerIds = [ serverAccountId ]
  84. if (userAccountId) blockerIds.push(userAccountId)
  85. const blockerIdsString = blockerIds.join(', ')
  86. return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
  87. ' UNION ALL ' +
  88. 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
  89. 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
  90. 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
  91. }
  92. function buildServerIdsFollowedBy (actorId: any) {
  93. const actorIdNumber = parseInt(actorId + '', 10)
  94. return '(' +
  95. 'SELECT "actor"."serverId" FROM "actorFollow" ' +
  96. 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
  97. 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
  98. ')'
  99. }
  100. function buildWhereIdOrUUID (id: number | string) {
  101. return validator.isInt('' + id) ? { id } : { uuid: id }
  102. }
  103. function parseAggregateResult (result: any) {
  104. if (!result) return 0
  105. const total = parseInt(result + '', 10)
  106. if (isNaN(total)) return 0
  107. return total
  108. }
  109. const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
  110. return stringArr.map(t => model.sequelize.escape('' + t))
  111. .join(', ')
  112. }
  113. function buildLocalAccountIdsIn () {
  114. return literal(
  115. '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
  116. )
  117. }
  118. function buildLocalActorIdsIn () {
  119. return literal(
  120. '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
  121. )
  122. }
  123. // ---------------------------------------------------------------------------
  124. export {
  125. buildBlockedAccountSQL,
  126. buildLocalActorIdsIn,
  127. SortType,
  128. buildLocalAccountIdsIn,
  129. getSort,
  130. getVideoSort,
  131. getBlacklistSort,
  132. createSimilarityAttribute,
  133. throwIfNotValid,
  134. buildServerIdsFollowedBy,
  135. buildTrigramSearchIndex,
  136. buildWhereIdOrUUID,
  137. isOutdated,
  138. parseAggregateResult,
  139. getFollowsSort,
  140. createSafeIn
  141. }
  142. // ---------------------------------------------------------------------------
  143. function searchTrigramNormalizeValue (value: string) {
  144. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
  145. }
  146. function searchTrigramNormalizeCol (col: string) {
  147. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
  148. }
  149. function buildDirectionAndField (value: string) {
  150. let field: string
  151. let direction: 'ASC' | 'DESC'
  152. if (value.substring(0, 1) === '-') {
  153. direction = 'DESC'
  154. field = value.substring(1)
  155. } else {
  156. direction = 'ASC'
  157. field = value
  158. }
  159. return { direction, field }
  160. }