Add `common` subproject containing shared files

Move classes in `model` to their own `common` package.
Now, the client and server can import `common` as a library.
This is the first step to eventually migrate all the source code at the root of the
project to an `old-server` package.

GitLab: #55
Change-Id: I4b7a52e80171d9c3399416ab524bcdd6915ac540
diff --git a/common/src/Account.ts b/common/src/Account.ts
new file mode 100644
index 0000000..70acb52
--- /dev/null
+++ b/common/src/Account.ts
@@ -0,0 +1,239 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+import { AccountDetails, VolatileDetails } from './AccountDetails.js';
+import { Contact } from './Contact.js';
+import { Conversation } from './Conversation.js';
+import { Lookup, PromiseExecutor } from './util.js';
+
+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;
+}
+
+export class Account {
+  private readonly id: string;
+  private _details: AccountDetails;
+  private _volatileDetails: VolatileDetails;
+  private readonly contactCache: Record<string, Contact>;
+  private _contacts: Contact[];
+  private readonly conversations: Record<string, Conversation>;
+  private defaultModerators: Contact[];
+  private _lookups: Lookup[];
+  private devices: Devices;
+  private _registrationState: RegistrationState | undefined;
+  private _registeringName: AccountRegisteringName | 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 || {};
+    this.contactCache = {};
+    this._contacts = [];
+    this.conversations = {};
+    this.defaultModerators = [];
+    this._lookups = [];
+    this.devices = {};
+    this.registrationState = undefined;
+    this._registeringName = undefined;
+  }
+
+  static from(object: any) {
+    const account = new Account(object.id, object.details, object.volatileDetails);
+    if (object.defaultModerators) account.defaultModerators = object.defaultModerators.map((m: any) => 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';
diff --git a/common/src/AccountDetails.ts b/common/src/AccountDetails.ts
new file mode 100644
index 0000000..69968c0
--- /dev/null
+++ b/common/src/AccountDetails.ts
@@ -0,0 +1,187 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+
+/**
+ * Account parameters
+ *
+ * See `jami-daemon/src/account_schema.h`
+ */
+export 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/common/src/Contact.ts b/common/src/Contact.ts
new file mode 100644
index 0000000..88e1916
--- /dev/null
+++ b/common/src/Contact.ts
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+export class Contact {
+  private readonly uri: string;
+  private readonly displayName: string | undefined;
+  private registeredName: string | undefined;
+
+  constructor(uri: string) {
+    this.uri = uri;
+    this.displayName = undefined;
+    this.registeredName = undefined;
+  }
+
+  static from(object: any) {
+    const contact = new Contact(object.uri);
+    if (object.registeredName) contact.setRegisteredName(object.registeredName);
+    return contact;
+  }
+
+  getUri() {
+    return this.uri;
+  }
+
+  getRegisteredName() {
+    return this.registeredName;
+  }
+
+  setRegisteredName(name: string | undefined) {
+    this.registeredName = name;
+  }
+
+  isRegisteredNameResolved() {
+    return this.registeredName !== undefined;
+  }
+
+  getDisplayName() {
+    return this.getDisplayNameNoFallback() || this.getUri();
+  }
+
+  getDisplayNameNoFallback() {
+    return this.displayName || this.getRegisteredName();
+  }
+
+  async getObject() {
+    return {
+      uri: this.uri,
+      registeredName: await this.registeredName,
+    };
+  }
+}
diff --git a/common/src/Conversation.ts b/common/src/Conversation.ts
new file mode 100644
index 0000000..01b70cd
--- /dev/null
+++ b/common/src/Conversation.ts
@@ -0,0 +1,171 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+import { Socket } from 'socket.io';
+
+import { Contact } from './Contact.js';
+import { PromiseExecutor, Session } from './util.js';
+
+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;
+  }
+>;
+
+export 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 || [];
+
+    this.messages = [];
+    this._infos = {};
+    this._requests = {};
+    this._listeners = {};
+  }
+
+  static from(accountId: string, object: any) {
+    const conversation = new Conversation(
+      object.id,
+      accountId,
+      object.members.map((member: any) => {
+        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;
+  }
+}
diff --git a/common/src/index.ts b/common/src/index.ts
new file mode 100644
index 0000000..e58fd49
--- /dev/null
+++ b/common/src/index.ts
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+export * from './Account.js';
+export * from './AccountDetails.js';
+export * from './Contact.js';
+export * from './Conversation.js';
+export * from './util.js';
diff --git a/common/src/util.ts b/common/src/util.ts
new file mode 100644
index 0000000..c814ba1
--- /dev/null
+++ b/common/src/util.ts
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2022 Savoir-faire Linux Inc.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation; either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public
+ * License along with this program.  If not, see
+ * <https://www.gnu.org/licenses/>.
+ */
+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;
+}