tweb/src/lib/appManagers/appUsersManager.ts

638 lines
18 KiB
TypeScript
Raw Normal View History

import { formatPhoneNumber } from "../../components/misc";
2020-10-17 00:31:58 +02:00
import { InputUser, Update, User as MTUser, UserStatus } from "../../layer";
2020-04-26 14:19:17 +02:00
//import apiManager from '../mtproto/apiManager';
import apiManager from '../mtproto/mtprotoworker';
import serverTimeManager from "../mtproto/serverTimeManager";
import { RichTextProcessor } from "../richtextprocessor";
import $rootScope from "../rootScope";
import searchIndexManager from "../searchIndexManager";
2020-10-29 17:26:08 +01:00
import { isObject, safeReplaceObject, tsNow } from "../utils";
import appChatsManager from "./appChatsManager";
2020-06-20 03:11:24 +02:00
import appPeersManager from "./appPeersManager";
import appStateManager from "./appStateManager";
2020-02-06 16:43:07 +01:00
// TODO: updateUserBlocked
2020-10-17 00:31:58 +02:00
export type User = MTUser.user;
2020-02-06 16:43:07 +01:00
export class AppUsersManager {
public users: {[userID: number]: User} = {};
public usernames: {[username: string]: number} = {};
//public userAccess: {[userID: number]: string} = {};
2020-02-06 16:43:07 +01:00
public cachedPhotoLocations: any = {};
public contactsIndex = searchIndexManager.createIndex();
2020-06-19 13:49:55 +02:00
public contactsFillPromise: Promise<Set<number>>;
public contactsList: Set<number> = new Set();
2020-02-06 16:43:07 +01:00
public getTopPeersPromise: Promise<number[]>;
2020-06-20 03:11:24 +02:00
2020-02-06 16:43:07 +01:00
constructor() {
setInterval(this.updateUsersStatuses, 60000);
2020-02-06 16:43:07 +01:00
$rootScope.$on('stateSynchronized', this.updateUsersStatuses);
2020-02-06 16:43:07 +01:00
2020-09-20 00:38:00 +02:00
$rootScope.$on('apiUpdate', (e) => {
const update = e.detail as Update;
//console.log('on apiUpdate', update);
2020-02-06 16:43:07 +01:00
switch(update._) {
case 'updateUserStatus':
const userID = update.user_id;
const user = this.users[userID];
2020-02-06 16:43:07 +01:00
if(user) {
user.status = update.status;
if(user.status) {
if('expires' in user.status) {
user.status.expires -= serverTimeManager.serverTimeOffset;
2020-02-06 16:43:07 +01:00
}
if('was_online' in user.status) {
user.status.was_online -= serverTimeManager.serverTimeOffset;
2020-02-06 16:43:07 +01:00
}
}
user.sortStatus = this.getUserStatusForSort(user.status);
$rootScope.$broadcast('user_update', userID);
2020-02-17 13:18:06 +01:00
} //////else console.warn('No user by id:', userID);
2020-02-06 16:43:07 +01:00
break;
case 'updateUserPhoto': {
const userID = update.user_id;
const user = this.users[userID];
2020-02-06 16:43:07 +01:00
if(user) {
this.forceUserOnline(userID);
if(!user.photo) {
user.photo = update.photo;
} else {
safeReplaceObject(user.photo, update.photo);
}
if(this.cachedPhotoLocations[userID] !== undefined) {
safeReplaceObject(this.cachedPhotoLocations[userID], update.photo ?
update.photo : {empty: true});
}
$rootScope.$broadcast('user_update', userID);
$rootScope.$broadcast('avatar_update', userID);
2020-02-06 16:43:07 +01:00
} else console.warn('No user by id:', userID);
break;
}
/* // @ts-ignore
case 'updateUserBlocked': {
const id = (update as any).user_id;
const blocked: boolean = (update as any).blocked;
const user = this.getUser(id);
if(user) {
}
break;
} */
2020-02-06 16:43:07 +01:00
2020-08-31 18:48:46 +02:00
/* case 'updateContactLink':
2020-02-06 16:43:07 +01:00
this.onContactUpdated(update.user_id, update.my_link._ == 'contactLinkContact');
2020-08-31 18:48:46 +02:00
break; */
2020-02-06 16:43:07 +01:00
}
});
appStateManager.addListener('save', () => {
const contactsList = [...this.contactsList];
for(const userID of contactsList) {
appStateManager.setPeer(userID, this.getUser(userID));
}
appStateManager.pushToState('contactsList', contactsList);
});
appStateManager.getState().then((state) => {
const contactsList = state.contactsList;
if(contactsList && Array.isArray(contactsList) && contactsList.length) {
contactsList.forEach(userID => {
this.pushContact(userID);
});
this.contactsFillPromise = Promise.resolve(this.contactsList);
}
this.users = state.users;
});
2020-02-06 16:43:07 +01:00
}
public fillContacts() {
2020-02-06 16:43:07 +01:00
if(this.contactsFillPromise) {
return this.contactsFillPromise;
}
return this.contactsFillPromise = apiManager.invokeApi('contacts.getContacts', {
2020-02-06 16:43:07 +01:00
hash: 0
}).then((result) => {
if(result._ == 'contacts.contacts') {
this.saveApiUsers(result.users);
2020-02-06 16:43:07 +01:00
result.contacts.forEach((contact) => {
this.pushContact(contact.user_id);
});
}
2020-02-06 16:43:07 +01:00
return this.contactsList;
});
}
2020-02-06 16:43:07 +01:00
public async resolveUsername(username: string) {
if(this.usernames[username]) {
return this.users[this.usernames[username]];
}
return await apiManager.invokeApi('contacts.resolveUsername', {username}).then(resolvedPeer => {
2020-10-17 00:31:58 +02:00
this.saveApiUser(resolvedPeer.users[0] as User);
appChatsManager.saveApiChats(resolvedPeer.chats);
return this.users[this.usernames[username]];
});
}
2020-06-19 13:49:55 +02:00
public pushContact(userID: number) {
this.contactsList.add(userID);
searchIndexManager.indexObject(userID, this.getUserSearchText(userID), this.contactsIndex);
}
2020-02-06 16:43:07 +01:00
public getUserSearchText(id: number) {
const user = this.users[id];
2020-02-06 16:43:07 +01:00
if(!user) {
return '';
2020-02-06 16:43:07 +01:00
}
const serviceText = user.pFlags.self ? 'user_name_saved_msgs_raw' : '';
2020-02-06 16:43:07 +01:00
return (user.first_name || '') +
' ' + (user.last_name || '') +
' ' + (user.phone || '') +
' ' + (user.username || '') +
' ' + serviceText;
}
public getContacts(query?: string) {
2020-06-19 13:49:55 +02:00
return this.fillContacts().then(_contactsList => {
let contactsList = [..._contactsList];
if(query) {
const results = searchIndexManager.search(query, this.contactsIndex);
2020-06-19 13:49:55 +02:00
const filteredContactsList = [...contactsList].filter(id => !!results[id]);
2020-02-06 16:43:07 +01:00
contactsList = filteredContactsList;
}
contactsList.sort((userID1: number, userID2: number) => {
const sortName1 = (this.users[userID1] || {}).sortName || '';
const sortName2 = (this.users[userID2] || {}).sortName || '';
2020-05-09 14:02:07 +02:00
return sortName1.localeCompare(sortName2);
});
/* contactsList.sort((userID1: number, userID2: number) => {
const sortName1 = (this.users[userID1] || {}).sortName || '';
const sortName2 = (this.users[userID2] || {}).sortName || '';
if(sortName1 == sortName2) {
return 0;
2020-05-09 14:02:07 +02:00
}
return sortName1 > sortName2 ? 1 : -1;
2020-05-09 14:02:07 +02:00
}); */
2020-02-06 16:43:07 +01:00
return contactsList;
});
}
2020-02-06 16:43:07 +01:00
public saveApiUsers(apiUsers: any[]) {
apiUsers.forEach((user) => this.saveApiUser(user));
2020-02-06 16:43:07 +01:00
}
2020-10-17 00:31:58 +02:00
public saveApiUser(_user: MTUser, noReplace?: boolean) {
if(_user._ == 'userEmpty') return;
const user = _user;
if(noReplace && isObject(this.users[user.id]) && this.users[user.id].first_name) {
2020-02-06 16:43:07 +01:00
return;
}
2020-10-17 00:31:58 +02:00
var userID = user.id;
2020-02-06 16:43:07 +01:00
var result = this.users[userID];
2020-10-17 00:31:58 +02:00
if(user.pFlags === undefined) {
user.pFlags = {};
2020-02-06 16:43:07 +01:00
}
2020-10-17 00:31:58 +02:00
if(user.pFlags.min) {
2020-02-06 16:43:07 +01:00
if(result !== undefined) {
return;
}
}
2020-10-17 00:31:58 +02:00
// * exclude from state
// defineNotNumerableProperties(user, ['initials', 'num', 'rFirstName', 'rFullName', 'rPhone', 'sortName', 'sortStatus']);
2020-10-17 00:31:58 +02:00
if(user.phone) {
user.rPhone = '+' + formatPhoneNumber(user.phone).formatted;
2020-02-06 16:43:07 +01:00
}
2020-10-17 00:31:58 +02:00
const fullName = user.first_name + ' ' + (user.last_name || '');
if(user.first_name) {
user.rFirstName = RichTextProcessor.wrapRichText(user.first_name, {noLinks: true, noLinebreaks: true})
user.rFullName = user.last_name ? RichTextProcessor.wrapRichText(fullName, {noLinks: true, noLinebreaks: true}) : user.rFirstName;
2020-02-06 16:43:07 +01:00
} else {
2020-10-17 00:31:58 +02:00
user.rFirstName = RichTextProcessor.wrapRichText(user.last_name, {noLinks: true, noLinebreaks: true}) || user.rPhone || 'user_first_name_deleted';
user.rFullName = RichTextProcessor.wrapRichText(user.last_name, {noLinks: true, noLinebreaks: true}) || user.rPhone || 'user_name_deleted';
2020-02-06 16:43:07 +01:00
}
2020-10-17 00:31:58 +02:00
if(user.username) {
var searchUsername = searchIndexManager.cleanUsername(user.username);
2020-02-06 16:43:07 +01:00
this.usernames[searchUsername] = userID;
}
2020-10-17 00:31:58 +02:00
user.sortName = user.pFlags.deleted ? '' : searchIndexManager.cleanSearchText(fullName, false);
2020-02-06 16:43:07 +01:00
2020-10-29 17:26:08 +01:00
user.initials = RichTextProcessor.getAbbreviation(fullName);
2020-02-06 16:43:07 +01:00
2020-10-17 00:31:58 +02:00
if(user.status) {
if((user.status as UserStatus.userStatusOnline).expires) {
(user.status as UserStatus.userStatusOnline).expires -= serverTimeManager.serverTimeOffset
2020-02-06 16:43:07 +01:00
}
2020-10-17 00:31:58 +02:00
if((user.status as UserStatus.userStatusOffline).was_online) {
(user.status as UserStatus.userStatusOffline).was_online -= serverTimeManager.serverTimeOffset
2020-02-06 16:43:07 +01:00
}
}
2020-10-17 00:31:58 +02:00
if(user.pFlags.bot) {
user.sortStatus = -1;
2020-02-06 16:43:07 +01:00
} else {
2020-10-17 00:31:58 +02:00
user.sortStatus = this.getUserStatusForSort(user.status);
2020-02-06 16:43:07 +01:00
}
var result = this.users[userID];
if(result === undefined) {
2020-10-17 00:31:58 +02:00
result = this.users[userID] = user;
2020-02-06 16:43:07 +01:00
} else {
2020-10-17 00:31:58 +02:00
safeReplaceObject(result, user);
2020-02-06 16:43:07 +01:00
}
$rootScope.$broadcast('user_update', userID);
if(this.cachedPhotoLocations[userID] !== undefined) {
2020-10-17 00:31:58 +02:00
safeReplaceObject(this.cachedPhotoLocations[userID], user &&
user.photo ? user.photo : {empty: true});
2020-02-06 16:43:07 +01:00
}
}
/* public saveUserAccess(id: number, accessHash: string) {
2020-02-06 16:43:07 +01:00
this.userAccess[id] = accessHash;
} */
2020-02-06 16:43:07 +01:00
public getUserStatusForSort(status: User['status']) {
2020-02-06 16:43:07 +01:00
if(status) {
const expires = status._ == 'userStatusOnline' ? status.expires : (status._ == 'userStatusOffline' ? status.was_online : 0);
2020-02-06 16:43:07 +01:00
if(expires) {
return expires;
}
const timeNow = tsNow(true);
switch(status._) {
2020-02-06 16:43:07 +01:00
case 'userStatusRecently':
return timeNow - 86400 * 3;
case 'userStatusLastWeek':
return timeNow - 86400 * 7;
case 'userStatusLastMonth':
return timeNow - 86400 * 30;
}
}
return 0;
}
public getUser(id: any): User {
2020-02-06 16:43:07 +01:00
if(isObject(id)) {
return id;
}
return this.users[id] || {id: id, pFlags: {deleted: true}, access_hash: ''/* this.userAccess[id] */} as User;
2020-02-06 16:43:07 +01:00
}
public getSelf() {
return this.getUser($rootScope.myID);
2020-02-06 16:43:07 +01:00
}
public getUserStatusString(userID: number) {
if(this.isBot(userID)) {
return 'bot';
}
2020-06-19 13:49:55 +02:00
const user = this.getUser(userID);
if(!user) {
return '';
}
let str = '';
2020-06-19 13:49:55 +02:00
switch(user.status?._) {
case 'userStatusRecently': {
str = 'last seen recently';
break;
}
case 'userStatusLastWeek': {
str = 'last seen last week';
break;
}
case 'userStatusLastMonth': {
str = 'last seen last month';
break;
}
case 'userStatusOffline': {
str = 'last seen ';
2020-06-19 13:49:55 +02:00
const date = user.status.was_online;
const now = Date.now() / 1000;
if((now - date) < 60) {
str += ' just now';
} else if((now - date) < 3600) {
2020-06-19 13:49:55 +02:00
const c = (now - date) / 60 | 0;
str += c + ' ' + (c == 1 ? 'minute' : 'minutes') + ' ago';
} else if(now - date < 86400) {
2020-06-19 13:49:55 +02:00
const c = (now - date) / 3600 | 0;
str += c + ' ' + (c == 1 ? 'hour' : 'hours') + ' ago';
} else {
2020-06-19 13:49:55 +02:00
const d = new Date(date * 1000);
str += ('0' + d.getDate()).slice(-2) + '.' + ('0' + (d.getMonth() + 1)).slice(-2) + ' at ' +
('0' + d.getHours()).slice(-2) + ':' + ('0' + d.getMinutes()).slice(-2);
}
break;
}
case 'userStatusOnline': {
str = 'online';
break;
}
2020-06-19 13:49:55 +02:00
default: {
str = 'last seen a long time ago';
break;
}
}
return str;
}
2020-02-06 16:43:07 +01:00
public isBot(id: number) {
return this.users[id] && this.users[id].pFlags.bot;
}
2020-08-31 18:48:46 +02:00
public isContact(id: number) {
return this.contactsList.has(id);
}
public isRegularUser(id: number) {
const user = this.users[id];
return user && !this.isBot(id) && !user.pFlags.deleted && !user.pFlags.support;
}
public isNonContactUser(id: number) {
return this.isRegularUser(id) && !this.isContact(id) && id != $rootScope.myID;
}
2020-02-06 16:43:07 +01:00
public hasUser(id: number, allowMin?: boolean) {
var user = this.users[id];
return isObject(user) && (allowMin || !user.pFlags.min);
}
public canSendToUser(id: number) {
const user = this.getUser(id);
return !user.pFlags.deleted;
}
2020-02-06 16:43:07 +01:00
public getUserPhoto(id: number) {
var user = this.getUser(id);
if(this.cachedPhotoLocations[id] === undefined) {
this.cachedPhotoLocations[id] = user && user.photo ? user.photo : {empty: true};
}
return this.cachedPhotoLocations[id];
}
/* public getUserString(id: number) {
const user = this.getUser(id);
2020-02-06 16:43:07 +01:00
return 'u' + id + (user.access_hash ? '_' + user.access_hash : '');
} */
2020-02-06 16:43:07 +01:00
public getUserInput(id: number): InputUser {
const user = this.getUser(id);
if(user.pFlags && user.pFlags.self) {
2020-02-06 16:43:07 +01:00
return {_: 'inputUserSelf'};
}
return {
_: 'inputUser',
user_id: id,
access_hash: user.access_hash
2020-02-06 16:43:07 +01:00
};
}
public updateUsersStatuses = () => {
const timestampNow = tsNow(true);
for(const i in this.users) {
const user = this.users[i];
2020-02-06 16:43:07 +01:00
if(user.status &&
user.status._ == 'userStatusOnline' &&
user.status.expires < timestampNow) {
user.status = {_: 'userStatusOffline', was_online: user.status.expires};
2020-02-06 16:43:07 +01:00
$rootScope.$broadcast('user_update', user.id);
}
}
};
2020-02-06 16:43:07 +01:00
public forceUserOnline(id: number) {
if(this.isBot(id)) {
return;
}
const user = this.getUser(id);
2020-02-06 16:43:07 +01:00
if(user &&
user.status &&
user.status._ != 'userStatusOnline' &&
user.status._ != 'userStatusEmpty' &&
!user.pFlags.support &&
!user.pFlags.deleted) {
2020-02-06 16:43:07 +01:00
user.status = {
_: 'userStatusOnline',
expires: tsNow(true) + 60
2020-02-06 16:43:07 +01:00
};
2020-02-06 16:43:07 +01:00
user.sortStatus = this.getUserStatusForSort(user.status);
$rootScope.$broadcast('user_update', id);
}
}
/* function importContact (phone, firstName, lastName) {
return MtpApiManager.invokeApi('contacts.importContacts', {
contacts: [{
_: 'inputPhoneContact',
client_id: '1',
phone: phone,
first_name: firstName,
last_name: lastName
}],
replace: false
}).then(function (importedContactsResult) {
saveApiUsers(importedContactsResult.users)
var foundUserID = false
angular.forEach(importedContactsResult.imported, function (importedContact) {
onContactUpdated(foundUserID = importedContact.user_id, true)
})
return foundUserID || false
})
}
function importContacts (contacts) {
var inputContacts = [],
i
var j
for (i = 0; i < contacts.length; i++) {
for (j = 0; j < contacts[i].phones.length; j++) {
inputContacts.push({
_: 'inputPhoneContact',
client_id: (i << 16 | j).toString(10),
phone: contacts[i].phones[j],
first_name: contacts[i].first_name,
last_name: contacts[i].last_name
})
}
}
return MtpApiManager.invokeApi('contacts.importContacts', {
contacts: inputContacts,
replace: false
}).then(function (importedContactsResult) {
saveApiUsers(importedContactsResult.users)
var result = []
angular.forEach(importedContactsResult.imported, function (importedContact) {
onContactUpdated(importedContact.user_id, true)
result.push(importedContact.user_id)
})
return result
})
} */
2020-08-31 18:48:46 +02:00
/* public deleteContacts(userIDs: number[]) {
2020-02-06 16:43:07 +01:00
var ids: any[] = [];
userIDs.forEach((userID) => {
ids.push(this.getUserInput(userID));
})
return apiManager.invokeApi('contacts.deleteContacts', {
2020-02-06 16:43:07 +01:00
id: ids
}).then(() => {
userIDs.forEach((userID) => {
this.onContactUpdated(userID, false);
});
});
2020-08-31 18:48:46 +02:00
} */
2020-02-06 16:43:07 +01:00
2020-06-20 03:11:24 +02:00
public getTopPeers(): Promise<number[]> {
if(this.getTopPeersPromise) return this.getTopPeersPromise;
return this.getTopPeersPromise = appStateManager.getState().then((state) => {
2020-06-20 03:11:24 +02:00
if(state?.topPeers?.length) {
return state.topPeers;
}
return apiManager.invokeApi('contacts.getTopPeers', {
correspondents: true,
offset: 0,
limit: 30,
hash: 0,
}).then((result) => {
let peerIDs: number[];
if(result._ == 'contacts.topPeers') {
//console.log(result);
this.saveApiUsers(result.users);
appChatsManager.saveApiChats(result.chats);
peerIDs = result.categories[0].peers.map((topPeer) => {
const peerID = appPeersManager.getPeerID(topPeer.peer);
appStateManager.setPeer(peerID, this.getUser(peerID));
return peerID;
});
}
2020-06-20 03:11:24 +02:00
appStateManager.pushToState('topPeers', peerIDs);
return peerIDs;
});
});
}
public searchContacts(query: string, limit = 20) {
return apiManager.invokeApi('contacts.search', {
q: query,
limit
}).then((peers) => {
2020-11-06 23:20:30 +01:00
//console.log('search contacts result:', peers);
this.saveApiUsers(peers.users);
appChatsManager.saveApiChats(peers.chats);
return peers;
});
}
2020-08-31 18:48:46 +02:00
/* public onContactUpdated(userID: number, isContact: boolean) {
2020-02-06 16:43:07 +01:00
userID = parseInt('' + userID);
if(Array.isArray(this.contactsList)) {
var curPos = this.contactsList.indexOf(userID);
var curIsContact = curPos != -1;
if(isContact != curIsContact) {
if(isContact) {
this.contactsList.push(userID)
searchIndexManager.indexObject(userID, this.getUserSearchText(userID), this.contactsIndex);
2020-02-06 16:43:07 +01:00
} else {
this.contactsList.splice(curPos, 1);
}
$rootScope.$broadcast('contacts_update', userID);
}
}
2020-08-31 18:48:46 +02:00
} */
2020-02-06 16:43:07 +01:00
public setUserStatus(userID: number, offline: boolean) {
if(this.isBot(userID)) {
return;
}
const user = this.users[userID];
2020-02-06 16:43:07 +01:00
if(user) {
const status: any = offline ? {
2020-02-06 16:43:07 +01:00
_: 'userStatusOffline',
was_online: tsNow(true)
} : {
_: 'userStatusOnline',
expires: tsNow(true) + 500
};
user.status = status;
user.sortStatus = this.getUserStatusForSort(user.status);
$rootScope.$broadcast('user_update', userID);
}
}
}
export default new AppUsersManager();