diff --git a/dev/tlHash.js b/dev/tlHash.js new file mode 100644 index 000000000..af812f90c --- /dev/null +++ b/dev/tlHash.js @@ -0,0 +1,69 @@ +const fs = require('fs'); +const path = require('path'); + +const API_TL_PATH = path.resolve('./src/lib/gramjs/tl/static/api.tl'); + +function rehash() { + const data = fs.readFileSync(API_TL_PATH, 'utf8'); + + const lines = data.split('\n'); + // eslint-disable-next-line no-console + console.log(`Read ${lines.length} lines`); + + const resultLines = []; + + for (const line of lines) { + // Skip comments and namespaces + if (line.startsWith('//') || !line.endsWith(';') || !line.includes('=')) { + resultLines.push(line); + continue; + } + + const hash = getHash(line); + + const params = line.split(' '); + const name = params[0].split('#')[0]; + const rehashed = [`${name}#${hash}`, ...params.slice(1)].join(' '); + + resultLines.push(rehashed); + } + // eslint-disable-next-line no-console + console.log(`Writing ${resultLines.length} lines`); + + fs.writeFileSync(API_TL_PATH, resultLines.join('\n')); +} + +function getHash(line) { + line = line.replace(/;/g, ''); + const split = line.split(' '); + const cleaned = []; + cleaned.push(split[0].split('#')[0]); // Drop current hash + for (let i = 1; i < split.length; i++) { + let param = split[i]; + if (param.includes('?true')) continue; // Skip optional boolean flags + param = param.replace(/bytes(?![:>])/, 'string'); // Bytes are strings, but not in Vector + cleaned.push(param.replace(/[<>(){}]/g, ' ')); // Drop parenthesis + } + + // Join and clean spaces + const cleanedLine = cleaned.join(' ') + .replace(/\s{2,}/g, ' ') + .trim(); + return crc32(cleanedLine); +} + +/* eslint-disable */ +const a_table = '00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D'; +const b_table = a_table.split(' ').map((s) => parseInt(s, 16)); + +function crc32(str) { + let crc = -1; + for (let i = 0, iTop = str.length; i < iTop; i++) { + crc = (crc >>> 8) ^ b_table[(crc ^ str.charCodeAt(i)) & 0xFF]; + } + return ((crc ^ (-1)) >>> 0).toString(16); +} + +/* eslint-enable */ + +rehash(); diff --git a/package.json b/package.json index 14da9b99c..4f0137fd2 100644 --- a/package.json +++ b/package.json @@ -17,6 +17,7 @@ "telegraph:update_changelog": "node ./dev/telegraphChangelog.js", "check": "tsc && stylelint \"**/*.{css,scss}\" && eslint . --ext .ts,.tsx,.js --ignore-pattern src/lib/gramjs", "check:fix": "npm run check -- --fix", + "tl:rehash": "node ./dev/tlHash.js", "gramjs:tl": "node ./src/lib/gramjs/tl/generateModules.js", "gramjs:lint": "eslint src/lib/gramjs --ext .ts,.tsx,.js", "gramjs:lint:fix": "npm run gramjs:lint -- --fix", diff --git a/src/api/gramjs/apiBuilders/messages.ts b/src/api/gramjs/apiBuilders/messages.ts index cb1480b85..c185df4cf 100644 --- a/src/api/gramjs/apiBuilders/messages.ts +++ b/src/api/gramjs/apiBuilders/messages.ts @@ -24,7 +24,7 @@ import type { ApiGroupCall, ApiReactions, ApiReactionCount, - ApiUserReaction, + ApiPeerReaction, ApiAvailableReaction, ApiSponsoredMessage, ApiUser, @@ -277,20 +277,21 @@ function buildReactionCount(reactionCount: GramJs.ReactionCount): ApiReactionCou }; } -export function buildMessagePeerReaction(userReaction: GramJs.MessagePeerReaction): ApiUserReaction | undefined { +export function buildMessagePeerReaction(userReaction: GramJs.MessagePeerReaction): ApiPeerReaction | undefined { const { - peerId, reaction, big, unread, date, + peerId, reaction, big, unread, date, my, } = userReaction; const apiReaction = buildApiReaction(reaction); if (!apiReaction) return undefined; return { - userId: getApiChatIdFromMtpPeer(peerId), + peerId: getApiChatIdFromMtpPeer(peerId), reaction: apiReaction, addedDate: date, isUnread: unread, isBig: big, + isOwn: my, }; } @@ -833,7 +834,7 @@ export function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['resu const { results: rawResults, totalVoters, recentVoters, solution, solutionEntities: entities, min, } = pollResults; - const results = rawResults && rawResults.map(({ + const results = rawResults?.map(({ option, chosen, correct, voters, }) => ({ isChosen: chosen, @@ -845,7 +846,7 @@ export function buildPollResults(pollResults: GramJs.PollResults): ApiPoll['resu return { isMin: min, totalVoters, - recentVoterIds: recentVoters?.map((id) => buildApiPeerId(id, 'user')), + recentVoterIds: recentVoters?.map((peer) => getApiChatIdFromMtpPeer(peer)), results, solution, ...(entities && { solutionEntities: entities.map(buildApiMessageEntity) }), diff --git a/src/api/gramjs/methods/messages.ts b/src/api/gramjs/methods/messages.ts index ff00d4188..4bd237afb 100644 --- a/src/api/gramjs/methods/messages.ts +++ b/src/api/gramjs/methods/messages.ts @@ -1241,20 +1241,22 @@ export async function loadPollOptionResults({ } updateLocalDb({ - chats: [] as GramJs.TypeChat[], + chats: result.chats, users: result.users, messages: [] as GramJs.Message[], } as GramJs.messages.Messages); const users = result.users.map(buildApiUser).filter(Boolean); + const chats = result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean); const votes = result.votes.map((vote) => ({ - userId: vote.userId, + peerId: getApiChatIdFromMtpPeer(vote.peer), date: vote.date, })); return { count: result.count, votes, + chats, users, nextOffset: result.nextOffset, shouldResetVoters, diff --git a/src/api/gramjs/methods/reactions.ts b/src/api/gramjs/methods/reactions.ts index 8e78ab881..662347cbe 100644 --- a/src/api/gramjs/methods/reactions.ts +++ b/src/api/gramjs/methods/reactions.ts @@ -10,6 +10,7 @@ import { buildApiAvailableReaction, buildApiReaction, buildMessagePeerReaction } import { invokeRequest } from './client'; import localDb from '../localDb'; import { addEntitiesToLocalDb } from '../helpers'; +import { buildApiChatFromPreview } from '../apiBuilders/chats'; export function sendWatchingEmojiInteraction({ chat, @@ -134,11 +135,13 @@ export async function fetchMessageReactionsList({ } addEntitiesToLocalDb(result.users); + addEntitiesToLocalDb(result.chats); const { nextOffset, reactions, count } = result; return { users: result.users.map(buildApiUser).filter(Boolean), + chats: result.chats.map((c) => buildApiChatFromPreview(c)).filter(Boolean), nextOffset, reactions: reactions.map(buildMessagePeerReaction).filter(Boolean), count, diff --git a/src/api/gramjs/updater.ts b/src/api/gramjs/updater.ts index 8835c0bc3..e9aa623a0 100644 --- a/src/api/gramjs/updater.ts +++ b/src/api/gramjs/updater.ts @@ -492,7 +492,7 @@ export function updater(update: Update) { onUpdate({ '@type': 'updateMessagePollVote', pollId: String(update.pollId), - userId: buildApiPeerId(update.userId, 'user'), + peerId: getApiChatIdFromMtpPeer(update.peer), options: update.options.map(serializeBytes), }); } else if (update instanceof GramJs.UpdateChannelMessageViews) { diff --git a/src/api/types/messages.ts b/src/api/types/messages.ts index bb1972f66..e728ce0c7 100644 --- a/src/api/types/messages.ts +++ b/src/api/types/messages.ts @@ -438,7 +438,7 @@ export interface ApiMessage { reactors?: { nextOffset?: string; count: number; - reactions: ApiUserReaction[]; + reactions: ApiPeerReaction[]; }; reactions?: ApiReactions; } @@ -446,12 +446,13 @@ export interface ApiMessage { export interface ApiReactions { canSeeList?: boolean; results: ApiReactionCount[]; - recentReactions?: ApiUserReaction[]; + recentReactions?: ApiPeerReaction[]; } -export interface ApiUserReaction { - userId: string; +export interface ApiPeerReaction { + peerId: string; reaction: ApiReaction; + isOwn?: boolean; isBig?: boolean; isUnread?: boolean; addedDate: number; diff --git a/src/api/types/updates.ts b/src/api/types/updates.ts index e3c9ceee5..f113f71de 100644 --- a/src/api/types/updates.ts +++ b/src/api/types/updates.ts @@ -269,7 +269,7 @@ export type ApiUpdateMessagePoll = { export type ApiUpdateMessagePollVote = { '@type': 'updateMessagePollVote'; pollId: string; - userId: string; + peerId: string; options: string[]; }; diff --git a/src/components/common/GroupChatInfo.tsx b/src/components/common/GroupChatInfo.tsx index f5f3d19fa..870cb0e20 100644 --- a/src/components/common/GroupChatInfo.tsx +++ b/src/components/common/GroupChatInfo.tsx @@ -39,7 +39,7 @@ type OwnProps = { threadId?: number; className?: string; typingStatus?: ApiTypingStatus; - avatarSize?: 'small' | 'medium' | 'large' | 'jumbo'; + avatarSize?: 'tiny' | 'small' | 'medium' | 'large' | 'jumbo'; status?: string; withDots?: boolean; withMediaViewer?: boolean; @@ -49,6 +49,7 @@ type OwnProps = { withChatType?: boolean; noRtl?: boolean; noAvatar?: boolean; + noStatusOrTyping?: boolean; onClick?: VoidFunction; }; @@ -81,6 +82,7 @@ const GroupChatInfo: FC = ({ areMessagesLoaded, topic, messagesCount, + noStatusOrTyping, onClick, }) => { const { @@ -197,7 +199,7 @@ const GroupChatInfo: FC = ({ {topic ?

{renderText(topic.title)}

: } - {renderStatusOrTyping()} + {!noStatusOrTyping && renderStatusOrTyping()} ); diff --git a/src/components/common/helpers/renderText.tsx b/src/components/common/helpers/renderText.tsx index 76f2e1a65..40b9f2fe5 100644 --- a/src/components/common/helpers/renderText.tsx +++ b/src/components/common/helpers/renderText.tsx @@ -5,7 +5,7 @@ import type { TextPart } from '../../../types'; import EMOJI_REGEX from '../../../lib/twemojiRegex'; import { - RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE, IS_ELECTRON, PRODUCTION_URL, + IS_ELECTRON, PRODUCTION_URL, RE_LINK_TEMPLATE, RE_MENTION_TEMPLATE, } from '../../../config'; import { IS_EMOJI_SUPPORTED } from '../../../util/windowEnvironment'; import { @@ -109,35 +109,38 @@ function replaceEmojis(textParts: TextPart[], size: 'big' | 'small', type: 'jsx' return emojis.reduce((emojiResult: TextPart[], emoji, i) => { const code = nativeToUnifiedExtendedWithCache(emoji); - if (!code) return emojiResult; - const src = `${IS_ELECTRON ? PRODUCTION_URL : '.'}/img-apple-${size === 'big' ? '160' : '64'}/${code}.png`; - const className = buildClassName( - 'emoji', - size === 'small' && 'emoji-small', - ); - - if (type === 'jsx') { - const isLoaded = LOADED_EMOJIS.has(src); - - emojiResult.push( - {emoji}, + if (!code) { + emojiResult.push(emoji); + } else { + const src = `${IS_ELECTRON ? PRODUCTION_URL : '.'}/img-apple-${size === 'big' ? '160' : '64'}/${code}.png`; + const className = buildClassName( + 'emoji', + size === 'small' && 'emoji-small', ); - } - if (type === 'html') { - emojiResult.push( - `, + ); + } + if (type === 'html') { + emojiResult.push( + ``, - ); + ); + } } const index = i * 2 + 2; diff --git a/src/components/middle/ReactorListModal.tsx b/src/components/middle/ReactorListModal.tsx index aeeea9672..fe029e476 100644 --- a/src/components/middle/ReactorListModal.tsx +++ b/src/components/middle/ReactorListModal.tsx @@ -1,17 +1,20 @@ import type { FC } from '../../lib/teact/teact'; import React, { - memo, useEffect, useMemo, useRef, useState, + memo, useMemo, useEffect, useState, useRef, } from '../../lib/teact/teact'; import { getActions, getGlobal, withGlobal } from '../../global'; import type { ApiAvailableReaction, ApiMessage, ApiReaction } from '../../api/types'; import { LoadMoreDirection } from '../../types'; -import { selectChatMessage, selectTabState } from '../../global/selectors'; +import { + selectChatMessage, + selectTabState, +} from '../../global/selectors'; import buildClassName from '../../util/buildClassName'; import { formatIntegerCompact } from '../../util/textFormat'; import { unique } from '../../util/iteratees'; -import { getReactionUniqueKey, isSameReaction } from '../../global/helpers'; +import { isSameReaction, getReactionUniqueKey } from '../../global/helpers'; import { formatDateAtTime } from '../../util/dateFormat'; import useLang from '../../hooks/useLang'; @@ -58,9 +61,9 @@ const ReactorListModal: FC = ({ openChat, } = getActions(); - // No need for expensive global updates on users, so we avoid them - const usersById = getGlobal().users.byId; + // No need for expensive global updates on chats or users, so we avoid them const chatsById = getGlobal().chats.byId; + const usersById = getGlobal().users.byId; const lang = useLang(); const [isClosing, startClosing, stopClosing] = useFlag(false); @@ -113,20 +116,20 @@ const ReactorListModal: FC = ({ return uniqueReactions; }, [reactors]); - const userIds = useMemo(() => { + const peerIds = useMemo(() => { if (chosenTab) { return reactors?.reactions .filter(({ reaction }) => isSameReaction(reaction, chosenTab)) - .map(({ userId }) => userId); + .map(({ peerId }) => peerId); } const seenByUserIds = Object.keys(seenByDates || {}); - return unique(reactors?.reactions.map(({ userId }) => userId).concat(seenByUserIds || []) || []); + return unique(reactors?.reactions.map(({ peerId }) => peerId).concat(seenByUserIds || []) || []); }, [chosenTab, reactors, seenByDates]); const [viewportIds, getMore] = useInfiniteScroll( - handleLoadMore, userIds, reactors && reactors.nextOffset === undefined, + handleLoadMore, peerIds, reactors && reactors.nextOffset === undefined, ); useEffect(() => { @@ -188,11 +191,11 @@ const ReactorListModal: FC = ({ (peerId) => { const peer = usersById[peerId] || chatsById[peerId]; - const userReactions = reactors?.reactions.filter((reactor) => reactor.userId === peerId); + const peerReactions = reactors?.reactions.filter((reactor) => reactor.peerId === peerId); const items: React.ReactNode[] = []; const seenByUser = seenByDates?.[peerId]; - userReactions?.forEach((r) => { + peerReactions?.forEach((r) => { if (chosenTab && !isSameReaction(r.reaction, chosenTab)) return; items.push( @@ -221,7 +224,7 @@ const ReactorListModal: FC = ({ ); }); - if (!chosenTab && !userReactions?.length) { + if (!chosenTab && !peerReactions?.length) { items.push( = ({ } }, [hasFullInfo, isOpen, isPrivate, loadFullChat, message.chatId]); - const seenByRecentUsers = useMemo(() => { + const seenByRecentPeers = useMemo(() => { + // No need for expensive global updates on chats or users, so we avoid them + const chatsById = getGlobal().chats.byId; + const usersById = getGlobal().users.byId; if (message.reactions?.recentReactions?.length) { - // No need for expensive global updates on users, so we avoid them - const usersById = getGlobal().users.byId; - - const uniqueReactors = new Set(message.reactions?.recentReactions?.map(({ userId }) => usersById[userId])); + const uniqueReactors = new Set(message.reactions?.recentReactions?.map( + ({ peerId }) => usersById[peerId] || chatsById[peerId], + )); return Array.from(uniqueReactors).filter(Boolean).slice(0, 3); } @@ -250,9 +252,7 @@ const ContextMenuContainer: FC = ({ return undefined; } - // No need for expensive global updates on users, so we avoid them - const usersById = getGlobal().users.byId; - return Object.keys(message.seenByDates).slice(0, 3).map((id) => usersById[id]).filter(Boolean); + return Object.keys(message.seenByDates).slice(0, 3).map((id) => usersById[id] || chatsById[id]).filter(Boolean); }, [message.reactions?.recentReactions, message.seenByDates]); const isDownloading = useMemo(() => { @@ -517,7 +517,7 @@ const ContextMenuContainer: FC = ({ hasCustomEmoji={hasCustomEmoji} customEmojiSets={customEmojiSets} isDownloading={isDownloading} - seenByRecentUsers={seenByRecentUsers} + seenByRecentPeers={seenByRecentPeers} noReplies={noReplies} onOpenThread={handleOpenThread} onReply={handleReply} diff --git a/src/components/middle/message/MessageContextMenu.tsx b/src/components/middle/message/MessageContextMenu.tsx index e7f0803aa..347faf3c1 100644 --- a/src/components/middle/message/MessageContextMenu.tsx +++ b/src/components/middle/message/MessageContextMenu.tsx @@ -6,6 +6,7 @@ import { getActions } from '../../../global'; import type { FC } from '../../../lib/teact/teact'; import type { ApiAvailableReaction, + ApiChat, ApiChatReactions, ApiMessage, ApiReaction, @@ -19,9 +20,9 @@ import type { IAnchorPosition } from '../../../types'; import { REM } from '../../common/helpers/mediaDimensions'; import { getMessageCopyOptions } from './helpers/copyOptions'; import { disableScrolling, enableScrolling } from '../../../util/scrollLock'; -import { getUserFullName } from '../../../global/helpers'; import buildClassName from '../../../util/buildClassName'; import renderText from '../../common/helpers/renderText'; +import { getUserFullName, isUserId } from '../../../global/helpers'; import useLastCallback from '../../../hooks/useLastCallback'; import useFlag from '../../../hooks/useFlag'; @@ -77,7 +78,7 @@ type OwnProps = { canClosePoll?: boolean; isDownloading?: boolean; canShowSeenBy?: boolean; - seenByRecentUsers?: ApiUser[]; + seenByRecentPeers?: (ApiChat | ApiUser)[]; noReplies?: boolean; hasCustomEmoji?: boolean; customEmojiSets?: ApiStickerSet[]; @@ -162,7 +163,7 @@ const MessageContextMenu: FC = ({ canShowSeenBy, canShowReactionsCount, canShowReactionList, - seenByRecentUsers, + seenByRecentPeers, hasCustomEmoji, customEmojiSets, canPlayAnimatedEmojis, @@ -403,8 +404,12 @@ const MessageContextMenu: FC = ({ ) : lang('Chat.ContextReactionCount', message.reactors.count, 'i') ) : ( - seenByDatesCount === 1 && seenByRecentUsers - ? renderText(getUserFullName(seenByRecentUsers[0] as ApiUser)!) : ( + seenByDatesCount === 1 && seenByRecentPeers + ? renderText( + isUserId(seenByRecentPeers[0].id) + ? getUserFullName(seenByRecentPeers[0] as ApiUser)! + : (seenByRecentPeers[0] as ApiChat).title, + ) : ( seenByDatesCount ? lang('Conversation.ContextMenuSeen', seenByDatesCount, 'i') : lang('Conversation.ContextMenuNoViews') @@ -412,7 +417,7 @@ const MessageContextMenu: FC = ({ )} - + )} {canDelete && {lang('Delete')}} diff --git a/src/components/middle/message/Poll.tsx b/src/components/middle/message/Poll.tsx index fccd0d9d1..64a01210f 100644 --- a/src/components/middle/message/Poll.tsx +++ b/src/components/middle/message/Poll.tsx @@ -1,4 +1,3 @@ -import type { FC } from '../../../lib/teact/teact'; import React, { useEffect, useLayoutEffect, @@ -7,16 +6,17 @@ import React, { useMemo, useRef, } from '../../../lib/teact/teact'; -import { getActions, withGlobal } from '../../../global'; +import { getActions, getGlobal, withGlobal } from '../../../global'; +import type { FC } from '../../../lib/teact/teact'; +import type { LangFn } from '../../../hooks/useLang'; import type { - ApiMessage, ApiPoll, ApiUser, ApiPollAnswer, + ApiMessage, ApiPoll, ApiPollAnswer, ApiChat, ApiUser, } from '../../../api/types'; import renderText from '../../common/helpers/renderText'; import { renderTextWithEntities } from '../../common/helpers/renderTextWithEntities'; import { formatMediaDuration } from '../../../util/dateFormat'; -import type { LangFn } from '../../../hooks/useLang'; import useLang from '../../../hooks/useLang'; import { getServerTime } from '../../../util/serverTime'; @@ -39,7 +39,6 @@ type OwnProps = { type StateProps = { recentVoterIds?: number[]; - usersById: Record; }; const SOLUTION_CONTAINER_ID = '#middle-column-portals'; @@ -53,7 +52,6 @@ const Poll: FC = ({ message, poll, recentVoterIds, - usersById, onSendVote, }) => { const { loadMessage, openPollResults, requestConfetti } = getActions(); @@ -136,15 +134,21 @@ const Poll: FC = ({ }, [canVote, chatId, loadMessage, messageId, summary.closePeriod, summary.closed, summary.quiz]); const recentVoters = useMemo(() => { - return recentVoterIds ? recentVoterIds.reduce((result: ApiUser[], id) => { + // No need for expensive global updates on chats or users, so we avoid them + const chatsById = getGlobal().chats.byId; + const usersById = getGlobal().users.byId; + return recentVoterIds ? recentVoterIds.reduce((result: (ApiChat | ApiUser)[], id) => { + const chat = chatsById[id]; const user = usersById[id]; if (user) { result.push(user); + } else if (chat) { + result.push(chat); } return result; }, []) : []; - }, [usersById, recentVoterIds]); + }, [recentVoterIds]); const handleRadioChange = useLastCallback((option: string) => { setChosenOptions([option]); @@ -206,11 +210,11 @@ const Poll: FC = ({ return ( recentVoters.length > 0 && (
- {recentVoters.map((user) => ( + {recentVoters.map((peer) => ( ))}
diff --git a/src/components/middle/message/ReactionButton.tsx b/src/components/middle/message/ReactionButton.tsx index 4e4d7c13b..598e33950 100644 --- a/src/components/middle/message/ReactionButton.tsx +++ b/src/components/middle/message/ReactionButton.tsx @@ -4,7 +4,7 @@ import { getActions, getGlobal } from '../../../global'; import type { FC } from '../../../lib/teact/teact'; import type { ObserveFn } from '../../../hooks/useIntersectionObserver'; import type { - ApiAvailableReaction, ApiMessage, ApiReactionCount, ApiStickerSet, ApiUser, + ApiAvailableReaction, ApiChat, ApiMessage, ApiReactionCount, ApiStickerSet, ApiUser, } from '../../../api/types'; import type { ActiveReaction } from '../../../global/types'; @@ -48,13 +48,14 @@ const ReactionButton: FC<{ return undefined; } - // No need for expensive global updates on users, so we avoid them + // No need for expensive global updates on chats or users, so we avoid them + const chatsById = getGlobal().chats.byId; const usersById = getGlobal().users.byId; return recentReactions .filter((recentReaction) => isSameReaction(recentReaction.reaction, reaction.reaction)) - .map((recentReaction) => usersById[recentReaction.userId]) - .filter(Boolean) as ApiUser[]; + .map((recentReaction) => usersById[recentReaction.peerId] || chatsById[recentReaction.peerId]) + .filter(Boolean) as (ApiChat | ApiUser)[]; }, [reaction.reaction, recentReactions, withRecentReactors]); const handleClick = useLastCallback(() => { diff --git a/src/components/right/PollAnswerResults.tsx b/src/components/right/PollAnswerResults.tsx index b2e8c273c..4c01abc59 100644 --- a/src/components/right/PollAnswerResults.tsx +++ b/src/components/right/PollAnswerResults.tsx @@ -11,6 +11,7 @@ import type { ApiPollResult, } from '../../api/types'; import { selectTabState } from '../../global/selectors'; +import { isUserId } from '../../global/helpers'; import usePrevious from '../../hooks/usePrevious'; import useLang from '../../hooks/useLang'; @@ -18,6 +19,7 @@ import ShowMoreButton from '../ui/ShowMoreButton'; import Loading from '../ui/Loading'; import ListItem from '../ui/ListItem'; import PrivateChatInfo from '../common/PrivateChatInfo'; +import GroupChatInfo from '../common/GroupChatInfo'; import './PollAnswerResults.scss'; @@ -108,12 +110,20 @@ const PollAnswerResults: FC = ({ // eslint-disable-next-line react/jsx-no-bind onClick={() => handleMemberClick(id)} > - + {isUserId(id) ? ( + + ) : ( + + )}
)) : } diff --git a/src/global/actions/api/messages.ts b/src/global/actions/api/messages.ts index d43006a55..b4b7c513c 100644 --- a/src/global/actions/api/messages.ts +++ b/src/global/actions/api/messages.ts @@ -745,6 +745,7 @@ addActionHandler('loadPollOptionResults', async (global, actions, payload): Prom global = getGlobal(); global = addUsers(global, buildCollectionByKey(result.users, 'id')); + global = addChats(global, buildCollectionByKey(result.chats, 'id')); const tabState = selectTabState(global, tabId); const { pollResults } = tabState; @@ -756,8 +757,8 @@ addActionHandler('loadPollOptionResults', async (global, actions, payload): Prom voters: { ...voters, [option]: unique([ - ...(!shouldResetVoters && voters && voters[option] ? voters[option] : []), - ...(result && result.users.map((user) => user.id)), + ...(!shouldResetVoters && voters?.[option] ? voters[option] : []), + ...result.votes.map((vote) => vote.peerId), ]), }, offsets: { diff --git a/src/global/actions/api/reactions.ts b/src/global/actions/api/reactions.ts index 032817fe0..dc80325e0 100644 --- a/src/global/actions/api/reactions.ts +++ b/src/global/actions/api/reactions.ts @@ -262,9 +262,8 @@ addActionHandler('loadReactors', async (global, actions, payload): Promise global = getGlobal(); - if (result.users?.length) { - global = addUsers(global, buildCollectionByKey(result.users, 'id')); - } + global = addUsers(global, buildCollectionByKey(result.users, 'id')); + global = addChats(global, buildCollectionByKey(result.chats, 'id')); global = updateChatMessage(global, chatId, messageId, { reactors: result, diff --git a/src/global/actions/apiUpdaters/messages.ts b/src/global/actions/apiUpdaters/messages.ts index bc9e5de80..fcb1d661c 100644 --- a/src/global/actions/apiUpdaters/messages.ts +++ b/src/global/actions/apiUpdaters/messages.ts @@ -53,6 +53,7 @@ import { selectThreadIdFromMessage, selectTopicFromMessage, selectTabState, + selectSendAs, } from '../../selectors'; import { getMessageContent, isUserId, isMessageLocal, getMessageText, checkIfHasUnreadReactions, isActionMessage, @@ -517,7 +518,7 @@ addActionHandler('apiUpdate', (global, actions, update): ActionReturnType => { } case 'updateMessagePollVote': { - const { pollId, userId, options } = update; + const { pollId, peerId, options } = update; const message = selectChatMessageByPollId(global, pollId); if (!message || !message.content.poll || !message.content.poll.results) { break; @@ -525,12 +526,14 @@ addActionHandler('apiUpdate', (global, actions, update): ActionReturnType => { const { poll } = message.content; + const currentSendAs = selectSendAs(global, message.chatId); + const { recentVoterIds, totalVoters, results } = poll.results; const newRecentVoterIds = recentVoterIds ? [...recentVoterIds] : []; const newTotalVoters = totalVoters ? totalVoters + 1 : 1; const newResults = results ? [...results] : []; - newRecentVoterIds.push(userId); + newRecentVoterIds.push(peerId); options.forEach((option) => { const targetOptionIndex = newResults.findIndex((result) => result.option === option); @@ -538,7 +541,7 @@ addActionHandler('apiUpdate', (global, actions, update): ActionReturnType => { const updatedOption: ApiPollResult = targetOption ? { ...targetOption } : { option, votersCount: 0 }; updatedOption.votersCount += 1; - if (userId === global.currentUserId) { + if (currentSendAs?.id === peerId || peerId === global.currentUserId) { updatedOption.isChosen = true; } diff --git a/src/global/helpers/reactions.ts b/src/global/helpers/reactions.ts index d8ecc2d80..2b75667ea 100644 --- a/src/global/helpers/reactions.ts +++ b/src/global/helpers/reactions.ts @@ -14,7 +14,7 @@ export function getMessageRecentReaction(message: Partial) { export function checkIfHasUnreadReactions(global: GlobalState, reactions: ApiReactions) { const { currentUserId } = global; return reactions?.recentReactions?.some( - ({ isUnread, userId }) => isUnread && userId !== currentUserId, + ({ isUnread, isOwn, peerId }) => isUnread && !isOwn && currentUserId !== peerId, ); } diff --git a/src/global/reducers/reactions.ts b/src/global/reducers/reactions.ts index cdd169e69..1cb793ca5 100644 --- a/src/global/reducers/reactions.ts +++ b/src/global/reducers/reactions.ts @@ -10,7 +10,7 @@ import windowSize from '../../util/windowSize'; import { updateChat } from './chats'; import { isSameReaction, isReactionChosen } from '../helpers'; import { updateChatMessage } from './messages'; -import { selectTabState } from '../selectors'; +import { selectSendAs, selectTabState } from '../selectors'; import { getIsMobile } from '../../hooks/useAppLayout'; function getLeftColumnWidth(windowWidth: number) { @@ -42,6 +42,7 @@ export function addMessageReaction( global: T, message: ApiMessage, userReactions: ApiReaction[], ): T { const currentReactions = message.reactions || { results: [] }; + const currentSendAs = selectSendAs(global, message.chatId); // Update UI without waiting for server response const results = currentReactions.results.map((current) => ( @@ -72,15 +73,16 @@ export function addMessageReaction( let { recentReactions = [] } = currentReactions; if (recentReactions.length) { - recentReactions = recentReactions.filter(({ userId }) => userId !== global.currentUserId); + recentReactions = recentReactions.filter(({ isOwn, peerId }) => !isOwn && peerId !== global.currentUserId); } userReactions.forEach((reaction) => { const { currentUserId } = global; recentReactions.unshift({ - userId: currentUserId!, + peerId: currentSendAs?.id || currentUserId!, reaction, addedDate: Math.floor(Date.now() / 1000), + isOwn: true, }); }); diff --git a/src/global/selectors/messages.ts b/src/global/selectors/messages.ts index afc789cd1..651ae3d6e 100644 --- a/src/global/selectors/messages.ts +++ b/src/global/selectors/messages.ts @@ -542,6 +542,7 @@ export function selectAllowedMessageActions(global: T, me const isFailed = isMessageFailed(message); const isServiceNotification = isServiceNotificationMessage(message); const isOwn = isOwnMessage(message); + const isForwarded = isForwardedMessage(message); const isAction = isActionMessage(message); const { content } = message; const messageTopic = selectTopicFromMessage(global, message); @@ -557,7 +558,7 @@ export function selectAllowedMessageActions(global: T, me content.sticker || content.contact || content.poll || content.action || content.audio || (content.video?.isRound) || content.location || content.invoice ) - && !isForwardedMessage(message) + && !isForwarded && !message.viaBotId && !chat.isForbidden ); @@ -601,10 +602,9 @@ export function selectAllowedMessageActions(global: T, me )) ); - const canEdit = !isLocal && !isAction && isMessageEditable && ( - isOwn - || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages'))) - ); + const hasMessageEditRight = isOwn || (isChannel && (chat.isCreator || getHasAdminRight(chat, 'editMessages'))); + + const canEdit = !isLocal && !isAction && isMessageEditable && hasMessageEditRight; const isChatProtected = selectIsChatProtected(global, message.chatId); const canForward = ( @@ -626,7 +626,7 @@ export function selectAllowedMessageActions(global: T, me const poll = content.poll; const canRevote = !poll?.summary.closed && !poll?.summary.quiz && poll?.results.results?.some((r) => r.isChosen); - const canClosePoll = isOwn && poll && !poll.summary.closed; + const canClosePoll = hasMessageEditRight && poll && !poll.summary.closed && !isForwarded; const noOptions = [ canReply, diff --git a/src/lib/gramjs/tl/AllTLObjects.js b/src/lib/gramjs/tl/AllTLObjects.js index 3fba6f47a..7a9a8f79d 100644 --- a/src/lib/gramjs/tl/AllTLObjects.js +++ b/src/lib/gramjs/tl/AllTLObjects.js @@ -1,6 +1,6 @@ const api = require('./api'); -const LAYER = 158; +const LAYER = 159; const tlobjects = {}; for (const tl of Object.values(api)) { diff --git a/src/lib/gramjs/tl/api.d.ts b/src/lib/gramjs/tl/api.d.ts index 031a1f7bb..170f8e6e0 100644 --- a/src/lib/gramjs/tl/api.d.ts +++ b/src/lib/gramjs/tl/api.d.ts @@ -235,7 +235,7 @@ namespace Api { export type TypeInputThemeSettings = InputThemeSettings; export type TypeThemeSettings = ThemeSettings; export type TypeWebPageAttribute = WebPageAttributeTheme; - export type TypeMessageUserVote = MessageUserVote | MessageUserVoteInputOption | MessageUserVoteMultiple; + export type TypeMessagePeerVote = MessagePeerVote | MessagePeerVoteInputOption | MessagePeerVoteMultiple; export type TypeBankCardOpenUrl = BankCardOpenUrl; export type TypeDialogFilter = DialogFilter | DialogFilterDefault | DialogFilterChatlist; export type TypeDialogFilterSuggested = DialogFilterSuggested; @@ -2828,12 +2828,12 @@ namespace Api { export class UpdateLoginToken extends VirtualClass {}; export class UpdateMessagePollVote extends VirtualClass<{ pollId: long; - userId: long; + peer: Api.TypePeer; options: bytes[]; qts: int; }> { pollId: long; - userId: long; + peer: Api.TypePeer; options: bytes[]; qts: int; }; @@ -6723,7 +6723,7 @@ namespace Api { min?: true; results?: Api.TypePollAnswerVoters[]; totalVoters?: int; - recentVoters?: long[]; + recentVoters?: Api.TypePeer[]; solution?: string; solutionEntities?: Api.TypeMessageEntity[]; } | void> { @@ -6731,7 +6731,7 @@ namespace Api { min?: true; results?: Api.TypePollAnswerVoters[]; totalVoters?: int; - recentVoters?: long[]; + recentVoters?: Api.TypePeer[]; solution?: string; solutionEntities?: Api.TypeMessageEntity[]; }; @@ -7104,28 +7104,28 @@ namespace Api { documents?: Api.TypeDocument[]; settings?: Api.TypeThemeSettings; }; - export class MessageUserVote extends VirtualClass<{ - userId: long; + export class MessagePeerVote extends VirtualClass<{ + peer: Api.TypePeer; option: bytes; date: int; }> { - userId: long; + peer: Api.TypePeer; option: bytes; date: int; }; - export class MessageUserVoteInputOption extends VirtualClass<{ - userId: long; + export class MessagePeerVoteInputOption extends VirtualClass<{ + peer: Api.TypePeer; date: int; }> { - userId: long; + peer: Api.TypePeer; date: int; }; - export class MessageUserVoteMultiple extends VirtualClass<{ - userId: long; + export class MessagePeerVoteMultiple extends VirtualClass<{ + peer: Api.TypePeer; options: bytes[]; date: int; }> { - userId: long; + peer: Api.TypePeer; options: bytes[]; date: int; }; @@ -7637,6 +7637,7 @@ namespace Api { // flags: undefined; big?: true; unread?: true; + my?: true; peerId: Api.TypePeer; date: int; reaction: Api.TypeReaction; @@ -7644,6 +7645,7 @@ namespace Api { // flags: undefined; big?: true; unread?: true; + my?: true; peerId: Api.TypePeer; date: int; reaction: Api.TypeReaction; @@ -9083,13 +9085,15 @@ namespace Api { export class VotesList extends VirtualClass<{ // flags: undefined; count: int; - votes: Api.TypeMessageUserVote[]; + votes: Api.TypeMessagePeerVote[]; + chats: Api.TypeChat[]; users: Api.TypeUser[]; nextOffset?: string; }> { // flags: undefined; count: int; - votes: Api.TypeMessageUserVote[]; + votes: Api.TypeMessagePeerVote[]; + chats: Api.TypeChat[]; users: Api.TypeUser[]; nextOffset?: string; }; @@ -12161,11 +12165,6 @@ namespace Api { maxId: long; limit: int; }; - export class GetAllChats extends Request, messages.TypeChats> { - exceptIds: long[]; - }; export class GetWebPage extends Request, updates.TypeDifference> { // flags: undefined; pts: int; + ptsLimit?: int; ptsTotalLimit?: int; date: int; qts: int; + qtsLimit?: int; }; export class GetChannelDifference extends Request = Update; updateTheme#8216fba3 theme:Theme = Update; updateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update; updateLoginToken#564fe691 = Update; -updateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update; +updateMessagePollVote#24f40e77 poll_id:long peer:Peer options:Vector qts:int = Update; updateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update; updateDialogFilterOrder#a5d72105 order:Vector = Update; updateDialogFilters#3504914f = Update; @@ -868,7 +868,7 @@ help.userInfo#1eb3758 message:string entities:Vector author:strin pollAnswer#6ca9c2e9 text:string option:bytes = PollAnswer; poll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true multiple_choice:flags.2?true quiz:flags.3?true question:string answers:Vector close_period:flags.4?int close_date:flags.5?int = Poll; pollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters; -pollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults; +pollResults#7adf2420 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults; chatOnlines#f041e250 onlines:int = ChatOnlines; statsURL#47a971e0 url:string = StatsURL; chatAdminRights#5fb224d5 flags:# change_info:flags.0?true post_messages:flags.1?true edit_messages:flags.2?true delete_messages:flags.3?true ban_users:flags.4?true invite_users:flags.5?true pin_messages:flags.7?true add_admins:flags.9?true anonymous:flags.10?true manage_call:flags.11?true other:flags.12?true manage_topics:flags.13?true = ChatAdminRights; @@ -917,10 +917,10 @@ baseThemeArctic#5b11125a = BaseTheme; inputThemeSettings#8fde504f flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?InputWallPaper wallpaper_settings:flags.1?WallPaperSettings = InputThemeSettings; themeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:BaseTheme accent_color:int outbox_accent_color:flags.3?int message_colors:flags.0?Vector wallpaper:flags.1?WallPaper = ThemeSettings; webPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute; -messageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote; -messageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote; -messageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote; -messages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList; +messagePeerVote#b6cc2d5c peer:Peer option:bytes date:int = MessagePeerVote; +messagePeerVoteInputOption#74cda504 peer:Peer date:int = MessagePeerVote; +messagePeerVoteMultiple#4628f6e6 peer:Peer options:Vector date:int = MessagePeerVote; +messages.votesList#4899484e flags:# count:int votes:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.VotesList; bankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl; payments.bankCardData#3e24e573 title:string open_urls:Vector = payments.BankCardData; dialogFilter#7438f7e8 flags:# contacts:flags.0?true non_contacts:flags.1?true groups:flags.2?true broadcasts:flags.3?true bots:flags.4?true exclude_muted:flags.11?true exclude_read:flags.12?true exclude_archived:flags.13?true id:int title:string emoticon:flags.25?string pinned_peers:Vector include_peers:Vector exclude_peers:Vector = DialogFilter; @@ -1011,7 +1011,7 @@ messages.messageReactionsList#31bd492d flags:# count:int reactions:Vector = messages.AvailableReactions; -messagePeerReaction#8c79b63c flags:# big:flags.0?true unread:flags.1?true peer_id:Peer date:int reaction:Reaction = MessagePeerReaction; +messagePeerReaction#8c79b63c flags:# big:flags.0?true unread:flags.1?true my:flags.2?true peer_id:Peer date:int reaction:Reaction = MessagePeerReaction; groupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel; phone.groupCallStreamChannels#d0e482b2 channels:Vector = phone.GroupCallStreamChannels; phone.groupCallStreamRtmpUrl#2dbf3432 url:string key:string = phone.GroupCallStreamRtmpUrl; @@ -1309,7 +1309,7 @@ messages.togglePeerTranslations#e47cb579 flags:# disabled:flags.0?true peer:Inpu messages.getBotApp#34fdc5c3 app:InputBotApp hash:long = messages.BotApp; messages.requestAppWebView#8c5a3b3c flags:# write_allowed:flags.0?true peer:InputPeer app:InputBotApp start_param:flags.1?string theme_params:flags.2?DataJSON platform:string = AppWebViewResult; updates.getState#edd4882a = updates.State; -updates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference; +updates.getDifference#19c2f763 flags:# pts:int pts_limit:flags.1?int pts_total_limit:flags.0?int date:int qts:int qts_limit:flags.2?int = updates.Difference; updates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference; photos.updateProfilePhoto#9e82039 flags:# fallback:flags.0?true bot:flags.1?InputUser id:InputPhoto = photos.Photo; photos.uploadProfilePhoto#388a3b5 flags:# fallback:flags.3?true bot:flags.5?InputUser file:flags.0?InputFile video:flags.1?InputFile video_start_ts:flags.2?double video_emoji_markup:flags.4?VideoSize = photos.Photo; diff --git a/src/lib/gramjs/tl/static/api.tl b/src/lib/gramjs/tl/static/api.tl index 4abfc1d66..e33fff4b7 100644 --- a/src/lib/gramjs/tl/static/api.tl +++ b/src/lib/gramjs/tl/static/api.tl @@ -340,7 +340,7 @@ updateDeleteScheduledMessages#90866cee peer:Peer messages:Vector = Update; updateTheme#8216fba3 theme:Theme = Update; updateGeoLiveViewed#871fb939 peer:Peer msg_id:int = Update; updateLoginToken#564fe691 = Update; -updateMessagePollVote#106395c9 poll_id:long user_id:long options:Vector qts:int = Update; +updateMessagePollVote#24f40e77 poll_id:long peer:Peer options:Vector qts:int = Update; updateDialogFilter#26ffde7d flags:# id:int filter:flags.0?DialogFilter = Update; updateDialogFilterOrder#a5d72105 order:Vector = Update; updateDialogFilters#3504914f = Update; @@ -1105,7 +1105,7 @@ poll#86e18161 id:long flags:# closed:flags.0?true public_voters:flags.1?true mul pollAnswerVoters#3b6ddad2 flags:# chosen:flags.0?true correct:flags.1?true option:bytes voters:int = PollAnswerVoters; -pollResults#dcb82ea3 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults; +pollResults#7adf2420 flags:# min:flags.0?true results:flags.1?Vector total_voters:flags.2?int recent_voters:flags.3?Vector solution:flags.4?string solution_entities:flags.4?Vector = PollResults; chatOnlines#f041e250 onlines:int = ChatOnlines; @@ -1187,11 +1187,11 @@ themeSettings#fa58b6d4 flags:# message_colors_animated:flags.2?true base_theme:B webPageAttributeTheme#54b56617 flags:# documents:flags.0?Vector settings:flags.1?ThemeSettings = WebPageAttribute; -messageUserVote#34d247b4 user_id:long option:bytes date:int = MessageUserVote; -messageUserVoteInputOption#3ca5b0ec user_id:long date:int = MessageUserVote; -messageUserVoteMultiple#8a65e557 user_id:long options:Vector date:int = MessageUserVote; +messagePeerVote#b6cc2d5c peer:Peer option:bytes date:int = MessagePeerVote; +messagePeerVoteInputOption#74cda504 peer:Peer date:int = MessagePeerVote; +messagePeerVoteMultiple#4628f6e6 peer:Peer options:Vector date:int = MessagePeerVote; -messages.votesList#823f649 flags:# count:int votes:Vector users:Vector next_offset:flags.0?string = messages.VotesList; +messages.votesList#4899484e flags:# count:int votes:Vector chats:Vector users:Vector next_offset:flags.0?string = messages.VotesList; bankCardOpenUrl#f568028a url:string name:string = BankCardOpenUrl; @@ -1348,7 +1348,7 @@ availableReaction#c077ec01 flags:# inactive:flags.0?true premium:flags.2?true re messages.availableReactionsNotModified#9f071957 = messages.AvailableReactions; messages.availableReactions#768e3aad hash:int reactions:Vector = messages.AvailableReactions; -messagePeerReaction#8c79b63c flags:# big:flags.0?true unread:flags.1?true peer_id:Peer date:int reaction:Reaction = MessagePeerReaction; +messagePeerReaction#8c79b63c flags:# big:flags.0?true unread:flags.1?true my:flags.2?true peer_id:Peer date:int reaction:Reaction = MessagePeerReaction; groupCallStreamChannel#80eb48af channel:int scale:int last_timestamp_ms:long = GroupCallStreamChannel; @@ -1738,7 +1738,6 @@ messages.setInlineGameScore#15ad9f64 flags:# edit_message:flags.0?true force:fla messages.getGameHighScores#e822649d peer:InputPeer id:int user_id:InputUser = messages.HighScores; messages.getInlineGameHighScores#f635e1b id:InputBotInlineMessageID user_id:InputUser = messages.HighScores; messages.getCommonChats#e40ca104 user_id:InputUser max_id:long limit:int = messages.Chats; -messages.getAllChats#875f74be except_ids:Vector = messages.Chats; messages.getWebPage#32ca8f91 url:string hash:int = WebPage; messages.toggleDialogPin#a731e257 flags:# pinned:flags.0?true peer:InputDialogPeer = Bool; messages.reorderPinnedDialogs#3b1adf37 flags:# force:flags.0?true folder_id:int order:Vector = Bool; @@ -1852,7 +1851,7 @@ messages.requestAppWebView#8c5a3b3c flags:# write_allowed:flags.0?true peer:Inpu messages.setChatWallPaper#8ffacae1 flags:# peer:InputPeer wallpaper:flags.0?InputWallPaper settings:flags.2?WallPaperSettings id:flags.1?int = Updates; updates.getState#edd4882a = updates.State; -updates.getDifference#25939651 flags:# pts:int pts_total_limit:flags.0?int date:int qts:int = updates.Difference; +updates.getDifference#19c2f763 flags:# pts:int pts_limit:flags.1?int pts_total_limit:flags.0?int date:int qts:int qts_limit:flags.2?int = updates.Difference; updates.getChannelDifference#3173d78 flags:# force:flags.0?true channel:InputChannel filter:ChannelMessagesFilter pts:int limit:int = updates.ChannelDifference; photos.updateProfilePhoto#9e82039 flags:# fallback:flags.0?true bot:flags.1?InputUser id:InputPhoto = photos.Photo; diff --git a/src/util/notifications.ts b/src/util/notifications.ts index 88fec1a61..02cd76380 100644 --- a/src/util/notifications.ts +++ b/src/util/notifications.ts @@ -1,6 +1,6 @@ import { callApi } from '../api/gramjs'; import type { - ApiChat, ApiMessage, ApiPhoneCall, ApiUser, ApiUserReaction, + ApiChat, ApiMessage, ApiPhoneCall, ApiUser, ApiPeerReaction, } from '../api/types'; import { ApiMediaFormat } from '../api/types'; import { renderActionMessageText } from '../components/common/helpers/renderActionMessageText'; @@ -30,6 +30,7 @@ import { selectNotifyExceptions, selectNotifySettings, selectUser, + selectChat, } from '../global/selectors'; import { IS_SERVICE_WORKER_SUPPORTED, IS_TOUCH_ENV } from './windowEnvironment'; import { translate } from './langProvider'; @@ -310,7 +311,7 @@ function checkIfShouldNotify(chat: ApiChat, message: Partial) { return !document.hasFocus(); } -function getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: ApiUserReaction) { +function getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: ApiPeerReaction) { const global = getGlobal(); const { replyToMessageId, @@ -319,11 +320,13 @@ function getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: A senderId, } = message; const hasReaction = Boolean(reaction); - if (hasReaction) senderId = reaction.userId; + if (hasReaction) senderId = reaction.peerId; const { isScreenLocked } = global.passcode; - const messageSender = senderId ? selectUser(global, senderId) : undefined; + const messageSenderChat = senderId ? selectChat(global, senderId) : undefined; + const messageSenderUser = senderId ? selectUser(global, senderId) : undefined; const messageAction = getMessageAction(message as ApiMessage); + const actionTargetMessage = messageAction && replyToMessageId ? selectChatMessage(global, chat.id, replyToMessageId) : undefined; @@ -352,7 +355,7 @@ function getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: A body = renderActionMessageText( translate, message, - !isChat ? messageSender : undefined, + !isChat ? messageSenderUser : undefined, isChat ? chat : undefined, actionTargetUsers, actionTargetMessage, @@ -362,7 +365,7 @@ function getNotificationContent(chat: ApiChat, message: ApiMessage, reaction?: A ) as string; } else { // TODO[forums] Support ApiChat - const senderName = getMessageSenderName(translate, chat.id, messageSender); + const senderName = getMessageSenderName(translate, chat.id, isChat ? messageSenderChat : messageSenderUser); let summary = getMessageSummaryText(translate, message, hasReaction, 60); if (hasReaction) { @@ -396,7 +399,7 @@ async function getAvatar(chat: ApiChat | ApiUser) { return mediaData; } -function getReactionEmoji(reaction: ApiUserReaction) { +function getReactionEmoji(reaction: ApiPeerReaction) { let emoji; if ('emoticon' in reaction.reaction) { emoji = reaction.reaction.emoticon;