initial commit

This commit is contained in:
2023-10-15 20:02:52 +02:00
commit bd7452d198
47 changed files with 12202 additions and 0 deletions

View File

@ -0,0 +1,22 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AppController } from './app.controller';
import { AppService } from './app.service';
describe('AppController', () => {
let appController: AppController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [AppController],
providers: [AppService],
}).compile();
appController = app.get<AppController>(AppController);
});
describe('root', () => {
it('should return "Hello World!"', () => {
expect(appController.getHello()).toBe('Hello World!');
});
});
});

12
src/app.controller.ts Normal file
View File

@ -0,0 +1,12 @@
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get()
getHello(): string {
return this.appService.getHello();
}
}

44
src/app.module.ts Normal file
View File

@ -0,0 +1,44 @@
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { VideosController } from './videos/Controller/videos.controller';
import { CryptoService } from './crypto/Service/crypto.service';
import { VideosService } from './videos/Service/videos.service';
import { VideosModule } from './videos/module/videos.module';
import { CommentsService } from './comments/service/comments.service';
import { CommentsModule } from './comments/module/comments.module';
import { CommentsController } from './comments/controller/comments.controller';
import { Comments } from './comments/Entity/comments.entity';
import { UserController } from './users/controller/user.controller';
import { UserModule } from './users/module/user.module';
import { UserService } from './users/service/user.service';
import { User } from './users/entity/user.entity';
import { WatchhistoryService } from './watchhistory/service/watchhistory.service';
import { WatchhistoryEntity } from './watchhistory/entities/watchhistory.entity';
import { WatchhistoryModule } from './watchhistory/module/watchhistory.module';
import { Videos } from './videos/entity/videos.entity';
import { RoutAuthenticatorService } from './rout-authenticator/rout-authenticator.service';
import { TypeOrmModule } from '@nestjs/typeorm';
@Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: '',
database: 'proxima',
entities: [Videos, Comments, User, WatchhistoryEntity],
synchronize: true,
}),
VideosModule,
CommentsModule,
UserModule,
WatchhistoryModule
],
controllers: [AppController, VideosController, CommentsController, UserController],
providers: [AppService, CryptoService, VideosService, CommentsService, UserService, WatchhistoryService, RoutAuthenticatorService],
})
export class AppModule {}

8
src/app.service.ts Normal file
View File

@ -0,0 +1,8 @@
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getHello(): string {
return 'Hello World!';
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CommentsController } from './comments.controller';
describe('CommentsController', () => {
let controller: CommentsController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [CommentsController],
}).compile();
controller = module.get<CommentsController>(CommentsController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,48 @@
import { Controller, Get, Request, Post, Query, Body } from '@nestjs/common';
import { UserService } from 'src/users/service/user.service';
import { Comments } from '../Entity/comments.entity';
import { CommentsService } from '../service/comments.service';
@Controller('comments')
export class CommentsController {
constructor(
private service:CommentsService,
private userService:UserService){}
@Post('comment')
async createComment(@Body() comment:Comments, @Request() req){
try {
console.log(comment);
let date = new Date();
comment = comment['body'];
comment["commented_on"] = "" + date.getDate();
if(comment["author"] == null) return {success:false, error: "no_author_given"};
await this.service.createComment(comment);
return {success:true, code: 200};
} catch (error) {
console.log(error);
return {success:false, code:"not_commented"}
}
}
@Get('comments')
async getComments(@Query() query, @Request() req){
let comments = await this.service.getComments(JSON.parse(req.query['video'])['video'])
let r = [];
for(let i = 0; i<comments.length; i++) {
let u = await this.userService.getUserById(comments[i]['author']);
let object = {"author": u[0]['username'],"comment":comments[i]['comment']}
r.push(object);
}
return r;
}
@Get('comments/limit')
async getCommentsByLimit(@Body() body, @Request() req){
console.log(body)
//return this.service.getCommentsLimited();
}
}

View File

@ -0,0 +1,7 @@
import { Comment } from './comments.entity';
describe('CommentsEntity', () => {
it('should be defined', () => {
expect(new Comment()).toBeDefined();
});
});

View File

@ -0,0 +1,25 @@
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class Comments {
@PrimaryGeneratedColumn()
com_id: number;
@Column({nullable:false})
author: number;
@Column({nullable:false})
comment: string;
@Column({default: 0})
video: string;
@Column({default:0})
profile_id:number;
@Column({nullable:false})
vid_id: number;
@Column({default: Date.now().toLocaleString()})
commented_on: string;
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { CommentsController } from '../controller/comments.controller';
import { CommentsService } from '../service/comments.service';
import { Comments } from '../Entity/comments.entity';
import { UserService } from 'src/users/service/user.service';
import { UserModule } from 'src/users/module/user.module';
@Module({
imports: [TypeOrmModule.forFeature([Comments]),UserModule],
providers: [CommentsService,UserService],
controllers: [CommentsController],
exports: [TypeOrmModule]
})
export class CommentsModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CommentsService } from './comments.service';
describe('CommentsService', () => {
let service: CommentsService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CommentsService],
}).compile();
service = module.get<CommentsService>(CommentsService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,67 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comments } from '../Entity/comments.entity';
@Injectable()
export class CommentsService {
constructor(@InjectRepository(Comments)
private commentRepository:Repository<Comments>){}
/**
* creates comment from given data
* @param comments received data from comment
*/
async createComment(comments:Comments){
console.log("comments creation call");
try {
this.commentRepository.save(comments);
} catch (error) {
console.log(error);
}
}
/**
* gets all comments from video
* @param _video the video to receive
* @returns
*/
async getComments(_video:number):Promise<Comments[]>{
// TODO get data from datbase
// CURRENT ONGOIN ISSUE: NOT ALL DATA PRESENT
return await this.commentRepository.find({
select:["author", "comment"],
where: [{"vid_id":_video}],
});
}
/**
* gets limited ammount of comments from video
* @param _limit limts how many comments can be received
* @param _video the video to receive comments from
* @returns collection of comments
*/
async getCommentsLimited(_limit:number, _video:number){
return await this.commentRepository.find({
select:["author", "comment"],
where: [{"vid_id":_video}],
take: _limit
})
}
/**
* updates given comment
* @param comments the received comment to change
*/
async updateComment(comments:Comments){
this.commentRepository.save(comments);
}
/**
* deletes a comment
* @param comments comment to delete
*/
async deleteComment(comments:Comments){
await this.commentRepository.delete(comments)
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CryptoService } from './crypto.service';
describe('CryptoService', () => {
let service: CryptoService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [CryptoService],
}).compile();
service = module.get<CryptoService>(CryptoService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,60 @@
import { Injectable } from '@nestjs/common';
import * as CryptoJS from 'crypto-js';
import { Buffer } from 'buffer';
@Injectable()
export class CryptoService {
private static secretKey = "";
static makeid(length:number):string {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); }
return result;
}
static setKey(k:string) { this.secretKey = k; }
//The set method is use for encrypt the value.
static encrypt(data:string){
var key = CryptoJS.enc.Utf8.parse(this.secretKey);
var iv = CryptoJS.enc.Utf8.parse(this.makeid(16)); // TODO: Randomize IV to reenhance security
// console.log("Key: " + key);
console.log("Initial Vector: " + iv);
var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(data.toString()), key,
{
keySize: 128 / 8,
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
let out = {
"content": encrypted.toString(),
"iv": iv
};
// Instead of sending only the encrypted string, send an object with iv and encrypted data
return out;
}
//The get method is use for decrypt the value.
static decrypt(data:any){
console.log("Initial Vector: " + data['iv']);
var key = CryptoJS.enc.Utf8.parse(this.secretKey);
var decrypted = CryptoJS.AES.decrypt(data['content'], key, {
keySize: 128 / 8,
iv: data['iv'],
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
}
}

24
src/main.ts Normal file
View File

@ -0,0 +1,24 @@
import { NestFactory } from '@nestjs/core';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const fs = require('fs');
// const keyFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.key.pem');
// const certFile = fs.readFileSync(__dirname + '/../ssl/mydomain.com.crt.pem');
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
logger: console,
// httpsOptions: {
// key: keyFile,
// cert: certFile,
// },
cors: true
});
app.useStaticAssets(join(__dirname, '..', 'uploads'), {
prefix: '/public/'
});
await app.listen(3000);
}
bootstrap();

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { RoutAuthenticatorService } from './rout-authenticator.service';
describe('RoutAuthenticatorService', () => {
let service: RoutAuthenticatorService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [RoutAuthenticatorService],
}).compile();
service = module.get<RoutAuthenticatorService>(RoutAuthenticatorService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,49 @@
import { Injectable } from '@nestjs/common';
import { UserService } from 'src/users/service/user.service';
@Injectable()
export class RoutAuthenticatorService {
constructor(private userService: UserService){}
/**
* checks headers against either allowed or disallowed values
* @param header the header object from the request
* @returns true if allowed and false if disallowed
*/
async checkHeader(header:object): Promise<object> {
// Failsafe Check Validation for Header
try {
// Fetch userid Header
if(header["userid"] != null) {
if(header["platform"] != null) {
let user = await this.userService.getUserById(header["userid"]);
let platform = JSON.parse(header["platform"]);
return {valid: true, conditions: {
user: {
exists: user != null,
id: user["id"] == header["userid"],
token: header["usertoken"] == "test"
},
platform: {
name: platform["name"] == "test",
hash: platform["hash"] == "test"
},
origin: {
web: header["origin"] == "http://localhost:4200",
electrom: header["origin"] == "electron_shit"
}
}
}
} else {
return {valid:false};
}
} else {
return {valid:false};
}
} catch (error) {
console.log(error);
return {valid:false};
}
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
describe('UserController', () => {
let controller: UserController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [UserController],
}).compile();
controller = module.get<UserController>(UserController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,70 @@
import { Body, Controller, Get, Post, Request } from '@nestjs/common';
import { CryptoService } from 'src/crypto/Service/crypto.service';
import { RoutAuthenticatorService } from 'src/rout-authenticator/rout-authenticator.service';
import { WatchhistoryService } from 'src/watchhistory/service/watchhistory.service';
import { User } from '../entity/user.entity';
import { UserService } from '../service/user.service';
@Controller('user')
export class UserController {
constructor(
private service:UserService,
private watch:WatchhistoryService,
private routeAuth: RoutAuthenticatorService
){}
@Post('register')
async registerUser(@Body() user){
const uNameRes = this.service.getUserbyName(user.username);
const emailRes = this.service.getUser(user.email);
console.log(await uNameRes.valueOf.length);
if(uNameRes.valueOf.length == 0 || emailRes.valueOf.length == 0 ) {
user["profile_id"] = Math.floor(Math.random() * 99999);
this.service.createUser(user);
return {success:true, code:200};
} else {
return {success:false, code:"duplicating_user_or_email"};
}
}
@Get('settings')
async getSettings(@Request() req){
console.log(req.query);
let json = req.query;
console.log(json);
let user = JSON.parse(json["user"])["email"];
console.log(user);
return await this.service.getsettings(user);
}
@Get('login')
async loginUser(@Request() req){
console.log(req.query);
// get password hash from request body
// get password hash from database
// return user data and success code when logged in and error when not
const user = JSON.parse(req.query['user']);
console.log(user);
if(await this.service.verifyPassword(user.email, decodeURIComponent(user.password))) {
let u = await this.service.getUser(user.email);
console.log(u[0]['id']);
//this.watch.getHistory(u[0]['id']);
return {success:true, payload: {
username: u[0]['username'],
email: u[0]['email'],
id: u[0]['id']
}};
} else {
return {success:false, code:"invalid_login"};
}
}
@Post('update')
async updateUser(@Body() user:User){
this.service.updateUser(user);
}
}

View File

@ -0,0 +1,7 @@
import { UserEntity } from './user.entity';
describe('UserEntity', () => {
it('should be defined', () => {
expect(new UserEntity()).toBeDefined();
});
});

View File

@ -0,0 +1,43 @@
import { Column, Entity, PrimaryColumn, PrimaryGeneratedColumn } from "typeorm";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id:number;
@Column({nullable:false})
username: string;
@Column({nullable:false})
password: string;
@Column({nullable:true})
name: string;
@Column({nullable:false, unique: true})
email: string;
@Column({nullable: false, default: 0})
profile_likes: number;
@Column({nullable:true, default: null})
profile_pic: string;
@Column({nullable:false})
profile_id: number;
@Column({nullable:true})
profile_bio: string ;
@Column({default: false})
profile_public: boolean;
@Column({default: false})
public_stats: boolean;
@Column({default: false})
public_watchhistory: boolean;
@Column({default: false})
sub_newsletter: boolean;
}

View File

@ -0,0 +1,16 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { RoutAuthenticatorService } from 'src/rout-authenticator/rout-authenticator.service';
import { WatchhistoryModule } from 'src/watchhistory/module/watchhistory.module';
import { WatchhistoryService } from 'src/watchhistory/service/watchhistory.service';
import { UserController } from '../controller/user.controller';
import { User } from '../entity/user.entity';
import { UserService } from '../service/user.service';
@Module({
imports:[TypeOrmModule.forFeature([User]), WatchhistoryModule],
providers: [UserService, WatchhistoryService,RoutAuthenticatorService],
controllers: [UserController],
exports: [TypeOrmModule]
})
export class UserModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { UserService } from './user.service';
describe('User.ServiceService', () => {
let service: UserService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [UserService],
}).compile();
service = module.get<UserService>(UserService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,64 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entity/user.entity';
@Injectable()
export class UserService {
constructor(@InjectRepository(User)
private userRepository: Repository<User>){}
async createUser(user:User){
await this.userRepository.save(user);
}
async getUser(_email:string):Promise<object>{
return await this.userRepository.find({
select:["id", "email","name","profile_likes","profile_pic","username"],
where:[{"email":_email}]
});
}
async getUserById(_id:number):Promise<object>{
return await this.userRepository.find({
select:["id", "email","name","profile_likes","profile_pic","username"],
where:[{"id":_id}]
});
}
async getUserbyName(_username:string):Promise<Object>{
return await this.userRepository.find({
select:["id", "email","name","profile_likes","profile_pic","username"],
where:[{"username":_username}]
});
}
async getsettings(_email:string):Promise<object>{
return await this.userRepository.find({
select:["id", "email","name","profile_bio","profile_pic","username"],
where:[{"email":_email}]
})
}
async updateUser(user:User){
this.userRepository.save(user);
}
async deleteUser(user:User){
this.userRepository.delete(user);
}
async verifyPassword(_email:string, _password:string):Promise<boolean> {
console.log("email: " + _email);
console.log("password: " + _password);
const password = await this.userRepository.find({
select:["password"],
where:[{"email":_email}]
});
console.log(password[0]['password']);
console.log(password[0]['password'] == _password);
return password[0]['password'] == _password;
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { VideosController } from './videos.controller';
describe('VideosController', () => {
let controller: VideosController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [VideosController],
}).compile();
controller = module.get<VideosController>(VideosController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});

View File

@ -0,0 +1,181 @@
import { Controller, Get, Request, Post, Query, UploadedFile, UseInterceptors, Delete, Body, StreamableFile, Response, Req, Param, Res } from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { VideosService } from '../Service/videos.service';
import * as fs from 'node:fs';
import { UserService } from 'src/users/service/user.service';
@Controller('videos')
export class VideosController {
constructor(
private service: VideosService,
private user: UserService) {}
@Get('videos')
async getVideos(@Query() query, @Request() req) {
// TODO Pull data from database
// TODO: Verify data against proper permissions
// - Uses headers
// - checks params
console.log(query);
console.log(req.headers);
// Assuming verification succeeded
// Catch video data from request
// - requires constructed videos request string
let order = {};
order[query.sort]=query.order;
//console.log(this.service.getVideosByRequest(query.type, query.limit, order));
return {type: "reply", videos: await this.service.getVideos()}
//CryptoService.encrypt(JSON.stringify({type: "reply", videos: await this.service.getVideos()})); // returning = replying
}
@Get('channel')
async getVideosByChannel(@Query() query, @Request() req){
// TODO Pull data from database
// TODO: Verify data against proper permissions
// - Uses headers
// - checks params
console.log(JSON.parse(query['creator']).query);
console.log(req.headers);
// Assuming verification succeeded
// Catch video data from request
// - requires constructed videos request string
//console.log(this.service.getVideosByRequest(query.type, query.limit, order));
return {type: "reply", videos: await this.service.getVideoByChannel(JSON.parse(query['creator']).query)}
//CryptoService.encrypt(JSON.stringify({type: "reply", videos: await this.service.getVideos()})); // returning = replying
}
@Get('recommends')
async getRecommendation(@Request() req) {
return await this.service.getVideosByRequest("nothing",4,{vid_id:"DESC"});
}
@Get('stats')
async fetchStats(@Request() req) {
let final = {};
let stats = await this.service.getVideoStats(JSON.parse(req.query['stats'])['video']);
return stats;
}
@Get('search')
async searchInDB(@Request() req){
console.log(req.query);
console.log(await this.service.searchVideo(JSON.parse(req.query["query"])["query"]));
return await this.service.searchVideo(JSON.parse(req.query["query"])["query"]);
}
@Get('video/:id')
async getVideo(@Res() res, @Request() req, @Param('id') id) {
// TODO Pull data from database
// TODO: Verify data against proper permissions
// - fix crashes when wrong id is given
// - Uses headers
// - checks params
try {
const range = req.headers.range;
//console.log(range);
if (!range) {
res.status(400).send("Requires Range header");
}
let fetched = await this.service.getVideo(JSON.parse(id));
const videoPath = "./uploads/" + fetched[0]['file'];
if(!fs.existsSync(videoPath)) {
return {"success":"false","error":"video_not_exists"}
}
const videoSize = fs.statSync(videoPath).size;
const CHUNK_SIZE = 10 ** 4; // 1MB
const start = Number(range.replace(/\D/g, ""));
//console.log(start);
const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
const contentLength = end - start + 1;
const responseHeader = {
"Content-Range": `bytes ${start}-${end}/${videoSize}`,
"Accept-Ranges": "bytes",
"Content-Length": contentLength,
"Content-Type": "video/mp4",
};
res.writeHead(206, responseHeader);
const videoStream = fs.createReadStream(videoPath, { start, end });
videoStream.pipe(res);
} catch (error) {
console.log(error);
}
}
/**
* updloads files
* @param file the file
* @param query query gotten from request
* @returns reply object
*/
@UseInterceptors(FileInterceptor('file', {
dest: "./uploads"
}))
@Post('upload')
async postVideos(@UploadedFile() file: Express.Multer.File, @Request() req, @Body() video) {
// TODO: get file from request and insert it after type checking into storage
//console.log(video);
console.log(file);
let fileName = file.filename + ".mp4";
/**
* Structural Change
* uploads
* - videos (the now file id)
* - file id.mp4
* - file id.png
*/
// TODO: Compress video
fs.rename(file.path, './uploads/' + fileName, (err) => {if (err) throw err;});
// TODO: Verify data against proper permissions
// - Uses headers
// - checks params
console.log(req.headers);
video.file = fileName; // fixes undefined file issue
video.click = 0;
video.likes = 0;
video.dislikes = 0;
this.service.createVideo(video);
// Replyies to the requester that the request was successfull
// return {type: "reply", code: "succes"};
}
/**
* updloads files
* @param file the file
* @returns reply object
*/
@Delete('video')
async deleteVideo(@Request() req){
// TODO: Verify data against proper permissions
// - Uses headers
// - checks params
console.log(req.query);
console.log(req.headers);
this.service.deleteVideo(req.query.id);
// Replyies to the requester that the request was successfull
return {type: "reply", code: "succes"};
}
}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { VideosService } from './videos.service';
describe('VideosService', () => {
let service: VideosService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [VideosService],
}).compile();
service = module.get<VideosService>(VideosService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,194 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import * as fs from 'fs';
import { UserService } from 'src/users/service/user.service';
import { Like, Repository } from 'typeorm';
import { Videos } from '../entity/videos.entity';
@Injectable()
export class VideosService {
constructor(@InjectRepository(Videos)
private videoRepository: Repository<Videos>, private user: UserService){}
/**
* gets videos with the requested parameters
* @param video the requested video
* @returns array with video resolvables
*/
async getVideos(): Promise<Videos[]> | null{
return await this.videoRepository.find({
select: ["vid_id","creator","likes","dislikes","file","title","premium","creator"],
});
}
/**
* gets videos with the requested parameters
* @param video the requested video
* @returns array with video resolvables
*/
async getVideosByChannel(creator:number): Promise<Videos[]> | null{
return await this.videoRepository.find({
select: ["vid_id","creator","likes","dislikes","file","title","premium"],
where: [{"creator":creator}]
});
}
/**
* gets videos with the requested parameters
* @param video the requested video
* @param limit limiting the amount of returned video objects
* @returns array with video resolvables
*/
async getVideosLimited(limit:number):Promise<Videos[]> | null {
return await this.videoRepository.find({
select: ["vid_id","creator","likes","dislikes","file","title"],
take: limit
});
}
/**
* gets videos specified to properties given
* @param _type the type to specify videos for
* @param _order object specifying how to order the entries
* @param _limit how many videos should be returned
* @returns array with video resolvables
*/
async getVideosByRequest(_type: String, _limit: number, _order: object): Promise<Videos[]> | null {
try {
return await this.videoRepository.find({
select: ["vid_id","title","premium"],
order: _order,
take: _limit
});
} catch (error) {
console.log("error video not found");
console.log(error);
return null;
}
}
/**
* gets a video specified by its id
* @param _id the requested video id
* @returns object of videos
*/
async getVideo(_id: number):Promise<Videos[]> | null {
try {
return await this.videoRepository.find({
select: ["vid_id","file","premium"],
where: [{ "vid_id": _id }]
});
} catch (error) {
console.log("error video not found");
console.log(error);
return null
}
}
/**
* retrieve videos based on channel
* @param id the creator id
* @returns the videos by channel
*/
async getVideoByChannel(id:number):Promise<Videos[]> | null {
try {
return await this.videoRepository.find({
select: ["vid_id","file","premium", "title"],
where: [{ "creator": id}]
});
} catch (error) {
console.log("error video not found");
console.log(error);
return null
}
}
/**
* fetches statistics for a video from database
* @param _id the video to fetch statistic data from
* @returns JSON or null for a video when found or not
*/
async getVideoStats(_id:number): Promise<object> | null {
try {
// gets latest state of the wanted video
let video = await this.videoRepository.find({
select: ["title", "click", "likes", "dislikes", "uploaded_on", "creator"],
where: [{ "vid_id": _id }]
});
// specifies array position
let fetch = video[0];
let user = await this.user.getUserById(video[0]['creator']);
// Updates the click value as value
fetch['click'] = video[0]["click"] += 1;
fetch['username'] = user[0].username;
fetch['creatorimage'] = user[0].profile_pic;
// updates the database
if(await this.updateVideo(_id, {click:fetch['click']})){
return video;
} else {
return null;
}
} catch (error) {
console.log(error);
return null;
}
}
/**
* inserts a video into database
* @param _video the video data
*/
async createVideo(_video: Videos) {
this.videoRepository.save(_video);
}
/**
* searches the database for a given string
* @param _query the query (part of videoname) to search by
* @returns if anything found an array of video informations
*/
async searchVideo(_query:string):Promise<Object> | null {
return await this.videoRepository.find({
select: ["vid_id", "title", "file", "premium"],
where: [{ "title": Like("%"+_query+"%")}]
});
}
/**
* updates the database according to changes object
* @param _id video by id to update
* @param changes the changes to make as json
* @returns true if working false if error
*/
async updateVideo(_id:number, _changes:object):Promise<boolean> {
try {
this.videoRepository.update(_id, _changes);
return true;
} catch (error) {
console.log(error);
return false;
}
}
/**
* deletes video specified by id
* @param _id video to delete
* @returns true if removal was successfull false if errors occured
*/
async deleteVideo(_id: number):Promise<boolean> {
try {
let video = await this.getVideo(_id);
console.log(video[0]["file"]);
await fs.unlinkSync("./uploads/" + video[0]["file"]);
await this.videoRepository.delete(_id);
return true;
} catch (error) {
console.log(error);
return false;
}
}
}

View File

@ -0,0 +1,7 @@
import { Videos } from './videos.entity';
describe('Videos', () => {
it('should be defined', () => {
expect(new Videos()).toBeDefined();
});
});

View File

@ -0,0 +1,32 @@
import { Column, Entity, PrimaryGeneratedColumn, Timestamp } from "typeorm";
@Entity()
export class Videos {
@PrimaryGeneratedColumn()
vid_id:number;
@Column({nullable:false})
file: string;
@Column({nullable:false})
title: string;
@Column({default: 0})
likes: number;
@Column({default: 0})
dislikes: string;
@Column({default: 0})
premium: boolean;
@Column({nullable:true})
uploaded_on:string;
@Column({default: 0})
click:number;
@Column({nullable:false})
creator:number;
}

View File

@ -0,0 +1,15 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from 'src/users/module/user.module';
import { UserService } from 'src/users/service/user.service';
import { VideosService } from 'src/videos/Service/videos.service';
import { VideosController } from '../Controller/videos.controller';
import { Videos } from '../entity/videos.entity';
@Module({
imports:[TypeOrmModule.forFeature([Videos]), UserModule],
providers: [VideosService, UserService],
controllers: [VideosController],
exports: [TypeOrmModule]
})
export class VideosModule {}

View File

@ -0,0 +1,7 @@
import { WatchhistoryEntity } from './watchhistory.entity';
describe('WatchhistoryEntity', () => {
it('should be defined', () => {
expect(new WatchhistoryEntity()).toBeDefined();
});
});

View File

@ -0,0 +1,10 @@
import { Column, Entity, PrimaryColumn } from "typeorm";
@Entity()
export class WatchhistoryEntity {
@PrimaryColumn()
user_id:number;
@Column()
vid_id:number;
}

View File

@ -0,0 +1,11 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { WatchhistoryEntity } from '../entities/watchhistory.entity';
import { WatchhistoryService } from '../service/watchhistory.service';
@Module({
imports:[TypeOrmModule.forFeature([WatchhistoryEntity])],
providers: [WatchhistoryService],
exports: [TypeOrmModule]
})
export class WatchhistoryModule {}

View File

@ -0,0 +1,18 @@
import { Test, TestingModule } from '@nestjs/testing';
import { WatchhistoryService } from './watchhistory.service';
describe('WatchhistoryService', () => {
let service: WatchhistoryService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [WatchhistoryService],
}).compile();
service = module.get<WatchhistoryService>(WatchhistoryService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});

View File

@ -0,0 +1,22 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { WatchhistoryEntity } from '../entities/watchhistory.entity';
@Injectable()
export class WatchhistoryService {
constructor(@InjectRepository(WatchhistoryEntity)
private watchrRepository: Repository<WatchhistoryEntity>){}
async getHistory(_user:number): Promise<Object> {
let videos = await this.watchrRepository.find({
select: ["vid_id"],
where: [{"user_id":_user}]
});
let v = await videos;
console.log(v[0]);
return null;
}
}