X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fcontrollers%2Fapi%2Fserver%2Ffollows.ts;h=c87107197e585f9313a3752882a3aac2d7396c3f;hb=85cd9bde5a93500f973773f46680c07dd90d5912;hp=c2fb37c39a451059931ec5609be50a4a1e81a535;hpb=a2431b7dcbc72c05101dcdbe631ff84a823aeb51;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/controllers/api/server/follows.ts b/server/controllers/api/server/follows.ts index c2fb37c39..c87107197 100644 --- a/server/controllers/api/server/follows.ts +++ b/server/controllers/api/server/follows.ts @@ -1,24 +1,20 @@ import * as express from 'express' -import { UserRight } from '../../../../shared/models/users/user-right.enum' -import { getFormattedObjects } from '../../../helpers' +import { UserRight } from '../../../../shared/models/users' +import { sanitizeHost } from '../../../helpers/core-utils' import { retryTransactionWrapper } from '../../../helpers/database-utils' import { logger } from '../../../helpers/logger' -import { getServerAccount } from '../../../helpers/utils' -import { getAccountFromWebfinger } from '../../../helpers/webfinger' -import { SERVER_ACCOUNT_NAME } from '../../../initializers/constants' -import { database as db } from '../../../initializers/database' -import { saveAccountAndServerIfNotExist } from '../../../lib/activitypub/account' -import { sendUndoFollow } from '../../../lib/activitypub/send/send-undo' -import { sendFollow } from '../../../lib/index' -import { asyncMiddleware, paginationValidator, removeFollowingValidator, setFollowersSort, setPagination } from '../../../middlewares' -import { authenticate } from '../../../middlewares/oauth' -import { setBodyHostsPort } from '../../../middlewares/servers' -import { setFollowingSort } from '../../../middlewares/sort' -import { ensureUserHasRight } from '../../../middlewares/user-right' -import { followValidator } from '../../../middlewares/validators/follows' -import { followersSortValidator, followingSortValidator } from '../../../middlewares/validators/sort' -import { AccountInstance } from '../../../models/account/account-interface' -import { AccountFollowInstance } from '../../../models/index' +import { getFormattedObjects, getServerActor } from '../../../helpers/utils' +import { loadActorUrlOrGetFromWebfinger } from '../../../helpers/webfinger' +import { REMOTE_SCHEME, sequelizeTypescript, SERVER_ACTOR_NAME } from '../../../initializers' +import { getOrCreateActorAndServerAndModel } from '../../../lib/activitypub/actor' +import { sendFollow, sendUndoFollow } from '../../../lib/activitypub/send' +import { + asyncMiddleware, authenticate, ensureUserHasRight, paginationValidator, removeFollowingValidator, setBodyHostsPort, + setFollowersSort, setFollowingSort, setPagination +} from '../../../middlewares' +import { followersSortValidator, followingSortValidator, followValidator } from '../../../middlewares/validators' +import { ActorModel } from '../../../models/activitypub/actor' +import { ActorFollowModel } from '../../../models/activitypub/actor-follow' const serverFollowsRouter = express.Router() @@ -38,7 +34,7 @@ serverFollowsRouter.post('/following', asyncMiddleware(followRetry) ) -serverFollowsRouter.delete('/following/:accountId', +serverFollowsRouter.delete('/following/:host', authenticate, ensureUserHasRight(UserRight.MANAGE_SERVER_FOLLOW), asyncMiddleware(removeFollowingValidator), @@ -62,43 +58,43 @@ export { // --------------------------------------------------------------------------- async function listFollowing (req: express.Request, res: express.Response, next: express.NextFunction) { - const serverAccount = await getServerAccount() - const resultList = await db.AccountFollow.listFollowingForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort) + const serverActor = await getServerActor() + const resultList = await ActorFollowModel.listFollowingForApi(serverActor.id, req.query.start, req.query.count, req.query.sort) return res.json(getFormattedObjects(resultList.data, resultList.total)) } async function listFollowers (req: express.Request, res: express.Response, next: express.NextFunction) { - const serverAccount = await getServerAccount() - const resultList = await db.AccountFollow.listFollowersForApi(serverAccount.id, req.query.start, req.query.count, req.query.sort) + const serverActor = await getServerActor() + const resultList = await ActorFollowModel.listFollowersForApi(serverActor.id, req.query.start, req.query.count, req.query.sort) return res.json(getFormattedObjects(resultList.data, resultList.total)) } async function followRetry (req: express.Request, res: express.Response, next: express.NextFunction) { const hosts = req.body.hosts as string[] - const fromAccount = await getServerAccount() + const fromActor = await getServerActor() const tasks: Promise[] = [] - const accountName = SERVER_ACCOUNT_NAME + const actorName = SERVER_ACTOR_NAME for (const host of hosts) { + const sanitizedHost = sanitizeHost(host, REMOTE_SCHEME.HTTP) // We process each host in a specific transaction // First, we add the follow request in the database - // Then we send the follow request to other account - const p = loadLocalOrGetAccountFromWebfinger(accountName, host) - .then(accountResult => { - let targetAccount = accountResult.account - + // Then we send the follow request to other actor + const p = loadActorUrlOrGetFromWebfinger(actorName, sanitizedHost) + .then(actorUrl => getOrCreateActorAndServerAndModel(actorUrl)) + .then(targetActor => { const options = { - arguments: [ fromAccount, targetAccount, accountResult.loadedFromDB ], + arguments: [ fromActor, targetActor ], errorMessage: 'Cannot follow with many retries.' } return retryTransactionWrapper(follow, options) }) - .catch(err => logger.warn('Cannot follow server %s.', `${accountName}@${host}`, err)) + .catch(err => logger.warn('Cannot follow server %s.', sanitizedHost, err)) tasks.push(p) } @@ -110,67 +106,44 @@ async function followRetry (req: express.Request, res: express.Response, next: e return res.status(204).end() } -async function follow (fromAccount: AccountInstance, targetAccount: AccountInstance, targetAlreadyInDB: boolean) { - try { - await db.sequelize.transaction(async t => { - if (targetAlreadyInDB === false) { - await saveAccountAndServerIfNotExist(targetAccount, t) - } - - const [ accountFollow ] = await db.AccountFollow.findOrCreate({ - where: { - accountId: fromAccount.id, - targetAccountId: targetAccount.id - }, - defaults: { - state: 'pending', - accountId: fromAccount.id, - targetAccountId: targetAccount.id - }, - transaction: t - }) - accountFollow.AccountFollowing = targetAccount - accountFollow.AccountFollower = fromAccount - - // Send a notification to remote server - if (accountFollow.state === 'pending') { - await sendFollow(accountFollow, t) - } +function follow (fromActor: ActorModel, targetActor: ActorModel) { + return sequelizeTypescript.transaction(async t => { + const [ actorFollow ] = await ActorFollowModel.findOrCreate({ + where: { + actorId: fromActor.id, + targetActorId: targetActor.id + }, + defaults: { + state: 'pending', + actorId: fromActor.id, + targetActorId: targetActor.id + }, + transaction: t }) - } catch (err) { - // Reset target account - targetAccount.isNewRecord = !targetAlreadyInDB - throw err - } + actorFollow.ActorFollowing = targetActor + actorFollow.ActorFollower = fromActor + + // Send a notification to remote server + if (actorFollow.state === 'pending') { + await sendFollow(actorFollow, t) + } + }) } async function removeFollow (req: express.Request, res: express.Response, next: express.NextFunction) { - const follow: AccountFollowInstance = res.locals.follow + const follow: ActorFollowModel = res.locals.follow - await db.sequelize.transaction(async t => { + await sequelizeTypescript.transaction(async t => { if (follow.state === 'accepted') await sendUndoFollow(follow, t) await follow.destroy({ transaction: t }) }) - // Destroy the account that will destroy video channels, videos and video files too + // Destroy the actor that will destroy video channels, videos and video files too // This could be long so don't wait this task - const following = follow.AccountFollowing + const following = follow.ActorFollowing following.destroy() - .catch(err => logger.error('Cannot destroy account that we do not follow anymore %s.', following.url, err)) + .catch(err => logger.error('Cannot destroy actor that we do not follow anymore %s.', following.url, err)) return res.status(204).end() } - -async function loadLocalOrGetAccountFromWebfinger (name: string, host: string) { - let loadedFromDB = true - let account = await db.Account.loadByNameAndHost(name, host) - - if (!account) { - const nameWithDomain = name + '@' + host - account = await getAccountFromWebfinger(nameWithDomain) - loadedFromDB = false - } - - return { account, loadedFromDB } -}