]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - client/src/app/videos/shared/video.service.ts
b4396f76794abe1eebc2265e66959f3f6ce9f08d
[github/Chocobozzz/PeerTube.git] / client / src / app / videos / shared / video.service.ts
1 import { Injectable } from '@angular/core';
2 import { Http, Response, URLSearchParams } from '@angular/http';
3 import { Observable } from 'rxjs/Observable';
4
5 import { Pagination } from './pagination.model';
6 import { Search } from '../../shared';
7 import { SortField } from './sort-field.type';
8 import { AuthHttp, AuthService } from '../../shared';
9 import { Video } from './video.model';
10
11 @Injectable()
12 export class VideoService {
13 private static BASE_VIDEO_URL = '/api/v1/videos/';
14
15 constructor(
16 private authService: AuthService,
17 private authHttp: AuthHttp,
18 private http: Http
19 ) {}
20
21 getVideo(id: string) {
22 return this.http.get(VideoService.BASE_VIDEO_URL + id)
23 .map(res => <Video> res.json())
24 .catch(this.handleError);
25 }
26
27 getVideos(pagination: Pagination, sort: SortField) {
28 const params = this.createPaginationParams(pagination);
29
30 if (sort) params.set('sort', sort);
31
32 return this.http.get(VideoService.BASE_VIDEO_URL, { search: params })
33 .map(res => res.json())
34 .map(this.extractVideos)
35 .catch(this.handleError);
36 }
37
38 removeVideo(id: string) {
39 return this.authHttp.delete(VideoService.BASE_VIDEO_URL + id)
40 .map(res => <number> res.status)
41 .catch(this.handleError);
42 }
43
44 searchVideos(search: Search, pagination: Pagination, sort: SortField) {
45 const params = this.createPaginationParams(pagination);
46
47 if (search.field) params.set('field', search.field);
48 if (sort) params.set('sort', sort);
49
50 return this.http.get(VideoService.BASE_VIDEO_URL + 'search/' + encodeURIComponent(search.value), { search: params })
51 .map(res => res.json())
52 .map(this.extractVideos)
53 .catch(this.handleError);
54 }
55
56 private createPaginationParams(pagination: Pagination) {
57 const params = new URLSearchParams();
58 const start: number = (pagination.currentPage - 1) * pagination.itemsPerPage;
59 const count: number = pagination.itemsPerPage;
60
61 params.set('start', start.toString());
62 params.set('count', count.toString());
63
64 return params;
65 }
66
67 private extractVideos(body: any) {
68 const videos_json = body.data;
69 const totalVideos = body.total;
70 const videos = [];
71 for (const video_json of videos_json) {
72 videos.push(new Video(video_json));
73 }
74
75 return { videos, totalVideos };
76 }
77
78 private handleError(error: Response) {
79 console.error(error);
80 return Observable.throw(error.json().error || 'Server error');
81 }
82 }