}
.moderation-expanded {
- word-wrap: break-word;
- overflow: visible !important;
- text-overflow: unset !important;
- white-space: unset !important;
+ word-wrap: break-word;
+ overflow: visible !important;
+ text-overflow: unset !important;
+ white-space: unset !important;
}
--- /dev/null
+<ng-template #modal let-close="close" let-dismiss="dismiss">
+ <div class="modal-header">
+ <h4 i18n class="modal-title">Accept ownership</h4>
+ <span class="close" aria-label="Close" role="button" (click)="dismiss()"></span>
+ </div>
+
+ <div class="modal-body" [formGroup]="form">
+ <div class="form-group">
+ <label i18n for="channel">Select the target channel</label>
+ <select formControlName="channel" id="channel" class="peertube-select-container">
+ <option></option>
+ <option *ngFor="let channel of videoChannels" [value]="channel.id">{{ channel.displayName }}
+ </option>
+ </select>
+ <div *ngIf="formErrors.channel" class="form-error">
+ {{ formErrors.channel }}
+ </div>
+ </div>
+ </div>
+
+ <div class="modal-footer inputs">
+ <div class="form-group inputs">
+ <span i18n class="action-button action-button-cancel" (click)="dismiss()">
+ Cancel
+ </span>
+
+ <input
+ type="submit" i18n-value value="Submit" class="action-button-submit"
+ [disabled]="!form.valid"
+ (click)="close()"
+ >
+ </div>
+ </div>
+</ng-template>
--- /dev/null
+@import '_variables';
+@import '_mixins';
+
+select {
+ display: block;
+}
+
+.form-group {
+ margin: 20px 0;
+}
\ No newline at end of file
--- /dev/null
+import { Component, ElementRef, EventEmitter, OnInit, Output, ViewChild } from '@angular/core'
+import { NotificationsService } from 'angular2-notifications'
+import { FormReactive } from '@app/shared'
+import { FormValidatorService } from '@app/shared/forms/form-validators/form-validator.service'
+import { VideoOwnershipService } from '@app/shared/video-ownership'
+import { VideoChangeOwnership } from '../../../../../../shared/models/videos'
+import { VideoAcceptOwnershipValidatorsService } from '@app/shared/forms/form-validators'
+import { VideoChannel } from '@app/shared/video-channel/video-channel.model'
+import { VideoChannelService } from '@app/shared/video-channel/video-channel.service'
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { AuthService } from '@app/core'
+import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
+
+@Component({
+ selector: 'my-account-accept-ownership',
+ templateUrl: './my-account-accept-ownership.component.html',
+ styleUrls: [ './my-account-accept-ownership.component.scss' ]
+})
+export class MyAccountAcceptOwnershipComponent extends FormReactive implements OnInit {
+ @Output() accepted = new EventEmitter<void>()
+
+ @ViewChild('modal') modal: ElementRef
+
+ videoChangeOwnership: VideoChangeOwnership | undefined = undefined
+
+ videoChannels: VideoChannel[]
+
+ error: string = null
+
+ constructor (
+ protected formValidatorService: FormValidatorService,
+ private videoChangeOwnershipValidatorsService: VideoAcceptOwnershipValidatorsService,
+ private videoOwnershipService: VideoOwnershipService,
+ private notificationsService: NotificationsService,
+ private authService: AuthService,
+ private videoChannelService: VideoChannelService,
+ private modalService: NgbModal,
+ private i18n: I18n
+ ) {
+ super()
+ }
+
+ ngOnInit () {
+ this.videoChannels = []
+
+ this.videoChannelService.listAccountVideoChannels(this.authService.getUser().account)
+ .subscribe(videoChannels => this.videoChannels = videoChannels.data)
+
+ this.buildForm({
+ channel: this.videoChangeOwnershipValidatorsService.CHANNEL
+ })
+ }
+
+ show (videoChangeOwnership: VideoChangeOwnership) {
+ this.videoChangeOwnership = videoChangeOwnership
+ this.modalService
+ .open(this.modal)
+ .result
+ .then(() => this.acceptOwnership())
+ .catch(() => this.videoChangeOwnership = undefined)
+ }
+
+ acceptOwnership () {
+ const channel = this.form.value['channel']
+
+ const videoChangeOwnership = this.videoChangeOwnership
+ this.videoOwnershipService
+ .acceptOwnership(videoChangeOwnership.id, { channelId: channel })
+ .subscribe(
+ () => {
+ this.notificationsService.success(this.i18n('Success'), this.i18n('Ownership accepted'))
+ if (this.accepted) this.accepted.emit()
+ this.videoChangeOwnership = undefined
+ },
+
+ err => this.notificationsService.error(this.i18n('Error'), err.message)
+ )
+ }
+}
--- /dev/null
+<p-table
+ [value]="videoChangeOwnerships"
+ [lazy]="true"
+ [paginator]="true"
+ [totalRecords]="totalRecords"
+ [rows]="rowsPerPage"
+ [sortField]="sort.field"
+ [sortOrder]="sort.order"
+ (onLazyLoad)="loadLazy($event)"
+>
+ <ng-template pTemplate="header">
+ <tr>
+ <th i18n>Initiator</th>
+ <th i18n>Video</th>
+ <th i18n pSortableColumn="createdAt">
+ Created
+ <p-sortIcon field="createdAt"></p-sortIcon>
+ </th>
+ <th i18n>Status</th>
+ <th i18n>Action</th>
+ </tr>
+ </ng-template>
+
+ <ng-template pTemplate="body" let-videoChangeOwnership>
+ <tr>
+ <td>
+ <a [href]="videoChangeOwnership.initiatorAccount.url" i18n-title title="Go to the account"
+ target="_blank" rel="noopener noreferrer">
+ {{ createByString(videoChangeOwnership.initiatorAccount) }}
+ </a>
+ </td>
+ <td>
+ <a [href]="videoChangeOwnership.video.url" i18n-title title="Go to the video" target="_blank"
+ rel="noopener noreferrer">
+ {{ videoChangeOwnership.video.name }}
+ </a>
+ </td>
+ <td>{{ videoChangeOwnership.createdAt }}</td>
+ <td i18n>{{ videoChangeOwnership.status }}</td>
+ <td class="action-cell">
+ <ng-container *ngIf="videoChangeOwnership.status === 'WAITING'">
+ <my-button i18n label="Accept"
+ icon="icon-tick"
+ (click)="openAcceptModal(videoChangeOwnership)"></my-button>
+ <my-button i18n label="Refuse"
+ icon="icon-cross"
+ (click)="refuse(videoChangeOwnership)">Refuse</my-button>
+ </ng-container>
+ </td>
+ </tr>
+ </ng-template>
+</p-table>
+
+<my-account-accept-ownership #myAccountAcceptOwnershipComponent (accepted)="accepted()"></my-account-accept-ownership>
\ No newline at end of file
--- /dev/null
+import { Component, OnInit, ViewChild } from '@angular/core'
+import { NotificationsService } from 'angular2-notifications'
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { RestPagination, RestTable } from '@app/shared'
+import { SortMeta } from 'primeng/components/common/sortmeta'
+import { VideoChangeOwnership } from '../../../../../shared'
+import { VideoOwnershipService } from '@app/shared/video-ownership'
+import { Account } from '@app/shared/account/account.model'
+import { MyAccountAcceptOwnershipComponent }
+from '@app/+my-account/my-account-ownership/my-account-accept-ownership/my-account-accept-ownership.component'
+
+@Component({
+ selector: 'my-account-ownership',
+ templateUrl: './my-account-ownership.component.html'
+})
+export class MyAccountOwnershipComponent extends RestTable implements OnInit {
+ videoChangeOwnerships: VideoChangeOwnership[] = []
+ totalRecords = 0
+ rowsPerPage = 10
+ sort: SortMeta = { field: 'createdAt', order: -1 }
+ pagination: RestPagination = { count: this.rowsPerPage, start: 0 }
+
+ @ViewChild('myAccountAcceptOwnershipComponent') myAccountAcceptOwnershipComponent: MyAccountAcceptOwnershipComponent
+
+ constructor (
+ private notificationsService: NotificationsService,
+ private videoOwnershipService: VideoOwnershipService,
+ private i18n: I18n
+ ) {
+ super()
+ }
+
+ ngOnInit () {
+ this.loadSort()
+ }
+
+ protected loadData () {
+ return this.videoOwnershipService.getOwnershipChanges(this.pagination, this.sort)
+ .subscribe(
+ resultList => {
+ this.videoChangeOwnerships = resultList.data
+ this.totalRecords = resultList.total
+ },
+
+ err => this.notificationsService.error(this.i18n('Error'), err.message)
+ )
+ }
+
+ createByString (account: Account) {
+ return Account.CREATE_BY_STRING(account.name, account.host)
+ }
+
+ openAcceptModal (videoChangeOwnership: VideoChangeOwnership) {
+ this.myAccountAcceptOwnershipComponent.show(videoChangeOwnership)
+ }
+
+ accepted () {
+ this.loadData()
+ }
+
+ refuse (videoChangeOwnership: VideoChangeOwnership) {
+ this.videoOwnershipService.refuseOwnership(videoChangeOwnership.id)
+ .subscribe(
+ () => this.loadData(),
+ err => this.notificationsService.error(this.i18n('Error'), err.message)
+ )
+ }
+}
import { MyAccountVideoChannelUpdateComponent } from '@app/+my-account/my-account-video-channels/my-account-video-channel-update.component'
import { MyAccountVideoImportsComponent } from '@app/+my-account/my-account-video-imports/my-account-video-imports.component'
import { MyAccountSubscriptionsComponent } from '@app/+my-account/my-account-subscriptions/my-account-subscriptions.component'
+import { MyAccountOwnershipComponent } from '@app/+my-account/my-account-ownership/my-account-ownership.component'
const myAccountRoutes: Routes = [
{
title: 'Account subscriptions'
}
}
+ },
+ {
+ path: 'ownership',
+ component: MyAccountOwnershipComponent,
+ data: {
+ meta: {
+ title: 'Ownership changes'
+ }
+ }
}
]
}
<my-delete-button (click)="deleteVideo(video)"></my-delete-button>
<my-edit-button [routerLink]="[ '/videos', 'update', video.uuid ]"></my-edit-button>
+
+ <my-button i18n label="Change ownership"
+ className="action-button-change-ownership"
+ icon="icon-im-with-her"
+ (click)="changeOwnership($event, video)"
+ ></my-button>
</div>
</div>
</div>
</div>
+
+<my-video-change-ownership #videoChangeOwnershipModal></my-video-change-ownership>
\ No newline at end of file
}
}
-/deep/ .action-button {
- &.action-button-delete {
- margin-right: 10px;
- }
-}
-
.video {
@include row-blocks;
.video-buttons {
min-width: 190px;
+
+ *:not(:last-child) {
+ margin-right: 10px;
+ }
}
}
import { from as observableFrom, Observable } from 'rxjs'
import { concatAll, tap } from 'rxjs/operators'
-import { Component, OnDestroy, OnInit, Inject, LOCALE_ID } from '@angular/core'
+import { Component, OnDestroy, OnInit, Inject, LOCALE_ID, ViewChild } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { Location } from '@angular/common'
import { immutableAssign } from '@app/shared/misc/utils'
import { I18n } from '@ngx-translate/i18n-polyfill'
import { VideoPrivacy, VideoState } from '../../../../../shared/models/videos'
import { ScreenService } from '@app/shared/misc/screen.service'
+import { VideoChangeOwnershipComponent } from './video-change-ownership/video-change-ownership.component'
@Component({
selector: 'my-account-videos',
protected baseVideoWidth = -1
protected baseVideoHeight = 155
+ @ViewChild('videoChangeOwnershipModal') videoChangeOwnershipModal: VideoChangeOwnershipComponent
+
constructor (
protected router: Router,
protected route: ActivatedRoute,
)
}
+ changeOwnership (event: Event, video: Video) {
+ event.preventDefault()
+ this.videoChangeOwnershipModal.show(video)
+ }
+
getStateLabel (video: Video) {
let suffix: string
--- /dev/null
+<ng-template #modal let-close="close" let-dismiss="dismiss">
+ <div class="modal-header">
+ <h4 i18n class="modal-title">Change ownership</h4>
+ <span class="close" aria-label="Close" role="button" (click)="dismiss()"></span>
+ </div>
+
+ <div class="modal-body" [formGroup]="form">
+ <div class="form-group">
+ <label i18n for="next-ownership-username">Select the next owner</label>
+ <p-autoComplete formControlName="username" [suggestions]="usernamePropositions"
+ (completeMethod)="search($event)" id="next-ownership-username"></p-autoComplete>
+ <div *ngIf="formErrors.username" class="form-error">
+ {{ formErrors.username }}
+ </div>
+ </div>
+ </div>
+
+ <div class="modal-footer inputs">
+ <div class="form-group inputs">
+ <span i18n class="action-button action-button-cancel" (click)="dismiss()">
+ Cancel
+ </span>
+
+ <input
+ type="submit" i18n-value value="Submit" class="action-button-submit"
+ [disabled]="!form.valid"
+ (click)="close()"
+ />
+ </div>
+ </div>
+</ng-template>
--- /dev/null
+@import '_variables';
+@import '_mixins';
+
+p-autocomplete {
+ display: block;
+}
+
+.form-group {
+ margin: 20px 0;
+}
\ No newline at end of file
--- /dev/null
+import { Component, ElementRef, OnInit, ViewChild } from '@angular/core'
+import { NotificationsService } from 'angular2-notifications'
+import { NgbModal } from '@ng-bootstrap/ng-bootstrap'
+import { FormReactive, UserService } from '../../../shared/index'
+import { Video } from '@app/shared/video/video.model'
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { FormValidatorService, VideoChangeOwnershipValidatorsService } from '@app/shared'
+import { VideoOwnershipService } from '@app/shared/video-ownership'
+
+@Component({
+ selector: 'my-video-change-ownership',
+ templateUrl: './video-change-ownership.component.html',
+ styleUrls: [ './video-change-ownership.component.scss' ]
+})
+export class VideoChangeOwnershipComponent extends FormReactive implements OnInit {
+ @ViewChild('modal') modal: ElementRef
+
+ usernamePropositions: string[]
+
+ error: string = null
+
+ private video: Video | undefined = undefined
+
+ constructor (
+ protected formValidatorService: FormValidatorService,
+ private videoChangeOwnershipValidatorsService: VideoChangeOwnershipValidatorsService,
+ private videoOwnershipService: VideoOwnershipService,
+ private notificationsService: NotificationsService,
+ private userService: UserService,
+ private modalService: NgbModal,
+ private i18n: I18n
+ ) {
+ super()
+ }
+
+ ngOnInit () {
+ this.buildForm({
+ username: this.videoChangeOwnershipValidatorsService.USERNAME
+ })
+ this.usernamePropositions = []
+ }
+
+ show (video: Video) {
+ this.video = video
+ this.modalService
+ .open(this.modal)
+ .result
+ .then(() => this.changeOwnership())
+ .catch((_) => _) // Called when closing (cancel) the modal without validating, do nothing
+ }
+
+ search (event) {
+ const query = event.query
+ this.userService.autocomplete(query)
+ .subscribe(
+ (usernames) => {
+ this.usernamePropositions = usernames
+ },
+
+ err => this.notificationsService.error('Error', err.message)
+ )
+ }
+
+ changeOwnership () {
+ const username = this.form.value['username']
+
+ this.videoOwnershipService
+ .changeOwnership(this.video.id, username)
+ .subscribe(
+ () => this.notificationsService.success(this.i18n('Success'), this.i18n('Ownership changed.')),
+
+ err => this.notificationsService.error(this.i18n('Error'), err.message)
+ )
+ }
+}
<a i18n routerLink="/my-account/subscriptions" routerLinkActive="active" class="title-page">My subscriptions</a>
<a *ngIf="isVideoImportEnabled()" i18n routerLink="/my-account/video-imports" routerLinkActive="active" class="title-page">My imports</a>
+
+ <a i18n routerLink="/my-account/ownership" routerLinkActive="active" class="title-page">Ownership changes</a>
</div>
<div class="margin-content">
import { TableModule } from 'primeng/table'
import { NgModule } from '@angular/core'
+import { AutoCompleteModule } from 'primeng/autocomplete'
import { SharedModule } from '../shared'
import { MyAccountRoutingModule } from './my-account-routing.module'
import { MyAccountChangePasswordComponent } from './my-account-settings/my-account-change-password/my-account-change-password.component'
import { MyAccountSettingsComponent } from './my-account-settings/my-account-settings.component'
import { MyAccountComponent } from './my-account.component'
import { MyAccountVideosComponent } from './my-account-videos/my-account-videos.component'
+import { VideoChangeOwnershipComponent } from './my-account-videos/video-change-ownership/video-change-ownership.component'
+import { MyAccountOwnershipComponent } from './my-account-ownership/my-account-ownership.component'
+import { MyAccountAcceptOwnershipComponent } from './my-account-ownership/my-account-accept-ownership/my-account-accept-ownership.component'
import { MyAccountProfileComponent } from '@app/+my-account/my-account-settings/my-account-profile/my-account-profile.component'
import { MyAccountVideoChannelsComponent } from '@app/+my-account/my-account-video-channels/my-account-video-channels.component'
import { MyAccountVideoChannelCreateComponent } from '@app/+my-account/my-account-video-channels/my-account-video-channel-create.component'
@NgModule({
imports: [
+ TableModule,
MyAccountRoutingModule,
+ AutoCompleteModule,
SharedModule,
TableModule
],
MyAccountVideoSettingsComponent,
MyAccountProfileComponent,
MyAccountVideosComponent,
+ VideoChangeOwnershipComponent,
+ MyAccountOwnershipComponent,
+ MyAccountAcceptOwnershipComponent,
MyAccountVideoChannelsComponent,
MyAccountVideoChannelCreateComponent,
MyAccountVideoChannelUpdateComponent,
--- /dev/null
+<span class="action-button" [ngClass]="className" [title]="getTitle()">
+ <span class="icon" [ngClass]="icon"></span>
+ <span class="button-label">{{ label }}</span>
+</span>
&.icon-delete-grey {
background-image: url('../../../assets/images/global/delete-grey.svg');
}
+
+ &.icon-im-with-her {
+ background-image: url('../../../assets/images/global/im-with-her.svg');
+ }
+
+ &.icon-tick {
+ background-image: url('../../../assets/images/global/tick.svg');
+ }
+
+ &.icon-cross {
+ background-image: url('../../../assets/images/global/cross.svg');
+ }
}
}
--- /dev/null
+import { Component, Input } from '@angular/core'
+
+@Component({
+ selector: 'my-button',
+ styleUrls: ['./button.component.scss'],
+ templateUrl: './button.component.html'
+})
+
+export class ButtonComponent {
+ @Input() label = ''
+ @Input() className = undefined
+ @Input() icon = undefined
+ @Input() title = undefined
+
+ getTitle () {
+ return this.title || this.label
+ }
+}
export * from './video-comment-validators.service'
export * from './video-validators.service'
export * from './video-captions-validators.service'
+export * from './video-change-ownership-validators.service'
+export * from './video-accept-ownership-validators.service'
--- /dev/null
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { Validators } from '@angular/forms'
+import { Injectable } from '@angular/core'
+import { BuildFormValidator } from '@app/shared'
+
+@Injectable()
+export class VideoAcceptOwnershipValidatorsService {
+ readonly CHANNEL: BuildFormValidator
+
+ constructor (private i18n: I18n) {
+ this.CHANNEL = {
+ VALIDATORS: [ Validators.required ],
+ MESSAGES: {
+ 'required': this.i18n('The channel is required.')
+ }
+ }
+ }
+}
--- /dev/null
+import { I18n } from '@ngx-translate/i18n-polyfill'
+import { Validators } from '@angular/forms'
+import { Injectable } from '@angular/core'
+import { BuildFormValidator } from '@app/shared'
+
+@Injectable()
+export class VideoChangeOwnershipValidatorsService {
+ readonly USERNAME: BuildFormValidator
+
+ constructor (private i18n: I18n) {
+ this.USERNAME = {
+ VALIDATORS: [ Validators.required ],
+ MESSAGES: {
+ 'required': this.i18n('The username is required.')
+ }
+ }
+ }
+}
import { SharedModule as PrimeSharedModule } from 'primeng/components/common/shared'
import { AUTH_INTERCEPTOR_PROVIDER } from './auth'
+import { ButtonComponent } from './buttons/button.component'
import { DeleteButtonComponent } from './buttons/delete-button.component'
import { EditButtonComponent } from './buttons/edit-button.component'
import { FromNowPipe } from './misc/from-now.pipe'
import { UserService } from './users'
import { VideoAbuseService } from './video-abuse'
import { VideoBlacklistService } from './video-blacklist'
+import { VideoOwnershipService } from './video-ownership'
import { VideoMiniatureComponent } from './video/video-miniature.component'
import { VideoFeedComponent } from './video/video-feed.component'
import { VideoThumbnailComponent } from './video/video-thumbnail.component'
VideoBlacklistValidatorsService,
VideoChannelValidatorsService,
VideoCommentValidatorsService,
- VideoValidatorsService
+ VideoValidatorsService,
+ VideoChangeOwnershipValidatorsService, VideoAcceptOwnershipValidatorsService
} from '@app/shared/forms'
import { I18nPrimengCalendarService } from '@app/shared/i18n/i18n-primeng-calendar'
import { ScreenService } from '@app/shared/misc/screen.service'
VideoThumbnailComponent,
VideoMiniatureComponent,
VideoFeedComponent,
+ ButtonComponent,
DeleteButtonComponent,
EditButtonComponent,
ActionDropdownComponent,
VideoThumbnailComponent,
VideoMiniatureComponent,
VideoFeedComponent,
+ ButtonComponent,
DeleteButtonComponent,
EditButtonComponent,
ActionDropdownComponent,
RestService,
VideoAbuseService,
VideoBlacklistService,
+ VideoOwnershipService,
UserService,
VideoService,
AccountService,
VideoCaptionsValidatorsService,
VideoBlacklistValidatorsService,
OverviewService,
+ VideoChangeOwnershipValidatorsService,
+ VideoAcceptOwnershipValidatorsService,
I18nPrimengCalendarService,
ScreenService,
+import { Observable } from 'rxjs'
import { catchError, map } from 'rxjs/operators'
-import { HttpClient } from '@angular/common/http'
+import { HttpClient, HttpParams } from '@angular/common/http'
import { Injectable } from '@angular/core'
import { UserCreate, UserUpdateMe, UserVideoQuota } from '../../../../../shared'
import { environment } from '../../../environments/environment'
catchError(err => this.restExtractor.handleError(err))
)
}
+
+ autocomplete (search: string): Observable<string[]> {
+ const url = UserService.BASE_USERS_URL + 'autocomplete'
+ const params = new HttpParams().append('search', search)
+
+ return this.authHttp
+ .get<string[]>(url, { params })
+ .pipe(catchError(res => this.restExtractor.handleError(res)))
+ }
}
--- /dev/null
+export * from './video-ownership.service'
--- /dev/null
+import { catchError, map } from 'rxjs/operators'
+import { HttpClient, HttpParams } from '@angular/common/http'
+import { Injectable } from '@angular/core'
+import { environment } from '../../../environments/environment'
+import { RestExtractor, RestService } from '../rest'
+import { VideoChangeOwnershipCreate } from '../../../../../shared/models/videos'
+import { Observable } from 'rxjs/index'
+import { SortMeta } from 'primeng/components/common/sortmeta'
+import { ResultList, VideoChangeOwnership } from '../../../../../shared'
+import { RestPagination } from '@app/shared/rest'
+import { VideoChangeOwnershipAccept } from '../../../../../shared/models/videos/video-change-ownership-accept.model'
+
+@Injectable()
+export class VideoOwnershipService {
+ private static BASE_VIDEO_CHANGE_OWNERSHIP_URL = environment.apiUrl + '/api/v1/videos/'
+
+ constructor (
+ private authHttp: HttpClient,
+ private restService: RestService,
+ private restExtractor: RestExtractor
+ ) {
+ }
+
+ changeOwnership (id: number, username: string) {
+ const url = VideoOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + id + '/give-ownership'
+ const body: VideoChangeOwnershipCreate = {
+ username
+ }
+
+ return this.authHttp.post(url, body)
+ .pipe(
+ map(this.restExtractor.extractDataBool),
+ catchError(res => this.restExtractor.handleError(res))
+ )
+ }
+
+ getOwnershipChanges (pagination: RestPagination, sort: SortMeta): Observable<ResultList<VideoChangeOwnership>> {
+ const url = VideoOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + 'ownership'
+
+ let params = new HttpParams()
+ params = this.restService.addRestGetParams(params, pagination, sort)
+
+ return this.authHttp.get<ResultList<VideoChangeOwnership>>(url, { params })
+ .pipe(
+ map(res => this.restExtractor.convertResultListDateToHuman(res)),
+ catchError(res => this.restExtractor.handleError(res))
+ )
+ }
+
+ acceptOwnership (id: number, input: VideoChangeOwnershipAccept) {
+ const url = VideoOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + 'ownership/' + id + '/accept'
+ return this.authHttp.post(url, input)
+ .pipe(
+ map(this.restExtractor.extractDataBool),
+ catchError(this.restExtractor.handleError)
+ )
+ }
+
+ refuseOwnership (id: number) {
+ const url = VideoOwnershipService.BASE_VIDEO_CHANGE_OWNERSHIP_URL + 'ownership/' + id + '/refuse'
+ return this.authHttp.post(url, {})
+ .pipe(
+ map(this.restExtractor.extractDataBool),
+ catchError(this.restExtractor.handleError)
+ )
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<svg width="24px" height="24px" viewBox="0 0 24 24" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
+ <!-- Generator: Sketch 43.2 (39069) - http://www.bohemiancoding.com/sketch -->
+ <title>im-with-her</title>
+ <desc>Created with Sketch.</desc>
+ <defs></defs>
+ <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
+ <g id="Artboard-4" transform="translate(-708.000000, -467.000000)">
+ <g id="176" transform="translate(708.000000, 467.000000)">
+ <path d="M8,9 L8,3.99339768 C8,3.44494629 7.55641359,3 7.00922203,3 L2.99077797,3 C2.45097518,3 2,3.44475929 2,3.99339768 L2,20.0066023 C2,20.5550537 2.44358641,21 2.99077797,21 L7.00922203,21 C7.54902482,21 8,20.5552407 8,20.0066023 L8,15 L14,15 L14,20.0066023 C14,20.5550537 14.4435864,21 14.990778,21 L19.009222,21 C19.5490248,21 20,20.5564587 20,20.0093228 L20,15.0006104 L23,12 L20,8.99267578 L20,4.00303919 C20,3.45042467 19.5564136,3 19.009222,3 L14.990778,3 C14.4509752,3 14,3.44475929 14,3.99339768 L14,9 L8,9 Z" id="Combined-Shape" fill="#333333" opacity="0.5"></path>
+ <path d="M2,9 L14,9 L14,3.99077797 C14,3.44358641 14.3203148,3.32031476 14.7062149,3.7062149 L23,12 L14.7062149,20.2937851 C14.3161832,20.6838168 14,20.5490248 14,20.009222 L14,15 L2,15 L2,9 Z" id="Rectangle-121" fill-opacity="0.5" fill="#000000"></path>
+ </g>
+ </g>
+ </g>
+</svg>
\ No newline at end of file
* @param $line-height line-height property
* @param $lines-to-show amount of lines to show
*/
- @mixin ellipsis-multiline($font-size: 1rem, $line-height: 1, $lines-to-show: 2) {
+@mixin ellipsis-multiline($font-size: 1rem, $line-height: 1, $lines-to-show: 2) {
display: block;
/* Fallback for non-webkit */
display: -webkit-box;
setDefaultPagination,
setDefaultSort,
token,
+ userAutocompleteValidator,
usersAddValidator,
usersGetValidator,
usersRegisterValidator,
const usersRouter = express.Router()
usersRouter.use('/', meRouter)
+usersRouter.get('/autocomplete',
+ userAutocompleteValidator,
+ asyncMiddleware(autocompleteUsers)
+)
+
usersRouter.get('/',
authenticate,
ensureUserHasRight(UserRight.MANAGE_USERS),
return res.json((res.locals.user as UserModel).toFormattedJSON())
}
+async function autocompleteUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
+ const resultList = await UserModel.autocomplete(req.query.search as string)
+
+ return res.json(resultList)
+}
+
async function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
const resultList = await UserModel.listForApi(req.query.start, req.query.count, req.query.sort)
import { blacklistRouter } from './blacklist'
import { videoCommentRouter } from './comment'
import { rateVideoRouter } from './rate'
+import { ownershipVideoRouter } from './ownership'
import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils'
import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
videosRouter.use('/', videoCommentRouter)
videosRouter.use('/', videoCaptionsRouter)
videosRouter.use('/', videoImportsRouter)
+videosRouter.use('/', ownershipVideoRouter)
videosRouter.get('/categories', listVideoCategories)
videosRouter.get('/licences', listVideoLicences)
--- /dev/null
+import * as express from 'express'
+import { logger } from '../../../helpers/logger'
+import { sequelizeTypescript } from '../../../initializers'
+import {
+ asyncMiddleware,
+ asyncRetryTransactionMiddleware,
+ authenticate,
+ paginationValidator,
+ setDefaultPagination,
+ videosAcceptChangeOwnershipValidator,
+ videosChangeOwnershipValidator,
+ videosTerminateChangeOwnershipValidator
+} from '../../../middlewares'
+import { AccountModel } from '../../../models/account/account'
+import { VideoModel } from '../../../models/video/video'
+import { VideoChangeOwnershipModel } from '../../../models/video/video-change-ownership'
+import { VideoChangeOwnershipStatus } from '../../../../shared/models/videos'
+import { VideoChannelModel } from '../../../models/video/video-channel'
+import { getFormattedObjects } from '../../../helpers/utils'
+
+const ownershipVideoRouter = express.Router()
+
+ownershipVideoRouter.post('/:videoId/give-ownership',
+ authenticate,
+ asyncMiddleware(videosChangeOwnershipValidator),
+ asyncRetryTransactionMiddleware(giveVideoOwnership)
+)
+
+ownershipVideoRouter.get('/ownership',
+ authenticate,
+ paginationValidator,
+ setDefaultPagination,
+ asyncRetryTransactionMiddleware(listVideoOwnership)
+)
+
+ownershipVideoRouter.post('/ownership/:id/accept',
+ authenticate,
+ asyncMiddleware(videosTerminateChangeOwnershipValidator),
+ asyncMiddleware(videosAcceptChangeOwnershipValidator),
+ asyncRetryTransactionMiddleware(acceptOwnership)
+)
+
+ownershipVideoRouter.post('/ownership/:id/refuse',
+ authenticate,
+ asyncMiddleware(videosTerminateChangeOwnershipValidator),
+ asyncRetryTransactionMiddleware(refuseOwnership)
+)
+
+// ---------------------------------------------------------------------------
+
+export {
+ ownershipVideoRouter
+}
+
+// ---------------------------------------------------------------------------
+
+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 nextOwner = res.locals.nextOwner as AccountModel
+
+ await sequelizeTypescript.transaction(async t => {
+ await VideoChangeOwnershipModel.findOrCreate({
+ where: {
+ initiatorAccountId: initiatorAccount.id,
+ nextOwnerAccountId: nextOwner.id,
+ videoId: videoInstance.id,
+ status: VideoChangeOwnershipStatus.WAITING
+ },
+ defaults: {
+ initiatorAccountId: initiatorAccount.id,
+ nextOwnerAccountId: nextOwner.id,
+ videoId: videoInstance.id,
+ status: VideoChangeOwnershipStatus.WAITING
+ }
+ })
+ logger.info('Ownership change for video %s created.', videoInstance.name)
+ return res.type('json').status(204).end()
+ })
+}
+
+async function listVideoOwnership (req: express.Request, res: express.Response) {
+ const currentAccount = res.locals.oauth.token.User.Account as AccountModel
+ const resultList = await VideoChangeOwnershipModel.listForApi(
+ currentAccount.id,
+ req.query.start || 0,
+ req.query.count || 10,
+ req.query.sort || 'createdAt'
+ )
+
+ return res.json(getFormattedObjects(resultList.data, resultList.total))
+}
+
+async function acceptOwnership (req: express.Request, res: express.Response) {
+ return sequelizeTypescript.transaction(async t => {
+ const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
+ const targetVideo = videoChangeOwnership.Video
+ const channel = res.locals.videoChannel as VideoChannelModel
+
+ targetVideo.set('channelId', channel.id)
+
+ await targetVideo.save()
+ videoChangeOwnership.set('status', VideoChangeOwnershipStatus.ACCEPTED)
+ await videoChangeOwnership.save()
+
+ return res.sendStatus(204)
+ })
+}
+
+async function refuseOwnership (req: express.Request, res: express.Response) {
+ return sequelizeTypescript.transaction(async t => {
+ const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
+ videoChangeOwnership.set('status', VideoChangeOwnershipStatus.REFUSED)
+ await videoChangeOwnership.save()
+ return res.sendStatus(204)
+ })
+}
--- /dev/null
+import { Response } from 'express'
+import * as validator from 'validator'
+import { VideoChangeOwnershipModel } from '../../models/video/video-change-ownership'
+import { UserModel } from '../../models/account/user'
+
+export async function doesChangeVideoOwnershipExist (id: string, res: Response): Promise<boolean> {
+ const videoChangeOwnership = await loadVideoChangeOwnership(id)
+
+ if (!videoChangeOwnership) {
+ res.status(404)
+ .json({ error: 'Video change ownership not found' })
+ .end()
+
+ return false
+ }
+
+ res.locals.videoChangeOwnership = videoChangeOwnership
+ return true
+}
+
+async function loadVideoChangeOwnership (id: string): Promise<VideoChangeOwnershipModel | undefined> {
+ if (validator.isInt(id)) {
+ return VideoChangeOwnershipModel.load(parseInt(id, 10))
+ }
+
+ return undefined
+}
+
+export function checkUserCanTerminateOwnershipChange (
+ user: UserModel,
+ videoChangeOwnership: VideoChangeOwnershipModel,
+ res: Response
+): boolean {
+ if (videoChangeOwnership.NextOwner.userId === user.Account.userId) {
+ return true
+ }
+
+ res.status(403)
+ .json({ error: 'Cannot terminate an ownership change of another user' })
+ .end()
+ return false
+}
import { VideoCaptionModel } from '../models/video/video-caption'
import { VideoImportModel } from '../models/video/video-import'
import { VideoViewModel } from '../models/video/video-views'
+import { VideoChangeOwnershipModel } from '../models/video/video-change-ownership'
require('pg').defaults.parseInt8 = true // Avoid BIGINT to be converted to string
AccountVideoRateModel,
UserModel,
VideoAbuseModel,
+ VideoChangeOwnershipModel,
VideoChannelModel,
VideoShareModel,
VideoFileModel,
}
]
+const userAutocompleteValidator = [
+ param('search').isString().not().isEmpty().withMessage('Should have a search parameter')
+]
+
// ---------------------------------------------------------------------------
export {
usersAskResetPasswordValidator,
usersResetPasswordValidator,
usersAskSendVerifyEmailValidator,
- usersVerifyEmailValidator
+ usersVerifyEmailValidator,
+ userAutocompleteValidator
}
// ---------------------------------------------------------------------------
import * as express from 'express'
import 'express-validator'
import { body, param, ValidationChain } from 'express-validator/check'
-import { UserRight, VideoPrivacy } from '../../../shared'
+import { UserRight, VideoChangeOwnershipStatus, VideoPrivacy } from '../../../shared'
import {
isBooleanValid,
isDateValid,
import { cleanUpReqFiles } from '../../helpers/express-utils'
import { VideoModel } from '../../models/video/video'
import { UserModel } from '../../models/account/user'
+import { checkUserCanTerminateOwnershipChange, doesChangeVideoOwnershipExist } from '../../helpers/custom-validators/video-ownership'
+import { VideoChangeOwnershipAccept } from '../../../shared/models/videos/video-change-ownership-accept.model'
+import { VideoChangeOwnershipModel } from '../../models/video/video-change-ownership'
+import { AccountModel } from '../../models/account/account'
const videosAddValidator = getCommonVideoAttributes().concat([
body('videofile')
}
]
+const videosChangeOwnershipValidator = [
+ param('videoId').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
+
+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+ logger.debug('Checking changeOwnership parameters', { parameters: req.params })
+
+ if (areValidationErrors(req, res)) return
+ if (!await isVideoExist(req.params.videoId, res)) return
+
+ // Check if the user who did the request is able to change the ownership of the video
+ if (!checkUserCanManageVideo(res.locals.oauth.token.User, res.locals.video, UserRight.CHANGE_VIDEO_OWNERSHIP, res)) return
+
+ const nextOwner = await AccountModel.loadLocalByName(req.body.username)
+ if (!nextOwner) {
+ res.status(400)
+ .type('json')
+ .end()
+ return
+ }
+ res.locals.nextOwner = nextOwner
+
+ return next()
+ }
+]
+
+const videosTerminateChangeOwnershipValidator = [
+ param('id').custom(isIdOrUUIDValid).not().isEmpty().withMessage('Should have a valid id'),
+
+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+ logger.debug('Checking changeOwnership parameters', { parameters: req.params })
+
+ if (areValidationErrors(req, res)) return
+ if (!await doesChangeVideoOwnershipExist(req.params.id, res)) return
+
+ // Check if the user who did the request is able to change the ownership of the video
+ if (!checkUserCanTerminateOwnershipChange(res.locals.oauth.token.User, res.locals.videoChangeOwnership, res)) return
+
+ return next()
+ },
+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+ const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
+
+ if (videoChangeOwnership.status === VideoChangeOwnershipStatus.WAITING) {
+ return next()
+ } else {
+ res.status(403)
+ .json({ error: 'Ownership already accepted or refused' })
+ .end()
+ return
+ }
+ }
+]
+
+const videosAcceptChangeOwnershipValidator = [
+ async (req: express.Request, res: express.Response, next: express.NextFunction) => {
+ const body = req.body as VideoChangeOwnershipAccept
+ if (!await isVideoChannelOfAccountExist(body.channelId, res.locals.oauth.token.User, res)) return
+
+ const user = res.locals.oauth.token.User
+ const videoChangeOwnership = res.locals.videoChangeOwnership as VideoChangeOwnershipModel
+ const isAble = await user.isAbleToUploadVideo(videoChangeOwnership.Video.getOriginalFile())
+ if (isAble === false) {
+ res.status(403)
+ .json({ error: 'The user video quota is exceeded with this video.' })
+ .end()
+ return
+ }
+
+ return next()
+ }
+]
+
function getCommonVideoAttributes () {
return [
body('thumbnailfile')
videoRateValidator,
+ videosChangeOwnershipValidator,
+ videosTerminateChangeOwnershipValidator,
+ videosAcceptChangeOwnershipValidator,
+
getCommonVideoAttributes
}
import { NSFWPolicyType } from '../../../shared/models/videos/nsfw-policy.type'
import { values } from 'lodash'
import { NSFW_POLICY_TYPES } from '../../initializers'
+import { VideoFileModel } from '../video/video-file'
enum ScopeNames {
WITH_VIDEO_CHANNEL = 'WITH_VIDEO_CHANNEL'
return parseInt(total, 10)
})
}
+
+ static autocomplete (search: string) {
+ return UserModel.findAll({
+ where: {
+ username: {
+ [Sequelize.Op.like]: `%${search}%`
+ }
+ }
+ })
+ .then(u => u.map(u => u.username))
+ }
}
--- /dev/null
+import { AllowNull, BelongsTo, Column, CreatedAt, ForeignKey, Model, Scopes, Table, UpdatedAt } from 'sequelize-typescript'
+import { AccountModel } from '../account/account'
+import { VideoModel } from './video'
+import { VideoChangeOwnership, VideoChangeOwnershipStatus } from '../../../shared/models/videos'
+import { getSort } from '../utils'
+import { VideoFileModel } from './video-file'
+
+enum ScopeNames {
+ FULL = 'FULL'
+}
+
+@Table({
+ tableName: 'videoChangeOwnership',
+ indexes: [
+ {
+ fields: ['videoId']
+ },
+ {
+ fields: ['initiatorAccountId']
+ },
+ {
+ fields: ['nextOwnerAccountId']
+ }
+ ]
+})
+@Scopes({
+ [ScopeNames.FULL]: {
+ include: [
+ {
+ model: () => AccountModel,
+ as: 'Initiator',
+ required: true
+ },
+ {
+ model: () => AccountModel,
+ as: 'NextOwner',
+ required: true
+ },
+ {
+ model: () => VideoModel,
+ required: true,
+ include: [{ model: () => VideoFileModel }]
+ }
+ ]
+ }
+})
+export class VideoChangeOwnershipModel extends Model<VideoChangeOwnershipModel> {
+ @CreatedAt
+ createdAt: Date
+
+ @UpdatedAt
+ updatedAt: Date
+
+ @AllowNull(false)
+ @Column
+ status: VideoChangeOwnershipStatus
+
+ @ForeignKey(() => AccountModel)
+ @Column
+ initiatorAccountId: number
+
+ @BelongsTo(() => AccountModel, {
+ foreignKey: {
+ name: 'initiatorAccountId',
+ allowNull: false
+ },
+ onDelete: 'cascade'
+ })
+ Initiator: AccountModel
+
+ @ForeignKey(() => AccountModel)
+ @Column
+ nextOwnerAccountId: number
+
+ @BelongsTo(() => AccountModel, {
+ foreignKey: {
+ name: 'nextOwnerAccountId',
+ allowNull: false
+ },
+ onDelete: 'cascade'
+ })
+ NextOwner: AccountModel
+
+ @ForeignKey(() => VideoModel)
+ @Column
+ videoId: number
+
+ @BelongsTo(() => VideoModel, {
+ foreignKey: {
+ allowNull: false
+ },
+ onDelete: 'cascade'
+ })
+ Video: VideoModel
+
+ static listForApi (nextOwnerId: number, start: number, count: number, sort: string) {
+ return VideoChangeOwnershipModel.scope(ScopeNames.FULL).findAndCountAll({
+ offset: start,
+ limit: count,
+ order: getSort(sort),
+ where: {
+ nextOwnerAccountId: nextOwnerId
+ }
+ })
+ .then(({ rows, count }) => ({ total: count, data: rows }))
+ }
+
+ static load (id: number) {
+ return VideoChangeOwnershipModel.scope(ScopeNames.FULL).findById(id)
+ }
+
+ toFormattedJSON (): VideoChangeOwnership {
+ return {
+ id: this.id,
+ status: this.status,
+ initiatorAccount: this.Initiator.toFormattedJSON(),
+ nextOwnerAccount: this.NextOwner.toFormattedJSON(),
+ video: {
+ id: this.Video.id,
+ uuid: this.Video.uuid,
+ url: this.Video.url,
+ name: this.Video.name
+ },
+ createdAt: this.createdAt
+ }
+ }
+}
--- /dev/null
+/* tslint:disable:no-unused-expression */
+
+import * as chai from 'chai'
+import 'mocha'
+import {
+ acceptChangeOwnership,
+ changeVideoOwnership,
+ createUser,
+ flushTests,
+ getMyUserInformation,
+ getVideoChangeOwnershipList,
+ getVideosList,
+ killallServers,
+ refuseChangeOwnership,
+ runServer,
+ ServerInfo,
+ setAccessTokensToServers,
+ uploadVideo,
+ userLogin
+} from '../../utils'
+import { waitJobs } from '../../utils/server/jobs'
+import { User } from '../../../../shared/models/users'
+
+const expect = chai.expect
+
+describe('Test video change ownership - nominal', function () {
+ let server: ServerInfo = undefined
+ const firstUser = {
+ username: 'first',
+ password: 'My great password'
+ }
+ const secondUser = {
+ username: 'second',
+ password: 'My other password'
+ }
+ let firstUserAccessToken = ''
+ let secondUserAccessToken = ''
+ let lastRequestChangeOwnershipId = undefined
+
+ before(async function () {
+ this.timeout(50000)
+
+ // Run one server
+ await flushTests()
+ server = await runServer(1)
+ await setAccessTokensToServers([server])
+
+ const videoQuota = 42000000
+ await createUser(server.url, server.accessToken, firstUser.username, firstUser.password, videoQuota)
+ await createUser(server.url, server.accessToken, secondUser.username, secondUser.password, videoQuota)
+
+ firstUserAccessToken = await userLogin(server, firstUser)
+ secondUserAccessToken = await userLogin(server, secondUser)
+
+ // Upload some videos on the server
+ const video1Attributes = {
+ name: 'my super name',
+ description: 'my super description'
+ }
+ await uploadVideo(server.url, firstUserAccessToken, video1Attributes)
+
+ await waitJobs(server)
+
+ const res = await getVideosList(server.url)
+ const videos = res.body.data
+
+ expect(videos.length).to.equal(1)
+
+ server.video = videos.find(video => video.name === 'my super name')
+ })
+
+ it('Should not have video change ownership', async function () {
+ const resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken)
+
+ expect(resFirstUser.body.total).to.equal(0)
+ expect(resFirstUser.body.data).to.be.an('array')
+ expect(resFirstUser.body.data.length).to.equal(0)
+
+ const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken)
+
+ expect(resSecondUser.body.total).to.equal(0)
+ expect(resSecondUser.body.data).to.be.an('array')
+ expect(resSecondUser.body.data.length).to.equal(0)
+ })
+
+ it('Should send a request to change ownership of a video', async function () {
+ this.timeout(15000)
+
+ await changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username)
+ })
+
+ it('Should only return a request to change ownership for the second user', async function () {
+ const resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken)
+
+ expect(resFirstUser.body.total).to.equal(0)
+ expect(resFirstUser.body.data).to.be.an('array')
+ expect(resFirstUser.body.data.length).to.equal(0)
+
+ const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken)
+
+ expect(resSecondUser.body.total).to.equal(1)
+ expect(resSecondUser.body.data).to.be.an('array')
+ expect(resSecondUser.body.data.length).to.equal(1)
+
+ lastRequestChangeOwnershipId = resSecondUser.body.data[0].id
+ })
+
+ it('Should accept the same change ownership request without crashing', async function () {
+ this.timeout(10000)
+
+ await changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username)
+ })
+
+ it('Should not create multiple change ownership requests while one is waiting', async function () {
+ this.timeout(10000)
+
+ const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken)
+
+ expect(resSecondUser.body.total).to.equal(1)
+ expect(resSecondUser.body.data).to.be.an('array')
+ expect(resSecondUser.body.data.length).to.equal(1)
+ })
+
+ it('Should not be possible to refuse the change of ownership from first user', async function () {
+ this.timeout(10000)
+
+ await refuseChangeOwnership(server.url, firstUserAccessToken, lastRequestChangeOwnershipId, 403)
+ })
+
+ it('Should be possible to refuse the change of ownership from second user', async function () {
+ this.timeout(10000)
+
+ await refuseChangeOwnership(server.url, secondUserAccessToken, lastRequestChangeOwnershipId)
+ })
+
+ it('Should send a new request to change ownership of a video', async function () {
+ this.timeout(15000)
+
+ await changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username)
+ })
+
+ it('Should return two requests to change ownership for the second user', async function () {
+ const resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken)
+
+ expect(resFirstUser.body.total).to.equal(0)
+ expect(resFirstUser.body.data).to.be.an('array')
+ expect(resFirstUser.body.data.length).to.equal(0)
+
+ const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken)
+
+ expect(resSecondUser.body.total).to.equal(2)
+ expect(resSecondUser.body.data).to.be.an('array')
+ expect(resSecondUser.body.data.length).to.equal(2)
+
+ lastRequestChangeOwnershipId = resSecondUser.body.data[0].id
+ })
+
+ it('Should not be possible to accept the change of ownership from first user', async function () {
+ this.timeout(10000)
+
+ const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserAccessToken)
+ const secondUserInformation: User = secondUserInformationResponse.body
+ const channelId = secondUserInformation.videoChannels[0].id
+ await acceptChangeOwnership(server.url, firstUserAccessToken, lastRequestChangeOwnershipId, channelId, 403)
+ })
+
+ it('Should be possible to accept the change of ownership from second user', async function () {
+ this.timeout(10000)
+
+ const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserAccessToken)
+ const secondUserInformation: User = secondUserInformationResponse.body
+ const channelId = secondUserInformation.videoChannels[0].id
+ await acceptChangeOwnership(server.url, secondUserAccessToken, lastRequestChangeOwnershipId, channelId)
+ })
+
+ after(async function () {
+ killallServers([server])
+ })
+})
+
+describe('Test video change ownership - quota too small', function () {
+ let server: ServerInfo = undefined
+ const firstUser = {
+ username: 'first',
+ password: 'My great password'
+ }
+ const secondUser = {
+ username: 'second',
+ password: 'My other password'
+ }
+ let firstUserAccessToken = ''
+ let secondUserAccessToken = ''
+ let lastRequestChangeOwnershipId = undefined
+
+ before(async function () {
+ this.timeout(50000)
+
+ // Run one server
+ await flushTests()
+ server = await runServer(1)
+ await setAccessTokensToServers([server])
+
+ const videoQuota = 42000000
+ const limitedVideoQuota = 10
+ await createUser(server.url, server.accessToken, firstUser.username, firstUser.password, videoQuota)
+ await createUser(server.url, server.accessToken, secondUser.username, secondUser.password, limitedVideoQuota)
+
+ firstUserAccessToken = await userLogin(server, firstUser)
+ secondUserAccessToken = await userLogin(server, secondUser)
+
+ // Upload some videos on the server
+ const video1Attributes = {
+ name: 'my super name',
+ description: 'my super description'
+ }
+ await uploadVideo(server.url, firstUserAccessToken, video1Attributes)
+
+ await waitJobs(server)
+
+ const res = await getVideosList(server.url)
+ const videos = res.body.data
+
+ expect(videos.length).to.equal(1)
+
+ server.video = videos.find(video => video.name === 'my super name')
+ })
+
+ it('Should send a request to change ownership of a video', async function () {
+ this.timeout(15000)
+
+ await changeVideoOwnership(server.url, firstUserAccessToken, server.video.id, secondUser.username)
+ })
+
+ it('Should only return a request to change ownership for the second user', async function () {
+ const resFirstUser = await getVideoChangeOwnershipList(server.url, firstUserAccessToken)
+
+ expect(resFirstUser.body.total).to.equal(0)
+ expect(resFirstUser.body.data).to.be.an('array')
+ expect(resFirstUser.body.data.length).to.equal(0)
+
+ const resSecondUser = await getVideoChangeOwnershipList(server.url, secondUserAccessToken)
+
+ expect(resSecondUser.body.total).to.equal(1)
+ expect(resSecondUser.body.data).to.be.an('array')
+ expect(resSecondUser.body.data.length).to.equal(1)
+
+ lastRequestChangeOwnershipId = resSecondUser.body.data[0].id
+ })
+
+ it('Should not be possible to accept the change of ownership from second user because of exceeded quota', async function () {
+ this.timeout(10000)
+
+ const secondUserInformationResponse = await getMyUserInformation(server.url, secondUserAccessToken)
+ const secondUserInformation: User = secondUserInformationResponse.body
+ const channelId = secondUserInformation.videoChannels[0].id
+ await acceptChangeOwnership(server.url, secondUserAccessToken, lastRequestChangeOwnershipId, channelId, 403)
+ })
+
+ after(async function () {
+ killallServers([server])
+ })
+})
export * from './videos/video-blacklist'
export * from './videos/video-channels'
export * from './videos/videos'
+export * from './videos/video-change-ownership'
export * from './feeds/feeds'
export * from './search/videos'
--- /dev/null
+import * as request from 'supertest'
+
+function changeVideoOwnership (url: string, token: string, videoId: number | string, username) {
+ const path = '/api/v1/videos/' + videoId + '/give-ownership'
+
+ return request(url)
+ .post(path)
+ .set('Accept', 'application/json')
+ .set('Authorization', 'Bearer ' + token)
+ .send({ username })
+ .expect(204)
+}
+
+function getVideoChangeOwnershipList (url: string, token: string) {
+ const path = '/api/v1/videos/ownership'
+
+ return request(url)
+ .get(path)
+ .query({ sort: '-createdAt' })
+ .set('Accept', 'application/json')
+ .set('Authorization', 'Bearer ' + token)
+ .expect(200)
+ .expect('Content-Type', /json/)
+}
+
+function acceptChangeOwnership (url: string, token: string, ownershipId: string, channelId: number, expectedStatus = 204) {
+ const path = '/api/v1/videos/ownership/' + ownershipId + '/accept'
+
+ return request(url)
+ .post(path)
+ .set('Accept', 'application/json')
+ .set('Authorization', 'Bearer ' + token)
+ .send({ channelId })
+ .expect(expectedStatus)
+}
+
+function refuseChangeOwnership (url: string, token: string, ownershipId: string, expectedStatus = 204) {
+ const path = '/api/v1/videos/ownership/' + ownershipId + '/refuse'
+
+ return request(url)
+ .post(path)
+ .set('Accept', 'application/json')
+ .set('Authorization', 'Bearer ' + token)
+ .expect(expectedStatus)
+}
+
+// ---------------------------------------------------------------------------
+
+export {
+ changeVideoOwnership,
+ getVideoChangeOwnershipList,
+ acceptChangeOwnership,
+ refuseChangeOwnership
+}
REMOVE_ANY_VIDEO,
REMOVE_ANY_VIDEO_CHANNEL,
REMOVE_ANY_VIDEO_COMMENT,
- UPDATE_ANY_VIDEO
+ UPDATE_ANY_VIDEO,
+ CHANGE_VIDEO_OWNERSHIP
}
export * from './channel/video-channel-create.model'
export * from './channel/video-channel-update.model'
export * from './channel/video-channel.model'
+export * from './video-change-ownership.model'
+export * from './video-change-ownership-create.model'
export * from './video-create.model'
export * from './video-privacy.enum'
export * from './video-rate.type'
--- /dev/null
+export interface VideoChangeOwnershipAccept {
+ channelId: number
+}
--- /dev/null
+export interface VideoChangeOwnershipCreate {
+ username: string
+}
--- /dev/null
+import { Account } from '../actors'
+
+export interface VideoChangeOwnership {
+ id: number
+ status: VideoChangeOwnershipStatus
+ initiatorAccount: Account
+ nextOwnerAccount: Account
+ video: {
+ id: number
+ name: string
+ uuid: string
+ url: string
+ }
+ createdAt: Date
+}
+
+export enum VideoChangeOwnershipStatus {
+ WAITING = 'WAITING',
+ ACCEPTED = 'ACCEPTED',
+ REFUSED = 'REFUSED'
+}