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

109 lines
2.5 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 {
2017-11-16 17:30:15 +01:00
private _connection: T = null;
2017-11-16 17:24:44 +01:00
2017-11-17 13:14:03 +01:00
private disposeTimerId: any;
2017-11-16 17:24:44 +01:00
/**
*
*/
private users = [];
protected set connection(connection: T) {
this._connection = connection;
if (this._connection == null) {
this.emit('disconnected');
} else {
this.emit('connected', this._connection);
2018-02-26 11:23:53 +01:00
this._connection.on('_connected_', () => {
this.emit('_connected_');
});
this._connection.on('_disconnected_', () => {
this.emit('_disconnected_');
});
2018-03-15 11:53:46 +01:00
this._connection.user = 'Managed';
2017-11-16 17:24:44 +01:00
}
}
protected get connection() {
return this._connection;
}
/**
*
*/
public get hasConnection() {
return this._connection != null;
}
2018-02-26 11:23:53 +01:00
public get state(): string {
if (!this.hasConnection) return 'no-connection';
return this._connection.state;
}
2017-11-16 17:24:44 +01:00
/**
*
*/
public abstract getConnection(): T;
2017-11-16 17:30:47 +01:00
/**
*
*/
2017-11-16 17:24:44 +01:00
public borrow() {
return this._connection;
}
/**
* IDを発行します
*/
public use() {
2017-11-17 13:14:03 +01:00
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
2017-11-16 17:24:44 +01:00
// ユーザーID生成
const userId = uuid();
this.users.push(userId);
2018-03-15 11:53:46 +01:00
this._connection.user = `Managed (${ this.users.length })`;
2017-11-16 17:24:44 +01:00
return userId;
}
/**
*
* @param userId use ID
*/
public dispose(userId) {
this.users = this.users.filter(id => id != userId);
2018-03-15 11:53:46 +01:00
this._connection.user = `Managed (${ this.users.length })`;
2017-11-16 17:24:44 +01:00
// 誰もコネクションの利用者がいなくなったら
if (this.users.length == 0) {
2017-11-17 13:14:03 +01:00
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
2017-11-17 13:17:30 +01:00
this.disposeTimerId = null;
2017-11-17 13:14:03 +01:00
this.connection.close();
this.connection = null;
}, 3000);
2017-11-16 17:24:44 +01:00
}
}
}