increment views

This commit is contained in:
2025-08-29 15:03:42 +02:00
parent 1d57c64ce5
commit 96641cf4be
2 changed files with 58 additions and 16 deletions
+44
View File
@@ -16,6 +16,7 @@ import Slider from "../../components/Slider";
import firebase, {
arrayRemove,
arrayUnion,
increment,
projectsRef,
usersRef,
} from "../../config/firebase";
@@ -25,6 +26,9 @@ import { Palette } from "../../styles";
import { FONT_FAMILY } from "../../styles/Fonts";
import Style, { gutters, size } from "../../styles/Style";
// 20 secondes
const timeBeforeIncrement = 20000;
const MusicDetails = () => {
const params = useRoute().params || {};
const action = params?.action;
@@ -34,6 +38,9 @@ const MusicDetails = () => {
const [isPlaying, setIsPlaying] = useState(false);
const [progressInfo, setProgressInfo] = useState({ pos: 0, dur: 0 });
const wasPlayingBeforeSeek = React.useRef(false);
const listenedMsRef = React.useRef(0);
const incrementDoneRef = React.useRef(false);
const timerRef = React.useRef(null);
const { data: project } = useDataFromRef({
ref: projectId
@@ -82,6 +89,9 @@ const MusicDetails = () => {
soundRef.current.setOnPlaybackStatusUpdate(null);
soundRef.current = null;
}
// Reset listen tracking per song load
listenedMsRef.current = 0;
incrementDoneRef.current = false;
if (!songUrl) return;
const { sound } = await Audio.Sound.createAsync(
{ uri: songUrl },
@@ -115,6 +125,40 @@ const MusicDetails = () => {
};
}, [songUrl]);
// Start/stop a timer to accumulate listened milliseconds while playing
useEffect(() => {
const clearTimer = () => {
if (timerRef.current) {
global.clearInterval(timerRef.current);
timerRef.current = null;
}
};
if (isPlaying && projectId) {
if (!timerRef.current) {
timerRef.current = global.setInterval(async () => {
try {
listenedMsRef.current += 500;
if (
!incrementDoneRef.current &&
listenedMsRef.current >= timeBeforeIncrement &&
projectId
) {
incrementDoneRef.current = true;
await projectsRef
.doc(projectId)
.set({ views: increment(1) }, { merge: true });
}
} catch (e) {
// Silent fail for counter
}
}, 500);
}
} else {
clearTimer();
}
return clearTimer;
}, [isPlaying, projectId]);
const fmt = (ms) => {
const total = Math.max(0, Math.floor((ms || 0) / 1000));
const m = Math.floor(total / 60)