X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fcontrollers%2Fapi%2Faccounts.ts;h=5a1d652f237ec98c8ae178b40fe8bf4f0f5a3da2;hb=89cd12756035a146bbcc4db78cd3cd64f2f3d88d;hp=85987c912faca8eabd05139412b548233b5407f0;hpb=6b738c7a31591a83fdcd9c78b6b1f98e543c378b;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/controllers/api/accounts.ts b/server/controllers/api/accounts.ts index 85987c912..5a1d652f2 100644 --- a/server/controllers/api/accounts.ts +++ b/server/controllers/api/accounts.ts @@ -1,30 +1,33 @@ import * as express from 'express' -import { getFormattedObjects, resetSequelizeInstance } from '../../helpers/utils' +import { getFormattedObjects, getServerActor } from '../../helpers/utils' import { asyncMiddleware, authenticate, - listVideoAccountChannelsValidator, + commonVideosFiltersValidator, optionalAuthenticate, paginationValidator, setDefaultPagination, setDefaultSort, - videoChannelsAddValidator, - videoChannelsGetValidator, - videoChannelsRemoveValidator, - videoChannelsUpdateValidator + videoPlaylistsSortValidator, + videoRatesSortValidator, + videoRatingValidator } from '../../middlewares' -import { accountsGetValidator, accountsSortValidator, videosSortValidator } from '../../middlewares/validators' +import { + accountNameWithHostGetValidator, + accountsSortValidator, + ensureAuthUserOwnsAccountValidator, + videosSortValidator, + videoChannelsSortValidator +} from '../../middlewares/validators' import { AccountModel } from '../../models/account/account' +import { AccountVideoRateModel } from '../../models/account/account-video-rate' import { VideoModel } from '../../models/video/video' -import { isNSFWHidden } from '../../helpers/express-utils' +import { buildNSFWFilter, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils' import { VideoChannelModel } from '../../models/video/video-channel' -import { VideoChannelCreate, VideoChannelUpdate } from '../../../shared' -import { sendUpdateActor } from '../../lib/activitypub/send' -import { createVideoChannel } from '../../lib/video-channel' -import { setAsyncActorKeys } from '../../lib/activitypub' -import { sequelizeTypescript } from '../../initializers' +import { JobQueue } from '../../lib/job-queue' import { logger } from '../../helpers/logger' -import { retryTransactionWrapper } from '../../helpers/database-utils' +import { VideoPlaylistModel } from '../../models/video/video-playlist' +import { commonVideoPlaylistFiltersValidator } from '../../middlewares/validators/videos/video-playlists' const accountsRouter = express.Router() @@ -36,57 +39,52 @@ accountsRouter.get('/', asyncMiddleware(listAccounts) ) -accountsRouter.get('/:id', - asyncMiddleware(accountsGetValidator), +accountsRouter.get('/:accountName', + asyncMiddleware(accountNameWithHostGetValidator), getAccount ) -accountsRouter.get('/:id/videos', - asyncMiddleware(accountsGetValidator), +accountsRouter.get('/:accountName/videos', + asyncMiddleware(accountNameWithHostGetValidator), paginationValidator, videosSortValidator, setDefaultSort, setDefaultPagination, optionalAuthenticate, + commonVideosFiltersValidator, asyncMiddleware(listAccountVideos) ) -accountsRouter.get('/:accountId/video-channels', - asyncMiddleware(listVideoAccountChannelsValidator), - asyncMiddleware(listVideoAccountChannels) -) - -accountsRouter.post('/:accountId/video-channels', - authenticate, - videoChannelsAddValidator, - asyncMiddleware(addVideoChannelRetryWrapper) +accountsRouter.get('/:accountName/video-channels', + asyncMiddleware(accountNameWithHostGetValidator), + paginationValidator, + videoChannelsSortValidator, + setDefaultSort, + setDefaultPagination, + asyncMiddleware(listAccountChannels) ) -accountsRouter.put('/:accountId/video-channels/:id', - authenticate, - asyncMiddleware(videoChannelsUpdateValidator), - updateVideoChannelRetryWrapper +accountsRouter.get('/:accountName/video-playlists', + optionalAuthenticate, + asyncMiddleware(accountNameWithHostGetValidator), + paginationValidator, + videoPlaylistsSortValidator, + setDefaultSort, + setDefaultPagination, + commonVideoPlaylistFiltersValidator, + asyncMiddleware(listAccountPlaylists) ) -accountsRouter.delete('/:accountId/video-channels/:id', +accountsRouter.get('/:accountName/ratings', authenticate, - asyncMiddleware(videoChannelsRemoveValidator), - asyncMiddleware(removeVideoChannelRetryWrapper) -) - -accountsRouter.get('/:accountId/video-channels/:id', - asyncMiddleware(videoChannelsGetValidator), - asyncMiddleware(getVideoChannel) -) - -accountsRouter.get('/:accountId/video-channels/:id/videos', - asyncMiddleware(videoChannelsGetValidator), + asyncMiddleware(accountNameWithHostGetValidator), + ensureAuthUserOwnsAccountValidator, paginationValidator, - videosSortValidator, + videoRatesSortValidator, setDefaultSort, setDefaultPagination, - optionalAuthenticate, - asyncMiddleware(listVideoChannelVideos) + videoRatingValidator, + asyncMiddleware(listAccountRatings) ) // --------------------------------------------------------------------------- @@ -97,154 +95,92 @@ export { // --------------------------------------------------------------------------- -function getAccount (req: express.Request, res: express.Response, next: express.NextFunction) { - const account: AccountModel = res.locals.account +function getAccount (req: express.Request, res: express.Response) { + const account = res.locals.account + + if (account.isOutdated()) { + JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'actor', url: account.Actor.url } }) + .catch(err => logger.error('Cannot create AP refresher job for actor %s.', account.Actor.url, { err })) + } return res.json(account.toFormattedJSON()) } -async function listAccounts (req: express.Request, res: express.Response, next: express.NextFunction) { +async function listAccounts (req: express.Request, res: express.Response) { const resultList = await AccountModel.listForApi(req.query.start, req.query.count, req.query.sort) return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function listVideoAccountChannels (req: express.Request, res: express.Response, next: express.NextFunction) { - const resultList = await VideoChannelModel.listByAccount(res.locals.account.id) - - return res.json(getFormattedObjects(resultList.data, resultList.total)) -} - -// Wrapper to video channel add that retry the async function if there is a database error -// We need this because we run the transaction in SERIALIZABLE isolation that can fail -async function addVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { - const options = { - arguments: [ req, res ], - errorMessage: 'Cannot insert the video video channel with many retries.' - } - - const videoChannel = await retryTransactionWrapper(addVideoChannel, options) - return res.json({ - videoChannel: { - id: videoChannel.id, - uuid: videoChannel.Actor.uuid - } - }).end() -} - -async function addVideoChannel (req: express.Request, res: express.Response) { - const videoChannelInfo: VideoChannelCreate = req.body - const account: AccountModel = res.locals.oauth.token.User.Account - - const videoChannelCreated: VideoChannelModel = await sequelizeTypescript.transaction(async t => { - return createVideoChannel(videoChannelInfo, account, t) - }) - - setAsyncActorKeys(videoChannelCreated.Actor) - .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err })) - - logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid) - - return videoChannelCreated -} - -async function updateVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { +async function listAccountChannels (req: express.Request, res: express.Response) { const options = { - arguments: [ req, res ], - errorMessage: 'Cannot update the video with many retries.' + accountId: res.locals.account.id, + start: req.query.start, + count: req.query.count, + sort: req.query.sort } - await retryTransactionWrapper(updateVideoChannel, options) + const resultList = await VideoChannelModel.listByAccount(options) - return res.type('json').status(204).end() + return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function updateVideoChannel (req: express.Request, res: express.Response) { - const videoChannelInstance = res.locals.videoChannel as VideoChannelModel - const videoChannelFieldsSave = videoChannelInstance.toJSON() - const videoChannelInfoToUpdate = req.body as VideoChannelUpdate - - try { - await sequelizeTypescript.transaction(async t => { - const sequelizeOptions = { - transaction: t - } +async function listAccountPlaylists (req: express.Request, res: express.Response) { + const serverActor = await getServerActor() - if (videoChannelInfoToUpdate.name !== undefined) videoChannelInstance.set('name', videoChannelInfoToUpdate.name) - if (videoChannelInfoToUpdate.description !== undefined) videoChannelInstance.set('description', videoChannelInfoToUpdate.description) - if (videoChannelInfoToUpdate.support !== undefined) videoChannelInstance.set('support', videoChannelInfoToUpdate.support) - - const videoChannelInstanceUpdated = await videoChannelInstance.save(sequelizeOptions) - await sendUpdateActor(videoChannelInstanceUpdated, t) - }) - - logger.info('Video channel with name %s and uuid %s updated.', videoChannelInstance.name, videoChannelInstance.Actor.uuid) - } catch (err) { - logger.debug('Cannot update the video channel.', { err }) - - // Force fields we want to update - // If the transaction is retried, sequelize will think the object has not changed - // So it will skip the SQL request, even if the last one was ROLLBACKed! - resetSequelizeInstance(videoChannelInstance, videoChannelFieldsSave) - - throw err - } -} - -async function removeVideoChannelRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { - const options = { - arguments: [ req, res ], - errorMessage: 'Cannot remove the video channel with many retries.' + // Allow users to see their private/unlisted video playlists + let privateAndUnlisted = false + if (res.locals.oauth && res.locals.oauth.token.User.Account.id === res.locals.account.id) { + privateAndUnlisted = true } - await retryTransactionWrapper(removeVideoChannel, options) - - return res.type('json').status(204).end() -} - -async function removeVideoChannel (req: express.Request, res: express.Response) { - const videoChannelInstance: VideoChannelModel = res.locals.videoChannel - - return sequelizeTypescript.transaction(async t => { - await videoChannelInstance.destroy({ transaction: t }) - - logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid) + const resultList = await VideoPlaylistModel.listForApi({ + followerActorId: serverActor.id, + start: req.query.start, + count: req.query.count, + sort: req.query.sort, + accountId: res.locals.account.id, + privateAndUnlisted, + type: req.query.playlistType }) + return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function getVideoChannel (req: express.Request, res: express.Response, next: express.NextFunction) { - const videoChannelWithVideos = await VideoChannelModel.loadAndPopulateAccountAndVideos(res.locals.videoChannel.id) - - return res.json(videoChannelWithVideos.toFormattedJSON()) -} - -async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) { - const videoChannelInstance: VideoChannelModel = res.locals.videoChannel +async function listAccountVideos (req: express.Request, res: express.Response) { + const account = res.locals.account + const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined const resultList = await VideoModel.listForApi({ + followerActorId, start: req.query.start, count: req.query.count, sort: req.query.sort, - hideNSFW: isNSFWHidden(res), + includeLocalVideos: true, + categoryOneOf: req.query.categoryOneOf, + licenceOneOf: req.query.licenceOneOf, + languageOneOf: req.query.languageOneOf, + tagsOneOf: req.query.tagsOneOf, + tagsAllOf: req.query.tagsAllOf, + filter: req.query.filter, + nsfw: buildNSFWFilter(res, req.query.nsfw), withFiles: false, - videoChannelId: videoChannelInstance.id + accountId: account.id, + user: res.locals.oauth ? res.locals.oauth.token.User : undefined }) return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function listAccountVideos (req: express.Request, res: express.Response, next: express.NextFunction) { - const account: AccountModel = res.locals.account +async function listAccountRatings (req: express.Request, res: express.Response) { + const account = res.locals.account - const resultList = await VideoModel.listForApi({ + const resultList = await AccountVideoRateModel.listByAccountForApi({ + accountId: account.id, start: req.query.start, count: req.query.count, sort: req.query.sort, - hideNSFW: isNSFWHidden(res), - withFiles: false, - accountId: account.id + type: req.query.rating }) - - return res.json(getFormattedObjects(resultList.data, resultList.total)) + return res.json(getFormattedObjects(resultList.rows, resultList.count)) }