From bfb3a98fac582f104c6d9b8b7242ea2cbb650b91 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 14 Sep 2017 17:06:31 +0200 Subject: [PATCH] Remove ng2 file upload module Unmaintained and we don't need it anymore with httpclient --- client/package.json | 1 - .../friend-add/friend-add.component.ts | 2 +- .../friend-list/friend-list.component.ts | 6 +- .../request-schedulers-stats.component.ts | 2 +- .../users/user-list/user-list.component.ts | 4 +- .../video-abuse-list.component.ts | 2 +- client/src/app/app.component.ts | 3 +- .../app/shared/forms/form-validators/video.ts | 7 + .../app/shared/rest/rest-extractor.service.ts | 18 +- client/src/app/shared/shared.module.ts | 4 - client/src/app/videos/shared/video.service.ts | 25 ++- .../video-edit/video-add.component.html | 21 +-- .../videos/video-edit/video-add.component.ts | 160 +++++++----------- .../video-edit/video-update.component.ts | 1 - .../video-watch/video-report.component.ts | 2 +- .../video-watch/video-watch.component.ts | 6 +- client/yarn.lock | 4 - server/middlewares/validators/pods.ts | 6 +- server/middlewares/validators/users.ts | 36 +++- server/middlewares/validators/videos.ts | 42 +++-- 20 files changed, 189 insertions(+), 163 deletions(-) diff --git a/client/package.json b/client/package.json index caec34e44..8a82a294e 100644 --- a/client/package.json +++ b/client/package.json @@ -61,7 +61,6 @@ "intl": "^1.2.4", "json-loader": "^0.5.4", "ng-router-loader": "^2.0.0", - "ng2-file-upload": "^1.1.4-2", "ngc-webpack": "3.2.2", "ngx-bootstrap": "1.9.1", "ngx-chips": "1.5.3", diff --git a/client/src/app/+admin/friends/friend-add/friend-add.component.ts b/client/src/app/+admin/friends/friend-add/friend-add.component.ts index e0b73dfa3..6580e1b88 100644 --- a/client/src/app/+admin/friends/friend-add/friend-add.component.ts +++ b/client/src/app/+admin/friends/friend-add/friend-add.component.ts @@ -98,7 +98,7 @@ export class FriendAddComponent implements OnInit { setTimeout(() => this.router.navigate([ '/admin/friends/list' ]), 1000) }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } ) diff --git a/client/src/app/+admin/friends/friend-list/friend-list.component.ts b/client/src/app/+admin/friends/friend-list/friend-list.component.ts index 6a8bd492c..4af39c47e 100644 --- a/client/src/app/+admin/friends/friend-list/friend-list.component.ts +++ b/client/src/app/+admin/friends/friend-list/friend-list.component.ts @@ -40,7 +40,7 @@ export class FriendListComponent implements OnInit { this.loadData() }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } ) @@ -59,7 +59,7 @@ export class FriendListComponent implements OnInit { this.loadData() }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } ) @@ -72,7 +72,7 @@ export class FriendListComponent implements OnInit { this.friends = resultList.data }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } } diff --git a/client/src/app/+admin/request-schedulers/request-schedulers-stats/request-schedulers-stats.component.ts b/client/src/app/+admin/request-schedulers/request-schedulers-stats/request-schedulers-stats.component.ts index 1edeb31fe..1654827ab 100644 --- a/client/src/app/+admin/request-schedulers/request-schedulers-stats/request-schedulers-stats.component.ts +++ b/client/src/app/+admin/request-schedulers/request-schedulers-stats/request-schedulers-stats.component.ts @@ -57,7 +57,7 @@ export class RequestSchedulersStatsComponent implements OnInit, OnDestroy { this.requestService.getStats().subscribe( stats => this.stats = stats, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } diff --git a/client/src/app/+admin/users/user-list/user-list.component.ts b/client/src/app/+admin/users/user-list/user-list.component.ts index c3fa55825..73b5c0ce9 100644 --- a/client/src/app/+admin/users/user-list/user-list.component.ts +++ b/client/src/app/+admin/users/user-list/user-list.component.ts @@ -47,7 +47,7 @@ export class UserListComponent extends RestTable implements OnInit { this.loadData() }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } ) @@ -65,7 +65,7 @@ export class UserListComponent extends RestTable implements OnInit { this.totalRecords = resultList.total }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } } diff --git a/client/src/app/+admin/video-abuses/video-abuse-list/video-abuse-list.component.ts b/client/src/app/+admin/video-abuses/video-abuse-list/video-abuse-list.component.ts index 5a0131a81..92de11f0e 100644 --- a/client/src/app/+admin/video-abuses/video-abuse-list/video-abuse-list.component.ts +++ b/client/src/app/+admin/video-abuses/video-abuse-list/video-abuse-list.component.ts @@ -40,7 +40,7 @@ export class VideoAbuseListComponent extends RestTable implements OnInit { this.totalRecords = resultList.total }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } } diff --git a/client/src/app/app.component.ts b/client/src/app/app.component.ts index 57bf64f69..ae86bc96f 100644 --- a/client/src/app/app.component.ts +++ b/client/src/app/app.component.ts @@ -31,8 +31,7 @@ export class AppComponent implements OnInit { private authService: AuthService, private configService: ConfigService, private userService: UserService, - private videoService: VideoService, - viewContainerRef: ViewContainerRef + private videoService: VideoService ) {} ngOnInit () { diff --git a/client/src/app/shared/forms/form-validators/video.ts b/client/src/app/shared/forms/form-validators/video.ts index 6542cf8f6..32b1f1c2e 100644 --- a/client/src/app/shared/forms/form-validators/video.ts +++ b/client/src/app/shared/forms/form-validators/video.ts @@ -44,3 +44,10 @@ export const VIDEO_TAGS = { 'maxlength': 'A tag should be less than 10 characters long.' } } + +export const VIDEO_FILE = { + VALIDATORS: [ Validators.required ], + MESSAGES: { + 'required': 'Video file is required.' + } +} diff --git a/client/src/app/shared/rest/rest-extractor.service.ts b/client/src/app/shared/rest/rest-extractor.service.ts index 32dad5c73..1f6222da8 100644 --- a/client/src/app/shared/rest/rest-extractor.service.ts +++ b/client/src/app/shared/rest/rest-extractor.service.ts @@ -40,19 +40,29 @@ export class RestExtractor { handleError (err: HttpErrorResponse) { let errorMessage + console.log(err) + if (err.error instanceof Error) { // A client-side or network error occurred. Handle it accordingly. errorMessage = err.error.message console.error('An error occurred:', errorMessage) } else if (err.status !== undefined) { - // The backend returned an unsuccessful response code. - // The response body may contain clues as to what went wrong, - errorMessage = err.error + const body = err.error + errorMessage = body.error console.error(`Backend returned code ${err.status}, body was: ${errorMessage}`) } else { errorMessage = err } - return Observable.throw(errorMessage) + const errorObj = { + message: errorMessage, + status: undefined + } + + if (err.status) { + errorObj.status = err.status + } + + return Observable.throw(errorObj) } } diff --git a/client/src/app/shared/shared.module.ts b/client/src/app/shared/shared.module.ts index 118ce822d..a28ac322d 100644 --- a/client/src/app/shared/shared.module.ts +++ b/client/src/app/shared/shared.module.ts @@ -10,7 +10,6 @@ import { BsDropdownModule } from 'ngx-bootstrap/dropdown' import { ProgressbarModule } from 'ngx-bootstrap/progressbar' import { PaginationModule } from 'ngx-bootstrap/pagination' import { ModalModule } from 'ngx-bootstrap/modal' -import { FileUploadModule } from 'ng2-file-upload/ng2-file-upload' import { DataTableModule, SharedModule as PrimeSharedModule } from 'primeng/primeng' import { AUTH_INTERCEPTOR_PROVIDER } from './auth' @@ -32,8 +31,6 @@ import { VideoAbuseService } from './video-abuse' PaginationModule.forRoot(), ProgressbarModule.forRoot(), - FileUploadModule, - DataTableModule, PrimeSharedModule ], @@ -52,7 +49,6 @@ import { VideoAbuseService } from './video-abuse' HttpClientModule, BsDropdownModule, - FileUploadModule, ModalModule, PaginationModule, ProgressbarModule, diff --git a/client/src/app/videos/shared/video.service.ts b/client/src/app/videos/shared/video.service.ts index b6d2a0666..cfce4cb16 100644 --- a/client/src/app/videos/shared/video.service.ts +++ b/client/src/app/videos/shared/video.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core' import { Observable } from 'rxjs/Observable' import 'rxjs/add/operator/catch' import 'rxjs/add/operator/map' -import { HttpClient, HttpParams } from '@angular/common/http' +import { HttpClient, HttpParams, HttpRequest } from '@angular/common/http' import { Search } from '../../shared' import { SortField } from './sort-field.type' @@ -14,13 +14,14 @@ import { import { Video } from './video.model' import { VideoPagination } from './video-pagination.model' import { -UserVideoRate, -VideoRateType, -VideoUpdate, -VideoAbuseCreate, -UserVideoRateUpdate, -Video as VideoServerModel, -ResultList + VideoCreate, + UserVideoRate, + VideoRateType, + VideoUpdate, + VideoAbuseCreate, + UserVideoRateUpdate, + Video as VideoServerModel, + ResultList } from '../../../../../shared' @Injectable() @@ -73,6 +74,14 @@ export class VideoService { .catch(this.restExtractor.handleError) } + // uploadVideo (video: VideoCreate) { + uploadVideo (video: any) { + const req = new HttpRequest('POST', `${VideoService.BASE_VIDEO_URL}/upload`, video, { reportProgress: true }) + + return this.authHttp.request(req) + .catch(this.restExtractor.handleError) + } + getVideos (videoPagination: VideoPagination, sort: SortField) { const pagination = this.videoPaginationToRestPagination(videoPagination) diff --git a/client/src/app/videos/video-edit/video-add.component.html b/client/src/app/videos/video-edit/video-add.component.html index 7ad671ae7..cf8fc2b80 100644 --- a/client/src/app/videos/video-edit/video-add.component.html +++ b/client/src/app/videos/video-edit/video-add.component.html @@ -3,7 +3,7 @@

Upload a video

-
{{ error }}
+
{{ error }}
@@ -62,7 +62,7 @@
- (press enter to add the tag) + (press enter to add the tag) -
+
Select the video... - + +
-
+
{{ filename }}
-
- {{ fileError }} +
+ {{ formErrors.videofile }}
@@ -105,7 +102,7 @@
- +
diff --git a/client/src/app/videos/video-edit/video-add.component.ts b/client/src/app/videos/video-edit/video-add.component.ts index 42b11cd08..537ef9bc3 100644 --- a/client/src/app/videos/video-edit/video-add.component.ts +++ b/client/src/app/videos/video-edit/video-add.component.ts @@ -1,11 +1,9 @@ -import { Component, ElementRef, OnInit } from '@angular/core' +import { Component, OnInit, ViewChild } from '@angular/core' import { FormBuilder, FormGroup } from '@angular/forms' import { Router } from '@angular/router' -import { FileUploader } from 'ng2-file-upload/ng2-file-upload' import { NotificationsService } from 'angular2-notifications' -import { AuthService } from '../../core' import { FormReactive, VIDEO_NAME, @@ -17,6 +15,8 @@ import { } from '../../shared' import { VideoService } from '../shared' import { VideoCreate } from '../../../../../shared' +import { HttpEventType, HttpResponse } from '@angular/common/http' +import { VIDEO_FILE } from '../../shared/forms/form-validators/video' @Component({ selector: 'my-videos-add', @@ -25,8 +25,10 @@ import { VideoCreate } from '../../../../../shared' }) export class VideoAddComponent extends FormReactive implements OnInit { + @ViewChild('videofileInput') videofileInput + + progressPercent = 0 tags: string[] = [] - uploader: FileUploader videoCategories = [] videoLicences = [] videoLanguages = [] @@ -34,29 +36,26 @@ export class VideoAddComponent extends FormReactive implements OnInit { tagValidators = VIDEO_TAGS.VALIDATORS tagValidatorsMessages = VIDEO_TAGS.MESSAGES - error: string = null + error: string form: FormGroup formErrors = { name: '', category: '', licence: '', language: '', - description: '' + description: '', + videofile: '' } validationMessages = { name: VIDEO_NAME.MESSAGES, category: VIDEO_CATEGORY.MESSAGES, licence: VIDEO_LICENCE.MESSAGES, language: VIDEO_LANGUAGE.MESSAGES, - description: VIDEO_DESCRIPTION.MESSAGES + description: VIDEO_DESCRIPTION.MESSAGES, + videofile: VIDEO_FILE.MESSAGES } - // Special error messages - fileError = '' - constructor ( - private authService: AuthService, - private elementRef: ElementRef, private formBuilder: FormBuilder, private router: Router, private notificationsService: NotificationsService, @@ -66,11 +65,7 @@ export class VideoAddComponent extends FormReactive implements OnInit { } get filename () { - if (this.uploader.queue.length === 0) { - return null - } - - return this.uploader.queue[0].file.name + return this.form.value['videofile'] } buildForm () { @@ -81,7 +76,8 @@ export class VideoAddComponent extends FormReactive implements OnInit { licence: [ '', VIDEO_LICENCE.VALIDATORS ], language: [ '', VIDEO_LANGUAGE.VALIDATORS ], description: [ '', VIDEO_DESCRIPTION.VALIDATORS ], - tags: [ ''] + videofile: [ '', VIDEO_FILE.VALIDATORS ], + tags: [ '' ] }) this.form.valueChanges.subscribe(data => this.onValueChanged(data)) @@ -92,60 +88,24 @@ export class VideoAddComponent extends FormReactive implements OnInit { this.videoLicences = this.videoService.videoLicences this.videoLanguages = this.videoService.videoLanguages - this.uploader = new FileUploader({ - authToken: this.authService.getRequestHeaderValue(), - queueLimit: 1, - url: API_URL + '/api/v1/videos/upload', - removeAfterUpload: true - }) - - this.uploader.onBuildItemForm = (item, form: FormData) => { - const formValue: VideoCreate = this.form.value - - const name = formValue.name - const nsfw = formValue.nsfw - const category = formValue.category - const licence = formValue.licence - const language = formValue.language - const description = formValue.description - const tags = formValue.tags - - form.append('name', name) - form.append('category', '' + category) - form.append('nsfw', '' + nsfw) - form.append('licence', '' + licence) - - // Language is optional - if (language) { - form.append('language', '' + language) - } - - form.append('description', description) - - for (let i = 0; i < tags.length; i++) { - form.append(`tags[${i}]`, tags[i]) - } - } - this.buildForm() } - checkForm () { - this.forceCheck() - - if (this.filename === null) { - this.fileError = 'You did not add a file.' - } - - return this.form.valid === true && this.fileError === '' + // The goal is to keep reactive form validation (required field) + // https://stackoverflow.com/a/44238894 + fileChange ($event) { + this.form.controls['videofile'].setValue($event.target.files[0].name) } - fileChanged () { - this.fileError = '' + removeFile () { + this.videofileInput.nativeElement.value = '' + this.form.controls['videofile'].setValue('') } - removeFile () { - this.uploader.clearQueue() + checkForm () { + this.forceCheck() + + return this.form.valid } upload () { @@ -153,39 +113,49 @@ export class VideoAddComponent extends FormReactive implements OnInit { return } - const item = this.uploader.queue[0] - // TODO: wait for https://github.com/valor-software/ng2-file-upload/pull/242 - item.alias = 'videofile' - - item.onSuccess = () => { - console.log('Video uploaded.') - this.notificationsService.success('Success', 'Video uploaded.') - - // Print all the videos once it's finished - this.router.navigate(['/videos/list']) + const formValue: VideoCreate = this.form.value + + const name = formValue.name + const nsfw = formValue.nsfw + const category = formValue.category + const licence = formValue.licence + const language = formValue.language + const description = formValue.description + const tags = formValue.tags + const videofile = this.videofileInput.nativeElement.files[0] + + const formData = new FormData() + formData.append('name', name) + formData.append('category', '' + category) + formData.append('nsfw', '' + nsfw) + formData.append('licence', '' + licence) + formData.append('videofile', videofile) + + // Language is optional + if (language) { + formData.append('language', '' + language) } - item.onError = (response: string, status: number) => { - // We need to handle manually these cases because we use the FileUpload component - if (status === 400) { - this.error = response - } else if (status === 401) { - this.error = 'Access token was expired, refreshing token...' - this.authService.refreshAccessToken().subscribe( - () => { - // Update the uploader request header - this.uploader.authToken = this.authService.getRequestHeaderValue() - this.error += ' access token refreshed. Please retry your request.' - } - ) - } else if (status === 403) { - this.error = 'Your video quota is reached, you can\'t upload this video.' - } else { - this.error = 'Unknown error' - console.error(this.error) - } + formData.append('description', description) + + for (let i = 0; i < tags.length; i++) { + formData.append(`tags[${i}]`, tags[i]) } - this.uploader.uploadAll() + this.videoService.uploadVideo(formData).subscribe( + event => { + if (event.type === HttpEventType.UploadProgress) { + this.progressPercent = Math.round(100 * event.loaded / event.total) + } else if (event instanceof HttpResponse) { + console.log('Video uploaded.') + this.notificationsService.success('Success', 'Video uploaded.') + + // Display all the videos once it's finished + this.router.navigate([ '/videos/list ']) + } + }, + + err => this.error = err.message + ) } } diff --git a/client/src/app/videos/video-edit/video-update.component.ts b/client/src/app/videos/video-edit/video-update.component.ts index 6c57a23d8..141ed3522 100644 --- a/client/src/app/videos/video-edit/video-update.component.ts +++ b/client/src/app/videos/video-edit/video-update.component.ts @@ -2,7 +2,6 @@ import { Component, ElementRef, OnInit } from '@angular/core' import { FormBuilder, FormGroup } from '@angular/forms' import { ActivatedRoute, Router } from '@angular/router' -import { FileUploader } from 'ng2-file-upload/ng2-file-upload' import { NotificationsService } from 'angular2-notifications' import { AuthService } from '../../core' diff --git a/client/src/app/videos/video-watch/video-report.component.ts b/client/src/app/videos/video-watch/video-report.component.ts index a5758060d..d9c83a640 100644 --- a/client/src/app/videos/video-watch/video-report.component.ts +++ b/client/src/app/videos/video-watch/video-report.component.ts @@ -63,7 +63,7 @@ export class VideoReportComponent extends FormReactive implements OnInit { this.hide() }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } } diff --git a/client/src/app/videos/video-watch/video-watch.component.ts b/client/src/app/videos/video-watch/video-watch.component.ts index 9cedc9c76..f5a47199d 100644 --- a/client/src/app/videos/video-watch/video-watch.component.ts +++ b/client/src/app/videos/video-watch/video-watch.component.ts @@ -158,7 +158,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy { this.userRating = 'like' }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } @@ -175,7 +175,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy { this.userRating = 'dislike' }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } @@ -275,7 +275,7 @@ export class VideoWatchComponent implements OnInit, OnDestroy { } }, - err => this.notificationsService.error('Error', err) + err => this.notificationsService.error('Error', err.message) ) } diff --git a/client/yarn.lock b/client/yarn.lock index 3552dbf99..b61da8636 100644 --- a/client/yarn.lock +++ b/client/yarn.lock @@ -4436,10 +4436,6 @@ ng-router-loader@^2.0.0: loader-utils "^0.2.16" recast "^0.11.20" -ng2-file-upload@^1.1.4-2: - version "1.2.1" - resolved "https://registry.yarnpkg.com/ng2-file-upload/-/ng2-file-upload-1.2.1.tgz#5563c5dfd6f43fbfbe815c206e343464a0a6a197" - ng2-material-dropdown@0.7.10: version "0.7.10" resolved "https://registry.yarnpkg.com/ng2-material-dropdown/-/ng2-material-dropdown-0.7.10.tgz#093471f2a9cadd726cbcb120b0ad7818a54fa5ed" diff --git a/server/middlewares/validators/pods.ts b/server/middlewares/validators/pods.ts index 4d0e054b0..3a0f56f6a 100644 --- a/server/middlewares/validators/pods.ts +++ b/server/middlewares/validators/pods.ts @@ -11,7 +11,11 @@ import { isTestInstance } from '../../helpers' function makeFriendsValidator (req: express.Request, res: express.Response, next: express.NextFunction) { // Force https if the administrator wants to make friends if (isTestInstance() === false && CONFIG.WEBSERVER.SCHEME === 'http') { - return res.status(400).send('Cannot make friends with a non HTTPS web server.') + return res.status(400) + .json({ + error: 'Cannot make friends with a non HTTPS web server.' + }) + .end() } req.checkBody('hosts', 'Should have an array of unique hosts').isEachUniqueHostValid() diff --git a/server/middlewares/validators/users.ts b/server/middlewares/validators/users.ts index aec6324bf..15c07c693 100644 --- a/server/middlewares/validators/users.ts +++ b/server/middlewares/validators/users.ts @@ -45,9 +45,13 @@ function usersRemoveValidator (req: express.Request, res: express.Response, next return res.sendStatus(500) } - if (user.username === 'root') return res.status(400).send('Cannot remove the root user') + if (user.username === 'root') { + return res.status(400) + .send({ error: 'Cannot remove the root user' }) + .end() + } - next() + return next() }) }) } @@ -99,9 +103,13 @@ function usersVideoRatingValidator (req: express.Request, res: express.Response, videoPromise .then(video => { - if (!video) return res.status(404).send('Video not found') + if (!video) { + return res.status(404) + .json({ error: 'Video not found' }) + .end() + } - next() + return next() }) .catch(err => { logger.error('Error in user request validator.', err) @@ -113,7 +121,9 @@ function usersVideoRatingValidator (req: express.Request, res: express.Response, function ensureUserRegistrationAllowed (req: express.Request, res: express.Response, next: express.NextFunction) { isSignupAllowed().then(allowed => { if (allowed === false) { - return res.status(403).send('User registration is not enabled or user limit is reached.') + return res.status(403) + .send({ error: 'User registration is not enabled or user limit is reached.' }) + .end() } return next() @@ -138,10 +148,14 @@ export { function checkUserExists (id: number, res: express.Response, callback: (err: Error, user: UserInstance) => void) { db.User.loadById(id) .then(user => { - if (!user) return res.status(404).send('User not found') + if (!user) { + return res.status(404) + .send({ error: 'User not found' }) + .end() + } res.locals.user = user - callback(null, user) + return callback(null, user) }) .catch(err => { logger.error('Error in user request validator.', err) @@ -152,9 +166,13 @@ function checkUserExists (id: number, res: express.Response, callback: (err: Err function checkUserDoesNotAlreadyExist (username: string, email: string, res: express.Response, callback: () => void) { db.User.loadByUsernameOrEmail(username, email) .then(user => { - if (user) return res.status(409).send('User already exists.') + if (user) { + return res.status(409) + .send({ error: 'User already exists.' }) + .end() + } - callback() + return callback() }) .catch(err => { logger.error('Error in usersAdd request validator.', err) diff --git a/server/middlewares/validators/videos.ts b/server/middlewares/validators/videos.ts index 519e3d46c..213b4c46b 100644 --- a/server/middlewares/validators/videos.ts +++ b/server/middlewares/validators/videos.ts @@ -30,7 +30,9 @@ function videosAddValidator (req: express.Request, res: express.Response, next: user.isAbleToUploadVideo(videoFile) .then(isAble => { if (isAble === false) { - res.status(403).send('The user video quota is exceeded with this video.') + res.status(403) + .json({ error: 'The user video quota is exceeded with this video.' }) + .end() return undefined } @@ -38,17 +40,23 @@ function videosAddValidator (req: express.Request, res: express.Response, next: return db.Video.getDurationFromFile(videoFile.path) .catch(err => { logger.error('Invalid input file in videosAddValidator.', err) - res.status(400).send('Invalid input file.') + res.status(400) + .json({ error: 'Invalid input file.' }) + .end() return undefined }) }) .then(duration => { // Previous test failed, abort - if (duration === undefined) return undefined + if (duration === undefined) return if (!isVideoDurationValid('' + duration)) { - return res.status(400).send('Duration of the video file is too big (max: ' + CONSTRAINTS_FIELDS.VIDEOS.DURATION.max + 's).') + return res.status(400) + .json({ + error: 'Duration of the video file is too big (max: ' + CONSTRAINTS_FIELDS.VIDEOS.DURATION.max + 's).' + }) + .end() } videoFile['duration'] = duration @@ -80,11 +88,15 @@ function videosUpdateValidator (req: express.Request, res: express.Response, nex checkVideoExists(req.params.id, res, () => { // We need to make additional checks if (res.locals.video.isOwned() === false) { - return res.status(403).send('Cannot update video of another pod') + return res.status(403) + .json({ error: 'Cannot update video of another pod' }) + .end() } if (res.locals.video.Author.userId !== res.locals.oauth.token.User.id) { - return res.status(403).send('Cannot update video of another user') + return res.status(403) + .json({ error: 'Cannot update video of another user' }) + .end() } next() @@ -188,7 +200,11 @@ function checkVideoExists (id: string, res: express.Response, callback: () => vo } promise.then(video => { - if (!video) return res.status(404).send('Video not found') + if (!video) { + return res.status(404) + .json({ error: 'Video not found' }) + .end() + } res.locals.video = video callback() @@ -204,14 +220,18 @@ function checkUserCanDeleteVideo (userId: number, res: express.Response, callbac db.User.loadById(userId) .then(user => { if (res.locals.video.isOwned() === false) { - return res.status(403).send('Cannot remove video of another pod, blacklist it') + return res.status(403) + .json({ error: 'Cannot remove video of another pod, blacklist it' }) + .end() } // Check if the user can delete the video // The user can delete it if s/he is an admin // Or if s/he is the video's author if (user.isAdmin() === false && res.locals.video.Author.userId !== res.locals.oauth.token.User.id) { - return res.status(403).send('Cannot remove video of another user') + return res.status(403) + .json({ error: 'Cannot remove video of another user' }) + .end() } // If we reach this comment, we can delete the video @@ -225,7 +245,9 @@ function checkUserCanDeleteVideo (userId: number, res: express.Response, callbac function checkVideoIsBlacklistable (req: express.Request, res: express.Response, callback: () => void) { if (res.locals.video.isOwned() === true) { - return res.status(403).send('Cannot blacklist a local video') + return res.status(403) + .json({ error: 'Cannot blacklist a local video' }) + .end() } callback() -- 2.41.0