Convert js files in `model/` to Typescript

Convert `JamiDaemon.js` to Typescript
Add `model/util.ts` containing some utility types.

Gitlab: #30
Change-Id: Ia5d120330011e89a0be28732965ae9814ab68d19
diff --git a/model/Account.js b/model/Account.js
deleted file mode 100644
index aa1e957..0000000
--- a/model/Account.js
+++ /dev/null
@@ -1,140 +0,0 @@
-import Contact from './Contact.js';
-
-class Account {
-  constructor(id, details, volatileDetails) {
-    this.id = id;
-    this.details = details;
-    this.volatileDetails = volatileDetails;
-    this.contactCache = {};
-    this.contacts = {};
-    this.conversations = {};
-    this.lookups = [];
-    this.devices = {};
-  }
-
-  static from(object) {
-    const account = new Account(object.id, object.details, object.volatileDetails);
-    if (object.defaultModerators) account.defaultModerators = object.defaultModerators.map((m) => Contact.from(m));
-    return account;
-  }
-
-  update(data) {
-    this.details = data.details;
-    this.volatileDetails = data.volatileDetails;
-  }
-
-  async getObject() {
-    const hasModerators = this.defaultModerators && this.defaultModerators.length;
-    return {
-      id: this.id,
-      details: this.details,
-      defaultModerators: hasModerators
-        ? await Promise.all(this.defaultModerators.map(async (c) => await c.getObject()))
-        : undefined,
-      volatileDetails: this.volatileDetails,
-    };
-  }
-
-  getId() {
-    return this.id;
-  }
-
-  getType() {
-    return this.details['Account.type'];
-  }
-
-  getUri() {
-    return this.details['Account.username'];
-  }
-
-  getRegisteredName() {
-    return this.volatileDetails['Account.registeredName'];
-  }
-
-  isRendezVous() {
-    return this.details['Account.rendezVous'] === Account.BOOL_TRUE;
-  }
-
-  isPublicIn() {
-    return this.details['DHT.PublicInCalls'] === Account.BOOL_TRUE;
-  }
-
-  setDetail(detail, value) {
-    this.details[detail] = value;
-  }
-
-  updateDetails(details) {
-    return Object.assign(this.details, details);
-  }
-
-  getDetails() {
-    return this.details;
-  }
-
-  getSummary() {
-    return this.getObject();
-  }
-
-  getDisplayName() {
-    return this.details['Account.displayName'] || this.getDisplayUri();
-  }
-
-  getDisplayUri() {
-    return this.getRegisteredName() || this.getUri();
-  }
-
-  getDisplayNameNoFallback() {
-    return this.details['Account.displayName'] || this.getRegisteredName();
-  }
-
-  getConversationIds() {
-    return Object.keys(this.conversations);
-  }
-  getConversations() {
-    return this.conversations;
-  }
-
-  getConversation(conversationId) {
-    return this.conversations[conversationId];
-  }
-
-  addConversation(conversation) {
-    this.conversations[conversation.getId()] = conversation;
-  }
-
-  removeConversation(conversationId) {
-    delete this.conversations[conversationId];
-  }
-
-  getContactFromCache(uri) {
-    let contact = this.contactCache[uri];
-    if (!contact) {
-      contact = new Contact(uri);
-      this.contactCache[uri] = contact;
-    }
-    return contact;
-  }
-
-  getContacts() {
-    return this.contacts;
-  }
-
-  getDefaultModerators() {
-    return this.defaultModerators;
-  }
-
-  setDevices(devices) {
-    this.devices = { ...devices };
-  }
-  getDevices() {
-    return this.devices;
-  }
-}
-
-Account.TYPE_JAMI = 'RING';
-Account.TYPE_SIP = 'SIP';
-
-Account.BOOL_TRUE = 'true';
-Account.BOOL_FALSE = 'false';
-
-export default Account;
diff --git a/model/Account.ts b/model/Account.ts
new file mode 100644
index 0000000..ce529c0
--- /dev/null
+++ b/model/Account.ts
@@ -0,0 +1,216 @@
+import AccountDetails, { VolatileDetails } from './AccountDetails';
+import Contact from './Contact';
+import Conversation from './Conversation';
+import { Lookup, PromiseExecutor } from './util';
+
+type Devices = Record<string, string>;
+
+export type RegistrationState =
+  | 'UNREGISTERED'
+  | 'TRYING'
+  | 'REGISTERED'
+  | 'ERROR_GENERIC'
+  | 'ERROR_AUTH'
+  | 'ERROR_NETWORK'
+  | 'ERROR_HOST'
+  | 'ERROR_SERVICE_UNAVAILABLE'
+  | 'ERROR_NEED_MIGRATION'
+  | 'INITIALIZING';
+
+interface AccountRegisteringName extends PromiseExecutor<number> {
+  name: string;
+}
+
+class Account {
+  private readonly id: string;
+  private _details: AccountDetails;
+  private _volatileDetails: VolatileDetails;
+  private contactCache: Record<string, Contact> = {};
+  private _contacts: Contact[] = [];
+  private conversations: Record<string, Conversation> = {};
+  private defaultModerators: Contact[] = [];
+  private _lookups: Lookup[] = [];
+  private devices: Devices = {};
+  private _registrationState: RegistrationState | undefined = undefined;
+  private _registeringName: AccountRegisteringName | undefined = undefined;
+
+  static TYPE_JAMI: string;
+  static TYPE_SIP: string;
+  static BOOL_TRUE: string;
+  static BOOL_FALSE: string;
+
+  constructor(id: string, details: AccountDetails, volatileDetails: VolatileDetails) {
+    this.id = id;
+    this._details = details;
+    this._volatileDetails = volatileDetails;
+  }
+
+  static from(object: Account) {
+    const account = new Account(object.id, object._details, object._volatileDetails);
+    if (object.defaultModerators) account.defaultModerators = object.defaultModerators.map((m) => Contact.from(m));
+    return account;
+  }
+
+  update(data: Account) {
+    this._details = data._details;
+    this._volatileDetails = data._volatileDetails;
+  }
+
+  async getObject() {
+    const hasModerators = this.defaultModerators && this.defaultModerators.length;
+    return {
+      id: this.id,
+      details: this._details,
+      defaultModerators: hasModerators
+        ? await Promise.all(this.defaultModerators.map(async (c) => await c.getObject()))
+        : undefined,
+      volatileDetails: this._volatileDetails,
+    };
+  }
+
+  getId() {
+    return this.id;
+  }
+
+  getType() {
+    return this._details['Account.type'];
+  }
+
+  getUri() {
+    return this._details['Account.username'];
+  }
+
+  getRegisteredName() {
+    return this._volatileDetails['Account.registeredName'];
+  }
+
+  isRendezVous() {
+    return this._details['Account.rendezVous'] === Account.BOOL_TRUE;
+  }
+
+  isPublicIn() {
+    return this._details['DHT.PublicInCalls'] === Account.BOOL_TRUE;
+  }
+
+  setDetail(detail: keyof AccountDetails, value: string) {
+    this._details[detail] = value;
+  }
+
+  updateDetails(details: Partial<AccountDetails>) {
+    return Object.assign(this._details, details);
+  }
+
+  getDetails() {
+    return this._details;
+  }
+
+  getSummary() {
+    return this.getObject();
+  }
+
+  getDisplayName() {
+    return this._details['Account.displayName'] || this.getDisplayUri();
+  }
+
+  getDisplayUri() {
+    return this.getRegisteredName() || this.getUri();
+  }
+
+  getDisplayNameNoFallback() {
+    return this._details['Account.displayName'] || this.getRegisteredName();
+  }
+
+  getConversationIds() {
+    return Object.keys(this.conversations);
+  }
+
+  getConversations() {
+    return this.conversations;
+  }
+
+  getConversation(conversationId: string) {
+    return this.conversations[conversationId];
+  }
+
+  addConversation(conversation: Conversation) {
+    const conversationId = conversation.getId();
+    if (conversationId != null) {
+      this.conversations[conversationId] = conversation;
+    } else {
+      throw new Error('Conversation ID cannot be undefined');
+    }
+  }
+
+  removeConversation(conversationId: string) {
+    delete this.conversations[conversationId];
+  }
+
+  getContactFromCache(uri: string) {
+    let contact = this.contactCache[uri];
+    if (!contact) {
+      contact = new Contact(uri);
+      this.contactCache[uri] = contact;
+    }
+    return contact;
+  }
+
+  getContacts() {
+    return this._contacts;
+  }
+
+  set contacts(contacts: Contact[]) {
+    this._contacts = contacts;
+  }
+
+  getDefaultModerators() {
+    return this.defaultModerators;
+  }
+
+  set details(value: AccountDetails) {
+    this._details = value;
+  }
+
+  set volatileDetails(value: VolatileDetails) {
+    this._volatileDetails = value;
+  }
+
+  get lookups(): Lookup[] {
+    return this._lookups;
+  }
+
+  set lookups(lookups: Lookup[]) {
+    this._lookups = lookups;
+  }
+
+  setDevices(devices: Devices) {
+    this.devices = { ...devices };
+  }
+
+  getDevices() {
+    return this.devices;
+  }
+
+  get registrationState(): RegistrationState | undefined {
+    return this._registrationState;
+  }
+
+  set registrationState(registrationState: RegistrationState | undefined) {
+    this._registrationState = registrationState;
+  }
+
+  get registeringName(): AccountRegisteringName | undefined {
+    return this._registeringName;
+  }
+
+  set registeringName(registeringName: AccountRegisteringName | undefined) {
+    this._registeringName = registeringName;
+  }
+}
+
+Account.TYPE_JAMI = 'RING';
+Account.TYPE_SIP = 'SIP';
+
+Account.BOOL_TRUE = 'true';
+Account.BOOL_FALSE = 'false';
+
+export default Account;
diff --git a/model/AccountDetails.ts b/model/AccountDetails.ts
new file mode 100644
index 0000000..e9514aa
--- /dev/null
+++ b/model/AccountDetails.ts
@@ -0,0 +1,169 @@
+/**
+ * Account parameters
+ *
+ * See `jami-daemon/src/account_schema.h`
+ */
+export default interface AccountDetails {
+  // Common account parameters
+  'Account.type': string;
+  'Account.alias': string;
+  'Account.displayName': string;
+  'Account.mailbox': string;
+  'Account.enable': string;
+  'Account.autoAnswer': string;
+  'Account.sendReadReceipt': string;
+  'Account.rendezVous': string;
+  'Account.registrationExpire': string;
+  'Account.dtmfType': string;
+  'Account.ringtonePath': string;
+  'Account.ringtoneEnabled': string;
+  'Account.videoEnabled': string;
+  'Account.keepAliveEnabled': string;
+  'Account.presenceEnabled': string;
+  'Account.presencePublishSupported': string;
+  'Account.presenceSubscribeSupported': string;
+  'Account.presenceStatus': string;
+  'Account.presenceNote': string;
+
+  'Account.hostname': string;
+  'Account.username': string;
+  'Account.routeset': string;
+  'Account.allowIPAutoRewrite': string;
+  'Account.password': string;
+  'Account.realm': string;
+  'Account.useragent': string;
+  'Account.hasCustomUserAgent': string;
+  'Account.audioPortMin': string;
+  'Account.audioPortMax': string;
+  'Account.videoPortMin': string;
+  'Account.videoPortMax': string;
+
+  'Account.bindAddress': string;
+  'Account.localInterface': string;
+  'Account.publishedSameAsLocal': string;
+  'Account.localPort': string;
+  'Account.publishedPort': string;
+  'Account.publishedAddress': string;
+  'Account.upnpEnabled': string;
+  'Account.defaultModerators': string;
+  'Account.localModeratorsEnabled': string;
+  'Account.allModeratorEnabled': string;
+
+  // SIP specific parameters
+  'STUN.server': string;
+  'STUN.enable': string;
+  'TURN.server': string;
+  'TURN.enable': string;
+  'TURN.username': string;
+  'TURN.password': string;
+  'TURN.realm': string;
+
+  // SRTP specific parameters
+  'SRTP.enable': string;
+  'SRTP.keyExchange': string;
+  'SRTP.rtpFallback': string;
+
+  'TLS.listenerPort': string;
+  'TLS.enable': string;
+  'TLS.certificateListFile': string;
+  'TLS.certificateFile': string;
+  'TLS.privateKeyFile': string;
+  'TLS.password': string;
+  'TLS.method': string;
+  'TLS.ciphers': string;
+  'TLS.serverName': string;
+  'TLS.verifyServer': string;
+  'TLS.verifyClient': string;
+  'TLS.requireClientCertificate': string;
+  'TLS.negotiationTimeoutSec': string;
+
+  // DHT specific parameters
+  'DHT.port': string;
+  'DHT.PublicInCalls': string;
+
+  // Volatile parameters
+  'Account.registrationStatus': string;
+  'Account.registrationCode': string;
+  'Account.registrationDescription': string;
+  'Transport.statusCode': string;
+  'Transport.statusDescription': string;
+}
+
+/**
+ * Volatile properties
+ *
+ * See `jami-daemon/src/jami/account_const.h`
+ */
+export interface VolatileDetails {
+  'Account.active': string;
+  'Account.deviceAnnounced': string;
+  'Account.registeredName': string;
+}
+
+/**
+ * See `ConfProperties` in `jami-daemon/src/jami/account_const.h
+ */
+export interface AccountConfig {
+  id?: string;
+  type?: string;
+  alias?: string;
+  displayName?: string;
+  enable?: boolean;
+  mailbox?: string;
+  dtmfType?: string;
+  autoAnswer?: boolean;
+  sendReadReceipt?: string;
+  rendezVous?: boolean;
+  activeCallLimit?: string;
+  hostname?: string;
+  username?: string;
+  bindAddress?: string;
+  routeset?: string;
+  password?: string;
+  realm?: string;
+  localInterface?: string;
+  publishedSameAsLocal?: boolean;
+  localPort?: string;
+  publishedPort?: string;
+  publishedAddress?: string;
+  useragent?: string;
+  upnpEnabled?: boolean;
+  hasCustomUserAgent?: string;
+  allowCertFromHistory?: string;
+  allowCertFromContact?: string;
+  allowCertFromTrusted?: string;
+  archivePassword?: string;
+  archiveHasPassword?: string;
+  archivePath?: string;
+  archivePIN?: string;
+  deviceID?: string;
+  deviceName?: string;
+  proxyEnabled?: boolean;
+  proxyServer?: string;
+  proxyPushToken?: string;
+  keepAliveEnabled?: boolean;
+  peerDiscovery?: string;
+  accountDiscovery?: string;
+  accountPublish?: string;
+  managerUri?: string;
+  managerUsername?: string;
+  bootstrapListUrl?: string;
+  dhtProxyListUrl?: string;
+  defaultModerators?: string;
+  localModeratorsEnabled?: boolean;
+  allModeratorsEnabled?: boolean;
+  allowIPAutoRewrite?: string;
+
+  // Audio
+  audioPortMax?: string;
+  audioPortMin?: string;
+
+  // Video
+  videoEnabled?: boolean;
+  videoPortMax?: boolean;
+  videoPortMin?: string;
+
+  // Ringtone
+  ringtonePath?: string;
+  ringtoneEnabled?: boolean;
+}
diff --git a/model/Contact.js b/model/Contact.ts
similarity index 73%
rename from model/Contact.js
rename to model/Contact.ts
index cc8e386..01d4a02 100644
--- a/model/Contact.js
+++ b/model/Contact.ts
@@ -1,11 +1,13 @@
 class Contact {
-  constructor(uri) {
+  private readonly uri: string;
+  private displayName: string | undefined = undefined;
+  private registeredName: string | undefined = undefined;
+
+  constructor(uri: string) {
     this.uri = uri;
-    this.displayName = undefined;
-    this.registeredName = undefined;
   }
 
-  static from(object) {
+  static from(object: Contact) {
     const contact = new Contact(object.uri);
     if (object.registeredName) contact.setRegisteredName(object.registeredName);
     return contact;
@@ -19,7 +21,7 @@
     return this.registeredName;
   }
 
-  setRegisteredName(name) {
+  setRegisteredName(name: string | undefined) {
     this.registeredName = name;
   }
 
diff --git a/model/Conversation.js b/model/Conversation.js
deleted file mode 100644
index 174ba03..0000000
--- a/model/Conversation.js
+++ /dev/null
@@ -1,104 +0,0 @@
-import Contact from './Contact.js';
-
-class Conversation {
-  constructor(id, accountId, members) {
-    this.id = id;
-    this.accountId = accountId;
-    this.members = members || [];
-    this.messages = [];
-    this.infos = {};
-  }
-
-  static from(accountId, object) {
-    const conversation = new Conversation(
-      object.id,
-      accountId,
-      object.members.map((member) => {
-        member.contact = Contact.from(member.contact);
-        return member;
-      })
-    );
-    conversation.messages = object.messages;
-    return conversation;
-  }
-  static fromSingleContact(accountId, contact) {
-    return new Conversation(undefined, accountId, [{ contact }]);
-  }
-
-  getId() {
-    return this.id;
-  }
-
-  getAccountId() {
-    return this.accountId;
-  }
-
-  getDisplayName() {
-    if (this.members.length !== 0) {
-      return this.members[0].contact.getDisplayName();
-    }
-    return this.getDisplayUri();
-  }
-
-  getDisplayNameNoFallback() {
-    if (this.members.length !== 0) {
-      return this.members[0].contact.getDisplayNameNoFallback();
-    }
-  }
-
-  async getObject(params) {
-    const members = params.memberFilter ? this.members.filter(params.memberFilter) : this.members;
-    return {
-      id: this.id,
-      messages: this.messages,
-      members: await Promise.all(
-        members.map(async (member) => {
-          const copiedMember = { role: member.role }; //Object.assign({}, member);
-          copiedMember.contact = await member.contact.getObject();
-          return copiedMember;
-        })
-      ),
-    };
-  }
-
-  getSummary() {
-    return this.getObject();
-  }
-
-  getDisplayUri() {
-    return this.getId() || this.getFirstMember().contact.getUri();
-  }
-
-  getFirstMember() {
-    return this.members[0];
-  }
-
-  getMembers() {
-    return this.members;
-  }
-
-  addMessage(message) {
-    if (this.messages.length === 0) this.messages.push(message);
-    else if (message.id === this.messages[this.messages.length - 1].linearizedParent) {
-      this.messages.push(message);
-    } else if (message.linearizedParent === this.messages[0].id) {
-      this.messages.unshift(message);
-    } else {
-      console.log("Can't insert message " + message.id);
-    }
-  }
-
-  addLoadedMessages(messages) {
-    messages.forEach((message) => this.addMessage(message));
-  }
-
-  getMessages() {
-    return this.messages;
-  }
-
-  setInfos(infos) {
-    this.infos = infos;
-  }
-}
-
-export default Conversation;
diff --git a/model/Conversation.ts b/model/Conversation.ts
new file mode 100644
index 0000000..3a75567
--- /dev/null
+++ b/model/Conversation.ts
@@ -0,0 +1,151 @@
+import { Socket } from 'socket.io';
+
+import Contact from './Contact';
+import { PromiseExecutor, Session } from './util';
+
+export interface ConversationMember {
+  contact: Contact;
+  role?: 'admin' | 'member' | 'invited' | 'banned' | 'left';
+}
+
+type ConversationInfos = Record<string, unknown>;
+
+export type Message = Record<string, string>;
+type ConversationRequest = PromiseExecutor<Message[]>;
+
+type ConversationListeners = Record<
+  string,
+  {
+    socket: Socket;
+    session: Session;
+  }
+>;
+
+class Conversation {
+  private readonly id: string | undefined;
+  private readonly accountId: string;
+  private readonly members: ConversationMember[];
+  private messages: Message[] = [];
+  private _infos: ConversationInfos = {};
+  private _requests: Record<string, ConversationRequest> = {};
+  private _listeners: ConversationListeners = {};
+
+  constructor(id: string | undefined, accountId: string, members?: ConversationMember[]) {
+    this.id = id;
+    this.accountId = accountId;
+    this.members = members || [];
+  }
+
+  static from(accountId: string, object: Conversation) {
+    const conversation = new Conversation(
+      object.id,
+      accountId,
+      object.members.map((member) => {
+        member.contact = Contact.from(member.contact);
+        return member;
+      })
+    );
+    conversation.messages = object.messages;
+    return conversation;
+  }
+  static fromSingleContact(accountId: string, contact: Contact) {
+    return new Conversation(undefined, accountId, [{ contact }]);
+  }
+
+  getId() {
+    return this.id;
+  }
+
+  getAccountId() {
+    return this.accountId;
+  }
+
+  getDisplayName() {
+    if (this.members.length !== 0) {
+      return this.members[0].contact.getDisplayName();
+    }
+    return this.getDisplayUri();
+  }
+
+  getDisplayNameNoFallback() {
+    if (this.members.length !== 0) {
+      return this.members[0].contact.getDisplayNameNoFallback();
+    }
+  }
+
+  async getObject(params?: {
+    memberFilter: (value: ConversationMember, index: number, array: ConversationMember[]) => boolean;
+  }) {
+    const members = params?.memberFilter ? this.members.filter(params.memberFilter) : this.members;
+    return {
+      id: this.id,
+      messages: this.messages,
+      members: await Promise.all(
+        members.map(async (member) => {
+          //Object.assign({}, member);
+          return {
+            role: member.role,
+            contact: await member.contact.getObject(),
+          };
+        })
+      ),
+    };
+  }
+
+  getSummary() {
+    return this.getObject();
+  }
+
+  getDisplayUri() {
+    return this.getId() || this.getFirstMember().contact.getUri();
+  }
+
+  getFirstMember() {
+    return this.members[0];
+  }
+
+  getMembers() {
+    return this.members;
+  }
+
+  addMessage(message: Message) {
+    if (this.messages.length === 0) this.messages.push(message);
+    else if (message.id === this.messages[this.messages.length - 1].linearizedParent) {
+      this.messages.push(message);
+    } else if (message.linearizedParent === this.messages[0].id) {
+      this.messages.unshift(message);
+    } else {
+      console.log("Can't insert message " + message.id);
+    }
+  }
+
+  addLoadedMessages(messages: Message[]) {
+    messages.forEach((message) => this.addMessage(message));
+  }
+
+  getMessages() {
+    return this.messages;
+  }
+
+  set infos(infos: ConversationInfos) {
+    this._infos = infos;
+  }
+
+  get requests(): Record<string, ConversationRequest> {
+    return this._requests;
+  }
+
+  set requests(value: Record<string, ConversationRequest>) {
+    this._requests = value;
+  }
+
+  get listeners(): ConversationListeners {
+    return this._listeners;
+  }
+
+  set listeners(listeners: ConversationListeners) {
+    this._listeners = listeners;
+  }
+}
+
+export default Conversation;
diff --git a/model/util.ts b/model/util.ts
new file mode 100644
index 0000000..630b358
--- /dev/null
+++ b/model/util.ts
@@ -0,0 +1,22 @@
+import { Session as ISession } from 'express-session';
+
+export interface PromiseExecutor<T> {
+  resolve: (value: T) => void;
+  reject: (reason?: any) => void;
+}
+
+export interface LookupResolveValue {
+  address: string;
+  name: string;
+  state: number;
+}
+
+export interface Lookup extends PromiseExecutor<LookupResolveValue> {
+  name?: string;
+  address?: string;
+}
+
+export interface Session extends ISession {
+  socketId: string;
+  conversation: any;
+}