Home Reference Source

src/chat/ChatMessageFile.ts

import Logs from '../Logs';

const log = Logs.instance.getLogger('SippoJS/chats/ChatMessageFile');

/**
 * Instances of this class represents a file in a chat message. This class must not be
 * directly instantiated. Instances of this class can be obtained using {@link ChatMessage#getData}.
 */
export class ChatMessageFile {
	private name: string;
	private url: string;
	private cachedType?: string;

	/** @ignore */
	constructor(name: string, url: string) {
		/** @private */
		this.name = name;
		/** @private */
		this.url = url;
		Object.freeze(this);
	}

	/**
	 * @desc Returns the name of the file.
	 * @return {string} Name of the file
	 */
	getName(): string {
		return this.name;
	}

	/**
	 * @desc Returns the URL of the file.
	 * @return {string} URL of the file
	 */
	getUrl(): string {
		return this.url;
	}

	/**
	 * @desc Returns the mime-type of the file.
	 * @return {Promise<string>} A promise fulfilled with the mime-type of the file
	 * @deprecated You must directly send a HEAD request to the URL instead of relying on this method
	 * e.g.: fetch(chatFile.getUrl(), {method: 'HEAD'})
	 */
	async getType(): Promise<string|undefined> {
		log.warn('ChatMessageFile.getType() is deprecated and will be removed in future versions.');
		if (!this.cachedType) {
			const res = await window.fetch(this.url, {
				method: 'HEAD',
			});
			const contentType = res.headers.get('content-type');
			if (contentType) {
				/** @private */
				this.cachedType = contentType;
			}
		}
		return this.cachedType;
	}
}