2
1

actor.ts 15 KB

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