utils.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. import { Model, Sequelize } from 'sequelize-typescript'
  2. import validator from 'validator'
  3. import { Col } from 'sequelize/types/lib/utils'
  4. import { literal, OrderItem, Op } 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 (blockerIds: number[]) {
  93. const blockerIdsString = blockerIds.join(', ')
  94. return 'SELECT "targetAccountId" AS "id" FROM "accountBlocklist" WHERE "accountId" IN (' + blockerIdsString + ')' +
  95. ' UNION ALL ' +
  96. 'SELECT "account"."id" AS "id" FROM account INNER JOIN "actor" ON account."actorId" = actor.id ' +
  97. 'INNER JOIN "serverBlocklist" ON "actor"."serverId" = "serverBlocklist"."targetServerId" ' +
  98. 'WHERE "serverBlocklist"."accountId" IN (' + blockerIdsString + ')'
  99. }
  100. function buildServerIdsFollowedBy (actorId: any) {
  101. const actorIdNumber = parseInt(actorId + '', 10)
  102. return '(' +
  103. 'SELECT "actor"."serverId" FROM "actorFollow" ' +
  104. 'INNER JOIN "actor" ON actor.id = "actorFollow"."targetActorId" ' +
  105. 'WHERE "actorFollow"."actorId" = ' + actorIdNumber +
  106. ')'
  107. }
  108. function buildWhereIdOrUUID (id: number | string) {
  109. return validator.isInt('' + id) ? { id } : { uuid: id }
  110. }
  111. function parseAggregateResult (result: any) {
  112. if (!result) return 0
  113. const total = parseInt(result + '', 10)
  114. if (isNaN(total)) return 0
  115. return total
  116. }
  117. const createSafeIn = (model: typeof Model, stringArr: (string | number)[]) => {
  118. return stringArr.map(t => {
  119. return t === null
  120. ? null
  121. : model.sequelize.escape('' + t)
  122. }).join(', ')
  123. }
  124. function buildLocalAccountIdsIn () {
  125. return literal(
  126. '(SELECT "account"."id" FROM "account" INNER JOIN "actor" ON "actor"."id" = "account"."actorId" AND "actor"."serverId" IS NULL)'
  127. )
  128. }
  129. function buildLocalActorIdsIn () {
  130. return literal(
  131. '(SELECT "actor"."id" FROM "actor" WHERE "actor"."serverId" IS NULL)'
  132. )
  133. }
  134. function buildDirectionAndField (value: string) {
  135. let field: string
  136. let direction: 'ASC' | 'DESC'
  137. if (value.substring(0, 1) === '-') {
  138. direction = 'DESC'
  139. field = value.substring(1)
  140. } else {
  141. direction = 'ASC'
  142. field = value
  143. }
  144. return { direction, field }
  145. }
  146. function searchAttribute (sourceField?: string, targetField?: string) {
  147. if (!sourceField) return {}
  148. return {
  149. [targetField]: {
  150. [Op.iLike]: `%${sourceField}%`
  151. }
  152. }
  153. }
  154. // ---------------------------------------------------------------------------
  155. export {
  156. buildBlockedAccountSQL,
  157. buildLocalActorIdsIn,
  158. SortType,
  159. buildLocalAccountIdsIn,
  160. getSort,
  161. getCommentSort,
  162. getVideoSort,
  163. getBlacklistSort,
  164. createSimilarityAttribute,
  165. throwIfNotValid,
  166. buildServerIdsFollowedBy,
  167. buildTrigramSearchIndex,
  168. buildWhereIdOrUUID,
  169. isOutdated,
  170. parseAggregateResult,
  171. getFollowsSort,
  172. buildDirectionAndField,
  173. createSafeIn,
  174. searchAttribute
  175. }
  176. // ---------------------------------------------------------------------------
  177. function searchTrigramNormalizeValue (value: string) {
  178. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', value))
  179. }
  180. function searchTrigramNormalizeCol (col: string) {
  181. return Sequelize.fn('lower', Sequelize.fn('immutable_unaccent', Sequelize.col(col)))
  182. }