├── .nvmrc ├── data └── .gitkeep ├── .gitignore ├── .github └── workflows │ ├── release.yml │ ├── pr-tests.yml │ └── validate-pull-request-title.yml ├── package.json ├── release.config.mjs ├── biome.json ├── lib ├── helpers.js ├── Database.js └── MBNDSynchronizer.js ├── test ├── findBestMatch.test.js ├── isDateAfter.test.js └── Database.test.js ├── index.js ├── CHANGELOG.md ├── README.md └── LICENCE /.nvmrc: -------------------------------------------------------------------------------- 1 | 22 -------------------------------------------------------------------------------- /data/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /data/* 2 | !/data/.gitkeep 3 | .idea/ 4 | /node_modules/ 5 | TODO.md 6 | /musicbee-navidrome-sync.exe 7 | /dist/ 8 | /.dist/ 9 | /MusicBee_Export.csv 10 | /navidrome.db 11 | /backups/ 12 | index.cjs -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | 7 | jobs: 8 | release: 9 | name: Release 10 | runs-on: windows-latest 11 | 12 | steps: 13 | - name: Checkout 14 | uses: actions/checkout@v4 15 | 16 | - name: Setup Node.js 17 | uses: actions/setup-node@v4 18 | with: 19 | node-version-file: 'package.json' 20 | 21 | - name: Install dependencies 22 | run: npm ci --include=dev 23 | 24 | - name: Tests 25 | run: npm run test 26 | 27 | - name: Release 28 | env: 29 | GH_TOKEN: ${{ secrets.GH_TOKEN }} 30 | run: npx semantic-release 31 | 32 | -------------------------------------------------------------------------------- /.github/workflows/pr-tests.yml: -------------------------------------------------------------------------------- 1 | name: 'PR Tests' 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - edited 8 | - synchronize 9 | - reopened 10 | - ready_for_review 11 | 12 | jobs: 13 | tests: 14 | name: Run app tests 15 | runs-on: ubuntu-latest 16 | if: github.event.pull_request.draft == false 17 | 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v4 21 | 22 | - name: Setup Node.js 23 | uses: actions/setup-node@v4 24 | with: 25 | node-version-file: 'package.json' 26 | 27 | - name: Install dependencies 28 | run: npm ci 29 | 30 | - name: Tests 31 | run: npm run test 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "musicbee-navidrome-sync", 3 | "version": "1.5.0", 4 | "description": "sync ratings and playcount from musicbee db to navidrome db", 5 | "type": "module", 6 | "main": "index.js", 7 | "scripts": { 8 | "fullSync": "NODE_NO_WARNINGS=1 node index.js fullSync", 9 | "albumsSync": "NODE_NO_WARNINGS=1 node index.js albumsSync", 10 | "artistsSync": "NODE_NO_WARNINGS=1 node index.js artistsSync", 11 | "build": "sh ./build.sh", 12 | "build-bundle": "node build.config.js", 13 | "test": "node --test test/*.js" 14 | }, 15 | "author": "rombat", 16 | "license": "GNU GPL V3.0", 17 | "dependencies": { 18 | "camelcase": "^8.0.0", 19 | "cli-progress": "^3.12.0", 20 | "commander": "^14.0.0", 21 | "csvtojson": "^2.0.10", 22 | "dayjs": "^1.11.13", 23 | "p-limit": "^7.1.1" 24 | }, 25 | "devDependencies": { 26 | "@biomejs/biome": "2.2.2", 27 | "@semantic-release/changelog": "^6.0.3", 28 | "@semantic-release/exec": "^7.1.0", 29 | "@semantic-release/git": "^10.0.1", 30 | "@semantic-release/github": "^11.0.3", 31 | "@yao-pkg/pkg": "^6.6.0", 32 | "esbuild": "^0.25.9", 33 | "semantic-release": "^24.2.5" 34 | }, 35 | "engines": { 36 | "node": ">=22.17.0 <23.0.0" 37 | }, 38 | "private": true 39 | } 40 | -------------------------------------------------------------------------------- /release.config.mjs: -------------------------------------------------------------------------------- 1 | export default { 2 | branches: ['master'], 3 | plugins: [ 4 | '@semantic-release/commit-analyzer', 5 | { 6 | preset: 'eslint', 7 | releaseRules: [ 8 | { scope: 'no-release', release: false }, 9 | { type: '', release: 'patch' } 10 | ] 11 | }, 12 | '@semantic-release/release-notes-generator', 13 | [ 14 | '@semantic-release/changelog', 15 | { 16 | changelogTitle: 'MBNDS CHANGELOG' 17 | } 18 | ], 19 | [ 20 | '@semantic-release/npm', 21 | { 22 | npmPublish: false 23 | } 24 | ], 25 | [ 26 | '@semantic-release/exec', 27 | { 28 | publishCmd: 'npm run build' 29 | } 30 | ], 31 | [ 32 | '@semantic-release/github', 33 | { 34 | assets: [ 35 | { 36 | path: '.dist/musicbee-navidrome-sync.exe' 37 | } 38 | ] 39 | } 40 | ], 41 | [ 42 | '@semantic-release/git', 43 | { 44 | // biome-ignore lint/suspicious/noTemplateCurlyInString: semantic-release template variables 45 | message: 'chore(release): set `package.json` to ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}', 46 | assets: ['package.json', 'CHANGELOG.md'] 47 | } 48 | ] 49 | ] 50 | }; 51 | -------------------------------------------------------------------------------- /biome.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://biomejs.dev/schemas/2.2.2/schema.json", 3 | "vcs": { 4 | "enabled": false, 5 | "clientKind": "git", 6 | "useIgnoreFile": false 7 | }, 8 | "files": { 9 | "ignoreUnknown": false, 10 | "includes": ["**", "!**/package-lock.json", "!.dist"] 11 | }, 12 | "formatter": { 13 | "enabled": true, 14 | "indentStyle": "space", 15 | "indentWidth": 2, 16 | "lineWidth": 130 17 | }, 18 | "linter": { 19 | "enabled": true, 20 | "rules": { 21 | "recommended": true, 22 | "correctness": { 23 | "noUnusedImports": { 24 | "level": "error", 25 | "fix": "safe" 26 | } 27 | }, 28 | "style": { 29 | "useBlockStatements": { 30 | "level": "error", 31 | "fix": "unsafe" 32 | }, 33 | "noParameterAssign": "error", 34 | "useDefaultParameterLast": "error", 35 | "useSingleVarDeclarator": "error", 36 | "noUnusedTemplateLiteral": "error", 37 | "useNumberNamespace": "error", 38 | "noUselessElse": "error" 39 | } 40 | } 41 | }, 42 | "javascript": { 43 | "formatter": { 44 | "quoteStyle": "single", 45 | "trailingCommas": "none", 46 | "arrowParentheses": "asNeeded" 47 | } 48 | }, 49 | "json": { 50 | "formatter": { 51 | "trailingCommas": "none" 52 | } 53 | }, 54 | "assist": { 55 | "enabled": true, 56 | "actions": { 57 | "source": { 58 | "organizeImports": "on" 59 | } 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /lib/helpers.js: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs'; 2 | import utc from 'dayjs/plugin/utc.js'; 3 | 4 | dayjs.extend(utc); 5 | 6 | /** 7 | * Normalize path to use forward slashes 8 | * @param {string} path 9 | * @returns {string} 10 | */ 11 | const normalizePath = path => path.replace(/\\/g, '/'); 12 | 13 | /** 14 | * Get path segments 15 | * @param {string} path 16 | * @returns {string[]} 17 | */ 18 | const getSegments = path => normalizePath(path).split('/'); 19 | 20 | /** 21 | * Find best match for a given MusicBee track 22 | * @param {object} mbTrack 23 | * @param {object[]} ndTracks 24 | * @returns {object|undefined} 25 | */ 26 | const findBestMatch = (mbTrack, ndTracks) => { 27 | const mbTrackSegments = getSegments(mbTrack.filePath).reverse(); 28 | mbTrackSegments.unshift(mbTrack.filename); 29 | let bestMatch; 30 | let bestMatchScore = 0; 31 | 32 | ndTracks.filter(Boolean).forEach(ndTrack => { 33 | const ndTrackSegments = getSegments(ndTrack.path).reverse(); 34 | let matchScore = 0; 35 | 36 | if (mbTrackSegments[0] !== ndTrackSegments[0]) { 37 | return; 38 | } 39 | for (let i = 1; i <= Math.min(mbTrackSegments.length, ndTrackSegments.length); i++) { 40 | if (mbTrackSegments[i] === ndTrackSegments[i]) { 41 | matchScore++; 42 | } else { 43 | break; 44 | } 45 | } 46 | if (matchScore > bestMatchScore) { 47 | bestMatchScore = matchScore; 48 | bestMatch = ndTrack; 49 | } 50 | }); 51 | 52 | return bestMatch; 53 | }; 54 | 55 | /** 56 | * Safe date comparison - handles dayjs objects vs database strings 57 | * All comparisons are done in UTC to ensure consistency 58 | * @param {dayjs|string|null} dateA - Usually from CSV (dayjs UTC object) 59 | * @param {string|null} dateB - Usually from database (string) 60 | * @returns {boolean} 61 | */ 62 | const isDateAfter = (dateA, dateB) => { 63 | if (!dateA) { 64 | return false; 65 | } 66 | if (!dateB) { 67 | return true; 68 | } 69 | 70 | // dateA: If dayjs object (from CSV), use as is; if string, treat as UTC 71 | const dayjsA = dayjs.isDayjs(dateA) ? dateA : dayjs.utc(dateA); 72 | 73 | // dateB: Database strings are already in UTC format, treat them as such 74 | const dayjsB = dayjs.utc(dateB); 75 | 76 | return dayjsA.isAfter(dayjsB); 77 | }; 78 | 79 | export { findBestMatch, isDateAfter }; 80 | -------------------------------------------------------------------------------- /test/findBestMatch.test.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert'; 2 | import { describe, it } from 'node:test'; 3 | 4 | import { findBestMatch } from '../lib/helpers.js'; 5 | 6 | describe('findBestMatch', () => { 7 | it('should return the best matching path', () => { 8 | const mbTrack = { 9 | filePath: 'V:\\data\\media\\music\\Soundtracks Author\\Carpenter Brut\\Carpenter Brut - 2018 - Leather Teeth', 10 | filename: '01 - Leather Teeth.mp3' 11 | }; 12 | const ndTracks = [ 13 | { 14 | path: '/music/lidarr/Electro Retrowave/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 15 | }, 16 | { 17 | path: '/music/lidarr/Soundtracks Author/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 18 | } 19 | ]; 20 | const expectedMatch = { 21 | path: '/music/lidarr/Soundtracks Author/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 22 | }; 23 | const result = findBestMatch(mbTrack, ndTracks); 24 | assert.deepStrictEqual(result, expectedMatch); 25 | }); 26 | 27 | it('should handle paths with different lengths', () => { 28 | const mbTrack = { filePath: 'V:\\data\\media\\music\\Short Path', filename: 'File.mp3' }; 29 | const ndTracks = [ 30 | { path: '/music/whatever/longer/length/Short Path/File.mp3' }, 31 | { path: '/music/lidarr/Short Path/Another File.mp3' } 32 | ]; 33 | const expectedMatch = { path: '/music/whatever/longer/length/Short Path/File.mp3' }; 34 | const result = findBestMatch(mbTrack, ndTracks); 35 | assert.deepStrictEqual(result, expectedMatch); 36 | }); 37 | 38 | it('should return undefined if no match is found', () => { 39 | const mbTrack = { filePath: 'V:\\data\\media\\music\\Nonexistent Path', filename: 'Nonexistent File.mp3' }; 40 | const ndTracks = [ 41 | { 42 | path: '/music/lidarr/Electro Retrowave/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 43 | }, 44 | { 45 | path: '/music/lidarr/Soundtracks Author/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 46 | } 47 | ]; 48 | const result = findBestMatch(mbTrack, ndTracks); 49 | assert.strictEqual(result, undefined); 50 | }); 51 | 52 | it('should return undefined if same filename but no matching path', () => { 53 | const mbTrack = { filePath: 'V:\\data\\media\\music\\Nonexistent Path', filename: '01 - Leather Teeth.mp3' }; 54 | const ndTracks = [ 55 | { 56 | path: '/music/lidarr/Electro Retrowave/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 57 | }, 58 | { 59 | path: '/music/lidarr/Soundtracks Author/Carpenter Brut/Carpenter Brut - 2018 - Leather Teeth/01 - Leather Teeth.mp3' 60 | } 61 | ]; 62 | const result = findBestMatch(mbTrack, ndTracks); 63 | assert.strictEqual(result, undefined); 64 | }); 65 | }); 66 | -------------------------------------------------------------------------------- /.github/workflows/validate-pull-request-title.yml: -------------------------------------------------------------------------------- 1 | name: 'PR Title' 2 | 3 | on: 4 | pull_request: 5 | types: 6 | - opened 7 | - edited 8 | - synchronize 9 | - reopened 10 | 11 | jobs: 12 | auto-format-pr: 13 | name: Autoformat PR title if possible 14 | runs-on: ubuntu-latest 15 | outputs: 16 | already_valid: ${{ steps.check_format.outputs.already_valid }} 17 | steps: 18 | - uses: actions/checkout@v4 19 | 20 | - name: Auto-format PR Title 21 | id: check_format 22 | uses: actions/github-script@v7 23 | with: 24 | github-token: ${{ secrets.GITHUB_TOKEN }} 25 | script: | 26 | const pr = context.payload.pull_request; 27 | const branchName = pr.head.ref; 28 | 29 | function getTypeFromBranch(branch) { 30 | const validTypes = [ 31 | 'build', 'chore', 'ci', 'docs', 'feat', 'fix', 32 | 'hotfix', 'perf', 'refactor', 'revert', 'style', 'test' 33 | ]; 34 | 35 | // Extract prefix from branch (e.g., feat/my-branch → feat) 36 | const prefix = branch.split('/')[0].toLowerCase(); 37 | return validTypes.includes(prefix) ? prefix : null; 38 | } 39 | 40 | const type = getTypeFromBranch(branchName); 41 | if (!type) { 42 | console.log('No conventional commit type found in branch name'); 43 | return; 44 | } 45 | 46 | // Check if the title already follows convention 47 | const conventionalPattern = /^(build|chore|ci|docs|feat|fix|hotfix|perf|refactor|revert|style|test)(\(.+\))?: .+/; 48 | if (conventionalPattern.test(pr.title)) { 49 | console.log('PR title already follows conventional commit format'); 50 | core.setOutput('already_valid', 'true'); 51 | return; 52 | } 53 | 54 | // Format the title if it doesn't follow convention 55 | // Extract the actual feature name, removing the prefix 56 | let description = pr.title; 57 | if (pr.title.toLowerCase().startsWith(branchName.split('/')[0].toLowerCase())) { 58 | description = pr.title.substring(pr.title.indexOf('/') + 1).trim(); 59 | } 60 | 61 | const newTitle = `${type}: ${description}`; 62 | 63 | await github.rest.pulls.update({ 64 | owner: context.repo.owner, 65 | repo: context.repo.repo, 66 | pull_number: pr.number, 67 | title: newTitle 68 | }); 69 | 70 | console.log(`Updated PR title to "${newTitle}"`); 71 | core.setOutput('already_valid', 'true'); 72 | 73 | validation: 74 | name: Validate PR title 75 | runs-on: ubuntu-latest 76 | needs: auto-format-pr 77 | if: ${{ needs.auto-format-pr.outputs.already_valid != 'true' }} 78 | steps: 79 | - uses: amannn/action-semantic-pull-request@v5 80 | env: 81 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 82 | with: 83 | wip: false 84 | requireScope: false 85 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import { program } from 'commander'; 2 | import { MBNDSynchronizer } from './lib/MBNDSynchronizer.js'; 3 | import packageJson from './package.json' with { type: 'json' }; 4 | 5 | const runAction = async (options, command) => { 6 | const synchronizer = new MBNDSynchronizer(options); 7 | await synchronizer.run(command._name); 8 | }; 9 | 10 | const commandLinesOptions = { 11 | csv: { 12 | flags: '--csv ', 13 | description: 'MusicBee CSV source file path. Default: MusicBee_Export.csv, in the same folder as MBNDS', 14 | defaultValue: 'MusicBee_Export.csv' 15 | }, 16 | db: { 17 | flags: '--db ', 18 | description: 'Navidrome SQLITE .db source file path. Default: navidrome.db, in the same folder as MBNDS', 19 | defaultValue: 'navidrome.db' 20 | }, 21 | user: { 22 | flags: '-u, --user ', 23 | description: 'choose Navidrome username (by default if not used, the first user will be used)' 24 | }, 25 | datetimeFormat: { 26 | flags: '--datetime-format ', 27 | description: 'MusicBee CSV datetime format. Default: "DD/MM/YYYY HH:mm"', 28 | defaultValue: 'DD/MM/YYYY HH:mm' 29 | }, 30 | verbose: { 31 | flags: '--verbose', 32 | description: 'verbose debugging' 33 | }, 34 | showNotFound: { 35 | flags: '--show-not-found', 36 | description: 'output tracks that were not found in Navidrome database' 37 | } 38 | }; 39 | 40 | program 41 | .name('musicbee-navidrome-sync') 42 | .description( 43 | `MusicBee to Navidrome Sync (MBNDS) : Tools to sync MusicBee DB to Navidrome DB (v${packageJson.version})\nhttps://github.com/rombat/musicbee-navidrome-sync` 44 | ) 45 | .version(packageJson.version, '-v, --version', 'output the current version'); 46 | 47 | program 48 | .command('fullSync') 49 | .description('sync playcounts, track ratings, loved tracks and last played from MusicBee DB to Navidrome DB') 50 | .option(commandLinesOptions.user.flags, commandLinesOptions.user.description) 51 | .option('-f, --first', 'run sync for the first time: add MB playcount to ND playcount') 52 | .option(commandLinesOptions.verbose.flags, commandLinesOptions.verbose.description) 53 | .option(commandLinesOptions.showNotFound.flags, commandLinesOptions.showNotFound.description) 54 | .option(commandLinesOptions.csv.flags, commandLinesOptions.description, commandLinesOptions.defaultValue) 55 | .option(commandLinesOptions.db.flags, commandLinesOptions.db.description, commandLinesOptions.db.defaultValue) 56 | .option( 57 | commandLinesOptions.datetimeFormat.flags, 58 | commandLinesOptions.datetimeFormat.description, 59 | commandLinesOptions.datetimeFormat.defaultValue 60 | ) 61 | .action(runAction); 62 | 63 | program 64 | .command('albumsSync') 65 | .description('update all albums playcounts and ratings based on existing Navidrome DB') 66 | .option(commandLinesOptions.user.flags, commandLinesOptions.user.description) 67 | .option(commandLinesOptions.verbose.flags, commandLinesOptions.verbose.description) 68 | .option(commandLinesOptions.db.flags, commandLinesOptions.db.description, commandLinesOptions.db.defaultValue) 69 | .action(runAction); 70 | 71 | program 72 | .command('artistsSync') 73 | .description('update all artists playcounts and ratings based on existing Navidrome DB') 74 | .option(commandLinesOptions.user.flags, commandLinesOptions.user.description) 75 | .option(commandLinesOptions.verbose.flags, commandLinesOptions.verbose.description) 76 | .option(commandLinesOptions.db.flags, commandLinesOptions.db.description, commandLinesOptions.db.defaultValue) 77 | .action(runAction); 78 | 79 | program.parse(); 80 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | MBNDS CHANGELOG 2 | 3 | # [1.5.0](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.4.0...v1.5.0) (2025-08-30) 4 | 5 | ## Lean release 6 | 7 | This release doesn't bring new features (except the `--show-not-found` flag). 8 | 9 | But the project has been completely refactored to reduce memory consumption and increase speed, from 2 to 5 times faster in my tests. 10 | 11 | Lots of dependencies have been removed too, to rely more on node native modules, more unit tests added, and it has been converted to ESM to use a more modern JS and make it more future-proof. 12 | 13 | ### Bug Fixes 14 | 15 | * semantic-release ESM ([db7d84c](https://github.com/rombat/musicbee-navidrome-sync/commit/db7d84c8902cf55069325aa11e85b0e5e7e3c2ec)) 16 | * test env variable ([b9090f7](https://github.com/rombat/musicbee-navidrome-sync/commit/b9090f7405bfaf34f875cea51709a904d7c0baaa)) 17 | * test env variable ([cc0a031](https://github.com/rombat/musicbee-navidrome-sync/commit/cc0a03185e4eb59454e54bafa49cf04f8cf7639b)) 18 | 19 | 20 | ### Features 21 | 22 | * --show-not-found option added ([048c60d](https://github.com/rombat/musicbee-navidrome-sync/commit/048c60d2ade1aee3c7c08b33b8659f1f9983c4a9)) 23 | * complete refactoring to ESM ([2efa636](https://github.com/rombat/musicbee-navidrome-sync/commit/2efa636451bcced6494557e68330050d06dc6d31)) 24 | * refactor albums and artists with aggregate queries ([94765a1](https://github.com/rombat/musicbee-navidrome-sync/commit/94765a179c2cb5651160e69742e4681ab2c9d3b6)) 25 | * refactored csvtojson to reduce memory usage ([f74fb4a](https://github.com/rombat/musicbee-navidrome-sync/commit/f74fb4a99bec2e2a310a69aa8c31bffd43f62028)) 26 | * removed sequelize/sqlite3 in favor of native node:sqlite ([793d090](https://github.com/rombat/musicbee-navidrome-sync/commit/793d090add5bf6247fcab3de466904e8b79157b2)) 27 | * tests added on PR ([669521c](https://github.com/rombat/musicbee-navidrome-sync/commit/669521c31643b1d26c0ee12b9c18cf3fb32674cd)) 28 | 29 | # [1.4.0](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.3.0...v1.4.0) (2025-08-15) 30 | 31 | 32 | ### Features 33 | 34 | * handle new schemas for navidrome versions >= 0.55.0 (tested up to 0.58.0) ([a1a6c0e](https://github.com/rombat/musicbee-navidrome-sync/commit/a1a6c0ebad8b556fc9e0d16a93ac86ed40234776)) 35 | * new relationships following navidrome 0.55.0 BFR ([dec3ada](https://github.com/rombat/musicbee-navidrome-sync/commit/dec3ada8640023816a11d756b4524942622af33a)) 36 | 37 | # [1.3.0](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.2.2...v1.3.0) (2025-07-03) 38 | 39 | 40 | ### Features 41 | 42 | * update node version to 22.17 LTS ([827f25d](https://github.com/rombat/musicbee-navidrome-sync/commit/827f25dac29aaab3685dba1ffa0ad40b00a23e02)) 43 | 44 | ## [1.2.2](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.2.1...v1.2.2) (2024-07-28) 45 | 46 | 47 | ### Bug Fixes 48 | 49 | * ETA being sometimes erratic ([474d840](https://github.com/rombat/musicbee-navidrome-sync/commit/474d8407256066e408783853d36429331b759ecb)) 50 | 51 | ## [1.2.1](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.2.0...v1.2.1) (2024-07-28) 52 | 53 | 54 | ### Bug Fixes 55 | 56 | * path matching to find tracks ([bc70d90](https://github.com/rombat/musicbee-navidrome-sync/commit/bc70d9091a10e0814441a73390307cf6b8bcc9ce)) 57 | 58 | # [1.2.0](https://github.com/rombat/musicbee-navidrome-sync/compare/v1.1.0...v1.2.0) (2024-07-26) 59 | 60 | 61 | ### Bug Fixes 62 | 63 | * ann_id removed ([fbcd882](https://github.com/rombat/musicbee-navidrome-sync/commit/fbcd882b2b5ff3ea2cac1c2d2e8dec32577f0982)) 64 | * github actions assets broken ([4541ccc](https://github.com/rombat/musicbee-navidrome-sync/commit/4541ccc404f8affde4d2479a319854db881e341b)) 65 | * handle ann_id being removed ([ed92022](https://github.com/rombat/musicbee-navidrome-sync/commit/ed9202296898e774c816b4c523f025fd9ac007c6)) 66 | 67 | 68 | ### Features 69 | 70 | * autorelease with github actions ([cd32a8b](https://github.com/rombat/musicbee-navidrome-sync/commit/cd32a8b86d9d1ccfc4d2f6e2498b3228cc2f1ce0)) 71 | -------------------------------------------------------------------------------- /lib/Database.js: -------------------------------------------------------------------------------- 1 | import { randomUUID } from 'node:crypto'; 2 | import { DatabaseSync } from 'node:sqlite'; 3 | import dayjs from 'dayjs'; 4 | import utc from 'dayjs/plugin/utc.js'; 5 | 6 | dayjs.extend(utc); 7 | 8 | /** 9 | * Database wrapper class that encapsulates db connection and utilities 10 | */ 11 | class Database { 12 | constructor(dbFilePath) { 13 | this.db = new DatabaseSync(dbFilePath); 14 | 15 | const result = this.db.prepare('SELECT 1 as test').get(); 16 | if (result.test !== 1) { 17 | throw new Error('Database connection test failed'); 18 | } 19 | } 20 | 21 | /** 22 | * @param {string} tableName 23 | * @returns {boolean} 24 | */ 25 | tableExists(tableName) { 26 | const result = this.db 27 | .prepare( 28 | ` 29 | SELECT name FROM sqlite_master 30 | WHERE type='table' AND name=? 31 | ` 32 | ) 33 | .get(tableName); 34 | return !!result; 35 | } 36 | 37 | /** 38 | * @param {string} tableName 39 | * @returns {Object} - Schema information with column names as keys 40 | */ 41 | getTableSchema(tableName) { 42 | const columns = this.db.prepare(`PRAGMA table_info(${tableName})`).all(); 43 | const schema = {}; 44 | columns.forEach(col => { 45 | schema[col.name] = { 46 | type: col.type, 47 | notNull: !!col.notnull, 48 | defaultValue: col.dflt_value, 49 | primaryKey: !!col.pk 50 | }; 51 | }); 52 | return schema; 53 | } 54 | 55 | /** 56 | * Check if annotation table has the legacy ann_id column 57 | * @returns {boolean} 58 | */ 59 | hasLegacyAnnotationSchema() { 60 | if (!this.tableExists('annotation')) { 61 | return false; 62 | } 63 | const schema = this.getTableSchema('annotation'); 64 | return 'ann_id' in schema; 65 | } 66 | 67 | /** 68 | * Check if media_file_artists table exists (new Navidrome schema post BFR >= 0.55.0) 69 | * @returns {boolean} 70 | */ 71 | hasMediaFileArtistsTable() { 72 | return this.tableExists('media_file_artists'); 73 | } 74 | 75 | /** 76 | * @param {string} sql 77 | * @param {Array} params 78 | * @returns {Array} 79 | */ 80 | query(sql, params = []) { 81 | return this.db.prepare(sql).all(...params); 82 | } 83 | 84 | /** 85 | * @param {string} sql 86 | * @returns {import('node:sqlite').StatementSync} 87 | */ 88 | prepare(sql) { 89 | return this.db.prepare(sql); 90 | } 91 | 92 | close() { 93 | this.db.close(); 94 | } 95 | 96 | /** 97 | * @param {Object} params - Annotation parameters 98 | * @param {('media_file' | 'album' | 'artist')} params.itemType 99 | * @param {string} params.userId 100 | * @param {string} params.itemId 101 | * @param {Object} params.update - Update object with new values 102 | * @param {boolean} params.needsCreate - Whether to create new annotation 103 | * @returns {Promise} 104 | */ 105 | async upsertAnnotation({ itemType, userId, itemId, update, needsCreate }) { 106 | if (update.play_date) { 107 | const playDate = dayjs.isDayjs(update.play_date) ? update.play_date : dayjs.utc(update.play_date); 108 | update.play_date = playDate.format('YYYY-MM-DD HH:mm:ss'); 109 | } 110 | if (update.starred_at) { 111 | // If already a dayjs object (from CSV), use as-is; if string, treat as UTC 112 | const starredAt = dayjs.isDayjs(update.starred_at) ? update.starred_at : dayjs.utc(update.starred_at); 113 | update.starred_at = starredAt.format('YYYY-MM-DD HH:mm:ss'); 114 | } 115 | 116 | if (needsCreate) { 117 | const record = { 118 | item_type: itemType, 119 | user_id: userId, 120 | item_id: itemId, 121 | play_count: 0, 122 | starred: 0, 123 | rating: 0, 124 | play_date: null, 125 | starred_at: null, 126 | ...update 127 | }; 128 | 129 | if (this.hasLegacyAnnotationSchema()) { 130 | record.ann_id = randomUUID(); 131 | } 132 | 133 | const columns = Object.keys(record).join(', '); 134 | const placeholders = Object.keys(record) 135 | .map(() => '?') 136 | .join(', '); 137 | 138 | this.prepare(`INSERT INTO annotation (${columns}) VALUES (${placeholders})`).run(...Object.values(record)); 139 | } else { 140 | const setClauses = Object.keys(update) 141 | .map(key => `${key} = ?`) 142 | .join(', '); 143 | 144 | this.prepare( 145 | ` 146 | UPDATE annotation 147 | SET ${setClauses} 148 | WHERE item_type = ? 149 | AND user_id = ? 150 | AND item_id = ? 151 | ` 152 | ).run(...Object.values(update), itemType, userId, itemId); 153 | } 154 | } 155 | } 156 | 157 | export const init = async dbFilePath => { 158 | try { 159 | const database = new Database(dbFilePath); 160 | console.log('Connection has been established successfully.'); 161 | return database; 162 | } catch (error) { 163 | console.error('Unable to connect to the database:', error); 164 | throw error; 165 | } 166 | }; 167 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MusicBee to Navidrome Sync (MBNDS) 2 | 3 | 4 | 5 | 6 | 7 | 8 | ## 🎶 Preamble 9 | 10 | I've been using [MusicBee](https://www.getmusicbee.com/) for more than a decade. That means years of playcounts, ratings, loved tracks and so on. 11 | When I set up myself a [Navidrome](https://www.navidrome.org/) server, I didn't want to lose all those years of data, so I decided to do something to import them. 12 | And I actually still use MusicBee, I only use Navidrome when I'm not home, so I wanted to be able to sync my local ratings/playcounts etc. from time to time. 13 | Hence this project. It's probably a niche use case, but who knows, it can be useful to somebody? 14 | 15 | 16 | 17 | ## 🤔 Purpose 18 | 19 | MusicBee to Navidrome Sync allows you to: 20 | * import MB tracks playcount, ratings, loved tracks, last played date. You can add them to already existing ND data (for a first time sync), or update them occasionally if needed. 21 | * update ND albums/artists playcount and last played date, and generate or update their ratings based only on ND data (see [Notes](#-notes)); 22 | 23 | 24 | ## ❔ How to use it 25 | 26 | 1. First, you need MusicBee 3.5 with its language set as **English** and [Additional Tagging & Reporting Tools](https://getmusicbee.com/addons/plugins/49/additional-tagging-amp-reporting-tools/) plugin installed 27 | 2. Once it's done, select **Music** under the Collection menu. Then click on **MusicBee** > **Tools** > **Additional Tagging Tools** > **Library Report**... to export library data in a CSV 28 | 3. Click **New Preset** to create a new preset, and give it a name by just by typing anything in the field where **(Auto preset name)** is displayed 29 | 4. You can now add data to your export, by clicking on **Add** (**Function** select needs to be ``). Here, you have to select tags that will be exported as headers for your CSV. You need to select **at least** the following ones for MBNDS to work properly: 30 | * `` 31 | * `` 32 | * `` 33 | * `Title` 34 | * `Last Played` 35 | * `Play Count` 36 | * `Rating` 37 | * `Love` 38 | * `Skip Count` 39 | 5. If the checkbox is available, you can tick **Hide preview**, it'll scan your library faster 40 | 6. Click on **Preview**, MusicBee will scan your entire collection, so it can take some time depending on its size. Once it's done, select `CSV` in **Format** (if necessary), click on **Export** and name your file `MusicBee_Export.csv` 41 | 7. **Shutdown Navidrome properly**. This is mandatory to avoid backing up its database while there's still operations going on with it. 42 | 8. Once Navidrome is shut down, backup its database file, `navidrome.db`. Its location is usually in navidrome `/data` folder. You can back up it either by copying it or with sqlite3 CLI if installed (`sqlite3 ".timeout 30000" ".backup "` for instance). ⚠️ If Navidrome has been properly shut down, you shouldn't have any remaining `navidrome.db-shm` or `navidrome.db-wal` next to `navidrome.db`. 43 | 9. Download [this repository latest release](https://github.com/rombat/musicbee-navidrome-sync/releases/latest) .exe 44 | 10. Copy **only** `navidrome.db` and `MusicBee_Export.csv` in the same folder as this .exe (or you can provide pathes with CLI, see **Commands** below). 45 | 11. Run the command you want to run (, see **Commands** below), your database file will be updated 46 | 12. Once it's done, go back to navidrome `/data` folder where you found `navidrome.db` and overwrite it with the updated one. 47 | 13. Restart Navidrome, and that's it ! 48 | 49 | 50 | ## ⌨️ Commands 51 | 52 | All commands must be run this way: `musicbee-navidrome-sync.exe [command name] [options]`. 53 | For instance, `musicbee-navidrome-sync.exe fullSync -h` 54 | 55 | ### fullSync 56 | 57 | Syncs playcounts, track ratings, loved tracks and last played date from MusicBee DB to Navidrome DB. Runs on tracks first, then updates albums and artists accordingly. 58 | 59 | #### Available options : 60 | 61 | * `-f, --first` : runs sync for the first time: **add** MusicBee playcount to Navidrome playcount. If not used, playcount will be updated only if greater than Navidrome's one (see [Notes](#-notes)). 62 | * `--csv ` : MusicBee CSV source file path. By default if not passed, will look for a file named `MusicBee_Export.csv` in the same folder as `musicbee-navidrome-sync.exe` 63 | * `--datetime-format ` : MusicBee CSV datetime format. Default: `"DD/MM/YYYY HH:mm"`. Use available formats from https://day.js.org/docs/en/display/format 64 | 65 | 66 | ### albumsSync 67 | 68 | Updates all albums playcounts and ratings based on existing Navidrome DB. 69 | 70 | ### artistsSync 71 | 72 | Updates all artists playcounts and ratings based on existing Navidrome DB 73 | 74 | ### Common options 75 | 76 | All commands have these options available: 77 | * `--db ` : Navidrome SQLITE .db source file path. By default if not passed, will look for a file named `navidrome.db` in the same folder as `musicbee-navidrome-sync.exe` 78 | * `-u, --user ` : selects Navidrome username (by default if not used, the first found user will be used) 79 | * `--verbose` : verbose debugging 80 | * `--show-not-found` : display tracks that were not found in Navidrome database (useful for troubleshooting missing tracks without verbose output noise) 81 | * `-h, --help` : displays help for command 82 | 83 | 84 | ## 📋 Notes 85 | 86 | * This is a **one way sync** only, from MusicBee to Navidrome. Can't do the other way. 87 | * A backup of your Navidrome DB is created in a newly created `backups` folder everytime you run a command 88 | * Updates are only applied when they are more favorable (ex: MusicBee rating > Navidrome rating, MusicBee play date > Navidrome play date...) 89 | * Ratings are updated on certain conditions: 90 | * For tracks: if MusicBee rating is greater than Navidrome rating 91 | * For albums, if more than half of the album tracks are rated (its rating will be the average of available tracks ratings) 92 | * For artists, same as album, will be applied only to artists with more than 1 track 93 | * **Cross-version compatibility**: Automatically detects and works with both old and new Navidrome database schemas 94 | * Tested with the following versions : 95 | * MusicBee: 96 | * 3.5.* 97 | * Advance Tagging and Reporting Tool: 98 | * 5.2.* 99 | * 5.7.* 100 | * 8.0.* 101 | * 9.2.* 102 | * Navidrome: 103 | * 0.47.5 up to 0.58.5 104 | 105 | 106 | ## ➡️ What's next ? 107 | 108 | Maybe build it as a .exe GUI ? 109 | If you have any enhancements suggestions, don't hesitate! 110 | 111 | 112 | ## ☕ Did you like this tool ? 113 | 114 | If you found this tool useful, if it saved you some time, you can buy me a coffee ! 115 | I'm more of a tea (or beer >_>) drinker, but I can appreciate a good coffee too. 116 | 117 | Buy Me a Coffee at ko-fi.com 118 | 119 | -------------------------------------------------------------------------------- /test/isDateAfter.test.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert'; 2 | import { describe, it } from 'node:test'; 3 | import dayjs from 'dayjs'; 4 | import customParseFormat from 'dayjs/plugin/customParseFormat.js'; 5 | import utc from 'dayjs/plugin/utc.js'; 6 | 7 | dayjs.extend(utc); 8 | dayjs.extend(customParseFormat); 9 | 10 | import { isDateAfter } from '../lib/helpers.js'; 11 | 12 | describe('isDateAfter', () => { 13 | describe('dayjs object vs string comparisons', () => { 14 | it('should return true when dayjs date is after string date', () => { 15 | const dayjsDate = dayjs('2025-01-15 10:30:00'); 16 | const stringDate = '2025-01-10 09:00:00'; 17 | 18 | const result = isDateAfter(dayjsDate, stringDate); 19 | assert.strictEqual(result, true); 20 | }); 21 | 22 | it('should return false when dayjs date is before string date', () => { 23 | const dayjsDate = dayjs('2025-01-05 10:30:00'); 24 | const stringDate = '2025-01-10 09:00:00'; 25 | 26 | const result = isDateAfter(dayjsDate, stringDate); 27 | assert.strictEqual(result, false); 28 | }); 29 | 30 | it('should return false when dayjs date equals string date', () => { 31 | const testDate = '2025-01-10 09:00:00'; 32 | const dayjsDate = dayjs(testDate); 33 | 34 | const result = isDateAfter(dayjsDate, testDate); 35 | assert.strictEqual(result, false); 36 | }); 37 | }); 38 | 39 | describe('string vs string comparisons', () => { 40 | it('should return true when first string date is after second', () => { 41 | const dateA = '2025-01-15 10:30:00'; 42 | const dateB = '2025-01-10 09:00:00'; 43 | 44 | const result = isDateAfter(dateA, dateB); 45 | assert.strictEqual(result, true); 46 | }); 47 | 48 | it('should return false when first string date is before second', () => { 49 | const dateA = '2025-01-05 10:30:00'; 50 | const dateB = '2025-01-10 09:00:00'; 51 | 52 | const result = isDateAfter(dateA, dateB); 53 | assert.strictEqual(result, false); 54 | }); 55 | 56 | it('should return false when string dates are equal', () => { 57 | const dateA = '2025-01-10 09:00:00'; 58 | const dateB = '2025-01-10 09:00:00'; 59 | 60 | const result = isDateAfter(dateA, dateB); 61 | assert.strictEqual(result, false); 62 | }); 63 | }); 64 | 65 | describe('null and undefined handling', () => { 66 | it('should return false when first date is null', () => { 67 | const result = isDateAfter(null, '2025-01-10 09:00:00'); 68 | assert.strictEqual(result, false); 69 | }); 70 | 71 | it('should return false when first date is undefined', () => { 72 | const result = isDateAfter(undefined, '2025-01-10 09:00:00'); 73 | assert.strictEqual(result, false); 74 | }); 75 | 76 | it('should return true when second date is null and first is valid', () => { 77 | const dayjsDate = dayjs('2025-01-15 10:30:00'); 78 | const result = isDateAfter(dayjsDate, null); 79 | assert.strictEqual(result, true); 80 | }); 81 | 82 | it('should return true when second date is undefined and first is valid', () => { 83 | const stringDate = '2025-01-15 10:30:00'; 84 | const result = isDateAfter(stringDate, undefined); 85 | assert.strictEqual(result, true); 86 | }); 87 | 88 | it('should return false when both dates are null', () => { 89 | const result = isDateAfter(null, null); 90 | assert.strictEqual(result, false); 91 | }); 92 | 93 | it('should return false when both dates are undefined', () => { 94 | const result = isDateAfter(undefined, undefined); 95 | assert.strictEqual(result, false); 96 | }); 97 | }); 98 | 99 | describe('edge cases', () => { 100 | it('should handle different date formats correctly', () => { 101 | const dayjsDate = dayjs('2025-01-15T10:30:00Z'); 102 | const stringDate = '2025-01-10 09:00:00'; 103 | 104 | const result = isDateAfter(dayjsDate, stringDate); 105 | assert.strictEqual(result, true); 106 | }); 107 | 108 | it('should handle milliseconds precision', () => { 109 | const dayjsDate = dayjs.utc('2025-01-10 09:00:00.001'); 110 | const stringDate = '2025-01-10 09:00:00.000'; 111 | 112 | const result = isDateAfter(dayjsDate, stringDate); 113 | assert.strictEqual(result, true); 114 | }); 115 | 116 | it('should handle timezone differences', () => { 117 | const dayjsDate = dayjs.utc('2025-01-15 10:30:00'); 118 | const stringDate = '2025-01-15 08:30:00'; // 2 hours earlier 119 | 120 | const result = isDateAfter(dayjsDate, stringDate); 121 | assert.strictEqual(result, true); 122 | }); 123 | 124 | it('should return false when first date is empty string', () => { 125 | const result = isDateAfter('', '2025-01-10 09:00:00'); 126 | assert.strictEqual(result, false); 127 | }); 128 | 129 | it('should return true when second date is empty string and first is valid', () => { 130 | const dayjsDate = dayjs.utc('2025-01-15 10:30:00'); 131 | const result = isDateAfter(dayjsDate, ''); 132 | assert.strictEqual(result, true); 133 | }); 134 | }); 135 | 136 | describe('real-world scenarios from codebase', () => { 137 | it('should handle CSV date (dayjs UTC) vs database date (string) - newer CSV', () => { 138 | // Simulate CSV processing: lastPlayed from MusicBee (UTC) 139 | const csvLastPlayed = dayjs.utc('2025-01-15 10:30:00'); 140 | // Simulate database: play_date from annotation table 141 | const dbPlayDate = '2025-01-10 09:00:00'; 142 | 143 | const result = isDateAfter(csvLastPlayed, dbPlayDate); 144 | assert.strictEqual(result, true); 145 | }); 146 | 147 | it('should handle album/artist aggregated dates (string vs string)', () => { 148 | // Simulate album stats: tracks_last_played vs album_last_played 149 | const tracksLastPlayed = '2025-01-15 10:30:00'; 150 | const albumLastPlayed = '2025-01-10 09:00:00'; 151 | 152 | const result = isDateAfter(tracksLastPlayed, albumLastPlayed); 153 | assert.strictEqual(result, true); 154 | }); 155 | 156 | it('should handle new annotations (CSV vs null database)', () => { 157 | // New track that has no existing annotation 158 | const csvLastPlayed = dayjs.utc('2025-01-15 10:30:00'); 159 | const dbPlayDate = null; 160 | 161 | const result = isDateAfter(csvLastPlayed, dbPlayDate); 162 | assert.strictEqual(result, true); 163 | }); 164 | 165 | it('should handle timezone differences consistently', () => { 166 | // CSV date in UTC 167 | const csvDate = dayjs.utc('2025-01-15 10:30:00'); 168 | // Database date that could be interpreted as local time 169 | const dbDate = '2025-01-15 06:30:00'; // 4 hours earlier (different timezone) 170 | 171 | const result = isDateAfter(csvDate, dbDate); 172 | assert.strictEqual(result, true); // UTC comparison should be consistent 173 | }); 174 | 175 | it('should handle MusicBee CSV format vs database storage (same date)', () => { 176 | // Simulate exact MusicBee scenario 177 | const musicbeeDate = '28/04/2009 07:38'; 178 | const format = 'DD/MM/YYYY HH:mm'; 179 | 180 | // Parse as done in CSV processing 181 | const csvParsedDate = dayjs(musicbeeDate, format).utc(); 182 | 183 | // Simulate what gets stored in database (should be the same moment in UTC) 184 | const dbStoredDate = csvParsedDate.format('YYYY-MM-DD HH:mm:ss'); 185 | 186 | const result = isDateAfter(csvParsedDate, dbStoredDate); 187 | assert.strictEqual(result, false); // Should be false - same dates 188 | }); 189 | 190 | it('should handle MusicBee CSV format vs database storage (newer CSV)', () => { 191 | // Simulate MusicBee scenario with newer CSV date 192 | const musicbeeDate = '28/04/2009 07:39'; // 1 minute later 193 | const format = 'DD/MM/YYYY HH:mm'; 194 | 195 | const csvParsedDate = dayjs(musicbeeDate, format).utc(); 196 | const olderDbDate = '2009-04-28 05:38:00'; // 1 minute earlier in UTC 197 | 198 | const result = isDateAfter(csvParsedDate, olderDbDate); 199 | assert.strictEqual(result, true); // Should be true - CSV is newer 200 | }); 201 | }); 202 | }); 203 | -------------------------------------------------------------------------------- /test/Database.test.js: -------------------------------------------------------------------------------- 1 | import assert from 'node:assert'; 2 | import { afterEach, beforeEach, describe, it } from 'node:test'; 3 | 4 | import dayjs from 'dayjs'; 5 | import customParseFormat from 'dayjs/plugin/customParseFormat.js'; 6 | import utc from 'dayjs/plugin/utc.js'; 7 | 8 | dayjs.extend(utc); 9 | dayjs.extend(customParseFormat); 10 | 11 | import * as dbManager from '../lib/Database.js'; 12 | 13 | describe('Database', () => { 14 | let database; 15 | 16 | afterEach(() => { 17 | if (database) { 18 | try { 19 | database.close(); 20 | } catch (_e) { 21 | // Ignore close errors during cleanup 22 | } 23 | database = null; 24 | } 25 | }); 26 | 27 | describe('constructor and basic connection', () => { 28 | it('should create database connection successfully', async () => { 29 | database = await dbManager.init(':memory:'); 30 | assert(database); 31 | assert.strictEqual(database.constructor.name, 'Database'); 32 | }); 33 | 34 | it('should verify connection with test query', async () => { 35 | database = await dbManager.init(':memory:'); 36 | const result = database.prepare('SELECT 1 as test').get(); 37 | assert.strictEqual(result.test, 1); 38 | }); 39 | 40 | it('should handle invalid database path gracefully', async () => { 41 | try { 42 | const invalidPath = '/nonexistent/directory/test.db'; 43 | await dbManager.init(invalidPath); 44 | assert.fail('Should have thrown an error'); 45 | } catch (error) { 46 | assert(error); 47 | } 48 | }); 49 | }); 50 | 51 | describe('query and prepare methods', () => { 52 | beforeEach(async () => { 53 | database = await dbManager.init(':memory:'); 54 | 55 | database 56 | .prepare( 57 | ` 58 | CREATE TABLE test_table ( 59 | id INTEGER PRIMARY KEY, 60 | name TEXT, 61 | value INTEGER 62 | ) 63 | ` 64 | ) 65 | .run(); 66 | 67 | database.prepare('INSERT INTO test_table (name, value) VALUES (?, ?)').run('test1', 100); 68 | database.prepare('INSERT INTO test_table (name, value) VALUES (?, ?)').run('test2', 200); 69 | }); 70 | 71 | it('should execute query with parameters', () => { 72 | const results = database.query('SELECT * FROM test_table WHERE value > ?', [150]); 73 | assert.strictEqual(results.length, 1); 74 | assert.strictEqual(results[0].name, 'test2'); 75 | assert.strictEqual(results[0].value, 200); 76 | }); 77 | 78 | it('should execute query without parameters', () => { 79 | const results = database.query('SELECT COUNT(*) as count FROM test_table'); 80 | assert.strictEqual(results.length, 1); 81 | assert.strictEqual(results[0].count, 2); 82 | }); 83 | 84 | it('should prepare and execute statements', () => { 85 | const stmt = database.prepare('SELECT * FROM test_table WHERE name = ?'); 86 | const result = stmt.get('test1'); 87 | assert.strictEqual(result.name, 'test1'); 88 | assert.strictEqual(result.value, 100); 89 | }); 90 | 91 | it('should handle empty results', () => { 92 | const results = database.query('SELECT * FROM test_table WHERE value > ?', [300]); 93 | assert.strictEqual(results.length, 0); 94 | }); 95 | }); 96 | 97 | describe('schema detection methods', () => { 98 | beforeEach(async () => { 99 | database = await dbManager.init(':memory:'); 100 | }); 101 | 102 | describe('tableExists', () => { 103 | it('should return true for existing table', () => { 104 | database.prepare('CREATE TABLE existing_table (id INTEGER)').run(); 105 | const exists = database.tableExists('existing_table'); 106 | assert.strictEqual(exists, true); 107 | }); 108 | 109 | it('should return false for non-existing table', () => { 110 | const exists = database.tableExists('nonexistent_table'); 111 | assert.strictEqual(exists, false); 112 | }); 113 | 114 | it('should handle case sensitivity', () => { 115 | database.prepare('CREATE TABLE CamelCase (id INTEGER)').run(); 116 | const exists = database.tableExists('CamelCase'); 117 | assert.strictEqual(exists, true); 118 | }); 119 | }); 120 | 121 | describe('getTableSchema', () => { 122 | it('should return correct schema for simple table', () => { 123 | database 124 | .prepare( 125 | ` 126 | CREATE TABLE simple_table ( 127 | id INTEGER PRIMARY KEY, 128 | name TEXT NOT NULL, 129 | optional_field TEXT 130 | ) 131 | ` 132 | ) 133 | .run(); 134 | 135 | const schema = database.getTableSchema('simple_table'); 136 | assert('id' in schema); 137 | assert('name' in schema); 138 | assert('optional_field' in schema); 139 | 140 | assert.strictEqual(schema.id.primaryKey, true); 141 | assert.strictEqual(schema.name.notNull, true); 142 | assert.strictEqual(schema.optional_field.notNull, false); 143 | }); 144 | 145 | it('should return correct types', () => { 146 | database 147 | .prepare( 148 | ` 149 | CREATE TABLE typed_table ( 150 | int_field INTEGER, 151 | text_field TEXT, 152 | real_field REAL 153 | ) 154 | ` 155 | ) 156 | .run(); 157 | 158 | const schema = database.getTableSchema('typed_table'); 159 | assert.strictEqual(schema.int_field.type, 'INTEGER'); 160 | assert.strictEqual(schema.text_field.type, 'TEXT'); 161 | assert.strictEqual(schema.real_field.type, 'REAL'); 162 | }); 163 | 164 | it('should handle default values', () => { 165 | database 166 | .prepare( 167 | ` 168 | CREATE TABLE default_table ( 169 | id INTEGER PRIMARY KEY, 170 | status TEXT DEFAULT 'active', 171 | count INTEGER DEFAULT 0 172 | ) 173 | ` 174 | ) 175 | .run(); 176 | 177 | const schema = database.getTableSchema('default_table'); 178 | assert.strictEqual(schema.status.defaultValue, "'active'"); 179 | assert.strictEqual(schema.count.defaultValue, '0'); 180 | }); 181 | }); 182 | 183 | describe('hasLegacyAnnotationSchema', () => { 184 | it('should return false when annotation table does not exist', () => { 185 | const hasLegacy = database.hasLegacyAnnotationSchema(); 186 | assert.strictEqual(hasLegacy, false); 187 | }); 188 | 189 | it('should return true when annotation table has ann_id column', () => { 190 | database 191 | .prepare( 192 | ` 193 | CREATE TABLE annotation ( 194 | ann_id TEXT PRIMARY KEY, 195 | user_id TEXT, 196 | item_id TEXT, 197 | item_type TEXT 198 | ) 199 | ` 200 | ) 201 | .run(); 202 | 203 | const hasLegacy = database.hasLegacyAnnotationSchema(); 204 | assert.strictEqual(hasLegacy, true); 205 | }); 206 | 207 | it('should return false when annotation table lacks ann_id column', () => { 208 | database 209 | .prepare( 210 | ` 211 | CREATE TABLE annotation ( 212 | user_id TEXT, 213 | item_id TEXT, 214 | item_type TEXT, 215 | PRIMARY KEY (user_id, item_id, item_type) 216 | ) 217 | ` 218 | ) 219 | .run(); 220 | 221 | const hasLegacy = database.hasLegacyAnnotationSchema(); 222 | assert.strictEqual(hasLegacy, false); 223 | }); 224 | }); 225 | 226 | describe('hasMediaFileArtistsTable', () => { 227 | it('should return false when table does not exist', () => { 228 | const hasTable = database.hasMediaFileArtistsTable(); 229 | assert.strictEqual(hasTable, false); 230 | }); 231 | 232 | it('should return true when media_file_artists table exists', () => { 233 | database 234 | .prepare( 235 | ` 236 | CREATE TABLE media_file_artists ( 237 | media_file_id TEXT, 238 | artist_id TEXT, 239 | role TEXT 240 | ) 241 | ` 242 | ) 243 | .run(); 244 | 245 | const hasTable = database.hasMediaFileArtistsTable(); 246 | assert.strictEqual(hasTable, true); 247 | }); 248 | }); 249 | }); 250 | 251 | describe('upsertAnnotation method', () => { 252 | beforeEach(async () => { 253 | database = await dbManager.init(':memory:'); 254 | }); 255 | 256 | describe('with modern annotation schema (no ann_id)', () => { 257 | beforeEach(() => { 258 | database 259 | .prepare( 260 | ` 261 | CREATE TABLE annotation ( 262 | user_id TEXT NOT NULL, 263 | item_id TEXT NOT NULL, 264 | item_type TEXT NOT NULL, 265 | play_count INTEGER DEFAULT 0, 266 | play_date TEXT, 267 | rating INTEGER DEFAULT 0, 268 | starred INTEGER DEFAULT 0, 269 | starred_at TEXT, 270 | PRIMARY KEY (user_id, item_id, item_type) 271 | ) 272 | ` 273 | ) 274 | .run(); 275 | }); 276 | 277 | it('should create new annotation when needsCreate is true', async () => { 278 | const update = { 279 | play_count: 5, 280 | rating: 4, 281 | play_date: dayjs.utc('2024-01-15 10:30:00') 282 | }; 283 | 284 | await database.upsertAnnotation({ 285 | itemType: 'media_file', 286 | userId: 'user1', 287 | itemId: 'track1', 288 | update, 289 | needsCreate: true 290 | }); 291 | 292 | const result = database.prepare('SELECT * FROM annotation WHERE user_id = ? AND item_id = ?').get('user1', 'track1'); 293 | assert(result); 294 | assert.strictEqual(result.play_count, 5); 295 | assert.strictEqual(result.rating, 4); 296 | assert.strictEqual(result.play_date, '2024-01-15 10:30:00'); 297 | assert.strictEqual(result.item_type, 'media_file'); 298 | }); 299 | 300 | it('should update existing annotation when needsCreate is false', async () => { 301 | // Create initial annotation 302 | database 303 | .prepare( 304 | ` 305 | INSERT INTO annotation (user_id, item_id, item_type, play_count, rating) 306 | VALUES (?, ?, ?, ?, ?) 307 | ` 308 | ) 309 | .run('user1', 'track1', 'media_file', 3, 2); 310 | 311 | const update = { 312 | play_count: 8, 313 | rating: 5 314 | }; 315 | 316 | await database.upsertAnnotation({ 317 | itemType: 'media_file', 318 | userId: 'user1', 319 | itemId: 'track1', 320 | update, 321 | needsCreate: false 322 | }); 323 | 324 | const result = database.prepare('SELECT * FROM annotation WHERE user_id = ? AND item_id = ?').get('user1', 'track1'); 325 | assert.strictEqual(result.play_count, 8); 326 | assert.strictEqual(result.rating, 5); 327 | }); 328 | 329 | it('should handle date formatting correctly', async () => { 330 | const testDate = dayjs.utc('2024-01-15 10:30:00'); 331 | const update = { 332 | play_date: testDate, 333 | starred_at: testDate 334 | }; 335 | 336 | await database.upsertAnnotation({ 337 | itemType: 'media_file', 338 | userId: 'user1', 339 | itemId: 'track1', 340 | update, 341 | needsCreate: true 342 | }); 343 | 344 | const result = database.prepare('SELECT * FROM annotation WHERE user_id = ? AND item_id = ?').get('user1', 'track1'); 345 | assert.strictEqual(result.play_date, '2024-01-15 10:30:00'); 346 | assert.strictEqual(result.starred_at, '2024-01-15 10:30:00'); 347 | }); 348 | 349 | it('should handle MusicBee CSV dayjs objects correctly', async () => { 350 | // Simulate exactly how CSV dates are parsed 351 | const musicbeeDate = '28/04/2009 07:38'; 352 | const format = 'DD/MM/YYYY HH:mm'; 353 | const csvParsedDate = dayjs(musicbeeDate, format).utc(); 354 | 355 | const update = { 356 | play_date: csvParsedDate, // This is a dayjs UTC object 357 | rating: 5 358 | }; 359 | 360 | await database.upsertAnnotation({ 361 | itemType: 'media_file', 362 | userId: 'user1', 363 | itemId: 'track1', 364 | update, 365 | needsCreate: true 366 | }); 367 | 368 | const result = database.prepare('SELECT * FROM annotation WHERE user_id = ? AND item_id = ?').get('user1', 'track1'); 369 | // Should store the UTC time (which would be 05:38 if local timezone was UTC+2) 370 | assert.match(result.play_date, /2009-04-28 \d{2}:38:00/); // Time depends on local timezone 371 | assert.strictEqual(result.rating, 5); 372 | }); 373 | 374 | it('should handle different item types', async () => { 375 | const update = { play_count: 10, rating: 5 }; 376 | 377 | // Test album annotation 378 | await database.upsertAnnotation({ 379 | itemType: 'album', 380 | userId: 'user1', 381 | itemId: 'album1', 382 | update, 383 | needsCreate: true 384 | }); 385 | 386 | // Test artist annotation 387 | await database.upsertAnnotation({ 388 | itemType: 'artist', 389 | userId: 'user1', 390 | itemId: 'artist1', 391 | update, 392 | needsCreate: true 393 | }); 394 | 395 | const albumResult = database.prepare('SELECT * FROM annotation WHERE item_type = ?').get('album'); 396 | const artistResult = database.prepare('SELECT * FROM annotation WHERE item_type = ?').get('artist'); 397 | 398 | assert.strictEqual(albumResult.item_id, 'album1'); 399 | assert.strictEqual(artistResult.item_id, 'artist1'); 400 | }); 401 | }); 402 | 403 | describe('with legacy annotation schema (with ann_id)', () => { 404 | beforeEach(() => { 405 | database 406 | .prepare( 407 | ` 408 | CREATE TABLE annotation ( 409 | ann_id TEXT PRIMARY KEY, 410 | user_id TEXT NOT NULL, 411 | item_id TEXT NOT NULL, 412 | item_type TEXT NOT NULL, 413 | play_count INTEGER DEFAULT 0, 414 | play_date TEXT, 415 | rating INTEGER DEFAULT 0, 416 | starred INTEGER DEFAULT 0, 417 | starred_at TEXT 418 | ) 419 | ` 420 | ) 421 | .run(); 422 | }); 423 | 424 | it('should include ann_id when creating new annotation in legacy schema', async () => { 425 | const update = { play_count: 5, rating: 4 }; 426 | 427 | await database.upsertAnnotation({ 428 | itemType: 'media_file', 429 | userId: 'user1', 430 | itemId: 'track1', 431 | update, 432 | needsCreate: true 433 | }); 434 | 435 | const result = database.prepare('SELECT * FROM annotation WHERE user_id = ? AND item_id = ?').get('user1', 'track1'); 436 | assert(result); 437 | assert(result.ann_id); 438 | assert.strictEqual(typeof result.ann_id, 'string'); 439 | assert(result.ann_id.length > 0); 440 | }); 441 | 442 | it('should update existing annotation in legacy schema', async () => { 443 | database 444 | .prepare( 445 | ` 446 | INSERT INTO annotation (ann_id, user_id, item_id, item_type, play_count, rating) 447 | VALUES (?, ?, ?, ?, ?, ?) 448 | ` 449 | ) 450 | .run('existing-id', 'user1', 'track1', 'media_file', 3, 2); 451 | 452 | const update = { play_count: 8, rating: 5 }; 453 | 454 | await database.upsertAnnotation({ 455 | itemType: 'media_file', 456 | userId: 'user1', 457 | itemId: 'track1', 458 | update, 459 | needsCreate: false 460 | }); 461 | 462 | const result = database.prepare('SELECT * FROM annotation WHERE ann_id = ?').get('existing-id'); 463 | assert.strictEqual(result.play_count, 8); 464 | assert.strictEqual(result.rating, 5); 465 | assert.strictEqual(result.ann_id, 'existing-id'); 466 | }); 467 | }); 468 | 469 | describe('error scenarios', () => { 470 | beforeEach(() => { 471 | database 472 | .prepare( 473 | ` 474 | CREATE TABLE annotation ( 475 | user_id TEXT NOT NULL, 476 | item_id TEXT NOT NULL, 477 | item_type TEXT NOT NULL, 478 | play_count INTEGER DEFAULT 0, 479 | play_date TEXT, 480 | rating INTEGER DEFAULT 0, 481 | starred INTEGER DEFAULT 0, 482 | starred_at TEXT, 483 | PRIMARY KEY (user_id, item_id, item_type) 484 | ) 485 | ` 486 | ) 487 | .run(); 488 | }); 489 | 490 | it('should handle duplicate key error gracefully during create', async () => { 491 | const update = { play_count: 5 }; 492 | 493 | // First insert should succeed 494 | await database.upsertAnnotation({ 495 | itemType: 'media_file', 496 | userId: 'user1', 497 | itemId: 'track1', 498 | update, 499 | needsCreate: true 500 | }); 501 | 502 | // Second insert with same key should throw error 503 | try { 504 | await database.upsertAnnotation({ 505 | itemType: 'media_file', 506 | userId: 'user1', 507 | itemId: 'track1', 508 | update, 509 | needsCreate: true 510 | }); 511 | assert.fail('Should have thrown duplicate key error'); 512 | } catch (error) { 513 | assert(error.message.includes('UNIQUE constraint failed')); 514 | } 515 | }); 516 | 517 | it('should handle update of non-existent record', async () => { 518 | const update = { play_count: 5 }; 519 | 520 | // Update non-existent record should not throw but affect 0 rows 521 | await database.upsertAnnotation({ 522 | itemType: 'media_file', 523 | userId: 'user1', 524 | itemId: 'nonexistent', 525 | update, 526 | needsCreate: false 527 | }); 528 | 529 | // Verify no record was created 530 | const result = database.prepare('SELECT * FROM annotation WHERE item_id = ?').get('nonexistent'); 531 | assert.strictEqual(result, undefined); 532 | }); 533 | }); 534 | }); 535 | 536 | describe('cleanup and resource management', () => { 537 | it('should close database connection properly', async () => { 538 | database = await dbManager.init(':memory:'); 539 | 540 | const result = database.prepare('SELECT 1 as test').get(); 541 | assert.strictEqual(result.test, 1); 542 | 543 | database.close(); 544 | 545 | try { 546 | database.prepare('SELECT 1 as test').get(); 547 | assert.fail('Should have thrown error on closed database'); 548 | } catch (error) { 549 | assert(error.message.includes('database is not open')); 550 | } 551 | }); 552 | 553 | it('should handle multiple close calls gracefully', async () => { 554 | database = await dbManager.init(':memory:'); 555 | 556 | database.close(); 557 | 558 | // Second close should not throw error (but might internally) 559 | // This is implementation dependent, so we just verify it doesn't crash the process 560 | try { 561 | database.close(); 562 | } catch (error) { 563 | // It's acceptable if the second close throws an error 564 | assert(error.message.includes('database is not open')); 565 | } 566 | }); 567 | }); 568 | }); 569 | -------------------------------------------------------------------------------- /lib/MBNDSynchronizer.js: -------------------------------------------------------------------------------- 1 | import fs from 'node:fs'; 2 | import path from 'node:path'; 3 | import camelCase from 'camelcase'; 4 | import cliProgress from 'cli-progress'; 5 | import csv2json from 'csvtojson'; 6 | import dayjs from 'dayjs'; 7 | import customParseFormat from 'dayjs/plugin/customParseFormat.js'; 8 | import duration from 'dayjs/plugin/duration.js'; 9 | import relativeTime from 'dayjs/plugin/relativeTime.js'; 10 | import utc from 'dayjs/plugin/utc.js'; 11 | import pLimit from 'p-limit'; 12 | 13 | dayjs.extend(utc); 14 | dayjs.extend(customParseFormat); 15 | dayjs.extend(duration); 16 | dayjs.extend(relativeTime); 17 | 18 | import packageJson from '../package.json' with { type: 'json' }; 19 | import * as dbManager from './Database.js'; 20 | import { findBestMatch, isDateAfter } from './helpers.js'; 21 | 22 | class MBNDSynchronizer { 23 | constructor(options) { 24 | this.REQUIRED_HEADERS = [ 25 | '', 26 | '', 27 | '', 28 | 'Last Played', 29 | 'Play Count', 30 | 'Rating', 31 | 'Love', 32 | 'Skip Count', 33 | 'Title' 34 | ]; 35 | this.paths = { 36 | backupFilePath: undefined, 37 | defaultWorkingDirectory: './', 38 | defaultDbFileName: 'navidrome.db', 39 | defaultCsvFileName: 'MusicBee_Export.csv', 40 | csvFilePath: undefined, 41 | dbFilePath: undefined 42 | }; 43 | this.options = options; 44 | this.limit = pLimit(20); 45 | 46 | process.on('SIGINT', async () => await this.restoreDbFile()); 47 | process.on('SIGTERM', async () => await this.restoreDbFile()); 48 | 49 | this.start = dayjs(); 50 | } 51 | 52 | /** 53 | * check/set files paths, backup DB file, connect to it and get navidrome user 54 | * @param action 55 | * @returns {Promise} 56 | */ 57 | initiate = async action => { 58 | const { options, paths } = this; 59 | if (Object.keys(options).length) { 60 | console.log(`MBNDS v${packageJson.version} running with following options:`, options); 61 | } 62 | 63 | if (action === 'fullSync') { 64 | paths.csvFilePath = options.csv ?? path.join(paths.defaultWorkingDirectory, paths.defaultCsvFileName); 65 | if (!fs.existsSync(paths.csvFilePath)) { 66 | throw new Error('CSV file not found'); 67 | } 68 | } 69 | 70 | paths.dbFilePath = options.db ?? path.join(paths.defaultWorkingDirectory, paths.defaultDbFileName); 71 | if (!fs.existsSync(paths.dbFilePath)) { 72 | throw new Error('DB file not found'); 73 | } 74 | 75 | if (options.datetimeFormat && !dayjs(dayjs().format(options.datetimeFormat), options.datetimeFormat).isValid()) { 76 | throw new Error( 77 | `Invalid datetime format : ${options.datetimeFormat}. Please use available formats from https://day.js.org/docs/en/display/format` 78 | ); 79 | } 80 | 81 | this.backupDbFile(); 82 | 83 | this.database = await dbManager.init(paths.dbFilePath); 84 | 85 | this.user = await this.getUser(); 86 | }; 87 | 88 | /** 89 | * by default, get the first user found in ND DB if no option passed 90 | * @returns {Promise} 91 | */ 92 | getUser = async () => { 93 | const { database, options } = this; 94 | 95 | const user = options.user 96 | ? database.prepare('SELECT * FROM user WHERE user_name = ?').get(options.user) 97 | : database.prepare('SELECT * FROM user LIMIT 1').get(); 98 | 99 | if (!user) { 100 | throw new Error(`user ${options.user ?? ''} not found`); 101 | } 102 | return user; 103 | }; 104 | 105 | backupDbFile = () => { 106 | const { paths } = this; 107 | if (!fs.existsSync('./backups')) { 108 | fs.mkdirSync('./backups'); 109 | } 110 | paths.backupFilePath = `./backups/navidrome_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}_backup.db`; 111 | fs.copyFileSync(paths.dbFilePath, paths.backupFilePath); 112 | console.log(`DB has been backed up to ${paths.backupFilePath}`); 113 | }; 114 | 115 | restoreDbFile = async () => { 116 | const { paths } = this; 117 | fs.copyFileSync(paths.backupFilePath, paths.dbFilePath); 118 | try { 119 | this.database.close(); 120 | } catch (_e) {} 121 | for (const ext of ['-shm', '-wal']) { 122 | fs.rmSync(`${paths.dbFilePath}${ext}`, { force: true }); 123 | } 124 | }; 125 | 126 | run = async action => { 127 | await this.initiate(action); 128 | 129 | try { 130 | switch (action) { 131 | case 'fullSync': 132 | await this.fullSync(); 133 | break; 134 | case 'albumsSync': 135 | await this.albumsSync(); 136 | break; 137 | case 'artistsSync': 138 | await this.artistsSync(); 139 | break; 140 | } 141 | 142 | this.database.close(); 143 | console.log(`${action} completed successfully ${dayjs.duration(dayjs().diff(this.start)).humanize(true)}`); 144 | } catch (e) { 145 | await this.globalErrorHander(e); 146 | } 147 | }; 148 | 149 | globalErrorHander = async e => { 150 | console.error('An error as occured, restoring DB file...'); 151 | await this.restoreDbFile(); 152 | throw e; 153 | }; 154 | 155 | /** 156 | * Unified CSV processing function that can either count or process tracks 157 | * @param {('count'|'process')} mode 158 | * @param {[function|null]} [tracksHandler = null] - callback for handling eligible tracks 159 | * @param {object} [options = {}] - additional options like batchSize, totalCount, etc. 160 | * @param {number} [options.batchSize = 500] - batch size for processing mode 161 | * @param {number} [options.totalCount = null] - total count for progress tracking 162 | * @returns {Promise} - number of processed tracks 163 | */ 164 | processCsv = async (mode, tracksHandler = null, options = {}) => { 165 | const { batchSize = 500, totalCount = null } = options; 166 | const { options: syncOptions, paths } = this; 167 | let headerProcessed = false; 168 | let processedCount = 0; 169 | const currentBatch = []; 170 | let progressBar = null; 171 | 172 | const colParser = { 173 | playCount: 'number', 174 | rating: item => { 175 | let rating = Number.parseInt(item, 10); 176 | if (!rating) { 177 | return 0; 178 | } 179 | if (rating > 5 && rating <= 100) { 180 | rating = Math.round(rating / 20); 181 | } 182 | return rating; 183 | }, 184 | lastPlayed: item => 185 | dayjs(item, syncOptions.datetimeFormat).isValid() ? dayjs(item, syncOptions.datetimeFormat).utc() : null, 186 | love: item => (item?.trim() ? 1 : 0) 187 | }; 188 | 189 | if (mode === 'process') { 190 | if (!tracksHandler) { 191 | throw new Error('trackHandler is required for processing mode'); 192 | } 193 | if (!totalCount) { 194 | throw new Error('totalCount is required for processing mode'); 195 | } 196 | 197 | if (!syncOptions.verbose) { 198 | progressBar = new cliProgress.SingleBar( 199 | { etaBuffer: Math.max(100, Math.floor(totalCount * 0.1)) }, 200 | cliProgress.Presets.shades_classic 201 | ); 202 | } 203 | 204 | colParser.albumRating = 'number'; 205 | colParser.playCount = 'number'; 206 | colParser.skipCount = 'number'; 207 | colParser.dateAdded = item => 208 | dayjs(item, syncOptions.datetimeFormat).isValid() ? dayjs(item, syncOptions.datetimeFormat).utc() : null; 209 | colParser.dateModified = item => 210 | dayjs(item, syncOptions.datetimeFormat).isValid() ? dayjs(item, syncOptions.datetimeFormat).utc() : null; 211 | } 212 | 213 | progressBar?.start(totalCount, 0); 214 | const incrementProgress = () => progressBar?.increment(); 215 | 216 | await csv2json({ 217 | delimiter: 'auto', 218 | colParser 219 | }) 220 | .preFileLine((fileLineString, lineIdx) => { 221 | if (lineIdx === 0 && !headerProcessed) { 222 | this.REQUIRED_HEADERS.forEach(header => { 223 | if (!camelCase(fileLineString).includes(camelCase(header))) { 224 | throw new Error(`${header} missing in your CSV headers`); 225 | } 226 | }); 227 | headerProcessed = true; 228 | return camelCase(fileLineString.replace(/<|>/g, '')); 229 | } 230 | return fileLineString; 231 | }) 232 | .subscribe(async track => { 233 | const trackEligible = !!track.playCount || !!track.rating || !!track.lastPlayed || !!track.love; 234 | if (!trackEligible) { 235 | return; 236 | } 237 | 238 | if (mode === 'count' || !tracksHandler) { 239 | processedCount++; 240 | return; 241 | } 242 | 243 | currentBatch.push(track); 244 | 245 | if (currentBatch.length >= batchSize) { 246 | await tracksHandler([...currentBatch], incrementProgress); 247 | processedCount += currentBatch.length; 248 | currentBatch.length = 0; 249 | } 250 | }) 251 | .fromFile(paths.csvFilePath); 252 | 253 | if (mode === 'process' && currentBatch.length > 0) { 254 | await tracksHandler(currentBatch, incrementProgress); 255 | processedCount += currentBatch.length; 256 | } 257 | 258 | progressBar?.stop(); 259 | return processedCount; 260 | }; 261 | 262 | fullSync = async () => { 263 | const { options, user, database, paths, limit } = this; 264 | 265 | let trackUpdatedCount = 0; 266 | let notFoundTracksCount = 0; 267 | 268 | const totalEligibleTracks = await this.processCsv('count'); 269 | console.log(`${paths.csvFilePath} parsed successfully, ${totalEligibleTracks} potential tracks to be updated`); 270 | 271 | console.log('Processing tracks...'); 272 | 273 | await this.processCsv( 274 | 'process', 275 | /** 276 | * @param {object[]} trackBatch 277 | * @param {function} incrementProgress 278 | */ 279 | async (trackBatch, incrementProgress) => { 280 | await Promise.all( 281 | trackBatch.map(track => 282 | limit(async () => { 283 | incrementProgress?.(); 284 | 285 | const foundTracks = database.query( 286 | ` 287 | SELECT 288 | mf.id, 289 | mf.path, 290 | mf.title, 291 | mf.album, 292 | mf.album_id, 293 | mf.artist_id, 294 | mf.album_artist, 295 | mf.album_artist_id, 296 | a.play_count as annotation_play_count, 297 | a.play_date as annotation_play_date, 298 | a.rating as annotation_rating, 299 | a.starred as annotation_starred, 300 | a.starred_at as annotation_starred_at 301 | FROM media_file mf 302 | LEFT JOIN annotation a ON ( 303 | a.item_id = mf.id 304 | AND a.item_type = 'media_file' 305 | AND a.user_id = ? 306 | ) 307 | WHERE mf.title = ? 308 | AND mf.path LIKE ? 309 | `, 310 | [user.id, track.title, `%${track.filename}`] 311 | ); 312 | const foundTrack = findBestMatch(track, foundTracks); 313 | 314 | if (!foundTrack) { 315 | notFoundTracksCount++; 316 | if (options.verbose || options.showNotFound) { 317 | console.error(`track not found. path: ${track.filePath} | filename: ${track.filename}`); 318 | } 319 | return; 320 | } 321 | 322 | if (options.verbose) { 323 | console.log(`processing track: ${track.filePath}`); 324 | } 325 | 326 | const hasExistingAnnotation = foundTrack.annotation_play_count !== null || foundTrack.annotation_rating !== null; 327 | 328 | const annotation = { 329 | play_count: foundTrack.annotation_play_count || 0, 330 | play_date: foundTrack.annotation_play_date, 331 | rating: foundTrack.annotation_rating || 0, 332 | starred: foundTrack.annotation_starred || 0, 333 | starred_at: foundTrack.annotation_starred_at 334 | }; 335 | 336 | const update = {}; 337 | if (track.rating > annotation.rating) { 338 | update.rating = track.rating; 339 | } 340 | if (track.love > annotation.starred) { 341 | update.starred = track.love; 342 | update.starred_at = track.lastPlayed || null; 343 | } 344 | if (track.playCount !== annotation.play_count) { 345 | if (track.playCount > annotation.play_count) { 346 | update.play_count = track.playCount; 347 | } 348 | if (options.first && annotation.play_count + track.playCount > annotation.play_count) { 349 | update.play_count = annotation.play_count + track.playCount; 350 | } 351 | } 352 | 353 | if (isDateAfter(track.lastPlayed, annotation.play_date)) { 354 | update.play_date = track.lastPlayed; 355 | if (!annotation.play_count && !update.play_count && !track.skipCount && !track.playCount) { 356 | update.play_count = 1; 357 | } 358 | } 359 | 360 | if (!Object.keys(update).length) { 361 | return; 362 | } 363 | 364 | await database.upsertAnnotation({ 365 | itemType: 'media_file', 366 | userId: user.id, 367 | itemId: foundTrack.id, 368 | update, 369 | needsCreate: !hasExistingAnnotation 370 | }); 371 | trackUpdatedCount++; 372 | }) 373 | ) 374 | ); 375 | }, 376 | { totalCount: totalEligibleTracks } 377 | ); 378 | console.log(`${trackUpdatedCount} tracks updated`); 379 | 380 | if (notFoundTracksCount > 0) { 381 | console.warn(`${notFoundTracksCount} tracks not found`); 382 | } 383 | 384 | await this.albumsSync(); 385 | 386 | await this.artistsSync(); 387 | }; 388 | 389 | /** 390 | * Get album statistics with existing annotations in one efficient query 391 | */ 392 | getAlbumsWithStats = async (user, albumIds = null) => { 393 | const { database } = this; 394 | 395 | let whereClause = ''; 396 | if (albumIds?.length) { 397 | whereClause = `AND a.id IN (${albumIds.map(() => '?').join(',')})`; 398 | } 399 | 400 | const query = ` 401 | SELECT 402 | a.id AS album_id, 403 | a.name, 404 | COUNT(mf.id) AS total_tracks, 405 | SUM(COALESCE(ta.play_count, 0)) AS total_tracks_play_count, 406 | SUM(CASE WHEN ta.rating IS NULL OR ta.rating = 0 THEN 0 ELSE 1 END) AS tracks_rated_count, 407 | SUM(COALESCE(ta.rating, 0)) AS tracks_rating_sum, 408 | MAX(ta.play_date) AS tracks_last_played, 409 | MAX(aa.rating) AS album_rating, 410 | MAX(aa.play_count) AS album_play_count, 411 | MAX(aa.play_date) AS album_last_played 412 | FROM album a 413 | INNER JOIN media_file mf ON mf.album_id = a.id 414 | LEFT JOIN annotation ta ON ( 415 | ta.item_id = mf.id 416 | AND ta.item_type = 'media_file' 417 | AND ta.user_id = ? 418 | ) 419 | LEFT JOIN annotation aa ON ( 420 | aa.item_id = a.id 421 | AND aa.item_type = 'album' 422 | AND aa.user_id = ? 423 | ) 424 | WHERE 1=1 ${whereClause} 425 | GROUP BY a.id, a.name 426 | HAVING total_tracks_play_count > 0 OR tracks_rated_count > 0 OR tracks_last_played IS NOT NULL 427 | `; 428 | 429 | const params = [user.id, user.id]; 430 | if (albumIds?.length) { 431 | params.push(...albumIds); 432 | } 433 | 434 | const results = database.query(query, params); 435 | 436 | return results; 437 | }; 438 | 439 | /** 440 | * @param {Set|null} albumsToUpdate 441 | * @returns {Promise} 442 | */ 443 | albumsSync = async (albumsToUpdate = null) => { 444 | const { options, user, database, limit } = this; 445 | 446 | console.log('Processing albums...'); 447 | 448 | const albumsData = await this.getAlbumsWithStats(user, albumsToUpdate ? [...albumsToUpdate] : null); 449 | 450 | if (albumsData.length === 0) { 451 | console.log('0 albums updated'); 452 | return 0; 453 | } 454 | 455 | const progressBar = options.verbose 456 | ? null 457 | : new cliProgress.SingleBar( 458 | { etaBuffer: Math.max(100, Math.floor(albumsData.length * 0.1)) }, 459 | cliProgress.Presets.shades_classic 460 | ); 461 | progressBar?.start(albumsData.length, 0); 462 | 463 | let albumUpdatedCount = 0; 464 | 465 | await Promise.all( 466 | albumsData.map(albumData => 467 | limit(async () => { 468 | progressBar?.increment(); 469 | 470 | const needsCreate = albumData.album_play_count === null && albumData.album_rating === null; 471 | 472 | const update = {}; 473 | const currentPlayCount = albumData.album_play_count || 0; 474 | const currentRating = albumData.album_rating || 0; 475 | const currentPlayDate = albumData.album_last_played; 476 | 477 | if (albumData.total_tracks_play_count > currentPlayCount) { 478 | update.play_count = albumData.total_tracks_play_count; 479 | } 480 | 481 | if (albumData.tracks_rated_count > albumData.total_tracks * 0.5) { 482 | const newRating = Math.round(albumData.tracks_rating_sum / albumData.tracks_rated_count); 483 | if (newRating > currentRating) { 484 | update.rating = newRating; 485 | } 486 | } 487 | 488 | if (isDateAfter(albumData.tracks_last_played, currentPlayDate)) { 489 | update.play_date = albumData.tracks_last_played; 490 | } 491 | 492 | if (!Object.keys(update).length) { 493 | return; 494 | } 495 | 496 | await database.upsertAnnotation({ 497 | itemType: 'album', 498 | userId: user.id, 499 | itemId: albumData.album_id, 500 | update, 501 | needsCreate 502 | }); 503 | 504 | albumUpdatedCount++; 505 | 506 | if (options.verbose) { 507 | console.log(`Updated album: ${albumData.name}`); 508 | } 509 | }) 510 | ) 511 | ); 512 | 513 | progressBar?.stop(); 514 | console.log(`${albumUpdatedCount} albums updated`); 515 | return albumUpdatedCount; 516 | }; 517 | 518 | /** 519 | * Get artist statistics with existing annotations - handles both old and new schema 520 | */ 521 | getArtistsWithStats = async (user, artistIds = null) => { 522 | const { database } = this; 523 | 524 | let whereClause = ''; 525 | if (artistIds?.length) { 526 | whereClause = `AND ar.id IN (${artistIds.map(() => '?').join(',')})`; 527 | } 528 | 529 | const hasMediaFileArtists = database.hasMediaFileArtistsTable(); 530 | 531 | if (this.options.verbose) { 532 | console.log( 533 | `Using ${hasMediaFileArtists ? 'new' : 'old'} artist schema (${ 534 | hasMediaFileArtists ? 'media_file_artist junction table' : 'direct artist_id' 535 | })` 536 | ); 537 | } 538 | 539 | const { joinClause, countColumn, annotationJoin } = hasMediaFileArtists 540 | ? { 541 | joinClause: `INNER JOIN media_file_artists mfa ON (mfa.artist_id = ar.id AND mfa.role = 'artist')`, 542 | countColumn: 'COUNT(mfa.media_file_id) AS total_tracks', 543 | annotationJoin: `LEFT JOIN annotation ta ON ( 544 | ta.item_id = mfa.media_file_id 545 | AND ta.item_type = 'media_file' 546 | AND ta.user_id = ? 547 | )` 548 | } 549 | : { 550 | joinClause: 'INNER JOIN media_file mf ON mf.artist_id = ar.id', 551 | countColumn: 'COUNT(mf.id) AS total_tracks', 552 | annotationJoin: `LEFT JOIN annotation ta ON ( 553 | ta.item_id = mf.id 554 | AND ta.item_type = 'media_file' 555 | AND ta.user_id = ? 556 | )` 557 | }; 558 | 559 | const query = ` 560 | SELECT 561 | ar.id AS artist_id, 562 | ar.name, 563 | ${countColumn}, 564 | SUM(COALESCE(ta.play_count, 0)) AS total_tracks_play_count, 565 | SUM(CASE WHEN ta.rating IS NULL OR ta.rating = 0 THEN 0 ELSE 1 END) AS tracks_rated_count, 566 | SUM(COALESCE(ta.rating, 0)) AS tracks_rating_sum, 567 | MAX(ta.play_date) AS tracks_last_played, 568 | MAX(aa.rating) AS artist_rating, 569 | MAX(aa.play_count) AS artist_play_count, 570 | MAX(aa.play_date) AS artist_last_played 571 | FROM artist ar 572 | ${joinClause} 573 | ${annotationJoin} 574 | LEFT JOIN annotation aa ON ( 575 | aa.item_id = ar.id 576 | AND aa.item_type = 'artist' 577 | AND aa.user_id = ? 578 | ) 579 | WHERE 1=1 ${whereClause} 580 | GROUP BY ar.id, ar.name 581 | HAVING total_tracks_play_count > 0 OR tracks_rated_count > 0 OR tracks_last_played IS NOT NULL 582 | `; 583 | 584 | const params = [user.id, user.id]; 585 | if (artistIds?.length) { 586 | params.push(...artistIds); 587 | } 588 | 589 | const results = database.query(query, params); 590 | 591 | return results; 592 | }; 593 | 594 | /** 595 | * @param {Set|null} artistsToUpdate 596 | * @returns {Promise} 597 | */ 598 | artistsSync = async (artistsToUpdate = null) => { 599 | const { options, user, database, limit } = this; 600 | 601 | console.log('Processing artists...'); 602 | 603 | const artistsData = await this.getArtistsWithStats(user, artistsToUpdate ? [...artistsToUpdate] : null); 604 | 605 | if (artistsData.length === 0) { 606 | console.log('0 artists updated'); 607 | return 0; 608 | } 609 | 610 | const progressBar = options.verbose 611 | ? null 612 | : new cliProgress.SingleBar( 613 | { etaBuffer: Math.max(100, Math.floor(artistsData.length * 0.1)) }, 614 | cliProgress.Presets.shades_classic 615 | ); 616 | progressBar?.start(artistsData.length, 0); 617 | 618 | let artistUpdatedCount = 0; 619 | 620 | await Promise.all( 621 | artistsData.map(artistData => 622 | limit(async () => { 623 | progressBar?.increment(); 624 | 625 | const needsCreate = artistData.artist_play_count === null && artistData.artist_rating === null; 626 | 627 | const update = {}; 628 | const currentPlayCount = artistData.artist_play_count || 0; 629 | const currentRating = artistData.artist_rating || 0; 630 | const currentPlayDate = artistData.artist_last_played; 631 | 632 | if (artistData.total_tracks_play_count > currentPlayCount) { 633 | update.play_count = artistData.total_tracks_play_count; 634 | } 635 | 636 | if (artistData.total_tracks > 1 && artistData.tracks_rated_count > artistData.total_tracks * 0.5) { 637 | const newRating = Math.round(artistData.tracks_rating_sum / artistData.tracks_rated_count); 638 | if (newRating > currentRating) { 639 | update.rating = newRating; 640 | } 641 | } 642 | 643 | if (isDateAfter(artistData.tracks_last_played, currentPlayDate)) { 644 | update.play_date = artistData.tracks_last_played; 645 | } 646 | 647 | if (!Object.keys(update).length) { 648 | return; 649 | } 650 | 651 | await database.upsertAnnotation({ 652 | itemType: 'artist', 653 | userId: user.id, 654 | itemId: artistData.artist_id, 655 | update, 656 | needsCreate 657 | }); 658 | 659 | artistUpdatedCount++; 660 | 661 | if (options.verbose) { 662 | console.log(`Updated artist: ${artistData.name}`); 663 | } 664 | }) 665 | ) 666 | ); 667 | 668 | progressBar?.stop(); 669 | console.log(`${artistUpdatedCount} artists updated`); 670 | return artistUpdatedCount; 671 | }; 672 | } 673 | 674 | export { MBNDSynchronizer }; 675 | -------------------------------------------------------------------------------- /LICENCE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------