Spaces:
Running
Running
4SEND commited on
Commit ·
c4341fd
1
Parent(s): 3fd4e79
deploy: sessions/pins/calls/video-message fixes + rebuilt client assets
Browse filesFiles changed (39)
- index.js+2-1
- jobs/autoDeleteUsers.js+3-1
- jobs/sessionCleanup.js+10-5
- middleware/authenticateToken.js+6-3
- models/Pin.js+2-2
- public/assets/AvatarCropper-YXBtLMg1.js → public/assets/AvatarCropper-BpVibBmq.jsRenamed+1-1
- public/assets/EmojiPanel-C0q3T_JG.js → public/assets/EmojiPanel-BwB33XQa.jsRenamed+1-1
- public/assets/EncryptionModal-DVr1yxXX.js → public/assets/EncryptionModal-BOkioGOz.jsRenamed+1-1
- public/assets/MessengerPage-BEPX8mwe.js → public/assets/MessengerPage-6Fs5zx2C.jsRenamed
- public/assets/MessengerPage-BJOhOjc3.cssDeleted
- public/assets/MessengerPage-DuSMdAeg.cssAdded
- public/assets/ModalShell-BrGMDJl_.js → public/assets/ModalShell-ClUKyIG2.jsRenamed+1-1
- public/assets/index-DY9FqaHJ.jsAdded
- public/assets/index-HjRUEDl2.jsDeleted
- public/assets/storage-B_75ItAe.js → public/assets/storage-8tFmIq9d.jsRenamed+1-1
- public/index.html+1-1
- public/package-lock.jsonAdded
- public/package.jsonAdded+51
- public/pwa-sw.js+1-1
- public/src/components/chat/CallOverlay.tsxAdded+528
- public/src/components/chat/PinnedBar.tsxAdded+176
- public/src/components/chat/VoiceRecorder.module.cssAdded+198
- public/src/components/chat/VoiceRecorder.tsxAdded+346
- public/src/components/settings/ChatSettingsModal.module.cssAdded+286
- public/src/components/settings/ChatSettingsModal.tsxAdded+350
- public/src/context/SettingsContext.tsxAdded+856
- public/src/pages/MessengerPage.module.cssAdded+1205
- public/src/pages/MessengerPage.tsxAdded
- public/src/services/socket.tsAdded+68
- public/src/utils/videoMessage.tsAdded+37
- routes/auth.js+1
- routes/pins.js+19-4
- routes/sessions.js+6-1
- routes/settings.js+13
- services/migration.js+26-1
- socket/handlers/call.js+1-1
- socket/handlers/pin.js+39-10
- socket/index.js+12
- socket/kick.jsAdded+14
2 unmodified lines345678911 unmodified lines2122232425262 unmodified linesconst app = require('./app');const { initSocket } = require('./socket/index');const { PORT, MONGO_URI } = require('./constants/allowed');const { runMigration, loadPrivacyMap } = require('./services/migration');const { startAutoDeleteJob } = require('./jobs/autoDeleteUsers');const { startNotificationRepeatJob } = require('./jobs/notificationRepeat');const { startSessionCleanupJob } = require('./jobs/sessionCleanup');11 unmodified lines.then(async () => {await runMigration();await loadPrivacyMap();startAutoDeleteJob();startNotificationRepeatJob();startSessionCleanupJob();2 unmodified lines345678911 unmodified lines212223242526272 unmodified linesconst app = require('./app');const { initSocket } = require('./socket/index');const { PORT, MONGO_URI } = require('./constants/allowed');const { runMigration, loadPrivacyMap, dedupPins } = require('./services/migration');const { startAutoDeleteJob } = require('./jobs/autoDeleteUsers');const { startNotificationRepeatJob } = require('./jobs/notificationRepeat');const { startSessionCleanupJob } = require('./jobs/sessionCleanup');11 unmodified lines.then(async () => {await runMigration();await loadPrivacyMap();await dedupPins();startAutoDeleteJob();startNotificationRepeatJob();startSessionCleanupJob();
15 unmodified lines1617181920212215 unmodified linesawait nukeUserAccount(user.username);}}} catch (err) {}}, 24 * 60 * 60 * 1000);};15 unmodified lines16171819202122232415 unmodified linesawait nukeUserAccount(user.username);}}} catch (err) {console.error('[autoDeleteUsers]', err);}}, 24 * 60 * 60 * 1000);};
12345 unmodified lines10111213141516171819202122const User = require('../models/User');const startSessionCleanupJob = () => {setInterval(async () => {5 unmodified linesconst limitDays = u.autoLogoutDays || 7;const limitMs = limitDays * 24 * 60 * 60 * 1000;const validSessions = u.sessions.filter(s => (now - new Date(s.lastActive)) < limitMs);if (validSessions.length !== u.sessions.length) {await User.updateOne({ _id: u._id }, { $set: { sessions: validSessions } });}}} catch (err) {}}, 60 * 60 * 1000);};123455 unmodified lines1112131415161718192021222324252627const User = require('../models/User');const { kickSessions } = require('../socket/kick');const startSessionCleanupJob = () => {setInterval(async () => {5 unmodified linesconst limitDays = u.autoLogoutDays || 7;const limitMs = limitDays * 24 * 60 * 60 * 1000;const expired = u.sessions.filter(s => (now - new Date(s.lastActive)) >= limitMs);if (!expired.length) continue;const expiredTokens = new Set(expired.map(s => s.token));const validSessions = u.sessions.filter(s => !expiredTokens.has(s.token));await User.updateOne({ _id: u._id }, { $set: { sessions: validSessions } });kickSessions(u.username, t => expiredTokens.has(t));}} catch (err) {console.error('[sessionCleanup]', err);}}, 60 * 60 * 1000);};
7 unmodified lines8910111213141516171 unmodified line192021222324257 unmodified linesconst token = authHeader && authHeader.split(' ')[1];if (!token || !JWT_SECRET) return res.status(401).json({ error: 'Unauthorized' });jwt.verify(token, JWT_SECRET, async (err, decoded) => {if (err || !decoded || typeof decoded.username !== 'string') return res.status(403).json({ error: 'Forbidden' });try {const username = decoded.username.trim().toLowerCase();if (!/^[a-z]{4,20}$/.test(username)) return res.status(403).json({ error: 'Forbidden' });const user = await User.findOne({ username }).lean();if (!user || user.role === 'banned') return res.status(403).json({ error: 'Banned' });const isValid = Array.isArray(user.sessions) && user.sessions.some(s => s && s.token === token);1 unmodified lineif (shouldUpdateLastActive(username, token)) {await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date() } });}req.user = { ...decoded, username, role: user.role };7 unmodified lines8910111213141516171819201 unmodified line222324252627287 unmodified linesconst token = authHeader && authHeader.split(' ')[1];if (!token || !JWT_SECRET) return res.status(401).json({ error: 'Unauthorized' });jwt.verify(token, JWT_SECRET, async (err, decoded) => {if (err || !decoded || typeof decoded.username !== 'string') {const msg = err && err.name === 'TokenExpiredError' ? 'Session expired' : 'Unauthorized';return res.status(401).json({ error: msg });}try {const username = decoded.username.trim().toLowerCase();if (!/^[a-z]{4,20}$/.test(username)) return res.status(401).json({ error: 'Unauthorized' });const user = await User.findOne({ username }).lean();if (!user || user.role === 'banned') return res.status(403).json({ error: 'Banned' });const isValid = Array.isArray(user.sessions) && user.sessions.some(s => s && s.token === token);1 unmodified lineif (shouldUpdateLastActive(username, token)) {await User.updateOne({ username, "sessions.token": token },{ $set: { "sessions.$.lastActive": new Date(), last_seen: new Date() } });}req.user = { ...decoded, username, role: user.role };
3 unmodified lines4567891011121314153 unmodified linesmessage_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Message' },chat_id: { type: String, index: true },pinner_id: { type: String },pin_type: { type: String, default: 'both' },text_preview: { type: String },timestamp: { type: Date, default: Date.now }});PinSchema.index({ chat_id: 1, pinner_id: 1 });PinSchema.index({ message_id: 1, chat_id: 1 });module.exports = mongoose.model('Pin', PinSchema);3 unmodified lines4567891011121314153 unmodified linesmessage_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Message' },chat_id: { type: String, index: true },pinner_id: { type: String },pin_type: { type: String, enum: ['both', 'me', 'self'], default: 'both' },text_preview: { type: String },timestamp: { type: Date, default: Date.now }});PinSchema.index({ chat_id: 1, pinner_id: 1 });PinSchema.index({ message_id: 1, chat_id: 1, pinner_id: 1 }, { unique: true });module.exports = mongoose.model('Pin', PinSchema);
1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{l as t,t as n,u as r}from"./vendor-BbmWO_jh.js";import{l as i}from"./index-HjRUEDl2.js";var a=e(r(),1),o=e(t(),1),s={overlay:`_overlay_17o5h_1`,open:`_open_17o5h_17`,closing:`_closing_17o5h_23`,box:`_box_17o5h_30`,boxOpen:`_boxOpen_17o5h_47`,boxClosing:`_boxClosing_17o5h_52`,title:`_title_17o5h_58`,stage:`_stage_17o5h_66`,canvas:`_canvas_17o5h_83`,ring:`_ring_17o5h_91`,zoomLabel:`_zoomLabel_17o5h_100`,zoom:`_zoom_17o5h_100`,actions:`_actions_17o5h_114`,cancel:`_cancel_17o5h_121`,done:`_done_17o5h_122`},c=n(),l=260,u=512;function d({file:e,onCancel:t,onCrop:n}){let{t:r}=i(),d=(0,a.useRef)(null),f=(0,a.useRef)(null),p=(0,a.useRef)(null),[m,h]=(0,a.useState)(1),[g,_]=(0,a.useState)({x:0,y:0}),v=(0,a.useRef)(null),[y,b]=(0,a.useState)(!0),[x,S]=(0,a.useState)(!1),[C,w]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>S(!0))});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{if(!C)return;let e=setTimeout(()=>{b(!1),w(!1),S(!1),t()},400);return()=>clearTimeout(e)},[C,t]);let T=(0,a.useCallback)(()=>{C||w(!0)},[C]);(0,a.useEffect)(()=>{let e=e=>{e.key===`Escape`&&T()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[T]),(0,a.useEffect)(()=>{let t=new Image;return t.onload=()=>{f.current=t,h(.5),_({x:0,y:0}),E()},t.src=URL.createObjectURL(e),()=>URL.revokeObjectURL(t.src)},[e]);let E=(0,a.useCallback)(()=>{let e=d.current,t=f.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.clearRect(0,0,l,l);let r=m,i=t.width*r,a=t.height*r;n.save(),n.beginPath(),n.arc(l/2,l/2,l/2,0,Math.PI*2),n.closePath(),n.clip(),n.drawImage(t,(l-i)/2+g.x,(l-a)/2+g.y,i,a),n.restore()},[m,g]);(0,a.useEffect)(()=>{E()},[E]);let D=e=>{e.target.setPointerCapture(e.pointerId),v.current={x:e.clientX,y:e.clientY,px:g.x,py:g.y}},O=e=>{if(!v.current)return;let t=e.clientX-v.current.x,n=e.clientY-v.current.y;_({x:v.current.px+t,y:v.current.py+n})},k=()=>{v.current=null};return y?(0,o.createPortal)((0,c.jsx)(`div`,{className:`${s.overlay} ${x&&!C?s.open:``} ${C?s.closing:``}`,onClick:T,children:(0,c.jsxs)(`div`,{className:`${s.box} ${x&&!C?s.boxOpen:``} ${C?s.boxClosing:``}`,onClick:e=>e.stopPropagation(),children:[(0,c.jsx)(`h3`,{className:s.title,children:r(`Обрезка аватара`)}),(0,c.jsxs)(`div`,{ref:p,className:s.stage,style:{width:l,height:l},onPointerDown:D,onPointerMove:O,onPointerUp:k,onPointerLeave:k,children:[(0,c.jsx)(`canvas`,{ref:d,width:l,height:l,className:s.canvas}),(0,c.jsx)(`div`,{className:s.ring})]}),(0,c.jsx)(`div`,{className:s.zoomLabel,children:r(`Масштаб`)}),(0,c.jsx)(`input`,{className:s.zoom,type:`range`,min:.5,max:4,step:.01,value:m,onChange:e=>h(parseFloat(e.target.value))}),(0,c.jsxs)(`div`,{className:s.actions,children:[(0,c.jsx)(`button`,{className:s.cancel,onClick:T,children:r(`Отмена`)}),(0,c.jsx)(`button`,{className:s.done,onClick:()=>{let e=document.createElement(`canvas`);e.width=u,e.height=u;let t=e.getContext(`2d`);if(!t||!f.current)return;t.beginPath(),t.arc(u/2,u/2,u/2,0,Math.PI*2),t.closePath(),t.clip();let r=u/l,i=m*r,a=f.current.width*i,o=f.current.height*i;t.drawImage(f.current,(u-a)/2+g.x*r,(u-o)/2+g.y*r,a,o),e.toBlob(e=>{e&&n(new File([e],`avatar.png`,{type:`image/png`}))},`image/png`)},children:r(`Готово`)})]})]})}),document.body):null}export{d as default};1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{l as t,t as n,u as r}from"./vendor-BbmWO_jh.js";import{l as i}from"./index-DY9FqaHJ.js";var a=e(r(),1),o=e(t(),1),s={overlay:`_overlay_17o5h_1`,open:`_open_17o5h_17`,closing:`_closing_17o5h_23`,box:`_box_17o5h_30`,boxOpen:`_boxOpen_17o5h_47`,boxClosing:`_boxClosing_17o5h_52`,title:`_title_17o5h_58`,stage:`_stage_17o5h_66`,canvas:`_canvas_17o5h_83`,ring:`_ring_17o5h_91`,zoomLabel:`_zoomLabel_17o5h_100`,zoom:`_zoom_17o5h_100`,actions:`_actions_17o5h_114`,cancel:`_cancel_17o5h_121`,done:`_done_17o5h_122`},c=n(),l=260,u=512;function d({file:e,onCancel:t,onCrop:n}){let{t:r}=i(),d=(0,a.useRef)(null),f=(0,a.useRef)(null),p=(0,a.useRef)(null),[m,h]=(0,a.useState)(1),[g,_]=(0,a.useState)({x:0,y:0}),v=(0,a.useRef)(null),[y,b]=(0,a.useState)(!0),[x,S]=(0,a.useState)(!1),[C,w]=(0,a.useState)(!1);(0,a.useEffect)(()=>{let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>S(!0))});return()=>cancelAnimationFrame(e)},[]),(0,a.useEffect)(()=>{if(!C)return;let e=setTimeout(()=>{b(!1),w(!1),S(!1),t()},400);return()=>clearTimeout(e)},[C,t]);let T=(0,a.useCallback)(()=>{C||w(!0)},[C]);(0,a.useEffect)(()=>{let e=e=>{e.key===`Escape`&&T()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[T]),(0,a.useEffect)(()=>{let t=new Image;return t.onload=()=>{f.current=t,h(.5),_({x:0,y:0}),E()},t.src=URL.createObjectURL(e),()=>URL.revokeObjectURL(t.src)},[e]);let E=(0,a.useCallback)(()=>{let e=d.current,t=f.current;if(!e||!t)return;let n=e.getContext(`2d`);if(!n)return;n.clearRect(0,0,l,l);let r=m,i=t.width*r,a=t.height*r;n.save(),n.beginPath(),n.arc(l/2,l/2,l/2,0,Math.PI*2),n.closePath(),n.clip(),n.drawImage(t,(l-i)/2+g.x,(l-a)/2+g.y,i,a),n.restore()},[m,g]);(0,a.useEffect)(()=>{E()},[E]);let D=e=>{e.target.setPointerCapture(e.pointerId),v.current={x:e.clientX,y:e.clientY,px:g.x,py:g.y}},O=e=>{if(!v.current)return;let t=e.clientX-v.current.x,n=e.clientY-v.current.y;_({x:v.current.px+t,y:v.current.py+n})},k=()=>{v.current=null};return y?(0,o.createPortal)((0,c.jsx)(`div`,{className:`${s.overlay} ${x&&!C?s.open:``} ${C?s.closing:``}`,onClick:T,children:(0,c.jsxs)(`div`,{className:`${s.box} ${x&&!C?s.boxOpen:``} ${C?s.boxClosing:``}`,onClick:e=>e.stopPropagation(),children:[(0,c.jsx)(`h3`,{className:s.title,children:r(`Обрезка аватара`)}),(0,c.jsxs)(`div`,{ref:p,className:s.stage,style:{width:l,height:l},onPointerDown:D,onPointerMove:O,onPointerUp:k,onPointerLeave:k,children:[(0,c.jsx)(`canvas`,{ref:d,width:l,height:l,className:s.canvas}),(0,c.jsx)(`div`,{className:s.ring})]}),(0,c.jsx)(`div`,{className:s.zoomLabel,children:r(`Масштаб`)}),(0,c.jsx)(`input`,{className:s.zoom,type:`range`,min:.5,max:4,step:.01,value:m,onChange:e=>h(parseFloat(e.target.value))}),(0,c.jsxs)(`div`,{className:s.actions,children:[(0,c.jsx)(`button`,{className:s.cancel,onClick:T,children:r(`Отмена`)}),(0,c.jsx)(`button`,{className:s.done,onClick:()=>{let e=document.createElement(`canvas`);e.width=u,e.height=u;let t=e.getContext(`2d`);if(!t||!f.current)return;t.beginPath(),t.arc(u/2,u/2,u/2,0,Math.PI*2),t.closePath(),t.clip();let r=u/l,i=m*r,a=f.current.width*i,o=f.current.height*i;t.drawImage(f.current,(u-a)/2+g.x*r,(u-o)/2+g.y*r,a,o),e.toBlob(e=>{e&&n(new File([e],`avatar.png`,{type:`image/png`}))},`image/png`)},children:r(`Готово`)})]})]})}),document.body):null}export{d as default};
1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r}from"./index-HjRUEDl2.js";var i=e(n(),1),a={overlay:`_overlay_1qhis_1`,panel:`_panel_1qhis_9`,tabs:`_tabs_1qhis_33`,tab:`_tab_1qhis_33`,active:`_active_1qhis_57`,category:`_category_1qhis_63`,categoryTitle:`_categoryTitle_1qhis_67`,grid:`_grid_1qhis_76`,emojiBtn:`_emojiBtn_1qhis_82`,stickerGrid:`_stickerGrid_1qhis_105`,stickerSlot:`_stickerSlot_1qhis_113`,stickerDelete:`_stickerDelete_1qhis_138`,stickerPlus:`_stickerPlus_1qhis_159`},o=t(),s={Частые:[`😀`,`😂`,`😍`,`🥰`,`😎`,`🤔`,`😅`,`🙌`,`👍`,`👋`,`❤️`,`🔥`,`✨`,`🎉`,`💯`,`🙏`,`😢`,`😤`,`🫡`,`😈`],Смайлики:`😀.😃.😄.😁.😆.😅.🤣.😂.🙂.🙃.😉.😊.😇.🥰.😍.🤩.😘.😗.😚.😙.🥲.😋.😛.😜.🤪.😝.🤑.🤗.🤭.🫢.🤫.🤔.🫡.🤐.🤨.😐.😑.😶.🫥.😏.😒.🙄.😬.🤥.😌.😔.😪.🤤.😴.😷.🤒.🤕.🤢.🤮.🥵.🥶.🥴.😵.🤯.🤠.🥳.🥸.😎.🤓.🧐`.split(`.`),Жесты:`👋.🤚.🖐️.✋.🖖.🫱.🫲.🫳.🫴.👌.🤌.🤏.✌️.🤞.🫰.🤟.🤘.🤙.👈.👉.👆.🖕.👇.☝️.🫵.👍.👎.✊.👊.🤛.🤜.👏.🙌.🫶.👐.🤲.🤝.🙏.💪`.split(`.`),Сердце:[`❤️`,`🧡`,`💛`,`💚`,`💙`,`💜`,`🖤`,`🤍`,`🤎`,`💔`,`❤️🔥`,`❤️🩹`,`❣️`,`💕`,`💞`,`💓`,`💗`,`💖`,`💘`,`💝`],Животные:`🐶.🐱.🐭.🐹.🐰.🦊.🐻.🐼.🐻❄️.🐨.🐯.🦁.🐮.🐷.🐸.🐵.🙈.🙉.🙊.🐒.🐔.🐧.🐦.🐤.🐣.🐥.🦆.🦅.🦉.🦇.🐺.🐗.🐴.🦄.🐝.🪱.🐛.🦋.🐌.🐞`.split(`.`),Еда:`🍎.🍐.🍊.🍋.🍌.🍉.🍇.🍓.🫐.🍈.🍒.🍑.🥭.🍍.🥥.🥝.🍅.🥑.🍆.🥔.🥕.🌽.🌶️.🫑.🥒.🥬.🥦.🧄.🧅.🍄`.split(`.`),Объекты:`⌚.📱.💻.⌨️.🖥️.🖨️.🖱️.🖲️.💾.💿.📀.📼.📷.📸.📹.🎥.📽️.🎞️.📞.☎️.📟.📠.📺.📻.🎙️.🎚️.🎛️.🧭.⏱️.⏰.📦`.split(`.`)};function c(e){try{let t=localStorage.getItem(e);return t?JSON.parse(t):[]}catch{return[]}}function l(e,t){localStorage.setItem(e,JSON.stringify(t))}function u({onSelect:e,onClose:t,sourceRect:n,closing:u}){let{t:d}=r(),[f,p]=(0,i.useState)(`emoji`),[m,h]=(0,i.useState)(()=>c(`4send_saved_stickers`)),[g,_]=(0,i.useState)(()=>c(`4send_saved_gifs`)),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useRef)(null),[x,S]=(0,i.useState)(!1),[C,w]=(0,i.useState)(!1),[T,E]=(0,i.useState)(!1),[D,O]=(0,i.useState)(`50% 100%`),k=(0,i.useMemo)(()=>Object.keys(s),[]);(0,i.useLayoutEffect)(()=>{if(!T&&n&&b.current){let e=b.current.getBoundingClientRect();if(e.width>0&&e.height>0){let t=(n.left+n.width/2-e.left)/e.width*100,r=(n.top+n.height/2-e.top)/e.height*100;O(`${t}% ${r}%`),E(!0)}}},[n,T]),(0,i.useEffect)(()=>{T&&!C&&requestAnimationFrame(()=>{requestAnimationFrame(()=>w(!0))})},[T,C]),(0,i.useEffect)(()=>{u&&!x&&(S(!0),setTimeout(t,300))},[u,x,t]);let A=(0,i.useCallback)(()=>{x||(S(!0),setTimeout(t,300))},[t,x]);(0,i.useEffect)(()=>{if(x)return;let e=e=>{e.key===`Escape`&&A()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[x,A]);let j=(0,i.useMemo)(()=>T?{transformOrigin:D,transform:C&&!x?`scale(1)`:`scale(0)`,opacity:C&&!x?1:0}:{visibility:`hidden`,opacity:0},[D,T,C,x]),M=(0,i.useCallback)(t=>{e(t)},[e]),N=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...m,e];h(t),l(`4send_saved_stickers`,t)},n.readAsDataURL(t),e.target.value=``},[m]),P=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...g,e];_(t),l(`4send_saved_gifs`,t)},n.readAsDataURL(t),e.target.value=``},[g]),F=(0,i.useCallback)(e=>{let t=m.filter((t,n)=>n!==e);h(t),l(`4send_saved_stickers`,t)},[m]),I=(0,i.useCallback)(e=>{let t=g.filter((t,n)=>n!==e);_(t),l(`4send_saved_gifs`,t)},[g]);return(0,o.jsx)(`div`,{className:a.overlay,onClick:A,children:(0,o.jsxs)(`div`,{ref:b,className:a.panel,"data-entered":T||void 0,style:j,onClick:e=>e.stopPropagation(),children:[(0,o.jsxs)(`div`,{className:a.tabs,children:[(0,o.jsx)(`button`,{className:`${a.tab} ${f===`emoji`?a.active:``}`,onClick:()=>p(`emoji`),children:d(`Эмодзи`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`stickers`?a.active:``}`,onClick:()=>p(`stickers`),children:d(`Стикеры`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`gifs`?a.active:``}`,onClick:()=>p(`gifs`),children:`GIF`})]}),f===`emoji`&&k.map(e=>(0,o.jsxs)(`div`,{className:a.category,children:[(0,o.jsx)(`div`,{className:a.categoryTitle,children:d(e)}),(0,o.jsx)(`div`,{className:a.grid,children:s[e].map((t,n)=>(0,o.jsx)(`button`,{className:a.emojiBtn,onClick:()=>M(t),children:t},`${e}-${n}`))})]},e)),f===`stickers`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:v,type:`file`,accept:`image/*`,style:{display:`none`},onChange:N}),(0,o.jsxs)(`div`,{className:a.stickerGrid,children:[m.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),F(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>v.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]}),f===`gifs`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:y,type:`file`,accept:`image/gif`,style:{display:`none`},onChange:P}),(0,o.jsxs)(`div`,{className:a.stickerGrid,style:{gridTemplateColumns:`repeat(3, 1fr)`},children:[g.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),I(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>y.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]})]})})}export{u as default};1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r}from"./index-DY9FqaHJ.js";var i=e(n(),1),a={overlay:`_overlay_1qhis_1`,panel:`_panel_1qhis_9`,tabs:`_tabs_1qhis_33`,tab:`_tab_1qhis_33`,active:`_active_1qhis_57`,category:`_category_1qhis_63`,categoryTitle:`_categoryTitle_1qhis_67`,grid:`_grid_1qhis_76`,emojiBtn:`_emojiBtn_1qhis_82`,stickerGrid:`_stickerGrid_1qhis_105`,stickerSlot:`_stickerSlot_1qhis_113`,stickerDelete:`_stickerDelete_1qhis_138`,stickerPlus:`_stickerPlus_1qhis_159`},o=t(),s={Частые:[`😀`,`😂`,`😍`,`🥰`,`😎`,`🤔`,`😅`,`🙌`,`👍`,`👋`,`❤️`,`🔥`,`✨`,`🎉`,`💯`,`🙏`,`😢`,`😤`,`🫡`,`😈`],Смайлики:`😀.😃.😄.😁.😆.😅.🤣.😂.🙂.🙃.😉.😊.😇.🥰.😍.🤩.😘.😗.😚.😙.🥲.😋.😛.😜.🤪.😝.🤑.🤗.🤭.🫢.🤫.🤔.🫡.🤐.🤨.😐.😑.😶.🫥.😏.😒.🙄.😬.🤥.😌.😔.😪.🤤.😴.😷.🤒.🤕.🤢.🤮.🥵.🥶.🥴.😵.🤯.🤠.🥳.🥸.😎.🤓.🧐`.split(`.`),Жесты:`👋.🤚.🖐️.✋.🖖.🫱.🫲.🫳.🫴.👌.🤌.🤏.✌️.🤞.🫰.🤟.🤘.🤙.👈.👉.👆.🖕.👇.☝️.🫵.👍.👎.✊.👊.🤛.🤜.👏.🙌.🫶.👐.🤲.🤝.🙏.💪`.split(`.`),Сердце:[`❤️`,`🧡`,`💛`,`💚`,`💙`,`💜`,`🖤`,`🤍`,`🤎`,`💔`,`❤️🔥`,`❤️🩹`,`❣️`,`💕`,`💞`,`💓`,`💗`,`💖`,`💘`,`💝`],Животные:`🐶.🐱.🐭.🐹.🐰.🦊.🐻.🐼.🐻❄️.🐨.🐯.🦁.🐮.🐷.🐸.🐵.🙈.🙉.🙊.🐒.🐔.🐧.🐦.🐤.🐣.🐥.🦆.🦅.🦉.🦇.🐺.🐗.🐴.🦄.🐝.🪱.🐛.🦋.🐌.🐞`.split(`.`),Еда:`🍎.🍐.🍊.🍋.🍌.🍉.🍇.🍓.🫐.🍈.🍒.🍑.🥭.🍍.🥥.🥝.🍅.🥑.🍆.🥔.🥕.🌽.🌶️.🫑.🥒.🥬.🥦.🧄.🧅.🍄`.split(`.`),Объекты:`⌚.📱.💻.⌨️.🖥️.🖨️.🖱️.🖲️.💾.💿.📀.📼.📷.📸.📹.🎥.📽️.🎞️.📞.☎️.📟.📠.📺.📻.🎙️.🎚️.🎛️.🧭.⏱️.⏰.📦`.split(`.`)};function c(e){try{let t=localStorage.getItem(e);return t?JSON.parse(t):[]}catch{return[]}}function l(e,t){localStorage.setItem(e,JSON.stringify(t))}function u({onSelect:e,onClose:t,sourceRect:n,closing:u}){let{t:d}=r(),[f,p]=(0,i.useState)(`emoji`),[m,h]=(0,i.useState)(()=>c(`4send_saved_stickers`)),[g,_]=(0,i.useState)(()=>c(`4send_saved_gifs`)),v=(0,i.useRef)(null),y=(0,i.useRef)(null),b=(0,i.useRef)(null),[x,S]=(0,i.useState)(!1),[C,w]=(0,i.useState)(!1),[T,E]=(0,i.useState)(!1),[D,O]=(0,i.useState)(`50% 100%`),k=(0,i.useMemo)(()=>Object.keys(s),[]);(0,i.useLayoutEffect)(()=>{if(!T&&n&&b.current){let e=b.current.getBoundingClientRect();if(e.width>0&&e.height>0){let t=(n.left+n.width/2-e.left)/e.width*100,r=(n.top+n.height/2-e.top)/e.height*100;O(`${t}% ${r}%`),E(!0)}}},[n,T]),(0,i.useEffect)(()=>{T&&!C&&requestAnimationFrame(()=>{requestAnimationFrame(()=>w(!0))})},[T,C]),(0,i.useEffect)(()=>{u&&!x&&(S(!0),setTimeout(t,300))},[u,x,t]);let A=(0,i.useCallback)(()=>{x||(S(!0),setTimeout(t,300))},[t,x]);(0,i.useEffect)(()=>{if(x)return;let e=e=>{e.key===`Escape`&&A()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[x,A]);let j=(0,i.useMemo)(()=>T?{transformOrigin:D,transform:C&&!x?`scale(1)`:`scale(0)`,opacity:C&&!x?1:0}:{visibility:`hidden`,opacity:0},[D,T,C,x]),M=(0,i.useCallback)(t=>{e(t)},[e]),N=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...m,e];h(t),l(`4send_saved_stickers`,t)},n.readAsDataURL(t),e.target.value=``},[m]),P=(0,i.useCallback)(e=>{let t=e.target.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,t=[...g,e];_(t),l(`4send_saved_gifs`,t)},n.readAsDataURL(t),e.target.value=``},[g]),F=(0,i.useCallback)(e=>{let t=m.filter((t,n)=>n!==e);h(t),l(`4send_saved_stickers`,t)},[m]),I=(0,i.useCallback)(e=>{let t=g.filter((t,n)=>n!==e);_(t),l(`4send_saved_gifs`,t)},[g]);return(0,o.jsx)(`div`,{className:a.overlay,onClick:A,children:(0,o.jsxs)(`div`,{ref:b,className:a.panel,"data-entered":T||void 0,style:j,onClick:e=>e.stopPropagation(),children:[(0,o.jsxs)(`div`,{className:a.tabs,children:[(0,o.jsx)(`button`,{className:`${a.tab} ${f===`emoji`?a.active:``}`,onClick:()=>p(`emoji`),children:d(`Эмодзи`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`stickers`?a.active:``}`,onClick:()=>p(`stickers`),children:d(`Стикеры`)}),(0,o.jsx)(`button`,{className:`${a.tab} ${f===`gifs`?a.active:``}`,onClick:()=>p(`gifs`),children:`GIF`})]}),f===`emoji`&&k.map(e=>(0,o.jsxs)(`div`,{className:a.category,children:[(0,o.jsx)(`div`,{className:a.categoryTitle,children:d(e)}),(0,o.jsx)(`div`,{className:a.grid,children:s[e].map((t,n)=>(0,o.jsx)(`button`,{className:a.emojiBtn,onClick:()=>M(t),children:t},`${e}-${n}`))})]},e)),f===`stickers`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:v,type:`file`,accept:`image/*`,style:{display:`none`},onChange:N}),(0,o.jsxs)(`div`,{className:a.stickerGrid,children:[m.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),F(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>v.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]}),f===`gifs`&&(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)(`input`,{ref:y,type:`file`,accept:`image/gif`,style:{display:`none`},onChange:P}),(0,o.jsxs)(`div`,{className:a.stickerGrid,style:{gridTemplateColumns:`repeat(3, 1fr)`},children:[g.map((t,n)=>(0,o.jsxs)(`div`,{className:a.stickerSlot,onClick:()=>e(t),children:[(0,o.jsx)(`img`,{src:t,alt:``}),(0,o.jsx)(`button`,{className:a.stickerDelete,onClick:e=>{e.stopPropagation(),I(n)},children:`×`})]},n)),(0,o.jsx)(`div`,{className:a.stickerSlot,onClick:()=>y.current?.click(),children:(0,o.jsx)(`span`,{className:a.stickerPlus,children:`+`})})]})]})]})})}export{u as default};
1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r,r as i}from"./index-HjRUEDl2.js";import{t as a}from"./ModalShell-BrGMDJl_.js";var o=e(n(),1),s={step:`_step_1q5ed_1`,heroIcon:`_heroIcon_1q5ed_9`,fadeInScale:`_fadeInScale_1q5ed_1`,infoBlock:`_infoBlock_1q5ed_19`,infoTitle:`_infoTitle_1q5ed_26`,infoText:`_infoText_1q5ed_35`,featureList:`_featureList_1q5ed_42`,featureItem:`_featureItem_1q5ed_49`,dot:`_dot_1q5ed_65`,muted:`_muted_1q5ed_72`,warnBox:`_warnBox_1q5ed_77`,warnText:`_warnText_1q5ed_91`,fieldGroup:`_fieldGroup_1q5ed_102`,fieldLabel:`_fieldLabel_1q5ed_109`,passwordRow:`_passwordRow_1q5ed_116`,passwordInput:`_passwordInput_1q5ed_122`,activeBadge:`_activeBadge_1q5ed_152`,error:`_error_1q5ed_165`,primaryBtn:`_primaryBtn_1q5ed_177`,dangerBtn:`_dangerBtn_1q5ed_206`,progressBar:`_progressBar_1q5ed_234`,progressFill:`_progressFill_1q5ed_242`,progressText:`_progressText_1q5ed_249`,doneText:`_doneText_1q5ed_255`},c=t();function l({isOpen:e,onClose:t}){let{t:n}=r(),{isEncrypted:l,enableEncryption:u,disableEncryption:d,isLoading:f,error:p,setError:m}=i(),[h,g]=(0,o.useState)(`main`),[_,v]=(0,o.useState)(``),[y,b]=(0,o.useState)(``),[x,S]=(0,o.useState)(``),[C,w]=(0,o.useState)(``),[T,E]=(0,o.useState)(``),[D,O]=(0,o.useState)(``),[k,A]=(0,o.useState)(0);(0,o.useEffect)(()=>{e&&(g(`main`),m(null))},[e,m]);let j=(0,o.useRef)(null),M=(0,o.useCallback)(async()=>{let e=_.toLowerCase()+y;if(_.length!==3||y.length!==3){m(n(`Введите 3 буквы и 3 цифры`));return}if(e!==x.toLowerCase()+C){m(n(`Пароли не совпадают`));return}if(g(`progress`),A(10),setTimeout(()=>A(30),200),setTimeout(()=>A(60),500),setTimeout(()=>A(90),800),!await u(e)){g(`main`);return}A(100),setTimeout(()=>g(`done`),500)},[_,y,x,C,u,m]),N=(0,o.useCallback)(async()=>{let e=T.toLowerCase()+D;if(T.length!==3||D.length!==3){m(n(`Введите пароль`));return}await d(e)},[T,D,d,m]),P=(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(var(--accent-rgb,167,79,255),0.1)`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]});return(0,c.jsxs)(a,{isOpen:e,onClose:t,title:n(`Шифрование базы`),maxWidth:`400px`,closeRef:j,children:[h===`main`&&!l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Что зашифровано`)}),(0,c.jsxs)(`div`,{className:s.featureList,children:[(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Сообщения, медиа, вложения`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Криптоключи E2EE (сессии, identity)`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Токен авторизации и данные аккаунтов`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#888`}}),(0,c.jsx)(`span`,{className:s.muted,children:n(`Настройки интерфейса без изменений`)})]})]})]}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Как работает`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`При включении задаётся пароль (3 буквы + 3 цифры). Данные шифруются на устройстве алгоритмом Argon2id + XChaCha20. При каждом запуске приложения потребуется ввести пароль.`)})]}),(0,c.jsxs)(`div`,{className:s.warnBox,children:[(0,c.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,fill:`#ff9500`,style:{flexShrink:0,marginTop:1},children:(0,c.jsx)(`path`,{d:`M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 10-2 0 1 1 0 002 0zm-1-2a.75.75 0 01-.75-.75v-3.5a.75.75 0 011.5 0v3.5A.75.75 0 0110 11z`})}),(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`p`,{className:s.warnText,children:n(`Восстановление пароля невозможно.`)}),(0,c.jsx)(`p`,{className:s.warnText,children:n(`При потере пароля данные будут безвозвратно утеряны.`)})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:_,onChange:e=>v(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:y,onChange:e=>b(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Подтвердите пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:x,onChange:e=>S(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:C,onChange:e=>w(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:M,disabled:f||_.length<3||y.length<3,children:n(f?`Шифрование...`:`Включить шифрование`)})]}),h===`main`&&l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(52,199,89,0.1)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`#34c759`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`div`,{className:s.activeBadge,children:n(`Шифрование активно`)}),(0,c.jsx)(`div`,{className:s.infoBlock,children:(0,c.jsx)(`p`,{className:s.infoText,children:n(`Сообщения, ключи E2EE и данные аккаунтов зашифрованы на этом устройстве.`)})}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Отключение шифрования`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`Все данные будут расшифрованы и сохранены в открытом виде. Пароль введите для подтверждения.`)})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:T,onChange:e=>E(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:D,onChange:e=>O(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.dangerBtn,onClick:N,disabled:f||T.length<3||D.length<3,children:n(f?`Расшифровка...`:`Отключить шифрование`)})]}),h===`progress`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsx)(`p`,{className:s.progressText,children:n(`Шифрование базы данных...`)}),(0,c.jsx)(`div`,{className:s.progressBar,children:(0,c.jsx)(`div`,{className:s.progressFill,style:{width:`${k}%`}})})]}),h===`done`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`circle`,{cx:`24`,cy:`24`,r:`20`,fill:`rgba(52,199,89,0.12)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M16 24l5 5 11-11`,stroke:`#34c759`,strokeWidth:`3`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`p`,{className:s.doneText,children:n(`Шифрование активно`)}),(0,c.jsx)(`p`,{className:s.muted,children:n(`При следующем запуске потребуется ввести пароль.`)}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:()=>j.current?.(),children:n(`Готово`)})]})]})}export{l as default};1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r,r as i}from"./index-DY9FqaHJ.js";import{t as a}from"./ModalShell-ClUKyIG2.js";var o=e(n(),1),s={step:`_step_1q5ed_1`,heroIcon:`_heroIcon_1q5ed_9`,fadeInScale:`_fadeInScale_1q5ed_1`,infoBlock:`_infoBlock_1q5ed_19`,infoTitle:`_infoTitle_1q5ed_26`,infoText:`_infoText_1q5ed_35`,featureList:`_featureList_1q5ed_42`,featureItem:`_featureItem_1q5ed_49`,dot:`_dot_1q5ed_65`,muted:`_muted_1q5ed_72`,warnBox:`_warnBox_1q5ed_77`,warnText:`_warnText_1q5ed_91`,fieldGroup:`_fieldGroup_1q5ed_102`,fieldLabel:`_fieldLabel_1q5ed_109`,passwordRow:`_passwordRow_1q5ed_116`,passwordInput:`_passwordInput_1q5ed_122`,activeBadge:`_activeBadge_1q5ed_152`,error:`_error_1q5ed_165`,primaryBtn:`_primaryBtn_1q5ed_177`,dangerBtn:`_dangerBtn_1q5ed_206`,progressBar:`_progressBar_1q5ed_234`,progressFill:`_progressFill_1q5ed_242`,progressText:`_progressText_1q5ed_249`,doneText:`_doneText_1q5ed_255`},c=t();function l({isOpen:e,onClose:t}){let{t:n}=r(),{isEncrypted:l,enableEncryption:u,disableEncryption:d,isLoading:f,error:p,setError:m}=i(),[h,g]=(0,o.useState)(`main`),[_,v]=(0,o.useState)(``),[y,b]=(0,o.useState)(``),[x,S]=(0,o.useState)(``),[C,w]=(0,o.useState)(``),[T,E]=(0,o.useState)(``),[D,O]=(0,o.useState)(``),[k,A]=(0,o.useState)(0);(0,o.useEffect)(()=>{e&&(g(`main`),m(null))},[e,m]);let j=(0,o.useRef)(null),M=(0,o.useCallback)(async()=>{let e=_.toLowerCase()+y;if(_.length!==3||y.length!==3){m(n(`Введите 3 буквы и 3 цифры`));return}if(e!==x.toLowerCase()+C){m(n(`Пароли не совпадают`));return}if(g(`progress`),A(10),setTimeout(()=>A(30),200),setTimeout(()=>A(60),500),setTimeout(()=>A(90),800),!await u(e)){g(`main`);return}A(100),setTimeout(()=>g(`done`),500)},[_,y,x,C,u,m]),N=(0,o.useCallback)(async()=>{let e=T.toLowerCase()+D;if(T.length!==3||D.length!==3){m(n(`Введите пароль`));return}await d(e)},[T,D,d,m]),P=(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(var(--accent-rgb,167,79,255),0.1)`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`var(--accent-solid,#a74fff)`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]});return(0,c.jsxs)(a,{isOpen:e,onClose:t,title:n(`Шифрование базы`),maxWidth:`400px`,closeRef:j,children:[h===`main`&&!l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Что зашифровано`)}),(0,c.jsxs)(`div`,{className:s.featureList,children:[(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Сообщения, медиа, вложения`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Криптоключи E2EE (сессии, identity)`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#34c759`}}),(0,c.jsx)(`span`,{children:n(`Токен авторизации и данные аккаунтов`)})]}),(0,c.jsxs)(`div`,{className:s.featureItem,children:[(0,c.jsx)(`span`,{className:s.dot,style:{background:`#888`}}),(0,c.jsx)(`span`,{className:s.muted,children:n(`Настройки интерфейса без изменений`)})]})]})]}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Как работает`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`При включении задаётся пароль (3 буквы + 3 цифры). Данные шифруются на устройстве алгоритмом Argon2id + XChaCha20. При каждом запуске приложения потребуется ввести пароль.`)})]}),(0,c.jsxs)(`div`,{className:s.warnBox,children:[(0,c.jsx)(`svg`,{viewBox:`0 0 20 20`,width:`16`,height:`16`,fill:`#ff9500`,style:{flexShrink:0,marginTop:1},children:(0,c.jsx)(`path`,{d:`M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 10-2 0 1 1 0 002 0zm-1-2a.75.75 0 01-.75-.75v-3.5a.75.75 0 011.5 0v3.5A.75.75 0 0110 11z`})}),(0,c.jsxs)(`div`,{children:[(0,c.jsx)(`p`,{className:s.warnText,children:n(`Восстановление пароля невозможно.`)}),(0,c.jsx)(`p`,{className:s.warnText,children:n(`При потере пароля данные будут безвозвратно утеряны.`)})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:_,onChange:e=>v(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:y,onChange:e=>b(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Подтвердите пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:x,onChange:e=>S(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:C,onChange:e=>w(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:M,disabled:f||_.length<3||y.length<3,children:n(f?`Шифрование...`:`Включить шифрование`)})]}),h===`main`&&l&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`path`,{d:`M24 4L8 12v10c0 11.1 6.8 21.5 16 24 9.2-2.5 16-12.9 16-24V12L24 4z`,fill:`rgba(52,199,89,0.1)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M20 24l3 3 6-6`,stroke:`#34c759`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`div`,{className:s.activeBadge,children:n(`Шифрование активно`)}),(0,c.jsx)(`div`,{className:s.infoBlock,children:(0,c.jsx)(`p`,{className:s.infoText,children:n(`Сообщения, ключи E2EE и данные аккаунтов зашифрованы на этом устройстве.`)})}),(0,c.jsxs)(`div`,{className:s.infoBlock,children:[(0,c.jsx)(`p`,{className:s.infoTitle,children:n(`Отключение шифрования`)}),(0,c.jsx)(`p`,{className:s.infoText,children:n(`Все данные будут расшифрованы и сохранены в открытом виде. Пароль введите для подтверждения.`)})]}),(0,c.jsxs)(`div`,{className:s.fieldGroup,children:[(0,c.jsx)(`label`,{className:s.fieldLabel,children:n(`Пароль`)}),(0,c.jsxs)(`div`,{className:s.passwordRow,children:[(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`ABC`,value:T,onChange:e=>E(e.target.value.replace(/[^a-zA-Z]/g,``).slice(0,3)),autoComplete:`off`,autoCapitalize:`off`}),(0,c.jsx)(`input`,{className:s.passwordInput,type:`text`,maxLength:3,placeholder:`123`,value:D,onChange:e=>O(e.target.value.replace(/\D/g,``).slice(0,3)),autoComplete:`off`})]})]}),p&&(0,c.jsx)(`div`,{className:s.error,children:p}),(0,c.jsx)(`button`,{className:s.dangerBtn,onClick:N,disabled:f||T.length<3||D.length<3,children:n(f?`Расшифровка...`:`Отключить шифрование`)})]}),h===`progress`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:P}),(0,c.jsx)(`p`,{className:s.progressText,children:n(`Шифрование базы данных...`)}),(0,c.jsx)(`div`,{className:s.progressBar,children:(0,c.jsx)(`div`,{className:s.progressFill,style:{width:`${k}%`}})})]}),h===`done`&&(0,c.jsxs)(`div`,{className:s.step,children:[(0,c.jsx)(`div`,{className:s.heroIcon,children:(0,c.jsxs)(`svg`,{viewBox:`0 0 48 48`,width:`52`,height:`52`,fill:`none`,children:[(0,c.jsx)(`circle`,{cx:`24`,cy:`24`,r:`20`,fill:`rgba(52,199,89,0.12)`,stroke:`#34c759`,strokeWidth:`2`}),(0,c.jsx)(`path`,{d:`M16 24l5 5 11-11`,stroke:`#34c759`,strokeWidth:`3`,strokeLinecap:`round`,strokeLinejoin:`round`})]})}),(0,c.jsx)(`p`,{className:s.doneText,children:n(`Шифрование активно`)}),(0,c.jsx)(`p`,{className:s.muted,children:n(`При следующем запуске потребуется ввести пароль.`)}),(0,c.jsx)(`button`,{className:s.primaryBtn,onClick:()=>j.current?.(),children:n(`Готово`)})]})]})}export{l as default};
1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r}from"./index-HjRUEDl2.js";var i=e(n(),1),a={overlay:`_overlay_jh7o2_11`,open:`_open_jh7o2_27`,closing:`_closing_jh7o2_33`,content:`_content_jh7o2_40`,dangerBorder:`_dangerBorder_jh7o2_72`,title:`_title_jh7o2_77`,closeBtn:`_closeBtn_jh7o2_86`,backBtn:`_backBtn_jh7o2_110`,fadeIn:`_fadeIn_jh7o2_1`,fadeOut:`_fadeOut_jh7o2_1`},o=t();function s({isOpen:e,onClose:t,children:n,maxWidth:s=`380px`,title:c,showClose:l=!0,danger:u=!1,dangerColor:d,onBack:f,closeRef:p}){let{t:m}=r(),[h,g]=(0,i.useState)(e),[_,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),x=(0,i.useRef)(t);x.current=t;let S=(0,i.useCallback)(()=>{_||v(!0)},[_]);return(0,i.useEffect)(()=>{p&&(p.current=S)},[p,S]),(0,i.useEffect)(()=>{if(e){g(!0),v(!1),b(!1);let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>{b(!0)})});return()=>cancelAnimationFrame(e)}},[e]),(0,i.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{g(!1),v(!1),b(!1),x.current()},400);return()=>clearTimeout(e)},[_]),(0,i.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&S()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,S]),h?(0,o.jsx)(`div`,{className:`${a.overlay} ${y&&!_?a.open:``} ${_?a.closing:``}`,onClick:S,children:(0,o.jsxs)(`div`,{className:`${a.content} ${u?a.dangerBorder:``}`,style:{maxWidth:s},onClick:e=>e.stopPropagation(),children:[f&&(0,o.jsx)(`button`,{className:a.backBtn,onClick:f,children:(0,o.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`22`,height:`22`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,o.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),c&&(0,o.jsx)(`h3`,{className:a.title,style:u?{color:d||`#ff3b30`}:void 0,children:m(c)}),n,l&&(0,o.jsx)(`button`,{className:a.closeBtn,onClick:S,children:m(`Закрыть`)})]})}):null}export{s as t};1import{r as e}from"./rolldown-runtime-QTnfLwEv.js";import{t,u as n}from"./vendor-BbmWO_jh.js";import{l as r}from"./index-DY9FqaHJ.js";var i=e(n(),1),a={overlay:`_overlay_jh7o2_11`,open:`_open_jh7o2_27`,closing:`_closing_jh7o2_33`,content:`_content_jh7o2_40`,dangerBorder:`_dangerBorder_jh7o2_72`,title:`_title_jh7o2_77`,closeBtn:`_closeBtn_jh7o2_86`,backBtn:`_backBtn_jh7o2_110`,fadeIn:`_fadeIn_jh7o2_1`,fadeOut:`_fadeOut_jh7o2_1`},o=t();function s({isOpen:e,onClose:t,children:n,maxWidth:s=`380px`,title:c,showClose:l=!0,danger:u=!1,dangerColor:d,onBack:f,closeRef:p}){let{t:m}=r(),[h,g]=(0,i.useState)(e),[_,v]=(0,i.useState)(!1),[y,b]=(0,i.useState)(!1),x=(0,i.useRef)(t);x.current=t;let S=(0,i.useCallback)(()=>{_||v(!0)},[_]);return(0,i.useEffect)(()=>{p&&(p.current=S)},[p,S]),(0,i.useEffect)(()=>{if(e){g(!0),v(!1),b(!1);let e=requestAnimationFrame(()=>{requestAnimationFrame(()=>{b(!0)})});return()=>cancelAnimationFrame(e)}},[e]),(0,i.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>{g(!1),v(!1),b(!1),x.current()},400);return()=>clearTimeout(e)},[_]),(0,i.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&S()};return document.addEventListener(`keydown`,t),()=>document.removeEventListener(`keydown`,t)},[e,S]),h?(0,o.jsx)(`div`,{className:`${a.overlay} ${y&&!_?a.open:``} ${_?a.closing:``}`,onClick:S,children:(0,o.jsxs)(`div`,{className:`${a.content} ${u?a.dangerBorder:``}`,style:{maxWidth:s},onClick:e=>e.stopPropagation(),children:[f&&(0,o.jsx)(`button`,{className:a.backBtn,onClick:f,children:(0,o.jsx)(`svg`,{viewBox:`0 0 24 24`,width:`22`,height:`22`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,o.jsx)(`polyline`,{points:`15 18 9 12 15 6`})})}),c&&(0,o.jsx)(`h3`,{className:a.title,style:u?{color:d||`#ff3b30`}:void 0,children:m(c)}),n,l&&(0,o.jsx)(`button`,{className:a.closeBtn,onClick:S,children:m(`Закрыть`)})]})}):null}export{s as t};
1import{o as e,u as t}from"./MessengerPage-BEPX8mwe.js";export{e as getOneTimePreKeys,t as markOneTimePreKeyUsed};1import{o as e,u as t}from"./MessengerPage-6Fs5zx2C.js";export{e as getOneTimePreKeys,t as markOneTimePreKeyUsed};
28 unmodified lines2930313233343528 unmodified lines<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Montserrat:wght@400;500;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Unbounded:wght@700&family=Onest:wght@400&display=swap" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/@fontsource/gilroy@5.1.0/700.css" rel="stylesheet"><title>4SEND Messenger</title><script type="module" crossorigin src="/assets/index-HjRUEDl2.js"></script><link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-QTnfLwEv.js"><link rel="modulepreload" crossorigin href="/assets/vendor-BbmWO_jh.js"><link rel="modulepreload" crossorigin href="/assets/keyStore-DDPZ0U62.js">28 unmodified lines2930313233343528 unmodified lines<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Montserrat:wght@400;500;600;700;800;900&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Unbounded:wght@700&family=Onest:wght@400&display=swap" rel="stylesheet"><link href="https://cdn.jsdelivr.net/npm/@fontsource/gilroy@5.1.0/700.css" rel="stylesheet"><title>4SEND Messenger</title><script type="module" crossorigin src="/assets/index-DY9FqaHJ.js"></script><link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-QTnfLwEv.js"><link rel="modulepreload" crossorigin href="/assets/vendor-BbmWO_jh.js"><link rel="modulepreload" crossorigin href="/assets/keyStore-DDPZ0U62.js">
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051{ "name": "react", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "build": "tsc -b && vite build", "lint": "oxlint", "preview": "vite preview" }, "dependencies": { "@tanstack/react-virtual": "^3.14.7", "chart.js": "^4.5.1", "firebase": "^11.10.0", "flexsearch": "^0.8.212", "html5-qrcode": "^2.3.8", "idb": "^8.0.3", "libsodium-wrappers": "^0.7.14", "libsodium-wrappers-sumo": "^0.8.4", "lucide-react": "^1.21.0", "qrcode": "^1.5.4", "react": "^19.2.7", "react-chartjs-2": "^5.3.1", "react-dom": "^19.2.7", "react-router-dom": "^7.18.0", "socket.io-client": "^4.8.3" }, "devDependencies": { "@eslint/js": "^10.0.1", "@types/libsodium-wrappers": "^0.7.14", "@types/node": "^24.13.2", "@types/qrcode": "^1.5.6", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.3", "eslint": "^10.5.0", "eslint-config-prettier": "^10.1.8", "eslint-plugin-import": "^2.32.0", "eslint-plugin-jsx-a11y": "^6.10.2", "eslint-plugin-react": "^7.37.5", "eslint-plugin-react-hooks": "^7.1.1", "oxlint": "^1.69.0", "playwright": "^1.61.1", "prettier": "^3.8.4", "typescript": "~6.0.2", "vite": "^8.1.0", "vite-plugin-pwa": "^1.3.0", "workbox-window": "^7.4.1" }}1try{self[`workbox:core:7.4.0`]&&_()}catch{}var e=(e,...t)=>{let n=e;return t.length>0&&(n+=` :: ${JSON.stringify(t)}`),n},t=class extends Error{constructor(t,n){let r=e(t,n);super(r),this.name=t,this.details=n}},n={googleAnalytics:`googleAnalytics`,precache:`precache-v2`,prefix:`workbox`,runtime:`runtime`,suffix:typeof registration<`u`?registration.scope:``},r=e=>[n.prefix,e,n.suffix].filter(e=>e&&e.length>0).join(`-`),i=e=>{for(let t of Object.keys(n))e(t)},a={updateDetails:e=>{i(t=>{typeof e[t]==`string`&&(n[t]=e[t])})},getGoogleAnalyticsName:e=>e||r(n.googleAnalytics),getPrecacheName:e=>e||r(n.precache),getPrefix:()=>n.prefix,getRuntimeName:e=>e||r(n.runtime),getSuffix:()=>n.suffix};function o(e,t){let n=t();return e.waitUntil(n),n}try{self[`workbox:precaching:7.4.0`]&&_()}catch{}var s=`__WB_REVISION__`;function c(e){if(!e)throw new t(`add-to-cache-list-unexpected-type`,{entry:e});if(typeof e==`string`){let t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}let{revision:n,url:r}=e;if(!r)throw new t(`add-to-cache-list-unexpected-type`,{entry:e});if(!n){let e=new URL(r,location.href);return{cacheKey:e.href,url:e.href}}let i=new URL(r,location.href),a=new URL(r,location.href);return i.searchParams.set(s,n),{cacheKey:i.href,url:a.href}}var l=class{constructor(){this.updatedURLs=[],this.notUpdatedURLs=[],this.handlerWillStart=async({request:e,state:t})=>{t&&(t.originalRequest=e)},this.cachedResponseWillBeUsed=async({event:e,state:t,cachedResponse:n})=>{if(e.type===`install`&&t&&t.originalRequest&&t.originalRequest instanceof Request){let e=t.originalRequest.url;n?this.notUpdatedURLs.push(e):this.updatedURLs.push(e)}return n}}},u=class{constructor({precacheController:e}){this.cacheKeyWillBeUsed=async({request:e,params:t})=>{let n=t?.cacheKey||this._precacheController.getCacheKeyForURL(e.url);return n?new Request(n,{headers:e.headers}):e},this._precacheController=e}},d;function f(){if(d===void 0){let e=new Response(``);if(`body`in e)try{new Response(e.body),d=!0}catch{d=!1}d=!1}return d}async function p(e,n){let r=null;if(e.url&&(r=new URL(e.url).origin),r!==self.location.origin)throw new t(`cross-origin-copy-response`,{origin:r});let i=e.clone(),a={headers:new Headers(i.headers),status:i.status,statusText:i.statusText},o=n?n(a):a,s=f()?i.body:await i.blob();return new Response(s,o)}var ee=e=>new URL(String(e),location.href).href.replace(RegExp(`^${location.origin}`),``);function m(e,t){let n=new URL(e);for(let e of t)n.searchParams.delete(e);return n.href}async function h(e,t,n,r){let i=m(t.url,n);if(t.url===i)return e.match(t,r);let a=Object.assign(Object.assign({},r),{ignoreSearch:!0}),o=await e.keys(t,a);for(let t of o)if(i===m(t.url,n))return e.match(t,r)}var g=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}},v=new Set;async function y(){for(let e of v)await e()}function te(e){return new Promise(t=>setTimeout(t,e))}try{self[`workbox:strategies:7.4.0`]&&_()}catch{}function b(e){return typeof e==`string`?new Request(e):e}var ne=class{constructor(e,t){this._cacheKeys={},Object.assign(this,t),this.event=t.event,this._strategy=e,this._handlerDeferred=new g,this._extendLifetimePromises=[],this._plugins=[...e.plugins],this._pluginStateMap=new Map;for(let e of this._plugins)this._pluginStateMap.set(e,{});this.event.waitUntil(this._handlerDeferred.promise)}async fetch(e){let{event:n}=this,r=b(e);if(r.mode===`navigate`&&n instanceof FetchEvent&&n.preloadResponse){let e=await n.preloadResponse;if(e)return e}let i=this.hasCallback(`fetchDidFail`)?r.clone():null;try{for(let e of this.iterateCallbacks(`requestWillFetch`))r=await e({request:r.clone(),event:n})}catch(e){if(e instanceof Error)throw new t(`plugin-error-request-will-fetch`,{thrownErrorMessage:e.message})}let a=r.clone();try{let e;e=await fetch(r,r.mode===`navigate`?void 0:this._strategy.fetchOptions);for(let t of this.iterateCallbacks(`fetchDidSucceed`))e=await t({event:n,request:a,response:e});return e}catch(e){throw i&&await this.runCallbacks(`fetchDidFail`,{error:e,event:n,originalRequest:i.clone(),request:a.clone()}),e}}async fetchAndCachePut(e){let t=await this.fetch(e),n=t.clone();return this.waitUntil(this.cachePut(e,n)),t}async cacheMatch(e){let t=b(e),n,{cacheName:r,matchOptions:i}=this._strategy,a=await this.getCacheKey(t,`read`),o=Object.assign(Object.assign({},i),{cacheName:r});n=await caches.match(a,o);for(let e of this.iterateCallbacks(`cachedResponseWillBeUsed`))n=await e({cacheName:r,matchOptions:i,cachedResponse:n,request:a,event:this.event})||void 0;return n}async cachePut(e,n){let r=b(e);await te(0);let i=await this.getCacheKey(r,`write`);if(!n)throw new t(`cache-put-with-no-response`,{url:ee(i.url)});let a=await this._ensureResponseSafeToCache(n);if(!a)return!1;let{cacheName:o,matchOptions:s}=this._strategy,c=await self.caches.open(o),l=this.hasCallback(`cacheDidUpdate`),u=l?await h(c,i.clone(),[`__WB_REVISION__`],s):null;try{await c.put(i,l?a.clone():a)}catch(e){if(e instanceof Error)throw e.name===`QuotaExceededError`&&await y(),e}for(let e of this.iterateCallbacks(`cacheDidUpdate`))await e({cacheName:o,oldResponse:u,newResponse:a.clone(),request:i,event:this.event});return!0}async getCacheKey(e,t){let n=`${e.url} | ${t}`;if(!this._cacheKeys[n]){let r=e;for(let e of this.iterateCallbacks(`cacheKeyWillBeUsed`))r=b(await e({mode:t,request:r,event:this.event,params:this.params}));this._cacheKeys[n]=r}return this._cacheKeys[n]}hasCallback(e){for(let t of this._strategy.plugins)if(e in t)return!0;return!1}async runCallbacks(e,t){for(let n of this.iterateCallbacks(e))await n(t)}*iterateCallbacks(e){for(let t of this._strategy.plugins)if(typeof t[e]==`function`){let n=this._pluginStateMap.get(t);yield r=>{let i=Object.assign(Object.assign({},r),{state:n});return t[e](i)}}}waitUntil(e){return this._extendLifetimePromises.push(e),e}async doneWaiting(){for(;this._extendLifetimePromises.length;){let e=this._extendLifetimePromises.splice(0),t=(await Promise.allSettled(e)).find(e=>e.status===`rejected`);if(t)throw t.reason}}destroy(){this._handlerDeferred.resolve(null)}async _ensureResponseSafeToCache(e){let t=e,n=!1;for(let e of this.iterateCallbacks(`cacheWillUpdate`))if(t=await e({request:this.request,response:t,event:this.event})||void 0,n=!0,!t)break;return n||t&&t.status!==200&&(t=void 0),t}},x=class{constructor(e={}){this.cacheName=a.getRuntimeName(e.cacheName),this.plugins=e.plugins||[],this.fetchOptions=e.fetchOptions,this.matchOptions=e.matchOptions}handle(e){let[t]=this.handleAll(e);return t}handleAll(e){e instanceof FetchEvent&&(e={event:e,request:e.request});let t=e.event,n=typeof e.request==`string`?new Request(e.request):e.request,r=`params`in e?e.params:void 0,i=new ne(this,{event:t,request:n,params:r}),a=this._getResponse(i,n,t);return[a,this._awaitComplete(a,i,n,t)]}async _getResponse(e,n,r){await e.runCallbacks(`handlerWillStart`,{event:r,request:n});let i;try{if(i=await this._handle(n,e),!i||i.type===`error`)throw new t(`no-response`,{url:n.url})}catch(t){if(t instanceof Error){for(let a of e.iterateCallbacks(`handlerDidError`))if(i=await a({error:t,event:r,request:n}),i)break}if(!i)throw t}for(let t of e.iterateCallbacks(`handlerWillRespond`))i=await t({event:r,request:n,response:i});return i}async _awaitComplete(e,t,n,r){let i,a;try{i=await e}catch{}try{await t.runCallbacks(`handlerDidRespond`,{event:r,request:n,response:i}),await t.doneWaiting()}catch(e){e instanceof Error&&(a=e)}if(await t.runCallbacks(`handlerDidComplete`,{event:r,request:n,response:i,error:a}),t.destroy(),a)throw a}},S=class e extends x{constructor(t={}){t.cacheName=a.getPrecacheName(t.cacheName),super(t),this._fallbackToNetwork=t.fallbackToNetwork!==!1,this.plugins.push(e.copyRedirectedCacheableResponsesPlugin)}async _handle(e,t){return await t.cacheMatch(e)||(t.event&&t.event.type===`install`?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,n){let r,i=n.params||{};if(this._fallbackToNetwork){let t=i.integrity,a=e.integrity,o=!a||a===t;r=await n.fetch(new Request(e,{integrity:e.mode===`no-cors`?void 0:a||t})),t&&o&&e.mode!==`no-cors`&&(this._useDefaultCacheabilityPluginIfNeeded(),await n.cachePut(e,r.clone()))}else throw new t(`missing-precache-entry`,{cacheName:this.cacheName,url:e.url});return r}async _handleInstall(e,n){this._useDefaultCacheabilityPluginIfNeeded();let r=await n.fetch(e);if(!await n.cachePut(e,r.clone()))throw new t(`bad-precaching-response`,{url:e.url,status:r.status});return r}_useDefaultCacheabilityPluginIfNeeded(){let t=null,n=0;for(let[r,i]of this.plugins.entries())i!==e.copyRedirectedCacheableResponsesPlugin&&(i===e.defaultPrecacheCacheabilityPlugin&&(t=r),i.cacheWillUpdate&&n++);n===0?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):n>1&&t!==null&&this.plugins.splice(t,1)}};S.defaultPrecacheCacheabilityPlugin={async cacheWillUpdate({response:e}){return!e||e.status>=400?null:e}},S.copyRedirectedCacheableResponsesPlugin={async cacheWillUpdate({response:e}){return e.redirected?await p(e):e}};var C=class{constructor({cacheName:e,plugins:t=[],fallbackToNetwork:n=!0}={}){this._urlsToCacheKeys=new Map,this._urlsToCacheModes=new Map,this._cacheKeysToIntegrities=new Map,this._strategy=new S({cacheName:a.getPrecacheName(e),plugins:[...t,new u({precacheController:this})],fallbackToNetwork:n}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this._strategy}precache(e){this.addToCacheList(e),this._installAndActiveListenersAdded||=(self.addEventListener(`install`,this.install),self.addEventListener(`activate`,this.activate),!0)}addToCacheList(e){let n=[];for(let r of e){typeof r==`string`?n.push(r):r&&r.revision===void 0&&n.push(r.url);let{cacheKey:e,url:i}=c(r),a=typeof r!=`string`&&r.revision?`reload`:`default`;if(this._urlsToCacheKeys.has(i)&&this._urlsToCacheKeys.get(i)!==e)throw new t(`add-to-cache-list-conflicting-entries`,{firstEntry:this._urlsToCacheKeys.get(i),secondEntry:e});if(typeof r!=`string`&&r.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==r.integrity)throw new t(`add-to-cache-list-conflicting-integrities`,{url:i});this._cacheKeysToIntegrities.set(e,r.integrity)}if(this._urlsToCacheKeys.set(i,e),this._urlsToCacheModes.set(i,a),n.length>0){let e=`Workbox is precaching URLs without revision info: ${n.join(`, `)}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(e)}}}install(e){return o(e,async()=>{let t=new l;this.strategy.plugins.push(t);for(let[t,n]of this._urlsToCacheKeys){let r=this._cacheKeysToIntegrities.get(n),i=this._urlsToCacheModes.get(t),a=new Request(t,{integrity:r,cache:i,credentials:`same-origin`});await Promise.all(this.strategy.handleAll({params:{cacheKey:n},request:a,event:e}))}let{updatedURLs:n,notUpdatedURLs:r}=t;return{updatedURLs:n,notUpdatedURLs:r}})}activate(e){return o(e,async()=>{let e=await self.caches.open(this.strategy.cacheName),t=await e.keys(),n=new Set(this._urlsToCacheKeys.values()),r=[];for(let i of t)n.has(i.url)||(await e.delete(i),r.push(i.url));return{deletedURLs:r}})}getURLsToCacheKeys(){return this._urlsToCacheKeys}getCachedURLs(){return[...this._urlsToCacheKeys.keys()]}getCacheKeyForURL(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForCacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,n=this.getCacheKeyForURL(t);if(n)return(await self.caches.open(this.strategy.cacheName)).match(n)}createHandlerBoundToURL(e){let n=this.getCacheKeyForURL(e);if(!n)throw new t(`non-precached-url`,{url:e});return t=>(t.request=new Request(e),t.params=Object.assign({cacheKey:n},t.params),this.strategy.handle(t))}},w,T=()=>(w||=new C,w);try{self[`workbox:routing:7.4.0`]&&_()}catch{}var E=e=>e&&typeof e==`object`?e:{handle:e},D=class{constructor(e,t,n=`GET`){this.handler=E(t),this.match=e,this.method=n}setCatchHandler(e){this.catchHandler=E(e)}},re=class extends D{constructor(e,t,n){super(({url:t})=>{let n=e.exec(t.href);if(n&&!(t.origin!==location.origin&&n.index!==0))return n.slice(1)},t,n)}},ie=class{constructor(){this._routes=new Map,this._defaultHandlerMap=new Map}get routes(){return this._routes}addFetchListener(){self.addEventListener(`fetch`,(e=>{let{request:t}=e,n=this.handleRequest({request:t,event:e});n&&e.respondWith(n)}))}addCacheListener(){self.addEventListener(`message`,(e=>{if(e.data&&e.data.type===`CACHE_URLS`){let{payload:t}=e.data,n=Promise.all(t.urlsToCache.map(t=>{typeof t==`string`&&(t=[t]);let n=new Request(...t);return this.handleRequest({request:n,event:e})}));e.waitUntil(n),e.ports&&e.ports[0]&&n.then(()=>e.ports[0].postMessage(!0))}}))}handleRequest({request:e,event:t}){let n=new URL(e.url,location.href);if(!n.protocol.startsWith(`http`))return;let r=n.origin===location.origin,{params:i,route:a}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:n}),o=a&&a.handler,s=e.method;if(!o&&this._defaultHandlerMap.has(s)&&(o=this._defaultHandlerMap.get(s)),!o)return;let c;try{c=o.handle({url:n,request:e,event:t,params:i})}catch(e){c=Promise.reject(e)}let l=a&&a.catchHandler;return c instanceof Promise&&(this._catchHandler||l)&&(c=c.catch(async r=>{if(l)try{return await l.handle({url:n,request:e,event:t,params:i})}catch(e){e instanceof Error&&(r=e)}if(this._catchHandler)return this._catchHandler.handle({url:n,request:e,event:t});throw r})),c}findMatchingRoute({url:e,sameOrigin:t,request:n,event:r}){let i=this._routes.get(n.method)||[];for(let a of i){let i,o=a.match({url:e,sameOrigin:t,request:n,event:r});if(o)return i=o,(Array.isArray(i)&&i.length===0||o.constructor===Object&&Object.keys(o).length===0||typeof o==`boolean`)&&(i=void 0),{route:a,params:i}}return{}}setDefaultHandler(e,t=`GET`){this._defaultHandlerMap.set(t,E(e))}setCatchHandler(e){this._catchHandler=E(e)}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new t(`unregister-route-but-not-found-with-method`,{method:e.method});let n=this._routes.get(e.method).indexOf(e);if(n>-1)this._routes.get(e.method).splice(n,1);else throw new t(`unregister-route-route-not-registered`)}},O,ae=()=>(O||(O=new ie,O.addFetchListener(),O.addCacheListener()),O);function k(e,n,r){let i;if(typeof e==`string`){let t=new URL(e,location.href);i=new D(({url:e})=>e.href===t.href,n,r)}else if(e instanceof RegExp)i=new re(e,n,r);else if(typeof e==`function`)i=new D(e,n,r);else if(e instanceof D)i=e;else throw new t(`unsupported-route-type`,{moduleName:`workbox-routing`,funcName:`registerRoute`,paramName:`capture`});return ae().registerRoute(i),i}function oe(e,t=[]){for(let n of[...e.searchParams.keys()])t.some(e=>e.test(n))&&e.searchParams.delete(n);return e}function*se(e,{ignoreURLParametersMatching:t=[/^utm_/,/^fbclid$/],directoryIndex:n=`index.html`,cleanURLs:r=!0,urlManipulation:i}={}){let a=new URL(e,location.href);a.hash=``,yield a.href;let o=oe(a,t);if(yield o.href,n&&o.pathname.endsWith(`/`)){let e=new URL(o.href);e.pathname+=n,yield e.href}if(r){let e=new URL(o.href);e.pathname+=`.html`,yield e.href}if(i){let e=i({url:a});for(let t of e)yield t.href}}var A=class extends D{constructor(e,t){super(({request:n})=>{let r=e.getURLsToCacheKeys();for(let i of se(n.url,t)){let t=r.get(i);if(t)return{cacheKey:t,integrity:e.getIntegrityForCacheKey(t)}}},e.strategy)}};function j(e){k(new A(T(),e))}function M(e){T().precache(e)}function N(e,t){M(e),j(t)}var P=class extends x{async _handle(e,n){let r=await n.cacheMatch(e),i;if(!r)try{r=await n.fetchAndCachePut(e)}catch(e){e instanceof Error&&(i=e)}if(!r)throw new t(`no-response`,{url:e.url,error:i});return r}};function F(e){e.then(()=>{})}var I=(e,t)=>t.some(t=>e instanceof t),L,R;function z(){return L||=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]}function B(){return R||=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]}var V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap;function ce(e){let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(q(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)});return t.then(t=>{t instanceof IDBCursor&&V.set(t,e)}).catch(()=>{}),G.set(t,e),t}function le(e){if(H.has(e))return;let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`complete`,i),e.removeEventListener(`error`,a),e.removeEventListener(`abort`,a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException(`AbortError`,`AbortError`)),r()};e.addEventListener(`complete`,i),e.addEventListener(`error`,a),e.addEventListener(`abort`,a)});H.set(e,t)}var K={get(e,t,n){if(e instanceof IDBTransaction){if(t===`done`)return H.get(e);if(t===`objectStoreNames`)return e.objectStoreNames||U.get(e);if(t===`store`)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return q(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t===`done`||t===`store`)||t in e}};function ue(e){K=e(K)}function de(e){return e===IDBDatabase.prototype.transaction&&!(`objectStoreNames`in IDBTransaction.prototype)?function(t,...n){let r=e.call(J(this),t,...n);return U.set(r,t.sort?t.sort():[t]),q(r)}:B().includes(e)?function(...t){return e.apply(J(this),t),q(V.get(this))}:function(...t){return q(e.apply(J(this),t))}}function fe(e){return typeof e==`function`?de(e):(e instanceof IDBTransaction&&le(e),I(e,z())?new Proxy(e,K):e)}function q(e){if(e instanceof IDBRequest)return ce(e);if(W.has(e))return W.get(e);let t=fe(e);return t!==e&&(W.set(e,t),G.set(t,e)),t}var J=e=>G.get(e);function pe(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){let o=indexedDB.open(e,t),s=q(o);return r&&o.addEventListener(`upgradeneeded`,e=>{r(q(o.result),e.oldVersion,e.newVersion,q(o.transaction),e)}),n&&o.addEventListener(`blocked`,e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener(`close`,()=>a()),i&&e.addEventListener(`versionchange`,e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}function me(e,{blocked:t}={}){let n=indexedDB.deleteDatabase(e);return t&&n.addEventListener(`blocked`,e=>t(e.oldVersion,e)),q(n).then(()=>void 0)}var he=[`get`,`getKey`,`getAll`,`getAllKeys`,`count`],ge=[`put`,`add`,`delete`,`clear`],Y=new Map;function X(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==`string`))return;if(Y.get(t))return Y.get(t);let n=t.replace(/FromIndex$/,``),r=t!==n,i=ge.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||he.includes(n)))return;let a=async function(e,...t){let a=this.transaction(e,i?`readwrite`:`readonly`),o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return Y.set(t,a),a}ue(e=>({...e,get:(t,n,r)=>X(t,n)||e.get(t,n,r),has:(t,n)=>!!X(t,n)||e.has(t,n)}));try{self[`workbox:expiration:7.4.0`]&&_()}catch{}var Z=`workbox-expiration`,Q=`cache-entries`,$=e=>{let t=new URL(e,location.href);return t.hash=``,t.href},_e=class{constructor(e){this._db=null,this._cacheName=e}_upgradeDb(e){let t=e.createObjectStore(Q,{keyPath:`id`});t.createIndex(`cacheName`,`cacheName`,{unique:!1}),t.createIndex(`timestamp`,`timestamp`,{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&me(this._cacheName)}async setTimestamp(e,t){e=$(e);let n={url:e,timestamp:t,cacheName:this._cacheName,id:this._getId(e)},r=(await this.getDb()).transaction(Q,`readwrite`,{durability:`relaxed`});await r.store.put(n),await r.done}async getTimestamp(e){return(await(await this.getDb()).get(Q,this._getId(e)))?.timestamp}async expireEntries(e,t){let n=await this.getDb(),r=await n.transaction(Q).store.index(`timestamp`).openCursor(null,`prev`),i=[],a=0;for(;r;){let n=r.value;n.cacheName===this._cacheName&&(e&&n.timestamp<e||t&&a>=t?i.push(r.value):a++),r=await r.continue()}let o=[];for(let e of i)await n.delete(Q,e.id),o.push(e.url);return o}_getId(e){return this._cacheName+`|`+$(e)}async getDb(){return this._db||=await pe(Z,1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)}),this._db}},ve=class{constructor(e,t={}){this._isRunning=!1,this._rerunRequested=!1,this._maxEntries=t.maxEntries,this._maxAgeSeconds=t.maxAgeSeconds,this._matchOptions=t.matchOptions,this._cacheName=e,this._timestampModel=new _e(e)}async expireEntries(){if(this._isRunning){this._rerunRequested=!0;return}this._isRunning=!0;let e=this._maxAgeSeconds?Date.now()-this._maxAgeSeconds*1e3:0,t=await this._timestampModel.expireEntries(e,this._maxEntries),n=await self.caches.open(this._cacheName);for(let e of t)await n.delete(e,this._matchOptions);this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,F(this.expireEntries()))}async updateTimestamp(e){await this._timestampModel.setTimestamp(e,Date.now())}async isURLExpired(e){if(this._maxAgeSeconds){let t=await this._timestampModel.getTimestamp(e),n=Date.now()-this._maxAgeSeconds*1e3;return t===void 0||t<n}else return!1}async delete(){this._rerunRequested=!1,await this._timestampModel.expireEntries(1/0)}};function ye(e){v.add(e)}var be=class{constructor(e={}){this.cachedResponseWillBeUsed=async({event:e,request:t,cacheName:n,cachedResponse:r})=>{if(!r)return null;let i=this._isResponseDateFresh(r),a=this._getCacheExpiration(n);F(a.expireEntries());let o=a.updateTimestamp(t.url);if(e)try{e.waitUntil(o)}catch{}return i?r:null},this.cacheDidUpdate=async({cacheName:e,request:t})=>{let n=this._getCacheExpiration(e);await n.updateTimestamp(t.url),await n.expireEntries()},this._config=e,this._maxAgeSeconds=e.maxAgeSeconds,this._cacheExpirations=new Map,e.purgeOnQuotaError&&ye(()=>this.deleteCacheAndMetadata())}_getCacheExpiration(e){if(e===a.getRuntimeName())throw new t(`expire-custom-caches-only`);let n=this._cacheExpirations.get(e);return n||(n=new ve(e,this._config),this._cacheExpirations.set(e,n)),n}_isResponseDateFresh(e){if(!this._maxAgeSeconds)return!0;let t=this._getDateHeaderTimestamp(e);return t===null||t>=Date.now()-this._maxAgeSeconds*1e3}_getDateHeaderTimestamp(e){if(!e.headers.has(`date`))return null;let t=e.headers.get(`date`),n=new Date(t).getTime();return isNaN(n)?null:n}async deleteCacheAndMetadata(){for(let[e,t]of this._cacheExpirations)await self.caches.delete(e),await t.delete();this._cacheExpirations=new Map}};N([{"revision":"7e6cb67aa9cf28050f2624e28a29f07e","url":"terms.html"},{"revision":"ee34904795012e3493a0c44b9f859308","url":"registerSW.js"},{"revision":"5be4c6cebfb9edbde2d13641ee401057","url":"privacy.html"},{"revision":"247dfacbec1ca7891c2e6a76c720a558","url":"pattern.svg"},{"revision":"f14cd675f0b6e7b885d32809abebae00","url":"notify.mp3"},{"revision":"effa7097c5ef2573e39c4d25a651493b","url":"index.html"},{"revision":"3b4fcfcf393eca4d264dca4a4663bc37","url":"icons.svg"},{"revision":"f46670f29cd911c162da51b955221002","url":"ico.png"},{"revision":"57d9c62138108b9c36062ef6b42999b0","url":"changelog.html"},{"revision":"36d60b85b445b4770dc8202baa0d64cf","url":"calling2.mp3"},{"revision":"61ac15422af330e0204ee6cf95634067","url":"calling.mp3"},{"revision":null,"url":"assets/vendor-BbmWO_jh.js"},{"revision":null,"url":"assets/storage-B_75ItAe.js"},{"revision":null,"url":"assets/socket-CbQsWyoH.js"},{"revision":null,"url":"assets/rolldown-runtime-QTnfLwEv.js"},{"revision":null,"url":"assets/libsodium-wrappers-DIT7SeqD.js"},{"revision":null,"url":"assets/keyStore-DDPZ0U62.js"},{"revision":null,"url":"assets/index-HjRUEDl2.js"},{"revision":null,"url":"assets/index-CJLIHFQ-.css"},{"revision":null,"url":"assets/encryption-CFSbljDF.js"},{"revision":null,"url":"assets/__vite-browser-external-BRm5n2qg.js"},{"revision":null,"url":"assets/ModalShell-DxpX6TOZ.css"},{"revision":null,"url":"assets/ModalShell-BrGMDJl_.js"},{"revision":null,"url":"assets/MessengerPage-BJOhOjc3.css"},{"revision":null,"url":"assets/MessengerPage-BEPX8mwe.js"},{"revision":null,"url":"assets/EncryptionModal-DVr1yxXX.js"},{"revision":null,"url":"assets/EncryptionModal-Bk9GLrBN.css"},{"revision":null,"url":"assets/EmojiPanel-C0q3T_JG.js"},{"revision":null,"url":"assets/EmojiPanel-Bf-sbcJk.css"},{"revision":null,"url":"assets/AvatarCropper-YXBtLMg1.js"},{"revision":null,"url":"assets/AvatarCropper-43twomjP.css"},{"revision":"61ac15422af330e0204ee6cf95634067","url":"calling.mp3"},{"revision":"36d60b85b445b4770dc8202baa0d64cf","url":"calling2.mp3"},{"revision":"f46670f29cd911c162da51b955221002","url":"ico.png"},{"revision":"f14cd675f0b6e7b885d32809abebae00","url":"notify.mp3"},{"revision":"5ba98964a3aeabde9f920bd5fa109422","url":"manifest.webmanifest"}]),k(({url:e})=>e.origin===`https://res.cloudinary.com`,new P({cacheName:`cloudinary-images`,plugins:[new be({maxEntries:100,maxAgeSeconds:3600*24*30})]})),self.addEventListener(`fetch`,e=>{let t=new URL(e.request.url);e.request.method===`POST`&&t.pathname===`/share-target`&&e.respondWith(xe(e.request))});async function xe(e){try{let t=(await e.formData()).get(`media`);if(t){let e=await caches.open(`shared-files`),n=await t.arrayBuffer();await e.put(`shared-file`,new Response(n,{headers:{"Content-Type":t.type,"X-File-Name":encodeURIComponent(t.name),"X-File-Size":String(t.size)}}))}}catch{}return Response.redirect(`/`,303)}self.addEventListener(`install`,()=>{self.skipWaiting()}),self.addEventListener(`activate`,e=>{e.waitUntil(self.clients.claim())}),self.addEventListener(`push`,e=>{let t={};try{t=e.data?e.data.json():{}}catch{t={title:`4SEND`,body:e.data?e.data.text():``}}let n=t.notification||t,r=n.title||t.title||`4SEND`,i=n.body||t.body||``,a=n.icon||`/ico.png`,o=n.click_action||t.data?.click_action||t.data?.url||`/`;e.waitUntil(self.registration.showNotification(r,{body:i,icon:a,data:{url:o},tag:`4send-notification`}))}),self.addEventListener(`notificationclick`,e=>{e.notification.close();let t=e.notification.data&&e.notification.data.url||`/`;e.waitUntil(self.clients.matchAll({type:`window`,includeUncontrolled:!0}).then(e=>{for(let n of e)if(n.focused)return n.navigate(t),n.focus();return e.length>0?e[0].navigate(t).then(e=>e&&e.focus()):self.clients.openWindow(t)}))});1try{self[`workbox:core:7.4.0`]&&_()}catch{}var e=(e,...t)=>{let n=e;return t.length>0&&(n+=` :: ${JSON.stringify(t)}`),n},t=class extends Error{constructor(t,n){let r=e(t,n);super(r),this.name=t,this.details=n}},n={googleAnalytics:`googleAnalytics`,precache:`precache-v2`,prefix:`workbox`,runtime:`runtime`,suffix:typeof registration<`u`?registration.scope:``},r=e=>[n.prefix,e,n.suffix].filter(e=>e&&e.length>0).join(`-`),i=e=>{for(let t of Object.keys(n))e(t)},a={updateDetails:e=>{i(t=>{typeof e[t]==`string`&&(n[t]=e[t])})},getGoogleAnalyticsName:e=>e||r(n.googleAnalytics),getPrecacheName:e=>e||r(n.precache),getPrefix:()=>n.prefix,getRuntimeName:e=>e||r(n.runtime),getSuffix:()=>n.suffix};function o(e,t){let n=t();return e.waitUntil(n),n}try{self[`workbox:precaching:7.4.0`]&&_()}catch{}var s=`__WB_REVISION__`;function c(e){if(!e)throw new t(`add-to-cache-list-unexpected-type`,{entry:e});if(typeof e==`string`){let t=new URL(e,location.href);return{cacheKey:t.href,url:t.href}}let{revision:n,url:r}=e;if(!r)throw new t(`add-to-cache-list-unexpected-type`,{entry:e});if(!n){let e=new URL(r,location.href);return{cacheKey:e.href,url:e.href}}let i=new URL(r,location.href),a=new URL(r,location.href);return i.searchParams.set(s,n),{cacheKey:i.href,url:a.href}}var l=class{constructor(){this.updatedURLs=[],this.notUpdatedURLs=[],this.handlerWillStart=async({request:e,state:t})=>{t&&(t.originalRequest=e)},this.cachedResponseWillBeUsed=async({event:e,state:t,cachedResponse:n})=>{if(e.type===`install`&&t&&t.originalRequest&&t.originalRequest instanceof Request){let e=t.originalRequest.url;n?this.notUpdatedURLs.push(e):this.updatedURLs.push(e)}return n}}},u=class{constructor({precacheController:e}){this.cacheKeyWillBeUsed=async({request:e,params:t})=>{let n=t?.cacheKey||this._precacheController.getCacheKeyForURL(e.url);return n?new Request(n,{headers:e.headers}):e},this._precacheController=e}},d;function f(){if(d===void 0){let e=new Response(``);if(`body`in e)try{new Response(e.body),d=!0}catch{d=!1}d=!1}return d}async function p(e,n){let r=null;if(e.url&&(r=new URL(e.url).origin),r!==self.location.origin)throw new t(`cross-origin-copy-response`,{origin:r});let i=e.clone(),a={headers:new Headers(i.headers),status:i.status,statusText:i.statusText},o=n?n(a):a,s=f()?i.body:await i.blob();return new Response(s,o)}var ee=e=>new URL(String(e),location.href).href.replace(RegExp(`^${location.origin}`),``);function m(e,t){let n=new URL(e);for(let e of t)n.searchParams.delete(e);return n.href}async function h(e,t,n,r){let i=m(t.url,n);if(t.url===i)return e.match(t,r);let a=Object.assign(Object.assign({},r),{ignoreSearch:!0}),o=await e.keys(t,a);for(let t of o)if(i===m(t.url,n))return e.match(t,r)}var g=class{constructor(){this.promise=new Promise((e,t)=>{this.resolve=e,this.reject=t})}},v=new Set;async function y(){for(let e of v)await e()}function te(e){return new Promise(t=>setTimeout(t,e))}try{self[`workbox:strategies:7.4.0`]&&_()}catch{}function b(e){return typeof e==`string`?new Request(e):e}var ne=class{constructor(e,t){this._cacheKeys={},Object.assign(this,t),this.event=t.event,this._strategy=e,this._handlerDeferred=new g,this._extendLifetimePromises=[],this._plugins=[...e.plugins],this._pluginStateMap=new Map;for(let e of this._plugins)this._pluginStateMap.set(e,{});this.event.waitUntil(this._handlerDeferred.promise)}async fetch(e){let{event:n}=this,r=b(e);if(r.mode===`navigate`&&n instanceof FetchEvent&&n.preloadResponse){let e=await n.preloadResponse;if(e)return e}let i=this.hasCallback(`fetchDidFail`)?r.clone():null;try{for(let e of this.iterateCallbacks(`requestWillFetch`))r=await e({request:r.clone(),event:n})}catch(e){if(e instanceof Error)throw new t(`plugin-error-request-will-fetch`,{thrownErrorMessage:e.message})}let a=r.clone();try{let e;e=await fetch(r,r.mode===`navigate`?void 0:this._strategy.fetchOptions);for(let t of this.iterateCallbacks(`fetchDidSucceed`))e=await t({event:n,request:a,response:e});return e}catch(e){throw i&&await this.runCallbacks(`fetchDidFail`,{error:e,event:n,originalRequest:i.clone(),request:a.clone()}),e}}async fetchAndCachePut(e){let t=await this.fetch(e),n=t.clone();return this.waitUntil(this.cachePut(e,n)),t}async cacheMatch(e){let t=b(e),n,{cacheName:r,matchOptions:i}=this._strategy,a=await this.getCacheKey(t,`read`),o=Object.assign(Object.assign({},i),{cacheName:r});n=await caches.match(a,o);for(let e of this.iterateCallbacks(`cachedResponseWillBeUsed`))n=await e({cacheName:r,matchOptions:i,cachedResponse:n,request:a,event:this.event})||void 0;return n}async cachePut(e,n){let r=b(e);await te(0);let i=await this.getCacheKey(r,`write`);if(!n)throw new t(`cache-put-with-no-response`,{url:ee(i.url)});let a=await this._ensureResponseSafeToCache(n);if(!a)return!1;let{cacheName:o,matchOptions:s}=this._strategy,c=await self.caches.open(o),l=this.hasCallback(`cacheDidUpdate`),u=l?await h(c,i.clone(),[`__WB_REVISION__`],s):null;try{await c.put(i,l?a.clone():a)}catch(e){if(e instanceof Error)throw e.name===`QuotaExceededError`&&await y(),e}for(let e of this.iterateCallbacks(`cacheDidUpdate`))await e({cacheName:o,oldResponse:u,newResponse:a.clone(),request:i,event:this.event});return!0}async getCacheKey(e,t){let n=`${e.url} | ${t}`;if(!this._cacheKeys[n]){let r=e;for(let e of this.iterateCallbacks(`cacheKeyWillBeUsed`))r=b(await e({mode:t,request:r,event:this.event,params:this.params}));this._cacheKeys[n]=r}return this._cacheKeys[n]}hasCallback(e){for(let t of this._strategy.plugins)if(e in t)return!0;return!1}async runCallbacks(e,t){for(let n of this.iterateCallbacks(e))await n(t)}*iterateCallbacks(e){for(let t of this._strategy.plugins)if(typeof t[e]==`function`){let n=this._pluginStateMap.get(t);yield r=>{let i=Object.assign(Object.assign({},r),{state:n});return t[e](i)}}}waitUntil(e){return this._extendLifetimePromises.push(e),e}async doneWaiting(){for(;this._extendLifetimePromises.length;){let e=this._extendLifetimePromises.splice(0),t=(await Promise.allSettled(e)).find(e=>e.status===`rejected`);if(t)throw t.reason}}destroy(){this._handlerDeferred.resolve(null)}async _ensureResponseSafeToCache(e){let t=e,n=!1;for(let e of this.iterateCallbacks(`cacheWillUpdate`))if(t=await e({request:this.request,response:t,event:this.event})||void 0,n=!0,!t)break;return n||t&&t.status!==200&&(t=void 0),t}},x=class{constructor(e={}){this.cacheName=a.getRuntimeName(e.cacheName),this.plugins=e.plugins||[],this.fetchOptions=e.fetchOptions,this.matchOptions=e.matchOptions}handle(e){let[t]=this.handleAll(e);return t}handleAll(e){e instanceof FetchEvent&&(e={event:e,request:e.request});let t=e.event,n=typeof e.request==`string`?new Request(e.request):e.request,r=`params`in e?e.params:void 0,i=new ne(this,{event:t,request:n,params:r}),a=this._getResponse(i,n,t);return[a,this._awaitComplete(a,i,n,t)]}async _getResponse(e,n,r){await e.runCallbacks(`handlerWillStart`,{event:r,request:n});let i;try{if(i=await this._handle(n,e),!i||i.type===`error`)throw new t(`no-response`,{url:n.url})}catch(t){if(t instanceof Error){for(let a of e.iterateCallbacks(`handlerDidError`))if(i=await a({error:t,event:r,request:n}),i)break}if(!i)throw t}for(let t of e.iterateCallbacks(`handlerWillRespond`))i=await t({event:r,request:n,response:i});return i}async _awaitComplete(e,t,n,r){let i,a;try{i=await e}catch{}try{await t.runCallbacks(`handlerDidRespond`,{event:r,request:n,response:i}),await t.doneWaiting()}catch(e){e instanceof Error&&(a=e)}if(await t.runCallbacks(`handlerDidComplete`,{event:r,request:n,response:i,error:a}),t.destroy(),a)throw a}},S=class e extends x{constructor(t={}){t.cacheName=a.getPrecacheName(t.cacheName),super(t),this._fallbackToNetwork=t.fallbackToNetwork!==!1,this.plugins.push(e.copyRedirectedCacheableResponsesPlugin)}async _handle(e,t){return await t.cacheMatch(e)||(t.event&&t.event.type===`install`?await this._handleInstall(e,t):await this._handleFetch(e,t))}async _handleFetch(e,n){let r,i=n.params||{};if(this._fallbackToNetwork){let t=i.integrity,a=e.integrity,o=!a||a===t;r=await n.fetch(new Request(e,{integrity:e.mode===`no-cors`?void 0:a||t})),t&&o&&e.mode!==`no-cors`&&(this._useDefaultCacheabilityPluginIfNeeded(),await n.cachePut(e,r.clone()))}else throw new t(`missing-precache-entry`,{cacheName:this.cacheName,url:e.url});return r}async _handleInstall(e,n){this._useDefaultCacheabilityPluginIfNeeded();let r=await n.fetch(e);if(!await n.cachePut(e,r.clone()))throw new t(`bad-precaching-response`,{url:e.url,status:r.status});return r}_useDefaultCacheabilityPluginIfNeeded(){let t=null,n=0;for(let[r,i]of this.plugins.entries())i!==e.copyRedirectedCacheableResponsesPlugin&&(i===e.defaultPrecacheCacheabilityPlugin&&(t=r),i.cacheWillUpdate&&n++);n===0?this.plugins.push(e.defaultPrecacheCacheabilityPlugin):n>1&&t!==null&&this.plugins.splice(t,1)}};S.defaultPrecacheCacheabilityPlugin={async cacheWillUpdate({response:e}){return!e||e.status>=400?null:e}},S.copyRedirectedCacheableResponsesPlugin={async cacheWillUpdate({response:e}){return e.redirected?await p(e):e}};var C=class{constructor({cacheName:e,plugins:t=[],fallbackToNetwork:n=!0}={}){this._urlsToCacheKeys=new Map,this._urlsToCacheModes=new Map,this._cacheKeysToIntegrities=new Map,this._strategy=new S({cacheName:a.getPrecacheName(e),plugins:[...t,new u({precacheController:this})],fallbackToNetwork:n}),this.install=this.install.bind(this),this.activate=this.activate.bind(this)}get strategy(){return this._strategy}precache(e){this.addToCacheList(e),this._installAndActiveListenersAdded||=(self.addEventListener(`install`,this.install),self.addEventListener(`activate`,this.activate),!0)}addToCacheList(e){let n=[];for(let r of e){typeof r==`string`?n.push(r):r&&r.revision===void 0&&n.push(r.url);let{cacheKey:e,url:i}=c(r),a=typeof r!=`string`&&r.revision?`reload`:`default`;if(this._urlsToCacheKeys.has(i)&&this._urlsToCacheKeys.get(i)!==e)throw new t(`add-to-cache-list-conflicting-entries`,{firstEntry:this._urlsToCacheKeys.get(i),secondEntry:e});if(typeof r!=`string`&&r.integrity){if(this._cacheKeysToIntegrities.has(e)&&this._cacheKeysToIntegrities.get(e)!==r.integrity)throw new t(`add-to-cache-list-conflicting-integrities`,{url:i});this._cacheKeysToIntegrities.set(e,r.integrity)}if(this._urlsToCacheKeys.set(i,e),this._urlsToCacheModes.set(i,a),n.length>0){let e=`Workbox is precaching URLs without revision info: ${n.join(`, `)}\nThis is generally NOT safe. Learn more at https://bit.ly/wb-precache`;console.warn(e)}}}install(e){return o(e,async()=>{let t=new l;this.strategy.plugins.push(t);for(let[t,n]of this._urlsToCacheKeys){let r=this._cacheKeysToIntegrities.get(n),i=this._urlsToCacheModes.get(t),a=new Request(t,{integrity:r,cache:i,credentials:`same-origin`});await Promise.all(this.strategy.handleAll({params:{cacheKey:n},request:a,event:e}))}let{updatedURLs:n,notUpdatedURLs:r}=t;return{updatedURLs:n,notUpdatedURLs:r}})}activate(e){return o(e,async()=>{let e=await self.caches.open(this.strategy.cacheName),t=await e.keys(),n=new Set(this._urlsToCacheKeys.values()),r=[];for(let i of t)n.has(i.url)||(await e.delete(i),r.push(i.url));return{deletedURLs:r}})}getURLsToCacheKeys(){return this._urlsToCacheKeys}getCachedURLs(){return[...this._urlsToCacheKeys.keys()]}getCacheKeyForURL(e){let t=new URL(e,location.href);return this._urlsToCacheKeys.get(t.href)}getIntegrityForCacheKey(e){return this._cacheKeysToIntegrities.get(e)}async matchPrecache(e){let t=e instanceof Request?e.url:e,n=this.getCacheKeyForURL(t);if(n)return(await self.caches.open(this.strategy.cacheName)).match(n)}createHandlerBoundToURL(e){let n=this.getCacheKeyForURL(e);if(!n)throw new t(`non-precached-url`,{url:e});return t=>(t.request=new Request(e),t.params=Object.assign({cacheKey:n},t.params),this.strategy.handle(t))}},w,T=()=>(w||=new C,w);try{self[`workbox:routing:7.4.0`]&&_()}catch{}var E=e=>e&&typeof e==`object`?e:{handle:e},D=class{constructor(e,t,n=`GET`){this.handler=E(t),this.match=e,this.method=n}setCatchHandler(e){this.catchHandler=E(e)}},re=class extends D{constructor(e,t,n){super(({url:t})=>{let n=e.exec(t.href);if(n&&!(t.origin!==location.origin&&n.index!==0))return n.slice(1)},t,n)}},ie=class{constructor(){this._routes=new Map,this._defaultHandlerMap=new Map}get routes(){return this._routes}addFetchListener(){self.addEventListener(`fetch`,(e=>{let{request:t}=e,n=this.handleRequest({request:t,event:e});n&&e.respondWith(n)}))}addCacheListener(){self.addEventListener(`message`,(e=>{if(e.data&&e.data.type===`CACHE_URLS`){let{payload:t}=e.data,n=Promise.all(t.urlsToCache.map(t=>{typeof t==`string`&&(t=[t]);let n=new Request(...t);return this.handleRequest({request:n,event:e})}));e.waitUntil(n),e.ports&&e.ports[0]&&n.then(()=>e.ports[0].postMessage(!0))}}))}handleRequest({request:e,event:t}){let n=new URL(e.url,location.href);if(!n.protocol.startsWith(`http`))return;let r=n.origin===location.origin,{params:i,route:a}=this.findMatchingRoute({event:t,request:e,sameOrigin:r,url:n}),o=a&&a.handler,s=e.method;if(!o&&this._defaultHandlerMap.has(s)&&(o=this._defaultHandlerMap.get(s)),!o)return;let c;try{c=o.handle({url:n,request:e,event:t,params:i})}catch(e){c=Promise.reject(e)}let l=a&&a.catchHandler;return c instanceof Promise&&(this._catchHandler||l)&&(c=c.catch(async r=>{if(l)try{return await l.handle({url:n,request:e,event:t,params:i})}catch(e){e instanceof Error&&(r=e)}if(this._catchHandler)return this._catchHandler.handle({url:n,request:e,event:t});throw r})),c}findMatchingRoute({url:e,sameOrigin:t,request:n,event:r}){let i=this._routes.get(n.method)||[];for(let a of i){let i,o=a.match({url:e,sameOrigin:t,request:n,event:r});if(o)return i=o,(Array.isArray(i)&&i.length===0||o.constructor===Object&&Object.keys(o).length===0||typeof o==`boolean`)&&(i=void 0),{route:a,params:i}}return{}}setDefaultHandler(e,t=`GET`){this._defaultHandlerMap.set(t,E(e))}setCatchHandler(e){this._catchHandler=E(e)}registerRoute(e){this._routes.has(e.method)||this._routes.set(e.method,[]),this._routes.get(e.method).push(e)}unregisterRoute(e){if(!this._routes.has(e.method))throw new t(`unregister-route-but-not-found-with-method`,{method:e.method});let n=this._routes.get(e.method).indexOf(e);if(n>-1)this._routes.get(e.method).splice(n,1);else throw new t(`unregister-route-route-not-registered`)}},O,ae=()=>(O||(O=new ie,O.addFetchListener(),O.addCacheListener()),O);function k(e,n,r){let i;if(typeof e==`string`){let t=new URL(e,location.href);i=new D(({url:e})=>e.href===t.href,n,r)}else if(e instanceof RegExp)i=new re(e,n,r);else if(typeof e==`function`)i=new D(e,n,r);else if(e instanceof D)i=e;else throw new t(`unsupported-route-type`,{moduleName:`workbox-routing`,funcName:`registerRoute`,paramName:`capture`});return ae().registerRoute(i),i}function oe(e,t=[]){for(let n of[...e.searchParams.keys()])t.some(e=>e.test(n))&&e.searchParams.delete(n);return e}function*se(e,{ignoreURLParametersMatching:t=[/^utm_/,/^fbclid$/],directoryIndex:n=`index.html`,cleanURLs:r=!0,urlManipulation:i}={}){let a=new URL(e,location.href);a.hash=``,yield a.href;let o=oe(a,t);if(yield o.href,n&&o.pathname.endsWith(`/`)){let e=new URL(o.href);e.pathname+=n,yield e.href}if(r){let e=new URL(o.href);e.pathname+=`.html`,yield e.href}if(i){let e=i({url:a});for(let t of e)yield t.href}}var A=class extends D{constructor(e,t){super(({request:n})=>{let r=e.getURLsToCacheKeys();for(let i of se(n.url,t)){let t=r.get(i);if(t)return{cacheKey:t,integrity:e.getIntegrityForCacheKey(t)}}},e.strategy)}};function j(e){k(new A(T(),e))}function M(e){T().precache(e)}function N(e,t){M(e),j(t)}var P=class extends x{async _handle(e,n){let r=await n.cacheMatch(e),i;if(!r)try{r=await n.fetchAndCachePut(e)}catch(e){e instanceof Error&&(i=e)}if(!r)throw new t(`no-response`,{url:e.url,error:i});return r}};function F(e){e.then(()=>{})}var I=(e,t)=>t.some(t=>e instanceof t),L,R;function z(){return L||=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]}function B(){return R||=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey]}var V=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap;function ce(e){let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`success`,i),e.removeEventListener(`error`,a)},i=()=>{t(q(e.result)),r()},a=()=>{n(e.error),r()};e.addEventListener(`success`,i),e.addEventListener(`error`,a)});return t.then(t=>{t instanceof IDBCursor&&V.set(t,e)}).catch(()=>{}),G.set(t,e),t}function le(e){if(H.has(e))return;let t=new Promise((t,n)=>{let r=()=>{e.removeEventListener(`complete`,i),e.removeEventListener(`error`,a),e.removeEventListener(`abort`,a)},i=()=>{t(),r()},a=()=>{n(e.error||new DOMException(`AbortError`,`AbortError`)),r()};e.addEventListener(`complete`,i),e.addEventListener(`error`,a),e.addEventListener(`abort`,a)});H.set(e,t)}var K={get(e,t,n){if(e instanceof IDBTransaction){if(t===`done`)return H.get(e);if(t===`objectStoreNames`)return e.objectStoreNames||U.get(e);if(t===`store`)return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return q(e[t])},set(e,t,n){return e[t]=n,!0},has(e,t){return e instanceof IDBTransaction&&(t===`done`||t===`store`)||t in e}};function ue(e){K=e(K)}function de(e){return e===IDBDatabase.prototype.transaction&&!(`objectStoreNames`in IDBTransaction.prototype)?function(t,...n){let r=e.call(J(this),t,...n);return U.set(r,t.sort?t.sort():[t]),q(r)}:B().includes(e)?function(...t){return e.apply(J(this),t),q(V.get(this))}:function(...t){return q(e.apply(J(this),t))}}function fe(e){return typeof e==`function`?de(e):(e instanceof IDBTransaction&&le(e),I(e,z())?new Proxy(e,K):e)}function q(e){if(e instanceof IDBRequest)return ce(e);if(W.has(e))return W.get(e);let t=fe(e);return t!==e&&(W.set(e,t),G.set(t,e)),t}var J=e=>G.get(e);function pe(e,t,{blocked:n,upgrade:r,blocking:i,terminated:a}={}){let o=indexedDB.open(e,t),s=q(o);return r&&o.addEventListener(`upgradeneeded`,e=>{r(q(o.result),e.oldVersion,e.newVersion,q(o.transaction),e)}),n&&o.addEventListener(`blocked`,e=>n(e.oldVersion,e.newVersion,e)),s.then(e=>{a&&e.addEventListener(`close`,()=>a()),i&&e.addEventListener(`versionchange`,e=>i(e.oldVersion,e.newVersion,e))}).catch(()=>{}),s}function me(e,{blocked:t}={}){let n=indexedDB.deleteDatabase(e);return t&&n.addEventListener(`blocked`,e=>t(e.oldVersion,e)),q(n).then(()=>void 0)}var he=[`get`,`getKey`,`getAll`,`getAllKeys`,`count`],ge=[`put`,`add`,`delete`,`clear`],Y=new Map;function X(e,t){if(!(e instanceof IDBDatabase&&!(t in e)&&typeof t==`string`))return;if(Y.get(t))return Y.get(t);let n=t.replace(/FromIndex$/,``),r=t!==n,i=ge.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||he.includes(n)))return;let a=async function(e,...t){let a=this.transaction(e,i?`readwrite`:`readonly`),o=a.store;return r&&(o=o.index(t.shift())),(await Promise.all([o[n](...t),i&&a.done]))[0]};return Y.set(t,a),a}ue(e=>({...e,get:(t,n,r)=>X(t,n)||e.get(t,n,r),has:(t,n)=>!!X(t,n)||e.has(t,n)}));try{self[`workbox:expiration:7.4.0`]&&_()}catch{}var Z=`workbox-expiration`,Q=`cache-entries`,$=e=>{let t=new URL(e,location.href);return t.hash=``,t.href},_e=class{constructor(e){this._db=null,this._cacheName=e}_upgradeDb(e){let t=e.createObjectStore(Q,{keyPath:`id`});t.createIndex(`cacheName`,`cacheName`,{unique:!1}),t.createIndex(`timestamp`,`timestamp`,{unique:!1})}_upgradeDbAndDeleteOldDbs(e){this._upgradeDb(e),this._cacheName&&me(this._cacheName)}async setTimestamp(e,t){e=$(e);let n={url:e,timestamp:t,cacheName:this._cacheName,id:this._getId(e)},r=(await this.getDb()).transaction(Q,`readwrite`,{durability:`relaxed`});await r.store.put(n),await r.done}async getTimestamp(e){return(await(await this.getDb()).get(Q,this._getId(e)))?.timestamp}async expireEntries(e,t){let n=await this.getDb(),r=await n.transaction(Q).store.index(`timestamp`).openCursor(null,`prev`),i=[],a=0;for(;r;){let n=r.value;n.cacheName===this._cacheName&&(e&&n.timestamp<e||t&&a>=t?i.push(r.value):a++),r=await r.continue()}let o=[];for(let e of i)await n.delete(Q,e.id),o.push(e.url);return o}_getId(e){return this._cacheName+`|`+$(e)}async getDb(){return this._db||=await pe(Z,1,{upgrade:this._upgradeDbAndDeleteOldDbs.bind(this)}),this._db}},ve=class{constructor(e,t={}){this._isRunning=!1,this._rerunRequested=!1,this._maxEntries=t.maxEntries,this._maxAgeSeconds=t.maxAgeSeconds,this._matchOptions=t.matchOptions,this._cacheName=e,this._timestampModel=new _e(e)}async expireEntries(){if(this._isRunning){this._rerunRequested=!0;return}this._isRunning=!0;let e=this._maxAgeSeconds?Date.now()-this._maxAgeSeconds*1e3:0,t=await this._timestampModel.expireEntries(e,this._maxEntries),n=await self.caches.open(this._cacheName);for(let e of t)await n.delete(e,this._matchOptions);this._isRunning=!1,this._rerunRequested&&(this._rerunRequested=!1,F(this.expireEntries()))}async updateTimestamp(e){await this._timestampModel.setTimestamp(e,Date.now())}async isURLExpired(e){if(this._maxAgeSeconds){let t=await this._timestampModel.getTimestamp(e),n=Date.now()-this._maxAgeSeconds*1e3;return t===void 0||t<n}else return!1}async delete(){this._rerunRequested=!1,await this._timestampModel.expireEntries(1/0)}};function ye(e){v.add(e)}var be=class{constructor(e={}){this.cachedResponseWillBeUsed=async({event:e,request:t,cacheName:n,cachedResponse:r})=>{if(!r)return null;let i=this._isResponseDateFresh(r),a=this._getCacheExpiration(n);F(a.expireEntries());let o=a.updateTimestamp(t.url);if(e)try{e.waitUntil(o)}catch{}return i?r:null},this.cacheDidUpdate=async({cacheName:e,request:t})=>{let n=this._getCacheExpiration(e);await n.updateTimestamp(t.url),await n.expireEntries()},this._config=e,this._maxAgeSeconds=e.maxAgeSeconds,this._cacheExpirations=new Map,e.purgeOnQuotaError&&ye(()=>this.deleteCacheAndMetadata())}_getCacheExpiration(e){if(e===a.getRuntimeName())throw new t(`expire-custom-caches-only`);let n=this._cacheExpirations.get(e);return n||(n=new ve(e,this._config),this._cacheExpirations.set(e,n)),n}_isResponseDateFresh(e){if(!this._maxAgeSeconds)return!0;let t=this._getDateHeaderTimestamp(e);return t===null||t>=Date.now()-this._maxAgeSeconds*1e3}_getDateHeaderTimestamp(e){if(!e.headers.has(`date`))return null;let t=e.headers.get(`date`),n=new Date(t).getTime();return isNaN(n)?null:n}async deleteCacheAndMetadata(){for(let[e,t]of this._cacheExpirations)await self.caches.delete(e),await t.delete();this._cacheExpirations=new Map}};N([{"revision":"7e6cb67aa9cf28050f2624e28a29f07e","url":"terms.html"},{"revision":"ee34904795012e3493a0c44b9f859308","url":"registerSW.js"},{"revision":"5be4c6cebfb9edbde2d13641ee401057","url":"privacy.html"},{"revision":"247dfacbec1ca7891c2e6a76c720a558","url":"pattern.svg"},{"revision":"f14cd675f0b6e7b885d32809abebae00","url":"notify.mp3"},{"revision":"9ca5e6d7f1dfaf8505ef349e1a2a6982","url":"index.html"},{"revision":"3b4fcfcf393eca4d264dca4a4663bc37","url":"icons.svg"},{"revision":"f46670f29cd911c162da51b955221002","url":"ico.png"},{"revision":"57d9c62138108b9c36062ef6b42999b0","url":"changelog.html"},{"revision":"36d60b85b445b4770dc8202baa0d64cf","url":"calling2.mp3"},{"revision":"61ac15422af330e0204ee6cf95634067","url":"calling.mp3"},{"revision":null,"url":"assets/vendor-BbmWO_jh.js"},{"revision":null,"url":"assets/storage-8tFmIq9d.js"},{"revision":null,"url":"assets/socket-CbQsWyoH.js"},{"revision":null,"url":"assets/rolldown-runtime-QTnfLwEv.js"},{"revision":null,"url":"assets/libsodium-wrappers-DIT7SeqD.js"},{"revision":null,"url":"assets/keyStore-DDPZ0U62.js"},{"revision":null,"url":"assets/index-DY9FqaHJ.js"},{"revision":null,"url":"assets/index-CJLIHFQ-.css"},{"revision":null,"url":"assets/encryption-CFSbljDF.js"},{"revision":null,"url":"assets/__vite-browser-external-BRm5n2qg.js"},{"revision":null,"url":"assets/ModalShell-DxpX6TOZ.css"},{"revision":null,"url":"assets/ModalShell-ClUKyIG2.js"},{"revision":null,"url":"assets/MessengerPage-DuSMdAeg.css"},{"revision":null,"url":"assets/MessengerPage-6Fs5zx2C.js"},{"revision":null,"url":"assets/EncryptionModal-Bk9GLrBN.css"},{"revision":null,"url":"assets/EncryptionModal-BOkioGOz.js"},{"revision":null,"url":"assets/EmojiPanel-BwB33XQa.js"},{"revision":null,"url":"assets/EmojiPanel-Bf-sbcJk.css"},{"revision":null,"url":"assets/AvatarCropper-BpVibBmq.js"},{"revision":null,"url":"assets/AvatarCropper-43twomjP.css"},{"revision":"61ac15422af330e0204ee6cf95634067","url":"calling.mp3"},{"revision":"36d60b85b445b4770dc8202baa0d64cf","url":"calling2.mp3"},{"revision":"f46670f29cd911c162da51b955221002","url":"ico.png"},{"revision":"f14cd675f0b6e7b885d32809abebae00","url":"notify.mp3"},{"revision":"5ba98964a3aeabde9f920bd5fa109422","url":"manifest.webmanifest"}]),k(({url:e})=>e.origin===`https://res.cloudinary.com`,new P({cacheName:`cloudinary-images`,plugins:[new be({maxEntries:100,maxAgeSeconds:3600*24*30})]})),self.addEventListener(`fetch`,e=>{let t=new URL(e.request.url);e.request.method===`POST`&&t.pathname===`/share-target`&&e.respondWith(xe(e.request))});async function xe(e){try{let t=(await e.formData()).get(`media`);if(t){let e=await caches.open(`shared-files`),n=await t.arrayBuffer();await e.put(`shared-file`,new Response(n,{headers:{"Content-Type":t.type,"X-File-Name":encodeURIComponent(t.name),"X-File-Size":String(t.size)}}))}}catch{}return Response.redirect(`/`,303)}self.addEventListener(`install`,()=>{self.skipWaiting()}),self.addEventListener(`activate`,e=>{e.waitUntil(self.clients.claim())}),self.addEventListener(`push`,e=>{let t={};try{t=e.data?e.data.json():{}}catch{t={title:`4SEND`,body:e.data?e.data.text():``}}let n=t.notification||t,r=n.title||t.title||`4SEND`,i=n.body||t.body||``,a=n.icon||`/ico.png`,o=n.click_action||t.data?.click_action||t.data?.url||`/`;e.waitUntil(self.registration.showNotification(r,{body:i,icon:a,data:{url:o},tag:`4send-notification`}))}),self.addEventListener(`notificationclick`,e=>{e.notification.close();let t=e.notification.data&&e.notification.data.url||`/`;e.waitUntil(self.clients.matchAll({type:`window`,includeUncontrolled:!0}).then(e=>{for(let n of e)if(n.focused)return n.navigate(t),n.focus();return e.length>0?e[0].navigate(t).then(e=>e&&e.focus()):self.clients.openWindow(t)}))});
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528import { memo, useEffect, useRef, useState, useCallback } from 'react';import { useI18n } from '../../hooks/useI18n';import { getSocket } from '../../services/socket';import styles from './CallOverlay.module.css';
interface CallOverlayProps { type: 'incoming' | 'outgoing' | 'active' | 'ended'; peer: string; peerDisplay?: string; peerAvatar?: string; withVideo?: boolean; signals?: Array<{ sdp?: unknown; candidate?: unknown }>; preloadedStream?: MediaStream | null; onAccept?: () => void; onClose: () => void;}
const RTC_CONFIG: RTCConfiguration = { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun1.l.google.com:19302' }, { urls: 'stun:stun2.l.google.com:19302' }, { urls: 'stun:stun3.l.google.com:19302' }, { urls: 'stun:stun4.l.google.com:19302' }, { urls: 'stun:stun.cloudflare.com:3478' }, { urls: 'stun:stun.services.mozilla.com:3478' }, { urls: 'stun:stunserver.stunprotocol.org:3478' }, ],};
const MicIcon = () => ( <svg viewBox="0 0 24 24"> <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/> <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/> </svg>);
const MicOffIcon = () => ( <svg viewBox="0 0 24 24"> <path d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z"/> <path d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z"/> <path d="M2 2l20 20" stroke="currentColor" strokeWidth="2" fill="none"/> </svg>);
function CallOverlay({ type, peer, peerDisplay, peerAvatar, withVideo, signals, preloadedStream, onAccept, onClose }: CallOverlayProps) { const { t } = useI18n(); const [visible, setVisible] = useState(false); const [closing, setClosing] = useState(false); const [callSecs, setCallSecs] = useState(0); const [micOff, setMicOff] = useState(false); const [videoOff, setVideoOff] = useState(false); const [cameraFlipped, setCameraFlipped] = useState(false); const [hasVideo, setHasVideo] = useState(false); const localVideoRef = useRef<HTMLVideoElement>(null); const remoteVideoRef = useRef<HTMLVideoElement>(null); const remoteAudioRef = useRef<HTMLAudioElement>(null); const timerRef = useRef<ReturnType<typeof setInterval>>(); const localStreamRef = useRef<MediaStream | null>(null); const ringtoneRef = useRef<HTMLAudioElement | null>(null); const streamStartedRef = useRef(false); const pcRef = useRef<RTCPeerConnection | null>(null); const pendingCandidatesRef = useRef<RTCIceCandidateInit[]>([]); const remoteSetRef = useRef(false); const processedSignalsRef = useRef(0); const signalChainRef = useRef<Promise<void>>(Promise.resolve()); const incomingOfferDeferredRef = useRef(false); const acceptedRef = useRef(false); const makingOfferRef = useRef(false); const processingSdpRef = useRef(false); const typeRef = useRef(type); typeRef.current = type; const preloadedStreamRef = useRef(preloadedStream); preloadedStreamRef.current = preloadedStream;
const displayName = peerDisplay || peer;
const tryPlay = (el: HTMLAudioElement | HTMLVideoElement | null) => { if (!el) return; el.play().catch(() => { const handler = () => { el.play().catch(() => {}); document.removeEventListener('click', handler); document.removeEventListener('touchstart', handler); }; document.addEventListener('click', handler, { once: true }); document.addEventListener('touchstart', handler, { once: true }); }); };
const closeWithAnim = useCallback(() => { if (pcRef.current) { pcRef.current.close(); pcRef.current = null; } if (localStreamRef.current) { localStreamRef.current.getTracks().forEach(track => track.stop()); localStreamRef.current = null; } setClosing(true); setTimeout(() => onClose(), 300); }, [onClose]);
const createPeerConnection = useCallback(() => { const pc = new RTCPeerConnection(RTC_CONFIG); pc.onicecandidate = (e) => { if (e.candidate) { getSocket().emit('webrtc_signal', { target: peer, signal: { candidate: e.candidate.toJSON() } }); } }; pc.ontrack = (e) => { const stream = e.streams[0] || new MediaStream([e.track]); if (e.track.kind === 'audio') { if (remoteAudioRef.current) { remoteAudioRef.current.srcObject = stream; tryPlay(remoteAudioRef.current); } } else if (remoteVideoRef.current) { remoteVideoRef.current.srcObject = stream; tryPlay(remoteVideoRef.current); } }; pc.onnegotiationneeded = async () => { if (makingOfferRef.current || processingSdpRef.current || pc.signalingState !== 'stable') return; if (typeRef.current === 'incoming' && !acceptedRef.current) return; makingOfferRef.current = true; try { const offer = await pc.createOffer(); await pc.setLocalDescription(offer); getSocket().emit('webrtc_signal', { target: peer, signal: { sdp: pc.localDescription } }); } catch {} finally { makingOfferRef.current = false; } }; if (localStreamRef.current) { localStreamRef.current.getTracks().forEach(track => pc.addTrack(track, localStreamRef.current!)); } pcRef.current = pc; return pc; }, [peer]);
const startLocalStream = useCallback(async (video = false) => { if (streamStartedRef.current) return; if (preloadedStreamRef.current) { localStreamRef.current = preloadedStreamRef.current; streamStartedRef.current = true; setHasVideo(video); if (video && localVideoRef.current) { localVideoRef.current.srcObject = preloadedStreamRef.current; } return; } try { const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: video ? { width: { ideal: 1280 }, height: { ideal: 720 }, frameRate: { ideal: 30 }, facingMode: 'user' } : false }); localStreamRef.current = stream; streamStartedRef.current = true; setHasVideo(video); if (video && localVideoRef.current) { localVideoRef.current.srcObject = stream; } } catch (e) {} }, []);
const sendOffer = useCallback(async () => { if (!localStreamRef.current) { await startLocalStream(!!withVideo); } makingOfferRef.current = true; try { const pc = createPeerConnection(); if (localStreamRef.current) { const existingKinds = new Set(pc.getSenders().map(s => s.track?.kind)); localStreamRef.current.getTracks().forEach(track => { if (!existingKinds.has(track.kind)) { pc.addTrack(track, localStreamRef.current!); existingKinds.add(track.kind); } }); } const offer = await pc.createOffer(); await pc.setLocalDescription(offer); getSocket().emit('webrtc_signal', { target: peer, signal: { sdp: pc.localDescription } }); } catch {} finally { makingOfferRef.current = false; } }, [createPeerConnection, peer, startLocalStream, withVideo]);
const addMissingTracks = useCallback((pc: RTCPeerConnection) => { if (!localStreamRef.current) return; const existingKinds = new Set(pc.getSenders().map(s => s.track?.kind)); localStreamRef.current.getTracks().forEach(track => { if (!existingKinds.has(track.kind)) { pc.addTrack(track, localStreamRef.current!); existingKinds.add(track.kind); } }); }, []);
const handleRemoteSignal = useCallback(async (sig: { sdp?: unknown; candidate?: unknown }) => { if (!pcRef.current && sig.sdp) { await startLocalStream(!!withVideo); if (!pcRef.current) { createPeerConnection(); } } const pc = pcRef.current; if (!pc) return; if (localStreamRef.current) { addMissingTracks(pc); } if (sig.sdp && (sig.sdp as RTCSessionDescriptionInit).type) { processingSdpRef.current = true; try { const desc = sig.sdp as RTCSessionDescriptionInit; if (desc.type === 'offer') { if (pc.signalingState === 'have-local-offer') { await pc.setLocalDescription({ type: 'rollback' }); } await pc.setRemoteDescription(desc); remoteSetRef.current = true; for (const c of pendingCandidatesRef.current) { await pc.addIceCandidate(c).catch(() => {}); } pendingCandidatesRef.current = []; const needDefer = typeRef.current === 'incoming' && !acceptedRef.current; if (needDefer) { incomingOfferDeferredRef.current = true; } else { const answer = await pc.createAnswer(); await pc.setLocalDescription(answer); getSocket().emit('webrtc_signal', { target: peer, signal: { sdp: pc.localDescription } }); } } else if (desc.type === 'answer' && pc.signalingState === 'have-local-offer') { await pc.setRemoteDescription(desc); remoteSetRef.current = true; for (const c of pendingCandidatesRef.current) { await pc.addIceCandidate(c).catch(() => {}); } pendingCandidatesRef.current = []; } } catch {} finally { processingSdpRef.current = false; } } else if (sig.candidate) { const candidate = sig.candidate as RTCIceCandidateInit; if (remoteSetRef.current) { await pc.addIceCandidate(candidate).catch(() => {}); } else { pendingCandidatesRef.current.push(candidate); } } }, [createPeerConnection, peer, startLocalStream, withVideo]);
useEffect(() => { if (!signals || signals.length === 0) return; const pending = signals.slice(processedSignalsRef.current); if (pending.length === 0) return; processedSignalsRef.current = signals.length; let chain = signalChainRef.current; for (const sig of pending) { chain = chain.then(() => handleRemoteSignal(sig)).catch(() => {}); } signalChainRef.current = chain; }, [signals, handleRemoteSignal]);
useEffect(() => { requestAnimationFrame(() => setVisible(true)); if (type === 'outgoing') { startLocalStream(withVideo).then(() => sendOffer()); } if (type === 'active') { timerRef.current = setInterval(() => { setCallSecs(s => s + 1); }, 1000); } if (type === 'incoming' || type === 'outgoing') { const audio = new Audio('calling.mp3'); audio.loop = true; audio.currentTime = 0; audio.play().catch(() => { const handler = () => { if (ringtoneRef.current === audio && audio.paused) audio.play().catch(() => {}); document.removeEventListener('click', handler); document.removeEventListener('touchstart', handler); }; document.addEventListener('click', handler); document.addEventListener('touchstart', handler); }); ringtoneRef.current = audio; } if (type === 'ended') { setTimeout(() => closeWithAnim(), 2000); } return () => { if (timerRef.current) clearInterval(timerRef.current); if (ringtoneRef.current) { ringtoneRef.current.pause(); ringtoneRef.current.currentTime = 0; ringtoneRef.current.loop = false; ringtoneRef.current = null; } }; }, [type, closeWithAnim, startLocalStream, withVideo, sendOffer]);
useEffect(() => { if (type === 'active') { if (timerRef.current) clearInterval(timerRef.current); timerRef.current = setInterval(() => { setCallSecs(s => s + 1); }, 1000); } return () => { if (timerRef.current && type !== 'active') { clearInterval(timerRef.current); } }; }, [type]);
useEffect(() => { if (type === 'ended' || type === 'active') { if (ringtoneRef.current) { ringtoneRef.current.pause(); ringtoneRef.current.currentTime = 0; ringtoneRef.current.loop = false; ringtoneRef.current = null; } } }, [type]);
const handleAccept = async () => { if (ringtoneRef.current) { ringtoneRef.current.pause(); ringtoneRef.current.currentTime = 0; ringtoneRef.current.loop = false; ringtoneRef.current = null; } acceptedRef.current = true; await startLocalStream(!!withVideo); await signalChainRef.current.catch(() => {});
const existingPc = pcRef.current; if (existingPc && (incomingOfferDeferredRef.current || existingPc.signalingState === 'have-remote-offer')) { addMissingTracks(existingPc); try { const answer = await existingPc.createAnswer(); await existingPc.setLocalDescription(answer); getSocket().emit('webrtc_signal', { target: peer, signal: { sdp: existingPc.localDescription } }); } catch {} incomingOfferDeferredRef.current = false; }
const socket = getSocket(); socket.emit('call_response', { target: peer, answer: 'accepted' }); onAccept?.(); };
const handleReject = () => { if (ringtoneRef.current) { ringtoneRef.current.pause(); ringtoneRef.current.currentTime = 0; ringtoneRef.current.loop = false; ringtoneRef.current = null; } const socket = getSocket(); socket.emit('call_response', { target: peer, answer: 'rejected' }); closeWithAnim(); };
const handleEnd = () => { const dur = localStreamRef.current && localStreamRef.current.getVideoTracks().length > 0; const socket = getSocket(); socket.emit('call_end', { target: peer, callDuration: callSecs, withVideo: dur }); closeWithAnim(); };
const handleCancel = () => { const socket = getSocket(); socket.emit('call_end', { target: peer, callDuration: 0, withVideo: false }); closeWithAnim(); };
const toggleCallVideo = async () => { if (!localStreamRef.current) return; const tracks = localStreamRef.current.getVideoTracks(); if (tracks.length > 0) { tracks[0].enabled = !tracks[0].enabled; setVideoOff(!tracks[0].enabled); } else { try { const newStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: { facingMode: 'user' } }); const videoTrack = newStream.getVideoTracks()[0]; if (videoTrack) { localStreamRef.current.addTrack(videoTrack); if (pcRef.current) { const sender = pcRef.current.getSenders().find(s => s.track?.kind === 'video'); if (sender) { await sender.replaceTrack(videoTrack); } else { pcRef.current.addTrack(videoTrack, localStreamRef.current); } } if (localVideoRef.current) { localVideoRef.current.srcObject = localStreamRef.current; } setHasVideo(true); setVideoOff(false); } } catch (e) {} } };
const toggleCallMic = () => { if (!localStreamRef.current) return; const audioTracks = localStreamRef.current.getAudioTracks(); if (audioTracks.length > 0) { audioTracks[0].enabled = !audioTracks[0].enabled; setMicOff(!audioTracks[0].enabled); } };
const flipCallCamera = async () => { if (!localStreamRef.current) return; const oldTracks = localStreamRef.current.getVideoTracks(); oldTracks.forEach(t => { localStreamRef.current?.removeTrack(t); t.stop(); }); try { const newStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: { facingMode: cameraFlipped ? 'user' : 'environment' } }); const videoTrack = newStream.getVideoTracks()[0]; if (videoTrack) { localStreamRef.current.addTrack(videoTrack); if (pcRef.current) { const sender = pcRef.current.getSenders().find(s => s.track?.kind === 'video'); if (sender) { await sender.replaceTrack(videoTrack); } else { pcRef.current.addTrack(videoTrack, localStreamRef.current); } } if (localVideoRef.current) { localVideoRef.current.srcObject = localStreamRef.current; } setCameraFlipped(!cameraFlipped); } } catch (e) {} };
const formatTime = (secs: number) => { const m = Math.floor(secs / 60); const s = secs % 60; return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`; };
const statusText = type === 'outgoing' ? (withVideo ? t('Видеозвонок...') : t('Звонок...')) : type === 'incoming' ? (withVideo ? t('Входящий видеозвонок') : t('Входящий звонок')) : type === 'active' ? formatTime(callSecs) : t('Звонок завершён');
return ( <div className={`${styles.overlay} ${visible && !closing ? styles.overlayVisible : ''}`}> <div className={styles.videoContainer}> <video ref={remoteVideoRef} autoPlay playsInline muted className={`${styles.remoteVideo} ${type === 'active' ? styles.remoteVideoVisible : ''}`} /> <audio ref={remoteAudioRef} autoPlay /> <video ref={localVideoRef} autoPlay playsInline muted className={`${styles.localVideo} ${type === 'active' && hasVideo && !videoOff ? styles.localVideoVisible : ''}`} /> </div> <div className={styles.uiLayer}> <div className={styles.mainArea}> <div className={`${styles.avatarContainer} ${type !== 'active' ? styles.avatarPulse : ''}`}> {peerAvatar ? ( <img src={peerAvatar} alt="" className={styles.avatarImg} /> ) : ( displayName.charAt(0).toUpperCase() )} </div> <div className={styles.name}>{displayName}</div> <div className={styles.status}>{statusText}</div> </div> <div className={styles.controls}> {type === 'incoming' && ( <> <button className={`${styles.controlBtn} ${styles.rejectBtn}`} onClick={handleReject}> <svg viewBox="0 0 24 24"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg> </button> <button className={`${styles.controlBtn} ${styles.acceptBtn}`} onClick={handleAccept}> <svg viewBox="0 0 24 24"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg> </button> </> )} {type === 'outgoing' && ( <button className={`${styles.controlBtn} ${styles.endBtn}`} onClick={handleCancel}> <svg viewBox="0 0 24 24"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg> </button> )} {type === 'active' && ( <> <button className={styles.activeControlBtn} onClick={toggleCallVideo} title={videoOff ? t('Вкл. видео') : t('Выкл. видео')}> <svg viewBox="0 0 24 24"><path d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z"/></svg> </button> {hasVideo && ( <button className={styles.activeControlBtn} onClick={flipCallCamera} title={t('Переключить камеру')}> <svg viewBox="0 0 24 24"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z"/></svg> </button> )} <button className={styles.activeControlBtn} onClick={toggleCallMic} title={micOff ? t('Вкл. микрофон') : t('Выкл. микрофон')}> {micOff ? <MicOffIcon /> : <MicIcon />} </button> <button className={`${styles.controlBtn} ${styles.endBtn}`} onClick={handleEnd}> <svg viewBox="0 0 24 24"><path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/></svg> </button> </> )} </div> </div> </div> );}
export default memo(CallOverlay);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176import { useState, useCallback, useEffect, useRef, type ReactNode } from 'react';import { useI18n } from '../../hooks/useI18n';
interface PinnedItem { text: string; id: string; mediaType?: string;}
interface Props { pinnedMessage: PinnedItem[] | null; onScrollTo: (id: string) => void; onUnpin: (id: string) => void; styles: Record<string, string>;}
const MEDIA_ICONS: Record<string, ReactNode> = { photo: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" /> </svg> ), video: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .55-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z" /> </svg> ), voice: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M12 14c1.66 0 3-1.34 3-3V5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3z" /> <path fill="currentColor" d="M17 11c0 2.76-2.24 5-5 5s-5-2.24-5-5H5c0 3.53 2.61 6.43 6 6.92V21h2v-3.08c3.39-.49 6-3.39 6-6.92h-2z" /> </svg> ), audio: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z" /> </svg> ), videonote: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .55-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11l-4 4z" /> </svg> ), sticker: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M12 2L2 22h20L12 2zm0 3.83L18.17 19H5.83L12 5.83z" /> </svg> ), gif: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M19 19H5V5h14v14zM5 3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2H5zm6.5 10h-2v-2h2v2zm0-4h-2V7h2v2zm4 4h-2v-2h2v2zm0-4h-2V7h2v2z" /> </svg> ), file: ( <svg viewBox="0 0 24 24" style={{ width: 14, height: 14, verticalAlign: 'middle', marginRight: 4 }}> <path fill="currentColor" d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 16H8v-2h8v2zm0-4H8v-2h8v2zm-3-5V3.5L18.5 9H13z" /> </svg> ),};
const truncate = (s: string, n: number) => (s.length > n ? s.slice(0, n).trimEnd() + '...' : s);
export default function PinnedBar({ pinnedMessage, onScrollTo, onUnpin, styles }: Props) { const { t } = useI18n(); const [pinIndex, setPinIndex] = useState(0); const [showList, setShowList] = useState(false); const touchStartX = useRef<number | null>(null); const suppressClickRef = useRef(false);
const list = Array.isArray(pinnedMessage) ? pinnedMessage : (pinnedMessage ? [pinnedMessage] : []); const current = list[pinIndex] || null;
useEffect(() => { if (pinIndex >= list.length) { setPinIndex(Math.max(0, list.length - 1)); } }, [list.length, pinIndex]);
const handleClick = useCallback(() => { if (suppressClickRef.current) { suppressClickRef.current = false; return; } if (!current) return; onScrollTo(current.id); }, [current, onScrollTo]);
const handlePrev = useCallback((e: React.MouseEvent) => { e.stopPropagation(); setPinIndex(i => (i - 1 + list.length) % list.length); }, [list.length]);
const handleNext = useCallback((e: React.MouseEvent) => { e.stopPropagation(); setPinIndex(i => (i + 1) % list.length); }, [list.length]);
const handleTouchStart = useCallback((e: React.TouchEvent) => { touchStartX.current = e.touches[0].clientX; }, []);
const handleTouchEnd = useCallback((e: React.TouchEvent) => { if (touchStartX.current == null) return; const dx = e.changedTouches[0].clientX - touchStartX.current; touchStartX.current = null; if (list.length < 2 || Math.abs(dx) < 40) return; suppressClickRef.current = true; setPinIndex(i => (dx > 0 ? (i - 1 + list.length) % list.length : (i + 1) % list.length)); }, [list.length]);
const mediaIcon = current?.mediaType ? MEDIA_ICONS[current.mediaType] : null; const displayText = current?.text || (current?.mediaType ? t('Медиа') : ''); const shortText = truncate(displayText, 160); const isMulti = list.length > 1;
return ( <div className={`${styles.pinnedBar} ${list.length === 0 ? styles.hidden : ''}`} onClick={handleClick} onTouchStart={handleTouchStart} onTouchEnd={handleTouchEnd} style={{ cursor: current ? 'pointer' : undefined }} > <div className={styles.pinnedAccent} /> <div className={styles.pinnedContent}> <div className={styles.pinnedCounter} onClick={(e) => { e.stopPropagation(); if (isMulti) setShowList(s => !s); }} style={{ cursor: isMulti ? 'pointer' : undefined }} > {isMulti ? `${pinIndex + 1} / ${list.length} ${t('закреплённых')}` : t('Закреплённое сообщение')} {isMulti && ( <svg width="10" height="10" viewBox="0 0 24 24" fill="currentColor" style={{ marginLeft: 6, verticalAlign: 'middle', transform: showList ? 'rotate(180deg)' : 'none' }}> <path d="M7.41 8.59L12 13.17l4.59-4.58L18 10l-6 6-6-6z" /> </svg> )} </div> <div className={styles.pinnedText}> {isMulti && ( <button className={styles.pinArrow} onClick={handlePrev}> <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg> </button> )} <span className={styles.pinTextInner}> {mediaIcon} {shortText} </span> {isMulti && ( <button className={styles.pinArrow} onClick={handleNext}> <svg width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg> </button> )} </div> </div> <button className={styles.pinnedClose} onClick={(e) => { e.stopPropagation(); onUnpin(current?.id || ''); }}>✕</button> {showList && ( <div className={styles.pinnedDropdown} onClick={(e) => e.stopPropagation()}> {list.map((p, i) => ( <button key={p.id} className={`${styles.pinnedDropdownItem} ${i === pinIndex ? styles.pinnedDropdownItemActive : ''}`} onClick={() => { setPinIndex(i); setShowList(false); onScrollTo(p.id); }} > {p.mediaType && MEDIA_ICONS[p.mediaType]} {truncate(p.text || (p.mediaType ? t('Медиа') : ''), 90)} </button> ))} </div> )} </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198@keyframes fadeInUp { from { opacity: 0; transform: translateX(-50%) translateY(10px); } to { opacity: 1; transform: translateX(-50%) translateY(0); }}
@keyframes fadeOutDown { from { opacity: 1; transform: translateX(-50%) translateY(0); } to { opacity: 0; transform: translateX(-50%) translateY(10px); }}
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.3; }}
.container { position: fixed; bottom: 80px; left: calc(50% + var(--sidebar-width, 320px) / 2); transform: translateX(-50%); display: flex; flex-direction: column; align-items: center; gap: 10px; z-index: 9999; animation: fadeInUp 0.25s ease forwards; opacity: 0;}
.container.closing { animation: fadeOutDown 0.2s ease forwards;}
@media (max-width: 768px) { .container { left: 50% !important; bottom: calc(80px + env(safe-area-inset-bottom, 0px)) !important; } .pill { width: calc(100vw - 24px) !important; }}
.videoPreview { width: 240px; height: 240px; border-radius: 50%; overflow: hidden; border: 3px solid var(--accent-solid); box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5); background: #000;}
.video { width: 100%; height: 100%; object-fit: cover; border-radius: 50%;}
.camControls { display: flex; gap: 12px; margin-top: -4px;}
.camBtn { width: 44px; height: 44px; border-radius: 50%; border: 1px solid rgba(255, 255, 255, 0.2); background: rgba(0, 0, 0, 0.5); backdrop-filter: blur(10px); display: flex; align-items: center; justify-content: center; cursor: pointer; transition: background 0.2s;}
.camBtn:hover { background: rgba(255, 255, 255, 0.15);}
.pill { display: flex; align-items: center; gap: 12px; padding: 12px 20px; background: rgba(var(--card-rgb, 42, 38, 51), 0.95); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border-radius: 30px; border: 1px solid rgba(var(--accent-rgb, 157, 78, 221), 0.3); width: 420px; max-width: calc(100vw - 40px); justify-content: space-between;}
.pillLeft { display: flex; align-items: center; gap: 10px;}
.dot { width: 10px; height: 10px; background: #ff3b30; border-radius: 50%; animation: pulse 1.5s infinite;}
.timer { color: #fff; font-size: calc(15px * var(--font-size-scale)); font-weight: 600; font-variant-numeric: tabular-nums;}
.waveform { display: flex; gap: 2px; align-items: center; height: 30px; flex: 1; overflow: hidden; justify-content: center;}
.bar { width: 3px; background: var(--accent-solid); border-radius: 2px; transition: height 0.1s;}
.pillRight { display: flex; align-items: center; gap: 12px;}
.cancel { color: #888; font-size: calc(13px * var(--font-size-scale)); cursor: pointer;}
.cancel:hover { color: #aaa;}
.sendBtn { background: var(--accent-solid); color: var(--on-accent, #fff); border: none; border-radius: 50%; width: 32px; height: 32px; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: opacity 0.2s;}
.sendBtn:hover { opacity: 0.85;}
.trashBtn { background: transparent; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; padding: 4px; border-radius: 50%; transition: background 0.2s;}
.trashBtn:hover { background: rgba(255, 77, 77, 0.15);}
.videoBadge { display: flex; align-items: center; gap: 6px; flex: 1; justify-content: center;}
.pillLocked { border-color: rgba(255, 77, 77, 0.4);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346import { useState, useEffect, useRef, useCallback } from 'react';import { useI18n } from '../../hooks/useI18n';import { getVideoMessageSettings, pickVideoMessageMime } from '../../utils/videoMessage';import styles from './VoiceRecorder.module.css';
interface Props { isActive: boolean; mode: 'audio' | 'video'; onCancel: () => void; onSend: (blob: Blob, mode: 'audio' | 'video') => void; locked: boolean; onLockChange: (locked: boolean) => void;}
export default function VoiceRecorder({ isActive, mode, onCancel, onSend, locked, onLockChange }: Props) { const { t } = useI18n(); const [elapsed, setElapsed] = useState(0); const [bars, setBars] = useState<number[]>(new Array(20).fill(2)); const [closing, setClosing] = useState(false); const [visible, setVisible] = useState(isActive); const [facingMode, setFacingMode] = useState<'user' | 'environment'>(() => getVideoMessageSettings().camera); const [flashOn, setFlashOn] = useState(false); const mediaRecorderRef = useRef<MediaRecorder | null>(null); const chunksRef = useRef<Blob[]>([]); const mimeRef = useRef('audio/webm'); const pendingSendRef = useRef(false); const onSendRef = useRef(onSend); onSendRef.current = onSend; const streamRef = useRef<MediaStream | null>(null); const timerRef = useRef<ReturnType<typeof setInterval> | null>(null); const analyserRef = useRef<AnalyserNode | null>(null); const animFrameRef = useRef<number>(0); const videoRef = useRef<HTMLVideoElement>(null); const canvasRef = useRef<HTMLCanvasElement>(null); const drawFrameRef = useRef<number>(0); const swipeStartRef = useRef<{ x: number; y: number } | null>(null);
useEffect(() => { if (isActive) { setVisible(true); setClosing(false); setElapsed(0); } }, [isActive]);
useEffect(() => { if (!isActive && locked) { onLockChange(false); } }, [isActive, locked, onLockChange]);
const handlePointerDown = useCallback((e: React.PointerEvent) => { swipeStartRef.current = { x: e.clientX, y: e.clientY }; }, []);
const handlePointerMove = useCallback((e: React.PointerEvent) => { if (!swipeStartRef.current || locked) return; const dy = swipeStartRef.current.y - e.clientY; if (dy > 50) { onLockChange(true); swipeStartRef.current = null; } }, [locked, onLockChange]);
const handlePointerUp = useCallback(() => { swipeStartRef.current = null; }, []);
const stopStream = useCallback(() => { if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; } }, []);
const stopRecording = useCallback(() => { if (timerRef.current) { clearInterval(timerRef.current); timerRef.current = null; } cancelAnimationFrame(animFrameRef.current); cancelAnimationFrame(drawFrameRef.current); if (mediaRecorderRef.current && mediaRecorderRef.current.state !== 'inactive') { mediaRecorderRef.current.stop(); } stopStream(); }, [stopStream]);
const finalizeRecording = useCallback(() => { const chunks = chunksRef.current; chunksRef.current = []; if (!pendingSendRef.current) return; pendingSendRef.current = false; if (!chunks.length) return; const blob = new Blob(chunks, { type: mimeRef.current }); if (blob.size === 0) return; onSendRef.current(blob, mode); }, [mode]);
const animateClose = useCallback((cb: () => void) => { setClosing(true); setTimeout(() => { setClosing(false); setVisible(false); cb(); }, 250); }, []);
const handleCancel = useCallback(() => { stopRecording(); chunksRef.current = []; setElapsed(0); animateClose(onCancel); }, [stopRecording, onCancel, animateClose]);
const handleSend = useCallback(() => { pendingSendRef.current = true; stopRecording(); setElapsed(0); animateClose(() => {}); }, [stopRecording, animateClose]);
const switchCamera = useCallback(async () => { const newFacing: 'user' | 'environment' = facingMode === 'user' ? 'environment' : 'user'; try { const camStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: newFacing, width: { ideal: 720 }, height: { ideal: 720 }, frameRate: { ideal: 30 } } }); const newTrack = camStream.getVideoTracks()[0]; if (!newTrack) { camStream.getTracks().forEach(t => t.stop()); return; } const current = streamRef.current; let targetStream = current; if (current) { const oldTrack = current.getVideoTracks()[0]; current.removeTrack(oldTrack); if (oldTrack) oldTrack.stop(); current.addTrack(newTrack); } else { targetStream = camStream; streamRef.current = camStream; } if (videoRef.current && targetStream) { videoRef.current.srcObject = null; videoRef.current.srcObject = targetStream; await videoRef.current.play().catch(() => {}); } setFacingMode(newFacing); } catch { // камера недоступна/занята — продолжаем запись на текущей, модалку не закрываем } }, [facingMode]);
const toggleFlash = useCallback(async () => { setFlashOn(prev => !prev); if (facingMode === 'environment' && streamRef.current) { const track = streamRef.current.getVideoTracks()[0]; try { await track?.applyConstraints({ advanced: [{ torch: !flashOn }] as any }); } catch {} } }, [facingMode, flashOn]);
const handleStart = useCallback(async () => { try { const videoSettings = getVideoMessageSettings(); const constraints: MediaStreamConstraints = mode === 'video' ? { audio: { echoCancellation: true, noiseSuppression: true }, video: { facingMode, width: { ideal: videoSettings.quality }, height: { ideal: videoSettings.quality }, frameRate: { ideal: 30 } } } : { audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, sampleRate: 44100 } };
const stream = await navigator.mediaDevices.getUserMedia(constraints); streamRef.current = stream; chunksRef.current = [];
if (mode === 'video') { if (videoRef.current) { videoRef.current.srcObject = stream; await videoRef.current.play(); }
const canvas = document.createElement('canvas'); canvas.width = 600; canvas.height = 600; const ctx = canvas.getContext('2d')!;
const drawFrame = () => { if (!isActive || !videoRef.current) return; const v = videoRef.current; if (v.readyState >= 2) { const min = Math.min(v.videoWidth, v.videoHeight); const sx = (v.videoWidth - min) / 2; const sy = (v.videoHeight - min) / 2; ctx.drawImage(v, sx, sy, min, min, 0, 0, 600, 600); } drawFrameRef.current = requestAnimationFrame(drawFrame); }; drawFrame();
const canvasStream = canvas.captureStream(30); const audioTrack = stream.getAudioTracks()[0]; if (audioTrack) canvasStream.addTrack(audioTrack);
const mime = pickVideoMessageMime(videoSettings.codec); mimeRef.current = mime; const recorder = new MediaRecorder(canvasStream, { mimeType: mime, videoBitsPerSecond: videoSettings.bitrate }); mediaRecorderRef.current = recorder; recorder.ondataavailable = (e) => { if (e.data.size > 0) chunksRef.current.push(e.data); }; recorder.onstop = finalizeRecording; recorder.start(); } else { const audioCtx = new AudioContext(); const source = audioCtx.createMediaStreamSource(stream); const analyser = audioCtx.createAnalyser(); analyser.fftSize = 64; source.connect(analyser); analyserRef.current = analyser;
const gainNode = audioCtx.createGain(); gainNode.gain.value = 3.5; const destination = audioCtx.createMediaStreamDestination(); analyser.connect(gainNode); gainNode.connect(destination);
const recorder = new MediaRecorder(destination.stream, { audioBitsPerSecond: 128000 }); mimeRef.current = recorder.mimeType || 'audio/webm'; mediaRecorderRef.current = recorder; recorder.ondataavailable = (e) => { if (e.data.size > 0) chunksRef.current.push(e.data); }; recorder.onstop = finalizeRecording; recorder.start();
const updateBars = () => { if (!analyserRef.current) return; const data = new Uint8Array(analyser.frequencyBinCount); analyser.getByteFrequencyData(data); const newBars = Array.from({ length: 20 }, (_, i) => { const val = data[i] || 0; return Math.max(2, (val / 255) * 30); }); setBars(newBars); animFrameRef.current = requestAnimationFrame(updateBars); }; updateBars(); }
timerRef.current = setInterval(() => { setElapsed(prev => prev + 1); }, 1000); } catch { animateClose(onCancel); } }, [mode, facingMode, isActive, onCancel, animateClose, finalizeRecording]);
useEffect(() => { if (!isActive) return; handleStart(); return () => { stopRecording(); }; }, [isActive]);
useEffect(() => { if (!isActive || mode !== 'video') return; const ov = document.getElementById('flash-overlay'); if (flashOn && !ov) { const el = document.createElement('div'); el.id = 'flash-overlay'; Object.assign(el.style, { position: 'fixed', inset: '0', background: '#fff', opacity: '0.85', zIndex: '2147483647', pointerEvents: 'none' }); document.body.appendChild(el); } else if (!flashOn && ov) { ov.remove(); } return () => document.getElementById('flash-overlay')?.remove(); }, [flashOn, isActive, mode]);
if (!visible) return null;
const formatTime = (secs: number) => { const m = Math.floor(secs / 60).toString().padStart(2, '0'); const s = (secs % 60).toString().padStart(2, '0'); return `${m}:${s}`; };
return ( <div className={`${styles.container} ${closing ? styles.closing : ''}`} onPointerDown={handlePointerDown} onPointerMove={handlePointerMove} onPointerUp={handlePointerUp} onPointerLeave={handlePointerUp} style={{ touchAction: 'pan-y' }} > {mode === 'video' && ( <> <div className={styles.videoPreview}> <video ref={videoRef} muted playsInline className={styles.video} style={{ transform: facingMode === 'user' ? 'scaleX(-1)' : 'none' }} /> </div> <div className={styles.camControls}> <button className={styles.camBtn} onClick={toggleFlash} style={{ background: flashOn ? 'var(--accent-solid)' : undefined }}> <svg viewBox="0 0 24 24" width="20" height="20" fill="#fff"><path d="M7 2v11h3v9l7-12h-4l4-8z" /></svg> </button> <button className={styles.camBtn} onClick={switchCamera}> <svg viewBox="0 0 24 24" width="20" height="20" fill="#fff"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 12 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4v3z" /></svg> </button> </div> </> )}
<div className={`${styles.pill} ${locked ? styles.pillLocked : ''}`}> <div className={styles.pillLeft}> <div className={styles.dot} /> <span className={styles.timer}>{formatTime(elapsed)}</span> </div>
{mode === 'audio' && ( <div className={styles.waveform}> {bars.map((h, i) => ( <div key={i} className={styles.bar} style={{ height: `${h}px` }} /> ))} </div> )} {mode === 'video' && ( <div className={styles.videoBadge}> <svg viewBox="0 0 24 24" width="14" height="14" fill="#ff3b30"><circle cx="12" cy="12" r="3" /></svg> <span className={styles.timer}>{formatTime(elapsed)}</span> </div> )}
<div className={styles.pillRight}> {!locked && ( <span className={styles.cancel} onClick={handleCancel}>{t('Отмена')}</span> )} {locked && ( <button className={styles.trashBtn} onClick={handleCancel}> <svg viewBox="0 0 24 24" width="20" height="20" fill="#ff4d4d"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z" /></svg> </button> )} <button className={styles.sendBtn} onClick={handleSend}> <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z" /></svg> </button> </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; }}
@keyframes scaleIn { from { opacity: 0; transform: scale(0.9); } to { opacity: 1; transform: translateY(0) scale(1); }}
@keyframes fadeOut { from { opacity: 1; } to { opacity: 0; }}
@keyframes scaleOut { from { opacity: 1; transform: scale(1); } to { opacity: 0; transform: scale(0.8) translateY(20px); }}
.overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 11000; display: flex; align-items: center; justify-content: center; background: rgba(var(--overlay-rgb, 30, 27, 36), 0.95); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); opacity: 0; transition: opacity 0.5s ease;}
.overlay.open { opacity: 1;}
.overlay.closing { animation: fadeOut 0.4s ease forwards; pointer-events: none;}
.modal { background: rgba(var(--card-rgb, 42, 38, 51), 0.95); backdrop-filter: blur(40px); -webkit-backdrop-filter: blur(40px); width: 90%; max-width: 600px; max-height: 85vh; overflow-y: auto; scrollbar-width: none; -webkit-overflow-scrolling: touch; padding: 24px; border-radius: 24px; border: 1px solid rgba(var(--accent-rgb, 157, 78, 221), 0.2); box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); transform: scale(0.9); opacity: 0; transition: all 0.5s cubic-bezier(0.34, 1.56, 0.64, 1); margin: 0 auto;}
.modal::-webkit-scrollbar { display: none;}
.overlay.open .modal { opacity: 1; transform: translateY(0) scale(1);}
.overlay.closing .modal { opacity: 0; transform: scale(0.8) translateY(20px); transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);}
.header { display: flex; align-items: center; margin-bottom: 24px;}
.backBtn { background: rgba(255, 255, 255, 0.1); border: none; color: var(--accent-solid, #9d4edd); font-size: calc(24px * var(--font-size-scale)); cursor: pointer; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; transition: 0.2s; flex-shrink: 0;}
.backBtn:hover { background: rgba(255, 255, 255, 0.15);}
.title { flex: 1; text-align: center; margin: 0; color: #fff; font-size: calc(18px * var(--font-size-scale)); font-weight: 700;}
.placeholder { width: 40px; height: 40px; flex-shrink: 0;}
.scrollContent { max-width: 600px; margin: 0 auto;}
.sectionHeader { padding: 0 8px 12px 8px; color: #8e8e93; font-size: calc(11px * var(--font-size-scale)); font-weight: 600; letter-spacing: 0.5px; text-transform: uppercase;}
.sectionGroup { background: rgba(var(--accent-rgb, 157, 78, 221), 0.08); border-radius: 16px; margin-bottom: 24px; overflow: hidden;}
.hubItem { display: flex; align-items: center; gap: 14px; padding: 16px; background: transparent; cursor: pointer; transition: all 0.2s ease; border: none; width: 100%; text-align: left; border-bottom: 1px solid rgba(255, 255, 255, 0.05);}
.hubItem:last-child { border-bottom: none;}
.hubItem:hover { background: rgba(var(--accent-rgb, 157, 78, 221), 0.15);}
.iconBox { width: 40px; height: 40px; border-radius: 11px; display: flex; align-items: center; justify-content: center; flex-shrink: 0;}
.iconBox svg { width: 22px; height: 22px; fill: #fff;}
.textBlock { flex: 1;}
.itemLabel { color: #fff; font-size: calc(17px * var(--font-size-scale)); font-weight: 600; display: block;}
.itemDesc { color: #8e8e93; font-size: calc(14px * var(--font-size-scale)); margin-top: 3px; display: block;}
.arrow { color: var(--accent-solid, #9d4edd); font-size: calc(20px * var(--font-size-scale)); margin-left: auto; font-weight: 600; flex-shrink: 0;}
.toggle { width: 44px; height: 26px; border-radius: 13px; background: rgba(255,255,255,0.1); position: relative; cursor: pointer; transition: background 0.2s; flex-shrink: 0; margin-left: auto;}
.toggleOn { background: var(--accent-solid, #a74fff);}
.toggleKnob { width: 22px; height: 22px; border-radius: 50%; background: #fff; position: absolute; top: 2px; left: 2px; transition: transform 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.3);}
.toggleOn .toggleKnob { transform: translateX(18px);}
.videoOptionRow { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; background: var(--bg-secondary, #1b1b24); border-bottom: 1px solid var(--border, rgba(255,255,255,0.06));}
.videoOptionRow:last-child { border-bottom: none;}
.videoOptionLabel { font-size: calc(13px * var(--font-size-scale)); color: #ddd; flex-shrink: 0;}
.videoOptionBtns { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end;}
.videoOptionBtn { background: rgba(255, 255, 255, 0.06); border: 1px solid transparent; color: #aaa; cursor: pointer; padding: 5px 10px; border-radius: 8px; font-size: calc(12px * var(--font-size-scale)); transition: all 0.15s;}
.videoOptionBtn:hover { background: rgba(255, 255, 255, 0.1);}
.videoOptionBtnActive { background: rgba(var(--accent-rgb, 167, 79, 255), 0.2); border-color: var(--accent-solid, #a74fff); color: #fff;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350import { useCallback, useEffect, useState } from 'react';import { useI18n } from '../../hooks/useI18n';import { isFoldersEnabled, setFoldersEnabled } from '../../utils/folders';import { getVideoMessageSettings, setVideoMessageSetting, type VideoMessageSettings } from '../../utils/videoMessage';import styles from './ChatSettingsModal.module.css';
interface Props { isOpen: boolean; onClose: () => void; onOpenSubModal: (name: string) => void;}
const menuItems = [ { name: 'customization', gradient: 'linear-gradient(135deg,#B8A7F0,#8B7BD6)', iconPath: 'M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58a.49.49 0 0 0 .12-.61l-1.92-3.32a.49.49 0 0 0-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54a.484.484 0 0 0-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58a.49.49 0 0 0-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z', titleKey: 'Кастомизация', subtitleKey: 'Кастомизация интерфейса мессенджера', }, { name: 'hotkeys', gradient: 'linear-gradient(135deg,#667eea,#764ba2)', iconSvg: <svg viewBox="0 0 16 16" fill="currentColor" width="20" height="20"><path d="M0 6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2V6zm13 .25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5a.25.25 0 0 0-.25.25zM2.25 8a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 3 8.75v-.5A.25.25 0 0 0 2.75 8h-.5zM4 8.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 5 8.75v-.5A.25.25 0 0 0 4.75 8h-.5a.25.25 0 0 0-.25.25zM6.25 8a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 7 8.75v-.5A.25.25 0 0 0 6.75 8h-.5zM8 8.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 9 8.75v-.5A.25.25 0 0 0 8.75 8h-.5a.25.25 0 0 0-.25.25zM13.25 8a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5zm0 2a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5zm-3-2a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h1.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-1.5zm.75 2.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5a.25.25 0 0 0-.25.25zM11.25 6a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5zM9 6.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5A.25.25 0 0 0 9.75 6h-.5a.25.25 0 0 0-.25.25zM7.25 6a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 8 6.75v-.5A.25.25 0 0 0 7.75 6h-.5zM5 6.25v.5c0 .138.112.25.25.25h.5A.25.25 0 0 0 6 6.75v-.5A.25.25 0 0 0 5.75 6h-.5a.25.25 0 0 0-.25.25zM2.25 6a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h1.5A.25.25 0 0 0 4 6.75v-.5A.25.25 0 0 0 3.75 6h-1.5zM2 10.25v.5c0 .138.112.25.25.25h.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-.5a.25.25 0 0 0-.25.25zM4.25 10a.25.25 0 0 0-.25.25v.5c0 .138.112.25.25.25h5.5a.25.25 0 0 0 .25-.25v-.5a.25.25 0 0 0-.25-.25h-5.5z"/></svg>, titleKey: 'Горячие клавиши', subtitleKey: 'Настройка сочетаний клавиш', }, { name: 'sound', gradient: 'linear-gradient(135deg,#34c759,#28a745)', iconPath: 'M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z', titleKey: 'Настройки звука', subtitleKey: 'Громкость уведомлений и звуковых эффектов', }, { name: 'notifRepeat', gradient: 'linear-gradient(135deg,#e91e63,#c2185b)', iconPath: 'M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z', titleKey: 'Повтор уведомлений', subtitleKey: 'Напоминания о непрочитанных', }, { name: 'quickReaction', gradient: 'linear-gradient(135deg,#ff9500,#ff6b00)', iconPath: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm5 11h-4v4h-2v-4H7v-2h4V7h2v4h4v2z', titleKey: 'Быстрая реакция', subtitleKey: 'Выбор эмодзи для реакции по двойному нажатию', }, { name: 'archive', gradient: 'linear-gradient(135deg,#00c6ff,#0072ff)', iconPath: 'M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zM12 17.5L6.5 12H10v-2h4v2h3.5L12 17.5zM5.12 5l.81-1h12.14l.82 1H5.12z', titleKey: 'Настройки архива', subtitleKey: 'Установка пароля на архив чатов', }, { name: 'dataStorage', gradient: 'linear-gradient(135deg,#34aadc,#007aff)', iconSvg: ( <svg viewBox="0 0 16 16" fill="currentColor"> <path d="M4.318 2.687C5.234 2.271 6.536 2 8 2s2.766.27 3.682.687C12.644 3.125 13 3.627 13 4c0 .374-.356.875-1.318 1.313C10.766 5.729 9.464 6 8 6s-2.766-.27-3.682-.687C3.356 4.875 3 4.373 3 4c0-.374.356-.875 1.318-1.313M13 5.698V7c0 .374-.356.875-1.318 1.313C10.766 8.729 9.464 9 8 9s-2.766-.27-3.682-.687C3.356 7.875 3 7.373 3 7V5.698c.271.202.58.378.904.525C4.978 6.711 6.427 7 8 7s3.022-.289 4.096-.777A5 5 0 0 0 13 5.698M14 4c0-1.007-.875-1.755-1.904-2.223C11.022 1.289 9.573 1 8 1s-3.022.289-4.096.777C2.875 2.245 2 2.993 2 4v9c0 1.007.875 1.755 1.904 2.223C4.978 15.71 6.427 16 8 16s3.022-.289 4.096-.777C13.125 14.755 14 14.007 14 13zm-1 4.698V10c0 .374-.356.875-1.318 1.313C10.766 11.729 9.464 12 8 12s-2.766-.27-3.682-.687C3.356 10.875 3 10.373 3 10V8.698c.271.202.58.378.904.525C4.978 9.71 6.427 10 8 10s3.022-.289 4.096-.777A5 5 0 0 0 13 8.698m0 3V13c0 .374-.356.875-1.318 1.313C10.766 14.729 9.464 15 8 15s-2.766-.27-3.682-.687C3.356 13.875 3 13.373 3 13v-1.302c.271.202.58.378.904.525C4.978 12.71 6.427 13 8 13s3.022-.289 4.096-.777c.324-.147.633-.323.904-.525"/> </svg> ), titleKey: 'Данные и память', subtitleKey: 'Управление кэшем и автоматическая очистка', }, { name: 'exportData', gradient: 'linear-gradient(135deg,#30d158,#28a745)', iconPath: 'M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z', titleKey: 'Экспорт данных', subtitleKey: 'Выгрузить историю чатов и информацию', }, { name: 'language', gradient: 'linear-gradient(135deg,#af52de,#8e24aa)', iconPath: 'M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2s.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2s.07-1.35.16-2h4.68c.09.65.16 1.32.16 2s-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2s-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z', titleKey: 'Язык', subtitleKey: 'Выбор языка интерфейса', }, { name: 'reportBug', gradient: 'linear-gradient(135deg,#ff5a5f,#d93848)', iconSvg: ( <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"> <path d="M12 2L2 19h20L12 2zm-1 6h2v6h-2V8zm0 8h2v2h-2v-2z" /> </svg> ), titleKey: 'Сообщить об ошибке', subtitleKey: 'Отправить отчёт об ошибке', }, { name: 'faq', gradient: 'linear-gradient(135deg,#00c6ff,#3a86ff)', iconSvg: ( <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"> <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm1 16h-2v-2h2v2zm1.8-6.6c-.35.35-.8.62-1.3.86V13h-3v-1.5c0-.55.45-1 1-1s1 .45 1 1h1.5c0-1.38-1.12-2.5-2.5-2.5s-2.5 1.12-2.5 2.5c0 .7.29 1.33.75 1.78-.55.47-1.75 1.5-1.75 2.72h3c0-1 1-1.5 1.4-1.8.3-.2.6-.5.6-.9 0-.55.45-1 1-1s1 .45 1 1c0 .3-.13.56-.3.74z" /> </svg> ), titleKey: 'FAQ / Центр помощи', subtitleKey: 'База знаний для пользователей', }, { name: 'about', gradient: 'linear-gradient(135deg,#8e8e93,#636366)', iconSvg: ( <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"> <path d="M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z" /> </svg> ), titleKey: 'О приложении', subtitleKey: 'Версия, лицензии и политика конфиденциальности', },];
const sections = [ { titleKey: 'ОФОРМЛЕНИЕ', items: ['customization', 'language'], }, { titleKey: 'УПРАВЛЕНИЕ', items: ['hotkeys', 'archive', 'quickReaction', 'dataStorage', 'exportData'], }, { titleKey: 'УВЕДОМЛЕНИЯ', items: ['sound', 'notifRepeat'], },];
export default function ChatSettingsModal({ isOpen, onClose, onOpenSubModal }: Props) { const { t } = useI18n(); const [visible, setVisible] = useState(isOpen); const [closing, setClosing] = useState(false); const [entered, setEntered] = useState(false); const [foldersOn, setFoldersOn] = useState(() => isFoldersEnabled()); const [videoOpts, setVideoOpts] = useState<VideoMessageSettings>(() => getVideoMessageSettings());
const setVideoOpt = useCallback(<K extends keyof VideoMessageSettings>(key: K, value: VideoMessageSettings[K]) => { setVideoMessageSetting(key, value); setVideoOpts(prev => ({ ...prev, [key]: value })); }, []);
const toggleFolders = useCallback(() => { setFoldersOn(prev => { const next = !prev; setFoldersEnabled(next); return next; }); }, []);
useEffect(() => { if (isOpen) { setVisible(true); setClosing(false); setEntered(false); const raf = requestAnimationFrame(() => { requestAnimationFrame(() => { setEntered(true); }); }); return () => cancelAnimationFrame(raf); } return undefined; }, [isOpen]);
useEffect(() => { if (!closing) return; const timer = setTimeout(() => { setVisible(false); setClosing(false); setEntered(false); onClose(); }, 400); return () => clearTimeout(timer); }, [closing, onClose]);
const handleClose = useCallback(() => { if (closing) return; setClosing(true); }, [closing]);
useEffect(() => { const onEsc = (e: KeyboardEvent) => { if (e.key === 'Escape') handleClose(); }; document.addEventListener('keydown', onEsc); return () => document.removeEventListener('keydown', onEsc); }, [handleClose]);
const handleItemClick = useCallback((name: string) => { if (closing) return; setClosing(true); setTimeout(() => { setVisible(false); setClosing(false); onOpenSubModal(name); }, 400); }, [closing, onOpenSubModal]);
const itemMap = new Map(menuItems.map(i => [i.name, i]));
if (!visible) return null;
return ( <div className={`${styles.overlay} ${entered && !closing ? styles.open : ''} ${closing ? styles.closing : ''}`} onClick={handleClose} > <div className={styles.modal} onClick={e => e.stopPropagation()}> <div className={styles.header}> <h2 className={styles.title}>{t('Чаты')}</h2> </div>
<div className={styles.scrollContent}> {sections.map(section => ( <div key={section.titleKey}> <div className={styles.sectionHeader}>{t(section.titleKey)}</div> <div className={styles.sectionGroup}> {section.items.map(name => { const item = itemMap.get(name)!; return ( <button key={item.name} className={styles.hubItem} onClick={() => handleItemClick(item.name)} > <div className={styles.iconBox} style={{ background: item.gradient }} > {'iconSvg' in item ? (item as any).iconSvg : ( <svg viewBox="0 0 24 24"> <path d={item.iconPath} /> </svg> )} </div> <div className={styles.textBlock}> <span className={styles.itemLabel}>{t(item.titleKey)}</span> <span className={styles.itemDesc}>{t(item.subtitleKey)}</span> </div> <span className={styles.arrow}>›</span> </button> ); })} </div> </div> ))}
<div className={styles.sectionHeader}>{t('ВИДЕОСООБЩЕНИЯ')}</div> <div className={styles.sectionGroup}> <div className={styles.videoOptionRow}> <span className={styles.videoOptionLabel}>{t('Камера по умолчанию')}</span> <div className={styles.videoOptionBtns}> {([['user', 'Передняя'], ['environment', 'Основная']] as const).map(([v, label]) => ( <button key={v} className={`${styles.videoOptionBtn} ${videoOpts.camera === v ? styles.videoOptionBtnActive : ''}`} onClick={() => setVideoOpt('camera', v)} >{t(label)}</button> ))} </div> </div> <div className={styles.videoOptionRow}> <span className={styles.videoOptionLabel}>{t('Качество видео')}</span> <div className={styles.videoOptionBtns}> {[720, 480, 360].map(q => ( <button key={q} className={`${styles.videoOptionBtn} ${videoOpts.quality === q ? styles.videoOptionBtnActive : ''}`} onClick={() => setVideoOpt('quality', q)} >{q}p</button> ))} </div> </div> <div className={styles.videoOptionRow}> <span className={styles.videoOptionLabel}>{t('Формат')}</span> <div className={styles.videoOptionBtns}> {([['mp4', 'MP4 (H.264)'], ['webm', 'WebM']] as const).map(([v, label]) => ( <button key={v} className={`${styles.videoOptionBtn} ${videoOpts.codec === v ? styles.videoOptionBtnActive : ''}`} onClick={() => setVideoOpt('codec', v)} >{label}</button> ))} </div> </div> <div className={styles.videoOptionRow}> <span className={styles.videoOptionLabel}>{t('Битрейт')}</span> <div className={styles.videoOptionBtns}> {([1500000, 2500000, 4000000] as const).map(b => ( <button key={b} className={`${styles.videoOptionBtn} ${videoOpts.bitrate === b ? styles.videoOptionBtnActive : ''}`} onClick={() => setVideoOpt('bitrate', b)} >{b / 1000000} Мбит</button> ))} </div> </div> </div>
<div className={styles.sectionHeader}>{t('ДОПОЛНИТЕЛЬНО')}</div> <div className={styles.sectionGroup}> <div className={styles.hubItem} style={{ cursor: 'pointer' }} onClick={toggleFolders}> <div className={styles.iconBox} style={{ background: 'linear-gradient(135deg,#a74fff,#8b3dff)' }}> <svg viewBox="0 0 24 24" fill="currentColor" width="22" height="22"> <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" /> </svg> </div> <div className={styles.textBlock}> <span className={styles.itemLabel}>{t('Папки с чатами')}</span> <span className={styles.itemDesc}>{t('Группировка чатов по папкам')}</span> </div> <div className={`${styles.toggle} ${foldersOn ? styles.toggleOn : ''}`} onClick={e => { e.stopPropagation(); toggleFolders(); }}> <div className={styles.toggleKnob} /> </div> </div> </div>
<div className={styles.sectionHeader}>{t('ПОМОЩЬ')}</div> <div className={styles.sectionGroup}> {['reportBug', 'faq', 'about'].map(name => { const item = itemMap.get(name)!; return ( <button key={item.name} className={styles.hubItem} onClick={() => handleItemClick(item.name)} > <div className={styles.iconBox} style={{ background: item.gradient }}> {'iconSvg' in item ? (item as any).iconSvg : ( <svg viewBox="0 0 24 24"> <path d={item.iconPath} /> </svg> )} </div> <div className={styles.textBlock}> <span className={styles.itemLabel}>{t(item.titleKey)}</span> <span className={styles.itemDesc}>{t(item.subtitleKey)}</span> </div> <span className={styles.arrow}>›</span> </button> ); })} </div> </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856import { createContext, useContext, useState, useCallback, useEffect } from 'react';import type { ReactNode } from 'react';import { getLocalStorage, setLocalStorage } from '../utils/storage';import type { AppLang } from '../hooks/useI18n';
type FontFamily = 'default' | 'gilroy-inter' | 'unbounded-onest' | 'sf-display-text' | 'montserrat-roboto' | 'manrope-inter' | 'golos-onest' | 'rubik-geometria' | 'clash-satoshi' | 'ubuntu-noto';type Theme = 'classic' | 'lavender-graphite' | 'oil-ink' | 'mint-espresso' | 'sage-slate' | 'dusty-rose' | 'eucalyptus-asphalt' | 'oat-chocolate' | 'polar-mint-ocean' | 'ash-rose-marengo' | 'olive-anthracite' | 'meltwater-monsoon' | 'wild-honey-obsidian' | 'gray-sage-noir' | 'jade-graphite' | 'terracotta-basalt' | 'cyan-abyss' | 'crimson-twilight';
interface SettingsState { textSize: 'small' | 'medium' | 'large'; fontFamily: FontFamily; theme: Theme; bubbleRadius: 'none' | 'small' | 'medium' | 'large' | 'full'; animationSpeed: 'off' | 'fast' | 'normal'; showTime: boolean; showRead: boolean; showEdited: boolean; showTimer: boolean; statusIndicator: 'ring' | 'dot'; avatarStyle: 'round' | 'rounded' | 'dodecagon'; chatBackground: 'default' | 'dark' | 'darker' | 'deep-purple' | 'gradient-night' | 'gradient-ocean' | 'gradient-sunset' | 'gradient-forest'; messageAlignment: 'default' | 'allLeft'; density: 'compact' | 'normal' | 'comfortable'; scrollbarWidth: 'thin' | 'normal' | 'medium'; sidebarWidth: 'compact' | 'normal' | 'medium' | 'large' | 'wide'; volume: number; notificationRepeat: number; autoLockMinutes: number; autoDeleteMonths: number; autoLogoutDays: number; quickReaction: string; language: AppLang; privacyState: Record<string, 'all' | 'none' | 'selected'>; privacyExceptions: Record<string, string[]>; isAppLocked: boolean; pin: string | null; menuItems: Record<string, string[]>;}
interface SettingsContextType extends SettingsState { textSize: 'small' | 'medium' | 'large'; setTextSize: (size: 'small' | 'medium' | 'large') => void; fontFamily: FontFamily; setFontFamily: (f: FontFamily) => void; theme: Theme; setTheme: (t: Theme) => void; bubbleRadius: 'none' | 'small' | 'medium' | 'large' | 'full'; setBubbleRadius: (r: 'none' | 'small' | 'medium' | 'large' | 'full') => void; animationSpeed: 'off' | 'fast' | 'normal'; setAnimationSpeed: (a: 'off' | 'fast' | 'normal') => void; showTime: boolean; setShowTime: (v: boolean) => void; showRead: boolean; setShowRead: (v: boolean) => void; showEdited: boolean; setShowEdited: (v: boolean) => void; showTimer: boolean; setShowTimer: (v: boolean) => void; statusIndicator: 'ring' | 'dot'; setStatusIndicator: (v: 'ring' | 'dot') => void; avatarStyle: 'round' | 'rounded' | 'dodecagon'; setAvatarStyle: (v: 'round' | 'rounded' | 'dodecagon') => void; chatBackground: 'default' | 'dark' | 'darker' | 'deep-purple' | 'gradient-night' | 'gradient-ocean' | 'gradient-sunset' | 'gradient-forest'; setChatBackground: (v: 'default' | 'dark' | 'darker' | 'deep-purple' | 'gradient-night' | 'gradient-ocean' | 'gradient-sunset' | 'gradient-forest') => void; messageAlignment: 'default' | 'allLeft'; setMessageAlignment: (v: 'default' | 'allLeft') => void; density: 'compact' | 'normal' | 'comfortable'; setDensity: (v: 'compact' | 'normal' | 'comfortable') => void; scrollbarWidth: 'thin' | 'normal' | 'medium'; setScrollbarWidth: (v: 'thin' | 'normal' | 'medium') => void; sidebarWidth: 'compact' | 'normal' | 'medium' | 'large' | 'wide'; setSidebarWidth: (v: 'compact' | 'normal' | 'medium' | 'large' | 'wide') => void; volume: number; setVolume: (vol: number) => void; notificationRepeat: number; setNotificationRepeat: (minutes: number) => void; autoLockMinutes: number; setAutoLockMinutes: (minutes: number) => void; autoDeleteMonths: number; setAutoDeleteMonths: (months: number) => void; autoLogoutDays: number; setAutoLogoutDays: (days: number) => void; quickReaction: string; setQuickReaction: (emoji: string) => void; language: AppLang; setLanguage: (lang: AppLang) => void; privacyState: Record<string, 'all' | 'none' | 'selected'>; setPrivacyOption: (key: string, val: 'all' | 'none' | 'selected') => void; privacyExceptions: Record<string, string[]>; setAllPrivacy: (state: Record<string, 'all' | 'none' | 'selected'>, exceptions: Record<string, string[]>) => void; addPrivacyException: (key: string, username: string) => void; removePrivacyException: (key: string, username: string) => void; isAppLocked: boolean; lockApp: () => void; unlockApp: (pin: string) => boolean; confirmUnlock: () => void; pin: string | null; setPin: (pin: string) => void; menuItems: Record<string, string[]>; setMenuOrder: (menu: string, items: string[]) => void;}
const SettingsContext = createContext<SettingsContextType | null>(null);
const initialSettings: SettingsState = { textSize: 'medium' as const, fontFamily: 'ubuntu-noto' as const, theme: 'classic' as const, bubbleRadius: 'medium' as const, animationSpeed: 'normal' as const, showTime: true, showRead: true, showEdited: true, showTimer: true, statusIndicator: 'ring', avatarStyle: 'round', chatBackground: 'default', messageAlignment: 'default', density: 'normal', scrollbarWidth: 'normal', sidebarWidth: 'normal', volume: 1, notificationRepeat: 5, autoLockMinutes: 0, autoDeleteMonths: 6, autoLogoutDays: 7, quickReaction: '❤️', language: 'ru' as const, privacyState: { avatar: 'all', bio: 'all', status: 'all', messages: 'all', calls: 'all', voice_video: 'all', forwards: 'all', search: 'all' }, privacyExceptions: { avatar: [], bio: [], status: [], messages: [], calls: [], voice_video: [], forwards: [], search: [] }, isAppLocked: false, pin: null, menuItems: { chat_ctx: ['pin', 'folder', 'archive', 'mute', 'block', 'delete_chat'], chat_header: ['search', 'mute', 'block', 'autoDelete', 'stats', 'profile', 'members', 'delete_chat'], msg_ctx: ['reply', 'copy', 'forward', 'save', 'pin_msg', 'select', 'edit', 'delete_msg'], },};
function applyCssVars(s: SettingsState) { const sizeMap: Record<string, string> = { small: '14px', medium: '16px', large: '18px' }; const fontMap: Record<string, string> = { default: '"Plus Jakarta Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'gilroy-inter': '"Gilroy", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'unbounded-onest': '"Unbounded", "Onest", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'sf-display-text': '"SF Pro Display", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'montserrat-roboto': '"Montserrat", "Roboto", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif', 'manrope-inter': '"Manrope", "Inter", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'golos-onest': '"Golos Text", "Onest", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'rubik-geometria': '"Rubik", "Geometria", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'clash-satoshi': '"Clash Display", "Satoshi", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', 'ubuntu-noto': '"Noto Sans", "Ubuntu", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', }; const headingFontMap: Record<string, string> = { default: '"Ubuntu", sans-serif', 'gilroy-inter': '"Gilroy", sans-serif', 'unbounded-onest': '"Unbounded", sans-serif', 'sf-display-text': '"SF Pro Display", sans-serif', 'montserrat-roboto': '"Montserrat", sans-serif', 'manrope-inter': '"Manrope", sans-serif', 'golos-onest': '"Golos Text", sans-serif', 'rubik-geometria': '"Rubik", sans-serif', 'clash-satoshi': '"Clash Display", sans-serif', 'ubuntu-noto': '"Ubuntu", sans-serif', }; const themeMap: Record<string, Record<string, string>> = { 'classic': { accent: '#a74fff', 'accent-solid': '#a74fff', 'accent-rgb': '167, 79, 255', 'accent-hover': '#9147e0', bg: '#0a0a0c', 'bg-elevated': '#0f0f13', sidebar: '#121218', 'sidebar-hover': '#1a1a22', card: '#1a1a24', 'card-hover': '#22222c', 'card-rgb': '26, 26, 36', border: '#252530', 'border-light': '#2e2e3a', 'overlay-rgb': '30, 27, 36', sent: '#2d1b4d', 'sent-hover': '#3a255a', rcv: '#1e1e24', 'rcv-hover': '#282830', 'shadow-glow': '0 0 20px rgba(167, 79, 255, 0.3)', }, 'lavender-graphite': { accent: '#B8A7F0', 'accent-solid': '#B8A7F0', 'accent-rgb': '184, 167, 240', 'accent-hover': '#A693E0', bg: '#232329', 'bg-elevated': '#28282E', sidebar: '#1E1E24', 'sidebar-hover': '#26262C', card: '#2A2A32', 'card-hover': '#32323A', 'card-rgb': '42, 42, 50', border: '#2F2F38', 'border-light': '#383842', 'overlay-rgb': '30, 30, 36', sent: '#2E2840', 'sent-hover': '#3A3250', rcv: '#1E1E26', 'rcv-hover': '#282830', 'shadow-glow': '0 0 20px rgba(184, 167, 240, 0.3)', }, 'oil-ink': { accent: '#F2D06B', 'accent-solid': '#F2D06B', 'accent-rgb': '242, 208, 107', 'accent-hover': '#E0BE59', 'on-accent': '#1a1a1a', bg: '#1E2530', 'bg-elevated': '#232A36', sidebar: '#181E28', 'sidebar-hover': '#202632', card: '#252D39', 'card-hover': '#2D3541', 'card-rgb': '37, 45, 57', border: '#2A3340', 'border-light': '#35404D', 'overlay-rgb': '24, 30, 40', sent: '#2E3430', 'sent-hover': '#3A403A', rcv: '#1A2028', 'rcv-hover': '#222A32', 'shadow-glow': '0 0 20px rgba(242, 208, 107, 0.3)', }, 'mint-espresso': { accent: '#B9E5C8', 'accent-solid': '#B9E5C8', 'accent-rgb': '185, 229, 200', 'accent-hover': '#A7D3B6', 'on-accent': '#1a1a1a', bg: '#2B1A12', 'bg-elevated': '#302018', sidebar: '#241511', 'sidebar-hover': '#2C1C18', card: '#33201B', 'card-hover': '#3B2823', 'card-rgb': '51, 32, 27', border: '#3A2620', 'border-light': '#45302A', 'overlay-rgb': '36, 21, 17', sent: '#2E2820', 'sent-hover': '#3A3228', rcv: '#241814', 'rcv-hover': '#2C201C', 'shadow-glow': '0 0 20px rgba(185, 229, 200, 0.3)', }, 'sage-slate': { accent: '#9CAF88', 'accent-solid': '#9CAF88', 'accent-rgb': '156, 175, 136', 'accent-hover': '#8A9D76', bg: '#2F3E46', 'bg-elevated': '#35454D', sidebar: '#28363D', 'sidebar-hover': '#303E45', card: '#35454D', 'card-hover': '#3D4D55', 'card-rgb': '53, 69, 77', border: '#3D4D55', 'border-light': '#4A5A62', 'overlay-rgb': '36, 46, 52', sent: '#2E3A36', 'sent-hover': '#3A4842', rcv: '#28363D', 'rcv-hover': '#303E45', 'shadow-glow': '0 0 20px rgba(156, 175, 136, 0.3)', }, 'dusty-rose': { accent: '#CCA7A3', 'accent-solid': '#CCA7A3', 'accent-rgb': '204, 167, 163', 'accent-hover': '#BA9591', bg: '#1A1C29', 'bg-elevated': '#20222F', sidebar: '#14161F', 'sidebar-hover': '#1C1E27', card: '#222430', 'card-hover': '#2A2C38', 'card-rgb': '34, 36, 48', border: '#2A2C38', 'border-light': '#353745', 'overlay-rgb': '22, 23, 33', sent: '#2E2430', 'sent-hover': '#3A2E3A', rcv: '#1A1C29', 'rcv-hover': '#222430', 'shadow-glow': '0 0 20px rgba(204, 167, 163, 0.3)', }, 'eucalyptus-asphalt': { accent: '#A3B19B', 'accent-solid': '#A3B19B', 'accent-rgb': '163, 177, 155', 'accent-hover': '#919F89', bg: '#252627', 'bg-elevated': '#2B2C2D', sidebar: '#1F2021', 'sidebar-hover': '#272829', card: '#2D2E2F', 'card-hover': '#353637', 'card-rgb': '45, 46, 47', border: '#353637', 'border-light': '#404142', 'overlay-rgb': '25, 26, 27', sent: '#2A2E28', 'sent-hover': '#363A32', rcv: '#1F2021', 'rcv-hover': '#272829', 'shadow-glow': '0 0 20px rgba(163, 177, 155, 0.3)', }, 'oat-chocolate': { accent: '#E6DFD3', 'accent-solid': '#E6DFD3', 'accent-rgb': '230, 223, 211', 'accent-hover': '#D4CDC1', 'on-accent': '#1a1a1a', bg: '#2B211B', 'bg-elevated': '#302721', sidebar: '#241B16', 'sidebar-hover': '#2C231E', card: '#332922', 'card-hover': '#3B312A', 'card-rgb': '51, 41, 34', border: '#3A302A', 'border-light': '#453B35', 'overlay-rgb': '36, 27, 22', sent: '#2E2820', 'sent-hover': '#3A3228', rcv: '#241B16', 'rcv-hover': '#2C231E', 'shadow-glow': '0 0 20px rgba(230, 223, 211, 0.3)', }, 'polar-mint-ocean': { accent: '#BFFCC6', 'accent-solid': '#BFFCC6', 'accent-rgb': '191, 252, 198', 'accent-hover': '#ADEAB4', 'on-accent': '#1a1a1a', bg: '#0D1B2A', 'bg-elevated': '#12202F', sidebar: '#0A1522', 'sidebar-hover': '#121D2A', card: '#14222F', 'card-hover': '#1C2A37', 'card-rgb': '20, 34, 47', border: '#1C2A37', 'border-light': '#273542', 'overlay-rgb': '10, 21, 30', sent: '#1A2830', 'sent-hover': '#263238', rcv: '#0D1B2A', 'rcv-hover': '#14222F', 'shadow-glow': '0 0 20px rgba(191, 252, 198, 0.3)', }, 'ash-rose-marengo': { accent: '#B59A9A', 'accent-solid': '#B59A9A', 'accent-rgb': '181, 154, 154', 'accent-hover': '#A38888', bg: '#20242C', 'bg-elevated': '#262A32', sidebar: '#1A1E26', 'sidebar-hover': '#22262E', card: '#282C34', 'card-hover': '#30343C', 'card-rgb': '40, 44, 52', border: '#30343C', 'border-light': '#3A3E46', 'overlay-rgb': '22, 26, 34', sent: '#2E2430', 'sent-hover': '#3A2E3A', rcv: '#1A1E26', 'rcv-hover': '#22262E', 'shadow-glow': '0 0 20px rgba(181, 154, 154, 0.3)', }, 'olive-anthracite': { accent: '#8A9A86', 'accent-solid': '#8A9A86', 'accent-rgb': '138, 154, 134', 'accent-hover': '#788874', bg: '#1C1E21', 'bg-elevated': '#222427', sidebar: '#16181B', 'sidebar-hover': '#1E2023', card: '#242628', 'card-hover': '#2C2E30', 'card-rgb': '36, 38, 40', border: '#2C2E30', 'border-light': '#36383A', 'overlay-rgb': '18, 20, 23', sent: '#2A2E28', 'sent-hover': '#363A32', rcv: '#1C1E21', 'rcv-hover': '#242628', 'shadow-glow': '0 0 20px rgba(138, 154, 134, 0.3)', }, 'meltwater-monsoon': { accent: '#A9BCC6', 'accent-solid': '#A9BCC6', 'accent-rgb': '169, 188, 198', 'accent-hover': '#97AAB4', bg: '#1E252B', 'bg-elevated': '#242B31', sidebar: '#181F25', 'sidebar-hover': '#20272D', card: '#262D33', 'card-hover': '#2E353B', 'card-rgb': '38, 45, 51', border: '#2E353B', 'border-light': '#384046', 'overlay-rgb': '22, 28, 34', sent: '#222A30', 'sent-hover': '#2E343A', rcv: '#181F25', 'rcv-hover': '#20272D', 'shadow-glow': '0 0 20px rgba(169, 188, 198, 0.3)', }, 'wild-honey-obsidian': { accent: '#D0A36E', 'accent-solid': '#D0A36E', 'accent-rgb': '208, 163, 110', 'accent-hover': '#BE915C', bg: '#191A1C', 'bg-elevated': '#1F2022', sidebar: '#131416', 'sidebar-hover': '#1B1C1E', card: '#212224', 'card-hover': '#292A2C', 'card-rgb': '33, 34, 36', border: '#292A2C', 'border-light': '#333436', 'overlay-rgb': '15, 16, 18', sent: '#2E2820', 'sent-hover': '#3A3228', rcv: '#191A1C', 'rcv-hover': '#212224', 'shadow-glow': '0 0 20px rgba(208, 163, 110, 0.3)', }, 'gray-sage-noir': { accent: '#B2C2B7', 'accent-solid': '#B2C2B7', 'accent-rgb': '178, 194, 183', 'accent-hover': '#A0B0A5', 'on-accent': '#1a1a1a', bg: '#15161A', 'bg-elevated': '#1B1C20', sidebar: '#0F1014', 'sidebar-hover': '#17181C', card: '#1D1E22', 'card-hover': '#25262A', 'card-rgb': '29, 30, 34', border: '#25262A', 'border-light': '#2F3034', 'overlay-rgb': '12, 13, 17', sent: '#222628', 'sent-hover': '#2E3234', rcv: '#15161A', 'rcv-hover': '#1D1E22', 'shadow-glow': '0 0 20px rgba(178, 194, 183, 0.3)', }, 'jade-graphite': { accent: '#9DB3A4', 'accent-solid': '#9DB3A4', 'accent-rgb': '157, 179, 164', 'accent-hover': '#8BA192', 'on-accent': '#1a1a1a', bg: '#1F2221', 'bg-elevated': '#252826', sidebar: '#191C1B', 'sidebar-hover': '#212423', card: '#272A29', 'card-hover': '#2F3231', 'card-rgb': '39, 42, 41', border: '#2F3231', 'border-light': '#393C3B', 'overlay-rgb': '18, 21, 20', sent: '#262A28', 'sent-hover': '#323634', rcv: '#1F2221', 'rcv-hover': '#272A29', 'shadow-glow': '0 0 20px rgba(157, 179, 164, 0.3)', }, 'terracotta-basalt': { accent: '#C87D6B', 'accent-solid': '#C87D6B', 'accent-rgb': '200, 125, 107', 'accent-hover': '#B66B59', bg: '#1A1615', 'bg-elevated': '#201C1B', sidebar: '#141011', 'sidebar-hover': '#1C1819', card: '#221E1D', 'card-hover': '#2A2625', 'card-rgb': '34, 30, 29', border: '#2A2625', 'border-light': '#34302F', 'overlay-rgb': '14, 10, 9', sent: '#2E221E', 'sent-hover': '#3A2C28', rcv: '#1A1615', 'rcv-hover': '#221E1D', 'shadow-glow': '0 0 20px rgba(200, 125, 107, 0.3)', }, 'cyan-abyss': { accent: '#5FD9D0', 'accent-solid': '#5FD9D0', 'accent-rgb': '95, 217, 208', 'accent-hover': '#4DC7BE', 'on-accent': '#1a1a1a', bg: '#0A0E12', 'bg-elevated': '#101418', sidebar: '#060A0E', 'sidebar-hover': '#0E1216', card: '#12161A', 'card-hover': '#1A1E22', 'card-rgb': '18, 22, 26', border: '#1A1E22', 'border-light': '#24282C', 'overlay-rgb': '6, 10, 14', sent: '#0E2228', 'sent-hover': '#1A2E34', rcv: '#060A0E', 'rcv-hover': '#0E1216', 'shadow-glow': '0 0 20px rgba(95, 217, 208, 0.3)', }, 'crimson-twilight': { accent: '#C6686A', 'accent-solid': '#C6686A', 'accent-rgb': '198, 104, 106', 'accent-hover': '#B45658', bg: '#161214', 'bg-elevated': '#1C181A', sidebar: '#100C0E', 'sidebar-hover': '#181416', card: '#1E1A1C', 'card-hover': '#262224', 'card-rgb': '30, 26, 28', border: '#262224', 'border-light': '#302C2E', 'overlay-rgb': '12, 8, 10', sent: '#2E1C22', 'sent-hover': '#3A2630', rcv: '#161214', 'rcv-hover': '#1E1A1C', 'shadow-glow': '0 0 20px rgba(198, 104, 106, 0.3)', }, }; const root = document.documentElement; const basePx = sizeMap[s.textSize] || '16px'; const scale = s.textSize === 'small' ? '0.875' : s.textSize === 'large' ? '1.125' : '1'; root.style.setProperty('--msg-text-size', basePx); root.style.setProperty('--font-size-base', basePx); root.style.setProperty('--font-size-scale', scale); root.style.setProperty('--fs-unit', `calc(1px * ${scale})`); root.style.fontSize = basePx; root.style.setProperty('--font-main', fontMap[s.fontFamily] ?? fontMap.default); root.style.setProperty('--font-heading', headingFontMap[s.fontFamily] ?? headingFontMap.default); const radiusMap: Record<string, string> = { none: '4px', small: '10px', medium: '18px', large: '28px', full: '50px' }; root.style.setProperty('--bubble-radius', radiusMap[s.bubbleRadius] || '18px'); const animDurations: Record<string, { fast: string; base: string; slow: string }> = { normal: { fast: '0.15s', base: '0.3s', slow: '0.5s' }, fast: { fast: '0.08s', base: '0.12s', slow: '0.2s' }, off: { fast: '0s', base: '0s', slow: '0s' }, }; const dur = animDurations[s.animationSpeed] ?? animDurations.normal; root.style.setProperty('--anim-dur-fast', dur.fast); root.style.setProperty('--anim-dur-base', dur.base); root.style.setProperty('--anim-dur-slow', dur.slow); root.style.setProperty('--show-time', s.showTime ? 'inline' : 'none'); root.style.setProperty('--show-read', s.showRead ? 'flex' : 'none'); root.style.setProperty('--show-edited', s.showEdited ? 'inline' : 'none'); root.style.setProperty('--show-timer', s.showTimer ? 'flex' : 'none'); root.style.setProperty('--status-style', s.statusIndicator); const avatarRadiusMap: Record<string, string> = { round: '50%', rounded: '12px', dodecagon: '0' }; const avatarClipMap: Record<string, string> = { round: 'none', rounded: 'none', dodecagon: 'polygon(100% 50%, 93.3% 75%, 75% 93.3%, 50% 100%, 25% 93.3%, 6.7% 75%, 0% 50%, 6.7% 25%, 25% 6.7%, 50% 0%, 75% 6.7%, 93.3% 25%)' }; root.style.setProperty('--avatar-radius', avatarRadiusMap[s.avatarStyle] || '50%'); root.style.setProperty('--avatar-clip', avatarClipMap[s.avatarStyle] || 'none'); const chatBgMap: Record<string, string> = { default: '#0f0f13', dark: '#0f0f13', darker: '#08080a', 'deep-purple': '#12101a', 'gradient-night': 'linear-gradient(145deg, #0a0a12 0%, #1a1025 50%, #0d0d1a 100%)', 'gradient-ocean': 'linear-gradient(145deg, #070e1a 0%, #0d1f2a 50%, #070e1a 100%)', 'gradient-sunset': 'linear-gradient(145deg, #1a0f0a 0%, #2a1512 50%, #1a0f0a 100%)', 'gradient-forest': 'linear-gradient(145deg, #0a140e 0%, #15221a 50%, #0a140e 100%)', }; const chatPatternOpacity: Record<string, string> = { default: '0.6', dark: '0', darker: '0', 'deep-purple': '0', 'gradient-night': '0.1', 'gradient-ocean': '0.1', 'gradient-sunset': '0.1', 'gradient-forest': '0.1', }; root.style.setProperty('--chat-bg', chatBgMap[s.chatBackground] || '#0f0f13'); root.style.setProperty('--chat-pattern', chatPatternOpacity[s.chatBackground] || '0'); root.style.setProperty('--msg-justify-sent', s.messageAlignment === 'allLeft' ? 'flex-start' : 'flex-end'); root.style.setProperty('--msg-align-self-sent', s.messageAlignment === 'allLeft' ? 'flex-start' : 'flex-end'); const densityVars: Record<string, Record<string, string>> = { compact: { '--density-msg-gap': '4px', '--density-msg-padding': '12px', '--density-contact-padding': '8px 15px', '--density-header-padding': '10px 20px', '--density-input-padding': '4px 8px', '--density-bottom-gap': '4px', }, normal: { '--density-msg-gap': '8px', '--density-msg-padding': '20px', '--density-contact-padding': '12px 15px', '--density-header-padding': '15px 25px', '--density-input-padding': '8px 12px', '--density-bottom-gap': '8px', }, comfortable: { '--density-msg-gap': '14px', '--density-msg-padding': '28px', '--density-contact-padding': '16px 20px', '--density-header-padding': '20px 30px', '--density-input-padding': '12px 16px', '--density-bottom-gap': '12px', }, }; const dv = densityVars[s.density] ?? densityVars.normal; Object.entries(dv ?? {}).forEach(([key, val]) => root.style.setProperty(key, val)); root.setAttribute('data-scrollbar', s.scrollbarWidth); const sidebarWidthMap: Record<string, string> = { compact: '80px', normal: '320px', medium: '380px', large: '450px', wide: '55vw', }; root.style.setProperty('--sidebar-width', sidebarWidthMap[s.sidebarWidth] || '320px'); root.setAttribute('data-sidebar', s.sidebarWidth); if (s.animationSpeed === 'off') { root.style.setProperty('--anim-disabled', 'none'); root.setAttribute('data-anim-off', ''); root.removeAttribute('data-anim-fast'); } else if (s.animationSpeed === 'fast') { root.style.removeProperty('--anim-disabled'); root.setAttribute('data-anim-fast', ''); root.removeAttribute('data-anim-off'); } else { root.style.removeProperty('--anim-disabled'); root.removeAttribute('data-anim-off'); root.removeAttribute('data-anim-fast'); } const theme = themeMap[s.theme] ?? themeMap['classic']; Object.entries(theme ?? {}).forEach(([key, val]) => { root.style.setProperty(`--${key}`, val); });}
export const SettingsProvider = ({ children }: { children: ReactNode }) => { const [settings, setSettings] = useState<SettingsState>(() => { const storedPrivacy = (() => { try { return JSON.parse(localStorage.getItem('4send_privacy') || '{}'); } catch { return {}; } })(); const initial: SettingsState = { ...initialSettings, textSize: getLocalStorage('4send_text_size', 'medium'), fontFamily: getLocalStorage('4send_fontFamily', 'ubuntu-noto'), theme: getLocalStorage('4send_theme', 'classic'), bubbleRadius: getLocalStorage('4send_bubbleRadius', 'medium'), animationSpeed: getLocalStorage('4send_animationSpeed', 'normal'), showTime: getLocalStorage('4send_showTime', true), showRead: getLocalStorage('4send_showRead', true), showEdited: getLocalStorage('4send_showEdited', true), showTimer: getLocalStorage('4send_showTimer', true), statusIndicator: getLocalStorage('4send_statusIndicator', 'ring'), avatarStyle: getLocalStorage('4send_avatarStyle', 'round'), chatBackground: getLocalStorage('4send_chatBackground', 'default'), messageAlignment: getLocalStorage('4send_messageAlignment', 'default'), density: getLocalStorage('4send_density', 'normal'), scrollbarWidth: getLocalStorage('4send_scrollbarWidth', 'normal'), sidebarWidth: getLocalStorage('4send_sidebarWidth', 'normal'), volume: getLocalStorage('4send_volume', 1), notificationRepeat: getLocalStorage('4send_notif_repeat', 5), autoLockMinutes: getLocalStorage('4send_lock_time', 0), autoDeleteMonths: getLocalStorage('4send_autoDeleteMonths', getLocalStorage('4send_auto_delete', 6)), autoLogoutDays: getLocalStorage('4send_autoLogoutDays', getLocalStorage('4send_auto_logout', 7)), quickReaction: getLocalStorage('4send_quick_reaction', '❤️'), language: getLocalStorage<AppLang>('4send_language', 'ru'), pin: getLocalStorage('4send_pin', null), menuItems: (() => { try { const v = localStorage.getItem('4send_menu_items'); return v ? JSON.parse(v) : initialSettings.menuItems; } catch { return initialSettings.menuItems; } })(), isAppLocked: sessionStorage.getItem('4send_is_locked') === '1', privacyState: { avatar: storedPrivacy.avatar || 'all', bio: storedPrivacy.bio || 'all', status: storedPrivacy.status || 'all', messages: storedPrivacy.messages || 'all', calls: storedPrivacy.calls || 'all', voice_video: storedPrivacy.voice_video || 'all', forwards: storedPrivacy.forwards || 'all', search: storedPrivacy.search || 'all', }, privacyExceptions: { avatar: storedPrivacy.exceptions?.avatar || [], bio: storedPrivacy.exceptions?.bio || [], status: storedPrivacy.exceptions?.status || [], messages: storedPrivacy.exceptions?.messages || [], calls: storedPrivacy.exceptions?.calls || [], voice_video: storedPrivacy.exceptions?.voice_video || [], forwards: storedPrivacy.exceptions?.forwards || [], search: storedPrivacy.exceptions?.search || [], }, }; applyCssVars(initial); return initial; });
useEffect(() => { applyCssVars(settings); }, [settings.textSize, settings.fontFamily, settings.theme, settings.bubbleRadius, settings.animationSpeed, settings.showTime, settings.showRead, settings.showEdited, settings.showTimer, settings.statusIndicator, settings.avatarStyle, settings.chatBackground, settings.messageAlignment, settings.density, settings.scrollbarWidth, settings.sidebarWidth]);
useEffect(() => { if (!localStorage.getItem('4send_token')) return; let cancelled = false; (async () => { try { const { api } = await import('../services/api'); const data = await api.get<{ autoLogoutDays?: number; autoDeleteMonths?: number }>('/api/security-settings'); if (cancelled || !data) return; const days = [1, 7, 30, 180].includes(Number(data.autoLogoutDays)) ? Number(data.autoLogoutDays) : null; const months = [3, 6, 12].includes(Number(data.autoDeleteMonths)) ? Number(data.autoDeleteMonths) : null; if (days !== null) { setLocalStorage('4send_autoLogoutDays', days); setSettings(prev => ({ ...prev, autoLogoutDays: days })); } if (months !== null) { setLocalStorage('4send_autoDeleteMonths', months); setSettings(prev => ({ ...prev, autoDeleteMonths: months })); } } catch { /* ignore */ } })(); return () => { cancelled = true; }; }, []);
const updateSetting = useCallback(<K extends keyof SettingsContextType>(key: K, value: SettingsContextType[K]) => { setSettings(prev => { const newSettings = { ...prev, [key]: value }; if (key !== 'isAppLocked' && key !== 'pin' && key !== 'privacyExceptions') { setLocalStorage(`4send_${key}`, value); } return newSettings; }); }, []);
return ( <SettingsContext.Provider value={{ ...settings, setTextSize: (v) => updateSetting('textSize', v), setFontFamily: (v) => updateSetting('fontFamily', v), setTheme: (v) => updateSetting('theme', v), setBubbleRadius: (v) => updateSetting('bubbleRadius', v), setAnimationSpeed: (v) => updateSetting('animationSpeed', v), setShowTime: (v) => updateSetting('showTime', v), setShowRead: (v) => updateSetting('showRead', v), setShowEdited: (v) => updateSetting('showEdited', v), setShowTimer: (v) => updateSetting('showTimer', v), setStatusIndicator: (v) => updateSetting('statusIndicator', v), setAvatarStyle: (v) => updateSetting('avatarStyle', v), setChatBackground: (v) => updateSetting('chatBackground', v), setMessageAlignment: (v) => updateSetting('messageAlignment', v), setDensity: (v) => updateSetting('density', v), setScrollbarWidth: (v) => updateSetting('scrollbarWidth', v), setSidebarWidth: (v) => updateSetting('sidebarWidth', v), setVolume: (v) => updateSetting('volume', v), setNotificationRepeat: (v) => updateSetting('notificationRepeat', v), setAutoLockMinutes: (v) => updateSetting('autoLockMinutes', v), setAutoDeleteMonths: (v) => updateSetting('autoDeleteMonths', v), setAutoLogoutDays: (v) => updateSetting('autoLogoutDays', v), setQuickReaction: (v) => updateSetting('quickReaction', v), setLanguage: (v) => updateSetting('language', v), setPrivacyOption: (key, val) => { setSettings(prev => { const newState = { ...prev.privacyState, [key]: val }; const stored = JSON.parse(localStorage.getItem('4send_privacy') || '{}'); const merged = { ...stored, ...newState, exceptions: stored.exceptions }; setLocalStorage('4send_privacy', JSON.stringify(merged)); return { ...prev, privacyState: newState }; }); }, setAllPrivacy: (state, exceptions) => { setSettings(prev => { const payload = { ...state, exceptions }; setLocalStorage('4send_privacy', JSON.stringify(payload)); return { ...prev, privacyState: state, privacyExceptions: exceptions }; }); }, addPrivacyException: (key, username) => { setSettings(prev => { const exceptions = { ...prev.privacyExceptions, [key]: [...(prev.privacyExceptions[key] || []), username] }; const privacy = JSON.parse(localStorage.getItem('4send_privacy') || '{}'); privacy.exceptions = { ...privacy.exceptions, [key]: exceptions[key] }; setLocalStorage('4send_privacy', JSON.stringify(privacy)); return { ...prev, privacyExceptions: exceptions }; }); }, removePrivacyException: (key, username) => { setSettings(prev => { const exceptions = { ...prev.privacyExceptions, [key]: (prev.privacyExceptions[key] || []).filter(u => u !== username) }; const privacy = JSON.parse(localStorage.getItem('4send_privacy') || '{}'); privacy.exceptions = { ...privacy.exceptions, [key]: exceptions[key] }; setLocalStorage('4send_privacy', JSON.stringify(privacy)); return { ...prev, privacyExceptions: exceptions }; }); }, lockApp: () => { sessionStorage.setItem('4send_is_locked', '1'); setSettings(prev => ({ ...prev, isAppLocked: true })); }, unlockApp: (pin: string) => { if (pin === settings.pin) { return true; } return false; }, confirmUnlock: () => { sessionStorage.removeItem('4send_is_locked'); setSettings(prev => ({ ...prev, isAppLocked: false })); }, setPin: (pin: string) => { setSettings(prev => { setLocalStorage('4send_pin', pin); return { ...prev, pin }; }); }, setMenuOrder: (menu: string, items: string[]) => { setSettings(prev => { const newItems = { ...prev.menuItems, [menu]: items }; localStorage.setItem('4send_menu_items', JSON.stringify(newItems)); return { ...prev, menuItems: newItems }; }); }, }}> {children} </SettingsContext.Provider> );};
export const useSettings = (): SettingsContextType => { const context = useContext(SettingsContext); if (!context) throw new Error('useSettings must be used within SettingsProvider'); return context;};12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205.mainApp { display: flex; width: 100%; height: 100vh;}
.sidebar { width: var(--sidebar-width, 320px); background: var(--sidebar); border-right: 1px solid var(--border); display: flex; flex-direction: column;}
.sidebarHeader { padding: 20px; padding-top: max(20px, env(safe-area-inset-top)); display: flex; align-items: center; justify-content: space-between;}
.sidebarHeaderLeft { display: flex; align-items: center; gap: 15px;}
.sidebarTitle { font-weight: 900; background: var(--accent); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; font-size: calc(22px * var(--font-size-scale)); cursor: pointer; user-select: none; transition: transform 0.15s ease;}
.sidebarTitle:active { transform: scale(0.9);}
.controlBtn { background: transparent; border: none; cursor: pointer; transition: 0.2s; display: flex; align-items: center; justify-content: center;}
.controlBtn svg { width: 26px; height: 26px; fill: var(--accent-solid);}
.controlBtn:hover { transform: scale(1.1);}
.searchWrapper { position: relative; margin: 0 15px 15px;}
.searchPlaceholder { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; gap: 6px; color: #888; pointer-events: none; transition: all 0.2s ease; font-size: calc(15px * var(--font-size-scale)); font-weight: 500; z-index: 1;}
.searchPlaceholder.searchFocused { left: 15px; transform: translate(0, -50%);}
.searchPlaceholder.searchFocused span,.searchTextHidden { opacity: 0;}
.searchPlaceholder svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round;}
.searchInput { width: 100%; padding: 12px 15px 12px 40px; background: var(--card); border: 1px solid var(--border); border-radius: 20px; color: #fff; outline: 0; box-sizing: border-box; transition: 0.2s; font-size: calc(15px * var(--font-size-scale));}
.searchInput:focus { border-color: var(--accent-solid);}
.contactsList { display: flex; flex-direction: column; overflow-y: auto; flex: 1; scrollbar-width: thin; scrollbar-color: rgba(var(--accent-rgb, 167, 79, 255), 0.3) transparent;}
.chatWindow { flex: 1; display: flex; flex-direction: column; background: var(--chat-bg, #0f0f13); position: relative;}
.chatWindow::before { content: ''; position: absolute; inset: 0; opacity: var(--chat-pattern, 0); background-color: rgba(var(--accent-rgb), 0.2); mask-image: url("/pattern.svg"); -webkit-mask-image: url("/pattern.svg"); mask-size: 1600px; -webkit-mask-size: 1600px; mask-repeat: repeat; -webkit-mask-repeat: repeat; pointer-events: none; transition: opacity 0.5s ease;}
.topBarArea { overflow: hidden;}
.chatHeader { background: var(--sidebar); padding: var(--density-header-padding, 15px 25px); padding-top: max(15px, env(safe-area-inset-top)); border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; transition: max-height 0.3s cubic-bezier(0.4, 0, 0.2, 1), padding 0.3s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1), border-color 0.3s cubic-bezier(0.4, 0, 0.2, 1); max-height: 200px; opacity: 1;}
.chatHeaderExit { max-height: 0; padding: 0 25px; opacity: 0; overflow: hidden; border-bottom-color: transparent;}
.chatHeaderLeft { display: flex; align-items: center; gap: 12px; flex: 1;}
.headerAvatar { width: 42px; height: 42px; border-radius: 50%; overflow: hidden; display: none;}
.headerAvatar.visible { display: flex; align-items: center; justify-content: center;}
.headerAvatar img { width: 100%; height: 100%; object-fit: cover;}
.chatName { font-weight: 700; font-family: var(--font-heading); letter-spacing: -0.5px; display: flex; align-items: center; white-space: nowrap; overflow: hidden; gap: 4px;}
.chatStatus { font-size: calc(12px * var(--font-size-scale)); color: #888;}
.messageContainer { display: flex; flex-direction: column; padding: var(--density-msg-padding, 20px); flex: 1; overflow-y: auto; overflow-x: hidden; overscroll-behavior-y: contain; scrollbar-width: thin; scrollbar-color: rgba(var(--accent-rgb, 167, 79, 255), 0.3) transparent; touch-action: pan-x pan-y;}
.messagesContent { display: flex; flex-direction: column; width: 100%; gap: var(--density-msg-gap, 8px); min-height: 100%;}
.bottomBar { padding: var(--density-input-padding, 8px 12px); display: flex; align-items: flex-end; gap: var(--density-bottom-gap, 8px); background: var(--sidebar); position: relative; border-top: 1px solid var(--border);}
.inputArea { flex: 1; display: flex; align-items: flex-end; background: var(--card); border: 1px solid var(--border); border-radius: 22px; padding: 2px 4px; position: relative; transition: border-color 0.3s;}
.inputArea:focus-within { border-color: var(--border); box-shadow: none;}
.inputArea.editing { border-color: var(--accent-solid); box-shadow: 0 0 0 2px rgba(var(--accent-rgb, 167, 79, 255), 0.25);}
.fileBtn { padding: 8px 10px; color: #888; background: transparent; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-bottom: 2px; transition: all 0.2s;}
.fileBtn:hover { color: var(--accent-solid); transform: scale(1.1);}
.fileBtn svg { width: 24px; height: 24px; fill: currentColor; transform: rotate(45deg);}
.textareaWrapper { flex: 1; position: relative; display: flex; align-items: center;}
.messageTextarea { width: 100%; padding: 10px 8px 10px 4px; background: transparent; border: none; color: #fff; outline: 0; resize: none; overflow-y: hidden; min-height: 40px; max-height: 150px; box-sizing: border-box; line-height: 20px; font-size: var(--msg-text-size, 15px); font-family: inherit; word-break: break-word; display: block; caret-color: var(--accent-solid);}
.messageTextarea::selection { background: rgba(var(--accent-rgb, 167, 79, 255), 0.3);}
.messageTextarea::-moz-selection { background: rgba(var(--accent-rgb, 167, 79, 255), 0.3);}
.charCounter { position: absolute; right: 8px; top: 50%; transform: translateY(-50%) scale(0.8); background: rgba(var(--accent-rgb, 167, 79, 255), 0.2); color: var(--accent-solid); padding: 4px 10px; border-radius: 15px; font-size: calc(11px * var(--font-size-scale)); font-weight: 600; border: 1px solid rgba(var(--accent-rgb, 167, 79, 255), 0.3); backdrop-filter: blur(10px); opacity: 0; transition: all 0.3s ease; pointer-events: none; z-index: 5;}
.charCounter.visible { opacity: 1;}
.charCounter.warning { color: var(--accent-solid); background: rgba(var(--accent-rgb, 167, 79, 255), 0.2); border-color: rgba(var(--accent-rgb, 167, 79, 255), 0.3);}
.charCounter.danger { color: #ff4444; background: rgba(255, 68, 68, 0.2); border-color: rgba(255, 68, 68, 0.3);}
.mentionList { position: absolute; bottom: calc(100% + 8px); left: 0; right: 0; max-height: 260px; overflow-y: auto; background: var(--bg, #fff); border: 1px solid rgba(var(--accent-rgb, 167, 79, 255), 0.25); border-radius: 14px; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.35); padding: 6px; z-index: 20;}
.mentionItem { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 10px; cursor: pointer;}
.mentionActive { background: rgba(var(--accent-rgb, 167, 79, 255), 0.15);}
.mentionAvatar,.mentionAvatarPlaceholder { width: 32px; height: 32px; border-radius: 50%; object-fit: cover; flex-shrink: 0; background: linear-gradient(135deg, var(--accent-solid), #6a11cb); color: var(--on-accent, #fff); display: flex; align-items: center; justify-content: center; font-weight: 700; font-size: 14px;}
.mentionName { font-size: calc(14px * var(--font-size-scale)); font-weight: 600; color: var(--text, #111); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.mentionUser { font-size: calc(12px * var(--font-size-scale)); color: var(--accent-solid, #9d4edd);}
.emojiBtn { padding: 8px 4px 8px 10px; color: #888; background: transparent; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-bottom: 2px; transition: all 0.2s;}
.emojiBtn:hover { transform: scale(1.1);}
.emojiBtn svg { width: 24px; height: 24px; fill: currentColor; transition: 0.2s;}
.emojiBtnActive { color: var(--accent-solid);}
.emojiBtnActive svg { fill: var(--accent-solid);}
.aiBtn { padding: 8px 10px; color: #888; background: transparent; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; margin-bottom: 2px; margin-right: 2px; transition: all 0.2s;}
.aiBtn:hover { color: var(--accent-solid); transform: scale(1.1);}
.aiBtn svg { width: 24px; height: 24px; fill: currentColor; transition: 0.2s;}
.actionBtn { position: relative; display: flex; align-items: flex-end; margin-bottom: 2px;}
.micSendBtn { width: 40px; height: 40px; border-radius: 50%; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; position: relative; transition: background-color 0.3s ease, color 0.3s ease, transform 0.2s ease; touch-action: none;}
.micMode { background: var(--accent); color: var(--on-accent, #fff);}
.sendMode { background: var(--accent); color: var(--on-accent, #fff);}
.micSendBtn:active { transform: scale(0.9) !important;}
.recordingActive { background: #ff3b30 !important;}
.sendOption { display: flex; align-items: center; gap: 12px; padding: 10px 14px; cursor: pointer; border-radius: 14px; font-size: calc(14px * var(--font-size-scale)); color: #eee; transition: background 0.15s;}
.sendOption:hover { background: rgba(167, 79, 255, 0.15);}
.sendOption svg { width: 20px; height: 20px; flex-shrink: 0;}
.menuClosing { animation: menuPopDown 0.2s ease-in forwards !important; transform: translateZ(0); will-change: transform, opacity;}
.sendSubOption { display: flex; align-items: center; gap: 12px; padding: 10px 14px; cursor: pointer; border-radius: 14px; font-size: calc(14px * var(--font-size-scale)); color: #eee; transition: background 0.15s;}
.sendSubOption:hover { background: rgba(167, 79, 255, 0.15);}
.sendSubOption svg { width: 20px; height: 20px; flex-shrink: 0;}
.micIcon,.sendIcon { position: absolute; display: flex; align-items: center; justify-content: center; transition: transform 0.35s cubic-bezier(0.175, 0.885, 0.32, 1.275), opacity 0.25s ease;}
.micIcon svg,.sendIcon svg { width: 24px; height: 24px; fill: currentColor;}
.sendIcon svg { width: 20px; height: 20px; transform: translateX(2px);}
.micMode .micIcon { transform: scale(1) rotate(0deg); opacity: 1;}
.micMode .sendIcon { transform: scale(0.5) rotate(-60deg); opacity: 0;}
.sendMode .micIcon { transform: scale(0.5) rotate(60deg); opacity: 0;}
.sendMode .sendIcon { transform: scale(1) rotate(0deg); opacity: 1;}
.replyBar { display: flex; align-items: center; gap: 10px; padding: 10px 25px; background: var(--sidebar); border-top: 1px solid var(--border); border-left: 4px solid var(--accent-solid);}
.replyBar.hidden { display: none;}
.replyText { flex: 1; font-size: calc(14px * var(--font-size-scale)); color: #ccc; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.replyClose { background: 0 0; border: none; color: #ff4d4d; cursor: pointer; font-size: calc(16px * var(--font-size-scale));}
.pinnedBar { display: flex; align-items: center; gap: 15px; padding: 10px 20px; background: rgba(18, 18, 26, 0.95); border-bottom: 1px solid rgba(var(--accent-rgb, 167, 79, 255), 0.3); backdrop-filter: blur(15px); position: sticky; top: 0; z-index: 1000; cursor: pointer; width: 100%; box-sizing: border-box;}
.pinnedBar.hidden { display: none;}
.pinnedAccent { width: 3px; height: 32px; background: var(--accent-solid); border-radius: 4px; flex-shrink: 0;}
.pinnedContent { flex: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; gap: 2px;}
.pinnedCounter { font-size: calc(11px * var(--font-size-scale)); color: var(--accent-solid); font-weight: 800; text-transform: uppercase; letter-spacing: 0.5px; white-space: nowrap;}
.pinnedText { font-size: calc(13px * var(--font-size-scale)); color: #eee; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; opacity: 0.8; display: flex; align-items: center; gap: 2px;}
.pinArrow { background: 0 0; border: none; color: #777; cursor: pointer; padding: 2px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; border-radius: 4px; transition: color 0.15s;}
.pinArrow:hover { color: #aaa;}
.pinTextInner { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; flex: 1;}
.pinnedClose { background: 0 0; border: none; color: #555; cursor: pointer; font-size: calc(18px * var(--font-size-scale)); padding: 5px; flex-shrink: 0;}
.pinnedDropdown { position: absolute; top: 100%; left: 0; right: 0; background: rgba(22, 22, 32, 0.98); border-bottom: 1px solid rgba(var(--accent-rgb, 167, 79, 255), 0.35); box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45); max-height: 240px; overflow-y: auto; z-index: 1001; display: flex; flex-direction: column;}
.pinnedDropdownItem { background: 0 0; border: none; border-bottom: 1px solid rgba(255, 255, 255, 0.05); color: #ddd; text-align: left; cursor: pointer; padding: 10px 20px; font-size: calc(13px * var(--font-size-scale)); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: block; width: 100%; box-sizing: border-box;}
.pinnedDropdownItem:hover { background: rgba(255, 255, 255, 0.06);}
.pinnedDropdownItemActive { background: rgba(var(--accent-rgb, 167, 79, 255), 0.15); color: #fff;}
.chatSearchBar { padding: 10px 25px; background: var(--sidebar); border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 8px;}
.chatSearchBar.hidden { display: none;}
.chatSearchInput { width: 100%; background: 0 0; border: none; color: #fff; outline: 0; font-size: calc(14px * var(--font-size-scale));}
.chatSearchNav { display: flex; align-items: center; gap: 4px; flex-shrink: 0;}
.chatSearchNavBtn { background: none; border: none; color: var(--accent-solid); cursor: pointer; padding: 4px; border-radius: 4px; display: flex; align-items: center; justify-content: center;}
.chatSearchNavBtn:disabled { opacity: 0.3; cursor: default;}
.chatSearchCounter { color: #888; font-size: calc(12px * var(--font-size-scale)); min-width: 50px; text-align: center;}
.loadMoreIndicator { text-align: center; padding: 12px; color: #888; font-size: calc(13px * var(--font-size-scale));}
.loadMoreSpinner { width: 20px; height: 20px; border: 2px solid rgba(var(--accent-rgb, 167, 79, 255), 0.2); border-top-color: var(--accent-solid); border-radius: 50%; animation: spin 0.8s linear infinite; margin: 0 auto 8px;}
@keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}
.searchHighlight { background: rgba(var(--accent-rgb, 167, 79, 255), 0.3); border-radius: 2px;}
.dropZone { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(var(--accent-rgb, 167, 79, 255), 0.15); backdrop-filter: blur(8px); z-index: 9999; border: 3px dashed var(--accent-solid); align-items: center; justify-content: center; pointer-events: none; transition: 0.3s;}
.dropZone.active { display: flex;}
.dropZoneContent { text-align: center; color: #fff; background: #13131b; padding: 30px; border-radius: 20px; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);}
.dropZoneIcon { font-size: 50px; margin-bottom: 10px;}
.dropZoneTitle { font-weight: 700; font-size: calc(18px * var(--font-size-scale));}
.dropZoneSub { font-size: calc(12px * var(--font-size-scale)); color: #888; margin-top: 5px;}
.scrollDownWrapper { position: fixed; right: 25px; bottom: 95px; z-index: 99999; display: flex; flex-direction: column; align-items: center; justify-content: center; pointer-events: none; opacity: 0; transform: translateY(16px) scale(0.85); transition: opacity 0.25s ease, transform 0.25s ease; visibility: hidden;}
.scrollDownWrapper.visible { visibility: visible; opacity: 1; transform: translateY(0) scale(1); pointer-events: auto;}
.scrollDownWrapper.visible .scrollDownBtn { animation: scrollBounceIn 0.4s cubic-bezier(0.22, 1, 0.36, 1) both;}
@keyframes scrollBounceIn { 0% { transform: translateY(24px) scale(0.6); opacity: 0; } 50% { transform: translateY(-3px) scale(1.03); } 100% { transform: translateY(0) scale(1); opacity: 1; }}
.scrollDownBtn { width: 50px; height: 50px; border-radius: 50%; background: var(--border); border: 1px solid rgba(var(--accent-rgb, 167, 79, 255), 0.4); color: var(--accent-solid); cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 8px 25px rgba(0, 0, 0, 0.7); backdrop-filter: blur(15px); transition: 0.2s; pointer-events: auto;}
.scrollDownBtn:hover { transform: scale(1.1);}
.scrollDownBtn svg { width: 28px; height: 28px; fill: currentColor;}
.emptyChat { flex: 1; display: flex; align-items: center; justify-content: center; user-select: none;}
.emptyChatInner { display: flex; flex-direction: column; align-items: center; justify-content: center;}
.emptyChatIcon { width: 80px; height: 80px; fill: none; stroke: var(--accent-solid); stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; margin-bottom: 20px; animation: floatEmpty 3s ease-in-out infinite;}
.emptyChatTitle { font-size: calc(18px * var(--font-size-scale)); font-weight: 600; color: #eee; letter-spacing: 0.5px;}
.emptyChatSub { font-size: calc(13px * var(--font-size-scale)); margin-top: 8px; opacity: 0.6;}
@keyframes floatEmpty { 0%, 100% { transform: translateY(0px); } 50% { transform: translateY(-10px); }}
.chatHeaderHidden { display: none;}
.mobileBackBtn { display: none; background: 0 0; border: none; cursor: pointer; padding: 0; margin-right: 5px;}
.mobileBackBtn svg { width: 28px; height: 28px; fill: var(--accent-solid);}
.contextMenu { position: fixed; z-index: 10000; background: rgba(var(--card-rgb, 42, 38, 51), 0.98); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid rgba(255, 255, 255, 0.1); border-radius: 16px; padding: 6px; min-width: 210px; box-shadow: 0 10px 40px rgba(0, 0, 0, 0.7); animation: menuPopUp 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); overflow-y: auto; overscroll-behavior: contain;}
@keyframes menuPopUp { from { opacity: 0; transform: scale(0.8); } to { opacity: 1; transform: scale(1); }}
.contextMenuClosing { animation: menuPopDown 0.2s ease-in forwards !important;}
@keyframes menuPopDown { from { opacity: 1; transform: scale(1); } to { opacity: 0; transform: scale(0.85); }}
.ctxReactions { display: flex; align-items: center; gap: 2px; padding: 10px 14px; border-bottom: 1px solid rgba(255, 255, 255, 0.06);}
.ctxReactionBtn { background: transparent; border: none; font-size: calc(22px * var(--font-size-scale)); padding: 4px 6px; border-radius: 8px; cursor: pointer; transition: background 0.15s, transform 0.15s; line-height: 1; animation: emojiPop 0.3s cubic-bezier(0.34, 1.56, 0.64, 1) backwards;}
.ctxReactionBtn:nth-child(1) { animation-delay: 0s; }.ctxReactionBtn:nth-child(2) { animation-delay: 0.04s; }.ctxReactionBtn:nth-child(3) { animation-delay: 0.08s; }.ctxReactionBtn:nth-child(4) { animation-delay: 0.12s; }.ctxReactionBtn:nth-child(5) { animation-delay: 0.16s; }
.ctxReactionBtn:active { transform: scale(1.3);}
@keyframes emojiPop { 0% { opacity: 0; transform: scale(0); } 60% { transform: scale(1.2); } 100% { opacity: 1; transform: scale(1); }}
.ctxReactionBtn:hover { background: rgba(var(--accent-rgb, 167, 79, 255), 0.15); transform: scale(1.2);}
.ctxDivider { height: 1px; background: rgba(255, 255, 255, 0.08); margin: 4px 6px;}
.ctxMenuItem { display: flex; align-items: center; gap: 12px; padding: 10px 14px; cursor: pointer; color: #eee; font-size: calc(14px * var(--font-size-scale)); font-weight: 500; transition: background 0.15s; border-radius: 10px;}
.ctxMenuItem:hover { background: rgba(var(--accent-rgb, 167, 79, 255), 0.1);}
.ctxMenuIcon { width: 18px; height: 18px; fill: var(--accent-solid); flex-shrink: 0;}
.contextMenuIcon { width: 18px; height: 18px; fill: var(--accent-solid); flex-shrink: 0;}
.ctxMenuDanger { color: #ff4d4d;}
.ctxMenuDangerIcon { fill: #ff4d4d;}
.contextMenuDanger { color: #ff4d4d;}
.contextMenuDangerIcon { fill: #ff4d4d;}
@keyframes dateAppear { from { opacity: 0; transform: scale(0.8) translateY(-10px); } to { opacity: 1; transform: scale(1) translateY(0); }}
@media (max-width: 768px) { .sidebar { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000; transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1); }
.sidebarHidden { transform: translateX(-100%); pointer-events: none; }
.chatWindow { width: 100%; flex: 1; z-index: 500; }
.chatWindow .emptyChat { display: none; }
.mobileBackBtn { display: block; }
.scrollDownWrapper { right: 16px; bottom: 80px; }}
.screenshotFlash { position: fixed; inset: 0; z-index: 2147483647; background: #000; pointer-events: none;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { io, Socket } from 'socket.io-client';
const SOCKET_URL = import.meta.env.VITE_SOCKET_URL ?? 'https://4send-messenger.hf.space';
let socketInstance: Socket | null = null;let pendingToken: string | null = null;
const dispatchSessionExpired = () => { window.dispatchEvent(new CustomEvent('4send:session-expired'));};
const isAuthErrorMessage = (message?: string) => /Authentication error|Banned/i.test(String(message || ''));
export const getSocket = (): Socket => { if (!socketInstance) { const raw = localStorage.getItem('4send_language') || 'en'; const lang = (() => { try { return JSON.parse(raw); } catch { return raw; } })(); socketInstance = io(SOCKET_URL, { auth: { token: pendingToken }, query: { lang }, transports: ['websocket', 'polling'], reconnection: true, reconnectionAttempts: 10, reconnectionDelay: 1000 });
socketInstance.on('session_revoked', () => dispatchSessionExpired());
socketInstance.on('connect_error', (err) => { if (!isAuthErrorMessage(err?.message)) return; if (!pendingToken) return; void (async () => { try { const { resolveToken } = await import('./api'); const current = await resolveToken(); if (current && current === pendingToken) dispatchSessionExpired(); } catch { /* ignore */ } })(); });
void (async () => { try { const { resolveToken } = await import('./api'); const token = await resolveToken(); if (token !== pendingToken) { pendingToken = token; if (socketInstance) { socketInstance.auth = { token }; if (!socketInstance.connected) socketInstance.connect(); } } } catch { /* ignore */ } })(); } return socketInstance;};
export const updateSocketToken = async (): Promise<void> => { const { resolveToken } = await import('./api'); pendingToken = await resolveToken(); if (socketInstance) { socketInstance.auth = { token: pendingToken }; if (socketInstance.connected) { socketInstance.disconnect().connect(); } }};12345678910111213141516171819202122232425262728293031323334353637export interface VideoMessageSettings { camera: 'user' | 'environment'; quality: number; codec: 'mp4' | 'webm'; bitrate: number;}
export const VIDEO_QUALITIES = [720, 480, 360];export const VIDEO_BITRATES = [1500000, 2500000, 4000000];
export const getVideoMessageSettings = (): VideoMessageSettings => { const camera = localStorage.getItem('4send_videoMsg_camera') === 'environment' ? 'environment' : 'user'; const q = parseInt(localStorage.getItem('4send_videoMsg_quality') || '', 10); const quality = VIDEO_QUALITIES.includes(q) ? q : 720; const codec = localStorage.getItem('4send_videoMsg_codec') === 'webm' ? 'webm' : 'mp4'; const b = parseInt(localStorage.getItem('4send_videoMsg_bitrate') || '', 10); const bitrate = VIDEO_BITRATES.includes(b) ? b : 1500000; return { camera, quality, codec, bitrate };};
const STORAGE_KEYS: Record<keyof VideoMessageSettings, string> = { camera: '4send_videoMsg_camera', quality: '4send_videoMsg_quality', codec: '4send_videoMsg_codec', bitrate: '4send_videoMsg_bitrate'};
export const setVideoMessageSetting = <K extends keyof VideoMessageSettings>(key: K, value: VideoMessageSettings[K]): void => { localStorage.setItem(STORAGE_KEYS[key], String(value));};
export const pickVideoMessageMime = (codec: 'mp4' | 'webm'): string => { const supportsMp4 = typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported('video/mp4'); const supportsWebm = typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported('video/webm'); if (codec === 'mp4') return supportsMp4 ? 'video/mp4' : (supportsWebm ? 'video/webm' : 'video/mp4'); return supportsWebm ? 'video/webm' : (supportsMp4 ? 'video/mp4' : 'video/webm');};110 unmodified lines111112113114115116110 unmodified lines{ username: req.user.username },{ $pull: { sessions: { token: req.token } } });res.json({ success: true });} catch {res.status(500).json({ error: 'Error' });110 unmodified lines111112113114115116117110 unmodified lines{ username: req.user.username },{ $pull: { sessions: { token: req.token } } });require('../socket/kick').kickSessions(req.user.username, t => t === req.token);res.json({ success: true });} catch {res.status(500).json({ error: 'Error' });
13 unmodified lines141516171819202122232413 unmodified lines}try {const query = me === target? { chat_id: me, pinner_id: me }: { $or: [{ chat_id: me, pinner_id: target, pin_type: 'both' }, { chat_id: target, pinner_id: me, pin_type: 'both' }, { chat_id: target, pinner_id: me, pin_type: 'me' }] };const pins = await Pin.find(query).sort({ timestamp: -1 }).lean();res.json(pins.map(p => ({ id: p.message_id, text: clarify(p.text_preview) })));} catch { res.status(500).json([]); }});13 unmodified lines141516171819202122232425262728293031323334353637383913 unmodified lines}try {let query;if (me === target) {query = { chat_id: me, pinner_id: me };} else if (target.startsWith('room_')) {query = { chat_id: target, $or: [{ pinner_id: me }, { pin_type: 'both' }] };} else {query = { $or: [{ chat_id: me, pinner_id: target, pin_type: 'both' },{ chat_id: target, pinner_id: me, pin_type: { $in: ['both', 'me', 'self'] } }] };}const pins = await Pin.find(query).sort({ timestamp: -1 }).lean();const seen = new Set();const unique = pins.filter(p => {const id = String(p.message_id);if (seen.has(id)) return false;seen.add(id);return true;});res.json(unique.map(p => ({ id: p.message_id, text: clarify(p.text_preview) })));} catch { res.status(500).json([]); }});
1 unmodified line23456710 unmodified lines181920212223245 unmodified lines3031323334351 unmodified lineconst router = express.Router();const { authenticateToken } = require('../middleware/authenticateToken');const User = require('../models/User');router.get('/api/sessions', authenticateToken, async (req, res) => {try {10 unmodified linesrouter.post('/api/sessions/revoke', authenticateToken, async (req, res) => {try {await User.updateOne({ username: req.user.username }, { $pull: { sessions: { token: req.body.token } } });res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});5 unmodified lines{ username: req.user.username },{ $pull: { sessions: { token: { $ne: currentToken } } } });res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});1 unmodified line234567810 unmodified lines192021222324252627285 unmodified lines343536373839401 unmodified lineconst router = express.Router();const { authenticateToken } = require('../middleware/authenticateToken');const User = require('../models/User');const { kickSessions } = require('../socket/kick');router.get('/api/sessions', authenticateToken, async (req, res) => {try {10 unmodified linesrouter.post('/api/sessions/revoke', authenticateToken, async (req, res) => {try {const token = req.body && req.body.token;if (!token) return res.status(400).json({ error: 'Invalid token' });await User.updateOne({ username: req.user.username }, { $pull: { sessions: { token } } });kickSessions(req.user.username, t => t === token);res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});5 unmodified lines{ username: req.user.username },{ $pull: { sessions: { token: { $ne: currentToken } } } });kickSessions(req.user.username, t => t !== currentToken);res.json({ success: true });} catch { res.status(500).json({ error: 'Error' }); }});
43 unmodified lines44454647484943 unmodified lines}});router.post('/api/notification-repeat', authenticateToken, async (req, res) => {try {const minutes = parseInt(req.body.minutes);43 unmodified lines4445464748495051525354555657585960616243 unmodified lines}});router.get('/api/security-settings', authenticateToken, async (req, res) => {try {const user = await User.findOne({ username: req.user.username }).lean();if (!user) return res.status(404).json({ error: 'Not found' });res.json({autoLogoutDays: user.autoLogoutDays || 7,autoDeleteMonths: user.autoDeleteMonths || 6});} catch (err) {res.status(500).json({ error: "DB Error" });}});router.post('/api/notification-repeat', authenticateToken, async (req, res) => {try {const minutes = parseInt(req.body.minutes);
72 unmodified lines7374757677783 unmodified lines8283848572 unmodified linesif (!global.privacyMap) global.privacyMap = new Map();const loadPrivacyMap = async () => {try {const users = await User.find({ privacy: { $exists: true, $ne: '{}' } }).select('username privacy').lean();3 unmodified lines} catch (err) { logError('privacy_load', err); }};module.exports = { runMigration, loadPrivacyMap };72 unmodified lines7374757677787980818283848586878889909192939495969798991001011021033 unmodified lines10710810911072 unmodified linesif (!global.privacyMap) global.privacyMap = new Map();const dedupPins = async () => {try {const Pin = require('../models/Pin');await Pin.updateMany({ pin_type: 'self' }, { $set: { pin_type: 'me' } });const dupes = await Pin.aggregate([{ $sort: { timestamp: -1 } },{ $group: {_id: { m: '$message_id', c: '$chat_id', p: '$pinner_id' },ids: { $push: '$_id' },n: { $sum: 1 }} },{ $match: { n: { $gt: 1 } } }]);const toDelete = [];for (const d of dupes) toDelete.push(...d.ids.slice(1));for (let i = 0; i < toDelete.length; i += 500) {await Pin.deleteMany({ _id: { $in: toDelete.slice(i, i + 500) } });}await Pin.syncIndexes();} catch (err) {logError('dedup_pins', err);}};const loadPrivacyMap = async () => {try {const users = await User.find({ privacy: { $exists: true, $ne: '{}' } }).select('username privacy').lean();3 unmodified lines} catch (err) { logError('privacy_load', err); }};module.exports = { runMigration, loadPrivacyMap, dedupPins };
59 unmodified lines606162636465666759 unmodified linesio.to(data.target).emit('call_answered', { answer: data.answer });const key = `${caller}_${receiver}`;if (callTimeouts.has(key)) { clearTimeout(callTimeouts.get(key)); callTimeouts.delete(key); }activeCalls.delete(caller);if (data.answer === 'rejected' || data.answer === 'busy') {try {const dialogId = getDialogId(caller, receiver);const ts = new Date();59 unmodified lines606162636465666759 unmodified linesio.to(data.target).emit('call_answered', { answer: data.answer });const key = `${caller}_${receiver}`;if (callTimeouts.has(key)) { clearTimeout(callTimeouts.get(key)); callTimeouts.delete(key); }if (data.answer === 'rejected' || data.answer === 'busy') {activeCalls.delete(caller);try {const dialogId = getDialogId(caller, receiver);const ts = new Date();
6 unmodified lines7891011123 unmodified lines16171819202122232425262728293031323334358 unmodified lines444546474849505152535455565758596061626 unmodified linesconst { broadcastSystemAction } = require('../../services/notification');const { getIO } = require('../io');const handlePinRequest = async (socket, { messageId, chatId, type, textPreview }) => {const pinnerId = socket.username.toLowerCase();const r = chatId.toLowerCase();3 unmodified linesif (!msg) return;const realMsgId = msg._id.toString();if (r.startsWith('room_')) {const room = await Room.findOne({ roomId: r }).lean();if (!room || !room.members.includes(pinnerId)) return;if (room.type === 'channel' && room.owner !== pinnerId) return;}const hiddenPreview = obscure(textPreview);await Pin.create({ message_id: realMsgId, chat_id: r, pinner_id: pinnerId, pin_type: type, text_preview: hiddenPreview, timestamp: new Date() });const io = getIO();const updateData = { messageId: realMsgId, text: textPreview, action: 'add', chatId: r, pinnerId, type };socket.emit('pin_update', updateData);if (type === 'both' && pinnerId !== r) io.to(r).emit('pin_update', { ...updateData, chatId: pinnerId });if (type === 'both') {let preview = textPreview.length > 20 ? textPreview.substring(0, 20) + '...' : textPreview;await broadcastSystemAction(pinnerId, r, `${st('закрепил(а)', detectLang(socket))} «${preview}»`);}8 unmodified linesconst msg = await Message.findOne(query).lean();const realMsgId = msg ? msg._id.toString() : messageId;if (r.startsWith('room_')) {const room = await Room.findOne({ roomId: r }).lean();if (!room || !room.members.includes(pinnerId)) return;if (room.type === 'channel' && room.owner !== pinnerId) return;}const pin = await Pin.findOne({ message_id: realMsgId, chat_id: r }).lean();await Pin.deleteOne({ message_id: realMsgId, chat_id: r });const io = getIO();socket.emit('pin_update', { messageId: realMsgId, action: 'remove', chatId: r });io.to(r).emit('pin_update', { messageId: realMsgId, action: 'remove', chatId: pinnerId });if (pin && pin.pin_type === 'both') {await broadcastSystemAction(pinnerId, r, `${st('открепил(а) сообщение', detectLang(socket))}`);}} catch {}6 unmodified lines78910111213143 unmodified lines18192021222324252627282930313233343536373839404142434445464748498 unmodified lines585960616263646566676869707172737475767778798081828384858687888990916 unmodified linesconst { broadcastSystemAction } = require('../../services/notification');const { getIO } = require('../io');const normalizePinType = (type) => (type === 'both' ? 'both' : 'me');const handlePinRequest = async (socket, { messageId, chatId, type, textPreview }) => {const pinnerId = socket.username.toLowerCase();const r = chatId.toLowerCase();3 unmodified linesif (!msg) return;const realMsgId = msg._id.toString();let room = null;if (r.startsWith('room_')) {room = await Room.findOne({ roomId: r }).lean();if (!room || !room.members.includes(pinnerId)) return;if (room.type === 'channel' && room.owner !== pinnerId) return;}const pinType = normalizePinType(type);const hiddenPreview = obscure(textPreview);await Pin.updateOne({ message_id: realMsgId, chat_id: r, pinner_id: pinnerId },{ $set: { pin_type: pinType, text_preview: hiddenPreview, timestamp: new Date() } },{ upsert: true });const io = getIO();const updateData = { messageId: realMsgId, text: textPreview, action: 'add', chatId: r, pinnerId, type: pinType };socket.emit('pin_update', updateData);if (pinType === 'both' && pinnerId !== r) {if (r.startsWith('room_')) {if (room) room.members.forEach(m => io.to(m).emit('pin_update', updateData));} else {io.to(r).emit('pin_update', { ...updateData, chatId: pinnerId });}}if (pinType === 'both') {let preview = textPreview.length > 20 ? textPreview.substring(0, 20) + '...' : textPreview;await broadcastSystemAction(pinnerId, r, `${st('закрепил(а)', detectLang(socket))} «${preview}»`);}8 unmodified linesconst msg = await Message.findOne(query).lean();const realMsgId = msg ? msg._id.toString() : messageId;let room = null;if (r.startsWith('room_')) {room = await Room.findOne({ roomId: r }).lean();if (!room || !room.members.includes(pinnerId)) return;if (room.type === 'channel' && room.owner !== pinnerId) return;}const docs = await Pin.find({message_id: realMsgId,$or: [{ chat_id: r }, { chat_id: pinnerId }],$and: [{ $or: [{ pinner_id: pinnerId }, { pin_type: { $in: ['both', 'self'] } }] }]}).lean();if (docs.length) {await Pin.deleteMany({ _id: { $in: docs.map(d => d._id) } });}const io = getIO();socket.emit('pin_update', { messageId: realMsgId, action: 'remove', chatId: r });const affectedShared = docs.some(d => d.pin_type === 'both' || d.pin_type === 'self');if (affectedShared) {if (r.startsWith('room_')) {if (room) room.members.forEach(m => io.to(m).emit('pin_update', { messageId: realMsgId, action: 'remove', chatId: r }));} else {io.to(r).emit('pin_update', { messageId: realMsgId, action: 'remove', chatId: pinnerId });}}if (affectedShared) {await broadcastSystemAction(pinnerId, r, `${st('открепил(а) сообщение', detectLang(socket))}`);}} catch {}
16 unmodified lines17181920212210 unmodified lines33343536373816 unmodified linesconst { handleCallRequest, handleCallResponse, handleWebrtcSignal, handleCallEnd, cleanupCallForUser } = require('./handlers/call');const { handleFileOffer, handleFileAnswer, handleFileIceCandidate, handleFileCancel, handleFileComplete } = require('./handlers/fileTransfer');const { handleE2EEInit, handleE2EEAccept } = require('./handlers/e2ee');const initSocket = (server) => {const io = new Server(server, {10 unmodified linesio.on('connection', (socket) => {socket.use(createSocketRateLimiter(socket, sanitizeMongo));socket.on('join', (user) => handleJoin(socket, user));socket.on('toggle_pin', ({ user, contact }) => handleToggleAction(socket, socket.username, contact, 'pin'));socket.on('toggle_archive', ({ me, contact }) => handleToggleAction(socket, socket.username, contact, 'archive'));16 unmodified lines171819202122232410 unmodified lines3536373839404142434445464748495016 unmodified linesconst { handleCallRequest, handleCallResponse, handleWebrtcSignal, handleCallEnd, cleanupCallForUser } = require('./handlers/call');const { handleFileOffer, handleFileAnswer, handleFileIceCandidate, handleFileCancel, handleFileComplete } = require('./handlers/fileTransfer');const { handleE2EEInit, handleE2EEAccept } = require('./handlers/e2ee');const User = require('../models/User');const { shouldUpdateLastActive } = require('../utils/lastActive');const initSocket = (server) => {const io = new Server(server, {10 unmodified linesio.on('connection', (socket) => {socket.use(createSocketRateLimiter(socket, sanitizeMongo));socket.use((packet, nextEvent) => {if (socket.username && socket.authToken && shouldUpdateLastActive(socket.username, socket.authToken)) {User.updateOne({ username: socket.username, "sessions.token": socket.authToken },{ $set: { "sessions.$.lastActive": new Date(), last_seen: new Date() } }).catch(() => {});}nextEvent();});socket.on('join', (user) => handleJoin(socket, user));socket.on('toggle_pin', ({ user, contact }) => handleToggleAction(socket, socket.username, contact, 'pin'));socket.on('toggle_archive', ({ me, contact }) => handleToggleAction(socket, socket.username, contact, 'archive'));
1234567891011121314const { getIO } = require('./io');
const kickSessions = (username, predicate) => { const io = getIO(); if (!io || !username) return; for (const [, s] of io.sockets.sockets) { if (s.username !== username) continue; if (predicate && !predicate(s.authToken)) continue; try { s.emit('session_revoked'); } catch {} setTimeout(() => { try { s.disconnect(true); } catch {} }, 50); }};
module.exports = { kickSessions };index.js+2-1
jobs/autoDeleteUsers.js+3-1
jobs/sessionCleanup.js+10-5
middleware/authenticateToken.js+6-3
models/Pin.js+2-2
public/assets/AvatarCropper-YXBtLMg1.js → public/assets/AvatarCropper-BpVibBmq.jsRenamed+1-1
public/assets/EmojiPanel-C0q3T_JG.js → public/assets/EmojiPanel-BwB33XQa.jsRenamed+1-1
public/assets/EncryptionModal-DVr1yxXX.js → public/assets/EncryptionModal-BOkioGOz.jsRenamed+1-1
public/assets/MessengerPage-BEPX8mwe.js → public/assets/MessengerPage-6Fs5zx2C.jsRenamed
public/assets/MessengerPage-BJOhOjc3.cssDeleted
public/assets/MessengerPage-DuSMdAeg.cssAdded
public/assets/ModalShell-BrGMDJl_.js → public/assets/ModalShell-ClUKyIG2.jsRenamed+1-1
public/assets/index-DY9FqaHJ.jsAdded
public/assets/index-HjRUEDl2.jsDeleted
public/assets/storage-B_75ItAe.js → public/assets/storage-8tFmIq9d.jsRenamed+1-1
public/index.html+1-1
public/package-lock.jsonAdded
public/package.jsonAdded+51
public/pwa-sw.js+1-1
public/src/components/chat/CallOverlay.tsxAdded+528
public/src/components/chat/PinnedBar.tsxAdded+176
public/src/components/chat/VoiceRecorder.module.cssAdded+198
public/src/components/chat/VoiceRecorder.tsxAdded+346
public/src/components/settings/ChatSettingsModal.module.cssAdded+286
public/src/components/settings/ChatSettingsModal.tsxAdded+350
public/src/context/SettingsContext.tsxAdded+856
public/src/pages/MessengerPage.module.cssAdded+1205
public/src/pages/MessengerPage.tsxAdded
public/src/services/socket.tsAdded+68
public/src/utils/videoMessage.tsAdded+37
routes/auth.js+1
routes/pins.js+19-4
routes/sessions.js+6-1
routes/settings.js+13
services/migration.js+26-1
socket/handlers/call.js+1-1
socket/handlers/pin.js+39-10
socket/index.js+12
socket/kick.jsAdded+14