utils.ts 6.3 KB

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