actor.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. import * as Bluebird from 'bluebird'
  2. import { Transaction } from 'sequelize'
  3. import * as url from 'url'
  4. import * as uuidv4 from 'uuid/v4'
  5. import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub'
  6. import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects'
  7. import { checkUrlsSameHost, getAPId } from '../../helpers/activitypub'
  8. import { sanitizeAndCheckActorObject } from '../../helpers/custom-validators/activitypub/actor'
  9. import { isActivityPubUrlValid } from '../../helpers/custom-validators/activitypub/misc'
  10. import { retryTransactionWrapper, updateInstanceWithAnother } from '../../helpers/database-utils'
  11. import { logger } from '../../helpers/logger'
  12. import { createPrivateAndPublicKeys } from '../../helpers/peertube-crypto'
  13. import { doRequest } from '../../helpers/requests'
  14. import { getUrlFromWebfinger } from '../../helpers/webfinger'
  15. import { MIMETYPES, WEBSERVER } from '../../initializers/constants'
  16. import { AccountModel } from '../../models/account/account'
  17. import { ActorModel } from '../../models/activitypub/actor'
  18. import { AvatarModel } from '../../models/avatar/avatar'
  19. import { ServerModel } from '../../models/server/server'
  20. import { VideoChannelModel } from '../../models/video/video-channel'
  21. import { JobQueue } from '../job-queue'
  22. import { getServerActor } from '../../helpers/utils'
  23. import { ActorFetchByUrlType, fetchActorByUrl } from '../../helpers/actor'
  24. import { sequelizeTypescript } from '../../initializers/database'
  25. import {
  26. MAccount,
  27. MActor,
  28. MActorAccountChannelId,
  29. MActorAccountId,
  30. MActorDefault,
  31. MActorFull,
  32. MActorId,
  33. MActorAccountChannelIdActor,
  34. MChannel,
  35. MActorFullActor, MAccountActorDefault, MChannelActorDefault, MChannelActorAccountDefault
  36. } from '../../typings/models'
  37. // Set account keys, this could be long so process after the account creation and do not block the client
  38. function setAsyncActorKeys (actor: MActor) {
  39. return createPrivateAndPublicKeys()
  40. .then(({ publicKey, privateKey }) => {
  41. actor.publicKey = publicKey
  42. actor.privateKey = privateKey
  43. return actor.save()
  44. })
  45. .catch(err => {
  46. logger.error('Cannot set public/private keys of actor %d.', actor.url, { err })
  47. return actor
  48. })
  49. }
  50. function getOrCreateActorAndServerAndModel (
  51. activityActor: string | ActivityPubActor,
  52. fetchType: 'all',
  53. recurseIfNeeded?: boolean,
  54. updateCollections?: boolean
  55. ): Promise<MActorFullActor>
  56. function getOrCreateActorAndServerAndModel (
  57. activityActor: string | ActivityPubActor,
  58. fetchType?: 'association-ids',
  59. recurseIfNeeded?: boolean,
  60. updateCollections?: boolean
  61. ): Promise<MActorAccountChannelId>
  62. async function getOrCreateActorAndServerAndModel (
  63. activityActor: string | ActivityPubActor,
  64. fetchType: ActorFetchByUrlType = 'association-ids',
  65. recurseIfNeeded = true,
  66. updateCollections = false
  67. ): Promise<MActorFullActor | MActorAccountChannelId> {
  68. const actorUrl = getAPId(activityActor)
  69. let created = false
  70. let accountPlaylistsUrl: string
  71. let actor = await fetchActorByUrl(actorUrl, fetchType)
  72. // Orphan actor (not associated to an account of channel) so recreate it
  73. if (actor && (!actor.Account && !actor.VideoChannel)) {
  74. await actor.destroy()
  75. actor = null
  76. }
  77. // We don't have this actor in our database, fetch it on remote
  78. if (!actor) {
  79. const { result } = await fetchRemoteActor(actorUrl)
  80. if (result === undefined) throw new Error('Cannot fetch remote actor ' + actorUrl)
  81. // Create the attributed to actor
  82. // In PeerTube a video channel is owned by an account
  83. let ownerActor: MActorFullActor
  84. if (recurseIfNeeded === true && result.actor.type === 'Group') {
  85. const accountAttributedTo = result.attributedTo.find(a => a.type === 'Person')
  86. if (!accountAttributedTo) throw new Error('Cannot find account attributed to video channel ' + actor.url)
  87. if (checkUrlsSameHost(accountAttributedTo.id, actorUrl) !== true) {
  88. throw new Error(`Account attributed to ${accountAttributedTo.id} does not have the same host than actor url ${actorUrl}`)
  89. }
  90. try {
  91. // Don't recurse another time
  92. const recurseIfNeeded = false
  93. ownerActor = await getOrCreateActorAndServerAndModel(accountAttributedTo.id, 'all', recurseIfNeeded)
  94. } catch (err) {
  95. logger.error('Cannot get or create account attributed to video channel ' + actor.url)
  96. throw new Error(err)
  97. }
  98. }
  99. actor = await retryTransactionWrapper(saveActorAndServerAndModelIfNotExist, result, ownerActor)
  100. created = true
  101. accountPlaylistsUrl = result.playlists
  102. }
  103. if (actor.Account) (actor as MActorAccountChannelIdActor).Account.Actor = actor
  104. if (actor.VideoChannel) (actor as MActorAccountChannelIdActor).VideoChannel.Actor = actor
  105. const { actor: actorRefreshed, refreshed } = await retryTransactionWrapper(refreshActorIfNeeded, actor, fetchType)
  106. if (!actorRefreshed) throw new Error('Actor ' + actorRefreshed.url + ' does not exist anymore.')
  107. if ((created === true || refreshed === true) && updateCollections === true) {
  108. const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' }
  109. await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
  110. }
  111. // We created a new account: fetch the playlists
  112. if (created === true && actor.Account && accountPlaylistsUrl) {
  113. const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' }
  114. await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
  115. }
  116. return actorRefreshed
  117. }
  118. function buildActorInstance (type: ActivityPubActorType, url: string, preferredUsername: string, uuid?: string) {
  119. return new ActorModel({
  120. type,
  121. url,
  122. preferredUsername,
  123. uuid,
  124. publicKey: null,
  125. privateKey: null,
  126. followersCount: 0,
  127. followingCount: 0,
  128. inboxUrl: url + '/inbox',
  129. outboxUrl: url + '/outbox',
  130. sharedInboxUrl: WEBSERVER.URL + '/inbox',
  131. followersUrl: url + '/followers',
  132. followingUrl: url + '/following'
  133. })
  134. }
  135. async function updateActorInstance (actorInstance: ActorModel, attributes: ActivityPubActor) {
  136. const followersCount = await fetchActorTotalItems(attributes.followers)
  137. const followingCount = await fetchActorTotalItems(attributes.following)
  138. actorInstance.type = attributes.type
  139. actorInstance.preferredUsername = attributes.preferredUsername
  140. actorInstance.url = attributes.id
  141. actorInstance.publicKey = attributes.publicKey.publicKeyPem
  142. actorInstance.followersCount = followersCount
  143. actorInstance.followingCount = followingCount
  144. actorInstance.inboxUrl = attributes.inbox
  145. actorInstance.outboxUrl = attributes.outbox
  146. actorInstance.sharedInboxUrl = attributes.endpoints.sharedInbox
  147. actorInstance.followersUrl = attributes.followers
  148. actorInstance.followingUrl = attributes.following
  149. }
  150. type AvatarInfo = { name: string, onDisk: boolean, fileUrl: string }
  151. async function updateActorAvatarInstance (actor: MActorDefault, info: AvatarInfo, t: Transaction) {
  152. if (info.name !== undefined) {
  153. if (actor.avatarId) {
  154. try {
  155. await actor.Avatar.destroy({ transaction: t })
  156. } catch (err) {
  157. logger.error('Cannot remove old avatar of actor %s.', actor.url, { err })
  158. }
  159. }
  160. const avatar = await AvatarModel.create({
  161. filename: info.name,
  162. onDisk: info.onDisk,
  163. fileUrl: info.fileUrl
  164. }, { transaction: t })
  165. actor.avatarId = avatar.id
  166. actor.Avatar = avatar
  167. }
  168. return actor
  169. }
  170. async function fetchActorTotalItems (url: string) {
  171. const options = {
  172. uri: url,
  173. method: 'GET',
  174. json: true,
  175. activityPub: true
  176. }
  177. try {
  178. const { body } = await doRequest(options)
  179. return body.totalItems ? body.totalItems : 0
  180. } catch (err) {
  181. logger.warn('Cannot fetch remote actor count %s.', url, { err })
  182. return 0
  183. }
  184. }
  185. async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) {
  186. if (
  187. actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined &&
  188. isActivityPubUrlValid(actorJSON.icon.url)
  189. ) {
  190. const extension = MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType]
  191. return {
  192. name: uuidv4() + extension,
  193. fileUrl: actorJSON.icon.url
  194. }
  195. }
  196. return undefined
  197. }
  198. async function addFetchOutboxJob (actor: Pick<ActorModel, 'id' | 'outboxUrl'>) {
  199. // Don't fetch ourselves
  200. const serverActor = await getServerActor()
  201. if (serverActor.id === actor.id) {
  202. logger.error('Cannot fetch our own outbox!')
  203. return undefined
  204. }
  205. const payload = {
  206. uri: actor.outboxUrl,
  207. type: 'activity' as 'activity'
  208. }
  209. return JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })
  210. }
  211. async function refreshActorIfNeeded <T extends MActorFull | MActorAccountChannelId> (
  212. actorArg: T,
  213. fetchedType: ActorFetchByUrlType
  214. ): Promise<{ actor: T | MActorFull, refreshed: boolean }> {
  215. if (!actorArg.isOutdated()) return { actor: actorArg, refreshed: false }
  216. // We need more attributes
  217. const actor = fetchedType === 'all'
  218. ? actorArg as MActorFull
  219. : await ActorModel.loadByUrlAndPopulateAccountAndChannel(actorArg.url)
  220. try {
  221. let actorUrl: string
  222. try {
  223. actorUrl = await getUrlFromWebfinger(actor.preferredUsername + '@' + actor.getHost())
  224. } catch (err) {
  225. logger.warn('Cannot get actor URL from webfinger, keeping the old one.', err)
  226. actorUrl = actor.url
  227. }
  228. const { result, statusCode } = await fetchRemoteActor(actorUrl)
  229. if (statusCode === 404) {
  230. logger.info('Deleting actor %s because there is a 404 in refresh actor.', actor.url)
  231. actor.Account ? actor.Account.destroy() : actor.VideoChannel.destroy()
  232. return { actor: undefined, refreshed: false }
  233. }
  234. if (result === undefined) {
  235. logger.warn('Cannot fetch remote actor in refresh actor.')
  236. return { actor, refreshed: false }
  237. }
  238. return sequelizeTypescript.transaction(async t => {
  239. updateInstanceWithAnother(actor, result.actor)
  240. if (result.avatar !== undefined) {
  241. const avatarInfo = {
  242. name: result.avatar.name,
  243. fileUrl: result.avatar.fileUrl,
  244. onDisk: false
  245. }
  246. await updateActorAvatarInstance(actor, avatarInfo, t)
  247. }
  248. // Force update
  249. actor.setDataValue('updatedAt', new Date())
  250. await actor.save({ transaction: t })
  251. if (actor.Account) {
  252. actor.Account.name = result.name
  253. actor.Account.description = result.summary
  254. await actor.Account.save({ transaction: t })
  255. } else if (actor.VideoChannel) {
  256. actor.VideoChannel.name = result.name
  257. actor.VideoChannel.description = result.summary
  258. actor.VideoChannel.support = result.support
  259. await actor.VideoChannel.save({ transaction: t })
  260. }
  261. return { refreshed: true, actor }
  262. })
  263. } catch (err) {
  264. logger.warn('Cannot refresh actor %s.', actor.url, { err })
  265. return { actor, refreshed: false }
  266. }
  267. }
  268. export {
  269. getOrCreateActorAndServerAndModel,
  270. buildActorInstance,
  271. setAsyncActorKeys,
  272. fetchActorTotalItems,
  273. getAvatarInfoIfExists,
  274. updateActorInstance,
  275. refreshActorIfNeeded,
  276. updateActorAvatarInstance,
  277. addFetchOutboxJob
  278. }
  279. // ---------------------------------------------------------------------------
  280. function saveActorAndServerAndModelIfNotExist (
  281. result: FetchRemoteActorResult,
  282. ownerActor?: MActorFullActor,
  283. t?: Transaction
  284. ): Bluebird<MActorFullActor> | Promise<MActorFullActor> {
  285. let actor = result.actor
  286. if (t !== undefined) return save(t)
  287. return sequelizeTypescript.transaction(t => save(t))
  288. async function save (t: Transaction) {
  289. const actorHost = url.parse(actor.url).host
  290. const serverOptions = {
  291. where: {
  292. host: actorHost
  293. },
  294. defaults: {
  295. host: actorHost
  296. },
  297. transaction: t
  298. }
  299. const [ server ] = await ServerModel.findOrCreate(serverOptions)
  300. // Save our new account in database
  301. actor.serverId = server.id
  302. // Avatar?
  303. if (result.avatar) {
  304. const avatar = await AvatarModel.create({
  305. filename: result.avatar.name,
  306. fileUrl: result.avatar.fileUrl,
  307. onDisk: false
  308. }, { transaction: t })
  309. actor.avatarId = avatar.id
  310. }
  311. // Force the actor creation, sometimes Sequelize skips the save() when it thinks the instance already exists
  312. // (which could be false in a retried query)
  313. const [ actorCreated ] = await ActorModel.findOrCreate<MActorFullActor>({
  314. defaults: actor.toJSON(),
  315. where: {
  316. url: actor.url
  317. },
  318. transaction: t
  319. })
  320. if (actorCreated.type === 'Person' || actorCreated.type === 'Application') {
  321. actorCreated.Account = await saveAccount(actorCreated, result, t) as MAccountActorDefault
  322. actorCreated.Account.Actor = actorCreated
  323. } else if (actorCreated.type === 'Group') { // Video channel
  324. actorCreated.VideoChannel = await saveVideoChannel(actorCreated, result, ownerActor, t) as MChannelActorAccountDefault
  325. actorCreated.VideoChannel.Actor = actorCreated
  326. actorCreated.VideoChannel.Account = ownerActor.Account
  327. }
  328. actorCreated.Server = server
  329. return actorCreated
  330. }
  331. }
  332. type FetchRemoteActorResult = {
  333. actor: MActor
  334. name: string
  335. summary: string
  336. support?: string
  337. playlists?: string
  338. avatar?: {
  339. name: string,
  340. fileUrl: string
  341. }
  342. attributedTo: ActivityPubAttributedTo[]
  343. }
  344. async function fetchRemoteActor (actorUrl: string): Promise<{ statusCode?: number, result: FetchRemoteActorResult }> {
  345. const options = {
  346. uri: actorUrl,
  347. method: 'GET',
  348. json: true,
  349. activityPub: true
  350. }
  351. logger.info('Fetching remote actor %s.', actorUrl)
  352. const requestResult = await doRequest<ActivityPubActor>(options)
  353. const actorJSON = requestResult.body
  354. if (sanitizeAndCheckActorObject(actorJSON) === false) {
  355. logger.debug('Remote actor JSON is not valid.', { actorJSON })
  356. return { result: undefined, statusCode: requestResult.response.statusCode }
  357. }
  358. if (checkUrlsSameHost(actorJSON.id, actorUrl) !== true) {
  359. logger.warn('Actor url %s has not the same host than its AP id %s', actorUrl, actorJSON.id)
  360. return { result: undefined, statusCode: requestResult.response.statusCode }
  361. }
  362. const followersCount = await fetchActorTotalItems(actorJSON.followers)
  363. const followingCount = await fetchActorTotalItems(actorJSON.following)
  364. const actor = new ActorModel({
  365. type: actorJSON.type,
  366. preferredUsername: actorJSON.preferredUsername,
  367. url: actorJSON.id,
  368. publicKey: actorJSON.publicKey.publicKeyPem,
  369. privateKey: null,
  370. followersCount: followersCount,
  371. followingCount: followingCount,
  372. inboxUrl: actorJSON.inbox,
  373. outboxUrl: actorJSON.outbox,
  374. sharedInboxUrl: actorJSON.endpoints.sharedInbox,
  375. followersUrl: actorJSON.followers,
  376. followingUrl: actorJSON.following
  377. })
  378. const avatarInfo = await getAvatarInfoIfExists(actorJSON)
  379. const name = actorJSON.name || actorJSON.preferredUsername
  380. return {
  381. statusCode: requestResult.response.statusCode,
  382. result: {
  383. actor,
  384. name,
  385. avatar: avatarInfo,
  386. summary: actorJSON.summary,
  387. support: actorJSON.support,
  388. playlists: actorJSON.playlists,
  389. attributedTo: actorJSON.attributedTo
  390. }
  391. }
  392. }
  393. async function saveAccount (actor: MActorId, result: FetchRemoteActorResult, t: Transaction) {
  394. const [ accountCreated ] = await AccountModel.findOrCreate({
  395. defaults: {
  396. name: result.name,
  397. description: result.summary,
  398. actorId: actor.id
  399. },
  400. where: {
  401. actorId: actor.id
  402. },
  403. transaction: t
  404. })
  405. return accountCreated as MAccount
  406. }
  407. async function saveVideoChannel (actor: MActorId, result: FetchRemoteActorResult, ownerActor: MActorAccountId, t: Transaction) {
  408. const [ videoChannelCreated ] = await VideoChannelModel.findOrCreate({
  409. defaults: {
  410. name: result.name,
  411. description: result.summary,
  412. support: result.support,
  413. actorId: actor.id,
  414. accountId: ownerActor.Account.id
  415. },
  416. where: {
  417. actorId: actor.id
  418. },
  419. transaction: t
  420. })
  421. return videoChannelCreated as MChannel
  422. }