From a15871560f80e07386c1dabb8370cd2664ecfd1f Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 31 Jan 2020 16:56:52 +0100 Subject: Move to eslint --- server/lib/activitypub/actor.ts | 22 +++-- server/lib/activitypub/crawl.ts | 6 +- server/lib/activitypub/follow.ts | 1 - server/lib/activitypub/send/send-accept.ts | 2 +- server/lib/activitypub/send/send-create.ts | 8 +- server/lib/activitypub/send/send-dislike.ts | 2 +- server/lib/activitypub/send/send-flag.ts | 2 +- server/lib/activitypub/send/send-like.ts | 2 +- server/lib/activitypub/send/send-reject.ts | 2 +- server/lib/activitypub/send/send-undo.ts | 10 +- server/lib/activitypub/send/send-update.ts | 3 +- server/lib/activitypub/send/utils.ts | 4 +- server/lib/activitypub/video-comments.ts | 14 +-- server/lib/activitypub/video-rates.ts | 2 - server/lib/activitypub/videos.ts | 50 +++++----- server/lib/client-html.ts | 24 ++--- server/lib/emailer.ts | 101 +++++++++++---------- server/lib/files-cache/videos-preview-cache.ts | 3 +- .../handlers/utils/activitypub-http-utils.ts | 2 +- server/lib/job-queue/handlers/video-file-import.ts | 2 +- server/lib/job-queue/handlers/video-import.ts | 2 +- server/lib/job-queue/handlers/video-transcoding.ts | 17 ++-- server/lib/job-queue/job-queue.ts | 34 ++++--- server/lib/moderation.ts | 22 ++--- server/lib/notifier.ts | 47 +++++----- server/lib/plugins/plugin-index.ts | 4 +- server/lib/plugins/plugin-manager.ts | 44 ++++----- server/lib/redis.ts | 41 +++++---- .../lib/schedulers/auto-follow-index-instances.ts | 3 +- server/lib/schedulers/plugins-check-scheduler.ts | 2 +- .../lib/schedulers/remove-old-views-scheduler.ts | 2 - .../lib/schedulers/videos-redundancy-scheduler.ts | 6 +- server/lib/thumbnail.ts | 18 ++-- server/lib/user.ts | 16 ++-- server/lib/video-blacklist.ts | 20 ++-- server/lib/video-channel.ts | 3 +- server/lib/video-comment.ts | 6 +- 37 files changed, 278 insertions(+), 271 deletions(-) (limited to 'server/lib') diff --git a/server/lib/activitypub/actor.ts b/server/lib/activitypub/actor.ts index f802658cf..3f6edc070 100644 --- a/server/lib/activitypub/actor.ts +++ b/server/lib/activitypub/actor.ts @@ -1,6 +1,6 @@ import * as Bluebird from 'bluebird' import { Transaction } from 'sequelize' -import * as url from 'url' +import { URL } from 'url' import * as uuidv4 from 'uuid/v4' import { ActivityPubActor, ActivityPubActorType } from '../../../shared/models/activitypub' import { ActivityPubAttributedTo } from '../../../shared/models/activitypub/objects' @@ -33,8 +33,7 @@ import { MActorFull, MActorFullActor, MActorId, - MChannel, - MChannelAccountDefault + MChannel } from '../../typings/models' // Set account keys, this could be long so process after the account creation and do not block the client @@ -121,13 +120,13 @@ async function getOrCreateActorAndServerAndModel ( if ((created === true || refreshed === true) && updateCollections === true) { const payload = { uri: actor.outboxUrl, type: 'activity' as 'activity' } - await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload }) + await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }) } // We created a new account: fetch the playlists if (created === true && actor.Account && accountPlaylistsUrl) { const payload = { uri: accountPlaylistsUrl, accountId: actor.Account.id, type: 'account-playlists' as 'account-playlists' } - await JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload }) + await JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload }) } return actorRefreshed @@ -215,7 +214,7 @@ async function fetchActorTotalItems (url: string) { } } -async function getAvatarInfoIfExists (actorJSON: ActivityPubActor) { +function getAvatarInfoIfExists (actorJSON: ActivityPubActor) { if ( actorJSON.icon && actorJSON.icon.type === 'Image' && MIMETYPES.IMAGE.MIMETYPE_EXT[actorJSON.icon.mediaType] !== undefined && isActivityPubUrlValid(actorJSON.icon.url) @@ -271,7 +270,10 @@ async function refreshActorIfNeeded | Promise { - let actor = result.actor + const actor = result.actor if (t !== undefined) return save(t) return sequelizeTypescript.transaction(t => save(t)) async function save (t: Transaction) { - const actorHost = url.parse(actor.url).host + const actorHost = new URL(actor.url).host const serverOptions = { where: { @@ -402,7 +404,7 @@ type FetchRemoteActorResult = { support?: string playlists?: string avatar?: { - name: string, + name: string fileUrl: string } attributedTo: ActivityPubAttributedTo[] diff --git a/server/lib/activitypub/crawl.ts b/server/lib/activitypub/crawl.ts index 9e469e3e6..eeafdf4ba 100644 --- a/server/lib/activitypub/crawl.ts +++ b/server/lib/activitypub/crawl.ts @@ -3,7 +3,7 @@ import { doRequest } from '../../helpers/requests' import { logger } from '../../helpers/logger' import * as Bluebird from 'bluebird' import { ActivityPubOrderedCollection } from '../../../shared/models/activitypub' -import { parse } from 'url' +import { URL } from 'url' type HandlerFunction = (items: T[]) => (Promise | Bluebird) type CleanerFunction = (startedDate: Date) => (Promise | Bluebird) @@ -24,7 +24,7 @@ async function crawlCollectionPage (uri: string, handler: HandlerFunction const response = await doRequest>(options) const firstBody = response.body - let limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT + const limit = ACTIVITY_PUB.FETCH_PAGE_LIMIT let i = 0 let nextLink = firstBody.first while (nextLink && i < limit) { @@ -32,7 +32,7 @@ async function crawlCollectionPage (uri: string, handler: HandlerFunction if (typeof nextLink === 'string') { // Don't crawl ourselves - const remoteHost = parse(nextLink).host + const remoteHost = new URL(nextLink).host if (remoteHost === WEBSERVER.HOST) continue options.uri = nextLink diff --git a/server/lib/activitypub/follow.ts b/server/lib/activitypub/follow.ts index 1abf43cd4..a1c95504e 100644 --- a/server/lib/activitypub/follow.ts +++ b/server/lib/activitypub/follow.ts @@ -27,7 +27,6 @@ async function autoFollowBackIfNeeded (actorFollow: MActorFollowActors) { } JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) - .catch(err => logger.error('Cannot create auto follow back job for %s.', host, err)) } } diff --git a/server/lib/activitypub/send/send-accept.ts b/server/lib/activitypub/send/send-accept.ts index 9f0225b64..c4c6b849b 100644 --- a/server/lib/activitypub/send/send-accept.ts +++ b/server/lib/activitypub/send/send-accept.ts @@ -5,7 +5,7 @@ import { buildFollowActivity } from './send-follow' import { logger } from '../../../helpers/logger' import { MActor, MActorFollowActors } from '../../../typings/models' -async function sendAccept (actorFollow: MActorFollowActors) { +function sendAccept (actorFollow: MActorFollowActors) { const follower = actorFollow.ActorFollower const me = actorFollow.ActorFollowing diff --git a/server/lib/activitypub/send/send-create.ts b/server/lib/activitypub/send/send-create.ts index 1709d8348..3585d704a 100644 --- a/server/lib/activitypub/send/send-create.ts +++ b/server/lib/activitypub/send/send-create.ts @@ -130,10 +130,10 @@ export { // --------------------------------------------------------------------------- async function sendVideoRelatedCreateActivity (options: { - byActor: MActorLight, - video: MVideoAccountLight, - url: string, - object: any, + byActor: MActorLight + video: MVideoAccountLight + url: string + object: any transaction?: Transaction }) { const activityBuilder = (audience: ActivityAudience) => { diff --git a/server/lib/activitypub/send/send-dislike.ts b/server/lib/activitypub/send/send-dislike.ts index 6e41f241f..600469c71 100644 --- a/server/lib/activitypub/send/send-dislike.ts +++ b/server/lib/activitypub/send/send-dislike.ts @@ -6,7 +6,7 @@ import { sendVideoRelatedActivity } from './utils' import { audiencify, getAudience } from '../audience' import { MActor, MActorAudience, MVideoAccountLight, MVideoUrl } from '../../../typings/models' -async function sendDislike (byActor: MActor, video: MVideoAccountLight, t: Transaction) { +function sendDislike (byActor: MActor, video: MVideoAccountLight, t: Transaction) { logger.info('Creating job to dislike %s.', video.url) const activityBuilder = (audience: ActivityAudience) => { diff --git a/server/lib/activitypub/send/send-flag.ts b/server/lib/activitypub/send/send-flag.ts index da7638a7b..e4e523631 100644 --- a/server/lib/activitypub/send/send-flag.ts +++ b/server/lib/activitypub/send/send-flag.ts @@ -7,7 +7,7 @@ import { Transaction } from 'sequelize' import { MActor, MVideoFullLight } from '../../../typings/models' import { MVideoAbuseVideo } from '../../../typings/models/video' -async function sendVideoAbuse (byActor: MActor, videoAbuse: MVideoAbuseVideo, video: MVideoFullLight, t: Transaction) { +function sendVideoAbuse (byActor: MActor, videoAbuse: MVideoAbuseVideo, video: MVideoFullLight, t: Transaction) { if (!video.VideoChannel.Account.Actor.serverId) return // Local user const url = getVideoAbuseActivityPubUrl(videoAbuse) diff --git a/server/lib/activitypub/send/send-like.ts b/server/lib/activitypub/send/send-like.ts index e84a6f98b..5db252325 100644 --- a/server/lib/activitypub/send/send-like.ts +++ b/server/lib/activitypub/send/send-like.ts @@ -6,7 +6,7 @@ import { audiencify, getAudience } from '../audience' import { logger } from '../../../helpers/logger' import { MActor, MActorAudience, MVideoAccountLight, MVideoUrl } from '../../../typings/models' -async function sendLike (byActor: MActor, video: MVideoAccountLight, t: Transaction) { +function sendLike (byActor: MActor, video: MVideoAccountLight, t: Transaction) { logger.info('Creating job to like %s.', video.url) const activityBuilder = (audience: ActivityAudience) => { diff --git a/server/lib/activitypub/send/send-reject.ts b/server/lib/activitypub/send/send-reject.ts index 4258a3c36..643c468a9 100644 --- a/server/lib/activitypub/send/send-reject.ts +++ b/server/lib/activitypub/send/send-reject.ts @@ -5,7 +5,7 @@ import { buildFollowActivity } from './send-follow' import { logger } from '../../../helpers/logger' import { MActor } from '../../../typings/models' -async function sendReject (follower: MActor, following: MActor) { +function sendReject (follower: MActor, following: MActor) { if (!follower.serverId) { // This should never happen logger.warn('Do not sending reject to local follower.') return diff --git a/server/lib/activitypub/send/send-undo.ts b/server/lib/activitypub/send/send-undo.ts index e9ab5b3c5..33f1d4921 100644 --- a/server/lib/activitypub/send/send-undo.ts +++ b/server/lib/activitypub/send/send-undo.ts @@ -28,7 +28,7 @@ import { MVideoShare } from '../../../typings/models' -async function sendUndoFollow (actorFollow: MActorFollowActors, t: Transaction) { +function sendUndoFollow (actorFollow: MActorFollowActors, t: Transaction) { const me = actorFollow.ActorFollower const following = actorFollow.ActorFollowing @@ -118,10 +118,10 @@ function undoActivityData ( } async function sendUndoVideoRelatedActivity (options: { - byActor: MActor, - video: MVideoAccountLight, - url: string, - activity: ActivityFollow | ActivityLike | ActivityDislike | ActivityCreate | ActivityAnnounce, + byActor: MActor + video: MVideoAccountLight + url: string + activity: ActivityFollow | ActivityLike | ActivityDislike | ActivityCreate | ActivityAnnounce transaction: Transaction }) { const activityBuilder = (audience: ActivityAudience) => { diff --git a/server/lib/activitypub/send/send-update.ts b/server/lib/activitypub/send/send-update.ts index 9c76671b5..cb500bd34 100644 --- a/server/lib/activitypub/send/send-update.ts +++ b/server/lib/activitypub/send/send-update.ts @@ -8,7 +8,6 @@ import { getUpdateActivityPubUrl } from '../url' import { broadcastToFollowers, sendVideoRelatedActivity } from './utils' import { audiencify, getActorsInvolvedInVideo, getAudience } from '../audience' import { logger } from '../../../helpers/logger' -import { VideoCaptionModel } from '../../../models/video/video-caption' import { VideoPlaylistPrivacy } from '../../../../shared/models/videos/playlist/video-playlist-privacy.model' import { getServerActor } from '../../../helpers/utils' import { @@ -29,7 +28,7 @@ async function sendUpdateVideo (videoArg: MVideoAPWithoutCaption, t: Transaction logger.info('Creating job to update video %s.', video.url) - const byActor = overrodeByActor ? overrodeByActor : video.VideoChannel.Account.Actor + const byActor = overrodeByActor || video.VideoChannel.Account.Actor const url = getUpdateActivityPubUrl(video.url, video.updatedAt.toISOString()) diff --git a/server/lib/activitypub/send/utils.ts b/server/lib/activitypub/send/utils.ts index 77b723479..6fb4efd60 100644 --- a/server/lib/activitypub/send/utils.ts +++ b/server/lib/activitypub/send/utils.ts @@ -10,8 +10,8 @@ import { afterCommitIfTransaction } from '../../../helpers/database-utils' import { MActorWithInboxes, MActor, MActorId, MActorLight, MVideo, MVideoAccountLight } from '../../../typings/models' async function sendVideoRelatedActivity (activityBuilder: (audience: ActivityAudience) => Activity, options: { - byActor: MActorLight, - video: MVideoAccountLight, + byActor: MActorLight + video: MVideoAccountLight transaction?: Transaction }) { const { byActor, video, transaction } = options diff --git a/server/lib/activitypub/video-comments.ts b/server/lib/activitypub/video-comments.ts index d5c078a29..8642d2432 100644 --- a/server/lib/activitypub/video-comments.ts +++ b/server/lib/activitypub/video-comments.ts @@ -10,9 +10,9 @@ import { checkUrlsSameHost } from '../../helpers/activitypub' import { MCommentOwner, MCommentOwnerVideo, MVideoAccountLightBlacklistAllFiles } from '../../typings/models/video' type ResolveThreadParams = { - url: string, - comments?: MCommentOwner[], - isVideo?: boolean, + url: string + comments?: MCommentOwner[] + isVideo?: boolean commentCreated?: boolean } type ResolveThreadResult = Promise<{ video: MVideoAccountLightBlacklistAllFiles, comment: MCommentOwnerVideo, commentCreated: boolean }> @@ -28,7 +28,7 @@ async function resolveThread (params: ResolveThreadParams): ResolveThreadResult if (params.commentCreated === undefined) params.commentCreated = false if (params.comments === undefined) params.comments = [] - // Already have this comment? + // Already have this comment? if (isVideo !== true) { const result = await resolveCommentFromDB(params) if (result) return result @@ -87,7 +87,7 @@ async function tryResolveThreadFromVideo (params: ResolveThreadParams) { let resultComment: MCommentOwnerVideo if (comments.length !== 0) { - const firstReply = comments[ comments.length - 1 ] as MCommentOwnerVideo + const firstReply = comments[comments.length - 1] as MCommentOwnerVideo firstReply.inReplyToCommentId = null firstReply.originCommentId = null firstReply.videoId = video.id @@ -97,9 +97,9 @@ async function tryResolveThreadFromVideo (params: ResolveThreadParams) { comments[comments.length - 1] = await firstReply.save() for (let i = comments.length - 2; i >= 0; i--) { - const comment = comments[ i ] as MCommentOwnerVideo + const comment = comments[i] as MCommentOwnerVideo comment.originCommentId = firstReply.id - comment.inReplyToCommentId = comments[ i + 1 ].id + comment.inReplyToCommentId = comments[i + 1].id comment.videoId = video.id comment.changed('updatedAt', true) comment.Video = video diff --git a/server/lib/activitypub/video-rates.ts b/server/lib/activitypub/video-rates.ts index 6bd46bb58..79ccfbc7e 100644 --- a/server/lib/activitypub/video-rates.ts +++ b/server/lib/activitypub/video-rates.ts @@ -58,8 +58,6 @@ async function createRates (ratesUrl: string[], video: MVideo, rate: VideoRateTy const field = rate === 'like' ? 'likes' : 'dislikes' await video.increment(field, { by: rateCounts }) } - - return } async function sendVideoRateChange ( diff --git a/server/lib/activitypub/videos.ts b/server/lib/activitypub/videos.ts index 6bc2258cc..9e43caa20 100644 --- a/server/lib/activitypub/videos.ts +++ b/server/lib/activitypub/videos.ts @@ -197,25 +197,25 @@ async function syncVideoExternalAttributes (video: MVideo, fetchedVideo: VideoTo jobPayloads.push({ uri: fetchedVideo.comments, videoId: video.id, type: 'video-comments' as 'video-comments' }) } - await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJob({ type: 'activitypub-http-fetcher', payload })) + await Bluebird.map(jobPayloads, payload => JobQueue.Instance.createJobWithPromise({ type: 'activitypub-http-fetcher', payload })) } function getOrCreateVideoAndAccountAndChannel (options: { - videoObject: { id: string } | string, - syncParam?: SyncParam, - fetchType?: 'all', + videoObject: { id: string } | string + syncParam?: SyncParam + fetchType?: 'all' allowRefresh?: boolean }): Promise<{ video: MVideoAccountLightBlacklistAllFiles, created: boolean, autoBlacklisted?: boolean }> function getOrCreateVideoAndAccountAndChannel (options: { - videoObject: { id: string } | string, - syncParam?: SyncParam, - fetchType?: VideoFetchByUrlType, + videoObject: { id: string } | string + syncParam?: SyncParam + fetchType?: VideoFetchByUrlType allowRefresh?: boolean }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }> async function getOrCreateVideoAndAccountAndChannel (options: { - videoObject: { id: string } | string, - syncParam?: SyncParam, - fetchType?: VideoFetchByUrlType, + videoObject: { id: string } | string + syncParam?: SyncParam + fetchType?: VideoFetchByUrlType allowRefresh?: boolean // true by default }): Promise<{ video: MVideoAccountLightBlacklistAllFiles | MVideoThumbnail, created: boolean, autoBlacklisted?: boolean }> { // Default params @@ -235,8 +235,14 @@ async function getOrCreateVideoAndAccountAndChannel (options: { syncParam } - if (syncParam.refreshVideo === true) videoFromDatabase = await refreshVideoIfNeeded(refreshOptions) - else await JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: videoFromDatabase.url } }) + if (syncParam.refreshVideo === true) { + videoFromDatabase = await refreshVideoIfNeeded(refreshOptions) + } else { + await JobQueue.Instance.createJobWithPromise({ + type: 'activitypub-refresher', + payload: { type: 'video', url: videoFromDatabase.url } + }) + } } return { video: videoFromDatabase, created: false } @@ -255,10 +261,10 @@ async function getOrCreateVideoAndAccountAndChannel (options: { } async function updateVideoFromAP (options: { - video: MVideoAccountLightBlacklistAllFiles, - videoObject: VideoTorrentObject, - account: MAccountIdActor, - channel: MChannelDefault, + video: MVideoAccountLightBlacklistAllFiles + videoObject: VideoTorrentObject + account: MAccountIdActor + channel: MChannelDefault overrideTo?: string[] }) { const { video, videoObject, account, channel, overrideTo } = options @@ -289,7 +295,7 @@ async function updateVideoFromAP (options: { throw new Error('Account ' + account.Actor.url + ' does not own video channel ' + videoChannel.Actor.url) } - const to = overrideTo ? overrideTo : videoObject.to + const to = overrideTo || videoObject.to const videoData = await videoActivityObjectToDBAttributes(channel, videoObject, to) video.name = videoData.name video.uuid = videoData.uuid @@ -412,8 +418,8 @@ async function updateVideoFromAP (options: { } async function refreshVideoIfNeeded (options: { - video: MVideoThumbnail, - fetchedType: VideoFetchByUrlType, + video: MVideoThumbnail + fetchedType: VideoFetchByUrlType syncParam: SyncParam }): Promise { if (!options.video.isOutdated()) return options.video @@ -582,13 +588,13 @@ async function createVideo (videoObject: VideoTorrentObject, channel: MChannelAc thumbnailModel = videoCreated.id return thumbnailModel.save() - }) + }).catch(err => logger.error('Cannot create miniature from url.', { err })) } return { autoBlacklisted, videoCreated } } -async function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) { +function videoActivityObjectToDBAttributes (videoChannel: MChannelId, videoObject: VideoTorrentObject, to: string[] = []) { const privacy = to.indexOf(ACTIVITY_PUB.PUBLIC) !== -1 ? VideoPrivacy.PUBLIC : VideoPrivacy.UNLISTED const duration = videoObject.duration.replace(/[^\d]+/, '') @@ -661,7 +667,7 @@ function videoFileActivityUrlToDBAttributes ( const mediaType = fileUrl.mediaType const attribute = { - extname: MIMETYPES.VIDEO.MIMETYPE_EXT[ mediaType ], + extname: MIMETYPES.VIDEO.MIMETYPE_EXT[mediaType], infoHash: parsed.infoHash, resolution: fileUrl.height, size: fileUrl.size, diff --git a/server/lib/client-html.ts b/server/lib/client-html.ts index 1d8a08ed0..572bd03bd 100644 --- a/server/lib/client-html.ts +++ b/server/lib/client-html.ts @@ -17,7 +17,7 @@ import { MAccountActor, MChannelActor, MVideo } from '../typings/models' export class ClientHtml { - private static htmlCache: { [ path: string ]: string } = {} + private static htmlCache: { [path: string]: string } = {} static invalidCache () { logger.info('Cleaning HTML cache.') @@ -94,7 +94,7 @@ export class ClientHtml { private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) { const path = ClientHtml.getIndexPath(req, res, paramLang) - if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ] + if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path] const buffer = await readFile(path) @@ -104,7 +104,7 @@ export class ClientHtml { html = ClientHtml.addCustomCSS(html) html = await ClientHtml.addAsyncPluginCSS(html) - ClientHtml.htmlCache[ path ] = html + ClientHtml.htmlCache[path] = html return html } @@ -214,21 +214,21 @@ export class ClientHtml { const schemaTags = { '@context': 'http://schema.org', '@type': 'VideoObject', - name: videoNameEscaped, - description: videoDescriptionEscaped, - thumbnailUrl: previewUrl, - uploadDate: video.createdAt.toISOString(), - duration: getActivityStreamDuration(video.duration), - contentUrl: videoUrl, - embedUrl: embedUrl, - interactionCount: video.views + 'name': videoNameEscaped, + 'description': videoDescriptionEscaped, + 'thumbnailUrl': previewUrl, + 'uploadDate': video.createdAt.toISOString(), + 'duration': getActivityStreamDuration(video.duration), + 'contentUrl': videoUrl, + 'embedUrl': embedUrl, + 'interactionCount': video.views } let tagsString = '' // Opengraph Object.keys(openGraphMetaTags).forEach(tagName => { - const tagValue = openGraphMetaTags[ tagName ] + const tagValue = openGraphMetaTags[tagName] tagsString += `` }) diff --git a/server/lib/emailer.ts b/server/lib/emailer.ts index 7484524a4..9ce6186b1 100644 --- a/server/lib/emailer.ts +++ b/server/lib/emailer.ts @@ -32,7 +32,8 @@ class Emailer { private initialized = false private transporter: Transporter - private constructor () {} + private constructor () { + } init () { // Already initialized @@ -97,12 +98,12 @@ class Emailer { const channelName = video.VideoChannel.getDisplayName() const videoUrl = WEBSERVER.URL + video.getWatchStaticPath() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `Your subscription ${channelName} just published a new video: ${video.name}` + - `\n\n` + + '\n\n' + `You can view it on ${videoUrl} ` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -118,10 +119,10 @@ class Emailer { const followerName = actorFollow.ActorFollower.Account.getDisplayName() const followingName = (actorFollow.ActorFollowing.VideoChannel || actorFollow.ActorFollowing.Account).getDisplayName() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `Your ${followType} ${followingName} has a new subscriber: ${followerName}` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -136,10 +137,10 @@ class Emailer { addNewInstanceFollowerNotification (to: string[], actorFollow: MActorFollowActors) { const awaitingApproval = actorFollow.state === 'pending' ? ' awaiting manual approval.' : '' - const text = `Hi dear admin,\n\n` + + const text = 'Hi dear admin,\n\n' + `Your instance has a new follower: ${actorFollow.ActorFollower.url}${awaitingApproval}` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -152,10 +153,10 @@ class Emailer { } addAutoInstanceFollowingNotification (to: string[], actorFollow: MActorFollowActors) { - const text = `Hi dear admin,\n\n` + + const text = 'Hi dear admin,\n\n' + `Your instance automatically followed a new instance: ${actorFollow.ActorFollowing.url}` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -170,12 +171,12 @@ class Emailer { myVideoPublishedNotification (to: string[], video: MVideo) { const videoUrl = WEBSERVER.URL + video.getWatchStaticPath() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `Your video ${video.name} has been published.` + - `\n\n` + + '\n\n' + `You can view it on ${videoUrl} ` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -190,12 +191,12 @@ class Emailer { myVideoImportSuccessNotification (to: string[], videoImport: MVideoImportVideo) { const videoUrl = WEBSERVER.URL + videoImport.Video.getWatchStaticPath() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `Your video import ${videoImport.getTargetIdentifier()} is finished.` + - `\n\n` + + '\n\n' + `You can view the imported video on ${videoUrl} ` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -210,12 +211,12 @@ class Emailer { myVideoImportErrorNotification (to: string[], videoImport: MVideoImport) { const importUrl = WEBSERVER.URL + '/my-account/video-imports' - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `Your video import ${videoImport.getTargetIdentifier()} encountered an error.` + - `\n\n` + + '\n\n' + `See your videos import dashboard for more information: ${importUrl}` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -232,12 +233,12 @@ class Emailer { const video = comment.Video const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `A new comment has been posted by ${accountName} on your video ${video.name}` + - `\n\n` + + '\n\n' + `You can view it on ${commentUrl} ` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -254,12 +255,12 @@ class Emailer { const video = comment.Video const commentUrl = WEBSERVER.URL + comment.getCommentStaticPath() - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `${accountName} mentioned you on video ${video.name}` + - `\n\n` + + '\n\n' + `You can view the comment on ${commentUrl} ` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -274,9 +275,9 @@ class Emailer { addVideoAbuseModeratorsNotification (to: string[], videoAbuse: MVideoAbuseVideo) { const videoUrl = WEBSERVER.URL + videoAbuse.Video.getWatchStaticPath() - const text = `Hi,\n\n` + + const text = 'Hi,\n\n' + `${WEBSERVER.HOST} received an abuse for the following video ${videoUrl}\n\n` + - `Cheers,\n` + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -292,14 +293,14 @@ class Emailer { const VIDEO_AUTO_BLACKLIST_URL = WEBSERVER.URL + '/admin/moderation/video-auto-blacklist/list' const videoUrl = WEBSERVER.URL + videoBlacklist.Video.getWatchStaticPath() - const text = `Hi,\n\n` + - `A recently added video was auto-blacklisted and requires moderator review before publishing.` + - `\n\n` + + const text = 'Hi,\n\n' + + 'A recently added video was auto-blacklisted and requires moderator review before publishing.' + + '\n\n' + `You can view it and take appropriate action on ${videoUrl}` + - `\n\n` + + '\n\n' + `A full list of auto-blacklisted videos can be reviewed here: ${VIDEO_AUTO_BLACKLIST_URL}` + - `\n\n` + - `Cheers,\n` + + '\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -312,9 +313,9 @@ class Emailer { } addNewUserRegistrationNotification (to: string[], user: MUser) { - const text = `Hi,\n\n` + + const text = 'Hi,\n\n' + `User ${user.username} just registered on ${WEBSERVER.HOST} PeerTube instance.\n\n` + - `Cheers,\n` + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -367,11 +368,11 @@ class Emailer { } addPasswordResetEmailJob (to: string, resetPasswordUrl: string) { - const text = `Hi dear user,\n\n` + + const text = 'Hi dear user,\n\n' + `A reset password procedure for your account ${to} has been requested on ${WEBSERVER.HOST} ` + `Please follow this link to reset it: ${resetPasswordUrl} (the link will expire within 1 hour)\n\n` + - `If you are not the person who initiated this request, please ignore this email.\n\n` + - `Cheers,\n` + + 'If you are not the person who initiated this request, please ignore this email.\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { @@ -384,11 +385,11 @@ class Emailer { } addVerifyEmailJob (to: string, verifyEmailUrl: string) { - const text = `Welcome to PeerTube,\n\n` + + const text = 'Welcome to PeerTube,\n\n' + `To start using PeerTube on ${WEBSERVER.HOST} you must verify your email! ` + `Please follow this link to verify this email belongs to you: ${verifyEmailUrl}\n\n` + - `If you are not the person who initiated this request, please ignore this email.\n\n` + - `Cheers,\n` + + 'If you are not the person who initiated this request, please ignore this email.\n\n' + + 'Cheers,\n' + `${CONFIG.EMAIL.BODY.SIGNATURE}` const emailPayload: EmailPayload = { diff --git a/server/lib/files-cache/videos-preview-cache.ts b/server/lib/files-cache/videos-preview-cache.ts index 7bfeb5783..d0d4fc5b5 100644 --- a/server/lib/files-cache/videos-preview-cache.ts +++ b/server/lib/files-cache/videos-preview-cache.ts @@ -1,9 +1,8 @@ import { join } from 'path' -import { FILES_CACHE, STATIC_PATHS } from '../../initializers/constants' +import { FILES_CACHE } from '../../initializers/constants' import { VideoModel } from '../../models/video/video' import { AbstractVideoStaticFileCache } from './abstract-video-static-file-cache' import { doRequestAndSaveToFile } from '@server/helpers/requests' -import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub' class VideosPreviewCache extends AbstractVideoStaticFileCache { diff --git a/server/lib/job-queue/handlers/utils/activitypub-http-utils.ts b/server/lib/job-queue/handlers/utils/activitypub-http-utils.ts index d3bde6e6a..a28f3596f 100644 --- a/server/lib/job-queue/handlers/utils/activitypub-http-utils.ts +++ b/server/lib/job-queue/handlers/utils/activitypub-http-utils.ts @@ -42,7 +42,7 @@ async function buildSignedRequestOptions (payload: Payload) { function buildGlobalHeaders (body: any) { return { - 'Digest': buildDigest(body) + Digest: buildDigest(body) } } diff --git a/server/lib/job-queue/handlers/video-file-import.ts b/server/lib/job-queue/handlers/video-file-import.ts index 99c991e72..be9e7d181 100644 --- a/server/lib/job-queue/handlers/video-file-import.ts +++ b/server/lib/job-queue/handlers/video-file-import.ts @@ -11,7 +11,7 @@ import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { getVideoFilePath } from '@server/lib/video-paths' export type VideoFileImportPayload = { - videoUUID: string, + videoUUID: string filePath: string } diff --git a/server/lib/job-queue/handlers/video-import.ts b/server/lib/job-queue/handlers/video-import.ts index 1fca17584..09f225cec 100644 --- a/server/lib/job-queue/handlers/video-import.ts +++ b/server/lib/job-queue/handlers/video-import.ts @@ -221,7 +221,7 @@ async function processFile (downloader: () => Promise, videoImport: MVid isNewVideo: true } - await JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }) + await JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: dataInput }) } } catch (err) { diff --git a/server/lib/job-queue/handlers/video-transcoding.ts b/server/lib/job-queue/handlers/video-transcoding.ts index 39b9fac98..c020057c9 100644 --- a/server/lib/job-queue/handlers/video-transcoding.ts +++ b/server/lib/job-queue/handlers/video-transcoding.ts @@ -6,7 +6,6 @@ import { JobQueue } from '../job-queue' import { federateVideoIfNeeded } from '../../activitypub' import { retryTransactionWrapper } from '../../../helpers/database-utils' import { sequelizeTypescript } from '../../../initializers' -import * as Bluebird from 'bluebird' import { computeResolutionsToTranscode } from '../../../helpers/ffmpeg-utils' import { generateHlsPlaylist, mergeAudioVideofile, optimizeOriginalVideofile, transcodeNewResolution } from '../../video-transcoding' import { Notifier } from '../../notifier' @@ -40,8 +39,11 @@ interface OptimizeTranscodingPayload extends BaseTranscodingPayload { type: 'optimize' } -export type VideoTranscodingPayload = HLSTranscodingPayload | NewResolutionTranscodingPayload - | OptimizeTranscodingPayload | MergeAudioTranscodingPayload +export type VideoTranscodingPayload = + HLSTranscodingPayload + | NewResolutionTranscodingPayload + | OptimizeTranscodingPayload + | MergeAudioTranscodingPayload async function processVideoTranscoding (job: Bull.Job) { const payload = job.data as VideoTranscodingPayload @@ -105,7 +107,7 @@ async function onVideoFileOptimizerSuccess (videoArg: MVideoWithFile, payload: O const { videoDatabase, videoPublished } = await sequelizeTypescript.transaction(async t => { // Maybe the video changed in database, refresh it - let videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t) + const videoDatabase = await VideoModel.loadAndPopulateAccountAndServerAndTags(videoArg.uuid, t) // Video does not exist anymore if (!videoDatabase) return undefined @@ -122,8 +124,6 @@ async function onVideoFileOptimizerSuccess (videoArg: MVideoWithFile, payload: O await createHlsJobIfEnabled(hlsPayload) if (resolutionsEnabled.length !== 0) { - const tasks: (Bluebird> | Promise>)[] = [] - for (const resolution of resolutionsEnabled) { let dataInput: VideoTranscodingPayload @@ -143,12 +143,9 @@ async function onVideoFileOptimizerSuccess (videoArg: MVideoWithFile, payload: O } } - const p = JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }) - tasks.push(p) + JobQueue.Instance.createJob({ type: 'video-transcoding', payload: dataInput }) } - await Promise.all(tasks) - logger.info('Transcoding jobs created for uuid %s.', videoDatabase.uuid, { resolutionsEnabled }) } else { // No transcoding to do, it's now published diff --git a/server/lib/job-queue/job-queue.ts b/server/lib/job-queue/job-queue.ts index 61f07c487..14acace7d 100644 --- a/server/lib/job-queue/job-queue.ts +++ b/server/lib/job-queue/job-queue.ts @@ -28,7 +28,7 @@ type CreateJobArgument = { type: 'videos-views', payload: {} } | { type: 'video-redundancy', payload: VideoRedundancyPayload } -const handlers: { [ id in JobType ]: (job: Bull.Job) => Promise} = { +const handlers: { [id in JobType]: (job: Bull.Job) => Promise } = { 'activitypub-http-broadcast': processActivityPubHttpBroadcast, 'activitypub-http-unicast': processActivityPubHttpUnicast, 'activitypub-http-fetcher': processActivityPubHttpFetcher, @@ -60,13 +60,14 @@ class JobQueue { private static instance: JobQueue - private queues: { [ id in JobType ]?: Bull.Queue } = {} + private queues: { [id in JobType]?: Bull.Queue } = {} private initialized = false private jobRedisPrefix: string - private constructor () {} + private constructor () { + } - async init () { + init () { // Already initialized if (this.initialized === true) return this.initialized = true @@ -108,11 +109,16 @@ class JobQueue { } } - createJob (obj: CreateJobArgument) { + createJob (obj: CreateJobArgument): void { + this.createJobWithPromise(obj) + .catch(err => logger.error('Cannot create job.', { err, obj })) + } + + createJobWithPromise (obj: CreateJobArgument) { const queue = this.queues[obj.type] if (queue === undefined) { logger.error('Unknown queue %s: cannot create job.', obj.type) - throw Error('Unknown queue, cannot create job') + return } const jobArgs: Bull.JobOptions = { @@ -125,10 +131,10 @@ class JobQueue { } async listForApi (options: { - state: JobState, - start: number, - count: number, - asc?: boolean, + state: JobState + start: number + count: number + asc?: boolean jobType: JobType }): Promise { const { state, start, count, asc, jobType } = options @@ -137,7 +143,7 @@ class JobQueue { const filteredJobTypes = this.filterJobTypes(jobType) for (const jobType of filteredJobTypes) { - const queue = this.queues[ jobType ] + const queue = this.queues[jobType] if (queue === undefined) { logger.error('Unknown queue %s to list jobs.', jobType) continue @@ -165,7 +171,7 @@ class JobQueue { const filteredJobTypes = this.filterJobTypes(jobType) for (const type of filteredJobTypes) { - const queue = this.queues[ type ] + const queue = this.queues[type] if (queue === undefined) { logger.error('Unknown queue %s to count jobs.', type) continue @@ -173,7 +179,7 @@ class JobQueue { const counts = await queue.getJobCounts() - total += counts[ state ] + total += counts[state] } return total @@ -189,7 +195,7 @@ class JobQueue { private addRepeatableJobs () { this.queues['videos-views'].add({}, { repeat: REPEAT_JOBS['videos-views'] - }) + }).catch(err => logger.error('Cannot add repeatable job.', { err })) } private filterJobTypes (jobType?: JobType) { diff --git a/server/lib/moderation.ts b/server/lib/moderation.ts index b609f4585..55f7a985d 100644 --- a/server/lib/moderation.ts +++ b/server/lib/moderation.ts @@ -15,41 +15,41 @@ export type AcceptResult = { // Can be filtered by plugins function isLocalVideoAccepted (object: { - videoBody: VideoCreate, - videoFile: Express.Multer.File & { duration?: number }, + videoBody: VideoCreate + videoFile: Express.Multer.File & { duration?: number } user: UserModel }): AcceptResult { return { accepted: true } } function isLocalVideoThreadAccepted (_object: { - commentBody: VideoCommentCreate, - video: VideoModel, + commentBody: VideoCommentCreate + video: VideoModel user: UserModel }): AcceptResult { return { accepted: true } } function isLocalVideoCommentReplyAccepted (_object: { - commentBody: VideoCommentCreate, - parentComment: VideoCommentModel, - video: VideoModel, + commentBody: VideoCommentCreate + parentComment: VideoCommentModel + video: VideoModel user: UserModel }): AcceptResult { return { accepted: true } } function isRemoteVideoAccepted (_object: { - activity: ActivityCreate, - videoAP: VideoTorrentObject, + activity: ActivityCreate + videoAP: VideoTorrentObject byActor: ActorModel }): AcceptResult { return { accepted: true } } function isRemoteVideoCommentAccepted (_object: { - activity: ActivityCreate, - commentAP: VideoCommentObject, + activity: ActivityCreate + commentAP: VideoCommentObject byActor: ActorModel }): AcceptResult { return { accepted: true } diff --git a/server/lib/notifier.ts b/server/lib/notifier.ts index 679b9bcf6..63197eee1 100644 --- a/server/lib/notifier.ts +++ b/server/lib/notifier.ts @@ -6,7 +6,6 @@ import { UserModel } from '../models/account/user' import { PeerTubeSocket } from './peertube-socket' import { CONFIG } from '../initializers/config' import { VideoPrivacy, VideoState } from '../../shared/models/videos' -import * as Bluebird from 'bluebird' import { AccountBlocklistModel } from '../models/account/account-blocklist' import { MCommentOwnerVideo, @@ -17,7 +16,8 @@ import { MVideoFullLight } from '../typings/models/video' import { - MUser, MUserAccount, + MUser, + MUserAccount, MUserDefault, MUserNotifSettingAccount, MUserWithNotificationSetting, @@ -32,14 +32,15 @@ class Notifier { private static instance: Notifier - private constructor () {} + private constructor () { + } notifyOnNewVideoIfNeeded (video: MVideoAccountLight): void { // Only notify on public and published videos which are not blacklisted if (video.privacy !== VideoPrivacy.PUBLIC || video.state !== VideoState.PUBLISHED || video.isBlacklisted()) return this.notifySubscribersOfNewVideo(video) - .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err })) + .catch(err => logger.error('Cannot notify subscribers of new video %s.', video.url, { err })) } notifyOnVideoPublishedAfterTranscoding (video: MVideoFullLight): void { @@ -63,7 +64,9 @@ class Notifier { if (video.ScheduleVideoUpdate || (video.waitTranscoding && video.state !== VideoState.PUBLISHED)) return this.notifyOwnedVideoHasBeenPublished(video) - .catch(err => logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err })) // tslint:disable-line:max-line-length + .catch(err => { + logger.error('Cannot notify owner that its video %s has been published after removed from auto-blacklist.', video.url, { err }) + }) } notifyOnNewComment (comment: MCommentOwnerVideo): void { @@ -76,17 +79,17 @@ class Notifier { notifyOnNewVideoAbuse (videoAbuse: MVideoAbuseVideo): void { this.notifyModeratorsOfNewVideoAbuse(videoAbuse) - .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err })) + .catch(err => logger.error('Cannot notify of new video abuse of video %s.', videoAbuse.Video.url, { err })) } notifyOnVideoAutoBlacklist (videoBlacklist: MVideoBlacklistLightVideo): void { this.notifyModeratorsOfVideoAutoBlacklist(videoBlacklist) - .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err })) + .catch(err => logger.error('Cannot notify of auto-blacklist of video %s.', videoBlacklist.Video.url, { err })) } notifyOnVideoBlacklist (videoBlacklist: MVideoBlacklistVideo): void { this.notifyVideoOwnerOfBlacklist(videoBlacklist) - .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err })) + .catch(err => logger.error('Cannot notify video owner of new video blacklist of %s.', videoBlacklist.Video.url, { err })) } notifyOnVideoUnblacklist (video: MVideoFullLight): void { @@ -96,7 +99,7 @@ class Notifier { notifyOnFinishedVideoImport (videoImport: MVideoImportVideo, success: boolean): void { this.notifyOwnerVideoImportIsFinished(videoImport, success) - .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err })) + .catch(err => logger.error('Cannot notify owner that its video import %s is finished.', videoImport.getTargetIdentifier(), { err })) } notifyOnNewUserRegistration (user: MUserDefault): void { @@ -106,14 +109,14 @@ class Notifier { notifyOfNewUserFollow (actorFollow: MActorFollowFull): void { this.notifyUserOfNewActorFollow(actorFollow) - .catch(err => { - logger.error( - 'Cannot notify owner of channel %s of a new follow by %s.', - actorFollow.ActorFollowing.VideoChannel.getDisplayName(), - actorFollow.ActorFollower.Account.getDisplayName(), - { err } - ) - }) + .catch(err => { + logger.error( + 'Cannot notify owner of channel %s of a new follow by %s.', + actorFollow.ActorFollowing.VideoChannel.getDisplayName(), + actorFollow.ActorFollower.Account.getDisplayName(), + { err } + ) + }) } notifyOfNewInstanceFollow (actorFollow: MActorFollowFull): void { @@ -548,10 +551,10 @@ class Notifier { return this.notify({ users: moderators, settingGetter, notificationCreator, emailSender }) } - private async notify (options: { - users: T[], - notificationCreator: (user: T) => Promise, - emailSender: (emails: string[]) => Promise | Bluebird, + private async notify (options: { + users: T[] + notificationCreator: (user: T) => Promise + emailSender: (emails: string[]) => void settingGetter: (user: T) => UserNotificationSettingValue }) { const emails: string[] = [] @@ -569,7 +572,7 @@ class Notifier { } if (emails.length !== 0) { - await options.emailSender(emails) + options.emailSender(emails) } } diff --git a/server/lib/plugins/plugin-index.ts b/server/lib/plugins/plugin-index.ts index 25b4f3c61..dcdfba28c 100644 --- a/server/lib/plugins/plugin-index.ts +++ b/server/lib/plugins/plugin-index.ts @@ -31,7 +31,7 @@ async function listAvailablePluginsFromIndex (options: PeertubePluginIndexList) logger.debug('Got result from PeerTube index.', { body }) - await addInstanceInformation(body) + addInstanceInformation(body) return body as ResultList } catch (err) { @@ -40,7 +40,7 @@ async function listAvailablePluginsFromIndex (options: PeertubePluginIndexList) } } -async function addInstanceInformation (result: ResultList) { +function addInstanceInformation (result: ResultList) { for (const d of result.data) { d.installed = PluginManager.Instance.isRegistered(d.npmName) d.name = PluginModel.normalizePluginName(d.npmName) diff --git a/server/lib/plugins/plugin-manager.ts b/server/lib/plugins/plugin-manager.ts index 7ebdabd34..73f7a71ce 100644 --- a/server/lib/plugins/plugin-manager.ts +++ b/server/lib/plugins/plugin-manager.ts @@ -55,30 +55,30 @@ export interface HookInformationValue { } type AlterableVideoConstant = 'language' | 'licence' | 'category' -type VideoConstant = { [ key in number | string ]: string } +type VideoConstant = { [key in number | string]: string } type UpdatedVideoConstant = { - [ name in AlterableVideoConstant ]: { - [ npmName: string ]: { - added: { key: number | string, label: string }[], + [name in AlterableVideoConstant]: { + [npmName: string]: { + added: { key: number | string, label: string }[] deleted: { key: number | string, label: string }[] } } } type PluginLocalesTranslations = { - [ locale: string ]: PluginTranslation + [locale: string]: PluginTranslation } export class PluginManager implements ServerHook { private static instance: PluginManager - private registeredPlugins: { [ name: string ]: RegisteredPlugin } = {} - private settings: { [ name: string ]: RegisterServerSettingOptions[] } = {} - private hooks: { [ name: string ]: HookInformationValue[] } = {} + private registeredPlugins: { [name: string]: RegisteredPlugin } = {} + private settings: { [name: string]: RegisterServerSettingOptions[] } = {} + private hooks: { [name: string]: HookInformationValue[] } = {} private translations: PluginLocalesTranslations = {} - private updatedVideoConstants: UpdatedVideoConstant = { + private readonly updatedVideoConstants: UpdatedVideoConstant = { language: {}, licence: {}, category: {} @@ -133,7 +133,7 @@ export class PluginManager implements ServerHook { // ###################### Hooks ###################### - async runHook (hookName: ServerHookName, result?: T, params?: any): Promise { + async runHook (hookName: ServerHookName, result?: T, params?: any): Promise { if (!this.hooks[hookName]) return Promise.resolve(result) const hookType = getHookType(hookName) @@ -312,7 +312,7 @@ export class PluginManager implements ServerHook { clientScripts[c.script] = c } - this.registeredPlugins[ npmName ] = { + this.registeredPlugins[npmName] = { npmName, name: plugin.name, type: plugin.type, @@ -438,7 +438,7 @@ export class PluginManager implements ServerHook { const plugins: RegisteredPlugin[] = [] for (const npmName of Object.keys(this.registeredPlugins)) { - const plugin = this.registeredPlugins[ npmName ] + const plugin = this.registeredPlugins[npmName] if (plugin.type !== type) continue plugins.push(plugin) @@ -518,11 +518,11 @@ export class PluginManager implements ServerHook { } } - private addConstant (parameters: { - npmName: string, - type: AlterableVideoConstant, - obj: VideoConstant, - key: T, + private addConstant (parameters: { + npmName: string + type: AlterableVideoConstant + obj: VideoConstant + key: T label: string }) { const { npmName, type, obj, key, label } = parameters @@ -545,10 +545,10 @@ export class PluginManager implements ServerHook { return true } - private deleteConstant (parameters: { - npmName: string, - type: AlterableVideoConstant, - obj: VideoConstant, + private deleteConstant (parameters: { + npmName: string + type: AlterableVideoConstant + obj: VideoConstant key: T }) { const { npmName, type, obj, key } = parameters @@ -604,7 +604,7 @@ export class PluginManager implements ServerHook { const { result: packageJSONValid, badFields } = isPackageJSONValid(packageJSON, pluginType) if (!packageJSONValid) { const formattedFields = badFields.map(f => `"${f}"`) - .join(', ') + .join(', ') throw new Error(`PackageJSON is invalid (invalid fields: ${formattedFields}).`) } diff --git a/server/lib/redis.ts b/server/lib/redis.ts index f77d0b62c..0c5dbdd3e 100644 --- a/server/lib/redis.ts +++ b/server/lib/redis.ts @@ -12,7 +12,7 @@ import { import { CONFIG } from '../initializers/config' type CachedRoute = { - body: string, + body: string contentType?: string statusCode?: string } @@ -24,7 +24,8 @@ class Redis { private client: RedisClient private prefix: string - private constructor () {} + private constructor () { + } init () { // Already initialized @@ -49,9 +50,9 @@ class Redis { return Object.assign({}, (CONFIG.REDIS.AUTH && CONFIG.REDIS.AUTH != null) ? { password: CONFIG.REDIS.AUTH } : {}, (CONFIG.REDIS.DB) ? { db: CONFIG.REDIS.DB } : {}, - (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) ? - { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } : - { path: CONFIG.REDIS.SOCKET } + (CONFIG.REDIS.HOSTNAME && CONFIG.REDIS.PORT) + ? { host: CONFIG.REDIS.HOSTNAME, port: CONFIG.REDIS.PORT } + : { path: CONFIG.REDIS.SOCKET } ) } @@ -63,7 +64,7 @@ class Redis { return this.prefix } - /************* Forgot password *************/ + /* ************ Forgot password ************ */ async setResetPasswordVerificationString (userId: number) { const generatedString = await generateRandomString(32) @@ -77,7 +78,7 @@ class Redis { return this.getValue(this.generateResetPasswordKey(userId)) } - /************* Email verification *************/ + /* ************ Email verification ************ */ async setVerifyEmailVerificationString (userId: number) { const generatedString = await generateRandomString(32) @@ -91,7 +92,7 @@ class Redis { return this.getValue(this.generateVerifyEmailKey(userId)) } - /************* Contact form per IP *************/ + /* ************ Contact form per IP ************ */ async setContactFormIp (ip: string) { return this.setValue(this.generateContactFormKey(ip), '1', CONTACT_FORM_LIFETIME) @@ -101,7 +102,7 @@ class Redis { return this.exists(this.generateContactFormKey(ip)) } - /************* Views per IP *************/ + /* ************ Views per IP ************ */ setIPVideoView (ip: string, videoUUID: string) { return this.setValue(this.generateViewKey(ip, videoUUID), '1', VIDEO_VIEW_LIFETIME) @@ -111,7 +112,7 @@ class Redis { return this.exists(this.generateViewKey(ip, videoUUID)) } - /************* API cache *************/ + /* ************ API cache ************ */ async getCachedRoute (req: express.Request) { const cached = await this.getObject(this.generateCachedRouteKey(req)) @@ -120,17 +121,17 @@ class Redis { } setCachedRoute (req: express.Request, body: any, lifetime: number, contentType?: string, statusCode?: number) { - const cached: CachedRoute = Object.assign({}, { - body: body.toString() - }, - (contentType) ? { contentType } : null, - (statusCode) ? { statusCode: statusCode.toString() } : null + const cached: CachedRoute = Object.assign( + {}, + { body: body.toString() }, + (contentType) ? { contentType } : null, + (statusCode) ? { statusCode: statusCode.toString() } : null ) return this.setObject(this.generateCachedRouteKey(req), cached, lifetime) } - /************* Video views *************/ + /* ************ Video views ************ */ addVideoView (videoId: number) { const keyIncr = this.generateVideoViewKey(videoId) @@ -173,7 +174,7 @@ class Redis { ]) } - /************* Keys generation *************/ + /* ************ Keys generation ************ */ generateCachedRouteKey (req: express.Request) { return req.method + '-' + req.originalUrl @@ -207,7 +208,7 @@ class Redis { return 'contact-form-' + ip } - /************* Redis helpers *************/ + /* ************ Redis helpers ************ */ private getValue (key: string) { return new Promise((res, rej) => { @@ -265,7 +266,7 @@ class Redis { }) } - private setObject (key: string, obj: { [ id: string ]: string }, expirationMilliseconds: number) { + private setObject (key: string, obj: { [id: string]: string }, expirationMilliseconds: number) { return new Promise((res, rej) => { this.client.hmset(this.prefix + key, obj, (err, ok) => { if (err) return rej(err) @@ -282,7 +283,7 @@ class Redis { } private getObject (key: string) { - return new Promise<{ [ id: string ]: string }>((res, rej) => { + return new Promise<{ [id: string]: string }>((res, rej) => { this.client.hgetall(this.prefix + key, (err, value) => { if (err) return rej(err) diff --git a/server/lib/schedulers/auto-follow-index-instances.ts b/server/lib/schedulers/auto-follow-index-instances.ts index dd326bc1e..d700a99f0 100644 --- a/server/lib/schedulers/auto-follow-index-instances.ts +++ b/server/lib/schedulers/auto-follow-index-instances.ts @@ -57,8 +57,7 @@ export class AutoFollowIndexInstances extends AbstractScheduler { isAutoFollow: true } - await JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) - .catch(err => logger.error('Cannot create follow job for %s.', unfollowedHost, err)) + JobQueue.Instance.createJob({ type: 'activitypub-follow', payload }) } } diff --git a/server/lib/schedulers/plugins-check-scheduler.ts b/server/lib/schedulers/plugins-check-scheduler.ts index 7ff41e639..014993e94 100644 --- a/server/lib/schedulers/plugins-check-scheduler.ts +++ b/server/lib/schedulers/plugins-check-scheduler.ts @@ -43,7 +43,7 @@ export class PluginsCheckScheduler extends AbstractScheduler { const results = await getLatestPluginsVersion(npmNames) for (const result of results) { - const plugin = pluginIndex[ result.npmName ] + const plugin = pluginIndex[result.npmName] if (!result.latestVersion) continue if ( diff --git a/server/lib/schedulers/remove-old-views-scheduler.ts b/server/lib/schedulers/remove-old-views-scheduler.ts index 39fbb9163..5ae87fe50 100644 --- a/server/lib/schedulers/remove-old-views-scheduler.ts +++ b/server/lib/schedulers/remove-old-views-scheduler.ts @@ -1,9 +1,7 @@ import { logger } from '../../helpers/logger' import { AbstractScheduler } from './abstract-scheduler' import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants' -import { UserVideoHistoryModel } from '../../models/account/user-video-history' import { CONFIG } from '../../initializers/config' -import { isTestInstance } from '../../helpers/core-utils' import { VideoViewModel } from '../../models/video/video-views' export class RemoveOldViewsScheduler extends AbstractScheduler { diff --git a/server/lib/schedulers/videos-redundancy-scheduler.ts b/server/lib/schedulers/videos-redundancy-scheduler.ts index 6e61cbe7d..e33a4133a 100644 --- a/server/lib/schedulers/videos-redundancy-scheduler.ts +++ b/server/lib/schedulers/videos-redundancy-scheduler.ts @@ -28,9 +28,9 @@ import { getVideoFilename } from '../video-paths' import { VideoModel } from '@server/models/video/video' type CandidateToDuplicate = { - redundancy: VideosRedundancyStrategy, - video: MVideoWithAllFiles, - files: MVideoFile[], + redundancy: VideosRedundancyStrategy + video: MVideoWithAllFiles + files: MVideoFile[] streamingPlaylists: MStreamingPlaylistFiles[] } diff --git a/server/lib/thumbnail.ts b/server/lib/thumbnail.ts index a99f71629..8dbd41771 100644 --- a/server/lib/thumbnail.ts +++ b/server/lib/thumbnail.ts @@ -69,7 +69,7 @@ function generateVideoMiniature (video: MVideoThumbnail, videoFile: MVideoFile, function createPlaceholderThumbnail (fileUrl: string, video: MVideoThumbnail, type: ThumbnailType, size: ImageSize) { const { filename, height, width, existingThumbnail } = buildMetadataFromVideo(video, type, size) - const thumbnail = existingThumbnail ? existingThumbnail : new ThumbnailModel() + const thumbnail = existingThumbnail || new ThumbnailModel() thumbnail.filename = filename thumbnail.height = height @@ -142,18 +142,18 @@ function buildMetadataFromVideo (video: MVideoThumbnail, type: ThumbnailType, si } async function createThumbnailFromFunction (parameters: { - thumbnailCreator: () => Promise, - filename: string, - height: number, - width: number, - type: ThumbnailType, - automaticallyGenerated?: boolean, - fileUrl?: string, + thumbnailCreator: () => Promise + filename: string + height: number + width: number + type: ThumbnailType + automaticallyGenerated?: boolean + fileUrl?: string existingThumbnail?: MThumbnail }) { const { thumbnailCreator, filename, width, height, type, existingThumbnail, automaticallyGenerated = null, fileUrl = null } = parameters - const thumbnail = existingThumbnail ? existingThumbnail : new ThumbnailModel() + const thumbnail = existingThumbnail || new ThumbnailModel() thumbnail.filename = filename thumbnail.height = height diff --git a/server/lib/user.ts b/server/lib/user.ts index c45438d95..88e60a7df 100644 --- a/server/lib/user.ts +++ b/server/lib/user.ts @@ -18,9 +18,9 @@ import { MUser, MUserDefault, MUserId } from '../typings/models/user' type ChannelNames = { name: string, displayName: string } async function createUserAccountAndChannelAndPlaylist (parameters: { - userToCreate: MUser, - userDisplayName?: string, - channelNames?: ChannelNames, + userToCreate: MUser + userDisplayName?: string + channelNames?: ChannelNames validateUser?: boolean }): Promise<{ user: MUserDefault, account: MAccountDefault, videoChannel: MChannelActor }> { const { userToCreate, userDisplayName, channelNames, validateUser = true } = parameters @@ -63,11 +63,11 @@ async function createUserAccountAndChannelAndPlaylist (parameters: { } async function createLocalAccountWithoutKeys (parameters: { - name: string, - displayName?: string, - userId: number | null, - applicationId: number | null, - t: Transaction | undefined, + name: string + displayName?: string + userId: number | null + applicationId: number | null + t: Transaction | undefined type?: ActivityPubActorType }) { const { name, displayName, userId, applicationId, t, type = 'Person' } = parameters diff --git a/server/lib/video-blacklist.ts b/server/lib/video-blacklist.ts index 1dd45b76d..3b90b1b94 100644 --- a/server/lib/video-blacklist.ts +++ b/server/lib/video-blacklist.ts @@ -9,15 +9,15 @@ import { Notifier } from './notifier' import { MUser, MVideoBlacklistVideo, MVideoWithBlacklistLight } from '@server/typings/models' async function autoBlacklistVideoIfNeeded (parameters: { - video: MVideoWithBlacklistLight, - user?: MUser, - isRemote: boolean, - isNew: boolean, - notify?: boolean, + video: MVideoWithBlacklistLight + user?: MUser + isRemote: boolean + isNew: boolean + notify?: boolean transaction?: Transaction }) { const { video, user, isRemote, isNew, notify = true, transaction } = parameters - const doAutoBlacklist = await Hooks.wrapPromiseFun( + const doAutoBlacklist = await Hooks.wrapFun( autoBlacklistNeeded, { video, user, isRemote, isNew }, 'filter:video.auto-blacklist.result' @@ -49,10 +49,10 @@ async function autoBlacklistVideoIfNeeded (parameters: { return true } -async function autoBlacklistNeeded (parameters: { - video: MVideoWithBlacklistLight, - isRemote: boolean, - isNew: boolean, +function autoBlacklistNeeded (parameters: { + video: MVideoWithBlacklistLight + isRemote: boolean + isNew: boolean user?: MUser }) { const { user, video, isRemote, isNew } = parameters diff --git a/server/lib/video-channel.ts b/server/lib/video-channel.ts index 41eab456b..14829c9d6 100644 --- a/server/lib/video-channel.ts +++ b/server/lib/video-channel.ts @@ -6,8 +6,7 @@ import { buildActorInstance, federateVideoIfNeeded, getVideoChannelActivityPubUr import { VideoModel } from '../models/video/video' import { MAccountId, MChannelDefault, MChannelId } from '../typings/models' -type CustomVideoChannelModelAccount = MChannelDefault & - { Account?: T } +type CustomVideoChannelModelAccount = MChannelDefault & { Account?: T } async function createLocalVideoChannel ( videoChannelInfo: VideoChannelCreate, diff --git a/server/lib/video-comment.ts b/server/lib/video-comment.ts index b8074e6d2..fe83d23e7 100644 --- a/server/lib/video-comment.ts +++ b/server/lib/video-comment.ts @@ -7,9 +7,9 @@ import { sendCreateVideoComment } from './activitypub/send' import { MAccountDefault, MComment, MCommentOwnerVideoReply, MVideoFullLight } from '../typings/models' async function createVideoComment (obj: { - text: string, - inReplyToComment: MComment | null, - video: MVideoFullLight, + text: string + inReplyToComment: MComment | null + video: MVideoFullLight account: MAccountDefault }, t: Sequelize.Transaction) { let originCommentId: number | null = null -- cgit v1.2.3