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

90 lines
2.1 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);
}
}
protected get connection() {
return this._connection;
}
/**
*
*/
public get hasConnection() {
return this._connection != null;
}
/**
*
*/
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);
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 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
}
}
}