From: buoyantair Date: Tue, 20 Nov 2018 06:58:13 +0000 (+0530) Subject: Merge branch 'develop' of https://github.com/Chocobozzz/PeerTube into move-utils... X-Git-Tag: v1.2.0-rc.1~88^2~1 X-Git-Url: https://git.librecmc.org/?a=commitdiff_plain;h=bc22d60899e14631cba0fb6450f4e85fc9528293;p=oweals%2Fpeertube.git Merge branch 'develop' of https://github.com/Chocobozzz/PeerTube into move-utils-to-shared --- bc22d60899e14631cba0fb6450f4e85fc9528293 diff --cc server/tests/api/activitypub/security.ts index 69b7c0148,7349749f1..b71a61c8c --- a/server/tests/api/activitypub/security.ts +++ b/server/tests/api/activitypub/security.ts @@@ -2,16 -2,7 +2,12 @@@ import 'mocha' -import { flushAndRunMultipleServers, flushTests, killallServers, ServerInfo } from '../../utils' +import { + flushAndRunMultipleServers, + flushTests, + killallServers, + ServerInfo +} from '../../../../shared/utils' - import { - makePOSTAPRequest, - makeFollowRequest, - } from '../../utils/requests/activitypub' import { HTTP_SIGNATURE } from '../../../initializers' import { buildDigest, buildGlobalHeaders } from '../../../lib/job-queue/handlers/utils/activitypub-http-utils' import * as chai from 'chai' diff --cc server/tests/api/videos/video-channels.ts index 5bffffc66,41429a3d8..63514d69c --- a/server/tests/api/videos/video-channels.ts +++ b/server/tests/api/videos/video-channels.ts @@@ -7,11 -7,13 +7,13 @@@ import createUser, doubleFollow, flushAndRunMultipleServers, - getVideoChannelVideos, serverLogin, testImage, + getVideoChannelVideos, + testImage, updateVideo, updateVideoChannelAvatar, - uploadVideo, wait, userLogin + uploadVideo, + userLogin -} from '../../utils' +} from '../../../../shared/utils' import { addVideoChannel, deleteVideoChannel, diff --cc server/tests/api/videos/video-schedule-update.ts index ecfc5e034,b226a9d50..632c4244c --- a/server/tests/api/videos/video-schedule-update.ts +++ b/server/tests/api/videos/video-schedule-update.ts @@@ -15,9 -15,8 +15,8 @@@ import updateVideo, uploadVideo, wait -} from '../../utils' -import { waitJobs } from '../../utils/server/jobs' +} from '../../../../shared/utils' - import { join } from 'path' +import { waitJobs } from '../../../../shared/utils/server/jobs' const expect = chai.expect diff --cc server/tests/api/videos/video-transcoder.ts index f9458f0ec,23920d452..68cf00194 --- a/server/tests/api/videos/video-transcoder.ts +++ b/server/tests/api/videos/video-transcoder.ts @@@ -18,12 -18,10 +18,11 @@@ import ServerInfo, setAccessTokensToServers, uploadVideo, - webtorrentAdd, - generateHighBitrateVideo + webtorrentAdd -} from '../../utils' +} from '../../../../shared/utils' import { join } from 'path' -import { waitJobs } from '../../utils/server/jobs' +import { waitJobs } from '../../../../shared/utils/server/jobs' +import { pathExists } from 'fs-extra' import { VIDEO_TRANSCODING_FPS } from '../../../../server/initializers/constants' const expect = chai.expect diff --cc shared/utils/requests/check-api-params.ts index edb47e0e9,000000000..a2a549682 mode 100644,000000..100644 --- a/shared/utils/requests/check-api-params.ts +++ b/shared/utils/requests/check-api-params.ts @@@ -1,40 -1,0 +1,40 @@@ +import { makeGetRequest } from './requests' - import { immutableAssign } from '..' ++import { immutableAssign } from '../miscs/miscs' + +function checkBadStartPagination (url: string, path: string, token?: string, query = {}) { + return makeGetRequest({ + url, + path, + token, + query: immutableAssign(query, { start: 'hello' }), + statusCodeExpected: 400 + }) +} + +function checkBadCountPagination (url: string, path: string, token?: string, query = {}) { + return makeGetRequest({ + url, + path, + token, + query: immutableAssign(query, { count: 'hello' }), + statusCodeExpected: 400 + }) +} + +function checkBadSortPagination (url: string, path: string, token?: string, query = {}) { + return makeGetRequest({ + url, + path, + token, + query: immutableAssign(query, { sort: 'hello' }), + statusCodeExpected: 400 + }) +} + +// --------------------------------------------------------------------------- + +export { + checkBadStartPagination, + checkBadCountPagination, + checkBadSortPagination +} diff --cc shared/utils/search/videos.ts index 115b3ff9a,000000000..ba4627017 mode 100644,000000..100644 --- a/shared/utils/search/videos.ts +++ b/shared/utils/search/videos.ts @@@ -1,77 -1,0 +1,77 @@@ +/* tslint:disable:no-unused-expression */ + +import * as request from 'supertest' +import { VideosSearchQuery } from '../../models/search' - import { immutableAssign } from '..' ++import { immutableAssign } from '../miscs/miscs' + +function searchVideo (url: string, search: string) { + const path = '/api/v1/search/videos' + const req = request(url) + .get(path) + .query({ sort: '-publishedAt', search }) + .set('Accept', 'application/json') + + return req.expect(200) + .expect('Content-Type', /json/) +} + +function searchVideoWithToken (url: string, search: string, token: string, query: { nsfw?: boolean } = {}) { + const path = '/api/v1/search/videos' + const req = request(url) + .get(path) + .set('Authorization', 'Bearer ' + token) + .query(immutableAssign(query, { sort: '-publishedAt', search })) + .set('Accept', 'application/json') + + return req.expect(200) + .expect('Content-Type', /json/) +} + +function searchVideoWithPagination (url: string, search: string, start: number, count: number, sort?: string) { + const path = '/api/v1/search/videos' + + const req = request(url) + .get(path) + .query({ start }) + .query({ search }) + .query({ count }) + + if (sort) req.query({ sort }) + + return req.set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function searchVideoWithSort (url: string, search: string, sort: string) { + const path = '/api/v1/search/videos' + + return request(url) + .get(path) + .query({ search }) + .query({ sort }) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function advancedVideosSearch (url: string, options: VideosSearchQuery) { + const path = '/api/v1/search/videos' + + return request(url) + .get(path) + .query(options) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +// --------------------------------------------------------------------------- + +export { + searchVideo, + advancedVideosSearch, + searchVideoWithToken, + searchVideoWithPagination, + searchVideoWithSort +} diff --cc shared/utils/server/config.ts index 15a94432b,000000000..5b888b061 mode 100644,000000..100644 --- a/shared/utils/server/config.ts +++ b/shared/utils/server/config.ts @@@ -1,135 -1,0 +1,135 @@@ - import { makeDeleteRequest, makeGetRequest, makePutBodyRequest } from '../' ++import { makeDeleteRequest, makeGetRequest, makePutBodyRequest } from '../requests/requests' +import { CustomConfig } from '../../models/server/custom-config.model' + +function getConfig (url: string) { + const path = '/api/v1/config' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getAbout (url: string) { + const path = '/api/v1/config/about' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getCustomConfig (url: string, token: string, statusCodeExpected = 200) { + const path = '/api/v1/config/custom' + + return makeGetRequest({ + url, + token, + path, + statusCodeExpected + }) +} + +function updateCustomConfig (url: string, token: string, newCustomConfig: CustomConfig, statusCodeExpected = 200) { + const path = '/api/v1/config/custom' + + return makePutBodyRequest({ + url, + token, + path, + fields: newCustomConfig, + statusCodeExpected + }) +} + +function updateCustomSubConfig (url: string, token: string, newConfig: any) { + const updateParams: CustomConfig = { + instance: { + name: 'PeerTube updated', + shortDescription: 'my short description', + description: 'my super description', + terms: 'my super terms', + defaultClientRoute: '/videos/recently-added', + defaultNSFWPolicy: 'blur', + customizations: { + javascript: 'alert("coucou")', + css: 'body { background-color: red; }' + } + }, + services: { + twitter: { + username: '@MySuperUsername', + whitelisted: true + } + }, + cache: { + previews: { + size: 2 + }, + captions: { + size: 3 + } + }, + signup: { + enabled: false, + limit: 5, + requiresEmailVerification: false + }, + admin: { + email: 'superadmin1@example.com' + }, + user: { + videoQuota: 5242881, + videoQuotaDaily: 318742 + }, + transcoding: { + enabled: true, + threads: 1, + resolutions: { + '240p': false, + '360p': true, + '480p': true, + '720p': false, + '1080p': false + } + }, + import: { + videos: { + http: { + enabled: false + }, + torrent: { + enabled: false + } + } + } + } + + Object.assign(updateParams, newConfig) + + return updateCustomConfig(url, token, updateParams) +} + +function deleteCustomConfig (url: string, token: string, statusCodeExpected = 200) { + const path = '/api/v1/config/custom' + + return makeDeleteRequest({ + url, + token, + path, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + getConfig, + getCustomConfig, + updateCustomConfig, + getAbout, + deleteCustomConfig, + updateCustomSubConfig +} diff --cc shared/utils/server/jobs.ts index 3eec1d7d7,000000000..7c7e89824 mode 100644,000000..100644 --- a/shared/utils/server/jobs.ts +++ b/shared/utils/server/jobs.ts @@@ -1,77 -1,0 +1,78 @@@ +import * as request from 'supertest' +import { Job, JobState } from '../../models' - import { ServerInfo, wait } from '../index' ++import { wait } from '../miscs/miscs' ++import { ServerInfo } from './servers' + +function getJobsList (url: string, accessToken: string, state: JobState) { + const path = '/api/v1/jobs/' + state + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +function getJobsListPaginationAndSort (url: string, accessToken: string, state: JobState, start: number, count: number, sort: string) { + const path = '/api/v1/jobs/' + state + + return request(url) + .get(path) + .query({ start }) + .query({ count }) + .query({ sort }) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +async function waitJobs (serversArg: ServerInfo[] | ServerInfo) { + let servers: ServerInfo[] + + if (Array.isArray(serversArg) === false) servers = [ serversArg as ServerInfo ] + else servers = serversArg as ServerInfo[] + + const states: JobState[] = [ 'waiting', 'active', 'delayed' ] + const tasks: Promise[] = [] + let pendingRequests: boolean + + do { + pendingRequests = false + + // Check if each server has pending request + for (const server of servers) { + for (const state of states) { + const p = getJobsListPaginationAndSort(server.url, server.accessToken, state, 0, 10, '-createdAt') + .then(res => res.body.data) + .then((jobs: Job[]) => jobs.filter(j => j.type !== 'videos-views')) + .then(jobs => { + if (jobs.length !== 0) pendingRequests = true + }) + tasks.push(p) + } + } + + await Promise.all(tasks) + + // Retry, in case of new jobs were created + if (pendingRequests === false) { + await wait(1000) + + await Promise.all(tasks) + } + + if (pendingRequests) { + await wait(1000) + } + } while (pendingRequests) +} + +// --------------------------------------------------------------------------- + +export { + getJobsList, + waitJobs, + getJobsListPaginationAndSort +} diff --cc shared/utils/server/stats.ts index 01989d952,000000000..6f079ad18 mode 100644,000000..100644 --- a/shared/utils/server/stats.ts +++ b/shared/utils/server/stats.ts @@@ -1,22 -1,0 +1,22 @@@ - import { makeGetRequest } from '../' ++import { makeGetRequest } from '../requests/requests' + +function getStats (url: string, useCache = false) { + const path = '/api/v1/server/stats' + + const query = { + t: useCache ? undefined : new Date().getTime() + } + + return makeGetRequest({ + url, + path, + query, + statusCodeExpected: 200 + }) +} + +// --------------------------------------------------------------------------- + +export { + getStats +} diff --cc shared/utils/users/accounts.ts index 5601f2a77,000000000..388eb6973 mode 100644,000000..100644 --- a/shared/utils/users/accounts.ts +++ b/shared/utils/users/accounts.ts @@@ -1,63 -1,0 +1,63 @@@ +/* tslint:disable:no-unused-expression */ + +import { expect } from 'chai' +import { existsSync, readdir } from 'fs-extra' +import { join } from 'path' +import { Account } from '../../models/actors' - import { root } from '../index' ++import { root } from '../miscs/miscs' +import { makeGetRequest } from '../requests/requests' + +function getAccountsList (url: string, sort = '-createdAt', statusCodeExpected = 200) { + const path = '/api/v1/accounts' + + return makeGetRequest({ + url, + query: { sort }, + path, + statusCodeExpected + }) +} + +function getAccount (url: string, accountName: string, statusCodeExpected = 200) { + const path = '/api/v1/accounts/' + accountName + + return makeGetRequest({ + url, + path, + statusCodeExpected + }) +} + +async function expectAccountFollows (url: string, nameWithDomain: string, followersCount: number, followingCount: number) { + const res = await getAccountsList(url) + const account = res.body.data.find((a: Account) => a.name + '@' + a.host === nameWithDomain) + + const message = `${nameWithDomain} on ${url}` + expect(account.followersCount).to.equal(followersCount, message) + expect(account.followingCount).to.equal(followingCount, message) +} + +async function checkActorFilesWereRemoved (actorUUID: string, serverNumber: number) { + const testDirectory = 'test' + serverNumber + + for (const directory of [ 'avatars' ]) { + const directoryPath = join(root(), testDirectory, directory) + + const directoryExists = existsSync(directoryPath) + expect(directoryExists).to.be.true + + const files = await readdir(directoryPath) + for (const file of files) { + expect(file).to.not.contain(actorUUID) + } + } +} + +// --------------------------------------------------------------------------- + +export { + getAccount, + expectAccountFollows, + getAccountsList, + checkActorFilesWereRemoved +} diff --cc shared/utils/users/blocklist.ts index 35b537571,000000000..0ead5e5f6 mode 100644,000000..100644 --- a/shared/utils/users/blocklist.ts +++ b/shared/utils/users/blocklist.ts @@@ -1,198 -1,0 +1,198 @@@ +/* tslint:disable:no-unused-expression */ + - import { makeDeleteRequest, makePostBodyRequest } from '../index' ++import { makeDeleteRequest, makePostBodyRequest } from '../requests/requests' +import { makeGetRequest } from '../requests/requests' + +function getAccountBlocklistByAccount ( + url: string, + token: string, + start: number, + count: number, + sort = '-createdAt', + statusCodeExpected = 200 +) { + const path = '/api/v1/users/me/blocklist/accounts' + + return makeGetRequest({ + url, + token, + query: { start, count, sort }, + path, + statusCodeExpected + }) +} + +function addAccountToAccountBlocklist (url: string, token: string, accountToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/blocklist/accounts' + + return makePostBodyRequest({ + url, + path, + token, + fields: { + accountName: accountToBlock + }, + statusCodeExpected + }) +} + +function removeAccountFromAccountBlocklist (url: string, token: string, accountToUnblock: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/blocklist/accounts/' + accountToUnblock + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +function getServerBlocklistByAccount ( + url: string, + token: string, + start: number, + count: number, + sort = '-createdAt', + statusCodeExpected = 200 +) { + const path = '/api/v1/users/me/blocklist/servers' + + return makeGetRequest({ + url, + token, + query: { start, count, sort }, + path, + statusCodeExpected + }) +} + +function addServerToAccountBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/blocklist/servers' + + return makePostBodyRequest({ + url, + path, + token, + fields: { + host: serverToBlock + }, + statusCodeExpected + }) +} + +function removeServerFromAccountBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/blocklist/servers/' + serverToBlock + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +function getAccountBlocklistByServer ( + url: string, + token: string, + start: number, + count: number, + sort = '-createdAt', + statusCodeExpected = 200 +) { + const path = '/api/v1/server/blocklist/accounts' + + return makeGetRequest({ + url, + token, + query: { start, count, sort }, + path, + statusCodeExpected + }) +} + +function addAccountToServerBlocklist (url: string, token: string, accountToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/server/blocklist/accounts' + + return makePostBodyRequest({ + url, + path, + token, + fields: { + accountName: accountToBlock + }, + statusCodeExpected + }) +} + +function removeAccountFromServerBlocklist (url: string, token: string, accountToUnblock: string, statusCodeExpected = 204) { + const path = '/api/v1/server/blocklist/accounts/' + accountToUnblock + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +function getServerBlocklistByServer ( + url: string, + token: string, + start: number, + count: number, + sort = '-createdAt', + statusCodeExpected = 200 +) { + const path = '/api/v1/server/blocklist/servers' + + return makeGetRequest({ + url, + token, + query: { start, count, sort }, + path, + statusCodeExpected + }) +} + +function addServerToServerBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/server/blocklist/servers' + + return makePostBodyRequest({ + url, + path, + token, + fields: { + host: serverToBlock + }, + statusCodeExpected + }) +} + +function removeServerFromServerBlocklist (url: string, token: string, serverToBlock: string, statusCodeExpected = 204) { + const path = '/api/v1/server/blocklist/servers/' + serverToBlock + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + getAccountBlocklistByAccount, + addAccountToAccountBlocklist, + removeAccountFromAccountBlocklist, + getServerBlocklistByAccount, + addServerToAccountBlocklist, + removeServerFromAccountBlocklist, + + getAccountBlocklistByServer, + addAccountToServerBlocklist, + removeAccountFromServerBlocklist, + getServerBlocklistByServer, + addServerToServerBlocklist, + removeServerFromServerBlocklist +} diff --cc shared/utils/users/user-subscriptions.ts index b0e7da7cc,000000000..7148fbfca mode 100644,000000..100644 --- a/shared/utils/users/user-subscriptions.ts +++ b/shared/utils/users/user-subscriptions.ts @@@ -1,82 -1,0 +1,82 @@@ - import { makeDeleteRequest, makeGetRequest, makePostBodyRequest } from '../' ++import { makeDeleteRequest, makeGetRequest, makePostBodyRequest } from '../requests/requests' + +function addUserSubscription (url: string, token: string, targetUri: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/subscriptions' + + return makePostBodyRequest({ + url, + path, + token, + statusCodeExpected, + fields: { uri: targetUri } + }) +} + +function listUserSubscriptions (url: string, token: string, sort = '-createdAt', statusCodeExpected = 200) { + const path = '/api/v1/users/me/subscriptions' + + return makeGetRequest({ + url, + path, + token, + statusCodeExpected, + query: { sort } + }) +} + +function listUserSubscriptionVideos (url: string, token: string, sort = '-createdAt', statusCodeExpected = 200) { + const path = '/api/v1/users/me/subscriptions/videos' + + return makeGetRequest({ + url, + path, + token, + statusCodeExpected, + query: { sort } + }) +} + +function getUserSubscription (url: string, token: string, uri: string, statusCodeExpected = 200) { + const path = '/api/v1/users/me/subscriptions/' + uri + + return makeGetRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +function removeUserSubscription (url: string, token: string, uri: string, statusCodeExpected = 204) { + const path = '/api/v1/users/me/subscriptions/' + uri + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +function areSubscriptionsExist (url: string, token: string, uris: string[], statusCodeExpected = 200) { + const path = '/api/v1/users/me/subscriptions/exist' + + return makeGetRequest({ + url, + path, + query: { 'uris[]': uris }, + token, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + areSubscriptionsExist, + addUserSubscription, + listUserSubscriptions, + getUserSubscription, + listUserSubscriptionVideos, + removeUserSubscription +} diff --cc shared/utils/users/users.ts index 1b385aaf7,000000000..d5d62a507 mode 100644,000000..100644 --- a/shared/utils/users/users.ts +++ b/shared/utils/users/users.ts @@@ -1,296 -1,0 +1,296 @@@ +import * as request from 'supertest' - import { makePostBodyRequest, makePutBodyRequest, updateAvatarRequest } from '../' ++import { makePostBodyRequest, makePutBodyRequest, updateAvatarRequest } from '../requests/requests' + +import { UserRole } from '../../index' +import { NSFWPolicyType } from '../../models/videos/nsfw-policy.type' + +function createUser ( + url: string, + accessToken: string, + username: string, + password: string, + videoQuota = 1000000, + videoQuotaDaily = -1, + role: UserRole = UserRole.USER, + specialStatus = 200 +) { + const path = '/api/v1/users' + const body = { + username, + password, + role, + email: username + '@example.com', + videoQuota, + videoQuotaDaily + } + + return request(url) + .post(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .send(body) + .expect(specialStatus) +} + +function registerUser (url: string, username: string, password: string, specialStatus = 204) { + const path = '/api/v1/users/register' + const body = { + username, + password, + email: username + '@example.com' + } + + return request(url) + .post(path) + .set('Accept', 'application/json') + .send(body) + .expect(specialStatus) +} + +function getMyUserInformation (url: string, accessToken: string, specialStatus = 200) { + const path = '/api/v1/users/me' + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(specialStatus) + .expect('Content-Type', /json/) +} + +function deleteMe (url: string, accessToken: string, specialStatus = 204) { + const path = '/api/v1/users/me' + + return request(url) + .delete(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(specialStatus) +} + +function getMyUserVideoQuotaUsed (url: string, accessToken: string, specialStatus = 200) { + const path = '/api/v1/users/me/video-quota-used' + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(specialStatus) + .expect('Content-Type', /json/) +} + +function getUserInformation (url: string, accessToken: string, userId: number) { + const path = '/api/v1/users/' + userId + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +function getMyUserVideoRating (url: string, accessToken: string, videoId: number | string, specialStatus = 200) { + const path = '/api/v1/users/me/videos/' + videoId + '/rating' + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(specialStatus) + .expect('Content-Type', /json/) +} + +function getUsersList (url: string, accessToken: string) { + const path = '/api/v1/users' + + return request(url) + .get(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +function getUsersListPaginationAndSort (url: string, accessToken: string, start: number, count: number, sort: string, search?: string) { + const path = '/api/v1/users' + + return request(url) + .get(path) + .query({ start }) + .query({ count }) + .query({ sort }) + .query({ search }) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +function removeUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204) { + const path = '/api/v1/users' + + return request(url) + .delete(path + '/' + userId) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(expectedStatus) +} + +function blockUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204, reason?: string) { + const path = '/api/v1/users' + let body: any + if (reason) body = { reason } + + return request(url) + .post(path + '/' + userId + '/block') + .send(body) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(expectedStatus) +} + +function unblockUser (url: string, userId: number | string, accessToken: string, expectedStatus = 204) { + const path = '/api/v1/users' + + return request(url) + .post(path + '/' + userId + '/unblock') + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(expectedStatus) +} + +function updateMyUser (options: { + url: string + accessToken: string, + currentPassword?: string, + newPassword?: string, + nsfwPolicy?: NSFWPolicyType, + email?: string, + autoPlayVideo?: boolean + displayName?: string, + description?: string +}) { + const path = '/api/v1/users/me' + + const toSend = {} + if (options.currentPassword !== undefined && options.currentPassword !== null) toSend['currentPassword'] = options.currentPassword + if (options.newPassword !== undefined && options.newPassword !== null) toSend['password'] = options.newPassword + if (options.nsfwPolicy !== undefined && options.nsfwPolicy !== null) toSend['nsfwPolicy'] = options.nsfwPolicy + if (options.autoPlayVideo !== undefined && options.autoPlayVideo !== null) toSend['autoPlayVideo'] = options.autoPlayVideo + if (options.email !== undefined && options.email !== null) toSend['email'] = options.email + if (options.description !== undefined && options.description !== null) toSend['description'] = options.description + if (options.displayName !== undefined && options.displayName !== null) toSend['displayName'] = options.displayName + + return makePutBodyRequest({ + url: options.url, + path, + token: options.accessToken, + fields: toSend, + statusCodeExpected: 204 + }) +} + +function updateMyAvatar (options: { + url: string, + accessToken: string, + fixture: string +}) { + const path = '/api/v1/users/me/avatar/pick' + + return updateAvatarRequest(Object.assign(options, { path })) +} + +function updateUser (options: { + url: string + userId: number, + accessToken: string, + email?: string, + videoQuota?: number, + videoQuotaDaily?: number, + role?: UserRole +}) { + const path = '/api/v1/users/' + options.userId + + const toSend = {} + if (options.email !== undefined && options.email !== null) toSend['email'] = options.email + if (options.videoQuota !== undefined && options.videoQuota !== null) toSend['videoQuota'] = options.videoQuota + if (options.videoQuotaDaily !== undefined && options.videoQuotaDaily !== null) toSend['videoQuotaDaily'] = options.videoQuotaDaily + if (options.role !== undefined && options.role !== null) toSend['role'] = options.role + + return makePutBodyRequest({ + url: options.url, + path, + token: options.accessToken, + fields: toSend, + statusCodeExpected: 204 + }) +} + +function askResetPassword (url: string, email: string) { + const path = '/api/v1/users/ask-reset-password' + + return makePostBodyRequest({ + url, + path, + fields: { email }, + statusCodeExpected: 204 + }) +} + +function resetPassword (url: string, userId: number, verificationString: string, password: string, statusCodeExpected = 204) { + const path = '/api/v1/users/' + userId + '/reset-password' + + return makePostBodyRequest({ + url, + path, + fields: { password, verificationString }, + statusCodeExpected + }) +} + +function askSendVerifyEmail (url: string, email: string) { + const path = '/api/v1/users/ask-send-verify-email' + + return makePostBodyRequest({ + url, + path, + fields: { email }, + statusCodeExpected: 204 + }) +} + +function verifyEmail (url: string, userId: number, verificationString: string, statusCodeExpected = 204) { + const path = '/api/v1/users/' + userId + '/verify-email' + + return makePostBodyRequest({ + url, + path, + fields: { verificationString }, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + createUser, + registerUser, + getMyUserInformation, + getMyUserVideoRating, + deleteMe, + getMyUserVideoQuotaUsed, + getUsersList, + getUsersListPaginationAndSort, + removeUser, + updateUser, + updateMyUser, + getUserInformation, + blockUser, + unblockUser, + askResetPassword, + resetPassword, + updateMyAvatar, + askSendVerifyEmail, + verifyEmail +} diff --cc shared/utils/videos/video-abuses.ts index 8be891a9b,000000000..7f011ec0f mode 100644,000000..100644 --- a/shared/utils/videos/video-abuses.ts +++ b/shared/utils/videos/video-abuses.ts @@@ -1,65 -1,0 +1,65 @@@ +import * as request from 'supertest' +import { VideoAbuseUpdate } from '../../models/videos/abuse/video-abuse-update.model' - import { makeDeleteRequest, makePutBodyRequest } from '..' ++import { makeDeleteRequest, makePutBodyRequest } from '../requests/requests' + +function reportVideoAbuse (url: string, token: string, videoId: number | string, reason: string, specialStatus = 200) { + const path = '/api/v1/videos/' + videoId + '/abuse' + + return request(url) + .post(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .send({ reason }) + .expect(specialStatus) +} + +function getVideoAbusesList (url: string, token: string) { + const path = '/api/v1/videos/abuse' + + return request(url) + .get(path) + .query({ sort: 'createdAt' }) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(200) + .expect('Content-Type', /json/) +} + +function updateVideoAbuse ( + url: string, + token: string, + videoId: string | number, + videoAbuseId: number, + body: VideoAbuseUpdate, + statusCodeExpected = 204 +) { + const path = '/api/v1/videos/' + videoId + '/abuse/' + videoAbuseId + + return makePutBodyRequest({ + url, + token, + path, + fields: body, + statusCodeExpected + }) +} + +function deleteVideoAbuse (url: string, token: string, videoId: string | number, videoAbuseId: number, statusCodeExpected = 204) { + const path = '/api/v1/videos/' + videoId + '/abuse/' + videoAbuseId + + return makeDeleteRequest({ + url, + token, + path, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + reportVideoAbuse, + getVideoAbusesList, + updateVideoAbuse, + deleteVideoAbuse +} diff --cc shared/utils/videos/video-captions.ts index 41e52be07,000000000..8d67f617b mode 100644,000000..100644 --- a/shared/utils/videos/video-captions.ts +++ b/shared/utils/videos/video-captions.ts @@@ -1,71 -1,0 +1,71 @@@ - import { makeDeleteRequest, makeGetRequest } from '../' - import { buildAbsoluteFixturePath, makeUploadRequest } from '../index' ++import { makeDeleteRequest, makeGetRequest, makeUploadRequest } from '../requests/requests' +import * as request from 'supertest' +import * as chai from 'chai' ++import { buildAbsoluteFixturePath } from '../miscs/miscs' + +const expect = chai.expect + +function createVideoCaption (args: { + url: string, + accessToken: string + videoId: string | number + language: string + fixture: string, + mimeType?: string, + statusCodeExpected?: number +}) { + const path = '/api/v1/videos/' + args.videoId + '/captions/' + args.language + + const captionfile = buildAbsoluteFixturePath(args.fixture) + const captionfileAttach = args.mimeType ? [ captionfile, { contentType: args.mimeType } ] : captionfile + + return makeUploadRequest({ + method: 'PUT', + url: args.url, + path, + token: args.accessToken, + fields: {}, + attaches: { + captionfile: captionfileAttach + }, + statusCodeExpected: args.statusCodeExpected || 204 + }) +} + +function listVideoCaptions (url: string, videoId: string | number) { + const path = '/api/v1/videos/' + videoId + '/captions' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function deleteVideoCaption (url: string, token: string, videoId: string | number, language: string) { + const path = '/api/v1/videos/' + videoId + '/captions/' + language + + return makeDeleteRequest({ + url, + token, + path, + statusCodeExpected: 204 + }) +} + +async function testCaptionFile (url: string, captionPath: string, containsString: string) { + const res = await request(url) + .get(captionPath) + .expect(200) + + expect(res.text).to.contain(containsString) +} + +// --------------------------------------------------------------------------- + +export { + createVideoCaption, + listVideoCaptions, + testCaptionFile, + deleteVideoCaption +} diff --cc shared/utils/videos/video-channels.ts index 3d37f0e4c,000000000..3935c261e mode 100644,000000..100644 --- a/shared/utils/videos/video-channels.ts +++ b/shared/utils/videos/video-channels.ts @@@ -1,118 -1,0 +1,118 @@@ +import * as request from 'supertest' +import { VideoChannelCreate, VideoChannelUpdate } from '../../models/videos' - import { updateAvatarRequest } from '../index' ++import { updateAvatarRequest } from '../requests/requests' + +function getVideoChannelsList (url: string, start: number, count: number, sort?: string) { + const path = '/api/v1/video-channels' + + const req = request(url) + .get(path) + .query({ start: start }) + .query({ count: count }) + + if (sort) req.query({ sort }) + + return req.set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getAccountVideoChannelsList (url: string, accountName: string, specialStatus = 200) { + const path = '/api/v1/accounts/' + accountName + '/video-channels' + + return request(url) + .get(path) + .set('Accept', 'application/json') + .expect(specialStatus) + .expect('Content-Type', /json/) +} + +function addVideoChannel ( + url: string, + token: string, + videoChannelAttributesArg: VideoChannelCreate, + expectedStatus = 200 +) { + const path = '/api/v1/video-channels/' + + // Default attributes + let attributes = { + displayName: 'my super video channel', + description: 'my super channel description', + support: 'my super channel support' + } + attributes = Object.assign(attributes, videoChannelAttributesArg) + + return request(url) + .post(path) + .send(attributes) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +function updateVideoChannel ( + url: string, + token: string, + channelName: string, + attributes: VideoChannelUpdate, + expectedStatus = 204 +) { + const body = {} + const path = '/api/v1/video-channels/' + channelName + + if (attributes.displayName) body['displayName'] = attributes.displayName + if (attributes.description) body['description'] = attributes.description + if (attributes.support) body['support'] = attributes.support + + return request(url) + .put(path) + .send(body) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +function deleteVideoChannel (url: string, token: string, channelName: string, expectedStatus = 204) { + const path = '/api/v1/video-channels/' + channelName + + return request(url) + .delete(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +function getVideoChannel (url: string, channelName: string) { + const path = '/api/v1/video-channels/' + channelName + + return request(url) + .get(path) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function updateVideoChannelAvatar (options: { + url: string, + accessToken: string, + fixture: string, + videoChannelName: string | number +}) { + + const path = '/api/v1/video-channels/' + options.videoChannelName + '/avatar/pick' + + return updateAvatarRequest(Object.assign(options, { path })) +} + +// --------------------------------------------------------------------------- + +export { + updateVideoChannelAvatar, + getVideoChannelsList, + getAccountVideoChannelsList, + addVideoChannel, + updateVideoChannel, + deleteVideoChannel, + getVideoChannel +} diff --cc shared/utils/videos/video-comments.ts index 7d4cae364,000000000..0ebf69ced mode 100644,000000..100644 --- a/shared/utils/videos/video-comments.ts +++ b/shared/utils/videos/video-comments.ts @@@ -1,87 -1,0 +1,87 @@@ +import * as request from 'supertest' - import { makeDeleteRequest } from '../' ++import { makeDeleteRequest } from '../requests/requests' + +function getVideoCommentThreads (url: string, videoId: number | string, start: number, count: number, sort?: string, token?: string) { + const path = '/api/v1/videos/' + videoId + '/comment-threads' + + const req = request(url) + .get(path) + .query({ start: start }) + .query({ count: count }) + + if (sort) req.query({ sort }) + if (token) req.set('Authorization', 'Bearer ' + token) + + return req.set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getVideoThreadComments (url: string, videoId: number | string, threadId: number, token?: string) { + const path = '/api/v1/videos/' + videoId + '/comment-threads/' + threadId + + const req = request(url) + .get(path) + .set('Accept', 'application/json') + + if (token) req.set('Authorization', 'Bearer ' + token) + + return req.expect(200) + .expect('Content-Type', /json/) +} + +function addVideoCommentThread (url: string, token: string, videoId: number | string, text: string, expectedStatus = 200) { + const path = '/api/v1/videos/' + videoId + '/comment-threads' + + return request(url) + .post(path) + .send({ text }) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +function addVideoCommentReply ( + url: string, + token: string, + videoId: number | string, + inReplyToCommentId: number, + text: string, + expectedStatus = 200 +) { + const path = '/api/v1/videos/' + videoId + '/comments/' + inReplyToCommentId + + return request(url) + .post(path) + .send({ text }) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +function deleteVideoComment ( + url: string, + token: string, + videoId: number | string, + commentId: number, + statusCodeExpected = 204 +) { + const path = '/api/v1/videos/' + videoId + '/comments/' + commentId + + return makeDeleteRequest({ + url, + path, + token, + statusCodeExpected + }) +} + +// --------------------------------------------------------------------------- + +export { + getVideoCommentThreads, + getVideoThreadComments, + addVideoCommentThread, + addVideoCommentReply, + deleteVideoComment +} diff --cc shared/utils/videos/video-imports.ts index bf5062cd1,000000000..3fa49b432 mode 100644,000000..100644 --- a/shared/utils/videos/video-imports.ts +++ b/shared/utils/videos/video-imports.ts @@@ -1,51 -1,0 +1,52 @@@ ++ +import { VideoImportCreate } from '../../models/videos' - import { makeGetRequest, makeUploadRequest } from '..' ++import { makeGetRequest, makeUploadRequest } from '../requests/requests' + +function getYoutubeVideoUrl () { + return 'https://youtu.be/msX3jv1XdvM' +} + +function getMagnetURI () { + // tslint:disable:max-line-length + return 'magnet:?xs=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Ftorrents%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.torrent&xt=urn:btih:0f498834733e8057ed5c6f2ee2b4efd8d84a76ee&dn=super+peertube2+video&tr=wss%3A%2F%2Fpeertube2.cpy.re%3A443%2Ftracker%2Fsocket&tr=https%3A%2F%2Fpeertube2.cpy.re%2Ftracker%2Fannounce&ws=https%3A%2F%2Fpeertube2.cpy.re%2Fstatic%2Fwebseed%2Fb209ca00-c8bb-4b2b-b421-1ede169f3dbc-720.mp4' +} + +function importVideo (url: string, token: string, attributes: VideoImportCreate) { + const path = '/api/v1/videos/imports' + + let attaches: any = {} + if (attributes.torrentfile) attaches = { torrentfile: attributes.torrentfile } + + return makeUploadRequest({ + url, + path, + token, + attaches, + fields: attributes, + statusCodeExpected: 200 + }) +} + +function getMyVideoImports (url: string, token: string, sort?: string) { + const path = '/api/v1/users/me/videos/imports' + + const query = {} + if (sort) query['sort'] = sort + + return makeGetRequest({ + url, + query, + path, + token, + statusCodeExpected: 200 + }) +} + +// --------------------------------------------------------------------------- + +export { + getYoutubeVideoUrl, + importVideo, + getMagnetURI, + getMyVideoImports +} diff --cc shared/utils/videos/videos.ts index b3206e566,000000000..1ab3e7c4b mode 100644,000000..100644 --- a/shared/utils/videos/videos.ts +++ b/shared/utils/videos/videos.ts @@@ -1,576 -1,0 +1,577 @@@ +/* tslint:disable:no-unused-expression */ + +import { expect } from 'chai' +import { existsSync, readdir, readFile } from 'fs-extra' +import * as parseTorrent from 'parse-torrent' +import { extname, join } from 'path' +import * as request from 'supertest' +import { + buildAbsoluteFixturePath, + getMyUserInformation, + immutableAssign, + makeGetRequest, + makePutBodyRequest, + makeUploadRequest, + root, + ServerInfo, + testImage +} from '../' ++ +import { VideoDetails, VideoPrivacy } from '../../models/videos' - import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers' - import { dateIsValid, webtorrentAdd } from '../index' ++import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../server/initializers/constants' ++import { dateIsValid, webtorrentAdd } from '../miscs/miscs' + +type VideoAttributes = { + name?: string + category?: number + licence?: number + language?: string + nsfw?: boolean + commentsEnabled?: boolean + waitTranscoding?: boolean + description?: string + tags?: string[] + channelId?: number + privacy?: VideoPrivacy + fixture?: string + thumbnailfile?: string + previewfile?: string + scheduleUpdate?: { + updateAt: string + privacy?: VideoPrivacy + } +} + +function getVideoCategories (url: string) { + const path = '/api/v1/videos/categories' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getVideoLicences (url: string) { + const path = '/api/v1/videos/licences' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getVideoLanguages (url: string) { + const path = '/api/v1/videos/languages' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getVideoPrivacies (url: string) { + const path = '/api/v1/videos/privacies' + + return makeGetRequest({ + url, + path, + statusCodeExpected: 200 + }) +} + +function getVideo (url: string, id: number | string, expectedStatus = 200) { + const path = '/api/v1/videos/' + id + + return request(url) + .get(path) + .set('Accept', 'application/json') + .expect(expectedStatus) +} + +function viewVideo (url: string, id: number | string, expectedStatus = 204, xForwardedFor?: string) { + const path = '/api/v1/videos/' + id + '/views' + + const req = request(url) + .post(path) + .set('Accept', 'application/json') + + if (xForwardedFor) { + req.set('X-Forwarded-For', xForwardedFor) + } + + return req.expect(expectedStatus) +} + +function getVideoWithToken (url: string, token: string, id: number | string, expectedStatus = 200) { + const path = '/api/v1/videos/' + id + + return request(url) + .get(path) + .set('Authorization', 'Bearer ' + token) + .set('Accept', 'application/json') + .expect(expectedStatus) +} + +function getVideoDescription (url: string, descriptionPath: string) { + return request(url) + .get(descriptionPath) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getVideosList (url: string) { + const path = '/api/v1/videos' + + return request(url) + .get(path) + .query({ sort: 'name' }) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getVideosListWithToken (url: string, token: string, query: { nsfw?: boolean } = {}) { + const path = '/api/v1/videos' + + return request(url) + .get(path) + .set('Authorization', 'Bearer ' + token) + .query(immutableAssign(query, { sort: 'name' })) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getLocalVideos (url: string) { + const path = '/api/v1/videos' + + return request(url) + .get(path) + .query({ sort: 'name', filter: 'local' }) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getMyVideos (url: string, accessToken: string, start: number, count: number, sort?: string) { + const path = '/api/v1/users/me/videos' + + const req = request(url) + .get(path) + .query({ start: start }) + .query({ count: count }) + + if (sort) req.query({ sort }) + + return req.set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .expect(200) + .expect('Content-Type', /json/) +} + +function getAccountVideos ( + url: string, + accessToken: string, + accountName: string, + start: number, + count: number, + sort?: string, + query: { nsfw?: boolean } = {} +) { + const path = '/api/v1/accounts/' + accountName + '/videos' + + return makeGetRequest({ + url, + path, + query: immutableAssign(query, { + start, + count, + sort + }), + token: accessToken, + statusCodeExpected: 200 + }) +} + +function getVideoChannelVideos ( + url: string, + accessToken: string, + videoChannelName: string, + start: number, + count: number, + sort?: string, + query: { nsfw?: boolean } = {} +) { + const path = '/api/v1/video-channels/' + videoChannelName + '/videos' + + return makeGetRequest({ + url, + path, + query: immutableAssign(query, { + start, + count, + sort + }), + token: accessToken, + statusCodeExpected: 200 + }) +} + +function getVideosListPagination (url: string, start: number, count: number, sort?: string) { + const path = '/api/v1/videos' + + const req = request(url) + .get(path) + .query({ start: start }) + .query({ count: count }) + + if (sort) req.query({ sort }) + + return req.set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getVideosListSort (url: string, sort: string) { + const path = '/api/v1/videos' + + return request(url) + .get(path) + .query({ sort: sort }) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function getVideosWithFilters (url: string, query: { tagsAllOf: string[], categoryOneOf: number[] | number }) { + const path = '/api/v1/videos' + + return request(url) + .get(path) + .query(query) + .set('Accept', 'application/json') + .expect(200) + .expect('Content-Type', /json/) +} + +function removeVideo (url: string, token: string, id: number | string, expectedStatus = 204) { + const path = '/api/v1/videos' + + return request(url) + .delete(path + '/' + id) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + token) + .expect(expectedStatus) +} + +async function checkVideoFilesWereRemoved ( + videoUUID: string, + serverNumber: number, + directories = [ 'videos', 'thumbnails', 'torrents', 'previews', 'captions' ] +) { + const testDirectory = 'test' + serverNumber + + for (const directory of directories) { + const directoryPath = join(root(), testDirectory, directory) + + const directoryExists = existsSync(directoryPath) + expect(directoryExists).to.be.true + + const files = await readdir(directoryPath) + for (const file of files) { + expect(file).to.not.contain(videoUUID) + } + } +} + +async function uploadVideo (url: string, accessToken: string, videoAttributesArg: VideoAttributes, specialStatus = 200) { + const path = '/api/v1/videos/upload' + let defaultChannelId = '1' + + try { + const res = await getMyUserInformation(url, accessToken) + defaultChannelId = res.body.videoChannels[0].id + } catch (e) { /* empty */ } + + // Override default attributes + const attributes = Object.assign({ + name: 'my super video', + category: 5, + licence: 4, + language: 'zh', + channelId: defaultChannelId, + nsfw: true, + waitTranscoding: false, + description: 'my super description', + support: 'my super support text', + tags: [ 'tag' ], + privacy: VideoPrivacy.PUBLIC, + commentsEnabled: true, + fixture: 'video_short.webm' + }, videoAttributesArg) + + const req = request(url) + .post(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .field('name', attributes.name) + .field('nsfw', JSON.stringify(attributes.nsfw)) + .field('commentsEnabled', JSON.stringify(attributes.commentsEnabled)) + .field('waitTranscoding', JSON.stringify(attributes.waitTranscoding)) + .field('privacy', attributes.privacy.toString()) + .field('channelId', attributes.channelId) + + if (attributes.description !== undefined) { + req.field('description', attributes.description) + } + if (attributes.language !== undefined) { + req.field('language', attributes.language.toString()) + } + if (attributes.category !== undefined) { + req.field('category', attributes.category.toString()) + } + if (attributes.licence !== undefined) { + req.field('licence', attributes.licence.toString()) + } + + for (let i = 0; i < attributes.tags.length; i++) { + req.field('tags[' + i + ']', attributes.tags[i]) + } + + if (attributes.thumbnailfile !== undefined) { + req.attach('thumbnailfile', buildAbsoluteFixturePath(attributes.thumbnailfile)) + } + if (attributes.previewfile !== undefined) { + req.attach('previewfile', buildAbsoluteFixturePath(attributes.previewfile)) + } + + if (attributes.scheduleUpdate) { + req.field('scheduleUpdate[updateAt]', attributes.scheduleUpdate.updateAt) + + if (attributes.scheduleUpdate.privacy) { + req.field('scheduleUpdate[privacy]', attributes.scheduleUpdate.privacy) + } + } + + return req.attach('videofile', buildAbsoluteFixturePath(attributes.fixture)) + .expect(specialStatus) +} + +function updateVideo (url: string, accessToken: string, id: number | string, attributes: VideoAttributes, statusCodeExpected = 204) { + const path = '/api/v1/videos/' + id + const body = {} + + if (attributes.name) body['name'] = attributes.name + if (attributes.category) body['category'] = attributes.category + if (attributes.licence) body['licence'] = attributes.licence + if (attributes.language) body['language'] = attributes.language + if (attributes.nsfw !== undefined) body['nsfw'] = JSON.stringify(attributes.nsfw) + if (attributes.commentsEnabled !== undefined) body['commentsEnabled'] = JSON.stringify(attributes.commentsEnabled) + if (attributes.description) body['description'] = attributes.description + if (attributes.tags) body['tags'] = attributes.tags + if (attributes.privacy) body['privacy'] = attributes.privacy + if (attributes.channelId) body['channelId'] = attributes.channelId + if (attributes.scheduleUpdate) body['scheduleUpdate'] = attributes.scheduleUpdate + + // Upload request + if (attributes.thumbnailfile || attributes.previewfile) { + const attaches: any = {} + if (attributes.thumbnailfile) attaches.thumbnailfile = attributes.thumbnailfile + if (attributes.previewfile) attaches.previewfile = attributes.previewfile + + return makeUploadRequest({ + url, + method: 'PUT', + path, + token: accessToken, + fields: body, + attaches, + statusCodeExpected + }) + } + + return makePutBodyRequest({ + url, + path, + fields: body, + token: accessToken, + statusCodeExpected + }) +} + +function rateVideo (url: string, accessToken: string, id: number, rating: string, specialStatus = 204) { + const path = '/api/v1/videos/' + id + '/rate' + + return request(url) + .put(path) + .set('Accept', 'application/json') + .set('Authorization', 'Bearer ' + accessToken) + .send({ rating }) + .expect(specialStatus) +} + +function parseTorrentVideo (server: ServerInfo, videoUUID: string, resolution: number) { + return new Promise((res, rej) => { + const torrentName = videoUUID + '-' + resolution + '.torrent' + const torrentPath = join(__dirname, '..', '..', '..', '..', 'test' + server.serverNumber, 'torrents', torrentName) + readFile(torrentPath, (err, data) => { + if (err) return rej(err) + + return res(parseTorrent(data)) + }) + }) +} + +async function completeVideoCheck ( + url: string, + video: any, + attributes: { + name: string + category: number + licence: number + language: string + nsfw: boolean + commentsEnabled: boolean + description: string + publishedAt?: string + support: string + account: { + name: string + host: string + } + isLocal: boolean + tags: string[] + privacy: number + likes?: number + dislikes?: number + duration: number + channel: { + displayName: string + name: string + description + isLocal: boolean + } + fixture: string + files: { + resolution: number + size: number + }[], + thumbnailfile?: string + previewfile?: string + } +) { + if (!attributes.likes) attributes.likes = 0 + if (!attributes.dislikes) attributes.dislikes = 0 + + expect(video.name).to.equal(attributes.name) + expect(video.category.id).to.equal(attributes.category) + expect(video.category.label).to.equal(attributes.category !== null ? VIDEO_CATEGORIES[attributes.category] : 'Misc') + expect(video.licence.id).to.equal(attributes.licence) + expect(video.licence.label).to.equal(attributes.licence !== null ? VIDEO_LICENCES[attributes.licence] : 'Unknown') + expect(video.language.id).to.equal(attributes.language) + expect(video.language.label).to.equal(attributes.language !== null ? VIDEO_LANGUAGES[attributes.language] : 'Unknown') + expect(video.privacy.id).to.deep.equal(attributes.privacy) + expect(video.privacy.label).to.deep.equal(VIDEO_PRIVACIES[attributes.privacy]) + expect(video.nsfw).to.equal(attributes.nsfw) + expect(video.description).to.equal(attributes.description) + expect(video.account.id).to.be.a('number') + expect(video.account.uuid).to.be.a('string') + expect(video.account.host).to.equal(attributes.account.host) + expect(video.account.name).to.equal(attributes.account.name) + expect(video.channel.displayName).to.equal(attributes.channel.displayName) + expect(video.channel.name).to.equal(attributes.channel.name) + expect(video.likes).to.equal(attributes.likes) + expect(video.dislikes).to.equal(attributes.dislikes) + expect(video.isLocal).to.equal(attributes.isLocal) + expect(video.duration).to.equal(attributes.duration) + expect(dateIsValid(video.createdAt)).to.be.true + expect(dateIsValid(video.publishedAt)).to.be.true + expect(dateIsValid(video.updatedAt)).to.be.true + + if (attributes.publishedAt) { + expect(video.publishedAt).to.equal(attributes.publishedAt) + } + + const res = await getVideo(url, video.uuid) + const videoDetails: VideoDetails = res.body + + expect(videoDetails.files).to.have.lengthOf(attributes.files.length) + expect(videoDetails.tags).to.deep.equal(attributes.tags) + expect(videoDetails.account.name).to.equal(attributes.account.name) + expect(videoDetails.account.host).to.equal(attributes.account.host) + expect(video.channel.displayName).to.equal(attributes.channel.displayName) + expect(video.channel.name).to.equal(attributes.channel.name) + expect(videoDetails.channel.host).to.equal(attributes.account.host) + expect(videoDetails.channel.isLocal).to.equal(attributes.channel.isLocal) + expect(dateIsValid(videoDetails.channel.createdAt.toString())).to.be.true + expect(dateIsValid(videoDetails.channel.updatedAt.toString())).to.be.true + expect(videoDetails.commentsEnabled).to.equal(attributes.commentsEnabled) + + for (const attributeFile of attributes.files) { + const file = videoDetails.files.find(f => f.resolution.id === attributeFile.resolution) + expect(file).not.to.be.undefined + + let extension = extname(attributes.fixture) + // Transcoding enabled on server 2, extension will always be .mp4 + if (attributes.account.host === 'localhost:9002') extension = '.mp4' + + const magnetUri = file.magnetUri + expect(file.magnetUri).to.have.lengthOf.above(2) + expect(file.torrentUrl).to.equal(`http://${attributes.account.host}/static/torrents/${videoDetails.uuid}-${file.resolution.id}.torrent`) + expect(file.fileUrl).to.equal(`http://${attributes.account.host}/static/webseed/${videoDetails.uuid}-${file.resolution.id}${extension}`) + expect(file.resolution.id).to.equal(attributeFile.resolution) + expect(file.resolution.label).to.equal(attributeFile.resolution + 'p') + + const minSize = attributeFile.size - ((10 * attributeFile.size) / 100) + const maxSize = attributeFile.size + ((10 * attributeFile.size) / 100) + expect(file.size, + 'File size for resolution ' + file.resolution.label + ' outside confidence interval (' + minSize + '> size <' + maxSize + ')') + .to.be.above(minSize).and.below(maxSize) + + { + await testImage(url, attributes.thumbnailfile || attributes.fixture, videoDetails.thumbnailPath) + } + + if (attributes.previewfile) { + await testImage(url, attributes.previewfile, videoDetails.previewPath) + } + + const torrent = await webtorrentAdd(magnetUri, true) + expect(torrent.files).to.be.an('array') + expect(torrent.files.length).to.equal(1) + expect(torrent.files[0].path).to.exist.and.to.not.equal('') + } +} + +// --------------------------------------------------------------------------- + +export { + getVideoDescription, + getVideoCategories, + getVideoLicences, + getVideoPrivacies, + getVideoLanguages, + getMyVideos, + getAccountVideos, + getVideoChannelVideos, + getVideo, + getVideoWithToken, + getVideosList, + getVideosListPagination, + getVideosListSort, + removeVideo, + getVideosListWithToken, + uploadVideo, + getVideosWithFilters, + updateVideo, + rateVideo, + viewVideo, + parseTorrentVideo, + getLocalVideos, + completeVideoCheck, + checkVideoFilesWereRemoved +}