Sharkey/src/web/app/common/scripts/streaming/stream-manager.ts

74 lines
1.6 KiB
TypeScript
Raw Normal View History

2017-11-16 17:24:44 +01:00
import { EventEmitter } from 'eventemitter3';
import * as uuid from 'uuid';
import Connection from './stream';
/**
*
*
*/
export default abstract class StreamManager<T extends Connection> extends EventEmitter {
protected _connection: T = null;
/**
*
*/
private users = [];
protected set connection(connection: T) {
this._connection = connection;
if (this._connection == null) {
this.emit('disconnected');
} else {
this.emit('connected', this._connection);
}
}
protected get connection() {
return this._connection;
}
/**
*
*/
public get hasConnection() {
return this._connection != null;
}
/**
*
*/
public abstract getConnection(): T;
public borrow() {
return this._connection;
}
/**
* IDを発行します
*/
public use() {
// ユーザーID生成
const userId = uuid();
this.users.push(userId);
return userId;
}
/**
*
* @param userId use ID
*/
public dispose(userId) {
this.users = this.users.filter(id => id != userId);
// 誰もコネクションの利用者がいなくなったら
if (this.users.length == 0) {
// コネクションを切断する
this.connection.close();
this.connection = null;
}
}
}