PeerTube/client/angular/videos/videos.service.ts

73 lines
2.4 KiB
TypeScript
Raw Normal View History

2016-05-13 12:18:37 +00:00
import { Injectable } from '@angular/core';
2016-05-22 08:43:06 +00:00
import { Http, Response, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Rx';
2016-03-14 12:50:19 +00:00
2016-05-22 08:43:06 +00:00
import { Pagination } from './pagination';
import { Video } from './video';
import { AuthService } from '../users/services/auth.service';
import { Search } from '../app/search';
2016-03-14 12:50:19 +00:00
@Injectable()
export class VideosService {
private _baseVideoUrl = '/api/v1/videos/';
constructor (private http: Http, private _authService: AuthService) {}
2016-03-14 12:50:19 +00:00
2016-05-22 08:43:06 +00:00
getVideos(pagination: Pagination) {
const params = this.createPaginationParams(pagination);
return this.http.get(this._baseVideoUrl, { search: params })
.map(res => res.json())
.map(this.extractVideos)
2016-03-14 12:50:19 +00:00
.catch(this.handleError);
}
getVideo(id: string) {
return this.http.get(this._baseVideoUrl + id)
.map(res => <Video> res.json())
.catch(this.handleError);
}
removeVideo(id: string) {
const options = this._authService.getAuthRequestOptions();
return this.http.delete(this._baseVideoUrl + id, options)
.map(res => <number> res.status)
.catch(this.handleError);
2016-03-14 12:50:19 +00:00
}
searchVideos(search: Search, pagination: Pagination) {
const params = this.createPaginationParams(pagination);
if (search.field) params.set('field', search.field);
return this.http.get(this._baseVideoUrl + 'search/' + encodeURIComponent(search.value), { search: params })
.map(res => res.json())
.map(this.extractVideos)
2016-03-14 21:16:43 +00:00
.catch(this.handleError);
}
2016-05-22 08:43:06 +00:00
private extractVideos (body: any) {
const videos_json = body.data;
const totalVideos = body.total;
const videos = [];
2016-05-22 08:43:06 +00:00
for (const video_json of videos_json) {
videos.push(new Video(video_json));
}
2016-05-22 08:43:06 +00:00
return { videos, totalVideos };
}
2016-03-14 12:50:19 +00:00
private handleError (error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
2016-05-22 08:43:06 +00:00
private createPaginationParams(pagination: Pagination) {
const params = new URLSearchParams();
const start: number = (pagination.currentPage - 1) * pagination.itemsPerPage;
const count: number = pagination.itemsPerPage;
params.set('start', start.toString());
params.set('count', count.toString());
return params;
}
2016-03-14 12:50:19 +00:00
}