2
1

utils.ts 7.6 KB

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