X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=server%2Fcontrollers%2Fapi%2Faccounts.ts;h=75679b0f44a0bbc1b0f0f067cdb148570578584a;hb=f82416cc58f6c1d0496935e815f3fcb2fdda88ea;hp=04c5897c5310e83b70339ac13720704cbac1c67f;hpb=48dce1c90dff4e90a4bcffefaecf157336cf904b;p=github%2FChocobozzz%2FPeerTube.git diff --git a/server/controllers/api/accounts.ts b/server/controllers/api/accounts.ts index 04c5897c5..75679b0f4 100644 --- a/server/controllers/api/accounts.ts +++ b/server/controllers/api/accounts.ts @@ -1,30 +1,37 @@ -import * as express from 'express' -import { getFormattedObjects, resetSequelizeInstance } from '../../helpers/utils' +import express from 'express' +import { pickCommonVideoQuery } from '@server/helpers/query' +import { getServerActor } from '@server/models/application/application' +import { buildNSFWFilter, getCountVideos, isUserAbleToSearchRemoteURI } from '../../helpers/express-utils' +import { getFormattedObjects } from '../../helpers/utils' +import { JobQueue } from '../../lib/job-queue' +import { Hooks } from '../../lib/plugins/hooks' import { asyncMiddleware, authenticate, - listVideoAccountChannelsValidator, + commonVideosFiltersValidator, optionalAuthenticate, paginationValidator, setDefaultPagination, setDefaultSort, - videoChannelsAddValidator, - videoChannelsGetValidator, - videoChannelsRemoveValidator, - videoChannelsUpdateValidator + setDefaultVideosSort, + videoPlaylistsSortValidator, + videoRatesSortValidator, + videoRatingValidator } from '../../middlewares' -import { accountsGetValidator, accountsSortValidator, videosSortValidator } from '../../middlewares/validators' +import { + accountNameWithHostGetValidator, + accountsSortValidator, + ensureAuthUserOwnsAccountValidator, + videoChannelsSortValidator, + videoChannelStatsValidator, + videosSortValidator +} from '../../middlewares/validators' +import { commonVideoPlaylistFiltersValidator, videoPlaylistsSearchValidator } from '../../middlewares/validators/videos/video-playlists' 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 { 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 { logger } from '../../helpers/logger' -import { retryTransactionWrapper } from '../../helpers/database-utils' +import { VideoPlaylistModel } from '../../models/video/video-playlist' const accountsRouter = express.Router() @@ -36,57 +43,54 @@ 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, + setDefaultVideosSort, 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), + videoChannelStatsValidator, + 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, + videoPlaylistsSearchValidator, + 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 +101,97 @@ 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 } }) + } 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) { +async function listAccountChannels (req: express.Request, res: express.Response) { 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 - } - }).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) { - 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, + withStats: req.query.withStats, + search: req.query.search } - 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 - } - - 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) - }) +async function listAccountPlaylists (req: express.Request, res: express.Response) { + const serverActor = await getServerActor() - 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 + // Allow users to see their private/unlisted video playlists + let listMyPlaylists = false + if (res.locals.oauth && res.locals.oauth.token.User.Account.id === res.locals.account.id) { + listMyPlaylists = true } -} - -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.' - } - - 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({ + search: req.query.search, + followerActorId: serverActor.id, + start: req.query.start, + count: req.query.count, + sort: req.query.sort, + accountId: res.locals.account.id, + listMyPlaylists, + 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 listAccountVideos (req: express.Request, res: express.Response) { + const account = res.locals.account + const followerActorId = isUserAbleToSearchRemoteURI(res) ? null : undefined + const countVideos = getCountVideos(req) + const query = pickCommonVideoQuery(req.query) -async function listVideoChannelVideos (req: express.Request, res: express.Response, next: express.NextFunction) { - const videoChannelInstance: VideoChannelModel = res.locals.videoChannel + const apiOptions = await Hooks.wrapObject({ + ...query, - const resultList = await VideoModel.listForApi({ - start: req.query.start, - count: req.query.count, - sort: req.query.sort, - hideNSFW: isNSFWHidden(res), + followerActorId, + search: req.query.search, + includeLocalVideos: true, + nsfw: buildNSFWFilter(res, query.nsfw), withFiles: false, - videoChannelId: videoChannelInstance.id - }) + accountId: account.id, + user: res.locals.oauth ? res.locals.oauth.token.User : undefined, + countVideos + }, 'filter:api.accounts.videos.list.params') + + const resultList = await Hooks.wrapPromiseFun( + VideoModel.listForApi, + apiOptions, + 'filter:api.accounts.videos.list.result' + ) return res.json(getFormattedObjects(resultList.data, resultList.total)) } +async function listAccountRatings (req: express.Request, res: express.Response) { + const account = res.locals.account -async function listAccountVideos (req: express.Request, res: express.Response, next: express.NextFunction) { - const account: AccountModel = 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)) }