Alphabetical

This commit is contained in:
Chocobozzz 2016-05-27 17:49:18 +02:00
parent ccf6ed16f1
commit 4fd8aa3270
10 changed files with 140 additions and 133 deletions

View File

@ -49,12 +49,12 @@ import {
}) })
export class AppComponent { export class AppComponent {
isLoggedIn: boolean;
search_field: string = name;
choices = []; choices = [];
isLoggedIn: boolean;
constructor(private friendService: FriendService, constructor(
private authService: AuthService, private authService: AuthService,
private friendService: FriendService,
private router: Router private router: Router
) { ) {
this.isLoggedIn = this.authService.isLoggedIn(); this.isLoggedIn = this.authService.isLoggedIn();
@ -71,8 +71,8 @@ export class AppComponent {
onSearch(search: Search) { onSearch(search: Search) {
if (search.value !== '') { if (search.value !== '') {
const params = { const params = {
search: search.value, field: search.field,
field: search.field search: search.value
}; };
this.router.navigate(['VideosList', params]); this.router.navigate(['VideosList', params]);
} else { } else {

View File

@ -14,26 +14,21 @@ import { SearchField } from './search-field.type';
export class SearchComponent { export class SearchComponent {
@Output() search = new EventEmitter<Search>(); @Output() search = new EventEmitter<Search>();
searchCriterias: Search = {
field: 'name',
value: ''
};
fieldChoices = { fieldChoices = {
name: 'Name', name: 'Name',
author: 'Author', author: 'Author',
podUrl: 'Pod Url', podUrl: 'Pod Url',
magnetUri: 'Magnet Uri' magnetUri: 'Magnet Uri'
}; };
searchCriterias: Search = {
field: 'name',
value: ''
};
get choiceKeys() { get choiceKeys() {
return Object.keys(this.fieldChoices); return Object.keys(this.fieldChoices);
} }
getStringChoice(choiceKey: SearchField) {
return this.fieldChoices[choiceKey];
}
choose($event: MouseEvent, choice: SearchField) { choose($event: MouseEvent, choice: SearchField) {
$event.preventDefault(); $event.preventDefault();
$event.stopPropagation(); $event.stopPropagation();
@ -45,4 +40,7 @@ export class SearchComponent {
this.search.emit(this.searchCriterias); this.search.emit(this.searchCriterias);
} }
getStringChoice(choiceKey: SearchField) {
return this.fieldChoices[choiceKey];
}
} }

View File

@ -10,7 +10,10 @@ import { AuthService, AuthStatus, User } from '../shared/index';
}) })
export class UserLoginComponent { export class UserLoginComponent {
constructor(private authService: AuthService, private router: Router) {} constructor(
private authService: AuthService,
private router: Router
) {}
login(username: string, password: string) { login(username: string, password: string) {
this.authService.login(username, password).subscribe( this.authService.login(username, password).subscribe(

View File

@ -7,14 +7,14 @@ import { User } from './user.model';
@Injectable() @Injectable()
export class AuthService { export class AuthService {
private static BASE_LOGIN_URL = '/api/v1/users/token';
private static BASE_CLIENT_URL = '/api/v1/users/client'; private static BASE_CLIENT_URL = '/api/v1/users/client';
private static BASE_LOGIN_URL = '/api/v1/users/token';
loginChangedSource: Observable<AuthStatus>; loginChangedSource: Observable<AuthStatus>;
private loginChanged: Subject<AuthStatus>;
private clientId: string; private clientId: string;
private clientSecret: string; private clientSecret: string;
private loginChanged: Subject<AuthStatus>;
constructor(private http: Http) { constructor(private http: Http) {
this.loginChanged = new Subject<AuthStatus>(); this.loginChanged = new Subject<AuthStatus>();
@ -37,40 +37,14 @@ export class AuthService {
); );
} }
login(username: string, password: string) { getAuthRequestOptions(): RequestOptions {
let body = new URLSearchParams(); return new RequestOptions({ headers: this.getRequestHeader() });
body.set('client_id', this.clientId);
body.set('client_secret', this.clientSecret);
body.set('response_type', 'code');
body.set('grant_type', 'password');
body.set('scope', 'upload');
body.set('username', username);
body.set('password', password);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = {
headers: headers
};
return this.http.post(AuthService.BASE_LOGIN_URL, body.toString(), options)
.map(res => res.json())
.catch(this.handleError);
}
logout() {
// TODO make HTTP request
} }
getRequestHeader() { getRequestHeader() {
return new Headers({ 'Authorization': `${this.getTokenType()} ${this.getToken()}` }); return new Headers({ 'Authorization': `${this.getTokenType()} ${this.getToken()}` });
} }
getAuthRequestOptions(): RequestOptions {
return new RequestOptions({ headers: this.getRequestHeader() });
}
getToken() { getToken() {
return localStorage.getItem('access_token'); return localStorage.getItem('access_token');
} }
@ -97,6 +71,32 @@ export class AuthService {
} }
} }
login(username: string, password: string) {
let body = new URLSearchParams();
body.set('client_id', this.clientId);
body.set('client_secret', this.clientSecret);
body.set('response_type', 'code');
body.set('grant_type', 'password');
body.set('scope', 'upload');
body.set('username', username);
body.set('password', password);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = {
headers: headers
};
return this.http.post(AuthService.BASE_LOGIN_URL, body.toString(), options)
.map(res => res.json())
.catch(this.handleError);
}
logout() {
// TODO make HTTP request
}
setStatus(status: AuthStatus) { setStatus(status: AuthStatus) {
this.loginChanged.next(status); this.loginChanged.next(status);
} }

View File

@ -1,24 +1,15 @@
export class Video { export class Video {
id: string;
name: string;
description: string;
magnetUri: string;
podUrl: string;
isLocal: boolean;
thumbnailPath: string;
author: string; author: string;
createdDate: Date;
by: string; by: string;
createdDate: Date;
description: string;
duration: string; duration: string;
id: string;
private static createDurationString(duration: number) { isLocal: boolean;
const minutes = Math.floor(duration / 60); magnetUri: string;
const seconds = duration % 60; name: string;
const minutes_padding = minutes >= 10 ? '' : '0'; podUrl: string;
const seconds_padding = seconds >= 10 ? '' : '0'; thumbnailPath: string;
return minutes_padding + minutes.toString() + ':' + seconds_padding + seconds.toString();
}
private static createByString(author: string, podUrl: string) { private static createByString(author: string, podUrl: string) {
let [ host, port ] = podUrl.replace(/^https?:\/\//, '').split(':'); let [ host, port ] = podUrl.replace(/^https?:\/\//, '').split(':');
@ -32,28 +23,38 @@ export class Video {
return author + '@' + host + port; return author + '@' + host + port;
} }
private static createDurationString(duration: number) {
const minutes = Math.floor(duration / 60);
const seconds = duration % 60;
const minutes_padding = minutes >= 10 ? '' : '0';
const seconds_padding = seconds >= 10 ? '' : '0';
return minutes_padding + minutes.toString() + ':' + seconds_padding + seconds.toString();
}
constructor(hash: { constructor(hash: {
id: string,
name: string,
description: string,
magnetUri: string,
podUrl: string,
isLocal: boolean,
thumbnailPath: string,
author: string, author: string,
createdDate: string, createdDate: string,
description: string,
duration: number; duration: number;
id: string,
isLocal: boolean,
magnetUri: string,
name: string,
podUrl: string,
thumbnailPath: string
}) { }) {
this.id = hash.id;
this.name = hash.name;
this.description = hash.description;
this.magnetUri = hash.magnetUri;
this.podUrl = hash.podUrl;
this.isLocal = hash.isLocal;
this.thumbnailPath = hash.thumbnailPath;
this.author = hash.author; this.author = hash.author;
this.createdDate = new Date(hash.createdDate); this.createdDate = new Date(hash.createdDate);
this.description = hash.description;
this.duration = Video.createDurationString(hash.duration); this.duration = Video.createDurationString(hash.duration);
this.id = hash.id;
this.isLocal = hash.isLocal;
this.magnetUri = hash.magnetUri;
this.name = hash.name;
this.podUrl = hash.podUrl;
this.thumbnailPath = hash.thumbnailPath;
this.by = Video.createByString(hash.author, hash.podUrl); this.by = Video.createByString(hash.author, hash.podUrl);
} }

View File

@ -12,7 +12,16 @@ import { Video } from './video.model';
export class VideoService { export class VideoService {
private static BASE_VIDEO_URL = '/api/v1/videos/'; private static BASE_VIDEO_URL = '/api/v1/videos/';
constructor(private http: Http, private authService: AuthService) {} constructor(
private authService: AuthService,
private http: Http
) {}
getVideo(id: string) {
return this.http.get(VideoService.BASE_VIDEO_URL + id)
.map(res => <Video> res.json())
.catch(this.handleError);
}
getVideos(pagination: Pagination, sort: SortField) { getVideos(pagination: Pagination, sort: SortField) {
const params = this.createPaginationParams(pagination); const params = this.createPaginationParams(pagination);
@ -25,12 +34,6 @@ export class VideoService {
.catch(this.handleError); .catch(this.handleError);
} }
getVideo(id: string) {
return this.http.get(VideoService.BASE_VIDEO_URL + id)
.map(res => <Video> res.json())
.catch(this.handleError);
}
removeVideo(id: string) { removeVideo(id: string) {
const options = this.authService.getAuthRequestOptions(); const options = this.authService.getAuthRequestOptions();
return this.http.delete(VideoService.BASE_VIDEO_URL + id, options) return this.http.delete(VideoService.BASE_VIDEO_URL + id, options)
@ -50,6 +53,17 @@ export class VideoService {
.catch(this.handleError); .catch(this.handleError);
} }
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;
}
private extractVideos(body: any) { private extractVideos(body: any) {
const videos_json = body.data; const videos_json = body.data;
const totalVideos = body.total; const totalVideos = body.total;
@ -65,15 +79,4 @@ export class VideoService {
console.error(error); console.error(error);
return Observable.throw(error.json().error || 'Server error'); return Observable.throw(error.json().error || 'Server error');
} }
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;
}
} }

View File

@ -18,20 +18,21 @@ declare var jQuery: any;
}) })
export class VideoAddComponent implements OnInit { export class VideoAddComponent implements OnInit {
user: User;
fileToUpload: any; fileToUpload: any;
progressBar: { value: number; max: number; } = { value: 0, max: 0 }; progressBar: { value: number; max: number; } = { value: 0, max: 0 };
user: User;
private _form: any; private form: any;
constructor( constructor(
private _router: Router, private _elementRef: ElementRef, private router: Router,
private _authService: AuthService private elementRef: ElementRef,
private authService: AuthService
) {} ) {}
ngOnInit() { ngOnInit() {
this.user = User.load(); this.user = User.load();
jQuery(this._elementRef.nativeElement).find('#videofile').fileupload({ jQuery(this.elementRef.nativeElement).find('#videofile').fileupload({
url: '/api/v1/videos', url: '/api/v1/videos',
dataType: 'json', dataType: 'json',
singleFileUploads: true, singleFileUploads: true,
@ -39,7 +40,7 @@ export class VideoAddComponent implements OnInit {
autoupload: false, autoupload: false,
add: (e, data) => { add: (e, data) => {
this._form = data; this.form = data;
this.fileToUpload = data['files'][0]; this.fileToUpload = data['files'][0];
}, },
@ -55,14 +56,14 @@ export class VideoAddComponent implements OnInit {
console.log('Video uploaded.'); console.log('Video uploaded.');
// Print all the videos once it's finished // Print all the videos once it's finished
this._router.navigate(['VideosList']); this.router.navigate(['VideosList']);
} }
}); });
} }
uploadFile() { uploadFile() {
this._form.headers = this._authService.getRequestHeader().toJSON(); this.form.headers = this.authService.getRequestHeader().toJSON();
this._form.formData = jQuery(this._elementRef.nativeElement).find('form').serializeArray(); this.form.formData = jQuery(this.elementRef.nativeElement).find('form').serializeArray();
this._form.submit(); this.form.submit();
} }
} }

View File

@ -23,23 +23,23 @@ import { VideoSortComponent } from './video-sort.component';
}) })
export class VideoListComponent implements OnInit { export class VideoListComponent implements OnInit {
user: User = null; loading = false;
videos: Video[] = [];
pagination: Pagination = { pagination: Pagination = {
currentPage: 1, currentPage: 1,
itemsPerPage: 9, itemsPerPage: 9,
total: 0 total: 0
}; };
sort: SortField; sort: SortField;
loading = false; user: User = null;
videos: Video[] = [];
private search: Search; private search: Search;
constructor( constructor(
private authService: AuthService, private authService: AuthService,
private videoService: VideoService, private router: Router,
private routeParams: RouteParams, private routeParams: RouteParams,
private router: Router private videoService: VideoService
) { ) {
this.search = { this.search = {
value: this.routeParams.get('search'), value: this.routeParams.get('search'),
@ -73,6 +73,7 @@ export class VideoListComponent implements OnInit {
({ videos, totalVideos }) => { ({ videos, totalVideos }) => {
this.videos = videos; this.videos = videos;
this.pagination.total = totalVideos; this.pagination.total = totalVideos;
this.loading = false; this.loading = false;
}, },
error => alert(error) error => alert(error)
@ -91,8 +92,8 @@ export class VideoListComponent implements OnInit {
}; };
if (this.search.value) { if (this.search.value) {
params.search = this.search.value;
params.field = this.search.field; params.field = this.search.field;
params.search = this.search.value;
} }
this.router.navigate(['VideosList', params]); this.router.navigate(['VideosList', params]);

View File

@ -16,23 +16,23 @@ import { User } from '../../users/index';
export class VideoMiniatureComponent { export class VideoMiniatureComponent {
@Output() removed = new EventEmitter<any>(); @Output() removed = new EventEmitter<any>();
@Input() video: Video;
@Input() user: User; @Input() user: User;
@Input() video: Video;
hovering = false; hovering = false;
constructor(private videoService: VideoService) {} constructor(private videoService: VideoService) {}
onHover() { displayRemoveIcon() {
this.hovering = true; return this.hovering && this.video.isRemovableBy(this.user);
} }
onBlur() { onBlur() {
this.hovering = false; this.hovering = false;
} }
displayRemoveIcon() { onHover() {
return this.hovering && this.video.isRemovableBy(this.user); this.hovering = true;
} }
removeVideo(id: string) { removeVideo(id: string) {

View File

@ -17,32 +17,24 @@ declare var WebTorrent: any;
}) })
export class VideoWatchComponent implements OnInit, CanDeactivate { export class VideoWatchComponent implements OnInit, CanDeactivate {
video: Video;
downloadSpeed: number; downloadSpeed: number;
uploadSpeed: number;
numPeers: number;
loading: boolean = false; loading: boolean = false;
numPeers: number;
uploadSpeed: number;
video: Video;
private interval: NodeJS.Timer;
private client: any; private client: any;
private interval: NodeJS.Timer;
constructor( constructor(
private videoService: VideoService, private elementRef: ElementRef,
private routeParams: RouteParams, private routeParams: RouteParams,
private elementRef: ElementRef private videoService: VideoService
) { ) {
// TODO: use a service // TODO: use a service
this.client = new WebTorrent({ dht: false }); this.client = new WebTorrent({ dht: false });
} }
ngOnInit() {
let id = this.routeParams.get('id');
this.videoService.getVideo(id).subscribe(
video => this.loadVideo(video),
error => alert(error)
);
}
loadVideo(video: Video) { loadVideo(video: Video) {
this.loading = true; this.loading = true;
this.video = video; this.video = video;
@ -60,12 +52,20 @@ export class VideoWatchComponent implements OnInit, CanDeactivate {
// Refresh each second // Refresh each second
this.interval = setInterval(() => { this.interval = setInterval(() => {
this.downloadSpeed = torrent.downloadSpeed; this.downloadSpeed = torrent.downloadSpeed;
this.uploadSpeed = torrent.uploadSpeed;
this.numPeers = torrent.numPeers; this.numPeers = torrent.numPeers;
this.uploadSpeed = torrent.uploadSpeed;
}, 1000); }, 1000);
}); });
} }
ngOnInit() {
let id = this.routeParams.get('id');
this.videoService.getVideo(id).subscribe(
video => this.loadVideo(video),
error => alert(error)
);
}
routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) { routerCanDeactivate(next: ComponentInstruction, prev: ComponentInstruction) {
console.log('Removing video from webtorrent.'); console.log('Removing video from webtorrent.');
clearInterval(this.interval); clearInterval(this.interval);