ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

account.ts 12 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. import { Account, AccountSummary } from '@peertube/peertube-models'
  2. import { ModelCache } from '@server/models/shared/model-cache.js'
  3. import { FindOptions, IncludeOptions, Includeable, Op, Transaction, WhereOptions } from 'sequelize'
  4. import {
  5. AllowNull,
  6. BeforeDestroy,
  7. BelongsTo, Column,
  8. CreatedAt,
  9. DataType,
  10. Default,
  11. DefaultScope,
  12. ForeignKey,
  13. HasMany,
  14. Is, Scopes,
  15. Table,
  16. UpdatedAt
  17. } from 'sequelize-typescript'
  18. import { isAccountDescriptionValid } from '../../helpers/custom-validators/accounts.js'
  19. import { CONSTRAINTS_FIELDS, SERVER_ACTOR_NAME, WEBSERVER } from '../../initializers/constants.js'
  20. import { sendDeleteActor } from '../../lib/activitypub/send/send-delete.js'
  21. import {
  22. MAccount, MAccountAP,
  23. MAccountDefault,
  24. MAccountFormattable,
  25. MAccountHost,
  26. MAccountSummaryFormattable,
  27. MChannelHost
  28. } from '../../types/models/index.js'
  29. import { ActorFollowModel } from '../actor/actor-follow.js'
  30. import { ActorImageModel } from '../actor/actor-image.js'
  31. import { ActorModel } from '../actor/actor.js'
  32. import { ApplicationModel } from '../application/application.js'
  33. import { AccountAutomaticTagPolicyModel } from '../automatic-tag/account-automatic-tag-policy.js'
  34. import { CommentAutomaticTagModel } from '../automatic-tag/comment-automatic-tag.js'
  35. import { VideoAutomaticTagModel } from '../automatic-tag/video-automatic-tag.js'
  36. import { ServerBlocklistModel } from '../server/server-blocklist.js'
  37. import { ServerModel } from '../server/server.js'
  38. import { SequelizeModel, buildSQLAttributes, getSort, throwIfNotValid } from '../shared/index.js'
  39. import { UserModel } from '../user/user.js'
  40. import { VideoChannelModel } from '../video/video-channel.js'
  41. import { VideoCommentModel } from '../video/video-comment.js'
  42. import { VideoPlaylistModel } from '../video/video-playlist.js'
  43. import { VideoModel } from '../video/video.js'
  44. import { AccountBlocklistModel } from './account-blocklist.js'
  45. export enum ScopeNames {
  46. SUMMARY = 'SUMMARY'
  47. }
  48. export type SummaryOptions = {
  49. actorRequired?: boolean // Default: true
  50. whereActor?: WhereOptions
  51. whereServer?: WhereOptions
  52. withAccountBlockerIds?: number[]
  53. forCount?: boolean
  54. }
  55. @DefaultScope(() => ({
  56. include: [
  57. {
  58. model: ActorModel, // Default scope includes avatar and server
  59. required: true
  60. }
  61. ]
  62. }))
  63. @Scopes(() => ({
  64. [ScopeNames.SUMMARY]: (options: SummaryOptions = {}) => {
  65. const serverInclude: IncludeOptions = {
  66. attributes: [ 'host' ],
  67. model: ServerModel.unscoped(),
  68. required: !!options.whereServer,
  69. where: options.whereServer
  70. }
  71. const actorInclude: Includeable = {
  72. attributes: [ 'id', 'preferredUsername', 'url', 'serverId' ],
  73. model: ActorModel.unscoped(),
  74. required: options.actorRequired ?? true,
  75. where: options.whereActor,
  76. include: [ serverInclude ]
  77. }
  78. if (options.forCount !== true) {
  79. actorInclude.include.push({
  80. model: ActorImageModel,
  81. as: 'Avatars',
  82. required: false
  83. })
  84. }
  85. const queryInclude: Includeable[] = [
  86. actorInclude
  87. ]
  88. const query: FindOptions = {
  89. attributes: [ 'id', 'name', 'actorId' ]
  90. }
  91. if (options.withAccountBlockerIds) {
  92. queryInclude.push({
  93. attributes: [ 'id' ],
  94. model: AccountBlocklistModel.unscoped(),
  95. as: 'BlockedBy',
  96. required: false,
  97. where: {
  98. accountId: {
  99. [Op.in]: options.withAccountBlockerIds
  100. }
  101. }
  102. })
  103. serverInclude.include = [
  104. {
  105. attributes: [ 'id' ],
  106. model: ServerBlocklistModel.unscoped(),
  107. required: false,
  108. where: {
  109. accountId: {
  110. [Op.in]: options.withAccountBlockerIds
  111. }
  112. }
  113. }
  114. ]
  115. }
  116. query.include = queryInclude
  117. return query
  118. }
  119. }))
  120. @Table({
  121. tableName: 'account',
  122. indexes: [
  123. {
  124. fields: [ 'actorId' ],
  125. unique: true
  126. },
  127. {
  128. fields: [ 'applicationId' ]
  129. },
  130. {
  131. fields: [ 'userId' ]
  132. }
  133. ]
  134. })
  135. export class AccountModel extends SequelizeModel<AccountModel> {
  136. @AllowNull(false)
  137. @Column
  138. name: string
  139. @AllowNull(true)
  140. @Default(null)
  141. @Is('AccountDescription', value => throwIfNotValid(value, isAccountDescriptionValid, 'description', true))
  142. @Column(DataType.STRING(CONSTRAINTS_FIELDS.USERS.DESCRIPTION.max))
  143. description: string
  144. @CreatedAt
  145. createdAt: Date
  146. @UpdatedAt
  147. updatedAt: Date
  148. @ForeignKey(() => ActorModel)
  149. @Column
  150. actorId: number
  151. @BelongsTo(() => ActorModel, {
  152. foreignKey: {
  153. allowNull: false
  154. },
  155. onDelete: 'cascade'
  156. })
  157. Actor: Awaited<ActorModel>
  158. @ForeignKey(() => UserModel)
  159. @Column
  160. userId: number
  161. @BelongsTo(() => UserModel, {
  162. foreignKey: {
  163. allowNull: true
  164. },
  165. onDelete: 'cascade'
  166. })
  167. User: Awaited<UserModel>
  168. @ForeignKey(() => ApplicationModel)
  169. @Column
  170. applicationId: number
  171. @BelongsTo(() => ApplicationModel, {
  172. foreignKey: {
  173. allowNull: true
  174. },
  175. onDelete: 'cascade'
  176. })
  177. Application: Awaited<ApplicationModel>
  178. @HasMany(() => VideoChannelModel, {
  179. foreignKey: {
  180. allowNull: false
  181. },
  182. onDelete: 'cascade',
  183. hooks: true
  184. })
  185. VideoChannels: Awaited<VideoChannelModel>[]
  186. @HasMany(() => VideoPlaylistModel, {
  187. foreignKey: {
  188. allowNull: false
  189. },
  190. onDelete: 'cascade',
  191. hooks: true
  192. })
  193. VideoPlaylists: Awaited<VideoPlaylistModel>[]
  194. @HasMany(() => VideoCommentModel, {
  195. foreignKey: {
  196. allowNull: true
  197. },
  198. onDelete: 'cascade',
  199. hooks: true
  200. })
  201. VideoComments: Awaited<VideoCommentModel>[]
  202. @HasMany(() => AccountBlocklistModel, {
  203. foreignKey: {
  204. name: 'targetAccountId',
  205. allowNull: false
  206. },
  207. as: 'BlockedBy',
  208. onDelete: 'CASCADE'
  209. })
  210. BlockedBy: Awaited<AccountBlocklistModel>[]
  211. @HasMany(() => AccountAutomaticTagPolicyModel, {
  212. foreignKey: {
  213. name: 'accountId',
  214. allowNull: false
  215. },
  216. onDelete: 'cascade'
  217. })
  218. AccountAutomaticTagPolicies: Awaited<AccountAutomaticTagPolicyModel>[]
  219. @HasMany(() => CommentAutomaticTagModel, {
  220. foreignKey: 'accountId',
  221. onDelete: 'CASCADE'
  222. })
  223. CommentAutomaticTags: Awaited<CommentAutomaticTagModel>[]
  224. @HasMany(() => VideoAutomaticTagModel, {
  225. foreignKey: 'accountId',
  226. onDelete: 'CASCADE'
  227. })
  228. VideoAutomaticTags: Awaited<VideoAutomaticTagModel>[]
  229. @BeforeDestroy
  230. static async sendDeleteIfOwned (instance: AccountModel, options) {
  231. if (!instance.Actor) {
  232. instance.Actor = await instance.$get('Actor', { transaction: options.transaction })
  233. }
  234. await ActorFollowModel.removeFollowsOf(instance.Actor.id, options.transaction)
  235. if (instance.isOwned()) {
  236. return sendDeleteActor(instance.Actor, options.transaction)
  237. }
  238. return undefined
  239. }
  240. // ---------------------------------------------------------------------------
  241. static getSQLAttributes (tableName: string, aliasPrefix = '') {
  242. return buildSQLAttributes({
  243. model: this,
  244. tableName,
  245. aliasPrefix
  246. })
  247. }
  248. // ---------------------------------------------------------------------------
  249. static load (id: number, transaction?: Transaction): Promise<MAccountDefault> {
  250. return AccountModel.findByPk(id, { transaction })
  251. }
  252. static loadByNameWithHost (nameWithHost: string): Promise<MAccountDefault> {
  253. const [ accountName, host ] = nameWithHost.split('@')
  254. if (!host || host === WEBSERVER.HOST) return AccountModel.loadLocalByName(accountName)
  255. return AccountModel.loadByNameAndHost(accountName, host)
  256. }
  257. static loadLocalByName (name: string): Promise<MAccountDefault> {
  258. const fun = () => {
  259. const query = {
  260. where: {
  261. [Op.or]: [
  262. {
  263. userId: {
  264. [Op.ne]: null
  265. }
  266. },
  267. {
  268. applicationId: {
  269. [Op.ne]: null
  270. }
  271. }
  272. ]
  273. },
  274. include: [
  275. {
  276. model: ActorModel,
  277. required: true,
  278. where: ActorModel.wherePreferredUsername(name)
  279. }
  280. ]
  281. }
  282. return AccountModel.findOne(query)
  283. }
  284. return ModelCache.Instance.doCache({
  285. cacheType: 'server-account',
  286. key: name,
  287. fun,
  288. // The server actor never change, so we can easily cache it
  289. whitelist: () => name === SERVER_ACTOR_NAME
  290. })
  291. }
  292. static loadByNameAndHost (name: string, host: string): Promise<MAccountDefault> {
  293. const query = {
  294. include: [
  295. {
  296. model: ActorModel,
  297. required: true,
  298. where: ActorModel.wherePreferredUsername(name),
  299. include: [
  300. {
  301. model: ServerModel,
  302. required: true,
  303. where: {
  304. host
  305. }
  306. }
  307. ]
  308. }
  309. ]
  310. }
  311. return AccountModel.findOne(query)
  312. }
  313. static loadByUrl (url: string, transaction?: Transaction): Promise<MAccountDefault> {
  314. const query = {
  315. include: [
  316. {
  317. model: ActorModel,
  318. required: true,
  319. where: {
  320. url
  321. }
  322. }
  323. ],
  324. transaction
  325. }
  326. return AccountModel.findOne(query)
  327. }
  328. static listForApi (start: number, count: number, sort: string) {
  329. const query = {
  330. offset: start,
  331. limit: count,
  332. order: getSort(sort)
  333. }
  334. return Promise.all([
  335. AccountModel.count(),
  336. AccountModel.findAll(query)
  337. ]).then(([ total, data ]) => ({ total, data }))
  338. }
  339. static loadAccountIdFromVideo (videoId: number): Promise<MAccount> {
  340. const query = {
  341. include: [
  342. {
  343. attributes: [ 'id', 'accountId' ],
  344. model: VideoChannelModel.unscoped(),
  345. required: true,
  346. include: [
  347. {
  348. attributes: [ 'id', 'channelId' ],
  349. model: VideoModel.unscoped(),
  350. where: {
  351. id: videoId
  352. }
  353. }
  354. ]
  355. }
  356. ]
  357. }
  358. return AccountModel.findOne(query)
  359. }
  360. static listLocalsForSitemap (sort: string): Promise<MAccountHost[]> {
  361. const query = {
  362. attributes: [ ],
  363. offset: 0,
  364. order: getSort(sort),
  365. include: [
  366. {
  367. attributes: [ 'preferredUsername', 'serverId' ],
  368. model: ActorModel.unscoped(),
  369. where: {
  370. serverId: null
  371. }
  372. }
  373. ]
  374. }
  375. return AccountModel
  376. .unscoped()
  377. .findAll(query)
  378. }
  379. toFormattedJSON (this: MAccountFormattable): Account {
  380. return {
  381. ...this.Actor.toFormattedJSON(false),
  382. id: this.id,
  383. displayName: this.getDisplayName(),
  384. description: this.description,
  385. updatedAt: this.updatedAt,
  386. userId: this.userId ?? undefined
  387. }
  388. }
  389. toFormattedSummaryJSON (this: MAccountSummaryFormattable): AccountSummary {
  390. const actor = this.Actor.toFormattedSummaryJSON()
  391. return {
  392. id: this.id,
  393. displayName: this.getDisplayName(),
  394. name: actor.name,
  395. url: actor.url,
  396. host: actor.host,
  397. avatars: actor.avatars
  398. }
  399. }
  400. async toActivityPubObject (this: MAccountAP) {
  401. const obj = await this.Actor.toActivityPubObject(this.name)
  402. return Object.assign(obj, {
  403. summary: this.description
  404. })
  405. }
  406. isOwned () {
  407. return this.Actor.isOwned()
  408. }
  409. isOutdated () {
  410. return this.Actor.isOutdated()
  411. }
  412. getDisplayName () {
  413. return this.name
  414. }
  415. // Avoid error when running this method on MAccount... | MChannel...
  416. getClientUrl (this: MAccountHost | MChannelHost) {
  417. return WEBSERVER.URL + '/a/' + this.Actor.getIdentifier() + '/video-channels'
  418. }
  419. isBlocked () {
  420. return this.BlockedBy && this.BlockedBy.length !== 0
  421. }
  422. }