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

103 lines
2.3 KiB
TypeScript
Raw Normal View History

2017-11-17 01:24:44 +09: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-17 01:30:15 +09:00
private _connection: T = null;
2017-11-17 01:24:44 +09:00
2017-11-17 21:14:03 +09:00
private disposeTimerId: any;
2017-11-17 01:24:44 +09: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 19:23:53 +09:00
this._connection.on('_connected_', () => {
this.emit('_connected_');
});
this._connection.on('_disconnected_', () => {
this.emit('_disconnected_');
});
2017-11-17 01:24:44 +09:00
}
}
protected get connection() {
return this._connection;
}
/**
*
*/
public get hasConnection() {
return this._connection != null;
}
2018-02-26 19:23:53 +09:00
public get state(): string {
if (!this.hasConnection) return 'no-connection';
return this._connection.state;
}
2017-11-17 01:24:44 +09:00
/**
*
*/
public abstract getConnection(): T;
2017-11-17 01:30:47 +09:00
/**
*
*/
2017-11-17 01:24:44 +09:00
public borrow() {
return this._connection;
}
/**
* IDを発行します
*/
public use() {
2017-11-17 21:14:03 +09:00
// タイマー解除
if (this.disposeTimerId) {
clearTimeout(this.disposeTimerId);
this.disposeTimerId = null;
}
2017-11-17 01:24:44 +09:00
// ユーザー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) {
2017-11-17 21:14:03 +09:00
// また直ぐに再利用される可能性があるので、一定時間待ち、
// 新たな利用者が現れなければコネクションを切断する
this.disposeTimerId = setTimeout(() => {
2017-11-17 21:17:30 +09:00
this.disposeTimerId = null;
2017-11-17 21:14:03 +09:00
this.connection.close();
this.connection = null;
}, 3000);
2017-11-17 01:24:44 +09:00
}
}
}