| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import { defineStore } from "pinia";
- import { ref } from "vue";
- import { getCurrentUser } from "@/lib/api";
- export const useAuthStore = defineStore("auth", () => {
- const user = ref<any>(null);
- const isLoading = ref(true);
- const showCompleteProfile = ref(false);
- let initialized = false;
- async function refreshUser() {
- try {
- const userData = await getCurrentUser();
- user.value = userData;
- showCompleteProfile.value = !!(
- userData && (!userData.phone || !userData.shipping_address)
- );
- } catch {
- user.value = null;
- showCompleteProfile.value = false;
- stopPing();
- } finally {
- isLoading.value = false;
- if (user.value && !pingInterval) startPing();
- }
- }
- let pingInterval: number | null = null;
- const unreadMessagesCount = ref(0);
- function playNotificationSound() {
- try {
- const AudioCtx = window.AudioContext || (window as any).webkitAudioContext;
- if (!AudioCtx) return;
- const ctx = new AudioCtx();
- const osc = ctx.createOscillator();
- const gainNode = ctx.createGain();
-
- osc.type = 'sine';
- osc.frequency.setValueAtTime(880, ctx.currentTime); // A5
- osc.frequency.exponentialRampToValueAtTime(1760, ctx.currentTime + 0.1); // Up to A6
-
- gainNode.gain.setValueAtTime(0, ctx.currentTime);
- gainNode.gain.linearRampToValueAtTime(0.1, ctx.currentTime + 0.05);
- gainNode.gain.linearRampToValueAtTime(0, ctx.currentTime + 0.2);
-
- osc.connect(gainNode);
- gainNode.connect(ctx.destination);
- osc.start();
- osc.stop(ctx.currentTime + 0.2);
- } catch (e) {
- console.warn("Audio disabled or not supported", e);
- }
- }
- function startPing() {
- import("@/lib/api").then(({ authPing }) => {
- const doPing = async () => {
- const res = await authPing();
- if (res && res.unread_count !== undefined) {
- if (res.unread_count > unreadMessagesCount.value) {
- playNotificationSound();
- }
- unreadMessagesCount.value = res.unread_count;
- }
- };
- doPing(); // ping immediately
- pingInterval = window.setInterval(doPing, 30000);
- });
- }
- function stopPing() {
- if (pingInterval) {
- clearInterval(pingInterval);
- pingInterval = null;
- }
- }
- function init() {
- if (!initialized) {
- initialized = true;
- refreshUser();
- }
- }
- function setUser(u: any) {
- user.value = u;
- }
- function onProfileComplete() {
- showCompleteProfile.value = false;
- refreshUser();
- }
- async function logout() {
- import("@/lib/api").then(async ({ logoutUser }) => {
- await logoutUser();
- localStorage.removeItem("token");
- user.value = null;
- unreadMessagesCount.value = 0;
- stopPing();
- });
- }
- return {
- user,
- isLoading,
- showCompleteProfile,
- unreadMessagesCount,
- init,
- setUser,
- refreshUser,
- onProfileComplete,
- logout,
- };
- });
|