forked from Furumi/furumi-web
Added stat page
This commit is contained in:
1 parent
bcb5d378c8
commit
4141562e33
51 files changed
+2235
-4754
No files matched your search
@@ -0,0 +1,41 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const {test} = require('node:test');
|
||||
const vm = require('node:vm');
|
||||
const template = readFileSync(`${__dirname}/../templates/admin/v2.html`, 'utf8');
|
||||
const script = template.match(/<script>\s*(function adminV2\(\)[\s\S]*?)<\/script>/)[1];
|
||||
function app() {
|
||||
const context = vm.createContext({URLSearchParams, Date}); vm.runInContext(script, context);
|
||||
const a = context.adminV2(); a.icons = () => {}; a.setRoute = () => {}; return a;
|
||||
}
|
||||
test('artist → listeners → user retains artist and period filters', async () => {
|
||||
const a = app(); const urls=[];
|
||||
a.request = async url => { urls.push(new URL(url, 'http://localhost').searchParams); return {}; };
|
||||
a.statisticsFilter.from = '2026-11-01'; a.statisticsHistoryPage = 5;
|
||||
await a.statisticsSelectArtist('Artist & Friends');
|
||||
assert.equal(urls[0].get('kind'), 'users'); assert.equal(urls[0].get('artist'), 'Artist & Friends');
|
||||
assert.equal(urls[0].get('history_page'), '1');
|
||||
await a.statisticsExplore({key:'23', label:'Alice'});
|
||||
assert.equal(urls[1].get('user_id'), '23'); assert.equal(urls[1].get('artist'), 'Artist & Friends');
|
||||
assert.equal(urls[1].get('from'), '2026-11-01');
|
||||
await a.statisticsClearFilter('user_id'); assert.equal(urls[2].get('user_id'), null);
|
||||
assert.equal(urls[2].get('artist'), 'Artist & Friends');
|
||||
});
|
||||
test('latest filters win when earlier requests arrive late', async () => {
|
||||
const a = app(); const responses=[];
|
||||
a.request = () => new Promise(resolve => responses.push(resolve));
|
||||
const first = a.loadStatistics(); const second = a.statisticsSelectArtist('Second');
|
||||
responses[1]({marker:2}); await second; responses[0]({marker:1}); await first;
|
||||
assert.equal(a.statisticsData.marker, 2); assert.equal(a.statisticsLoading, false);
|
||||
});
|
||||
test('errors are shown separately from an empty result', async () => {
|
||||
const a = app(); a.request = async () => {throw new Error('Database unavailable')};
|
||||
await a.loadStatistics(); assert.equal(a.statisticsError, 'Database unavailable'); assert.equal(a.statisticsLoading, false);
|
||||
});
|
||||
test('opening a user starts full history without an earlier artist selection', () => {
|
||||
const a = app(); a.statisticsFilter.artist = 'Previous'; a.statisticsSearch = 'old search'; a.statisticsHistoryKind = 'short'; a.statisticsFilter.source = 'synced'; a.statisticsSetPeriod = () => {};
|
||||
a.openStatistics({id:4, username:'user4'});
|
||||
assert.equal(a.statisticsFilter.user_id, 4); assert.equal(a.statisticsFilter.artist, '');
|
||||
assert.equal(a.statisticsSearch, ''); assert.equal(a.statisticsHistoryKind, 'all'); assert.equal(a.statisticsFilter.source, 'all');
|
||||
assert.equal(a.statisticsPeriod, 'all'); assert.equal(a.activeView, 'statistics'); assert.equal(a.userModalOpen, false);
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// Run only against a fresh disposable instance, with the import agent disabled.
|
||||
const {chromium}=require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const assert=require('node:assert/strict');
|
||||
const {spawnSync}=require('node:child_process');
|
||||
const base=process.env.FURU_TEST_URL || 'http://127.0.0.1:3019';
|
||||
const container=process.env.FURU_TEST_PG_CONTAINER || 'furumi-import-playlist-test-pg';
|
||||
function sql(statement) {
|
||||
const result=spawnSync('docker',['exec','-i',container,'psql','-U','postgres','-d','furumi_import_test','-At','-v','ON_ERROR_STOP=1'],{input:statement,encoding:'utf8'});
|
||||
assert.equal(result.status,0,result.stderr);return result.stdout.trim();
|
||||
}
|
||||
(async()=>{
|
||||
const browser=await chromium.launch({headless:true,executablePath:process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||
try {
|
||||
const context=await browser.newContext({viewport:{width:1440,height:1000}});
|
||||
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
|
||||
await page.goto(base+'/admin/setup');
|
||||
await page.locator('[name=username]').fill('importer');
|
||||
await page.locator('[name=password]').fill('import-test-password');
|
||||
await page.locator('[name=confirm_password]').fill('import-test-password');
|
||||
await page.locator('form button[type=submit]').click();await page.waitForURL('**/admin/v2');
|
||||
await page.goto(base+'/');
|
||||
await page.evaluate(()=>{Alpine.store('torrents').open();Alpine.store('torrents').showSourceTab('files');});
|
||||
await page.locator('#direct-audio-file-input').setInputFiles([
|
||||
{name:'theme.wav',mimeType:'audio/wav',buffer:Buffer.from('test-audio-one')},
|
||||
{name:'credits.wav',mimeType:'audio/wav',buffer:Buffer.from('test-audio-two')},
|
||||
]);
|
||||
await page.locator('#local-target-playlist').selectOption('__new__');
|
||||
await page.getByPlaceholder('New playlist name',{exact:true}).fill('Game Soundtrack');
|
||||
await page.screenshot({path:'/tmp/furumi-import-desktop.png'});
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.screenshot({path:'/tmp/furumi-import-mobile.png'});
|
||||
await page.getByRole('button',{name:'Upload selected files',exact:true}).click();
|
||||
await page.waitForFunction(()=>!Alpine.store('torrents').localFilesUploading && Alpine.store('torrents').localFiles.length===0);
|
||||
const history=await (await context.request.get(base+'/api/player/uploads/local/history')).json();
|
||||
assert.equal(history.length,2,JSON.stringify(history));
|
||||
const target=history[0].target_playlist_id;assert.ok(target>0);assert.equal(history[1].target_playlist_id,target);
|
||||
assert.equal(sql('SELECT count(*) FROM furumusic__import_playlist_target;'),'2');
|
||||
// Simulate the importer resolving both uploaded files to library tracks.
|
||||
sql(`INSERT INTO furumusic__media_file (file_type,file_path,original_filename,mime_type,file_size_bytes,sha256_hash,created_at)
|
||||
SELECT 'audio',input_path,input_path,'audio/wav',14,source_sha256,'2026-11-12T00:00:00Z' FROM furumusic__import_playlist_target;
|
||||
INSERT INTO furumusic__track (title,title_sort,release_id,duration_seconds,audio_file_id,is_hidden,created_at,updated_at)
|
||||
SELECT original_filename,original_filename,0,120,id,false,'2026-11-12T00:00:00Z','2026-11-12T00:00:00Z' FROM furumusic__media_file;`);
|
||||
assert.equal((await context.request.get(base+'/api/player/uploads/local/history')).status(),200);
|
||||
assert.equal(sql(`SELECT count(*) FROM furumusic__playlist_track WHERE playlist_id=${target};`),'2');
|
||||
await context.request.get(base+'/api/player/uploads/local/history');
|
||||
assert.equal(sql(`SELECT count(*) FROM furumusic__playlist_track WHERE playlist_id=${target};`),'2');
|
||||
const invalid=await context.request.post(base+'/api/player/uploads/local',{headers:{'X-Furumusic-Target-Playlist-Id':'99999','X-Furumusic-Filename':'bad.wav'},data:Buffer.from('bad')});
|
||||
assert.equal(invalid.status(),400);
|
||||
// Render the torrent picker with a local preview fixture; no external torrent network.
|
||||
await page.setViewportSize({width:1440,height:1000});
|
||||
await page.evaluate(()=>{
|
||||
const s=Alpine.store('torrents');s.showSourceTab('torrents');s._stopRefresh();s._stopPoll();
|
||||
s._applySession({job:{id:'preview-test',name:'Movie OST',status:'preview'},preview:{id:'preview-test',name:'Movie OST',total_size:20,files:[{index:0,name:'theme.flac',components:['theme.flac'],length:20,selected:true}]},selected_files:[0]});
|
||||
});
|
||||
await page.locator('#torrent-target-playlist').selectOption(String(target));
|
||||
assert.equal(await page.evaluate(()=>Alpine.store('torrents').torrentPlaylistChoice),String(target));
|
||||
await page.screenshot({path:'/tmp/furumi-torrent-playlist.png'});
|
||||
await page.evaluate(()=>{Alpine.store('torrents').currentJob.status='paused';});
|
||||
assert.equal(await page.locator('#torrent-target-playlist').isDisabled(),true);
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: file batch → new playlist, persistent destinations, imported tracks, idempotency, invalid destination, torrent picker, desktop/mobile');
|
||||
} finally {await browser.close();}
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,89 @@
|
||||
// Run against a fresh disposable instance and the named disposable PostgreSQL container.
|
||||
// PLAYWRIGHT_MODULE may point to an existing Playwright installation.
|
||||
const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const assert = require('node:assert/strict');
|
||||
const {spawnSync} = require('node:child_process');
|
||||
const base = process.env.FURU_TEST_URL || 'http://127.0.0.1:3018';
|
||||
(async () => {
|
||||
const browser = await chromium.launch({headless:true, executablePath:process.env.CHROME_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'});
|
||||
try {
|
||||
const context = await browser.newContext({viewport:{width:1440,height:1100}, ignoreHTTPSErrors:true});
|
||||
const page = await context.newPage(); const errors=[];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const anonymous = await context.request.get(`${base}/admin/v2/api/statistics`);
|
||||
assert.equal(anonymous.status(),401);
|
||||
await page.goto(`${base}/admin/setup`);
|
||||
await page.getByLabel('Username', {exact:true}).fill('alice');
|
||||
await page.getByLabel('Password', {exact:true}).fill('statistics-test-password');
|
||||
await page.locator('[name=confirm_password]').fill('statistics-test-password');
|
||||
await page.locator('form button[type=submit]').click();
|
||||
await page.waitForURL('**/admin/v2');
|
||||
await page.getByRole('button', {name:'Users',exact:true}).click();
|
||||
await page.getByRole('button', {name:'Add user',exact:true}).click();
|
||||
const editor = page.locator('.modal-backdrop').filter({has:page.getByRole('button',{name:'Save user',exact:true})});
|
||||
await editor.getByLabel('username', {exact:true}).fill('bob');
|
||||
await editor.getByLabel('password', {exact:true}).fill('statistics-test-password');
|
||||
await editor.getByRole('button',{name:'Save user',exact:true}).click();
|
||||
await editor.waitFor({state:'hidden'});
|
||||
const sql = `INSERT INTO furumusic__listen_event
|
||||
(user_id,listen_id,content_id,local_track_id,origin_device_id,started_at_ms,listened_ms,track_duration_ms,ended_reason,qualified,metadata_json,created_at)
|
||||
SELECT 1,'ui-'||n,'content-one',NULL,'web-a',1793491200000+n*1000,180000,180000,'"finished"',true,
|
||||
'{"title":"First song","artist_names":["Artist A"],"release_title":"Album"}'::jsonb,'2026-11-01T00:00:00Z' FROM generate_series(1,30) n;
|
||||
INSERT INTO furumusic__listen_event
|
||||
(user_id,listen_id,content_id,local_track_id,origin_device_id,started_at_ms,listened_ms,track_duration_ms,ended_reason,qualified,metadata_json,created_at)
|
||||
VALUES (2,'ui-bob','content-one',NULL,'web-b',1793664000000,90000,180000,'"skipped"',true,
|
||||
'{"title":"First song","artist_names":["Artist A"],"release_title":"Album"}','2026-11-03T00:00:00Z');`;
|
||||
const seeded = spawnSync('docker',['exec','-i','furumi-statistics-test-pg','psql','-U','postgres','-d','furumi_statistics_test','-v','ON_ERROR_STOP=1'],{input:sql, encoding:'utf8'});
|
||||
assert.equal(seeded.status,0,seeded.stderr);
|
||||
await page.getByRole('button',{name:'Statistics',exact:true}).click();
|
||||
const area = page.locator('.content').filter({has:page.getByText('Listening statistics',{exact:true})});
|
||||
await area.getByRole('button',{name:'Artist A',exact:true}).first().waitFor();
|
||||
const artistResponse = page.waitForResponse(r => r.url().includes('/api/statistics?') && r.url().includes('artist=Artist+A'));
|
||||
await area.getByRole('button',{name:'Artist A',exact:true}).first().click();
|
||||
assert.equal((await artistResponse).status(),200);
|
||||
await area.getByRole('button',{name:'bob',exact:true}).first().waitFor();
|
||||
const bobResponse = page.waitForResponse(r => r.url().includes('/api/statistics?') && r.url().includes('user_id=2'));
|
||||
await area.getByRole('button',{name:'bob',exact:true}).first().click();
|
||||
const bob = await (await bobResponse).json();
|
||||
assert.equal(bob.summary.plays,1); assert.equal(bob.history.items[0].user_name,'bob');
|
||||
assert.equal(bob.history.items[0].title,'First song');
|
||||
const cleared = page.waitForResponse(r => r.url().includes('/api/statistics?') && !r.url().includes('user_id=') && !r.url().includes('artist='));
|
||||
await area.getByRole('button',{name:'All listeners and music'}).click();
|
||||
await cleared;
|
||||
await area.getByText('Loading statistics…',{exact:true}).waitFor({state:'hidden'});
|
||||
await page.screenshot({path:'/tmp/furumi-statistics-desktop.png',fullPage:false});
|
||||
await page.setViewportSize({width:390,height:844});
|
||||
await page.screenshot({path:'/tmp/furumi-statistics-mobile.png',fullPage:false});
|
||||
await page.setViewportSize({width:1440,height:1100});
|
||||
const usersResponse = await context.request.get(`${base}/admin/v2/api/users`); const users = await usersResponse.json();
|
||||
assert.equal(users.items.find(u=>u.username==='bob').plays,1);
|
||||
const detailResponse = await context.request.get(`${base}/admin/v2/api/users/2`); const detail = await detailResponse.json();
|
||||
assert.equal(detail.stats.plays,1); assert.equal(detail.recent_plays[0].title,'First song');
|
||||
const next = await context.request.get(`${base}/admin/v2/api/statistics?from=all&history_page=2`);
|
||||
assert.equal((await next.json()).history.items.length,6);
|
||||
for (const path of ['/admin/debug','/admin/users','/admin/settings','/admin/artists','/admin/reviews','/admin/jobs']) {
|
||||
assert.equal((await context.request.get(base+path)).status(),404,path);
|
||||
}
|
||||
assert.equal((await context.request.get(`${base}/admin/v2/api/statistics?from=invalid`)).status(),400);
|
||||
const jobs = await (await context.request.get(`${base}/admin/v2/api/jobs`)).json();
|
||||
const job = jobs.find(j => j.name === 'metadata_backfill');
|
||||
if (job.enabled) assert.equal((await context.request.post(`${base}/admin/v2/api/jobs/${job.name}/toggle`)).status(),200);
|
||||
assert.equal((await context.request.post(`${base}/admin/v2/api/jobs/${job.name}/schedule`,{data:{cron:'0 17 3 * * *'}})).status(),200);
|
||||
await context.request.get(`${base}/admin/v2/api/dashboard`);
|
||||
const changedJob = (await (await context.request.get(`${base}/admin/v2/api/jobs`)).json()).find(j=>j.name===job.name);
|
||||
assert.equal(changedJob.enabled,false); assert.equal(changedJob.cron_expression,'0 17 3 * * *');
|
||||
const ownDelete = await context.request.post(`${base}/admin/v2/api/users/manage`, {data:{action:'delete',id:1}});
|
||||
assert.equal(ownDelete.status(),400);
|
||||
const listenerContext = await browser.newContext({ignoreHTTPSErrors:true});
|
||||
const login = await listenerContext.newPage();
|
||||
await login.goto(`${base}/login`);
|
||||
await login.locator('[name=username]').fill('bob');
|
||||
await login.locator('[name=password]').fill('statistics-test-password');
|
||||
await login.locator('form button[type=submit]').click();
|
||||
await login.waitForURL(base + '/');
|
||||
assert.equal((await listenerContext.request.get(`${base}/admin/v2/api/statistics`)).status(),403);
|
||||
await listenerContext.close();
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: setup, user creation, artist → listeners → user history, counts, pagination, invalid filters, v1 removal, desktop/mobile rendering');
|
||||
} finally { await browser.close(); }
|
||||
})().catch(error => {console.error(error); process.exitCode=1});
|
||||
@@ -0,0 +1,75 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const {test} = require('node:test');
|
||||
const vm = require('node:vm');
|
||||
const {randomUUID} = require('node:crypto');
|
||||
const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
|
||||
function downloads(fetchImpl) {
|
||||
let code = template.slice(template.indexOf(" Alpine.store('torrents', {"), template.indexOf(" Alpine.store('playlists', {"));
|
||||
code = code.replace(/\{\{[^}]+\}\}/g,'true').replace(/sourceTab: .*?,\n/,"sourceTab: 'files',\n");
|
||||
const stores={playlists:{list:[{id:10,title:'Mine',kind:'user',is_own:true},{id:20,title:'Other',kind:'user',is_own:false}],reload:async()=>{}}};
|
||||
const requests=[];
|
||||
class XHR {
|
||||
headers={}; upload={}; status=200; responseText='{}';
|
||||
open(method,url) {this.url=url;}
|
||||
setRequestHeader(key,value) {this.headers[key]=value;}
|
||||
send(file) {requests.push({file,headers:this.headers});this.onload();}
|
||||
}
|
||||
const context=vm.createContext({Alpine:{store:(name,value)=>value?(stores[name]=value):stores[name]},fetch:fetchImpl,
|
||||
T:new Proxy({}, {get:(_,key)=>key}),crypto:{randomUUID},XMLHttpRequest:XHR,redirectOnUnauthorized:()=>{},console,setInterval:()=>0,clearInterval:()=>{}});
|
||||
vm.runInContext(code,context);
|
||||
const store=stores.torrents;
|
||||
store._poll=()=>{};store.loadSessions=async()=>{};store.loadAgentStatus=async()=>{};store.loadLocalUploadHistory=async()=>{};
|
||||
return {store,requests};
|
||||
}
|
||||
test('destinations are independent, owned playlists only, new titles required',()=>{
|
||||
const {store:s}=downloads();
|
||||
assert.deepEqual(Array.from(s.youtubeOwnedPlaylists(),p=>p.id),[10]);
|
||||
s.localPlaylistChoice='__new__';assert.equal(s.importDestinationValid('local'),false);
|
||||
assert.equal(s.importDestinationValid('torrent'),true);
|
||||
s.localFiles=[{name:'song.flac',webkitRelativePath:'Soundtrack/song.flac'}];s.importPlaylistChoiceChanged('local');
|
||||
assert.equal(s.localNewPlaylistTitle,'Soundtrack');assert.equal(s.importDestinationValid('local'),true);
|
||||
});
|
||||
test('failed torrent starts reuse the newly created playlist and send only selected files',async()=>{
|
||||
const calls=[];
|
||||
const {store:s}=downloads(async(url,opts)=>{
|
||||
calls.push({url,data:JSON.parse(opts.body)});
|
||||
return url==='/api/player/playlists'?{ok:true,json:async()=>({id:33,title:'Soundtrack',kind:'user',is_own:true})}:{ok:false,json:async()=>({error:'retry'})};
|
||||
});
|
||||
s.previewData={id:'torrent-1'};s.selected=new Set([1,3]);s.torrentPlaylistChoice='__new__';s.torrentNewPlaylistTitle='Soundtrack';
|
||||
await s.start();await s.start();
|
||||
assert.equal(calls.filter(c=>c.url==='/api/player/playlists').length,1);
|
||||
assert.deepEqual(calls[1].data,{selected_files:[1,3],target_playlist_id:33});
|
||||
assert.deepEqual(calls[2].data,calls[1].data);assert.equal(s.loading,false);
|
||||
});
|
||||
test('local files carry the same playlist destination and retries retain upload IDs',async()=>{
|
||||
const {store:s,requests}=downloads();const f={name:'a.flac',size:10};
|
||||
s.setLocalFiles([f]);s.localTargetPlaylistId=10;
|
||||
await s.uploadLocalFile(f,0,10);await s.uploadLocalFile(f,0,10);
|
||||
assert.equal(requests[0].headers['X-Furumusic-Target-Playlist-Id'],'10');
|
||||
assert.equal(requests[0].headers['X-Furumusic-Upload-Id'],requests[1].headers['X-Furumusic-Upload-Id']);
|
||||
s.clearLocalFiles();s.setLocalFiles([f]);await s.uploadLocalFile(f,0,10);
|
||||
assert.equal(requests[2].headers['X-Furumusic-Target-Playlist-Id'],undefined);
|
||||
});
|
||||
test('partially failed batches keep their destination, create one playlist and retry remaining files',async()=>{
|
||||
let creates=0;let attempts=0;
|
||||
const {store:s}=downloads(async(url)=>{
|
||||
if(url==='/api/player/playlists') {creates++;return {ok:true,json:async()=>({id:44})};}
|
||||
return {ok:true};
|
||||
});
|
||||
s.setLocalFiles([{name:'a.mp3',size:1},{name:'b.mp3',size:1}]);s.localPlaylistChoice='__new__';s.localNewPlaylistTitle='OST';
|
||||
s.uploadLocalFile=async()=>{attempts++;if(attempts===2)throw Error('offline');return {};};
|
||||
await s.uploadLocalFiles();assert.equal(s.localFiles.length,1);assert.equal(s.localPlaylistLocked,true);
|
||||
assert.equal(s.localTargetPlaylistId,44);await s.uploadLocalFiles();
|
||||
assert.equal(creates,1);assert.equal(s.localFiles.length,0);assert.equal(s.localFilesUploading,false);
|
||||
});
|
||||
test('playlist creation failure leaves the batch editable and does not signal upload completion',async()=>{
|
||||
const calls=[];const {store:s}=downloads(async(url)=>{calls.push(url);return {ok:false,json:async()=>({error:'failed'})};});
|
||||
s.setLocalFiles([{name:'a.mp3',size:1}]);s.localPlaylistChoice='__new__';s.localNewPlaylistTitle='OST';
|
||||
await s.uploadLocalFiles();assert.equal(s.localPlaylistLocked,false);assert.equal(s.localFilesUploading,false);
|
||||
assert.deepEqual(calls,['/api/player/playlists']);assert.equal(s.localFiles.length,1);
|
||||
});
|
||||
test('torrent destination locks after start',()=>{
|
||||
const {store:s}=downloads();s.currentJob={status:'preview'};assert.equal(s.torrentDestinationLocked(),false);
|
||||
s.currentJob.status='paused';assert.equal(s.torrentDestinationLocked(),true);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
const assert = require('node:assert/strict');
|
||||
const {readFileSync} = require('node:fs');
|
||||
const {test} = require('node:test');
|
||||
const vm = require('node:vm');
|
||||
const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
|
||||
function player(fetchImpl = async () => ({ok:true}), beacon = () => true) {
|
||||
// Exercise the production methods with audio and network stubs.
|
||||
const methods = template.slice(template.indexOf(' _recordHistory(endedReason'), template.indexOf(' _sendNowPlaying()'));
|
||||
const audio = {currentTime:60};
|
||||
const context = vm.createContext({audio, fetch:fetchImpl, navigator:{sendBeacon:beacon}, Blob,
|
||||
globalThis:{crypto:{randomUUID:()=> 'uuid'}}, setTimeout: fn => { fn(); }, console});
|
||||
vm.runInContext('this.methods = {' + methods + '};', context);
|
||||
return Object.assign(context.methods, {
|
||||
currentTrack:{id:8,duration_seconds:180}, _historyTrack:{id:8,duration_seconds:180},
|
||||
_localSourceTrackId:8, _listenId:'event1', _playbackStartedAt:123456,
|
||||
_historyRecorded:false, _listenedSeconds:60, _lastAudioTime:60, isPlaying:true,
|
||||
});
|
||||
}
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve));
|
||||
test('switching tracks records short sessions, and completion is not counted twice', async () => {
|
||||
const calls=[]; const p=player(async (_url, options)=> {calls.push(JSON.parse(options.body)); return {ok:true};});
|
||||
p._listenedSeconds=8; p._recordHistory('replaced'); await flush();
|
||||
assert.equal(calls[0].duration_listened,8); assert.equal(calls[0].ended_reason,'replaced');
|
||||
p._recordHistory('skipped'); await flush(); assert.equal(calls.length,1);
|
||||
});
|
||||
test('natural finish records final duration; seeking does not create listened time', async () => {
|
||||
const calls=[]; const p=player(async (_url, options)=> {calls.push(JSON.parse(options.body)); return {ok:true};});
|
||||
p._listenedSeconds=179.4; p._recordHistory('finished'); await flush();
|
||||
assert.equal(calls[0].duration_listened,180); assert.equal(calls[0].completed,true);
|
||||
p._listenedSeconds=0; assert.equal(p._historyListenedSeconds(false),0);
|
||||
});
|
||||
test('failed submission retries the original event even after track changes', async () => {
|
||||
const calls=[]; const p=player(async (_url,options)=> {calls.push(JSON.parse(options.body)); return {ok:calls.length>1,status:503};});
|
||||
p._recordHistory('skipped'); p.currentTrack={id:9}; p._listenId='event2';
|
||||
await flush(); assert.equal(calls.length,2); assert.deepEqual(calls[0], calls[1]);
|
||||
assert.equal(calls[0].track_id,8);
|
||||
});
|
||||
test('page exit uses beacon and does not duplicate a recorded event', () => {
|
||||
const calls=[]; const p=player(()=>assert.fail('unexpected fetch'), (url,blob)=>{calls.push({url,blob});return true;});
|
||||
p._recordHistory('stopped',true); p._recordHistory('stopped',true);
|
||||
assert.equal(calls.length,1); assert.equal(calls[0].url,'/api/player/history');
|
||||
});
|
||||
test('remote UI updates cannot attribute local audio to the wrong track', async () => {
|
||||
let body; const p=player(async (_url,options)=> {body=JSON.parse(options.body);return {ok:true}});
|
||||
p.currentTrack={id:999}; p._recordHistory('replaced'); await flush(); assert.equal(body.track_id,8);
|
||||
});
|
||||
test('unstarted tracks and sub-five-second interrupted sessions are not recorded', async () => {
|
||||
const p=player(()=>assert.fail('unexpected fetch'));
|
||||
p._playbackStartedAt=null; p._recordHistory('finished');
|
||||
p._playbackStartedAt=123; p._listenedSeconds=4; p._recordHistory('skipped'); await flush();
|
||||
assert.equal(p._historyRecorded,false);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
CREATE TEMP TABLE furumusic__user (id bigint PRIMARY KEY, username text, display_name text);
|
||||
CREATE TEMP TABLE furumusic__fed_device_identity (user_id bigint PRIMARY KEY, device_id text);
|
||||
CREATE TEMP TABLE furumusic__fed_device (user_id bigint, device_id text, name text, PRIMARY KEY(user_id, device_id));
|
||||
CREATE TEMP TABLE furumusic__listen_event (
|
||||
user_id bigint, listen_id text, content_id text, local_track_id bigint, origin_device_id text,
|
||||
started_at_ms bigint, listened_ms bigint, track_duration_ms bigint, ended_reason text,
|
||||
qualified boolean, metadata_json jsonb, PRIMARY KEY(user_id, listen_id)
|
||||
);
|
||||
CREATE TEMP TABLE furumusic__track (id bigint);
|
||||
CREATE TEMP TABLE furumusic__release (id bigint);
|
||||
CREATE TEMP TABLE furumusic__artist (id bigint);
|
||||
CREATE TEMP TABLE furumusic__playlist (id bigint);
|
||||
CREATE TEMP TABLE furumusic__media_file (file_size_bytes bigint, audio_format text, file_type text);
|
||||
CREATE TEMP TABLE furumusic__pending_review (status text);
|
||||
CREATE TEMP TABLE furumusic__job_run (status text);
|
||||
CREATE TEMP TABLE furumusic__lastfm_scrobble_outbox (status text);
|
||||
INSERT INTO furumusic__user VALUES (1, 'alice', 'Alice'), (2, 'bob', 'Bob'), (3, 'silent', NULL);
|
||||
INSERT INTO furumusic__fed_device_identity VALUES (1, 'web-a'), (2, 'web-b');
|
||||
INSERT INTO furumusic__fed_device VALUES (1, 'phone', 'Alice phone');
|
||||
INSERT INTO furumusic__listen_event
|
||||
SELECT 1, 'listen-' || n, 'content-one', NULL, 'web-a',
|
||||
1793491200000 + n * 1000, 180000, 180000, '"finished"', true,
|
||||
'{"title":"First song", "artist_names":["Artist A"], "featured_artist_names":["Artist A", "Guest"], "release_title":"Album"}'::jsonb
|
||||
FROM generate_series(1, 30) n;
|
||||
INSERT INTO furumusic__listen_event VALUES
|
||||
(2, 'listen-1', 'content-one', NULL, 'web-b', 1793664000000, 90000, 180000, '"skipped"', true,
|
||||
'{"title":"First song", "artist_names":["Artist A"], "release_title":"Album"}'),
|
||||
(1, 'phone-1', 'content-two', NULL, 'phone', 1793664001000, 120000, 240000, '"replaced"', true,
|
||||
'{"title":"Remote song", "artist_names":["Artist B"], "release_title":"Remote album"}'),
|
||||
(2, 'short-1', 'content-one', NULL, 'web-b', 1793664002000, 8000, 180000, '"skipped"', false,
|
||||
'{"title":"First song", "artist_names":["Artist A"]}');
|
||||
Reference in new issue
Block a user