From 7348b1fd84dee869b3c36554aea6797f09d4ceed Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 14 Sep 2018 11:52:23 +0200 Subject: Speed up overviews route --- server/controllers/api/overviews.ts | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/overviews.ts b/server/controllers/api/overviews.ts index da941c0ac..cc3cc54a7 100644 --- a/server/controllers/api/overviews.ts +++ b/server/controllers/api/overviews.ts @@ -4,8 +4,9 @@ import { VideoModel } from '../../models/video/video' import { asyncMiddleware } from '../../middlewares' import { TagModel } from '../../models/video/tag' import { VideosOverview } from '../../../shared/models/overviews' -import { OVERVIEWS, ROUTE_CACHE_LIFETIME } from '../../initializers' +import { MEMOIZE_TTL, OVERVIEWS, ROUTE_CACHE_LIFETIME } from '../../initializers' import { cacheRoute } from '../../middlewares/cache' +import * as memoizee from 'memoizee' const overviewsRouter = express.Router() @@ -23,10 +24,17 @@ export { overviewsRouter } // This endpoint could be quite long, but we cache it async function getVideosOverview (req: express.Request, res: express.Response) { const attributes = await buildSamples() + + const [ categories, channels, tags ] = await Promise.all([ + Promise.all(attributes.categories.map(c => getVideosByCategory(c, res))), + Promise.all(attributes.channels.map(c => getVideosByChannel(c, res))), + Promise.all(attributes.tags.map(t => getVideosByTag(t, res))) + ]) + const result: VideosOverview = { - categories: await Promise.all(attributes.categories.map(c => getVideosByCategory(c, res))), - channels: await Promise.all(attributes.channels.map(c => getVideosByChannel(c, res))), - tags: await Promise.all(attributes.tags.map(t => getVideosByTag(t, res))) + categories, + channels, + tags } // Cleanup our object @@ -37,7 +45,7 @@ async function getVideosOverview (req: express.Request, res: express.Response) { return res.json(result) } -async function buildSamples () { +const buildSamples = memoizee(async function () { const [ categories, channels, tags ] = await Promise.all([ VideoModel.getRandomFieldSamples('category', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD, OVERVIEWS.VIDEOS.SAMPLES_COUNT), VideoModel.getRandomFieldSamples('channelId', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD ,OVERVIEWS.VIDEOS.SAMPLES_COUNT), @@ -45,7 +53,7 @@ async function buildSamples () { ]) return { categories, channels, tags } -} +}, { maxAge: MEMOIZE_TTL.OVERVIEWS_SAMPLE }) async function getVideosByTag (tag: string, res: express.Response) { const videos = await getVideos(res, { tagsOneOf: [ tag ] }) @@ -84,14 +92,16 @@ async function getVideos ( res: express.Response, where: { videoChannelId?: number, tagsOneOf?: string[], categoryOneOf?: number[] } ) { - const { data } = await VideoModel.listForApi(Object.assign({ + const query = Object.assign({ start: 0, count: 10, sort: '-createdAt', includeLocalVideos: true, nsfw: buildNSFWFilter(res), withFiles: false - }, where)) + }, where) + + const { data } = await VideoModel.listForApi(query, false) return data.map(d => d.toFormattedJSON()) } -- cgit v1.2.3 From 4b5384f6e7be62d072d21d8d964951ba572ab10e Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 14 Sep 2018 14:57:59 +0200 Subject: Add redundancy stats --- server/controllers/api/overviews.ts | 20 ++++++++++---------- server/controllers/api/server/stats.ts | 14 +++++++++++++- 2 files changed, 23 insertions(+), 11 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/overviews.ts b/server/controllers/api/overviews.ts index cc3cc54a7..8b6773056 100644 --- a/server/controllers/api/overviews.ts +++ b/server/controllers/api/overviews.ts @@ -21,6 +21,16 @@ export { overviewsRouter } // --------------------------------------------------------------------------- +const buildSamples = memoizee(async function () { + const [ categories, channels, tags ] = await Promise.all([ + VideoModel.getRandomFieldSamples('category', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD, OVERVIEWS.VIDEOS.SAMPLES_COUNT), + VideoModel.getRandomFieldSamples('channelId', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD ,OVERVIEWS.VIDEOS.SAMPLES_COUNT), + TagModel.getRandomSamples(OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD, OVERVIEWS.VIDEOS.SAMPLES_COUNT) + ]) + + return { categories, channels, tags } +}, { maxAge: MEMOIZE_TTL.OVERVIEWS_SAMPLE }) + // This endpoint could be quite long, but we cache it async function getVideosOverview (req: express.Request, res: express.Response) { const attributes = await buildSamples() @@ -45,16 +55,6 @@ async function getVideosOverview (req: express.Request, res: express.Response) { return res.json(result) } -const buildSamples = memoizee(async function () { - const [ categories, channels, tags ] = await Promise.all([ - VideoModel.getRandomFieldSamples('category', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD, OVERVIEWS.VIDEOS.SAMPLES_COUNT), - VideoModel.getRandomFieldSamples('channelId', OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD ,OVERVIEWS.VIDEOS.SAMPLES_COUNT), - TagModel.getRandomSamples(OVERVIEWS.VIDEOS.SAMPLE_THRESHOLD, OVERVIEWS.VIDEOS.SAMPLES_COUNT) - ]) - - return { categories, channels, tags } -}, { maxAge: MEMOIZE_TTL.OVERVIEWS_SAMPLE }) - async function getVideosByTag (tag: string, res: express.Response) { const videos = await getVideos(res, { tagsOneOf: [ tag ] }) diff --git a/server/controllers/api/server/stats.ts b/server/controllers/api/server/stats.ts index 6f4fe938c..bb6311e81 100644 --- a/server/controllers/api/server/stats.ts +++ b/server/controllers/api/server/stats.ts @@ -5,10 +5,14 @@ import { UserModel } from '../../../models/account/user' import { ActorFollowModel } from '../../../models/activitypub/actor-follow' import { VideoModel } from '../../../models/video/video' import { VideoCommentModel } from '../../../models/video/video-comment' +import { VideoRedundancyModel } from '../../../models/redundancy/video-redundancy' +import { CONFIG, ROUTE_CACHE_LIFETIME } from '../../../initializers/constants' +import { cacheRoute } from '../../../middlewares/cache' const statsRouter = express.Router() statsRouter.get('/stats', + asyncMiddleware(cacheRoute(ROUTE_CACHE_LIFETIME.STATS)), asyncMiddleware(getStats) ) @@ -18,6 +22,13 @@ async function getStats (req: express.Request, res: express.Response, next: expr const { totalUsers } = await UserModel.getStats() const { totalInstanceFollowers, totalInstanceFollowing } = await ActorFollowModel.getStats() + const videosRedundancyStats = await Promise.all( + CONFIG.REDUNDANCY.VIDEOS.map(r => { + return VideoRedundancyModel.getStats(r.strategy) + .then(stats => Object.assign(stats, { strategy: r.strategy, totalSize: r.size })) + }) + ) + const data: ServerStats = { totalLocalVideos, totalLocalVideoViews, @@ -26,7 +37,8 @@ async function getStats (req: express.Request, res: express.Response, next: expr totalVideoComments, totalUsers, totalInstanceFollowers, - totalInstanceFollowing + totalInstanceFollowing, + videosRedundancy: videosRedundancyStats } return res.json(data).end() -- cgit v1.2.3 From d61b817890d5d5bba61d447518321870498028d8 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 14 Sep 2018 16:47:15 +0200 Subject: Process inbox activities in a queue --- server/controllers/activitypub/inbox.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/activitypub/inbox.ts b/server/controllers/activitypub/inbox.ts index 20bd20ed4..738d155eb 100644 --- a/server/controllers/activitypub/inbox.ts +++ b/server/controllers/activitypub/inbox.ts @@ -7,6 +7,8 @@ import { asyncMiddleware, checkSignature, localAccountValidator, localVideoChann import { activityPubValidator } from '../../middlewares/validators/activitypub/activity' import { VideoChannelModel } from '../../models/video/video-channel' import { AccountModel } from '../../models/account/account' +import { queue } from 'async' +import { ActorModel } from '../../models/activitypub/actor' const inboxRouter = express.Router() @@ -14,7 +16,7 @@ inboxRouter.post('/inbox', signatureValidator, asyncMiddleware(checkSignature), asyncMiddleware(activityPubValidator), - asyncMiddleware(inboxController) + inboxController ) inboxRouter.post('/accounts/:name/inbox', @@ -22,14 +24,14 @@ inboxRouter.post('/accounts/:name/inbox', asyncMiddleware(checkSignature), asyncMiddleware(localAccountValidator), asyncMiddleware(activityPubValidator), - asyncMiddleware(inboxController) + inboxController ) inboxRouter.post('/video-channels/:name/inbox', signatureValidator, asyncMiddleware(checkSignature), asyncMiddleware(localVideoChannelValidator), asyncMiddleware(activityPubValidator), - asyncMiddleware(inboxController) + inboxController ) // --------------------------------------------------------------------------- @@ -40,7 +42,12 @@ export { // --------------------------------------------------------------------------- -async function inboxController (req: express.Request, res: express.Response, next: express.NextFunction) { +const inboxQueue = queue<{ activities: Activity[], signatureActor?: ActorModel, inboxActor?: ActorModel }, Error>((task, cb) => { + processActivities(task.activities, task.signatureActor, task.inboxActor) + .then(() => cb()) +}) + +function inboxController (req: express.Request, res: express.Response, next: express.NextFunction) { const rootActivity: RootActivity = req.body let activities: Activity[] = [] @@ -66,7 +73,11 @@ async function inboxController (req: express.Request, res: express.Response, nex logger.info('Receiving inbox requests for %d activities by %s.', activities.length, res.locals.signature.actor.url) - await processActivities(activities, res.locals.signature.actor, accountOrChannel ? accountOrChannel.Actor : undefined) + inboxQueue.push({ + activities, + signatureActor: res.locals.signature.actor, + inboxActor: accountOrChannel ? accountOrChannel.Actor : undefined + }) - res.status(204).end() + return res.status(204).end() } -- cgit v1.2.3 From a2377d15ee09301cf4cc5434ad865a21918da15f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 14 Sep 2018 16:51:35 +0200 Subject: Refractor activities sending --- server/controllers/api/videos/index.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index 0c9e6c2d1..8353a649a 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -393,9 +393,9 @@ async function viewVideo (req: express.Request, res: express.Response) { Redis.Instance.setIPVideoView(ip, videoInstance.uuid) ]) - const serverAccount = await getServerActor() + const serverActor = await getServerActor() - await sendCreateView(serverAccount, videoInstance, undefined) + await sendCreateView(serverActor, videoInstance, undefined) return res.status(204).end() } -- cgit v1.2.3 From 2ff83ae2923aa93ccefb0fa989ae0bf138a46d77 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Mon, 17 Sep 2018 10:12:30 +0200 Subject: Handle actors search beginning with '@' Something like @toto@example.com --- server/controllers/api/search.ts | 3 +++ 1 file changed, 3 insertions(+) (limited to 'server/controllers') diff --git a/server/controllers/api/search.ts b/server/controllers/api/search.ts index 28a7a04ca..58851d0b5 100644 --- a/server/controllers/api/search.ts +++ b/server/controllers/api/search.ts @@ -56,6 +56,9 @@ function searchVideoChannels (req: express.Request, res: express.Response) { const isURISearch = search.startsWith('http://') || search.startsWith('https://') const parts = search.split('@') + + // Handle strings like @toto@example.com + if (parts.length === 3 && parts[0].length === 0) parts.shift() const isWebfingerSearch = parts.length === 2 && parts.every(p => p.indexOf(' ') === -1) if (isURISearch || isWebfingerSearch) return searchVideoChannelURI(search, isWebfingerSearch, res) -- cgit v1.2.3 From 627621c1e8d37c33f7b3dd59f4c8907b12c630bc Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 18 Sep 2018 12:00:49 +0200 Subject: Optimize SQL requests of watch page API endpoints --- server/controllers/api/users/me.ts | 2 +- server/controllers/api/videos/comment.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index e886d4b2a..113563c39 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -293,7 +293,7 @@ async function getUserVideoQuotaUsed (req: express.Request, res: express.Respons } async function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) { - const videoId = +req.params.videoId + const videoId = res.locals.video.id const accountId = +res.locals.oauth.token.User.Account.id const ratingObj = await AccountVideoRateModel.load(accountId, videoId, null) diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index e35247829..8d0692b2b 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -86,7 +86,7 @@ async function listVideoThreadComments (req: express.Request, res: express.Respo let resultList: ResultList if (video.commentsEnabled === true) { - resultList = await VideoCommentModel.listThreadCommentsForApi(res.locals.video.id, res.locals.videoCommentThread.id) + resultList = await VideoCommentModel.listThreadCommentsForApi(video.id, res.locals.videoCommentThread.id) } else { resultList = { total: 0, -- cgit v1.2.3 From 96f29c0f6d2e623fb088e88200934c5df8da9924 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 19 Sep 2018 10:16:44 +0200 Subject: Optimize SQL requests of videos AP endpoints --- server/controllers/activitypub/client.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/activitypub/client.ts b/server/controllers/activitypub/client.ts index 2e168ea78..6229c44aa 100644 --- a/server/controllers/activitypub/client.ts +++ b/server/controllers/activitypub/client.ts @@ -6,7 +6,13 @@ import { CONFIG, ROUTE_CACHE_LIFETIME } from '../../initializers' import { buildAnnounceWithVideoAudience } from '../../lib/activitypub/send' import { audiencify, getAudience } from '../../lib/activitypub/audience' import { buildCreateActivity } from '../../lib/activitypub/send/send-create' -import { asyncMiddleware, executeIfActivityPub, localAccountValidator, localVideoChannelValidator } from '../../middlewares' +import { + asyncMiddleware, + executeIfActivityPub, + localAccountValidator, + localVideoChannelValidator, + videosCustomGetValidator +} from '../../middlewares' import { videosGetValidator, videosShareValidator } from '../../middlewares/validators' import { videoCommentGetValidator } from '../../middlewares/validators/video-comments' import { AccountModel } from '../../models/account/account' @@ -54,7 +60,7 @@ activityPubClientRouter.get('/videos/watch/:id/activity', executeIfActivityPub(asyncMiddleware(videoController)) ) activityPubClientRouter.get('/videos/watch/:id/announces', - executeIfActivityPub(asyncMiddleware(videosGetValidator)), + executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))), executeIfActivityPub(asyncMiddleware(videoAnnouncesController)) ) activityPubClientRouter.get('/videos/watch/:id/announces/:accountId', @@ -62,15 +68,15 @@ activityPubClientRouter.get('/videos/watch/:id/announces/:accountId', executeIfActivityPub(asyncMiddleware(videoAnnounceController)) ) activityPubClientRouter.get('/videos/watch/:id/likes', - executeIfActivityPub(asyncMiddleware(videosGetValidator)), + executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))), executeIfActivityPub(asyncMiddleware(videoLikesController)) ) activityPubClientRouter.get('/videos/watch/:id/dislikes', - executeIfActivityPub(asyncMiddleware(videosGetValidator)), + executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))), executeIfActivityPub(asyncMiddleware(videoDislikesController)) ) activityPubClientRouter.get('/videos/watch/:id/comments', - executeIfActivityPub(asyncMiddleware(videosGetValidator)), + executeIfActivityPub(asyncMiddleware(videosCustomGetValidator('only-video'))), executeIfActivityPub(asyncMiddleware(videoCommentsController)) ) activityPubClientRouter.get('/videos/watch/:videoId/comments/:commentId', -- cgit v1.2.3 From 4157cdb13748cb6e8ce7081d062a8778554cc5a7 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 19 Sep 2018 11:16:23 +0200 Subject: Refractor videos AP functions --- server/controllers/api/search.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers') diff --git a/server/controllers/api/search.ts b/server/controllers/api/search.ts index 58851d0b5..ea3166f5f 100644 --- a/server/controllers/api/search.ts +++ b/server/controllers/api/search.ts @@ -139,7 +139,7 @@ async function searchVideoURI (url: string, res: express.Response) { refreshVideo: false } - const result = await getOrCreateVideoAndAccountAndChannel(url, syncParam) + const result = await getOrCreateVideoAndAccountAndChannel({ videoObject: url, syncParam }) video = result ? result.video : undefined } catch (err) { logger.info('Cannot search remote video %s.', url, { err }) -- cgit v1.2.3 From e587e0ecee5bec43a225995948faaa4bc97f080a Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 19 Sep 2018 14:44:20 +0200 Subject: Optimize activity actor load in AP processors --- server/controllers/api/search.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers') diff --git a/server/controllers/api/search.ts b/server/controllers/api/search.ts index ea3166f5f..fd4db7a54 100644 --- a/server/controllers/api/search.ts +++ b/server/controllers/api/search.ts @@ -89,7 +89,7 @@ async function searchVideoChannelURI (search: string, isWebfingerSearch: boolean if (isUserAbleToSearchRemoteURI(res)) { try { - const actor = await getOrCreateActorAndServerAndModel(uri, true, true) + const actor = await getOrCreateActorAndServerAndModel(uri, 'all', true, true) videoChannel = actor.VideoChannel } catch (err) { logger.info('Cannot search remote video channel %s.', uri, { err }) -- cgit v1.2.3 From d9bdd007d7a1368d2a13127ecb5c0a81a18a8c04 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 19 Sep 2018 16:12:07 +0200 Subject: Put config redundancy strategies in "strategies" subkey --- server/controllers/api/server/stats.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers') diff --git a/server/controllers/api/server/stats.ts b/server/controllers/api/server/stats.ts index bb6311e81..85803f69e 100644 --- a/server/controllers/api/server/stats.ts +++ b/server/controllers/api/server/stats.ts @@ -23,7 +23,7 @@ async function getStats (req: express.Request, res: express.Response, next: expr const { totalInstanceFollowers, totalInstanceFollowing } = await ActorFollowModel.getStats() const videosRedundancyStats = await Promise.all( - CONFIG.REDUNDANCY.VIDEOS.map(r => { + CONFIG.REDUNDANCY.VIDEOS.STRATEGIES.map(r => { return VideoRedundancyModel.getStats(r.strategy) .then(stats => Object.assign(stats, { strategy: r.strategy, totalSize: r.size })) }) -- cgit v1.2.3 From 993cef4b6e000ee425087e5195dfe40cd0840243 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 19 Sep 2018 17:02:16 +0200 Subject: Refractor audit user identifier --- server/controllers/api/config.ts | 9 +++------ server/controllers/api/users/index.ts | 17 ++++++++++------- server/controllers/api/users/me.ts | 15 ++++++++------- server/controllers/api/video-channel.ts | 13 +++++-------- server/controllers/api/videos/comment.ts | 8 ++++---- server/controllers/api/videos/import.ts | 6 +++--- server/controllers/api/videos/index.ts | 8 ++++---- 7 files changed, 37 insertions(+), 39 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/config.ts b/server/controllers/api/config.ts index 6edbe4820..95549b724 100644 --- a/server/controllers/api/config.ts +++ b/server/controllers/api/config.ts @@ -8,7 +8,7 @@ import { CONFIG, CONSTRAINTS_FIELDS, reloadConfig } from '../../initializers' import { asyncMiddleware, authenticate, ensureUserHasRight } from '../../middlewares' import { customConfigUpdateValidator } from '../../middlewares/validators/config' import { ClientHtml } from '../../lib/client-html' -import { auditLoggerFactory, CustomConfigAuditView } from '../../helpers/audit-logger' +import { auditLoggerFactory, CustomConfigAuditView, getAuditIdFromRes } from '../../helpers/audit-logger' import { remove, writeJSON } from 'fs-extra' const packageJSON = require('../../../../package.json') @@ -134,10 +134,7 @@ async function getCustomConfig (req: express.Request, res: express.Response, nex async function deleteCustomConfig (req: express.Request, res: express.Response, next: express.NextFunction) { await remove(CONFIG.CUSTOM_FILE) - auditLogger.delete( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), - new CustomConfigAuditView(customConfig()) - ) + auditLogger.delete(getAuditIdFromRes(res), new CustomConfigAuditView(customConfig())) reloadConfig() ClientHtml.invalidCache() @@ -183,7 +180,7 @@ async function updateCustomConfig (req: express.Request, res: express.Response, const data = customConfig() auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new CustomConfigAuditView(data), oldCustomConfigAuditKeys ) diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index 07edf3727..a299167e8 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -27,12 +27,15 @@ import { usersUpdateValidator } from '../../../middlewares' import { - usersAskResetPasswordValidator, usersBlockingValidator, usersResetPasswordValidator, - usersAskSendVerifyEmailValidator, usersVerifyEmailValidator + usersAskResetPasswordValidator, + usersAskSendVerifyEmailValidator, + usersBlockingValidator, + usersResetPasswordValidator, + usersVerifyEmailValidator } from '../../../middlewares/validators' import { UserModel } from '../../../models/account/user' import { OAuthTokenModel } from '../../../models/oauth/oauth-token' -import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger' +import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' import { meRouter } from './me' const auditLogger = auditLoggerFactory('users') @@ -166,7 +169,7 @@ async function createUser (req: express.Request, res: express.Response) { const { user, account } = await createUserAccountAndChannel(userToCreate) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON())) + auditLogger.create(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) logger.info('User %s with its channel and account created.', body.username) return res.json({ @@ -245,7 +248,7 @@ async function removeUser (req: express.Request, res: express.Response, next: ex await user.destroy() - auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON())) + auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) return res.sendStatus(204) } @@ -269,7 +272,7 @@ async function updateUser (req: express.Request, res: express.Response, next: ex } auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView ) @@ -341,7 +344,7 @@ async function changeUserBlock (res: express.Response, user: UserModel, block: b await Emailer.Instance.addUserBlockJob(user, block, reason) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView ) diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index 113563c39..d4b7e3715 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -5,7 +5,8 @@ import { getFormattedObjects } from '../../../helpers/utils' import { CONFIG, IMAGE_MIMETYPE_EXT, sequelizeTypescript } from '../../../initializers' import { sendUpdateActor } from '../../../lib/activitypub/send' import { - asyncMiddleware, asyncRetryTransactionMiddleware, + asyncMiddleware, + asyncRetryTransactionMiddleware, authenticate, commonVideosFiltersValidator, paginationValidator, @@ -17,11 +18,11 @@ import { usersVideoRatingValidator } from '../../../middlewares' import { + areSubscriptionsExistValidator, deleteMeValidator, userSubscriptionsSortValidator, videoImportsSortValidator, - videosSortValidator, - areSubscriptionsExistValidator + videosSortValidator } from '../../../middlewares/validators' import { AccountVideoRateModel } from '../../../models/account/account-video-rate' import { UserModel } from '../../../models/account/user' @@ -31,7 +32,7 @@ import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils' import { UserVideoQuota } from '../../../../shared/models/users/user-video-quota.model' import { updateAvatarValidator } from '../../../middlewares/validators/avatar' import { updateActorAvatarFile } from '../../../lib/avatar' -import { auditLoggerFactory, UserAuditView } from '../../../helpers/audit-logger' +import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' import { VideoImportModel } from '../../../models/video/video-import' import { VideoFilter } from '../../../../shared/models/videos/video-query.type' import { ActorFollowModel } from '../../../models/activitypub/actor-follow' @@ -311,7 +312,7 @@ async function deleteMe (req: express.Request, res: express.Response) { await user.destroy() - auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new UserAuditView(user.toFormattedJSON())) + auditLogger.delete(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON())) return res.sendStatus(204) } @@ -337,7 +338,7 @@ async function updateMe (req: express.Request, res: express.Response, next: expr await sendUpdateActor(user.Account, t) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView ) @@ -355,7 +356,7 @@ async function updateMyAvatar (req: express.Request, res: express.Response, next const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView ) diff --git a/server/controllers/api/video-channel.ts b/server/controllers/api/video-channel.ts index a7a36080b..50dc44f7c 100644 --- a/server/controllers/api/video-channel.ts +++ b/server/controllers/api/video-channel.ts @@ -27,7 +27,7 @@ import { logger } from '../../helpers/logger' import { VideoModel } from '../../models/video/video' import { updateAvatarValidator } from '../../middlewares/validators/avatar' import { updateActorAvatarFile } from '../../lib/avatar' -import { auditLoggerFactory, VideoChannelAuditView } from '../../helpers/audit-logger' +import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger' import { resetSequelizeInstance } from '../../helpers/database-utils' const auditLogger = auditLoggerFactory('channels') @@ -109,7 +109,7 @@ async function updateVideoChannelAvatar (req: express.Request, res: express.Resp const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys ) @@ -133,7 +133,7 @@ async function addVideoChannel (req: express.Request, res: express.Response) { .catch(err => logger.error('Cannot set async actor keys for account %s.', videoChannelCreated.Actor.uuid, { err })) auditLogger.create( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()) ) logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid) @@ -166,7 +166,7 @@ async function updateVideoChannel (req: express.Request, res: express.Response) await sendUpdateActor(videoChannelInstanceUpdated, t) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstanceUpdated.toFormattedJSON()), oldVideoChannelAuditKeys ) @@ -192,10 +192,7 @@ async function removeVideoChannel (req: express.Request, res: express.Response) await sequelizeTypescript.transaction(async t => { await videoChannelInstance.destroy({ transaction: t }) - auditLogger.delete( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), - new VideoChannelAuditView(videoChannelInstance.toFormattedJSON()) - ) + auditLogger.delete(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelInstance.toFormattedJSON())) logger.info('Video channel with name %s and uuid %s deleted.', videoChannelInstance.name, videoChannelInstance.Actor.uuid) }) diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index 8d0692b2b..40ad54d09 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -23,7 +23,7 @@ import { } from '../../../middlewares/validators/video-comments' import { VideoModel } from '../../../models/video/video' import { VideoCommentModel } from '../../../models/video/video-comment' -import { auditLoggerFactory, CommentAuditView } from '../../../helpers/audit-logger' +import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' const auditLogger = auditLoggerFactory('comments') const videoCommentRouter = express.Router() @@ -109,7 +109,7 @@ async function addVideoCommentThread (req: express.Request, res: express.Respons }, t) }) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new CommentAuditView(comment.toFormattedJSON())) + auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON())) return res.json({ comment: comment.toFormattedJSON() @@ -128,7 +128,7 @@ async function addVideoCommentReply (req: express.Request, res: express.Response }, t) }) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new CommentAuditView(comment.toFormattedJSON())) + auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON())) return res.json({ comment: comment.toFormattedJSON() @@ -143,7 +143,7 @@ async function removeVideoComment (req: express.Request, res: express.Response) }) auditLogger.delete( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new CommentAuditView(videoCommentInstance.toFormattedJSON()) ) logger.info('Video comment %d deleted.', videoCommentInstance.id) diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 44f15ef74..398fd5a7f 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -1,7 +1,7 @@ import * as express from 'express' import * as magnetUtil from 'magnet-uri' import 'multer' -import { auditLoggerFactory, VideoImportAuditView } from '../../../helpers/audit-logger' +import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares' import { CONFIG, @@ -114,7 +114,7 @@ async function addTorrentImport (req: express.Request, res: express.Response, to } await JobQueue.Instance.createJob({ type: 'video-import', payload }) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON())) + auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) return res.json(videoImport.toFormattedJSON()).end() } @@ -158,7 +158,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) } await JobQueue.Instance.createJob({ type: 'video-import', payload }) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoImportAuditView(videoImport.toFormattedJSON())) + auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) return res.json(videoImport.toFormattedJSON()).end() } diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index 8353a649a..581046782 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -4,7 +4,7 @@ import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../ import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils' import { processImage } from '../../../helpers/image-utils' import { logger } from '../../../helpers/logger' -import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger' +import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' import { getFormattedObjects, getServerActor } from '../../../helpers/utils' import { CONFIG, @@ -253,7 +253,7 @@ async function addVideo (req: express.Request, res: express.Response) { await federateVideoIfNeeded(video, true, t) - auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) + auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) return videoCreated @@ -354,7 +354,7 @@ async function updateVideo (req: express.Request, res: express.Response) { await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) auditLogger.update( - res.locals.oauth.token.User.Account.Actor.getIdentifier(), + getAuditIdFromRes(res), new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), oldVideoAuditView ) @@ -439,7 +439,7 @@ async function removeVideo (req: express.Request, res: express.Response) { await videoInstance.destroy({ transaction: t }) }) - auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) + auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) return res.type('json').status(204).end() -- cgit v1.2.3 From fcc7c060374c3a547257d96af847352c14d6144b Mon Sep 17 00:00:00 2001 From: BO41 Date: Wed, 19 Sep 2018 18:27:10 +0200 Subject: rename manifest --- server/controllers/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers') diff --git a/server/controllers/client.ts b/server/controllers/client.ts index c33061289..73b40cf65 100644 --- a/server/controllers/client.ts +++ b/server/controllers/client.ts @@ -35,7 +35,7 @@ clientsRouter.use('' + // Static HTML/CSS/JS client files const staticClientFiles = [ - 'manifest.json', + 'manifest.webmanifest', 'ngsw-worker.js', 'ngsw.json' ] -- cgit v1.2.3 From 91411dba928678c15a5e99d9795ae061909e397d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 20 Sep 2018 10:13:13 +0200 Subject: Limit associations fetch when loading token --- server/controllers/api/users/index.ts | 16 +++------------- server/controllers/api/users/me.ts | 28 ++++++++++++---------------- server/controllers/api/video-channel.ts | 9 ++++----- server/controllers/api/videos/abuse.ts | 23 ++++++++++++----------- server/controllers/api/videos/comment.ts | 14 +++++++++----- server/controllers/api/videos/ownership.ts | 13 +++++++------ server/controllers/api/videos/rate.ts | 11 ++++++----- 7 files changed, 53 insertions(+), 61 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index a299167e8..d1163900b 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -267,15 +267,9 @@ async function updateUser (req: express.Request, res: express.Response, next: ex const user = await userToUpdate.save() // Destroy user token to refresh rights - if (roleChanged) { - await OAuthTokenModel.deleteUserToken(userToUpdate.id) - } + if (roleChanged) await OAuthTokenModel.deleteUserToken(userToUpdate.id) - auditLogger.update( - getAuditIdFromRes(res), - new UserAuditView(user.toFormattedJSON()), - oldUserAuditView - ) + auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) // Don't need to send this update to followers, these attributes are not propagated @@ -343,9 +337,5 @@ async function changeUserBlock (res: express.Response, user: UserModel, block: b await Emailer.Instance.addUserBlockJob(user, block, reason) - auditLogger.update( - getAuditIdFromRes(res), - new UserAuditView(user.toFormattedJSON()), - oldUserAuditView - ) + auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) } diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index d4b7e3715..eba1e7edd 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -38,6 +38,7 @@ import { VideoFilter } from '../../../../shared/models/videos/video-query.type' import { ActorFollowModel } from '../../../models/activitypub/actor-follow' import { JobQueue } from '../../../lib/job-queue' import { logger } from '../../../helpers/logger' +import { AccountModel } from '../../../models/account/account' const auditLogger = auditLoggerFactory('users-me') @@ -329,19 +330,17 @@ async function updateMe (req: express.Request, res: express.Response, next: expr if (body.autoPlayVideo !== undefined) user.autoPlayVideo = body.autoPlayVideo await sequelizeTypescript.transaction(async t => { + const userAccount = await AccountModel.load(user.Account.id) + await user.save({ transaction: t }) - if (body.displayName !== undefined) user.Account.name = body.displayName - if (body.description !== undefined) user.Account.description = body.description - await user.Account.save({ transaction: t }) + if (body.displayName !== undefined) userAccount.name = body.displayName + if (body.description !== undefined) userAccount.description = body.description + await userAccount.save({ transaction: t }) - await sendUpdateActor(user.Account, t) + await sendUpdateActor(userAccount, t) - auditLogger.update( - getAuditIdFromRes(res), - new UserAuditView(user.toFormattedJSON()), - oldUserAuditView - ) + auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) }) return res.sendStatus(204) @@ -351,15 +350,12 @@ async function updateMyAvatar (req: express.Request, res: express.Response, next const avatarPhysicalFile = req.files[ 'avatarfile' ][ 0 ] const user: UserModel = res.locals.oauth.token.user const oldUserAuditView = new UserAuditView(user.toFormattedJSON()) - const account = user.Account - const avatar = await updateActorAvatarFile(avatarPhysicalFile, account.Actor, account) + const userAccount = await AccountModel.load(user.Account.id) - auditLogger.update( - getAuditIdFromRes(res), - new UserAuditView(user.toFormattedJSON()), - oldUserAuditView - ) + const avatar = await updateActorAvatarFile(avatarPhysicalFile, userAccount.Actor, userAccount) + + auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) return res.json({ avatar: avatar.toFormattedJSON() }) } diff --git a/server/controllers/api/video-channel.ts b/server/controllers/api/video-channel.ts index 50dc44f7c..8fc340224 100644 --- a/server/controllers/api/video-channel.ts +++ b/server/controllers/api/video-channel.ts @@ -29,6 +29,7 @@ import { updateAvatarValidator } from '../../middlewares/validators/avatar' import { updateActorAvatarFile } from '../../lib/avatar' import { auditLoggerFactory, getAuditIdFromRes, VideoChannelAuditView } from '../../helpers/audit-logger' import { resetSequelizeInstance } from '../../helpers/database-utils' +import { UserModel } from '../../models/account/user' const auditLogger = auditLoggerFactory('channels') const reqAvatarFile = createReqFiles([ 'avatarfile' ], IMAGE_MIMETYPE_EXT, { avatarfile: CONFIG.STORAGE.AVATARS_DIR }) @@ -123,19 +124,17 @@ async function updateVideoChannelAvatar (req: express.Request, res: express.Resp 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 => { + const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, 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 })) - auditLogger.create( - getAuditIdFromRes(res), - new VideoChannelAuditView(videoChannelCreated.toFormattedJSON()) - ) + auditLogger.create(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannelCreated.toFormattedJSON())) logger.info('Video channel with uuid %s created.', videoChannelCreated.Actor.uuid) return res.json({ diff --git a/server/controllers/api/videos/abuse.ts b/server/controllers/api/videos/abuse.ts index 08e11b00b..d0c81804b 100644 --- a/server/controllers/api/videos/abuse.ts +++ b/server/controllers/api/videos/abuse.ts @@ -21,6 +21,7 @@ import { AccountModel } from '../../../models/account/account' import { VideoModel } from '../../../models/video/video' import { VideoAbuseModel } from '../../../models/video/video-abuse' import { auditLoggerFactory, VideoAbuseAuditView } from '../../../helpers/audit-logger' +import { UserModel } from '../../../models/account/user' const auditLogger = auditLoggerFactory('abuse') const abuseVideoRouter = express.Router() @@ -95,17 +96,18 @@ async function deleteVideoAbuse (req: express.Request, res: express.Response) { async function reportVideoAbuse (req: express.Request, res: express.Response) { const videoInstance = res.locals.video as VideoModel - const reporterAccount = res.locals.oauth.token.User.Account as AccountModel const body: VideoAbuseCreate = req.body - const abuseToCreate = { - reporterAccountId: reporterAccount.id, - reason: body.reason, - videoId: videoInstance.id, - state: VideoAbuseState.PENDING - } - const videoAbuse: VideoAbuseModel = await sequelizeTypescript.transaction(async t => { + const reporterAccount = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t) + + const abuseToCreate = { + reporterAccountId: reporterAccount.id, + reason: body.reason, + videoId: videoInstance.id, + state: VideoAbuseState.PENDING + } + const videoAbuseInstance = await VideoAbuseModel.create(abuseToCreate, { transaction: t }) videoAbuseInstance.Video = videoInstance videoAbuseInstance.Account = reporterAccount @@ -121,7 +123,6 @@ async function reportVideoAbuse (req: express.Request, res: express.Response) { }) logger.info('Abuse report for video %s created.', videoInstance.name) - return res.json({ - videoAbuse: videoAbuse.toFormattedJSON() - }).end() + + return res.json({ videoAbuse: videoAbuse.toFormattedJSON() }).end() } diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index 40ad54d09..dc25e1e85 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -24,6 +24,8 @@ import { import { VideoModel } from '../../../models/video/video' import { VideoCommentModel } from '../../../models/video/video-comment' import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' +import { AccountModel } from '../../../models/account/account' +import { UserModel } from '../../../models/account/user' const auditLogger = auditLoggerFactory('comments') const videoCommentRouter = express.Router() @@ -101,11 +103,13 @@ async function addVideoCommentThread (req: express.Request, res: express.Respons const videoCommentInfo: VideoCommentCreate = req.body const comment = await sequelizeTypescript.transaction(async t => { + const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t) + return createVideoComment({ text: videoCommentInfo.text, inReplyToComment: null, video: res.locals.video, - account: res.locals.oauth.token.User.Account + account }, t) }) @@ -120,19 +124,19 @@ async function addVideoCommentReply (req: express.Request, res: express.Response const videoCommentInfo: VideoCommentCreate = req.body const comment = await sequelizeTypescript.transaction(async t => { + const account = await AccountModel.load((res.locals.oauth.token.User as UserModel).Account.id, t) + return createVideoComment({ text: videoCommentInfo.text, inReplyToComment: res.locals.videoComment, video: res.locals.video, - account: res.locals.oauth.token.User.Account + account }, t) }) auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON())) - return res.json({ - comment: comment.toFormattedJSON() - }).end() + return res.json({ comment: comment.toFormattedJSON() }).end() } async function removeVideoComment (req: express.Request, res: express.Response) { diff --git a/server/controllers/api/videos/ownership.ts b/server/controllers/api/videos/ownership.ts index d26ed6cfc..5ea7d7c6a 100644 --- a/server/controllers/api/videos/ownership.ts +++ b/server/controllers/api/videos/ownership.ts @@ -19,6 +19,7 @@ import { VideoChannelModel } from '../../../models/video/video-channel' import { getFormattedObjects } from '../../../helpers/utils' import { changeVideoChannelShare } from '../../../lib/activitypub' import { sendUpdateVideo } from '../../../lib/activitypub/send' +import { UserModel } from '../../../models/account/user' const ownershipVideoRouter = express.Router() @@ -58,26 +59,25 @@ export { async function giveVideoOwnership (req: express.Request, res: express.Response) { const videoInstance = res.locals.video as VideoModel - const initiatorAccount = res.locals.oauth.token.User.Account as AccountModel + const initiatorAccountId = (res.locals.oauth.token.User as UserModel).Account.id const nextOwner = res.locals.nextOwner as AccountModel await sequelizeTypescript.transaction(t => { return VideoChangeOwnershipModel.findOrCreate({ where: { - initiatorAccountId: initiatorAccount.id, + initiatorAccountId, nextOwnerAccountId: nextOwner.id, videoId: videoInstance.id, status: VideoChangeOwnershipStatus.WAITING }, defaults: { - initiatorAccountId: initiatorAccount.id, + initiatorAccountId, nextOwnerAccountId: nextOwner.id, videoId: videoInstance.id, status: VideoChangeOwnershipStatus.WAITING }, transaction: t }) - }) logger.info('Ownership change for video %s created.', videoInstance.name) @@ -85,9 +85,10 @@ async function giveVideoOwnership (req: express.Request, res: express.Response) } async function listVideoOwnership (req: express.Request, res: express.Response) { - const currentAccount = res.locals.oauth.token.User.Account as AccountModel + const currentAccountId = (res.locals.oauth.token.User as UserModel).Account.id + const resultList = await VideoChangeOwnershipModel.listForApi( - currentAccount.id, + currentAccountId, req.query.start || 0, req.query.count || 10, req.query.sort || 'createdAt' diff --git a/server/controllers/api/videos/rate.ts b/server/controllers/api/videos/rate.ts index b1732837d..dc322bb0c 100644 --- a/server/controllers/api/videos/rate.ts +++ b/server/controllers/api/videos/rate.ts @@ -28,10 +28,11 @@ async function rateVideo (req: express.Request, res: express.Response) { const body: UserVideoRateUpdate = req.body const rateType = body.rating const videoInstance: VideoModel = res.locals.video - const accountInstance: AccountModel = res.locals.oauth.token.User.Account await sequelizeTypescript.transaction(async t => { const sequelizeOptions = { transaction: t } + + const accountInstance = await AccountModel.load(res.locals.oauth.token.User.Account.id, t) const previousRate = await AccountVideoRateModel.load(accountInstance.id, videoInstance.id, t) let likesToIncrement = 0 @@ -47,10 +48,10 @@ async function rateVideo (req: express.Request, res: express.Response) { else if (previousRate.type === VIDEO_RATE_TYPES.DISLIKE) dislikesToIncrement-- if (rateType === 'none') { // Destroy previous rate - await previousRate.destroy({ transaction: t }) + await previousRate.destroy(sequelizeOptions) } else { // Update previous rate previousRate.type = rateType - await previousRate.save({ transaction: t }) + await previousRate.save(sequelizeOptions) } } else if (rateType !== 'none') { // There was not a previous rate, insert a new one if there is a rate const query = { @@ -70,9 +71,9 @@ async function rateVideo (req: express.Request, res: express.Response) { await videoInstance.increment(incrementQuery, sequelizeOptions) await sendVideoRateChange(accountInstance, videoInstance, likesToIncrement, dislikesToIncrement, t) - }) - logger.info('Account video rate for video %s of account %s updated.', videoInstance.name, accountInstance.name) + logger.info('Account video rate for video %s of account %s updated.', videoInstance.name, accountInstance.name) + }) return res.type('json').status(204).end() } -- cgit v1.2.3 From f201a749929ec8094a7ba6bcab7b196870ca5a5e Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 20 Sep 2018 11:31:48 +0200 Subject: Cache user token --- server/controllers/api/users/index.ts | 5 +++-- server/controllers/api/users/me.ts | 2 +- server/controllers/api/video-channel.ts | 10 +++------- 3 files changed, 7 insertions(+), 10 deletions(-) (limited to 'server/controllers') diff --git a/server/controllers/api/users/index.ts b/server/controllers/api/users/index.ts index d1163900b..8b8ebcd23 100644 --- a/server/controllers/api/users/index.ts +++ b/server/controllers/api/users/index.ts @@ -37,6 +37,7 @@ import { UserModel } from '../../../models/account/user' import { OAuthTokenModel } from '../../../models/oauth/oauth-token' import { auditLoggerFactory, getAuditIdFromRes, UserAuditView } from '../../../helpers/audit-logger' import { meRouter } from './me' +import { deleteUserToken } from '../../../lib/oauth-model' const auditLogger = auditLoggerFactory('users') @@ -267,7 +268,7 @@ async function updateUser (req: express.Request, res: express.Response, next: ex const user = await userToUpdate.save() // Destroy user token to refresh rights - if (roleChanged) await OAuthTokenModel.deleteUserToken(userToUpdate.id) + if (roleChanged) await deleteUserToken(userToUpdate.id) auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) @@ -330,7 +331,7 @@ async function changeUserBlock (res: express.Response, user: UserModel, block: b user.blockedReason = reason || null await sequelizeTypescript.transaction(async t => { - await OAuthTokenModel.deleteUserToken(user.id, t) + await deleteUserToken(user.id, t) await user.save({ transaction: t }) }) diff --git a/server/controllers/api/users/me.ts b/server/controllers/api/users/me.ts index eba1e7edd..ff3a87b7f 100644 --- a/server/controllers/api/users/me.ts +++ b/server/controllers/api/users/me.ts @@ -353,7 +353,7 @@ async function updateMyAvatar (req: express.Request, res: express.Response, next const userAccount = await AccountModel.load(user.Account.id) - const avatar = await updateActorAvatarFile(avatarPhysicalFile, userAccount.Actor, userAccount) + const avatar = await updateActorAvatarFile(avatarPhysicalFile, userAccount) auditLogger.update(getAuditIdFromRes(res), new UserAuditView(user.toFormattedJSON()), oldUserAuditView) diff --git a/server/controllers/api/video-channel.ts b/server/controllers/api/video-channel.ts index 8fc340224..ff6bbe44c 100644 --- a/server/controllers/api/video-channel.ts +++ b/server/controllers/api/video-channel.ts @@ -56,7 +56,7 @@ videoChannelRouter.post('/:nameWithHost/avatar/pick', // Check the rights asyncMiddleware(videoChannelsUpdateValidator), updateAvatarValidator, - asyncMiddleware(updateVideoChannelAvatar) + asyncRetryTransactionMiddleware(updateVideoChannelAvatar) ) videoChannelRouter.put('/:nameWithHost', @@ -107,13 +107,9 @@ async function updateVideoChannelAvatar (req: express.Request, res: express.Resp const videoChannel = res.locals.videoChannel as VideoChannelModel const oldVideoChannelAuditKeys = new VideoChannelAuditView(videoChannel.toFormattedJSON()) - const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel.Actor, videoChannel) + const avatar = await updateActorAvatarFile(avatarPhysicalFile, videoChannel) - auditLogger.update( - getAuditIdFromRes(res), - new VideoChannelAuditView(videoChannel.toFormattedJSON()), - oldVideoChannelAuditKeys - ) + auditLogger.update(getAuditIdFromRes(res), new VideoChannelAuditView(videoChannel.toFormattedJSON()), oldVideoChannelAuditKeys) return res .json({ -- cgit v1.2.3