Compare commits

...

230 Commits

Author SHA1 Message Date
80b4b80508 update readme 2023-12-21 16:56:53 -05:00
f48c77e70a removed submodule 2023-12-21 16:50:58 -05:00
RemixDev
5d447b6035
Added macOS arm64 build 2022-12-14 14:23:04 +01:00
RemixDev
22f16a2c20
Updated electron 2022-12-14 14:17:16 +01:00
RemixDev
4c537a47dd
Updated dependencies 2022-12-14 13:46:22 +01:00
RemixDev
2d19cccebd Updated dependencies 2022-12-14 13:46:14 +01:00
RemixDev
1d778b2e45 Updated pt-br 2022-12-14 13:02:35 +01:00
RemixDev
c2b910c826 Merge branch 'main' into 'main'
Update

See merge request RemixDev/deemix-webui!43
2022-11-28 19:26:58 +00:00
Justman10000
c1ff8b3b59 Update german 2022-11-28 15:41:58 +00:00
RemixDev
80357584d2 Merge branch 'smowtenshi-main-patch-95763' into 'main'
Update officialRepo, since git.freezer.life is not available

See merge request RemixDev/deemix-webui!42
2022-11-22 21:00:24 +00:00
RemixDev
4c97f2e2da Small update to README.md 2022-11-22 20:59:34 +00:00
RemixDev
b5ec1894de Merge branch 'main' into 'main'
Update

See merge request RemixDev/deemix-gui!7
2022-11-22 20:58:52 +00:00
Justman10000
58cd8b72f6 Update 2022-11-22 20:58:52 +00:00
smow
0a39222b69 Update officialRepo, since git.freezer.life is not available 2022-10-15 13:17:27 +00:00
RemixDev
06305de9cf
Added retry function 2022-08-19 23:50:05 +02:00
RemixDev
12d6cafdd0
Added can't stream error before adding to queue 2022-08-19 23:49:53 +02:00
RemixDev
59d8222177
Updated libraries 2022-08-19 21:22:11 +02:00
RemixDev
f88bfebe02
Fixed typescript lint issues 2022-08-19 21:21:58 +02:00
RemixDev
88ee7ad976
Fixed isUpdateAvailable not working properly 2022-08-10 17:38:58 +02:00
RemixDev
8fa789170d
Fixed tailwind not being loaded 2022-07-30 11:01:22 +02:00
RemixDev
8fb89af4a9
Fixed server passing the wrong argument to the webui when using electron 2022-07-30 10:11:54 +02:00
RemixDev
cb8ab5cfae
Added support for reverse proxy and routing managed by vue
Use --locationbase to specify the path used by the reverse proxy
Updated deezer-js to 1.3.8
2022-07-30 00:23:48 +02:00
RemixDev
2a32e772dd
Updated dependencies 2022-07-29 20:07:56 +02:00
RemixDev
554dfcced7
Move /connect to /api/connect 2022-07-29 20:05:27 +02:00
RemixDev
a752a63e0e Updated libraries and webui 2022-05-28 15:52:54 +02:00
RemixDev
6d771b1faf Fix crash when using old queue files 2022-05-28 15:50:17 +02:00
RemixDev
516eb2557f Fix crash with wrong spotify username 2022-05-28 15:49:26 +02:00
RemixDev
f279ed43b5 Removed unused preload channels 2022-05-28 15:22:40 +02:00
RemixDev
475ccfc850 Fixed download issues on slow internet connections 2022-04-28 11:55:51 +02:00
RemixDev
dedb938bd5 webui: Fixed charts not working
server: Updated deemix library
2022-04-27 17:32:41 +02:00
RemixDev
784c08765a Added environment variable for singleuser 2022-03-10 22:30:55 +01:00
RemixDev
c8f02b310d Added --singleuser flag to server
replaces the old --serverwide-arl flag of deemix-pyweb
it's always off on the gui
2022-03-09 12:34:18 +01:00
RemixDev
79d602a490 Fixed get favorite tracks 2022-03-09 11:22:14 +01:00
RemixDev
0f9362c6ca Fixed sourcemap generation script 2022-03-09 11:21:46 +01:00
RemixDev
141341c28d Fixed getTracklist with private playlists 2022-03-08 16:11:08 +01:00
RemixDev
c02ddfbc9f Fixed restore of corrupted queue 2022-03-08 16:07:20 +01:00
RemixDev
73ae96c555 Fix bitrate dropdown 2022-03-05 20:51:35 +01:00
RemixDev
83b5675df3 Fixed undefined getSlimmedDict error 2022-03-05 14:01:36 +01:00
RemixDev
0a880bc245 Added clearQueueOnExit option
updated webui to v1.9.2
2022-03-05 13:39:13 +01:00
RemixDev
90799bd1f9 Fixed webpack config 2022-03-05 13:17:45 +01:00
RemixDev
4e78dc09d4 Updated libraries 2022-03-05 11:57:21 +01:00
RemixDev
a0746f088f added sourcemap option for webpack 2022-03-05 11:40:50 +01:00
RemixDev
504b7e06b5 Catch errors in search
Closes #53
2022-03-01 11:17:37 +01:00
RemixDev
1e14eb5b6b Added logging system 2022-02-28 14:58:25 +01:00
RemixDev
e1f7451e51 Fixed #52 2022-02-28 14:37:49 +01:00
RemixDev
ff4e20c6f4 Added deezer unreachable differentiation to the vpn warning 2022-02-12 14:36:02 +01:00
RemixDev
86d8853863 updated webui 2022-02-09 14:43:26 +01:00
RemixDev
877793da2f cleanup of package.json and server/package.json 2022-02-09 14:29:13 +01:00
RemixDev
c58df61ccc Fixed version checking issue 2022-02-05 11:44:36 +01:00
RemixDev
174f7b999b Added missing WebSocket import 2022-02-05 09:50:42 +01:00
RemixDev
9ff4aeace5 removed dist files from the repo 2022-02-05 01:17:12 +01:00
RemixDev
87164f0644 Major code rework 2022-02-05 01:15:26 +01:00
RemixDev
5d29424c3a Added patch for broken order.json
updated webui to 1.9.1
2022-02-01 21:56:05 +01:00
RemixDev
e6a8b0f65b fixed default bitrate being null 2022-01-13 09:42:31 +01:00
RemixDev
1563272d92 Added autoCheckForUpdates opt-in option in settings 2022-01-13 01:51:21 +01:00
RemixDev
b9e2fd298e Added update checker 2022-01-13 01:33:29 +01:00
RemixDev
018b008915 Removed extra logging 2022-01-13 01:27:30 +01:00
RemixDev
bb6e4bec0d Made POST requests actual post requests 2022-01-13 01:27:08 +01:00
RemixDev
62cb39f154 updated webui 2022-01-12 19:42:07 +01:00
RemixDev
89618c89a4 Fixed login hang issue 2022-01-08 10:59:26 +01:00
RemixDev
cbe3604142 fixed parse errors when loading the queue 2022-01-06 16:42:32 +01:00
RemixDev
a5c188f60c updated deemix lib 2022-01-06 16:41:57 +01:00
RemixDev
75c6d4dad7 Updated deemix and webui version 2022-01-04 23:22:09 +01:00
RemixDev
133c12af04 Fixed ERR_HTTP_HEADERS_SENT when loading charts 2022-01-04 23:21:53 +01:00
RemixDev
310c063055 library update 2022-01-02 14:24:44 +01:00
RemixDev
f8212f1969 fixed "start" changeCase with titles with only one parenthesis as word 2021-12-30 20:29:36 +01:00
RemixDev
63b591e57e added fix for loved tracks download 2021-12-29 18:49:30 +01:00
RemixDev
e98087c34a updated libraries
fixed some minor issues
2021-12-23 23:26:04 +01:00
RemixDev
d8a82d0bd5 Added the new options to the webui 2021-12-23 19:50:34 +01:00
RemixDev
90b2d987d8 updated deemix to 3.6.0 2021-12-23 17:14:28 +01:00
RemixDev
294411d3b9 updated libs and webui build 2021-12-21 17:56:24 +01:00
RemixDev
70a6584129 fixed login with incorrect email and password 2021-12-21 17:55:53 +01:00
RemixDev
af11277aa6 updated server dependencies 2021-12-15 07:33:15 +01:00
RemixDev
510146eab3 Use private api to load favorites 2021-12-07 13:46:42 +01:00
RemixDev
944e541d03 Updated deezer lib 2021-10-28 15:30:30 +02:00
RemixDev
3f75c520cc Clear session if login didn't complete 2021-10-28 15:29:16 +02:00
RemixDev
744824cde5 WebUI build 1.8.8 2021-10-28 15:28:47 +02:00
RemixDev
c03b84fee7 WebUI build 1.8.7 2021-10-05 14:36:45 +02:00
RemixDev
abf7e7f077 Updated deemix lib to 3.5.4 2021-09-30 19:02:43 +02:00
RemixDev
e0cd9c2669 Updated deemix lib to 3.5.3 2021-09-30 17:32:16 +02:00
RemixDev
27bd014a74 Quickfix for VPN error message 2021-09-30 17:17:43 +02:00
RemixDev
2ca766a9e7 webui: added user license and country under username in settings
updated deemix lib to 3.5.2
2021-09-23 14:49:02 +02:00
RemixDev
06329e64ad Updated deemix lib to 3.5.1 2021-09-22 16:45:25 +02:00
RemixDev
52da8b75ec Updated deemix lib to 3.5.0
Updated webui to 1.8.6
2021-09-21 18:52:20 +02:00
RemixDev
d73a235939 Added back child accounts dropdown 2021-08-18 14:59:49 +02:00
Roberto Tonino
fb738d5326 build(server): updated version; build(webui): v1.8.5 2021-08-11 15:26:48 +02:00
Roberto Tonino
43568713b6 feat(server): added spotifyStatus endpoint to get spotify plugin status; feat(server): added plugin information on connect endpoint 2021-08-11 15:25:02 +02:00
Roberto Tonino
94f79b4a8c build(webui): v1.8.4 2021-08-11 12:19:13 +02:00
RemixDev
869fa54f7a Updated deemix lib to 3.4.0 2021-08-02 23:59:48 +02:00
Roberto Tonino
04ad6ed400 build(webui): v1.8.3 2021-08-01 09:41:36 +02:00
RemixDev
3d5ba13b76 deemix lib 3.3.6 2021-07-28 14:24:35 +02:00
RemixDev
beba1c39bb Updated deemix lib to 3.3.5 2021-07-28 13:22:35 +02:00
RemixDev
6191439f1d Server build and webui update 2021-07-27 21:25:07 +02:00
RemixDev
91c7163402 Updated deemix lib to 3.3.4 2021-07-27 21:24:57 +02:00
RemixDev
ac13f3c096 Added fix for empty playlists 2021-07-27 20:34:30 +02:00
RemixDev
873b2b044d Disabled option executeCommand from api and webui for security reasons 2021-07-27 20:34:03 +02:00
RemixDev
af74eb36bd Fixed family account users not being able to log in 2021-07-25 20:09:01 +02:00
RemixDev
39911c6eb6 Updated deemix lib to 3.3.3
Hopefully all issues are gone
2021-07-25 16:58:44 +02:00
RemixDev
8698f3b563 Updated deemix lib to 3.3.2 2021-07-25 13:24:51 +02:00
RemixDev
9cbd52353c Updated deemix lib to 3.3.1
Electron build still doesn't work
2021-07-25 11:51:52 +02:00
RemixDev
fc43e7f6e9 Updated deemix lib to 3.2.1
Electron build doesn't work yet, server does
2021-07-20 15:00:45 +02:00
RemixDev
c489d274cc Fixed server builds 2021-07-20 14:52:01 +02:00
RemixDev
cb86be2b0c Updated deemix lib to 3.1.0 2021-07-19 18:47:16 +02:00
RemixDev
c65eb71952 Fixed month in version number 2021-07-19 16:34:30 +02:00
Roberto Tonino
a48e48e37b build(webui): v1.8.1 2021-07-19 10:56:18 +02:00
RemixDev
5f7a02a6f5 Changed version scripts to run on win and macos as well 2021-07-18 22:29:07 +02:00
RemixDev
4604f2176e Added automatic app versioning system 2021-07-18 21:59:41 +02:00
Roberto Tonino
74fcaa625c workflow: added root dev script 2021-07-17 15:17:29 +02:00
Roberto Tonino
96a1ac22b0 workflow(server): added predist script, now running just yarn dist will do everything needed 2021-07-17 15:11:17 +02:00
Roberto Tonino
94755a47a9 feat(server): switched DEEMIX_PORT to DEEMIX_SERVER_PORT, this closes #10 (breaking change) 2021-07-17 14:57:20 +02:00
Roberto Tonino
74f654fa6e build(webui): v1.8.0 2021-07-17 14:37:43 +02:00
RemixDev
ceaf5bd009 Merge branch 'lidarr' into 'main'
Webpack server and Lidarr support

See merge request RemixDev/deemix-gui!3
2021-07-16 10:39:32 +00:00
kermit
a903ba6444 Extra endpoints for lidarr 2021-07-16 11:35:54 +01:00
kermit
698ef1f9df Pack server with webpack 2021-07-13 19:23:12 +01:00
RemixDev
52aa1c2da5 Updated deemix lib to 3.0.3 2021-07-12 17:03:34 +02:00
RemixDev
312423e2a4 Added retry for deezer availability check and log error's traceback 2021-07-03 13:03:56 +02:00
RemixDev
d6bf3678f4 Re-added paste-in functionality for newline separated link lists
Library patch update
2021-07-03 11:10:07 +02:00
RemixDev
46980af0b6 Added pkg to build standalone server 2021-07-02 12:37:02 +02:00
RemixDev
2a005b513f Changed default host from localhost to 127.0.0.1
Made dev shortcuts not global
Added host and port arguments in electron launcher
2021-06-29 15:58:25 +02:00
RemixDev
00e2d0724b Builded server with latest changes 2021-06-29 00:10:02 +02:00
RemixDev
6183f9b7a6 Added correct deemix lib version + check deezer availability 2021-06-29 00:06:11 +02:00
RemixDev
9b157c42bc Fixed spotify playlist 20 entries limit 2021-06-27 11:50:00 +02:00
RemixDev
ea9d045075 Updated deemix lib to 0.2.5 2021-06-23 14:48:48 +02:00
RemixDev
b0292553f3 Updated deemix lib to 0.2.4 2021-06-19 12:04:42 +02:00
RemixDev
607d8c3530 Updated deemix to 0.2.3 2021-06-19 01:42:58 +02:00
RemixDev
d546eff21f Merge branch 'dev/unify-server-with-root' into 'main'
Dev/unify server with root

See merge request RemixDev/deemix-gui!2
2021-06-16 13:41:37 +00:00
RemixDev
70420b79fe Add deb target to linux build as well 2021-06-16 15:37:33 +02:00
RemixDev
752f05ac3b updated deemix lib version 2021-06-16 15:36:55 +02:00
Roberto Tonino
368232a843 feat: moved all server deps to root folder 2021-06-14 19:31:21 +02:00
RemixDev
d490033d58 Updated lib and fixed spotify playlists in favorite tab 2021-06-09 12:57:30 +02:00
RemixDev
e0ba538c0a Updated deemix lib to v0.2.0 2021-06-08 19:56:53 +02:00
RemixDev
8218ceee25 [webui] fixed download bar 2021-06-05 19:05:04 +02:00
RemixDev
1ee3657093 Added better logging for itemgen errors 2021-06-05 18:41:13 +02:00
RemixDev
6dbbe7c55f Fixed electron-builder builds 2021-06-05 16:37:06 +02:00
RemixDev
cd6a2e5d02 Fixed open download folder 2021-06-05 14:39:41 +02:00
RemixDev
aa3670bec1 Fixed lint issues 2021-06-05 13:58:50 +02:00
Roberto Tonino
e3e41f775f build(webui): v1.7.0; feat(webui): logs tab 2021-06-04 23:19:11 +02:00
Roberto Tonino
4999207a6e chore(server): console feedback at server listening event 2021-06-04 21:37:27 +02:00
Roberto Tonino
6617ece90c feat(server): support for --host flag 2021-06-04 21:29:55 +02:00
Roberto Tonino
c67e507667 tet(webui): added unit tests for utils 2021-06-02 17:52:34 +02:00
Roberto Tonino
d05a585094 build(server): tagged v0.1.0 (started server versioning) 2021-06-02 17:52:23 +02:00
Roberto Tonino
4005e6dab5 chore: webui sync 2021-06-02 16:49:15 +02:00
Roberto Tonino
c7f74ed6ce feat: implemented untested changeAccount logic 2021-06-02 16:46:20 +02:00
Roberto Tonino
10e1346521 chore: moved .yarnrc to the root of the project 2021-06-02 16:31:56 +02:00
Roberto Tonino
222455faee build(webui): v1.6.3 2021-06-02 16:28:01 +02:00
Roberto Tonino
0507806561 feat(webui): implemented link analyzer; fix(webui): removed blocking fetch responses if not ok 2021-06-02 15:34:45 +02:00
Roberto Tonino
d574d96885 fix(server): login-arl tests [skip ci] 2021-06-01 23:06:46 +02:00
Roberto Tonino
a9fe54eb72 fix(server): lint errors on main.ts; fix(server): lint script not linting 2021-06-01 22:56:01 +02:00
Roberto Tonino
8d9f79e662 fix(server): lint errors 2021-06-01 22:54:46 +02:00
Roberto Tonino
6dfd28f7a9 fix(server): album search endpoint multiple headers error 2021-06-01 22:41:27 +02:00
Roberto Tonino
cb77745776 feat(server): analyzeLink endpoint; test(server): analyzeLink unit tests; chore(server): linting 2021-06-01 22:35:49 +02:00
RemixDev
ffedd67a11 deemix lib update + prevent log data to reach frontend 2021-06-01 20:26:28 +02:00
RemixDev
3facae6955 Updated deemix lib 2021-05-31 23:27:38 +02:00
RemixDev
1c5b18dc16 Fixed windows nsis build script 2021-05-29 20:53:11 +02:00
RemixDev
40302ff756 Fixed alreadyInQueue not working properly 2021-05-29 20:37:12 +02:00
RemixDev
b0419964f4 Updated README.md 2021-05-29 18:35:40 +02:00
RemixDev
825fc2a204 Added README.md and LICENSE.txt 2021-05-29 18:32:29 +02:00
RemixDev
fba98d44a1 Fixed top result download button not working 2021-05-29 17:41:44 +02:00
RemixDev
972fc007dc updated build scripts 2021-05-29 16:43:23 +02:00
RemixDev
5291cbbd16 Fixed artist download issue 2021-05-29 16:21:00 +02:00
RemixDev
b33601e86a Added windows build script 2021-05-29 14:39:30 +02:00
RemixDev
c35de888fd Added build scripts 2021-05-29 13:58:10 +02:00
RemixDev
13b14c35f9 Added context menu and and electron window state saving 2021-05-29 12:33:20 +02:00
RemixDev
4f549c2fb5 Updated deemix version in package.json 2021-05-29 12:07:43 +02:00
RemixDev
731295a317 Implemented spotify plugin on server 2021-05-29 12:06:26 +02:00
RemixDev
fee34f2b2a Implemented logout and fixed loginWithCredentials 2021-05-28 15:10:53 +02:00
RemixDev
b44a3e9a31 Implemented queue management calls in RESTful api 2021-05-28 14:15:18 +02:00
RemixDev
7417e3c325 Implemented "openDownloadsFolder" and "selectDownloadFolder" 2021-05-28 12:40:06 +02:00
RemixDev
86aa075c8d Added simple electron wrapper 2021-05-23 22:42:16 +02:00
RemixDev
f33cbcb7d0 Fixed tsc build errors 2021-05-23 22:42:02 +02:00
RemixDev
05a892565b Code cleanup 2021-05-23 21:44:26 +02:00
RemixDev
08aefdce77 Added missing async for loginWithCredentials 2021-05-23 21:30:51 +02:00
RemixDev
47559071d6 Added logic to loginWithCredentials 2021-05-23 21:21:24 +02:00
Roberto Tonino
49f4804767 chore(webui): improved fetch operations feedbacks 2021-05-23 21:16:56 +02:00
Roberto Tonino
ea9639c7c2 feat(server): added loginWithCredentials endpoint; feat(webui): added loginWithCredentials call 2021-05-23 20:34:28 +02:00
Roberto Tonino
a1bc3fcbc1 build(webui): v1.6.2 2021-05-23 20:08:06 +02:00
RemixDev
6f7808c91b Added autostart queue after login 2021-05-21 12:34:52 +02:00
RemixDev
b384b4638f Fixed queue restoring issues 2021-05-21 12:34:39 +02:00
RemixDev
b9720ef781 Added support for ; separated urls 2021-05-21 12:34:05 +02:00
Roberto Tonino
6fa5057697 feat(server): bump deemix@0.0.7; wip(webui): queue restoring 2021-05-20 21:23:00 +02:00
Roberto Tonino
6b13916763 feat(webui): added placeholder login form; build(webui): bump to v1.6.1 2021-05-19 21:10:34 +02:00
Roberto Tonino
8574259115 chore(server): linting 2021-05-19 20:41:40 +02:00
RemixDev
57f7f4d6db Updated deemix to 0.0.5 2021-05-16 21:41:00 +02:00
RemixDev
fa6826c554 Implemented removeFromQueue and cancelAllDownloads 2021-05-16 20:11:48 +02:00
RemixDev
de85a39718 Implemented removeFinishedDownloads and started working on queue restore 2021-05-13 23:19:59 +02:00
Roberto Tonino
024d7e3998 workflow: made Makefile cross platform 2021-05-13 21:45:57 +02:00
Roberto Tonino
54cc112a47 workflow: added .gitattributes 2021-05-13 21:39:09 +02:00
RemixDev
021d631ffa Better already in queue check 2021-05-13 21:33:34 +02:00
RemixDev
cc82ee6376 Added broadcast for alreadyInQueue and loginNeededToDownload errors 2021-05-13 21:31:52 +02:00
Roberto Tonino
a82c4c303e feat(server): implemented SPA mode test 2021-05-13 21:29:37 +02:00
Roberto Tonino
a48ca0616b feat(server): implemented SPA mode, needs tests 2021-05-13 21:23:48 +02:00
Roberto Tonino
4a1d655523 chore(server): moved errors to dedicated file 2021-05-13 21:14:35 +02:00
Roberto Tonino
335819b2bb feat(server): added types for saveSettings 2021-05-13 20:59:58 +02:00
Roberto Tonino
669854f799 fix(server): lint errors 2021-05-13 20:47:48 +02:00
RemixDev
6b8e3be014 Added support for artists links 2021-05-13 19:20:22 +02:00
RemixDev
36f23ee87b Webui bump 2021-05-13 18:16:29 +02:00
RemixDev
dbc1e2bcfb Implemented simple queue structure 2021-05-13 18:14:38 +02:00
RemixDev
7b16ddc91a Implemented saveSettings websocket module 2021-05-13 11:40:32 +02:00
Roberto Tonino
a3ef23b289 feat: added empty socket modules for every WebUI listener but link analyzer 2021-05-11 22:11:33 +02:00
Roberto Tonino
c779515e3e chore: replaced @ts-ignore with @ts-expect-error 2021-05-11 21:45:55 +02:00
Roberto Tonino
62bdb71ede feat: websocket modules 2021-05-11 21:45:24 +02:00
Roberto Tonino
8c92f78e52 chore: moved tests folder outside src folder 2021-05-11 21:09:00 +02:00
Roberto Tonino
cbd6bd4791 feat: added on connection websocket server callback 2021-05-11 21:06:45 +02:00
Roberto Tonino
a6fe1bff19 chore: removed IO functor 2021-05-11 20:31:21 +02:00
Roberto Tonino
9fc36abf06 fix: type checking errors; feat: added .yarnrc file; chore: linting 2021-05-11 20:22:07 +02:00
RemixDev
d672b9bc55 Implemented login, autologin; Fixed search and user favorites 2021-05-06 11:52:19 +02:00
RemixDev
dfd66e5164 Implemented user api paths with session 2021-05-05 12:06:24 +02:00
RemixDev
85fcc70948 Added express-session 2021-05-03 17:08:36 +02:00
RemixDev
e54eaa6a00 Moved functions out of main, added getSettings 2021-04-30 14:27:37 +02:00
Roberto Tonino
d55470188c chore(server): added IO functor reference 2021-04-25 00:04:58 +02:00
Roberto Tonino
57987a83d0 chore(server): added functional flavour to error helpers 2021-04-25 00:03:57 +02:00
Roberto Tonino
2433209676 feat(server): implemented getChartTracks api; feat(server): added some error helpers 2021-04-24 21:53:24 +02:00
Roberto Tonino
4919c8d698 test(server): skipped album search test with start param 2021-04-24 21:26:53 +02:00
Roberto Tonino
c9cb976f64 chore(server): removed logs and increased consistency 2021-04-24 21:23:16 +02:00
Roberto Tonino
f83d017688 workflow(server): added login-arl tests 2021-04-24 21:22:38 +02:00
Roberto Tonino
d3e7e5a168 workflow(server): added dotenv dep 2021-04-24 21:12:52 +02:00
Roberto Tonino
2dc9ab66d4 feat(server): implemented login via ARL 2021-04-24 20:59:32 +02:00
Roberto Tonino
7caccd048e workflow: updated deezer-js@0.0.8 2021-04-24 20:35:03 +02:00
Roberto Tonino
4ac6aaddd4 workflow: removed carets from package.json 2021-04-24 20:34:00 +02:00
Roberto Tonino
17f8070dea feat: implemented album search (currently has a failing test) 2021-04-24 20:13:22 +02:00
Roberto Tonino
6f75b17bdb chore(server): added ramda dep 2021-04-24 18:16:08 +02:00
Roberto Tonino
1ecaaba51f chore: linting 2021-04-24 18:08:08 +02:00
Roberto Tonino
29c84cf8b9 Squashed commit of the following:
commit c0148e8301b9d2a987c79d8f49f90e678c75e5a4
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 21:06:02 2021 +0200

    test: disabled logger when in test mode; refactor: type names

commit 418fc5647f2adb97df312eed5eb9c2d17de9d24c
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 20:49:54 2021 +0200

    test: added albumSearch test; chore: removed sample endpoint

commit e2c79f6ee65448b92714bffd5281072279e0b522
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 19:16:25 2021 +0200

    test: added cookie parser test

commit 78d70b7369015cd467f684e636c6788b58c54a7a
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 19:07:44 2021 +0200

    feat: added root path first test

commit eb91ff06d62d81fbfa6851f1dea374addf709582
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 18:45:32 2021 +0200

    feat: added test deps
2021-04-24 18:03:27 +02:00
RemixDev
9800edf68d Added search and tracklist pages 2021-04-22 10:32:41 +02:00
RemixDev
902a9563a6 Added home and charts pages 2021-04-21 21:13:47 +02:00
RemixDev
0b810d7188 Added websocket server 2021-04-18 12:11:51 +02:00
Roberto Tonino
1bf94ea65d Squashed commit of the following:
commit e9e359ca8d8b2d98feefeff4e2fd1ac4a1604f2f
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Fri Apr 9 18:37:25 2021 +0200

    chore: updated patch and minor version deps

commit a9db754ba5623ee7ae5f171c891f4e572e6b5f22
Author: Roberto Tonino <roberto.tonino5@gmail.com>
Date:   Sat Apr 3 19:58:19 2021 +0200

    feat: added blank route files
2021-04-09 18:38:35 +02:00
Roberto Tonino
8e4e2ff5eb feat: refactored server to use ts and improved folder structure 2021-04-03 19:46:54 +02:00
Roberto Tonino
f98abb384c chore: added IDE exceptions to .gitignore 2021-03-26 22:38:12 +01:00
RemixDev
c20041aee7 Initial commit 2021-03-26 13:29:10 +01:00
289 changed files with 20169 additions and 4973 deletions

94
.gitignore vendored
View File

@ -1,37 +1,73 @@
__pycache__ # Logs
*/__pycache__ logs
*.log
.DS_Store
node_modules
# pyinstaller build dirs
/dist
/build
# local env files
/env/
/venv/
.env.local
.env.*.local
# Log files
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
# Editor directories and files # Runtime data
# .vscode pids
.idea *.pid
*.suo *.seed
*.ntvs* *.pid.lock
*.njsproj
*.sln
*.sw?
# Private configs # Directory for instrumented libs generated by jscoverage/JSCover
/config.py lib-cov
tailwind.config.full.js
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# next.js build output
.next
# IDE
.vscode
.idea
# development # development
*.map *.map
public/js/bundle.js dev.sh
# distribution
dist/*
server-dist/*

1
.yarnrc Normal file
View File

@ -0,0 +1 @@
save-prefix: ""

View File

@ -1,20 +1,38 @@
# deemix-webui # Deemixer
This is just the WebUI for deemix, it should be used with deemix-gui or something like that. This is forked from [deemix-webui](https://gitlab.com/RemixDev/deemix-webui) and [deemix-gui](https://gitlab.com/RemixDev/deemix-webui).
If you are a web developer and want to contribute to this project, please read the [COMPILE-UI](COMPILE-UI.md) file.
# "Hidden" features The submodule reference was removed and consolidated into this single repo. Git history was maintained.
- `CTRL+SHIFT+Backspace` deletes all the search bar content ## Running from source
- `CTRL+F` focuses the search bar
- `CTRL+B` toggles the download bar
- `ALT+Left` goes back to the previous page, if present (like would happen in the browser)
- `ALT+Right` goes forward to the next page, if present (like would happen in the browser)
- Custom context menu: on certain elements, like download buttons or album covers, when opening the context menu, a custom one with more options will appear instead of the default one
# Deps You need to use nodejs 16.x, using `yarn` is recommended.
- `rollup-plugin-vue@4.2.0` is needed because of https://github.com/vuejs/rollup-plugin-vue/issues/238 Install the dependencies using `yarn install-all` for production.
Install the dependencies using `yarn install-all-dev` for development.
Then you should be able to run the app with `yarn start`.
If you want to further develop deemix-gui and propose a PR, use `yarn dev`
Commands for easy setup:
```sh
# Production
git clone https://gitea.va.reichard.io/evan/Deemixer.git . && yarn install-all
# Development
git clone https://gitea.va.reichard.io/evan/Deemixer.git . && yarn install-all-dev
```
You can change the default port by setting the environment variable `PORT` to any other number before starting the app.
## Building the app
To build the app you need to have git installed and the repo cloned with `git`.
Make sure you've installed the dependencies for all packages (the root folder, `server` and `webui`).
Then from the root folder run `yarn dist` to make a distributable package for your current OS or `yarn dist-server` to make an executable for only the server.
## Feature requests
Before asking for a feature make sure it isn't an already open issue on the repo
# License # License

BIN
build/64x64.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

BIN
build/icon.icns Normal file

Binary file not shown.

View File

Before

Width:  |  Height:  |  Size: 238 KiB

After

Width:  |  Height:  |  Size: 238 KiB

1497
build/icon.svg Executable file

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 52 KiB

109
index.js Normal file
View File

@ -0,0 +1,109 @@
const { app, BrowserWindow, ipcMain, shell, dialog, Menu, MenuItem } = require('electron')
const contextMenu = require('electron-context-menu')
const WindowStateManager = require('electron-window-state-manager')
const path = require('path')
const os = require('os')
const yargs = require('yargs/yargs')
const { hideBin } = require('yargs/helpers')
const argv = yargs(hideBin(process.argv)).options({
port: { type: 'string', default: '6595' },
host: { type: 'string', default: '127.0.0.1' },
dev: { type: 'boolean', default: false}
}).argv
const { DeemixServer }= require('./server/dist/app.js')
const PORT = process.env.DEEMIX_SERVER_PORT || argv.port
process.env.DEEMIX_SERVER_PORT = PORT
process.env.DEEMIX_HOST = argv.host
const server = new DeemixServer(argv.host, PORT, '/', false)
server.init()
let win
const windowState = new WindowStateManager('mainWindow', {
defaultWidth: 800,
defaultHeight: 600
})
function createWindow () {
win = new BrowserWindow({
width: windowState.width,
height: windowState.height,
x: windowState.x,
y: windowState.y,
useContentSize: true,
autoHideMenuBar: true,
icon: path.join(__dirname, os.platform() === 'win32' ? 'build/icon.ico' : 'build/64x64.png'),
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
})
win.setMenu(null)
if (argv.dev){
const menu = new Menu()
menu.append(new MenuItem({
label: 'DevTools',
submenu: [
{ role: 'reload', accelerator: 'f5', click: () => { win.reload() } },
{ role: 'devtools', accelerator: 'f12', click: () => { win.webContents.toggleDevTools() } }
]
}))
Menu.setApplicationMenu(menu)
}
// Open links in external browser
win.webContents.on('new-window', function(e, url) {
e.preventDefault()
shell.openExternal(url)
})
win.loadURL(`http://${argv.host}:${PORT}`)
if (windowState.maximized) {
win.maximize();
}
win.on('close', (event)=>{
windowState.saveState(win);
if (server.deemixApp.getSettings().settings.clearQueueOnExit){
server.deemixApp.cancelAllDownloads()
}
})
}
app.whenReady().then(() => {
createWindow()
contextMenu({
showLookUpSelection: false,
showSearchWithGoogle: false,
showInspectElement: false
})
// Only one istance per time
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
})
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
ipcMain.on('openDownloadsFolder', (event)=>{
const { downloadLocation } = server.deemixApp.getSettings().settings
shell.openPath(downloadLocation)
})
ipcMain.on('selectDownloadFolder', async (event, downloadLocation)=>{
let path = await dialog.showOpenDialog(win, {
defaultPath: downloadLocation,
properties: ["openDirectory", "createDirectory"]
})
if (path.filePaths[0]) win.webContents.send("downloadFolderSelected", path.filePaths[0])
})

View File

@ -1,61 +1,92 @@
{ {
"name": "deemix-webui", "name": "deemix-gui",
"version": "1.9.3", "version": "0.0.0",
"main": "index.js",
"repository": "https://gitlab.com/RemixDev/deemix-gui.git",
"author": "RemixDev <RemixDev64@gmail.com>",
"license": "GPL-3.0-only",
"scripts": { "scripts": {
"clean": "rimraf public/js/bundle.js public/js/bundle.temp.js public/js/bundle.js.map", "install-all": "yarn install && yarn --cwd server install --production && yarn --cwd webui install --production",
"clean-temp": "rimraf public/js/bundle.temp.js", "install-all-dev": "yarn install && yarn --cwd server install && yarn --cwd webui install",
"build:js": "rollup -c", "dev": "yarn --cwd webui dev",
"minify": "esbuild public/js/bundle.temp.js --outfile=public/js/bundle.js --minify", "start": "electron . --dev",
"build": "npm-run-all --sequential clean build:js minify clean-temp", "predist": "yarn build-server && yarn build-webui",
"start:gui": "yarn --cwd ../ start", "dist": "yarn set-version && electron-builder && yarn reset-version",
"watch:server": "yarn --cwd ../server watch", "dist:dir": "yarn set-version && yarn predist && electron-builder --dir && yarn reset-version",
"watch:js": "rollup -c -w", "dist-server": "yarn set-version && yarn predist && ./node_modules/.bin/pkg --out-dir dist ./server/package.json && yarn reset-version",
"dev": "npm-run-all --parallel watch:server watch:js", "start-server": "yarn --cwd server start",
"lint": "eslint src/**/*.{js,vue,mjs} --fix", "build-server": "yarn --cwd server build",
"lint-tests": "eslint src/**/*.js --fix", "build-webui": "yarn --cwd webui build",
"test": "jest", "set-version": "node scripts/set-version.js",
"test-watch": "jest --watch", "reset-version": "node scripts/reset-version.js"
"testlang": "node ./tests/testlang.js"
},
"dependencies": {
"@rollup/plugin-alias": "3.1.5",
"@rollup/plugin-commonjs": "20.0.0",
"@rollup/plugin-node-resolve": "13.0.4",
"@rollup/plugin-replace": "3.0.0",
"@vue/composition-api": "1.0.6",
"esbuild": "0.12.19",
"flag-icon-css": "3.5.0",
"lodash-es": "4.17.21",
"npm-run-all": "4.1.5",
"postcss": "8.3.6",
"rimraf": "3.0.2",
"rollup": "2.56.1",
"rollup-plugin-analyzer": "4.0.0",
"rollup-plugin-postcss": "4.0.0",
"rollup-plugin-svg": "2.0.0",
"rollup-plugin-vue": "4.2.0",
"svg-country-flags": "1.2.10",
"tailwindcss": "1.9.6",
"toastify-js": "1.11.1",
"vue": "2.6.14",
"vue-i18n": "8.25.0",
"vue-router": "3.5.2",
"vuex": "3.6.2"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "7.15.0", "electron": "^22.0.0",
"@babel/plugin-transform-modules-commonjs": "7.15.0", "electron-builder": "^23.6.0",
"@nuxtjs/eslint-config": "6.0.1", "pkg": "^5.8.0"
"@types/jest": "26.0.24", },
"@typescript-eslint/eslint-plugin": "4.29.0", "dependencies": {
"@typescript-eslint/parser": "4.29.0", "electron-context-menu": "^3.6.1",
"babel-jest": "27.0.6", "electron-window-state-manager": "^0.3.2",
"eslint": "7.32.0", "yargs": "^17.6.2"
"eslint-config-prettier": "8.3.0", },
"eslint-plugin-prettier": "3.4.0", "build": {
"jest": "27.0.6", "appId": "app.deemix.gui",
"prettier": "2.3.2", "productName": "deemix-gui",
"typescript": "4.3.5", "files": [
"vue-template-compiler": "2.6.14" "index.js",
"preload.js",
"server/dist/**/*",
"webui/public/**/*",
"build/**/*",
"package.json"
],
"mac": {
"target": [
{
"target": "dmg",
"arch": "x64"
},
{
"target": "dmg",
"arch": "arm64"
}
],
"artifactName": "deemix-gui_${arch}.${ext}",
"category": "public.app-category.music"
},
"win": {
"target": [
{
"target": "nsis",
"arch": "x64"
},
{
"target": "portable",
"arch": "x64"
}
]
},
"linux": {
"target": [
"appimage",
"deb"
],
"artifactName": "deemix-gui.${ext}",
"category": "AudioVideo,Audio",
"icon": "build/icon.icns"
},
"nsis": {
"artifactName": "${productName}_setup.${ext}",
"oneClick": false,
"license": "LICENSE.txt",
"allowToChangeInstallationDirectory": true,
"uninstallDisplayName": "${productName}",
"deleteAppDataOnUninstall": true
},
"portable": {
"artifactName": "${productName}.${ext}",
"requestExecutionLevel": "user"
}
} }
} }

25
preload.js Normal file
View File

@ -0,0 +1,25 @@
const {
contextBridge,
ipcRenderer
} = require("electron");
// Expose protected methods that allow the renderer process to use
// the ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld(
"api", {
send: (channel, data) => {
// whitelist channels
let validChannels = ["openDownloadsFolder", "selectDownloadFolder"];
if (validChannels.includes(channel)) {
ipcRenderer.send(channel, data);
}
},
receive: (channel, func) => {
let validChannels = ["downloadFolderSelected"];
if (validChannels.includes(channel)) {
// Deliberately strip event as it includes `sender`
ipcRenderer.on(channel, (event, ...args) => func(...args));
}
}
}
);

16
scripts/gen-version.js Normal file
View File

@ -0,0 +1,16 @@
const { execSync } = require('child_process')
function generateVersion(){
const now = new Date();
const year = now.getFullYear();
const month = now.getMonth()+1;
const day = now.getDate();
const commitsNumber = String(execSync('git rev-list --count HEAD')).trim()
const commitHash = String(execSync('git rev-parse --short=10 HEAD')).trim()
return `${year}.${month}.${day}-r${commitsNumber}.${commitHash}`
}
console.log(generateVersion())
module.exports = generateVersion

6
scripts/reset-version.js Normal file
View File

@ -0,0 +1,6 @@
const { execSync } = require('child_process')
const fs = require('fs')
let package = JSON.parse(fs.readFileSync('package.json'))
package.version = "0.0.0"
fs.writeFileSync('package.json', JSON.stringify(package, null, 2)+"\n")

6
scripts/set-version.js Normal file
View File

@ -0,0 +1,6 @@
const fs = require('fs')
const generateVersion = require('./gen-version.js')
let package = JSON.parse(fs.readFileSync('package.json'))
package.version = generateVersion()
fs.writeFileSync('package.json', JSON.stringify(package, null, 2)+"\n")

1
server/.eslintignore Normal file
View File

@ -0,0 +1 @@
dist/

16
server/.eslintrc.yml Normal file
View File

@ -0,0 +1,16 @@
---
extends:
- "@nuxtjs"
- plugin:prettier/recommended
plugins:
- "@typescript-eslint"
parserOptions:
parser: "@typescript-eslint/parser"
rules:
"@typescript-eslint/no-unused-vars":
- error
- args: all
argsIgnorePattern: ^_
no-unused-vars: off
no-console: off
camelcase: off

68
server/.gitignore vendored Normal file
View File

@ -0,0 +1,68 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# next.js build output
.next
# IDE
.vscode
.idea
# development
dist/*

8
server/.prettierrc.yml Normal file
View File

@ -0,0 +1,8 @@
tabWidth: 2
printWidth: 120
useTabs: true
semi: false
singleQuote: true
bracketSpacing: true
arrowParens: avoid
trailingComma: none

7
server/jest.config.js Normal file
View File

@ -0,0 +1,7 @@
module.exports = {
clearMocks: true,
roots: ['<rootDir>/src', '<rootDir>/tests'],
testEnvironment: 'node',
preset: 'ts-jest',
setupFiles: ['dotenv/config']
}

83
server/package.json Normal file
View File

@ -0,0 +1,83 @@
{
"name": "@deemix-gui/deemix-server",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node dist/app.js",
"build": "webpack --env production",
"sourcemap": "webpack --env production sourcemap",
"prewatch": "yarn lint-build",
"watch": "webpack --watch",
"lint": "eslint \"./{src, tests}/**\" --fix",
"lint-build": "eslint \"./src/**\" --fix",
"test": "jest",
"test-watch": "jest --watch"
},
"bin": "./dist/app.js",
"pkg": {
"scripts": "./dist/**/*.js",
"assets": [
"../webui/public/**/*",
"../package.json"
],
"targets": [
"node16-linux-x64",
"node16-win-x64",
"node16-macos-x64"
]
},
"dependencies": {
"@types/cookie-parser": "1.4.2",
"@types/dateformat": "5.0.0",
"@types/debug": "4.1.5",
"@types/ejs": "3.1.1",
"@types/express": "4.17.11",
"@types/express-session": "^1.17.3",
"@types/morgan": "1.9.2",
"@types/node": "14.14.37",
"@types/ramda": "0.27.40",
"@types/uuid": "8.3.0",
"@types/ws": "7.4.1",
"@types/yargs": "17.0.0",
"bufferutil": "4.0.3",
"cookie-parser": "1.4.5",
"dateformat": "5.0.3",
"debug": "2.6.9",
"deemix": "^3.6.0",
"deezer-js": "^1.3.0",
"dotenv": "8.2.0",
"ejs": "3.1.8",
"express": "4.17.1",
"express-session": "^1.17.1",
"memorystore": "1.6.6",
"morgan": "1.10.0",
"nodemon": "2.0.7",
"nodemon-webpack-plugin": "4.8.1",
"ramda": "0.27.1",
"ts-loader": "9.4.2",
"utf-8-validate": "5.0.5",
"uuid": "8.3.2",
"webpack": "5.75.0",
"webpack-cli": "5.0.1",
"winston": "3.6.0",
"ws": "7.4.5",
"yargs": "17.0.1"
},
"devDependencies": {
"@nuxtjs/eslint-config": "6.0.0",
"@types/jest": "26.0.22",
"@types/supertest": "2.0.11",
"@typescript-eslint/eslint-plugin": "4.21.0",
"@typescript-eslint/parser": "4.21.0",
"eslint": "7.23.0",
"eslint-config-prettier": "8.1.0",
"eslint-plugin-prettier": "3.3.1",
"jest": "26.6.3",
"prettier": "2.2.1",
"supertest": "6.1.3",
"ts-jest": "26.5.4",
"ts-node": "9.1.1",
"ts-node-dev": "1.1.6",
"typescript": "4.2.4"
}
}

400
server/src/app.ts Normal file
View File

@ -0,0 +1,400 @@
import fs from 'fs'
import { sep } from 'path'
import { v4 as uuidv4 } from 'uuid'
// @ts-expect-error
import deemix from 'deemix'
import got from 'got'
import { Settings, Listener } from './types'
import { NotLoggedIn, CantStream } from './helpers/errors'
import { GUI_PACKAGE } from './helpers/paths'
import { logger } from './helpers/logger'
// Types
const Downloader = deemix.downloader.Downloader
const { Single, Collection, Convertable } = deemix.types.downloadObjects
// Functions
export const getAccessToken = deemix.utils.deezer.getAccessToken
export const getArlFromAccessToken = deemix.utils.deezer.getArlFromAccessToken
// Constants
export const configFolder: string = deemix.utils.localpaths.getConfigFolder()
export const defaultSettings: Settings = deemix.settings.DEFAULTS
export const deemixVersion = require('../node_modules/deemix/package.json').version
const currentVersionTemp = JSON.parse(String(fs.readFileSync(GUI_PACKAGE))).version
export const currentVersion = currentVersionTemp === '0.0.0' ? 'continuous' : currentVersionTemp
export const sessionDZ: any = {}
export class DeemixApp {
queueOrder: string[]
queue: any
currentJob: any
deezerAvailable: string | null
latestVersion: string | null
plugins: any
settings: any
listener: Listener
constructor(listener: Listener) {
this.settings = deemix.settings.load(configFolder)
this.queueOrder = []
this.queue = {}
this.currentJob = null
this.plugins = {
// eslint-disable-next-line new-cap
spotify: new deemix.plugins.spotify()
}
this.deezerAvailable = null
this.latestVersion = null
this.listener = listener
this.plugins.spotify.setup()
this.restoreQueueFromDisk()
}
async isDeezerAvailable(): Promise<string> {
if (this.deezerAvailable === null) {
let response
try {
response = await got.get('https://www.deezer.com/', {
headers: { Cookie: 'dz_lang=en; Domain=deezer.com; Path=/; Secure; hostOnly=false;' },
https: {
rejectUnauthorized: false
},
retry: 5
})
} catch (e) {
logger.error(e)
this.deezerAvailable = 'no-network'
return this.deezerAvailable
}
const title = (response.body.match(/<title[^>]*>([^<]+)<\/title>/)![1] || '').trim()
this.deezerAvailable = title !== 'Deezer will soon be available in your country.' ? 'yes' : 'no'
}
return this.deezerAvailable
}
async getLatestVersion(force = false): Promise<string | null> {
if ((this.latestVersion === null || force) && !this.settings.disableUpdateCheck) {
let response
try {
response = await got.get('https://deemix.app/gui/latest', {
https: {
rejectUnauthorized: false
}
})
} catch (e) {
logger.error(e)
this.latestVersion = 'NotFound'
return this.latestVersion
}
this.latestVersion = response.body.trim()
}
return this.latestVersion
}
parseVersion(version: string | null): any {
if (version === null || version === 'continuous' || version === 'NotFound') return null
try {
const matchResult = version.match(/(\d+)\.(\d+)\.(\d+)-r(\d+)\.(.+)/) || []
return {
year: parseInt(matchResult[1]),
month: parseInt(matchResult[2]),
day: parseInt(matchResult[3]),
revision: parseInt(matchResult[4]),
commit: matchResult[5] || ''
}
} catch (e) {
logger.error(e)
return null
}
}
isUpdateAvailable(): boolean {
const currentVersionObj: any = this.parseVersion(currentVersion)
const latestVersionObj: any = this.parseVersion(this.latestVersion)
if (currentVersionObj === null || latestVersionObj === null) return false
if (latestVersionObj.year > currentVersionObj.year) return true
let sameDate = latestVersionObj.year === currentVersionObj.year
if (sameDate && latestVersionObj.month > currentVersionObj.month) return true
sameDate = sameDate && latestVersionObj.month === currentVersionObj.month
if (sameDate && latestVersionObj.day > currentVersionObj.day) return true
sameDate = sameDate && latestVersionObj.day === currentVersionObj.day
if (sameDate && latestVersionObj.revision > currentVersionObj.revision) return true
if (
latestVersionObj.revision === currentVersionObj.revision &&
latestVersionObj.commit !== currentVersionObj.commit
)
return true
return false
}
getSettings(): any {
return { settings: this.settings, defaultSettings, spotifySettings: this.plugins.spotify.getSettings() }
}
saveSettings(newSettings: any, newSpotifySettings: any) {
newSettings.executeCommand = this.settings.executeCommand
deemix.settings.save(newSettings, configFolder)
this.settings = newSettings
this.plugins.spotify.saveSettings(newSpotifySettings)
}
getQueue() {
const result: any = {
queue: this.queue,
queueOrder: this.queueOrder
}
if (this.currentJob && this.currentJob !== true) {
result.current = this.currentJob.downloadObject.getSlimmedDict()
}
return result
}
async addToQueue(dz: any, url: string[], bitrate: number, retry: boolean = false) {
if (!dz.logged_in) throw new NotLoggedIn()
if (
!this.settings.feelingLucky &&
((!dz.current_user.can_stream_lossless && bitrate === 9) || (!dz.current_user.can_stream_hq && bitrate === 3))
)
throw new CantStream(bitrate)
let downloadObjs: any[] = []
const downloadErrors: any[] = []
let link: string = ''
const requestUUID = uuidv4()
if (url.length > 1) {
this.listener.send('startGeneratingItems', { uuid: requestUUID, total: url.length })
}
for (let i = 0; i < url.length; i++) {
link = url[i]
logger.info(`Adding ${link} to queue`)
let downloadObj
try {
downloadObj = await deemix.generateDownloadObject(dz, link, bitrate, this.plugins, this.listener)
} catch (e) {
downloadErrors.push(e)
}
if (Array.isArray(downloadObj)) {
downloadObjs = downloadObjs.concat(downloadObj)
} else if (downloadObj) downloadObjs.push(downloadObj)
}
if (downloadErrors.length) {
downloadErrors.forEach((e: any) => {
if (!e.errid) logger.error(e)
this.listener.send('queueError', { link: e.link, error: e.message, errid: e.errid })
})
}
if (url.length > 1) {
this.listener.send('finishGeneratingItems', { uuid: requestUUID, total: downloadObjs.length })
}
const slimmedObjects: any[] = []
downloadObjs.forEach((downloadObj: any) => {
// Check if element is already in queue
if (Object.keys(this.queue).includes(downloadObj.uuid) && !retry) {
this.listener.send('alreadyInQueue', downloadObj.getEssentialDict())
return
}
// Save queue status when adding something to the queue
if (!fs.existsSync(configFolder + 'queue')) fs.mkdirSync(configFolder + 'queue')
this.queueOrder.push(downloadObj.uuid)
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
this.queue[downloadObj.uuid] = downloadObj.getEssentialDict()
this.queue[downloadObj.uuid].status = 'inQueue'
const savedObject = downloadObj.toDict()
savedObject.status = 'inQueue'
fs.writeFileSync(configFolder + `queue${sep}${downloadObj.uuid}.json`, JSON.stringify(savedObject))
slimmedObjects.push(downloadObj.getSlimmedDict())
})
if (slimmedObjects.length === 1) this.listener.send('addedToQueue', slimmedObjects[0])
else this.listener.send('addedToQueue', slimmedObjects)
this.startQueue(dz)
return slimmedObjects
}
async startQueue(dz: any): Promise<any> {
do {
if (this.currentJob !== null || this.queueOrder.length === 0) {
// Should not start another download
return null
}
this.currentJob = true // lock currentJob
let currentUUID: string
do {
currentUUID = this.queueOrder.shift() || ''
} while (this.queue[currentUUID] === undefined && this.queueOrder.length)
if (this.queue[currentUUID] === undefined) {
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
this.currentJob = null
return null
}
this.queue[currentUUID].status = 'downloading'
const currentItem: any = JSON.parse(fs.readFileSync(configFolder + `queue${sep}${currentUUID}.json`).toString())
let downloadObject: any
switch (currentItem.__type__) {
case 'Single':
downloadObject = new Single(currentItem)
break
case 'Collection':
downloadObject = new Collection(currentItem)
break
case 'Convertable':
downloadObject = new Convertable(currentItem)
downloadObject = await this.plugins[downloadObject.plugin].convert(
dz,
downloadObject,
this.settings,
this.listener
)
fs.writeFileSync(
configFolder + `queue${sep}${downloadObject.uuid}.json`,
JSON.stringify({ ...downloadObject.toDict(), status: 'inQueue' })
)
break
}
this.currentJob = new Downloader(dz, downloadObject, this.settings, this.listener)
this.listener.send('startDownload', currentUUID)
await this.currentJob.start()
if (!downloadObject.isCanceled) {
// Set status
if (downloadObject.failed === downloadObject.size && downloadObject.size !== 0) {
this.queue[currentUUID].status = 'failed'
} else if (downloadObject.failed > 0) {
this.queue[currentUUID].status = 'withErrors'
} else {
this.queue[currentUUID].status = 'completed'
}
const savedObject = downloadObject.getSlimmedDict()
savedObject.status = this.queue[currentUUID].status
// Save queue status
this.queue[currentUUID] = savedObject
fs.writeFileSync(configFolder + `queue${sep}${currentUUID}.json`, JSON.stringify(savedObject))
}
logger.info(this.queueOrder)
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
this.currentJob = null
} while (this.queueOrder.length)
}
cancelDownload(uuid: string) {
if (Object.keys(this.queue).includes(uuid)) {
switch (this.queue[uuid].status) {
case 'downloading':
this.currentJob.downloadObject.isCanceled = true
this.listener.send('cancellingCurrentItem', uuid)
break
case 'inQueue':
this.queueOrder.splice(this.queueOrder.indexOf(uuid), 1)
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
// break
// eslint-disable-next-line no-fallthrough
default:
// This gets called even in the 'inQueue' case. Is this the expected behaviour? If no, de-comment the break
this.listener.send('removedFromQueue', uuid)
break
}
fs.unlinkSync(configFolder + `queue${sep}${uuid}.json`)
delete this.queue[uuid]
}
}
cancelAllDownloads() {
this.queueOrder = []
let currentItem: string | null = null
Object.values(this.queue).forEach((downloadObject: any) => {
if (downloadObject.status === 'downloading') {
this.currentJob.downloadObject.isCanceled = true
this.listener.send('cancellingCurrentItem', downloadObject.uuid)
currentItem = downloadObject.uuid
}
fs.unlinkSync(configFolder + `queue${sep}${downloadObject.uuid}.json`)
delete this.queue[downloadObject.uuid]
})
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
this.listener.send('removedAllDownloads', currentItem)
}
clearCompletedDownloads() {
Object.values(this.queue).forEach((downloadObject: any) => {
if (downloadObject.status === 'completed') {
fs.unlinkSync(configFolder + `queue${sep}${downloadObject.uuid}.json`)
delete this.queue[downloadObject.uuid]
}
})
this.listener.send('removedFinishedDownloads')
}
restoreQueueFromDisk() {
if (!fs.existsSync(configFolder + 'queue')) fs.mkdirSync(configFolder + 'queue')
const allItems: string[] = fs.readdirSync(configFolder + 'queue')
allItems.forEach((filename: string) => {
if (filename === 'order.json') {
try {
this.queueOrder = JSON.parse(fs.readFileSync(configFolder + `queue${sep}order.json`).toString())
} catch {
this.queueOrder = []
fs.writeFileSync(configFolder + `queue${sep}order.json`, JSON.stringify(this.queueOrder))
}
} else {
let currentItem: any
try {
currentItem = JSON.parse(fs.readFileSync(configFolder + `queue${sep}${filename}`).toString())
} catch {
fs.unlinkSync(configFolder + `queue${sep}${filename}`)
return
}
if (currentItem.status === 'inQueue') {
let downloadObject: any
switch (currentItem.__type__) {
case 'Single':
downloadObject = new Single(currentItem)
// Remove old incompatible queue items
if (downloadObject.single.trackAPI_gw) {
fs.unlinkSync(configFolder + `queue${sep}${filename}`)
return
}
break
case 'Collection':
downloadObject = new Collection(currentItem)
// Remove old incompatible queue items
if (downloadObject.collection.tracks_gw) {
fs.unlinkSync(configFolder + `queue${sep}${filename}`)
return
}
break
case 'Convertable':
downloadObject = new Convertable(currentItem)
break
}
this.queue[downloadObject.uuid] = downloadObject.getEssentialDict()
this.queue[downloadObject.uuid].status = 'inQueue'
} else {
this.queue[currentItem.uuid] = currentItem
}
}
})
}
}

View File

@ -0,0 +1,55 @@
const { TrackFormats } = require('deezer-js')
const bitrateLabels = {
[TrackFormats.MP4_RA3]: '360 HQ',
[TrackFormats.MP4_RA2]: '360 MQ',
[TrackFormats.MP4_RA1]: '360 LQ',
[TrackFormats.FLAC]: 'FLAC',
[TrackFormats.MP3_320]: '320kbps',
[TrackFormats.MP3_128]: '128kbps',
[TrackFormats.DEFAULT]: '128kbps',
[TrackFormats.LOCAL]: 'MP3'
}
export class BadRequestError extends Error {
constructor() {
super()
this.message = 'Bad request!'
}
}
export const isBadRequestError = (error: any) => error instanceof BadRequestError
export class QueueError extends Error {
constructor(message: string) {
super(message)
this.name = 'QueueError'
}
}
export class AlreadyInQueue extends QueueError {
item: any
silent: boolean
constructor(dwObj: any, silent: boolean) {
super(`${dwObj.artist} - ${dwObj.title} is already in queue.`)
this.name = 'AlreadyInQueue'
this.item = dwObj
this.silent = silent
}
}
export class NotLoggedIn extends QueueError {
constructor() {
super(`You must be logged in to start a download.`)
this.name = 'NotLoggedIn'
}
}
export class CantStream extends QueueError {
bitrate: number
constructor(bitrate: number) {
super(`Your account can't stream at ${bitrateLabels[bitrate]}.`)
this.name = 'CantStream'
this.bitrate = bitrate
}
}

View File

@ -0,0 +1,51 @@
import fs from 'fs'
import { join as joinPath } from 'path'
import os from 'os'
import dateFormat from 'dateformat'
import { createLogger, format, transports } from 'winston'
// @ts-expect-error
import deemix from 'deemix'
const { combine, timestamp, errors, colorize, printf } = format
const logFolder: string = joinPath(deemix.utils.localpaths.getConfigFolder(), 'logs')
const logFilename = joinPath(logFolder, `${dateFormat(new Date(), 'yyyy-mm-dd-HH.MM.ss')}.log`)
const logFormat = printf(error => {
const { level, message, timestamp, stack } = error
let result = `${timestamp} [${level}] ${message}`
if (stack && !message.startsWith('uncaughtException')) result += '\n' + stack + '\n'
return result
})
export const logger = createLogger({
format: combine(errors({ stack: true }), timestamp(), logFormat),
transports: [
new transports.File({
handleExceptions: true,
handleRejections: true,
format: combine(errors({ stack: true }), timestamp(), logFormat),
filename: logFilename
}),
new transports.Console({
handleExceptions: true,
handleRejections: true,
format: combine(errors({ stack: true }), colorize(), timestamp(), logFormat)
})
]
})
export function removeOldLogs(logFilesNumber: number) {
if (!fs.existsSync(logFolder)) fs.mkdirSync(logFolder, { recursive: true })
fs.appendFileSync(logFilename, `${os.platform()} - ${os.type()} ${os.release()} ${os.arch()}\n\n`)
const files = fs.readdirSync(logFolder)
const logs: Array<string> = []
files.forEach(function (file) {
logs.push(file.substring(0, file.length - 4))
})
logs.sort()
if (logs.length > logFilesNumber) {
for (let i = 0; i < logs.length - logFilesNumber; i++) {
fs.unlinkSync(joinPath(logFolder, logs[i] + '.log'))
}
}
}

View File

@ -0,0 +1,45 @@
import fs from 'fs'
// @ts-expect-error
import deemix from 'deemix'
import { LoginFile } from '../types'
const configFolder = deemix.utils.localpaths.getConfigFolder()
const DEFAULTS: LoginFile = {
accessToken: null,
arl: null
}
let loginData: LoginFile = {
accessToken: null,
arl: null
}
export function loadLoginCredentials() {
if (!fs.existsSync(configFolder)) fs.mkdirSync(configFolder)
if (!fs.existsSync(configFolder + 'login.json')) resetLoginCredentials()
try {
loginData = JSON.parse(fs.readFileSync(configFolder + 'login.json').toString())
} catch (e) {
if (e.name === 'SyntaxError') resetLoginCredentials()
}
}
export function getLoginCredentials(): LoginFile {
if (!loginData.arl) loadLoginCredentials()
return loginData
}
export function saveLoginCredentials(newLogin: LoginFile) {
if (newLogin.arl) loginData.arl = newLogin.arl
if (newLogin.accessToken) loginData.accessToken = newLogin.accessToken
if (!fs.existsSync(configFolder)) fs.mkdirSync(configFolder)
fs.writeFileSync(configFolder + 'login.json', JSON.stringify(loginData, null, 2))
}
export function resetLoginCredentials() {
if (!fs.existsSync(configFolder)) fs.mkdirSync(configFolder)
fs.writeFileSync(configFolder + 'login.json', JSON.stringify(DEFAULTS, null, 2))
loginData = JSON.parse(JSON.stringify(DEFAULTS))
}

View File

@ -0,0 +1,5 @@
import path from 'path'
export const ROOT_DIR = path.resolve(path.join(__dirname, '..', '..'))
export const WEBUI_DIR = path.join(ROOT_DIR, 'webui', 'public')
export const GUI_PACKAGE = path.join(ROOT_DIR, 'package.json')

View File

@ -0,0 +1,22 @@
import { Port } from '../types'
/**
* Normalize a port into a number, string, or false.
*
* @since 0.0.0
*/
export function normalizePort(portString: string): Port {
const port = parseInt(portString, 10)
if (isNaN(port)) {
// named pipe
return portString
}
if (port >= 0) {
// port number
return port
}
return false
}

View File

@ -0,0 +1 @@
export const isObjectEmpy = (obj: any) => Object.keys(obj).length === 0

View File

@ -0,0 +1,51 @@
import http from 'http'
import type { Debugger } from 'debug'
import { logger } from './logger'
/**
* Event listener for HTTP server "error" event.
*
* @since 0.0.0
*/
export function getErrorCb(port: number | string | boolean) {
return (error: any) => {
if (error.syscall !== 'listen') {
throw error
}
const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES': {
logger.error(bind + ' requires elevated privileges')
process.exit(1)
}
case 'EADDRINUSE': {
logger.error(bind + ' is already in use')
process.exit(1)
}
default:
throw error
}
}
}
/**
* Event listener for HTTP server "listening" event.
*
* @since 0.0.0
*/
export function getListeningCb(server: http.Server, debug: Debugger) {
return () => {
const addr = server.address()
if (addr) {
const ip = typeof addr === 'string' ? 'pipe ' + addr : addr.address
const port = typeof addr === 'string' ? 'pipe ' + addr : addr.port
debug(`Listening on ${ip}:${port}`)
logger.info(`Listening on ${ip}:${port}`)
}
}
}

27
server/src/index.ts Normal file
View File

@ -0,0 +1,27 @@
import yargs from 'yargs'
import { hideBin } from 'yargs/helpers'
import type { Arguments } from './types'
import { DeemixServer } from './server'
const isModule = process.mainModule && process.mainModule.parent
if (!isModule) {
// TODO: Remove type assertion while keeping correct types
const argv = yargs(hideBin(process.argv)).options({
port: { type: 'string', default: '6595' },
host: { type: 'string', default: '127.0.0.1' },
locationbase: { type: 'string', default: '/' },
singleuser: { type: 'boolean', default: false }
}).argv as Arguments
const DEEMIX_SERVER_PORT = process.env.DEEMIX_SERVER_PORT ?? argv.port
const DEEMIX_HOST = process.env.DEEMIX_HOST ?? argv.host
const DEEMIX_LOCATION_BASE = process.env.DEEMIX_LOCATION_BASE ?? argv.locationbase
const IS_SINGLE_USER = !!process.env.DEEMIX_SINGLE_USER ?? !!argv.singleuser
const server = new DeemixServer(DEEMIX_HOST, DEEMIX_SERVER_PORT, DEEMIX_LOCATION_BASE, IS_SINGLE_USER)
server.init()
}
export { DeemixServer }

36
server/src/middlewares.ts Normal file
View File

@ -0,0 +1,36 @@
import type { Application } from 'express'
import express from 'express'
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import session from 'express-session'
import { WEBUI_DIR } from './helpers/paths'
const MemoryStore = require('memorystore')(session)
declare module 'express-session' {
export interface SessionData {
dz: any
}
}
export function registerMiddlewares(app: Application) {
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(
session({
store: new MemoryStore({
checkPeriod: 86400000 // prune expired entries every 24h
}),
secret: 'U2hoLCBpdHMgYSBzZWNyZXQh',
resave: true,
saveUninitialized: true
})
)
app.use(express.static(WEBUI_DIR))
if (process.env.NODE_ENV === 'development') {
app.use(logger('dev'))
}
}

View File

@ -0,0 +1,3 @@
import { ApiHandler } from '../../../types'
export default [] as ApiHandler[]

View File

@ -0,0 +1,51 @@
import { appSendGet } from '../../../../tests/utils'
describe('albumSearch requests', () => {
it('should respond 200 to calls with term', async () => {
const responseStatusCollector: number[] = []
const batchCalls = [
'/api/album-search/?term=eminem',
'/api/album-search/?term=eminem?start=10',
'/api/album-search/?term=eminem?ack=aa',
'/api/album-search/?term=eminem?ack=aa?start=10',
'/api/album-search/?term=eminem?ack=aa?start=10?nb=34'
]
for (const uri of batchCalls) {
responseStatusCollector.push((await appSendGet(uri)).status)
}
expect(responseStatusCollector).toMatchObject(new Array(batchCalls.length).fill(200))
expect(responseStatusCollector).toMatchObject(new Array(responseStatusCollector.length).fill(200))
})
it('should respond 400 to calls without term', async () => {
const responseStatusCollector: number[] = []
const batchCalls = [
'/api/album-search/',
'/api/album-search/?start=10',
'/api/album-search/?ack=aa',
'/api/album-search/?ack=aa?start=10',
'/api/album-search/?ack=aa?start=10?nb=34'
]
for (const uri of batchCalls) {
responseStatusCollector.push((await appSendGet(uri)).status)
}
expect(responseStatusCollector).toMatchObject(new Array(responseStatusCollector.length).fill(400))
})
it('should respond the desired search result', async () => {
const res = (await appSendGet('/api/album-search/?term=eminem')).body
expect(res.data.data.length).not.toBe(0)
})
// TODO Understand whic should be the correct response
it.skip('should respond the desired search result with a start parameter', async () => {
const res = (await appSendGet('/api/album-search/?term=eminem?start=10')).body
expect(res.data.data.length).not.toBe(0)
})
})

View File

@ -0,0 +1,92 @@
import type { RequestHandler } from 'express'
// @ts-expect-error
import { Deezer } from 'deezer-js'
import type { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
export interface RawAlbumQuery {
term: string
start?: string
nb?: string
}
export interface AlbumSearchParams extends Omit<RawAlbumQuery, 'start' | 'nb'> {
start: number
nb: number
}
export interface AlbumResponse {
data: any[]
total: number
}
const path: ApiHandler['path'] = '/album-search/'
const handler: RequestHandler<{}, {}, {}, RawAlbumQuery> = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
if (!req.query) {
return res.status(400).send()
}
const { term, start, nb } = parseQuery(req.query)
if (!term || term.trim() === '') {
return res.status(400).send()
}
const results = await dz.gw.search_music(term, 'ALBUM', { index: start, limit: nb })
const albums = await Promise.all(results.data.map((c: any) => getAlbumDetails(dz, c.ALB_ID)))
const output: AlbumResponse = {
data: albums,
total: albums.length
}
return res.send(output)
}
const apiHandler = { path, handler }
function parseQuery(query: RawAlbumQuery): AlbumSearchParams {
let startingPoint = 0
if (typeof query.start !== 'undefined') {
startingPoint = parseInt(query.start)
}
let newNb = 30
if (typeof query.nb !== 'undefined') {
newNb = parseInt(query.nb)
}
return {
term: query.term,
start: startingPoint,
nb: newNb
}
}
async function getAlbumDetails(dz: any, albumId: string): Promise<any> {
const result = await dz.gw.get_album_page(albumId)
const output = result.DATA
let duration = 0
result.SONGS.data.forEach((s: any) => {
if ('DURATION' in s) {
duration += parseInt(s.DURATION)
}
})
output.DURATION = duration
output.NUMBER_TRACK = result.SONGS.total
output.LINK = `https://deezer.com/album/${output.ALB_ID}`
return output
}
export { apiHandler, getAlbumDetails }

View File

@ -0,0 +1,30 @@
import { appSendGet } from '../../../../tests/utils'
describe('analyzeLink requests', () => {
it('should respond 200 to calls with supported term', async () => {
const res = await appSendGet('/api/analyzeLink/?term=https://www.deezer.com/en/album/100896762')
expect(res.status).toBe(200)
})
it('should respond with an error to calls with not supported term', async () => {
const res = await appSendGet('/api/analyzeLink/?term=https://www.deezer.com/en/artist/15166511')
expect(res.status).toBe(400)
expect(res.body.errorMessage).toBe('Not supported')
})
it('should respond album analyzed data', async () => {
const res = await appSendGet('/api/analyzeLink/?term=https://www.deezer.com/en/album/100896762')
expect(res.body.type).toBe('album')
expect(res.body.artist.name).toBe('Lil Nas X')
})
it('should respond track analyzed data', async () => {
const res = await appSendGet('/api/analyzeLink/?term=https://www.deezer.com/en/track/1283264142')
expect(res.body.type).toBe('track')
expect(res.body.artist.name).toBe('Lil Nas X')
})
})

View File

@ -0,0 +1,47 @@
import type { RequestHandler } from 'express'
// @ts-expect-error
import deemix from 'deemix'
// @ts-expect-error
import { Deezer } from 'deezer-js'
import type { ApiHandler, GetTrackResponse, GetAlbumResponse } from '../../../types'
import { sessionDZ } from '../../../app'
export interface AnalyzeQuery {
term?: string
}
type ResBody = GetAlbumResponse | GetTrackResponse
const path: ApiHandler['path'] = '/analyzeLink'
const handler: RequestHandler<ResBody, {}, {}, AnalyzeQuery> = async (req, res) => {
try {
if (!req.query || !req.query.term) {
return res.status(400).send({ errorMessage: 'No term specified', errorCode: 'AL01' })
}
const { term: linkToAnalyze } = req.query
const [, linkType, linkId] = await deemix.parseLink(linkToAnalyze)
const isTrackOrAlbum = ['track', 'album'].includes(linkType)
if (isTrackOrAlbum) {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const apiMethod = linkType === 'track' ? 'get_track' : 'get_album'
const resBody: ResBody = await dz.api[apiMethod](linkId)
return res.status(200).send(resBody)
}
return res.status(400).send({ errorMessage: 'Not supported', errorCode: 'AL02' })
} catch (error) {
return res
.status(500)
.send({ errorMessage: 'The server had a problem. Please try again', errorObject: error, errorCode: 'AL03' })
}
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,16 @@
import { ApiHandler } from '../../../types'
const path: ApiHandler['path'] = '/checkForUpdates'
const handler: ApiHandler['handler'] = async (req, res) => {
const deemix = req.app.get('deemix')
const latestCommit = await deemix.getLatestVersion()
res.send({
latestCommit,
updateAvailable: deemix.isUpdateAvailable()
})
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,50 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { logger } from '../../../helpers/logger'
import { getLoginCredentials } from '../../../helpers/loginStorage'
import { sessionDZ, deemixVersion, currentVersion } from '../../../app'
const path: ApiHandler['path'] = '/connect'
let update: any = null
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const deemix = req.app.get('deemix')
const isSingleUser = req.app.get('isSingleUser')
if (!update) {
logger.info(`Currently running deemix-gui version ${currentVersion}`)
logger.info(`deemix-lib version ${deemixVersion}`)
update = {
currentCommit: currentVersion,
deemixVersion
}
}
const result: any = {
update,
autologin: !dz.logged_in,
currentUser: dz.current_user,
deezerAvailable: await deemix.isDeezerAvailable(),
spotifyEnabled: deemix.plugins.spotify.enabled,
settingsData: deemix.getSettings()
}
if (isSingleUser && result.autologin) result.singleUser = getLoginCredentials()
if (result.settingsData.settings.autoCheckForUpdates) result.checkForUpdates = true
const queue = deemix.getQueue()
if (Object.keys(queue.queue).length > 0) {
result.queue = queue
}
res.send(result)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,45 @@
import { RequestHandler } from 'express'
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
import { isObjectEmpy } from '../../../helpers/primitive-checks'
import { BadRequestError, isBadRequestError } from '../../../helpers/errors'
import { logger } from '../../../helpers/logger'
export interface RawChartTracksQuery {
id: string
index?: number
limit?: number
}
const path: ApiHandler['path'] = '/getChartTracks'
const handler: RequestHandler<{}, {}, {}, RawChartTracksQuery> = async (req, res, next) => {
try {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
if (isObjectEmpy(req.query) || !req.query.id) {
throw new BadRequestError()
}
const playlistId = req.query.id
const index = req.query.index
const limit = req.query.limit
const response = await dz.api.get_playlist_tracks(playlistId, { index, limit })
return res.status(200).send(response)
} catch (error) {
if (isBadRequestError(error)) {
logger.error(error.message)
res.status(400).send()
return next()
}
}
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,33 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getCharts'
let chartsCache: any
const handler: ApiHandler['handler'] = async (req, res) => {
if (!chartsCache) {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const chartsData = await dz.api.get_countries_charts()
const countries: any[] = []
chartsData.forEach((country: any) => {
countries.push({
title: country.title.replace('Top ', ''),
id: country.id,
picture_small: country.picture_small,
picture_medium: country.picture_medium,
picture_big: country.picture_big
})
})
chartsCache = { data: countries }
}
res.send(chartsCache)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,22 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getHome'
let homeCache: any
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
if (!homeCache) {
homeCache = await dz.api.get_chart(0, { limit: 30 })
}
res.send(homeCache)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,16 @@
// import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
const path: ApiHandler['path'] = '/getQueue'
// let homeCache: any
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
const result: any = deemix.getQueue()
res.send(result)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,12 @@
import { ApiHandler } from '../../../types'
const path: ApiHandler['path'] = '/getSettings'
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
res.send(deemix.getSettings())
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,105 @@
// @ts-expect-error
import { Deezer, utils as dzUtils } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getTracklist'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const deemix = req.app.get('deemix')
const list_id = String(req.query.id)
const list_type = String(req.query.type)
switch (list_type) {
case 'artist': {
const artistAPI = await dz.api.get_artist(list_id)
artistAPI.releases = await dz.gw.get_artist_discography_tabs(list_id, { limit: 100 })
res.send(artistAPI)
break
}
case 'spotifyplaylist':
case 'spotify_playlist': {
if (!deemix.plugins.spotify.enabled) {
res.send({
collaborative: false,
description: '',
external_urls: { spotify: null },
followers: { total: 0, href: null },
id: null,
images: [],
name: 'Something went wrong',
owner: {
display_name: 'Error',
id: null
},
public: true,
tracks: [],
type: 'playlist',
uri: null
})
break
}
const sp = deemix.plugins.spotify.sp
let playlist = await sp.getPlaylist(list_id)
playlist = playlist.body
let tracklist = playlist.tracks.items
while (playlist.tracks.next) {
const regExec = /offset=(\d+)&limit=(\d+)/g.exec(playlist.tracks.next)
const offset = regExec![1]
const limit = regExec![2]
const playlistTracks = await sp.getPlaylistTracks(list_id, { offset, limit })
playlist.tracks = playlistTracks.body
tracklist = tracklist.concat(playlist.tracks.items)
}
tracklist.forEach((item: any, i: number) => {
tracklist[i] = item.track
tracklist[i].selected = false
})
playlist.tracks = tracklist
res.send(playlist)
break
}
default: {
let releaseAPI, releaseTracksAPI
try {
releaseAPI = await dz.api[`get_${list_type}`](list_id)
releaseTracksAPI = await dz.api[`get_${list_type}_tracks`](list_id)
releaseTracksAPI = releaseTracksAPI.data
} catch {
if (list_type === 'playlist') {
releaseAPI = dzUtils.map_playlist(await (await dz.gw.get_playlist_page(list_id)).DATA)
releaseTracksAPI = await dz.gw.get_playlist_tracks(list_id)
} else {
releaseAPI = {}
releaseTracksAPI = []
}
}
const tracks: any[] = []
const showdiscs =
list_type === 'album' &&
releaseTracksAPI.length &&
releaseTracksAPI[releaseTracksAPI.length - 1].disk_number !== 1
let current_disk = 0
releaseTracksAPI.forEach((track: any) => {
if (track.SNG_ID) track = dzUtils.map_track(track)
if (showdiscs && parseInt(track.disk_number) !== current_disk) {
current_disk = parseInt(track.disk_number)
tracks.push({ type: 'disc_separator', number: current_disk })
}
track.selected = false
tracks.push(track)
})
releaseAPI.tracks = tracks
res.send(releaseAPI)
break
}
}
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,24 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getUserAlbums'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
let data
if (dz.logged_in) {
const userID = dz.current_user.id
data = await dz.gw.get_user_albums(userID, { limit: -1 })
} else {
data = { error: 'notLoggedIn' }
}
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,24 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getUserArtists'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
let data
if (dz.logged_in) {
const userID = dz.current_user.id
data = await dz.gw.get_user_artists(userID, { limit: -1 })
} else {
data = { error: 'notLoggedIn' }
}
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,30 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getUserFavorites'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
let result: any = {}
if (dz.logged_in) {
const userID = dz.current_user.id
result.playlists = await dz.gw.get_user_playlists(userID, { limit: -1 })
result.albums = await dz.gw.get_user_albums(userID, { limit: -1 })
result.artists = await dz.gw.get_user_artists(userID, { limit: -1 })
result.tracks = await dz.gw.get_my_favorite_tracks({ limit: -1 })
result.lovedTracks = `https://deezer.com/playlist/${dz.current_user.loved_tracks}`
} else {
result = { error: 'notLoggedIn' }
}
res.send(result)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,24 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getUserPlaylists'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
let data
if (dz.logged_in) {
const userID = dz.current_user.id
data = await dz.gw.get_user_playlists(userID, { limit: -1 })
} else {
data = { error: 'notLoggedIn' }
}
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,41 @@
import { ApiHandler } from '../../../types'
const path: ApiHandler['path'] = '/getUserSpotifyPlaylists'
const handler: ApiHandler['handler'] = async (req, res) => {
let data
const deemix = req.app.get('deemix')
if (deemix.plugins.spotify.enabled) {
const sp = deemix.plugins.spotify.sp
const username = req.query.spotifyUser
data = []
let playlists
try {
playlists = await sp.getUserPlaylists(username)
} catch (e) {
res.send({ error: 'wrongSpotifyUsername', username })
return
}
playlists = playlists.body
let playlistList = playlists.items
while (playlists.next) {
const regExec = /offset=(\d+)&limit=(\d+)/g.exec(playlists.next)
const offset = regExec![1]
const limit = regExec![2]
const newPlaylists = await sp.getUserPlaylists(username, { offset, limit })
playlists = newPlaylists.body
playlistList = playlistList.concat(playlists.items)
}
playlistList.forEach((playlist: any) => {
data.push(deemix.plugins.spotify._convertPlaylistStructure(playlist))
})
} else {
data = { error: 'spotifyNotEnabled' }
}
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,23 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/getUserTracks'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
let data
if (dz.logged_in) {
data = await dz.gw.get_my_favorite_tracks({ limit: -1 })
} else {
data = { error: 'notLoggedIn' }
}
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,43 @@
import connect from './connect'
import analyzeLink from './analyzeLink'
import getHome from './getHome'
import getCharts from './getCharts'
import mainSearch from './mainSearch'
import search from './search'
import newReleases from './newReleases'
import getTracklist from './getTracklist'
import { apiHandler as albumSearch } from './albumSearch'
import getChartTracks from './getChartTracks'
import getSettings from './getSettings'
import getUserTracks from './getUserTracks'
import getUserAlbums from './getUserAlbums'
import getUserArtists from './getUserArtists'
import getUserPlaylists from './getUserPlaylists'
import getUserSpotifyPlaylists from './getUserSpotifyPlaylists'
import getUserFavorites from './getUserFavorites'
import getQueue from './getQueue'
import spotifyStatus from './spotifyStatus'
import checkForUpdates from './checkForUpdates'
export default [
connect,
albumSearch,
analyzeLink,
getHome,
getCharts,
getChartTracks,
mainSearch,
search,
newReleases,
getTracklist,
getSettings,
getUserTracks,
getUserAlbums,
getUserArtists,
getUserPlaylists,
getUserSpotifyPlaylists,
getUserFavorites,
getQueue,
spotifyStatus,
checkForUpdates
]

View File

@ -0,0 +1,160 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/mainSearch'
const emptyResult = {
QUERY: '',
FUZZINNESS: true,
AUTOCORRECT: false,
ORDER: ['TOP_RESULT', 'TRACK', 'ARTIST', 'ALBUM', 'PLAYLIST'],
TOP_RESULT: [],
ARTIST: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
ALBUM: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
TRACK: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 10
},
PLAYLIST: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
RADIO: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
USER: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
SHOW: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
CHANNEL: {
data: [],
count: 0,
total: 0
},
LIVESTREAM: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
EPISODE: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
LYRICS: {
data: [],
count: 0,
total: 0,
filtered_count: 0,
filtered_items: [],
next: 20
},
ERROR: ''
}
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const term = String(req.query.term)
let results
try {
results = await dz.gw.search(term)
} catch (e) {
results = { ...emptyResult }
results.QUERY = term
results.ERROR = e.message
}
const order: string[] = []
results.ORDER.forEach((element: string) => {
if (['TOP_RESULT', 'TRACK', 'ALBUM', 'ARTIST', 'PLAYLIST'].includes(element)) order.push(element)
})
if (results.TOP_RESULT && results.TOP_RESULT.length) {
const originalTopResult = results.TOP_RESULT[0]
const topResult: any = {
type: originalTopResult.__TYPE__
}
switch (topResult.type) {
case 'artist':
topResult.id = originalTopResult.ART_ID
topResult.picture = `https://e-cdns-images.dzcdn.net/images/artist/${originalTopResult.ART_PICTURE}`
topResult.title = originalTopResult.ART_NAME
topResult.nb_fan = originalTopResult.NB_FAN
break
case 'album':
topResult.id = originalTopResult.ALB_ID
topResult.picture = `https://e-cdns-images.dzcdn.net/images/cover/${originalTopResult.ALB_PICTURE}`
topResult.title = originalTopResult.ALB_TITLE
topResult.artist = originalTopResult.ART_NAME
topResult.nb_song = originalTopResult.NUMBER_TRACK
break
case 'playlist':
topResult.id = originalTopResult.PLAYLIST_ID
topResult.picture = `https://e-cdns-images.dzcdn.net/images/${originalTopResult.PICTURE_TYPE}/${originalTopResult.PLAYLIST_PICTURE}`
topResult.title = originalTopResult.TITLE
topResult.artist = originalTopResult.PARENT_USERNAME
topResult.nb_song = originalTopResult.NB_SONG
break
default:
topResult.id = '0'
topResult.picture = 'https://e-cdns-images.dzcdn.net/images/cover'
break
}
topResult.picture += '/156x156-000000-80-0-0.jpg'
topResult.link = `https://deezer.com/${topResult.type}/${topResult.id}`
results.TOP_RESULT = [topResult]
}
results.ORDER = order
res.send(results)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,74 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
import { getAlbumDetails } from './albumSearch'
const path: ApiHandler['path'] = '/newReleases'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const results = await dz.gw.get_page('channels/explore')
const music_section = results.sections.find((e: any) =>
e.section_id.includes('module_id=83718b7b-5503-4062-b8b9-3530e2e2cefa')
)
const channels = music_section.items.map((e: any) => e.target)
const newReleasesByChannel = <any[][]>await Promise.all(channels.map((c: string) => channelNewReleases(dz, c)))
const seen = new Set()
const distinct: any[] = []
newReleasesByChannel.forEach(l => {
l.forEach(r => {
if (!seen.has(r.ALB_ID)) {
seen.add(r.ALB_ID)
distinct.push(r)
}
})
})
distinct.sort((a, b) =>
a.DIGITAL_RELEASE_DATE < b.DIGITAL_RELEASE_DATE ? 1 : b.DIGITAL_RELEASE_DATE < a.DIGITAL_RELEASE_DATE ? -1 : 0
)
const now = Date.now()
const delta = 8 * 24 * 60 * 60 * 1000
const recent = distinct.filter((x: any) => now - Date.parse(x.DIGITAL_RELEASE_DATE) < delta)
const albums = await Promise.all(recent.map((c: any) => getAlbumDetails(dz, c.ALB_ID)))
const output = {
data: albums,
total: albums.length
}
return res.send(output)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler
async function channelNewReleases(dz: any, channelName: string): Promise<any[]> {
const channelData = await dz.gw.get_page(channelName)
const re = /^New.*releases$/
const newReleases = channelData.sections.find((e: any) => re.test(e.title))
if (!newReleases) {
return []
} else if ('target' in newReleases) {
const showAll = await dz.gw.get_page(newReleases.target)
return showAll.sections[0].items.map((e: any) => e.data)
} else if ('items' in newReleases) {
return newReleases.items.map((e: any) => e.data)
} else {
return []
}
}

View File

@ -0,0 +1,61 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/search'
const emptyResult = {
data: [],
total: 0,
type: '',
error: ''
}
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const term = String(req.query.term)
const type = String(req.query.type)
const start = parseInt(String(req.query.start))
const nb = parseInt(String(req.query.nb))
let data
try {
switch (type) {
case 'track':
data = await dz.api.search_track(term, { limit: nb, index: start })
break
case 'album':
data = await dz.api.search_album(term, { limit: nb, index: start })
break
case 'artist':
data = await dz.api.search_artist(term, { limit: nb, index: start })
break
case 'playlist':
data = await dz.api.search_playlist(term, { limit: nb, index: start })
break
case 'radio':
data = await dz.api.search_radio(term, { limit: nb, index: start })
break
case 'user':
data = await dz.api.search_user(term, { limit: nb, index: start })
break
default:
data = await dz.api.search(term, { limit: nb, index: start })
break
}
} catch (e) {
data = { ...emptyResult }
data.error = e.message
}
data.type = type
res.send(data)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,12 @@
import { ApiHandler } from '../../../types'
const path: ApiHandler['path'] = '/spotifyStatus'
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
res.send({ spotifyEnabled: deemix.plugins.spotify.enabled })
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,3 @@
import { ApiHandler } from '../../../types'
export default [] as ApiHandler[]

View File

@ -0,0 +1,43 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
import { logger } from '../../../helpers/logger'
const path: ApiHandler['path'] = '/addToQueue'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const deemix = req.app.get('deemix')
const dz = sessionDZ[req.session.id]
const url = req.body.url.split(/[\s;]+/)
let bitrate = req.body.bitrate
if (bitrate === 'null' || bitrate === null) bitrate = deemix.getSettings().settings.maxBitrate
bitrate = Number(bitrate)
let obj: any
try {
obj = await deemix.addToQueue(dz, url, bitrate)
} catch (e) {
res.send({ result: false, errid: e.name, data: { url, bitrate } })
switch (e.name) {
case 'NotLoggedIn':
deemix.listener.send('queueError' + e.name)
break
case 'CantStream':
deemix.listener.send('queueError' + e.name, e.bitrate)
break
default:
logger.error(e)
break
}
return
}
res.send({ result: true, data: { url, bitrate, obj } })
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,13 @@
import { ApiHandler } from '../../../types'
const path = '/cancelAllDownloads'
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
deemix.cancelAllDownloads()
res.send({ result: true })
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,15 @@
import { appSendGet } from '../../../../tests/utils'
describe('analyzeLink requests', () => {
it('should respond 200 to calls with supported child number', async () => {
const res = await appSendGet('/api/changeAccount/?child=1')
expect(res.status).toBe(200)
})
it('should respond 400 to calls with not supported child number', async () => {
const res = await appSendGet('/api/changeAccount/')
expect(res.status).toBe(400)
})
})

View File

@ -0,0 +1,31 @@
import { RequestHandler } from 'express'
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
const path: ApiHandler['path'] = '/changeAccount'
interface ChangeAccountQuery {
child: number
}
const handler: RequestHandler<{}, {}, {}, ChangeAccountQuery> = (req, res) => {
if (!req.query || !req.query.child) {
return res.status(400).send({ errorMessage: 'No child specified', errorCode: 'CA01' })
}
const { child: accountNum } = req.query
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const dz = sessionDZ[req.session.id]
const accountData = dz.change_account(accountNum)
return res.status(200).send(accountData)
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,23 @@
import changeAccount from './changeAccount'
import loginArl from './loginArl'
import addToQueue from './addToQueue'
import loginEmail from './loginEmail'
import cancelAllDownloads from './cancelAllDownloads'
import removeFinishedDownloads from './removeFinishedDownloads'
import removeFromQueue from './removeFromQueue'
import logout from './logout'
import saveSettings from './saveSettings'
import retryDownload from './retryDownload'
export default [
changeAccount,
loginArl,
addToQueue,
loginEmail,
cancelAllDownloads,
removeFinishedDownloads,
removeFromQueue,
logout,
saveSettings,
retryDownload
]

View File

@ -0,0 +1,40 @@
import { appSendPost } from '../../../../tests/utils'
describe('loginArl requests', () => {
it('should respond 200 to calls with arl', async () => {
const responseStatusCollector: number[] = []
const batchCalls = ['/api/loginArl/?arl=abcdef1234']
for (const uri of batchCalls) {
responseStatusCollector.push((await appSendPost(uri)).status)
}
expect(responseStatusCollector).toMatchObject(new Array(batchCalls.length).fill(200))
expect(responseStatusCollector).toMatchObject(new Array(responseStatusCollector.length).fill(200))
})
it('should respond 400 to calls without arl', async () => {
const responseStatusCollector: number[] = []
const batchCalls = ['/api/loginArl/', '/api/loginArl/?dummy=test', '/api/loginArl/?email=aaa@aa.com']
for (const uri of batchCalls) {
responseStatusCollector.push((await appSendPost(uri)).status)
}
expect(responseStatusCollector).toMatchObject(new Array(responseStatusCollector.length).fill(400))
})
it('should login using ARL', async () => {
const response = await appSendPost(`/api/loginArl/?arl=${process.env.DEEZER_ARL}`)
expect(response.status).toBe(200)
expect(response.body.status).toBe(true)
})
it('should not login using wrong ARL', async () => {
const response = await appSendPost(`/api/loginArl/?arl=abcdef1234`)
expect(response.status).toBe(200)
expect(response.body.status).toBe(false)
})
})

View File

@ -0,0 +1,87 @@
import { RequestHandler } from 'express'
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { sessionDZ } from '../../../app'
import { ApiHandler } from '../../../types'
import { logger } from '../../../helpers/logger'
import { saveLoginCredentials, resetLoginCredentials } from '../../../helpers/loginStorage'
export interface RawLoginArlBody {
arl: string
child?: number
}
const LoginStatus = {
NOT_AVAILABLE: -1,
FAILED: 0,
SUCCESS: 1,
ALREADY_LOGGED: 2,
FORCED_SUCCESS: 3
}
const path: ApiHandler['path'] = '/loginArl'
const handler: RequestHandler<{}, {}, RawLoginArlBody, {}> = async (req, res, _) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const deemix = req.app.get('deemix')
const dz = sessionDZ[req.session.id]
const isSingleUser = req.app.get('isSingleUser')
if (!req.body) {
return res.status(400).send()
}
if (!req.body.arl) {
return res.status(400).send()
}
const loginParams: (string | number)[] = [req.body.arl]
// TODO Handle the child === 0 case, don't want to rely on the login_via_arl default param (it may change in the
// future)
if (req.body.child) {
loginParams.push(req.body.child)
}
let response
if (process.env.NODE_ENV !== 'test') {
if (!dz.logged_in) {
try {
response = await dz.login_via_arl(...loginParams)
} catch (e) {
logger.error(e)
response = false
}
response = response ? 1 : 0
} else {
response = LoginStatus.ALREADY_LOGGED
}
} else {
const testDz = new Deezer()
response = await testDz.login_via_arl(...loginParams)
}
if (response === LoginStatus.FAILED) sessionDZ[req.session.id] = new Deezer()
if (!(await deemix.isDeezerAvailable())) response = LoginStatus.NOT_AVAILABLE
const returnValue = {
status: response,
arl: req.body.arl,
user: dz.current_user,
childs: dz.childs,
currentChild: dz.selected_account
}
if (response !== LoginStatus.NOT_AVAILABLE && response !== LoginStatus.FAILED) {
deemix.startQueue(dz)
if (isSingleUser)
saveLoginCredentials({
accessToken: null,
arl: returnValue.arl
})
} else if (isSingleUser) resetLoginCredentials()
return res.status(200).send(returnValue)
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,30 @@
import { ApiHandler } from '../../../types'
import { getAccessToken, getArlFromAccessToken } from '../../../app'
import { saveLoginCredentials } from '../../../helpers/loginStorage'
const path = '/loginEmail'
const handler: ApiHandler['handler'] = async (req, res) => {
const isSingleUser = req.app.get('isSingleUser')
const { email, password } = req.body
let accessToken = req.body.accessToken
if (!accessToken) {
accessToken = await getAccessToken(email, password)
if (accessToken === 'undefined') accessToken = undefined
}
let arl
if (accessToken) arl = await getArlFromAccessToken(accessToken)
if (isSingleUser && accessToken)
saveLoginCredentials({
accessToken,
arl: arl || null
})
res.send({ accessToken, arl })
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,17 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
import { resetLoginCredentials } from '../../../helpers/loginStorage'
const path: ApiHandler['path'] = '/logout'
const handler: ApiHandler['handler'] = (req, res) => {
sessionDZ[req.session.id] = new Deezer()
res.send({ logged_out: true })
if (req.app.get('isSingleUser')) resetLoginCredentials()
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,13 @@
import { ApiHandler } from '../../../types'
const path = '/removeFinishedDownloads'
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
deemix.clearCompletedDownloads()
res.send({ result: true })
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,18 @@
import { ApiHandler } from '../../../types'
const path = '/removeFromQueue'
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
const { uuid } = req.query
if (uuid) {
deemix.cancelDownload(uuid)
res.send({ result: true })
} else {
res.send({ result: false })
}
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,56 @@
// @ts-expect-error
import { Deezer } from 'deezer-js'
import { ApiHandler } from '../../../types'
import { sessionDZ } from '../../../app'
import { logger } from '../../../helpers/logger'
const path: ApiHandler['path'] = '/retryDownload'
const handler: ApiHandler['handler'] = async (req, res) => {
if (!sessionDZ[req.session.id]) sessionDZ[req.session.id] = new Deezer()
const deemix = req.app.get('deemix')
const dz = sessionDZ[req.session.id]
const uuid = req.body.uuid
const data = uuid.split('_')
let url = ''
let bitrate = 0
if (data.lenght === 4) {
if (data[0] === 'spotify') {
url = `https://open.spotify.com/${data[1]}/${data[2]}`
bitrate = Number(data[3])
}
} else {
if (data[0] === 'playlist' && data[1].endsWith('_top_track')) {
data[0] = 'artist'
data[1] = data[1].replace('_top_track', '/top_track')
}
url = `https://www.deezer.com/${data[0]}/${data[1]}`
bitrate = Number(data[2])
}
let obj: any
try {
obj = await deemix.addToQueue(dz, [url], bitrate, true)
} catch (e) {
res.send({ result: false, errid: e.name, data: { url, bitrate } })
switch (e.name) {
case 'NotLoggedIn':
deemix.listener.send('queueError' + e.name)
break
case 'CantStream':
deemix.listener.send('queueError' + e.name, e.bitrate)
break
default:
logger.error(e)
break
}
return
}
res.send({ result: true, data: { url, bitrate, obj } })
}
const apiHandler: ApiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,20 @@
import { ApiHandler, Settings, SpotifySettings } from '../../../types'
const path = '/saveSettings'
export interface SaveSettingsData {
settings: Settings
spotifySettings: SpotifySettings
}
const handler: ApiHandler['handler'] = (req, res) => {
const deemix = req.app.get('deemix')
const { settings, spotifySettings }: SaveSettingsData = req.query
deemix.saveSettings(settings, spotifySettings)
deemix.listener.send('updateSettings', { settings, spotifySettings })
res.send({ result: true })
}
const apiHandler = { path, handler }
export default apiHandler

View File

@ -0,0 +1,46 @@
import type { Application } from 'express'
import type { ApiHandler } from '../../types'
import getEndpoints from './get'
import deleteEndpoints from './delete'
import postEndpoints from './post'
import patchEndpoints from './patch'
const prependApiPath = (path: string) => `*/api${path}`
interface Method {
method: string
endpoints: ApiHandler[]
}
const methods: Method[] = [
{
method: 'get',
endpoints: getEndpoints
},
{
method: 'delete',
endpoints: deleteEndpoints
},
{
method: 'post',
endpoints: postEndpoints
},
{
method: 'patch',
endpoints: patchEndpoints
}
]
export function registerApis(app: Application) {
methods.forEach(({ method, endpoints }) => {
endpoints.forEach(endpoint => {
// @ts-expect-error
app[method](prependApiPath(endpoint.path), endpoint.handler)
})
})
// Fallback, for SPA mode
app.get('*/api*', (_, res) => {
res.send({ error: "API endpoint doesn't exist" })
})
}

View File

@ -0,0 +1,35 @@
import request from 'supertest'
import { app } from '../app'
describe('root path requests', () => {
it('responds 200 to the GET method', async () => {
const result = await request(app).get('/').send()
expect(result.status).toBe(200)
})
it('responds 404 to the POST method', async () => {
const result = await request(app).post('/').send()
expect(result.status).toBe(404)
})
it('responds 404 to the PATCH method', async () => {
const result = await request(app).patch('/').send()
expect(result.status).toBe(404)
})
it('responds 404 to the DELETE method', async () => {
const result = await request(app).delete('/').send()
expect(result.status).toBe(404)
})
it('redirects to root when a non existing server route is requested', async () => {
const result = await request(app).get('/settings').send()
expect(result.header.location).toBe('/')
expect(result.status).toBe(302)
})
})

View File

@ -0,0 +1,4 @@
import express from 'express'
const router = express.Router()
export default router

125
server/src/server.ts Normal file
View File

@ -0,0 +1,125 @@
import http, { Server } from 'http'
import path from 'path'
import fs from 'fs'
import express, { Application } from 'express'
import ejs from 'ejs'
import { Server as WsServer, OPEN as WsOpen } from 'ws'
import initDebug from 'debug'
// @ts-expect-error
import deemix from 'deemix'
import { registerMiddlewares } from './middlewares'
import indexRouter from './routes'
import { getErrorCb, getListeningCb } from './helpers/server-callbacks'
import { registerApis } from './routes/api/register'
import { registerWebsocket } from './websocket'
import { logger, removeOldLogs } from './helpers/logger'
import { loadLoginCredentials } from './helpers/loginStorage'
import { Port, Listener } from './types'
import { DeemixApp } from './app'
import { normalizePort } from './helpers/port'
import { WEBUI_DIR } from './helpers/paths'
export class DeemixServer {
host: string
port: Port
locationBase: string
isSingleUser: boolean
wss: WsServer
app: Application
server: Server
deemixApp: DeemixApp
constructor(host: string, port: string, locationBase: string, singleuser: boolean = false) {
this.host = host
this.port = normalizePort(port)
this.locationBase = locationBase
this.isSingleUser = singleuser
this.wss = new WsServer({ noServer: true })
this.app = express()
this.server = http.createServer(this.app)
const listener: Listener = {
send: (key: string, data?: any) => {
const logLine = deemix.utils.formatListener(key, data)
if (logLine) logger.info(logLine)
if (['downloadInfo', 'downloadWarn'].includes(key)) return
this.wss.clients.forEach(client => {
if (client.readyState === WsOpen) {
client.send(JSON.stringify({ key, data }))
}
})
}
}
this.deemixApp = new DeemixApp(listener)
if (this.isSingleUser) loadLoginCredentials()
}
init() {
const debug = initDebug('deemix-gui:server')
this.app.set('deemix', this.deemixApp)
this.app.set('isSingleUser', this.isSingleUser)
/* === Middlewares === */
registerMiddlewares(this.app)
/* === Routes === */
this.app.use('/', indexRouter)
/* === APIs === */
registerApis(this.app)
/* === Fallback === */
this.app.get('*/favicon.ico', (_, res) => {
res.sendFile(path.join(WEBUI_DIR, 'favicon.ico'))
})
this.app.get('*/js/*', (req, res) => {
const link = req.url.substr(req.url.indexOf('/js/'))
res.sendFile(path.join(WEBUI_DIR, link))
})
this.app.get('*/fonts/*', (req, res) => {
const link = req.url.substr(req.url.indexOf('/fonts/'))
res.sendFile(path.join(WEBUI_DIR, link))
})
this.app.get('*/res/*', (req, res) => {
const link = req.url.substr(req.url.indexOf('/res/'))
res.sendFile(path.join(WEBUI_DIR, link))
})
this.app.get('*', (req, res) => {
console.log(req.url)
fs.readFile(path.join(WEBUI_DIR, 'index.ejs'), (_, html) => {
res.send(ejs.render(html.toString(), { locationBase: this.locationBase }))
})
})
/* === Config === */
this.app.set('port', this.port)
/* === Server port === */
if (process.env.NODE_ENV !== 'test') {
this.server.listen({ port: this.port, host: this.host })
}
registerWebsocket(this.wss, this.deemixApp)
/* === Server callbacks === */
this.app.on('mount', a => {
logger.info(a)
})
this.server.on('connect', () => {
logger.info('Server connected')
})
this.server.on('upgrade', (request, socket, head) => {
this.wss.handleUpgrade(request, socket, head, socket => {
this.wss.emit('connection', socket, request)
})
})
this.server.on('error', getErrorCb(this.port))
this.server.on('listening', getListeningCb(this.server, debug))
/* === Remove Old logs files === */
removeOldLogs(5)
}
}

252
server/src/types.ts Normal file
View File

@ -0,0 +1,252 @@
import { RequestHandler } from 'express'
/* === Utilities === */
// https://github.com/Microsoft/TypeScript/issues/25760#issuecomment-614417742
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<T>
export type Port = number | string | boolean
export interface ApiHandler {
path: string
handler: RequestHandler<any, any, any, any>
}
export interface Tags {
title: boolean
artist: boolean
album: boolean
cover: boolean
trackNumber: boolean
trackTotal: boolean
discNumber: boolean
discTotal: boolean
albumArtist: boolean
genre: boolean
year: boolean
date: boolean
explicit: boolean
isrc: boolean
length: boolean
barcode: boolean
bpm: boolean
replayGain: boolean
label: boolean
lyrics: boolean
syncedLyrics: boolean
copyright: boolean
composer: boolean
involvedPeople: boolean
source: boolean
savePlaylistAsCompilation: boolean
useNullSeparator: boolean
saveID3v1: boolean
multiArtistSeparator: string
singleAlbumArtist: boolean
coverDescriptionUTF8: boolean
}
export interface Settings {
downloadLocation: string
tracknameTemplate: string
albumTracknameTemplate: string
playlistTracknameTemplate: string
createPlaylistFolder: boolean
playlistNameTemplate: string
createArtistFolder: boolean
artistNameTemplate: string
createAlbumFolder: boolean
albumNameTemplate: string
createCDFolder: boolean
createStructurePlaylist: boolean
createSingleFolder: boolean
padTracks: boolean
paddingSize: string
illegalCharacterReplacer: string
queueConcurrency: number
maxBitrate: string
fallbackBitrate: boolean
fallbackSearch: boolean
logErrors: boolean
logSearched: boolean
saveDownloadQueue: boolean
overwriteFile: string
createM3U8File: boolean
playlistFilenameTemplate: string
syncedLyrics: boolean
embeddedArtworkSize: number
embeddedArtworkPNG: boolean
localArtworkSize: number
localArtworkFormat: string
saveArtwork: boolean
coverImageTemplate: string
saveArtworkArtist: boolean
artistImageTemplate: string
jpegImageQuality: number
dateFormat: string
albumVariousArtists: boolean
removeAlbumVersion: boolean
removeDuplicateArtists: boolean
tagsLanguage: string
featuredToTitle: string
titleCasing: string
artistCasing: string
executeCommand: string
tags: Tags
}
// TODO
export interface SpotifySettings {}
interface BaseDeezerObject {
id: number
type: string
}
interface NamedDeezerObject extends BaseDeezerObject {
name: string
}
interface PicturedDeezerObject extends BaseDeezerObject {
picture: string
picture_small: string
picture_medium: string
picture_big: string
picture_xl: string
}
interface CoveredDeezerObject extends BaseDeezerObject {
cover: string
cover_small: string
cover_medium: string
cover_big: string
cover_xl: string
}
interface DeezerWrapper<Type> {
data: Type[]
}
export interface DeezerContributor extends NamedDeezerObject, PicturedDeezerObject {
link: string
share: string
radio: boolean
tracklist: string
role: string
}
export interface DeezerTrackArtist extends NamedDeezerObject, PicturedDeezerObject {
link: string
share: string
radio: boolean
tracklist: string
}
export interface DeezerAlbumArtist extends NamedDeezerObject, PicturedDeezerObject {
tracklist: string
}
export interface DeezerAlbum extends BaseDeezerObject, CoveredDeezerObject {
title: string
link: string
md5_image: string
release_date: string
tracklist: string
}
export interface DeezerGenre extends NamedDeezerObject {
picture: string
}
type DeezerGenres = DeezerWrapper<DeezerGenre>
export interface GetAlbumTrackArtist extends NamedDeezerObject {
tracklist: string
}
export interface DeezerTrack extends BaseDeezerObject {
readable: boolean
title: string
title_short: string
title_version: string
link: string
duration: number
rank: number
explicit_lyrics: boolean
explicit_content_lyrics: number
explicit_content_cover: number
preview: string
md5_image: string
artist: GetAlbumTrackArtist
}
type DeezerTracks = DeezerWrapper<DeezerTrack>
export interface GetTrackResponse extends BaseDeezerObject {
readable: boolean
title: string
title_short: string
title_version: string
isrc: string
link: string
share: string
duration: number
track_position: number
disk_number: number
rank: number
release_date: string
explicit_lyrics: boolean
explicit_content_lyrics: number
explicit_content_cover: number
preview: string
bpm: number
gain: number
available_countries: string[]
contributors: DeezerContributor[]
md5_image: string
artist: DeezerTrackArtist
album: DeezerAlbum
}
export interface GetAlbumResponse extends BaseDeezerObject, CoveredDeezerObject {
title: string
upc: string
link: string
share: string
md5_image: string
genre_id: number
genres: DeezerGenres
label: string
nb_tracks: number
duration: number
fans: number
rating: number
release_date: string
record_type: string
available: boolean
tracklist: string
explicit_lyrics: boolean
explicit_content_lyrics: number
explicit_content_cover: number
contributors: DeezerContributor[]
artist: DeezerAlbumArtist
tracks: DeezerTracks
}
export interface Arguments {
port: string
host: string
locationbase: string
singleuser: boolean
[x: string]: unknown
$0: string
}
export interface Listener {
send: (key: string, data?: any) => void
}
export interface LoginFile {
arl: string | null
accessToken: string | null
}

View File

@ -0,0 +1,27 @@
import { Server as WsServer } from 'ws'
import { logger } from '../helpers/logger'
import { DeemixApp } from '../app'
import wsModules from './modules'
export const registerWebsocket = (wss: WsServer, deemix: DeemixApp) => {
wss.on('connection', ws => {
ws.on('message', message => {
const data = JSON.parse(message.toString())
wsModules.forEach(module => {
if (data.key === module.eventName) {
module.cb(data.data, ws, wss, deemix)
}
})
})
})
wss.on('error', () => {
logger.error('An error occurred to the WebSocket server.')
})
wss.on('close', () => {
logger.info('Connection to the WebSocket server closed.')
})
}

View File

@ -0,0 +1,12 @@
import { Server as WsServer } from 'ws'
import { logger } from '../../helpers/logger'
import { DeemixApp } from '../../app'
const eventName = 'cancelAllDownloads'
const cb = (_: any, __: any, ___: WsServer, deemix: DeemixApp) => {
deemix.cancelAllDownloads()
logger.info(`Queue cleared`)
}
export default { eventName, cb }

View File

@ -0,0 +1,6 @@
import saveSettings from './saveSettings'
import removeFinishedDownloads from './removeFinishedDownloads'
import removeFromQueue from './removeFromQueue'
import cancelAllDownloads from './cancelAllDownloads'
export default [saveSettings, removeFinishedDownloads, removeFromQueue, cancelAllDownloads]

View File

@ -0,0 +1,12 @@
import { Server as WsServer } from 'ws'
import { logger } from '../../helpers/logger'
import { DeemixApp } from '../../app'
const eventName = 'removeFinishedDownloads'
const cb = (_: any, __: any, ___: WsServer, deemix: DeemixApp) => {
deemix.clearCompletedDownloads()
logger.info('Completed downloads cleared')
}
export default { eventName, cb }

View File

@ -0,0 +1,12 @@
import { Server as WsServer } from 'ws'
import { logger } from '../../helpers/logger'
import { DeemixApp } from '../../app'
const eventName = 'removeFromQueue'
const cb = (data: any, __: any, ___: WsServer, deemix: DeemixApp) => {
deemix.cancelDownload(data)
logger.info(`Cancelled ${data}`)
}
export default { eventName, cb }

View File

@ -0,0 +1,20 @@
import { Server as WsServer } from 'ws'
import { logger } from '../../helpers/logger'
import { DeemixApp } from '../../app'
import { Settings, SpotifySettings } from '../../types'
const eventName = 'saveSettings'
export interface SaveSettingsData {
settings: Settings
spotifySettings: SpotifySettings
}
const cb = (data: SaveSettingsData, _: any, __: WsServer, deemix: DeemixApp) => {
const { settings, spotifySettings } = data
deemix.saveSettings(settings, spotifySettings)
logger.info('Settings saved')
deemix.listener.send('updateSettings', { settings, spotifySettings })
}
export default { eventName, cb }

View File

@ -0,0 +1,30 @@
// Taken from https://github.com/visionmedia/supertest
import request from 'supertest'
import express from 'express'
import cookieParser from 'cookie-parser'
describe('cookie parser', () => {
const app = express()
app.use(cookieParser())
app.get('/', (_, res) => {
res.cookie('cookie', 'hey')
res.send()
})
app.get('/return', (req, res) => {
if (req.cookies.cookie) res.send(req.cookies.cookie)
else res.send(':(')
})
const agent = request.agent(app)
it('should save cookies', done => {
agent.get('/').expect('set-cookie', 'cookie=hey; Path=/', done)
})
it('should send cookies', done => {
agent.get('/return').expect('hey', done)
})
})

9
server/tests/utils.ts Normal file
View File

@ -0,0 +1,9 @@
import { Application } from 'express'
import request from 'supertest'
import { app } from '../src/app'
export const sendGet = (app: Application) => (uri: string) => request(app).get(uri).send()
export const sendPost = (app: Application) => (uri: string) => request(app).post(uri).send()
export const appSendGet = sendGet(app)
export const appSendPost = sendPost(app)

76
server/tsconfig.json Normal file
View File

@ -0,0 +1,76 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": [
"node_modules",
"**/*.spec.ts",
"tests/**"
]
}

50
server/webpack.config.js Normal file
View File

@ -0,0 +1,50 @@
const path = require('path')
const webpack = require('webpack')
const NodemonPlugin = require('nodemon-webpack-plugin')
module.exports = env => {
const isProduction = !!env.production
const generateSourceMap = !!env.sourcemap
let devtool = 'eval'
if (isProduction) {
devtool = generateSourceMap ? 'source-map' : false
}
const config = {
mode: isProduction ? 'production' : 'development',
entry: './src/index.ts',
devtool,
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'app.js',
sourceMapFilename: '[file].map',
library: {
name: 'DeemixServer',
type: 'umd'
}
},
target: 'node',
plugins: [
new NodemonPlugin(),
new webpack.DefinePlugin({ 'global.GENTLY': false }),
new webpack.ContextReplacementPlugin(/[/\\](express|keyv)[/\\]/, data => {
delete data.dependencies[0].critical
return data
}),
new webpack.ContextReplacementPlugin(/yargs/)
]
}
return config
}

7049
server/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

148
webui/.gitattributes vendored Normal file
View File

@ -0,0 +1,148 @@
## Source: https://github.com/ptkdev-boilerplate/node-cli-boilerplate/blob/main/.gitattributes
## AUTO-DETECT
* text=auto
## SOURCE CODE
*.bat text eol=crlf
*.css text eol=lf
*.html text diff=html eol=lf
*.ini text eol=crlf
*.js text eol=lf
*.json text eol=lf
*.php text diff=php eol=lf
*.py text diff=python eol=lf
*.rb text diff=ruby
*.sass text eol=lf
*.scss text eol=lf
*.sh text eol=lf
*.sql text eol=lf
*.ts text eol=lf
*.vue text eol=lf
*.svelte text eol=lf
*.xml text eol=lf
*.xhtml text diff=html eol=lf
## DOCKER
*.dockerignore text eol=lf
Dockerfile text eol=lf
## DOCUMENTATION
*.md text eol=lf
*.txt text eol=lf
AUTHORS text eol=lf
CHANGELOG text eol=lf
CHANGES text eol=lf
CONTRIBUTING text eol=lf
COPYING text eol=lf
INSTALL text eol=lf
license text eol=lf
LICENSE text eol=lf
NEWS text eol=lf
README text eol=lf
TODO text eol=lf
## TEMPLATES
*.dot text eol=lf
*.tpl text eol=lf
*.twig text eol=lf
## LINTERS
.csslintrc text eol=lf
.eslintrc text eol=lf
.htmlhintrc text eol=lf
.jscsrc text eol=lf
.jshintrc text eol=lf
.jshintignore text eol=lf
.stylelintrc text eol=lf
.npmignore text eol=lf
## CONFIGS
*.bowerrc text eol=lf
*.cnf text eol=lf
*.conf text eol=lf
*.config text eol=lf
.babelrc text eol=lf
.browserslistrc text eol=lf
.editorconfig text eol=lf
.env text eol=lf
.gitattributes text eol=lf
.gitconfig text eol=lf
.htaccess text eol=lf
*.lock text eol=lf
*.npmignore text eol=lf
*.yaml text eol=lf
*.yml text eol=lf
browserslist text eol=lf
Makefile text eol=lf
makefile text eol=lf
## GRAPHICS
*.ai binary
*.bmp binary
*.eps binary
*.gif binary
*.ico binary
*.jng binary
*.jp2 binary
*.jpg binary
*.jpeg binary
*.jpx binary
*.jxr binary
*.pdf binary
*.png binary
*.psb binary
*.psd binary
*.svg text
*.svgz binary
*.tif binary
*.tiff binary
*.wbmp binary
*.webp binary
## AUDIO
*.kar binary
*.m4a binary
*.mid binary
*.midi binary
*.mp3 binary
*.ogg binary
*.ra binary
## VIDEO
*.3gpp binary
*.3gp binary
*.as binary
*.asf binary
*.asx binary
*.fla binary
*.flv binary
*.m4v binary
*.mng binary
*.mov binary
*.mp4 binary
*.mpeg binary
*.mpg binary
*.ogv binary
*.swc binary
*.swf binary
*.webm binary
## ARCHIVES
*.7z binary
*.gz binary
*.jar binary
*.rar binary
*.tar binary
*.zip binary
## FONTS
*.ttf binary
*.eot binary
*.otf binary
*.woff binary
*.woff2 binary
## EXECUTABLES
*.exe binary
*.pyc binary

37
webui/.gitignore vendored Normal file
View File

@ -0,0 +1,37 @@
__pycache__
*/__pycache__
.DS_Store
node_modules
# pyinstaller build dirs
/dist
/build
# local env files
/env/
/venv/
.env.local
.env.*.local
# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
# .vscode
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Private configs
/config.py
tailwind.config.full.js
# development
*.map
public/js/bundle.js

621
webui/LICENSE.txt Normal file
View File

@ -0,0 +1,621 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

32
webui/README.md Normal file
View File

@ -0,0 +1,32 @@
# deemix-webui
This is just the WebUI for deemix, it should be used with deemix-gui or something like that.
If you are a web developer and want to contribute to this project, please read the [COMPILE-UI](COMPILE-UI.md) file.
# "Hidden" features
- `CTRL+SHIFT+Backspace` deletes all the search bar content
- `CTRL+F` focuses the search bar
- `CTRL+B` toggles the download bar
- `ALT+Left` goes back to the previous page, if present (like would happen in the browser)
- `ALT+Right` goes forward to the next page, if present (like would happen in the browser)
- Custom context menu: on certain elements, like download buttons or album covers, when opening the context menu, a custom one with more options will appear instead of the default one
# Deps
- `rollup-plugin-vue@4.2.0` is needed because of https://github.com/vuejs/rollup-plugin-vue/issues/238
# License
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.

61
webui/package.json Normal file
View File

@ -0,0 +1,61 @@
{
"name": "deemix-webui",
"version": "1.9.3",
"scripts": {
"clean": "rimraf public/js/bundle.js public/js/bundle.temp.js public/js/bundle.js.map",
"clean-temp": "rimraf public/js/bundle.temp.js",
"build:js": "rollup -c",
"minify": "esbuild public/js/bundle.temp.js --outfile=public/js/bundle.js --minify",
"build": "npm-run-all --sequential clean build:js minify clean-temp",
"start:gui": "yarn --cwd ../ start",
"watch:server": "yarn --cwd ../server watch",
"watch:js": "rollup -c -w",
"dev": "npm-run-all --parallel watch:server watch:js",
"lint": "eslint src/**/*.{js,vue,mjs} --fix",
"lint-tests": "eslint src/**/*.js --fix",
"test": "jest",
"test-watch": "jest --watch",
"testlang": "node ./tests/testlang.js"
},
"dependencies": {
"@rollup/plugin-alias": "3.1.5",
"@rollup/plugin-commonjs": "20.0.0",
"@rollup/plugin-node-resolve": "13.0.4",
"@rollup/plugin-replace": "3.0.0",
"@vue/composition-api": "1.0.6",
"esbuild": "0.12.19",
"flag-icon-css": "3.5.0",
"lodash-es": "4.17.21",
"npm-run-all": "4.1.5",
"postcss": "8.3.6",
"rimraf": "3.0.2",
"rollup": "2.56.1",
"rollup-plugin-analyzer": "4.0.0",
"rollup-plugin-postcss": "4.0.0",
"rollup-plugin-svg": "2.0.0",
"rollup-plugin-vue": "4.2.0",
"svg-country-flags": "1.2.10",
"tailwindcss": "1.9.6",
"toastify-js": "1.11.1",
"vue": "2.6.14",
"vue-i18n": "8.25.0",
"vue-router": "3.5.2",
"vuex": "3.6.2"
},
"devDependencies": {
"@babel/core": "7.15.0",
"@babel/plugin-transform-modules-commonjs": "7.15.0",
"@nuxtjs/eslint-config": "6.0.1",
"@types/jest": "26.0.24",
"@typescript-eslint/eslint-plugin": "4.29.0",
"@typescript-eslint/parser": "4.29.0",
"babel-jest": "27.0.6",
"eslint": "7.32.0",
"eslint-config-prettier": "8.3.0",
"eslint-plugin-prettier": "3.4.0",
"jest": "27.0.6",
"prettier": "2.3.2",
"typescript": "4.3.5",
"vue-template-compiler": "2.6.14"
}
}

BIN
webui/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 238 KiB

Some files were not shown because too many files have changed in this diff Show More