814 Commits

Author SHA1 Message Date
dumbmoron
c68ebbe949 web/DownloadButton: use api-client 2024-09-14 19:14:47 +00:00
dumbmoron
1cd57fc7ff web/Omnibox: mark url input as ready once turnstile is loaded 2024-09-14 19:14:47 +00:00
dumbmoron
95f0fbdb5e api-client/turnstile: don't retry making session if it's not needed 2024-09-14 19:14:47 +00:00
dumbmoron
5d7cd861f3 web/api: remove stuff that was moved to api-client 2024-09-14 19:14:47 +00:00
dumbmoron
6d4477a962 web/api-url: replace getter with state 2024-09-14 19:14:47 +00:00
dumbmoron
64ac458941 api-client: make base URL reconfigurable 2024-09-14 19:14:47 +00:00
dumbmoron
d3e278660d api-client/session: pull URL from client 2024-09-14 19:14:47 +00:00
dumbmoron
d201deb60a api-client/package: configure tsup output and exports 2024-09-14 19:14:47 +00:00
dumbmoron
00d5754ea8 api-client: simplify interface, take turnstile object on init 2024-09-14 19:14:47 +00:00
dumbmoron
ff57a6a448 api-client/turnstile: expose information about client needing session 2024-09-14 19:14:47 +00:00
dumbmoron
1d30ac0139 api-client: implement individual api clients 2024-09-14 19:14:47 +00:00
dumbmoron
a80c7b7a5a api-client: rename CobaltAPIResponse type to CobaltResponse 2024-09-14 19:14:47 +00:00
dumbmoron
afe9917169 api-client: move base api and session to internal subfolder 2024-09-14 19:14:47 +00:00
dumbmoron
4755787b69 api-client: initial api request 2024-09-14 19:14:47 +00:00
dumbmoron
c8ccb32421 api-client: copy request schema from api 2024-09-14 19:14:47 +00:00
dumbmoron
6cc1227288 api-client: migrate session handler and response types 2024-09-14 19:14:47 +00:00
dumbmoron
ab8650030b api-client: set up error enums/types 2024-09-14 19:14:47 +00:00
dumbmoron
abb6a26ee0 i18n: move api errors to api-client package 2024-09-14 19:14:47 +00:00
dumbmoron
acb4e49e18 ci: increase timeout on api sanity check 2024-09-12 08:40:40 +00:00
wukko
b90a58f4f0 api/tests/twitch: fix expected twitch status 2024-09-12 14:38:36 +06:00
wukko
e768e7f6fa api/create-filename: don't assign any of potentially blank tags 2024-09-12 14:35:42 +06:00
wukko
80a01494c7 api/match-action: add missing twitch case to redirect group
closes #741
2024-09-12 14:30:21 +06:00
wukko
64173f7a03 api/create-filename: don't push youtubeFormat if it doesn't exist
oops
2024-09-11 22:18:51 +06:00
dumbmoron
4af48dd2f9 web: add UserActivation polyfill for browsers that don't have it 2024-09-11 11:15:25 +00:00
wukko
2122e87e66 web/NotchSticker: fix sticking out on XR and 11 2024-09-11 16:41:04 +06:00
wukko
d7454a073b web/download: assume userActivation expired if agent doesn't support it 2024-09-11 14:42:54 +06:00
dumbmoron
6e3589c8ce web/changelogs: fix broken bullet lists 2024-09-10 19:19:16 +00:00
dumbmoron
6653fdc8df changelogs/6.0: fix broken link 2024-09-10 19:18:00 +00:00
wukko
fd23080dd9 web/i18n/settings: fix typo in video quality description 2024-09-10 09:07:46 +06:00
wukko
394c1d8eaf web/remux: add remux tag to the end of filename
closes #720
2024-09-10 08:45:53 +06:00
dumbmoron
2fcda9c705 web/ChangelogEntry: fix off-by-one changelog date in some cases 2024-09-09 20:35:12 +00:00
dumbmoron
2dc9d64092 docs/examples: update composefile example 2024-09-09 16:50:50 +00:00
dumbmoron
08cc36c873 ci: update action to use api package 2024-09-09 16:45:04 +00:00
dumbmoron
aa25421422 web/changelogs: update references from current to main 2024-09-09 16:38:47 +00:00
dumbmoron
f71f8b086d github: update links from current to main 2024-09-09 16:31:37 +00:00
wukko
08bc5022a1 cobalt 10: svelte web app, improved backend (#719) 2024-09-09 22:26:14 +06:00
wukko
0a5405a3b4 api/tests/twitter: update age restricted video test 2024-09-09 22:21:27 +06:00
wukko
2a1ebd8e69 repo/readme: update formatting & clean up 2024-09-09 22:12:33 +06:00
dumbmoron
e5c0bfa6f8 README: clarify root license 2024-09-09 16:00:23 +00:00
dumbmoron
a93e9f593f web: scope package name 2024-09-09 15:59:40 +00:00
dumbmoron
35456fe6d7 README: add bluesky to supported services 2024-09-09 15:52:12 +00:00
dumbmoron
a86a96d8ce docs/api: also link to old docs for now 2024-09-09 15:50:51 +00:00
dumbmoron
d6929b0758 web/README: clarify wording in license permission explanation 2024-09-09 15:46:55 +00:00
dumbmoron
99d4f9e8c9 api/README: remove leftover links 2024-09-09 15:45:06 +00:00
dumbmoron
7b06a5047f repo: split README into subproject READMEs 2024-09-09 15:44:37 +00:00
dumbmoron
8df4bc00cb web/svelte: change public prefix to WEB_ 2024-09-09 15:24:23 +00:00
wukko
ce7633c81a api: move agpl license into subdir 2024-09-09 21:21:13 +06:00
wukko
93ca553fb2 web/about/community: add community links 2024-09-09 21:19:43 +06:00
dumbmoron
1b639edac8 web/layout: specify full path in og:url 2024-09-09 15:04:25 +00:00
dumbmoron
15a90e9b11 api/stream: use Map for storing info about internal streams 2024-09-09 14:29:06 +00:00
dumbmoron
57c9836f56 api/core: move ratelimiters before authentication handler 2024-09-09 14:21:19 +00:00
wukko
3317726afe api/core: rename req and next args to indicate that they're unused 2024-09-09 19:44:40 +06:00
wukko
0aae3fe7f0 api/core: rename err argument to indicate that it's unused 2024-09-09 19:41:44 +06:00
wukko
de5162e417 api/jwt: remove redundant exports 2024-09-09 19:39:07 +06:00
wukko
ebd1104df3 web/libav: remove redundant async 2024-09-09 19:36:16 +06:00
wukko
bd93da94dc web/download: remove redundant async 2024-09-09 19:36:08 +06:00
wukko
2dbcdb18f9 api/bluesky: remove redundant await & async 2024-09-09 19:32:17 +06:00
dumbmoron
5210d62490 merge: merge changes from 7.x into 10 2024-09-09 13:16:46 +00:00
dumbmoron
6e523f300a web/donate: update sendCustom handler to use links 2024-09-09 13:00:06 +00:00
dumbmoron
3156831847 web/donate: use links instead of onclick handler 2024-09-09 12:57:58 +00:00
dumbmoron
fba64df118 api/snapchat: fix regex matching to thumbnail 2024-09-09 12:53:46 +00:00
wukko
0b02c22d9c web/changelogs/10: rephrase the list starter 2024-09-09 18:50:24 +06:00
wukko
498e6f4419 api/snapchat: fix spotlight url extraction 2024-09-09 18:40:59 +06:00
wukko
e2c8723c0e web/changelogs/10: add changelog banner 2024-09-09 18:27:50 +06:00
wukko
263e6a9321 web/changelogs/10: fix some deeplinks and phrasing 2024-09-09 17:08:52 +06:00
wukko
049edd49f1 web/layout: fix strong element weight 2024-09-09 17:05:37 +06:00
dumbmoron
4777d69cd7 web/OuterLink: don't set target/rel for relative links 2024-09-09 11:02:38 +00:00
wukko
6d95700075 web/changelogs: add proper 10.0 changelog 2024-09-09 16:59:16 +06:00
wukko
0569bb87a1 web/about: remove faq section 2024-09-09 15:42:25 +06:00
wukko
a84664c9d5 web/about/general: remove corny text 2024-09-09 14:32:23 +06:00
wukko
11b756945f web/about: thanks & licenses page 2024-09-09 14:24:11 +06:00
wukko
35254502fe web/about/general: add human section 2024-09-09 13:52:40 +06:00
wukko
2049e65221 web/about/general: update the community section 2024-09-09 13:39:30 +06:00
wukko
272b7a64b8 web/i18n/remux: make description clearer 2024-09-09 13:14:26 +06:00
wukko
fbe8ccfc2a web/download: show an explanation when user activation expires 2024-09-09 12:53:22 +06:00
wukko
dcbda243a2 web/i18n: update basic russian translation 2024-09-09 12:36:47 +06:00
wukko
d171e3c158 web: clean up blank pages & stray i18n strings 2024-09-09 12:24:32 +06:00
wukko
b96d2ea352 web: add og:title to head on all pages with custom title 2024-09-09 12:19:25 +06:00
wukko
0b5b8454a9 web/remux: return render instead of the original file
LMFAOOOOOOO
2024-09-09 12:05:13 +06:00
wukko
91d09a4e89 web/layout: remove og:title from head 2024-09-09 03:30:11 +06:00
wukko
8a18645e0b web/remux: warn user & terminate libav before switching tabs
warning about aborting processing will be shown before navigating away from remuxing tab
2024-09-09 03:08:18 +06:00
wukko
dd1c630c71 web/remux: download files properly 2024-09-09 02:30:20 +06:00
wukko
853bc26587 web/download: support downloading and sharing raw files 2024-09-09 02:30:03 +06:00
wukko
b1f41cae41 web/remux: tweak progress appearance 2024-09-09 01:17:34 +06:00
dumbmoron
2bcc849790 web/remux: fix file saving on ios 2024-09-08 18:59:51 +00:00
dumbmoron
2c75c52eb3 web/remux: narrow file type 2024-09-08 18:58:36 +00:00
wukko
fff4393c46 web/layout: revert position change for #cobalt 2024-09-09 00:26:20 +06:00
wukko
0f51b22d99 web/SettingsCategory: rename state from animate to focus 2024-09-09 00:10:53 +06:00
wukko
913beda417 web/DialogHolder: fix top padding 2024-09-09 00:10:35 +06:00
wukko
53eb052fe6 web/SavingDialog: add ios saving tutorial 2024-09-09 00:10:21 +06:00
dumbmoron
a613f1402d web/FileReceiver: define input in component to prevent losing it to GC 2024-09-08 16:55:58 +00:00
dumbmoron
a351264ede web/api: send parameters to server only if they differ from defaults 2024-09-08 16:30:02 +00:00
dumbmoron
1f86faad12 web/api: don't request/send session token to custom instances 2024-09-08 16:30:02 +00:00
dumbmoron
b4599e68bb web/safety-warning: early returns 2024-09-08 16:30:02 +00:00
wukko
002e70cb89 api/schema: make tiktokFullAudio false by default 2024-09-08 22:03:29 +06:00
wukko
cda99a96e8 web/DonateAltItem: add proper aria label 2024-09-08 20:47:33 +06:00
wukko
fb1b5ffee2 web/donate: fix horizontal scroll on mobile 2024-09-08 20:22:07 +06:00
wukko
1821b4b614 web/settings/defaults: set tiktokFullAudio to false 2024-09-08 20:19:12 +06:00
wukko
fcde8ad745 web/settings/migrate: don't migrate twitterGif 2024-09-08 20:18:50 +06:00
dumbmoron
894174bed9 web/layout: fix main content jumping when navigating in some cases 2024-09-08 11:42:04 +00:00
dumbmoron
d0bd70e213 web/SidebarTab: fix content jumping when navigating between distant tabs 2024-09-07 20:26:29 +00:00
dumbmoron
f9e80e6d6f web: add link header to improve imessage previews 2024-09-07 18:08:20 +00:00
wukko
30bcad0ba4 web/layout: add og:url & application name to head 2024-09-07 23:15:20 +06:00
dumbmoron
08c34762e9 test: run service tests only when api/packages change 2024-09-07 17:07:48 +00:00
wukko
7f94c73e6a web/html: change og:type to article 2024-09-07 23:06:45 +06:00
wukko
25a33a4ea2 web/layout: split description metadata tags 2024-09-07 23:02:13 +06:00
wukko
08113d7ae5 web/html: add embed type 2024-09-07 22:58:33 +06:00
wukko
e839aa4c41 web/types/settings: add 8kbps bitrate option back 2024-09-07 22:33:43 +06:00
wukko
a698c55663 web/layout: add og:description 2024-09-07 22:32:40 +06:00
dumbmoron
9a504443fd api/stream: add support for 8kbps option for mp3 downloads 2024-09-07 16:28:34 +00:00
wukko
c6385f1842 web/layout: add description and title metadata 2024-09-07 22:14:55 +06:00
dumbmoron
b4f17487b4 web: remove built-in sveltekit announcer (for real this time) 2024-09-07 16:01:26 +00:00
wukko
3fdfd44515 web/UpdateNotification: set an alert aria role 2024-09-07 21:16:26 +06:00
wukko
f406e7355b web/layout: get rid of svelte announcer
it reads over our own a11y labels, and there's no official way to disable it
2024-09-07 20:58:30 +06:00
dumbmoron
70ba8f8b39 web: replace apple-mobile-web-app-capable with mobile-web-app-capable 2024-09-07 14:48:47 +00:00
dumbmoron
6a67ed29ca web/remux: split memory allocations into chunks
browsers don't like to allocate huge chunks of contiguous memory, but
we do not actually need a huge chunk of contiguous memory, and this
lets us process much larger files than before
2024-09-07 14:35:36 +00:00
dumbmoron
0a37c84e93 web/libav: always clean up files on function exit 2024-09-07 14:35:36 +00:00
wukko
0ce743d13f web/about: replace the godawful margin workaround 2024-09-07 20:29:13 +06:00
wukko
f03f849b99 web/changelogs: add a placeholder changelog for 10.0 update 2024-09-07 20:10:42 +06:00
wukko
7a45866c7c web/about: write the general about page 2024-09-07 18:31:02 +06:00
dumbmoron
5af4114c61 api/test: add facebook to finnicky services 2024-09-07 12:29:01 +00:00
dumbmoron
08490c54e4 api: include generated filename in api response 2024-09-07 12:26:43 +00:00
dumbmoron
438fce3c58 api/processing: append audio extension to filename before response 2024-09-07 12:26:43 +00:00
wukko
c52aa76426 web/about: merge community and help tabs 2024-09-07 18:22:17 +06:00
wukko
7cd572954f web/remux: improve accessibility 2024-09-07 18:21:40 +06:00
dumbmoron
3232c4a51b web/libav: simplify reading probe data 2024-09-07 11:41:56 +00:00
wukko
3189857c77 web/layout: reduce margin even more for long text h3 heading 2024-09-06 16:59:37 +06:00
wukko
b710906404 web/i18n/donate: better language for body text 2024-09-06 16:59:19 +06:00
wukko
5a5c9da3df web/settings/advanced: improve settings management buttons
also removed duplicate localization strings
2024-09-06 16:18:30 +06:00
wukko
494522d292 web/subnav/PageNavSection: fix vertical overflow 2024-09-06 16:06:55 +06:00
wukko
1758e2db19 web/settings/audio: swap tiktok and youtube sections 2024-09-06 15:58:01 +06:00
wukko
16d59a239c web/types/settings: remove 8kbps option 2024-09-06 15:57:37 +06:00
wukko
348a28dd12 web/about/terms: rename and rewrite the last section 2024-09-06 15:45:59 +06:00
wukko
96c6897ae0 web/i18n/settings: improve descriptions
less yapping and more clarity
2024-09-06 15:45:18 +06:00
wukko
4db0665ab6 web/SupportedServices: aria label for the expand button 2024-09-06 15:27:02 +06:00
wukko
aa0991eee4 web/about/privacy: don't show plausible info if it's disabled 2024-09-05 23:34:30 +06:00
wukko
59b6cbd8d4 web/about: add info about terms being valid only on official instance 2024-09-05 23:33:33 +06:00
wukko
065b4394c9 web/i18n/donate: update motivation text a little 2024-09-05 16:06:41 +06:00
wukko
ec3e411032 web/about/privacy: specify cloudflare services 2024-09-05 13:27:57 +06:00
wukko
b1b8f6967b web/about/terms: initial terms and ethics page 2024-09-05 10:22:02 +06:00
wukko
152a423bf3 web/about/privacy: add info about on-device processing 2024-09-05 10:21:47 +06:00
wukko
cb7d1baee0 web/layout: update global heading text style in long text 2024-09-05 10:21:30 +06:00
wukko
4921e5c151 web/about/privacy: initial privacy policy page 2024-09-05 09:58:45 +06:00
wukko
0408fc446a web/layout: don't apply noto mono for titles 2024-09-05 09:58:25 +06:00
wukko
4da1defcf8 web/Omnibox: add missing clipboard input type 2024-09-05 09:06:03 +06:00
wukko
80e32fc0c0 web/remux: check if env is browser before adding listeners 2024-09-05 08:56:01 +06:00
wukko
21832005e2 web/remux: handle more errors, add a basic progress bar 2024-09-05 08:51:41 +06:00
wukko
7a5e60f39a web/SettingsCategory: use general beta label 2024-09-05 08:00:18 +06:00
wukko
b03c71eb14 web/SidebarTab: add aria label for beta tabs & fix its position 2024-09-05 07:59:49 +06:00
wukko
9e8c953ca6 web/Sidebar: mark remux tab as beta 2024-09-05 07:55:30 +06:00
wukko
97866fb306 api/core: update the emoticon in startup message 2024-09-05 07:53:55 +06:00
wukko
10d867efc0 web/i18n/error: add api at capacity error 2024-09-05 00:55:02 +06:00
wukko
fff1c6c7a6 web & api: rename stream to tunnel
- updated the endpoint to /tunnel
- updated status to tunnel
- fixed one incorrectly named error in web
2024-09-05 00:26:48 +06:00
wukko
49460bd16d web: load turnstile only in save tab and only once
turnstile will stay in background after being loaded once (just like before), but now it will not load on pages other than save if they are opened first
2024-09-05 00:04:41 +06:00
dumbmoron
f0f5d7be7e web/DonateOptionsCard: parametrize card processor string 2024-09-04 17:01:51 +00:00
dumbmoron
218916cee3 web/CopyIcon: change copy-animation id to class 2024-09-04 16:45:52 +00:00
wukko
8b067e363b web/DonateBanner: remove useless classes from the hearts bg svg 2024-09-04 22:40:42 +06:00
wukko
b9bb760793 web/DonateBanner: replace 150 svgs with background-repeat 2024-09-04 22:36:34 +06:00
dumbmoron
79237185bd docs/api: update url misspecification 2024-09-04 16:30:02 +00:00
dumbmoron
9800a9b54f docs/api: update to reflect new request/response schema 2024-09-04 16:28:59 +00:00
wukko
41c23337ff web/error: redirect to default about page on 404 error 2024-09-04 21:23:47 +06:00
wukko
201f9aaefe web/Sidebar: dynamic about page link 2024-09-04 21:23:07 +06:00
wukko
520725462a web: fix auto navigation on scale change for about & settings pages 2024-09-04 21:20:56 +06:00
wukko
140683a679 web/save: make the terms note open the terms page 2024-09-04 21:00:41 +06:00
wukko
d98353d5af web/about: about page routing & navigation 2024-09-04 20:59:05 +06:00
wukko
6a0c05cf7a web/PageNav: add a prop for making content wider 2024-09-04 20:58:51 +06:00
wukko
7e8ae2ca61 web/PageNav: add a prop for enabling content padding 2024-09-04 20:51:13 +06:00
wukko
56008676f5 web/settings: move sub navigation into its own component 2024-09-04 17:50:47 +06:00
wukko
a18fd72ea0 web/remux: reduce gap in first state 2024-09-04 16:47:00 +06:00
wukko
3c5a5eaf25 web/save: make terms note thicker 2024-09-04 16:33:45 +06:00
wukko
032f592d95 web/remux: reduce desc font size on mobile 2024-09-04 16:32:20 +06:00
dumbmoron
b7e5a94226 web/svelte: enable fallback page generation 2024-09-03 13:39:21 +00:00
dumbmoron
1262bc20fe web/version: don't try to fetch when server-side rendering 2024-09-03 13:33:16 +00:00
dumbmoron
f009da7de4 web: wrap error handler in onMount 2024-09-03 13:30:32 +00:00
dumbmoron
93f8c038d2 web/Turnstile: remove unused import 2024-09-03 13:24:15 +00:00
dumbmoron
b5d570c43f web/Turnstile: check if already defined before making listener 2024-09-03 13:21:41 +00:00
dumbmoron
fc26032048 web: fix destructuring error if theme is undefined 2024-09-03 13:04:12 +00:00
dumbmoron
38ce64b310 web: fix type errors 2024-09-03 10:20:29 +00:00
wukko
cef90219e0 web: partially pre-render web for page metadata 2024-09-03 14:39:52 +06:00
dumbmoron
5b42757896 web: remove background override from global css 2024-09-03 07:58:52 +00:00
wukko
30c4c1ad20 web/device: add default values & types 2024-09-03 13:52:41 +06:00
wukko
645542c910 api/bluesky: catch video errors & prevent loading videos not from bsky 2024-09-03 13:24:08 +06:00
dumbmoron
4b4fce326f test: update match() arguments to new format 2024-09-02 14:18:11 +00:00
dumbmoron
2deb8aa53b web: add fade-in animation 2024-09-02 14:16:21 +00:00
wukko
8cee4e58c5 api/match: accept object as single argument
hi im what i do
2024-09-02 08:27:31 +06:00
wukko
93f2a6b226 api/bluesky: add support for saving images
one or multiple, everything works
2024-09-01 16:37:24 +06:00
wukko
d9925f2233 api/core: move friendly name map to server info 2024-09-01 16:02:06 +06:00
wukko
805e5d42c0 api/config: apply friendly name in a map
filter doesn't allow changing the value
2024-09-01 15:56:51 +06:00
wukko
c71ed59660 api/url: return friendly name in unsupported link error 2024-09-01 15:51:35 +06:00
wukko
97fb6e60a2 api/service-alias: refactor 2024-09-01 15:35:49 +06:00
wukko
740a75851e api: add support for service name aliases
currently only used for bluesky
2024-09-01 15:28:29 +06:00
wukko
57050fb742 api/match-action: fix mute tag assignment for default filename
it's also no longer applied to photos and gifs LMFAOOO
2024-09-01 14:59:35 +06:00
wukko
67073b274d api/tests: add bluesky tests 2024-09-01 14:41:41 +06:00
wukko
b727a56d67 api/bluesky: catch fetch errors (oops) 2024-09-01 14:39:28 +06:00
wukko
6c9601690b api: add support for bluesky videos & clean up service patterns 2024-09-01 14:34:44 +06:00
wukko
4478a963c5 api/config: add cobalt user agent 2024-09-01 14:15:16 +06:00
wukko
f3521da9c1 api/stream/remux: convert audio to aac to increase compatibility
only applies to hls exceptions
2024-09-01 14:09:58 +06:00
wukko
ccdcd4cb09 api/url: add missing break to dailymotion case 2024-09-01 12:00:48 +06:00
dumbmoron
7227a4ad6e web/layout: enable ssr 2024-08-31 17:46:52 +00:00
dumbmoron
f038e6a379 web: remove default title 2024-08-31 17:46:47 +00:00
dumbmoron
51c140fbfa web: make everything ssr-compatible 2024-08-31 17:46:10 +00:00
wukko
8e9e8ab63f web/privacy: mark tunnelling feature as beta 2024-08-31 15:32:30 +06:00
wukko
ac76f8e32b web/instances: mark community instances feature as beta 2024-08-31 15:32:16 +06:00
wukko
a46972c9a5 web/SettingsCategory: add ability to mark features as beta 2024-08-31 15:32:02 +06:00
wukko
fa941e9d82 web/i18n/settings: update privacy setting descriptions
made them easier to read
2024-08-31 15:20:02 +06:00
wukko
f464d87585 api/tiktok: add support for proxying images in a picker 2024-08-31 15:01:09 +06:00
wukko
0852f5dc09 api/snapchat: always proxy picker thumbs & support proxying everything 2024-08-31 14:52:12 +06:00
wukko
892b875e3f api/reddit: add a filename to returned gifs 2024-08-31 14:27:46 +06:00
wukko
10717c69f6 api/twitter: support proxying videos & images in a picker 2024-08-31 14:23:18 +06:00
wukko
00da2a9339 api/twitter: return a filename for images 2024-08-31 14:19:01 +06:00
wukko
d026eb75a5 api/instagram: add support for proxying everything in a picker 2024-08-31 14:10:03 +06:00
wukko
4476ae0672 api/pinterest: add missing filenames to images & gifs 2024-08-31 14:09:34 +06:00
wukko
d0d0f16c5f web/privacy: add support for always proxying files 2024-08-31 14:08:48 +06:00
wukko
a9e65b0da0 api: add an option to always proxy files 2024-08-31 14:07:37 +06:00
dumbmoron
2f63f6bab7 api/proxy: add support for proxying range requests 2024-08-31 07:15:20 +00:00
dumbmoron
305d0429f1 web/donate: make page scrollable on sides 2024-08-30 16:48:23 +00:00
wukko
744842cc3d web/CustomInstanceInput: fix colors & overflow in firefox and safari 2024-08-30 22:01:14 +06:00
dumbmoron
3d631b6c30 DonationOption: appropriately format amounts 2024-08-30 15:40:06 +00:00
wukko
d8bacbeeef api/tests/twitter: allow retweeted video tests to fail 2024-08-30 21:35:29 +06:00
dumbmoron
57a7090eb2 web/DonateOptionsCard: add more preset options 2024-08-30 15:33:18 +00:00
wukko
1debf3e639 web/settings/download: fix padding for filename preview 2024-08-30 21:31:21 +06:00
wukko
063f5d1806 web/CustomInstanceInput: proper style 2024-08-30 21:31:02 +06:00
wukko
ebb5deb43c web/safety-warning: remove misplaced comparison 2024-08-30 17:25:31 +06:00
wukko
b878d5f4f9 web/settings/appearance: slight import refactor 2024-08-30 17:18:04 +06:00
wukko
1850264da7 web/LanguageDropdown: refactor 2024-08-30 17:17:43 +06:00
wukko
b3954b9209 web/ResetSettingsButton: move to settings subdir & reduce timeout to 2s 2024-08-30 17:17:29 +06:00
wukko
3cdd615734 web/i18n/settings: more general debug description 2024-08-30 17:16:19 +06:00
wukko
cf42b1b2ef web/i18n/error: shorter timed out message 2024-08-30 17:16:04 +06:00
wukko
33d6b5bd81 web: base custom instance functionality
also:
- renamed processing tab in settings to "instances"
- improved override description
- prefer custom over override (and grey out the option)
- dedicated lib for all api safety warnings
- left aligned small popup with smaller icon
- ability to grey out settings category & toggle
2024-08-30 17:15:05 +06:00
wukko
70c1a85766 web/DonateOptionsCard: fix input click area 2024-08-30 15:11:28 +06:00
wukko
524235907d web/DonateOptionsCard: remove stepper in firefox 2024-08-30 15:03:04 +06:00
dumbmoron
5cbc91cba9 tests: mark "twitter voice" test as canFail 2024-08-30 08:40:04 +00:00
dumbmoron
97266a46fa ci: shuffle ciphers before running service tests 2024-08-30 08:30:34 +00:00
wukko
7f8204bc0c api/core: handle all express errors, not just path parsing (wtf) 2024-08-30 14:25:46 +06:00
wukko
329b068038 api/schema: don't decode the url
this is from the dinosaur era of cobalt and hasn't been used since we moved to POST requests
2024-08-30 14:09:18 +06:00
wukko
1fe419784d web/DonateOptionsCard: recolor the focus border of input container
also removed additional 0.5px that got partially cropped
2024-08-29 20:58:49 +06:00
wukko
f0ce0ccef7 web/server-info: refresh server info cache if endpoint changes 2024-08-29 18:10:46 +06:00
wukko
f7da62e817 web/Omnibox: increase max length to 512 characters 2024-08-29 13:22:52 +06:00
wukko
5dc0cf1772 web/processing: hide override section when DEFAULT_API isn't present 2024-08-29 13:20:17 +06:00
wukko
e59b7fd375 web/FileReceiver: reduce padding 2024-08-28 15:06:00 +06:00
wukko
3295afdaae api/create-filename: don't add dub name when it doesn't exist 2024-08-28 00:35:53 +06:00
wukko
2068bba4ee web/SupportedServices: make the button more minimal 2024-08-27 19:40:30 +06:00
wukko
74a2758413 web/i18n/save: update disclaimer & translate new strings to russian 2024-08-26 23:52:13 +06:00
wukko
42410f7b20 web/save: add supported services popover 2024-08-26 23:43:39 +06:00
wukko
7524d202f7 web/session: merge cached state into main lib 2024-08-26 23:38:24 +06:00
wukko
59308ed09f web/about: add the link type of alternative donation method 2024-08-25 17:10:17 +06:00
wukko
1c258ab0ae web/env: add more donation methods 2024-08-25 17:09:31 +06:00
wukko
83f1744508 web/about: move bottom margin to section 2024-08-25 16:53:51 +06:00
wukko
685f8cb65e web/sidebar: fix auto scroll & clean up 2024-08-25 16:43:24 +06:00
wukko
a8330b25fa web/donate: reduce bottom margin 2024-08-25 16:41:10 +06:00
wukko
481697ea12 web/donate: add crypto donation options 2024-08-25 16:38:13 +06:00
wukko
1147244e46 web/env: updated the list of crypto addresses 2024-08-25 16:34:27 +06:00
wukko
b8fc3aeb4c web/CopyIcon: added regular copy icon 2024-08-25 16:34:08 +06:00
wukko
a589bf7e54 api/youtube: fix audio dub track detection 2024-08-25 14:48:46 +06:00
wukko
6dcd951e21 api/create-filename: refactor 2024-08-25 14:48:28 +06:00
wukko
6aa39dd1d1 web/i18n/error: add token expiration youtube error & update login error 2024-08-24 18:34:38 +06:00
wukko
0bbf822d70 api/youtube: catch token expiration error 2024-08-24 18:34:02 +06:00
wukko
856004366e api/match: fix typo in fetch.critical code 2024-08-24 17:28:43 +06:00
wukko
7478a373fc api & web: add service context to api.fetch.critical error 2024-08-24 17:24:51 +06:00
wukko
0b7af10ab0 web/i18n/error: update api.link.invalid 2024-08-24 17:21:44 +06:00
wukko
e80a110264 web/i18n: add all strings for api errors 2024-08-24 17:13:35 +06:00
wukko
7ac0726f37 api: move error context to matcher 2024-08-24 16:56:07 +06:00
wukko
37efa035a2 api/twitter: update no tweet error code 2024-08-24 16:31:19 +06:00
wukko
0d58fad580 web/session: update session fetch error code 2024-08-24 16:16:12 +06:00
wukko
c0284fac13 web/translations: handle error contexts 2024-08-24 16:15:48 +06:00
wukko
7041d61d80 api/core: fix link parsing error handling 2024-08-24 16:13:42 +06:00
wukko
cc05833c6a web/SettingsNavBar: fix text line height 2024-08-23 23:17:39 +06:00
wukko
09a6b5179e web/SidebarTab: fix selection animation in webkit 2024-08-23 21:07:18 +06:00
wukko
2479900bb9 web/donate: adjust donate card gradient colors for dark theme 2024-08-23 20:50:38 +06:00
wukko
1f25b3d793 web/DonateShareCard: remove gradient on mobile 2024-08-23 20:50:17 +06:00
wukko
7daceea049 web/DonateCardContainer: reduce padding on mobile (again) 2024-08-23 20:25:03 +06:00
wukko
8200541b21 web/DonateBanner: reduce padding on mobile 2024-08-23 20:24:47 +06:00
wukko
ba3602aabb web/DonateBanner: slightly reduce amount of hearts 2024-08-23 20:13:04 +06:00
wukko
0d8065ac70 web/DonateBanner: reduce padding 2024-08-23 20:05:21 +06:00
wukko
8df70cc00b web: update page title style
prioritize the page title, not "cobalt"
2024-08-23 20:02:17 +06:00
wukko
1e5bc67e92 web/DonateCardContainer: reduce padding 2024-08-23 19:55:10 +06:00
wukko
24f2329e9d web/settings: slightly update navigation style on mobile 2024-08-23 19:44:10 +06:00
wukko
70264f3691 api/core: update server info
- cache server info as string
- serve a list of services & duration limit in server info
2024-08-23 00:33:52 +06:00
wukko
7a557a97c3 api: move service disabling to DISABLED_SERVICES env 2024-08-23 00:16:26 +06:00
wukko
ee375a27cd api/schema: enable tiktok full audio by default 2024-08-22 23:17:49 +06:00
wukko
b6d2175d4b web/settings/defaults: enable full tiktok audio by default 2024-08-22 23:15:05 +06:00
dumbmoron
d7d707e666 web/DialogHolder: fix dialog animation jumping on new safari versions
WebKit/WebKit@ce08f32453 breaks this animation on newer versions
of safari. why? i guess we'll never know
2024-08-22 17:09:58 +00:00
wukko
a21c9e7632 api/core/api: clean up imports 2024-08-22 23:04:11 +06:00
wukko
c7a08844e3 web/i18n/settings: update audio format & bitrate descriptions 2024-08-22 22:57:51 +06:00
wukko
102dec4a84 api/match-action: clean up audio action 2024-08-22 22:45:26 +06:00
wukko
b3d846a1e3 web/i18n/settings: update audio bitrate description 2024-08-22 20:50:45 +06:00
wukko
ff9efdc471 api & web: update default audio bitrate to be 128kbps 2024-08-22 20:50:21 +06:00
wukko
42ff874c95 api/schema: add 8bkps audio bitrate option 2024-08-22 20:06:54 +06:00
wukko
49184a235d web/save: add support for audio bitrate functionality 2024-08-22 19:38:39 +06:00
wukko
91fd26e880 api: add audio bitrate functionality 2024-08-22 19:35:17 +06:00
wukko
fb5d68a830 api/instagram: add file name for proxied image thumbs 2024-08-22 18:02:53 +06:00
wukko
76fa1b2b87 api/twitter: add proper file name for proxied thumb 2024-08-22 17:40:44 +06:00
wukko
facf7741ce api/stream: standardize stream types & clean up related functions 2024-08-22 17:37:31 +06:00
wukko
1064be6a7a api/twitter: proxy thumbnails 2024-08-22 13:38:16 +06:00
wukko
07dc176024 api/stream/types: fix cross origin resource policy for proxy 2024-08-22 13:38:04 +06:00
wukko
ed4a5889ab web/DownloadButton: fix download audio i18n 2024-08-22 13:05:17 +06:00
wukko
3057f9cffb web/DownloadButton: replace rem sizes with pixels 2024-08-20 22:34:47 +06:00
wukko
281ae25d4a api/youtube: prefer higher quality even if premuxed video is available 2024-08-20 22:27:03 +06:00
wukko
555625878e api/schema: update twitterGif & videoQuality defaults 2024-08-20 22:04:17 +06:00
wukko
cd9be54023 web/settings: update twitterGif & videoQuality defaults 2024-08-20 22:02:06 +06:00
wukko
98be6f017c web/i18n/settings: update twitter gif description 2024-08-20 22:01:33 +06:00
wukko
265ab77948 web/i18n: update string name formatting 2024-08-20 21:17:33 +06:00
wukko
05abf9ad3e api: update error codes in services, add more error codes where needed 2024-08-20 21:10:37 +06:00
wukko
c698d272a1 api/jwt: return relative expiration date to accommodate offset clocks 2024-08-19 22:25:21 +06:00
wukko
1f3509db07 api: update error codes in api core functions 2024-08-19 21:51:45 +06:00
dumbmoron
a4d57f175e web/libav: try to guess type from filename if browser fails 2024-08-17 14:07:10 +00:00
wukko
911f283b78 web/html: prevent chrome & darkreader from messing up the dark theme 2024-08-17 19:52:39 +06:00
dumbmoron
e678bd25fc web/lib/libav: clean up extension handling 2024-08-17 13:45:58 +00:00
dumbmoron
9d7512d6e5 web/remux: lower percentage bound 2024-08-17 13:45:18 +00:00
dumbmoron
7d10ab765e web/remux: override mp3 extension from mime type 2024-08-17 13:26:43 +00:00
dumbmoron
d446dfd87e web/remux: correctly unset processing state 2024-08-17 13:26:43 +00:00
wukko
0e461d4ebe web/session: add a delta to prevent token expiring on its way to api 2024-08-17 18:05:00 +06:00
wukko
9592e59f76 api/jwt: fix timestamp to match the spec 2024-08-17 17:58:40 +06:00
dumbmoron
580ca042f3 web/remux: display error if probe fails 2024-08-17 10:15:05 +00:00
dumbmoron
3bef12ff33 web/remux: copy all streams when remuxing 2024-08-17 10:07:55 +00:00
wukko
974b98f0ac api/core: fix & clean up auth middleware 2024-08-17 00:59:59 +06:00
wukko
30c51b9fe8 api/core: rate limit by token if it's present 2024-08-17 00:55:26 +06:00
wukko
c54294601b api/core: limit authorization header length 2024-08-17 00:13:26 +06:00
wukko
a49a87544c web/session: don't expect a trailing slash in DEFAULT_URL 2024-08-16 23:52:40 +06:00
wukko
3336210e93 web/state/session: clean up 2024-08-16 23:48:50 +06:00
wukko
51bd2f72fd api/core: fix typo 2024-08-16 23:41:20 +06:00
wukko
4857030933 web/api: jwt session token, clean up, move related modules to own dir 2024-08-16 23:36:56 +06:00
wukko
16acf62886 api/security: jwt session token 2024-08-16 23:28:03 +06:00
wukko
33c2fee847 web/remux: add page title 2024-08-16 22:52:33 +06:00
wukko
ac9568a422 web/remux: fix ghost click areas when processing 2024-08-16 02:13:26 +06:00
wukko
275c982c80 web/Sidebar: hide unfinished tabs 2024-08-16 01:55:25 +06:00
wukko
b9fabdc327 web/Omnibox: clean up input link icon code 2024-08-16 01:44:13 +06:00
wukko
478dd6e515 web/Omnibox: show a spinner when loading
replaces the link icon with a spinner when loading the turnstile checks or processing the link
2024-08-16 01:37:05 +06:00
wukko
8b9e3f58f4 web/i18n/error: add api authentication error 2024-08-16 00:24:21 +06:00
wukko
4283774c6c api: add support for cloudflare turnstile 2024-08-16 00:10:17 +06:00
wukko
384c6deced web: add support for cloudflare turnstile 2024-08-16 00:08:57 +06:00
wukko
c1813aa33f api/stream: rename bridge mode to proxy 2024-08-15 19:58:40 +06:00
wukko
9d577f23b1 web/FileReceiver: fix focus ring 2024-08-15 12:58:26 +06:00
wukko
5ce4ef8366 web/FileReceiver: reduce padding, fix scaling 2024-08-14 13:07:34 +06:00
wukko
70a8c53cba web/Sidebar: add blank convert & shrink tabs 2024-08-14 01:43:04 +06:00
dumbmoron
8af6761951 web/remux: transition into processing state before probe 2024-08-13 15:55:47 +00:00
dumbmoron
1493762ce9 web/remux: add speed to progress info 2024-08-13 15:55:30 +00:00
dumbmoron
4c2acc595e web/remux: add basic progress example 2024-08-13 15:34:53 +00:00
dumbmoron
f93d84c457 web/libav: add ffprobe wrapper 2024-08-13 15:34:53 +00:00
dumbmoron
4636f7b0d4 web/libav/wrapper: make sure libav is initialized only once 2024-08-13 15:34:53 +00:00
dumbmoron
72545ffb5d web/remux: init libav on page load, basic progress event handling 2024-08-13 15:34:53 +00:00
dumbmoron
28600e7e4c web/libav: emit progress events 2024-08-13 15:34:53 +00:00
wukko
f661e839b1 web/i18n/remux: less yapping in description 2024-08-13 16:56:46 +06:00
wukko
c8904fd939 web/FileReceiver: reduce icon size, change icon when dragged over 2024-08-13 16:48:53 +06:00
wukko
b9958a8102 web/FileReceiver: fix meowbalt z index 2024-08-13 16:16:50 +06:00
wukko
0d41fe6fa3 web/FileReceiver: animated svg dashed stroke, padding improvements 2024-08-13 16:15:00 +06:00
wukko
70b300bd71 web/remux: add processing state, clean file, prevent render loop 2024-08-13 15:22:24 +06:00
wukko
1fd2b72075 web/remux: rename DropReceiver component 2024-08-13 14:17:58 +06:00
wukko
af428bc964 web: stylize the file receiver, move text to i18n, update remux page 2024-08-13 14:17:10 +06:00
wukko
09deb5c7b6 web/Sidebar: move settings tab to bottom & move updates tab lower 2024-08-13 12:35:18 +06:00
wukko
6cc0871d99 web: add static headers file for multithreading on cloudflare pages 2024-08-13 12:06:09 +06:00
dumbmoron
e79f466c5f web/libav: shrink buffer _after_ ffmpeg is done running 2024-08-13 00:23:13 +00:00
dumbmoron
e084092f37 web/libav: remove stray curly brace 2024-08-12 20:39:36 +00:00
dumbmoron
bc272b910e web/libav: fix import double slash, use unlinkreadaheadfile 2024-08-12 20:36:24 +00:00
dumbmoron
5fb9b1c809 web: bump libav.js version 2024-08-12 20:34:57 +00:00
dumbmoron
83f46864b2 web/libav: properly instantiate libav property 2024-08-12 20:03:30 +00:00
dumbmoron
038c29dc8d web/libav: move types to dedicated file 2024-08-12 20:03:07 +00:00
wukko
b2288ed037 web: remove ffmpeg worker workaround 2024-08-13 00:23:20 +06:00
wukko
ed722e77ea web: remove ffmpeg wasm dependencies 2024-08-13 00:20:01 +06:00
wukko
55ab3c36b1 web/lib: remove ffmpeg 2024-08-13 00:18:45 +06:00
dumbmoron
940826697c web/libav: preallocate memory for output when remuxing 2024-08-12 18:07:04 +00:00
dumbmoron
2198a696ce web/libav: make it work & clean up 2024-08-12 17:06:45 +00:00
dumbmoron
75ef4604d8 web/vite: expose libav.js files directly 2024-08-12 16:47:11 +00:00
wukko
6a04312781 web: update package 2024-08-12 22:30:09 +06:00
wukko
57054c24b2 web: draft libav functionality 2024-08-12 22:28:38 +06:00
wukko
778eb51502 web/ffmpeg: don't return an empty blob 2024-08-11 19:13:04 +06:00
wukko
3fd05891e6 web/remux: move drop area and open file button into own components 2024-08-11 18:30:42 +06:00
wukko
b33bd39484 web/ffmpeg: accept and return blob, proper types & extensions, clean up 2024-08-11 18:24:29 +06:00
wukko
f87f6fa9c9 web/remux: accept files on drag, update ffmpeg function call 2024-08-11 13:05:15 +06:00
wukko
1113ddd9c5 web/ffmpeg: universal render function for all needs 2024-08-11 13:04:40 +06:00
dumbmoron
7044100aed web: fix build for remux and remove unused import 2024-08-10 11:45:16 +00:00
wukko
3c2dd93841 web/SidebarTab: fix scroll to first page of tabs 2024-08-10 17:43:53 +06:00
wukko
41a002929e web: barebones core for ffmpeg & remux page 2024-08-10 17:21:39 +06:00
wukko
ebd6cc801b web/Sidebar: remove incorrect aria-orientation 2024-08-09 21:07:38 +06:00
wukko
5e0824022c web/DonateShareCard: add alt text for qr code 2024-08-09 21:04:56 +06:00
wukko
b71d51de21 web: move svg icons from lib to components 2024-08-09 16:35:00 +06:00
wukko
6bda6dab03 web/DonateShareCard: hide twitter button in russia 2024-08-09 16:06:33 +06:00
wukko
d1a2d768d9 web/DonateShareCard: expand the card on QR press & better scaling 2024-08-09 16:06:19 +06:00
wukko
f81f155eb0 web/DonateShareCard: clean up imports 2024-08-09 14:52:48 +06:00
wukko
ffea8e6f2e web/DonateShareCard: hide share button if user agent doesn't support it 2024-08-09 14:52:22 +06:00
wukko
e7386234bc web/DonateShareCard: fix unrelated buttons triggering the copy anim 2024-08-09 14:51:25 +06:00
wukko
e4ec468f60 web/DonateShareCard: change action button id and class names
some adblock lists block everything named "share-button(s)"
2024-08-09 14:47:54 +06:00
wukko
077471d799 web/DonateShareCard: localize strings 2024-08-09 14:40:52 +06:00
wukko
536d9c9742 web/i18n: move call to action button strings to own file 2024-08-09 14:40:30 +06:00
wukko
21ef35ea20 web/donate: add a share card with qr and buttons
also:
- fixed more scaling quirks
- fixed thick icons
- fixed icon padding
2024-08-09 14:35:55 +06:00
wukko
e45aa2bdf6 web/CopyIcon: replace copy icon with a link icon 2024-08-09 14:35:06 +06:00
dumbmoron
2e9721d611 repo: set up api-client package 2024-08-09 07:55:21 +00:00
wukko
937d12ddff web/donate: bring up repeated card css to container
also fixed some scaling quirks on mobile
2024-08-09 13:13:48 +06:00
wukko
209833c8ea web/DonateOptionsCard: update subtitle color 2024-08-09 12:27:49 +06:00
wukko
b8cd6eb1e7 web/Sidebar: update tab holder aria role 2024-08-09 12:05:59 +06:00
wukko
608824f862 web/DonateBanner: focus the title first on the page 2024-08-09 12:05:15 +06:00
wukko
c94266a127 web/DonateOptionsCard: better accessibility 2024-08-09 12:04:43 +06:00
wukko
d4e91f2a1c web/DonateOptionsCard: fix button active color 2024-08-09 11:48:04 +06:00
wukko
cc5835a546 web/DonateOptionsCard: adjust padding, fix width, mask options row 2024-08-09 11:46:56 +06:00
wukko
98ac05ad86 web/donate: reduce text padding on mobile 2024-08-09 11:35:05 +06:00
wukko
80c26f712c web/DonateBanner: better scaling 2024-08-09 11:31:57 +06:00
wukko
abeacd7534 web/DonateOptionsCard: move all strings to i18n, mobile scaling 2024-08-09 11:31:44 +06:00
wukko
e727e3a95b api/processing: slightly reformat code related to zod 2024-08-08 23:43:04 +06:00
dumbmoron
66d70ffc44 test: update match() call format 2024-08-08 16:35:19 +00:00
dumbmoron
f32f624916 api: use zod for request schema validation 2024-08-08 16:34:54 +00:00
dumbmoron
b510cbf9e0 web/donate: add dollar sign before custom input 2024-08-06 18:30:06 +00:00
dumbmoron
c90a01daf9 web/donate: update logic for sending custom amounts 2024-08-06 18:30:06 +00:00
dumbmoron
d67ed89c38 web/donate: refactor, implement logic for choosing donation periodicity 2024-08-06 18:30:06 +00:00
dumbmoron
1077797aae web/donate: add minimum/maximum amounts to donation amount 2024-08-06 18:30:06 +00:00
wukko
03152375ec api/snapchat: fix the reverse strict not equals operator
oh my god
2024-08-06 21:35:39 +06:00
wukko
4505d6cfe1 web/api: merge picker types 2024-08-06 21:32:17 +06:00
wukko
9ff27391d0 api/snapchat: don't return thumb for photos in a picker
prevents saving low quality images with a long press
2024-08-06 21:31:43 +06:00
wukko
72a21b203e api/twitter: don't return thumb for photos in a picker
it's the same image anyway, this just makes the response smaller
2024-08-06 21:31:15 +06:00
wukko
95f5fd978f api: merge two picker types into one 2024-08-06 21:30:18 +06:00
wukko
ac6d68ec45 web/api: remove deprecated statuses, update error type, time out request
also updated some error codes
2024-08-06 20:50:20 +06:00
wukko
f96c1cd13b api: remove deprecated statuses & clean up related code 2024-08-06 20:45:04 +06:00
dumbmoron
5948cab4fb web: move iPadOS workaround to global level 2024-08-06 14:19:01 +00:00
dumbmoron
3b90f5ee17 web/Omnibox: workaround for link area being unusable on iPadOS 15 2024-08-06 14:02:21 +00:00
dumbmoron
075b2799e3 web/DonateBanner: fix top scroll caused by banner hearts overflowing
wtf
2024-08-06 13:24:11 +00:00
dumbmoron
0b602b9164 web/DonateBanner: disable pointer events for background animation 2024-08-06 12:42:17 +00:00
wukko
83cd51f4db web/DonateOptionsCard: fix width 2024-08-06 16:53:40 +06:00
wukko
a25e0bfb04 web/DonateOptionsCard: fix prefilled stripe amount 2024-08-06 16:48:39 +06:00
wukko
14d0577895 web/DonateOptionsCard: hide webkit stepper button 2024-08-06 16:46:32 +06:00
wukko
eccf75b7b7 web/donate: redesign the donation options card 2024-08-06 16:45:25 +06:00
wukko
5d58502fd8 web/DonateBanner: fix meowbalt overlapping the update notification 2024-08-06 14:57:10 +06:00
wukko
c98b08fc7f web/DonateBanner: load imput logo as component 2024-08-06 14:54:31 +06:00
wukko
e074dd5b89 web/layout: more global styling for long-text-noto 2024-08-06 14:50:12 +06:00
wukko
bf73f512e2 web/donate: move donation options card to own component
- moved reused variables to parent
- added body text
2024-08-06 14:48:06 +06:00
wukko
87b76ec1e2 web/layout: add global long-text-noto style class 2024-08-06 14:29:15 +06:00
wukko
894c1ada24 web/DonateBanner: make subtitle easier to read 2024-08-06 14:28:32 +06:00
wukko
250269bc09 web/DonateBanner: move to donate components folder 2024-08-06 14:27:56 +06:00
wukko
c8a0f74e62 web/DonateBanner: dark theme & scaling support 2024-08-06 14:09:16 +06:00
wukko
9dad15b48c web/DonateBanner: fix up colors & sizes to match mockup 2024-08-06 13:24:40 +06:00
dumbmoron
640898e022 web/donate: move header to component, initial donation options 2024-08-04 16:11:26 +00:00
dumbmoron
e72efae24d web/donate: initial re-redesign 2024-08-04 16:11:26 +00:00
dumbmoron
d431e9e9a2 web: add fast meowbalt 2024-08-04 16:11:26 +00:00
wukko
6267d1d58f web/version: use workspace version-info package 2024-08-04 22:01:36 +06:00
wukko
bfbf653463 web/package: update version to 10.0.0 2024-08-04 00:52:27 +06:00
wukko
61f8a61986 web/i18n/settings: point out that processing override desc isn't final 2024-08-04 00:47:09 +06:00
wukko
aba444ec8b web: updated api endpoint & params, default instance override
- dialogs can be undismissable now (impossible to click away by pressing the bg behind it)
- added security warning about api override
- moved default api url to env
- added new processing settings page
2024-08-04 00:43:24 +06:00
dumbmoron
168c1bdbbb api/test: update tests to use new request format 2024-08-03 17:33:56 +00:00
dumbmoron
94c2545ca6 api/serverInfo: make cors into boolean 2024-08-03 17:11:18 +00:00
wukko
0a28b4091f api/youtube: small indentation fix 2024-08-03 23:08:59 +06:00
wukko
5ea71ee58e api: update post parameters
they're now way easier to read
2024-08-03 23:06:32 +06:00
dumbmoron
d419fd35b0 ci: add build action for develop tag 2024-08-03 16:48:57 +00:00
dumbmoron
a7ab4a9706 version-info: don't throw on import if git does not exist 2024-08-03 16:48:57 +00:00
dumbmoron
985f6e385d docker: update dockerfile to use pnpm features 2024-08-03 16:48:57 +00:00
dumbmoron
c751837ed8 api/package: change name to @imput/cobalt-api 2024-08-03 16:48:57 +00:00
wukko
f227abf6cb docs/examples/compose: remove version top-level element 2024-08-03 22:09:35 +06:00
wukko
c57dce6806 docs/examples/compose: remove web example 2024-08-03 22:07:14 +06:00
wukko
e58bca0cdd api: remove alias mapping for deprecated env variables 2024-08-03 22:05:50 +06:00
wukko
edbea16b91 ci/test.sh: update api endpoint 2024-08-03 21:51:46 +06:00
wukko
3bd1a00855 api: renovate endpoints
no more redundant "/api" path
2024-08-03 21:51:05 +06:00
wukko
40425ad3bf api: use version-info package & clean up start message 2024-08-03 21:34:02 +06:00
wukko
0d20ffc004 packages: add version-info package 2024-08-03 21:27:14 +06:00
wukko
bef9b5b172 snapchat: add support for android short links 2024-08-03 16:50:57 +06:00
wukko
417a21ea91 ci: fix service config retrieval 2024-08-03 16:36:01 +06:00
wukko
0a411196e9 api/config: clean up (better formatting) 2024-08-03 16:33:36 +06:00
wukko
332eae16b2 api: convert service config to JS and remove it from main config 2024-08-03 16:27:20 +06:00
dumbmoron
3a2504ae87 ci: fix invalid node version for web 2024-08-03 09:52:46 +00:00
dumbmoron
18b3daf90f web/package: lower minimum node version, replace npm with pnpm 2024-08-03 09:50:42 +00:00
dumbmoron
786fd0555e ci: use node v20 for web build, clean up 2024-08-03 09:50:24 +00:00
dumbmoron
2beacce70d ci: use pnpm in tests 2024-08-03 09:32:42 +00:00
dumbmoron
e50b4b0328 repo: set up package.json in root 2024-08-03 09:31:59 +00:00
dumbmoron
350e1d4d4f ci: update tests for new cobalt 2024-08-03 09:29:33 +00:00
dumbmoron
6d817f149e api/load-from-fs: refactor loadFile, use in loadJSON 2024-08-03 09:29:33 +00:00
dumbmoron
0e0ad7cb0e api/load-from-fs: always load files from root of api folder 2024-08-03 09:29:33 +00:00
wukko
8e7b63ade6 api/match: fix audio format variable typo 2024-08-03 15:05:00 +06:00
wukko
0ffea2d886 api/match: pass action parameters as object 2024-08-03 15:02:59 +06:00
dumbmoron
559e8448e5 repo: add static build to gitignore 2024-08-03 08:59:57 +00:00
wukko
dd831e13e8 api: flatten code directories, better filenames, remove old files 2024-08-03 14:47:13 +06:00
dumbmoron
5ce208f1a5 ci: run tests on all branches 2024-08-03 10:38:57 +02:00
wukko
aff22e8560 api: remove localization, renovate error response 2024-08-03 13:51:09 +06:00
dumbmoron
3fdf266ad0 youtube: periodically refresh innertube player 2024-08-03 12:46:01 +06:00
wukko
dd30973601 package: update version to 10.0.0 2024-08-02 22:35:56 +06:00
wukko
f66ae63d57 api/core: remove favicon 2024-08-02 22:35:49 +06:00
wukko
012fadd2f0 api: remove API_NAME env variable & from server info 2024-08-02 21:33:59 +06:00
wukko
2575b0c145 api: remove web mode & variables 2024-08-02 21:32:00 +06:00
wukko
eede972ace api: remove old frontend files 2024-08-02 21:23:56 +06:00
wukko
ec98605336 git: update general gitignore & web gitignore 2024-08-02 21:16:04 +06:00
wukko
4f877f199b web: add to pnpm workspace and move lock to pnpm 2024-08-02 21:03:25 +06:00
wukko
c1179e2c9b merge: svelte branch into 10 2024-08-02 20:57:29 +06:00
wukko
65e095b178 repo: add pnpm workspace config & lock 2024-08-02 20:45:32 +06:00
wukko
213d259b09 repo: remove package-lock 2024-08-02 20:43:37 +06:00
wukko
a7087336ca repo: move api src from root to own subdir 2024-08-02 20:41:52 +06:00
wukko
008163073d web/updates: merge skeleton & entry components 2024-07-31 19:28:48 +06:00
wukko
2c4ba96d57 web/TransferSettings: pretty formatting 2024-07-31 14:59:53 +06:00
wukko
e7587a2ec6 web/TransferSettings: friendlier error messages 2024-07-31 14:57:34 +06:00
wukko
585ebd9cb4 web/settings/advanced: hide reset settings button if there are no settings 2024-07-31 13:53:34 +06:00
dumbmoron
d1930c1dbc web/advanced: check if imported settings are valid 2024-07-30 17:15:38 +00:00
dumbmoron
3d34e09e1c web: don't display pointer cursor for disabled buttons 2024-07-30 16:37:44 +00:00
dumbmoron
a6a0e91674 web/TransferSettings: don't offer export if there is nothing to export 2024-07-30 14:08:49 +00:00
wukko
96df9d55b8 web/updates: fix duplicate css 2024-07-29 14:46:10 +06:00
wukko
5fc893a273 web/updates: add alt text to navigation buttons 2024-07-29 14:32:15 +06:00
wukko
8b866ddf6f web/SettingsNavTab: reduce padding on desktop 2024-07-29 13:11:29 +06:00
wukko
a4e0e21a97 web/Omnibox: accept keyboard shortcuts only when focused 2024-07-28 23:36:38 +06:00
wukko
48d24ee1ea web/SavingDialog: show that link was copied, better accessibility 2024-07-28 23:29:32 +06:00
wukko
3aeebcc911 web/SavingDialog: don't render body text parent if there's no text 2024-07-28 19:20:32 +06:00
wukko
97e7763503 web/download: show explanation when getting blocked by browser 2024-07-28 19:15:22 +06:00
wukko
5c780a2d2e web: added saving method preference, made downloading resilient 2024-07-28 18:59:58 +06:00
wukko
87adffaf02 web/ResetSettingsButton: add a timeout to reset button in dialog 2024-07-28 14:51:02 +06:00
wukko
f34340a06d web/TransferSettings: add a timeout to import button in dialog 2024-07-28 14:50:59 +06:00
wukko
11d3d71937 web/dialogs: move buttons to own component & add optional timeout 2024-07-28 14:49:12 +06:00
wukko
a2ead8a813 web/i18n/dialog: add more info to import warning 2024-07-28 14:08:27 +06:00
wukko
cce3ce4cfa web/download: show saving dialog if new tab got blocked 2024-07-28 13:49:23 +06:00
dumbmoron
299d1867a2 web/TransferSettings: only export storedSettings instead of all settings 2024-07-28 07:46:15 +00:00
wukko
71204054c7 web/settings/defaults: disable downloadPopup by default 2024-07-28 13:33:09 +06:00
wukko
82091db154 web/download: open saving dialog if user action expired 2024-07-28 13:32:21 +06:00
wukko
4210b17d89 web/TransferSettings: show a safety warning before importing 2024-07-28 13:20:22 +06:00
wukko
5bb5c6dc3c web/SmallDialog: fix line breaking in body text 2024-07-28 13:15:28 +06:00
wukko
194ff90d3d web/layout: fix elevated colored button hover & active states 2024-07-28 13:14:55 +06:00
wukko
2fa1ad8f12 web/SavingDialog: hide buttons when actions are not supported 2024-07-28 12:49:13 +06:00
wukko
32743360be web/Omnibox: fix dimmed input placeholder in firefox 2024-07-27 19:27:58 +06:00
wukko
1ded7698ff web/Omnibox: fix input area dimming in safari when processing 2024-07-27 19:26:39 +06:00
wukko
6072fbac5c web/DialogHolder: fix bottom margin on mobile during the close animation 2024-07-27 19:26:07 +06:00
wukko
59f5560802 web/dialogs: move backdrop close handler to container 2024-07-27 15:30:00 +06:00
wukko
b8eb708748 web/DialogHolder: fix typescript error, add a note 2024-07-27 15:28:02 +06:00
wukko
26eaac5742 web/ActionButton: clean up 2024-07-27 15:07:38 +06:00
wukko
a9f9a3e342 web/dialogs: add saving method dialog 2024-07-27 15:07:26 +06:00
wukko
7411f358d2 web/DialogButtons: move elevated button styling to layout 2024-07-27 15:03:37 +06:00
wukko
778190b2b3 web/dialogs: create a container for reused code 2024-07-27 14:24:24 +06:00
wukko
0a7747c497 web/dialogs: move duplicated dialog css to parent 2024-07-27 12:53:57 +06:00
dumbmoron
82ecf16d79 web/donate: disable padding-left for wallets on mobile 2024-07-26 17:06:03 +00:00
dumbmoron
b3d8a9bf1c web/donate: minor css fixes 2024-07-26 17:00:01 +00:00
wukko
7427788efd web/PickerItem: add support for gifs in picker 2024-07-26 21:34:18 +06:00
dumbmoron
e0bc0553ca web/donate: fix price padding 2024-07-26 09:05:14 +00:00
dumbmoron
8ac834ec80 web: initial donate page 2024-07-26 08:22:30 +00:00
dumbmoron
809178d6d8 web: import italic normal version of ibm-plex-mono 2024-07-26 08:22:21 +00:00
dumbmoron
7a5e4c56d3 web/settings: make old settings migration use initial schema 2024-07-24 10:27:06 +00:00
wukko
49973eceb1 web/omnibox: disable input area when processing & reduce timeout
also fixed a typo that broke key spamming protection
2024-07-26 14:07:23 +06:00
dumbmoron
f8d06cf18b web/settings: settings import/export 2024-07-23 18:17:38 +00:00
wukko
6e24a8d172 web/PickerItem: enable video thumb mode only when item is a video 2024-07-23 22:11:25 +06:00
dumbmoron
5e26c1e122 web/PickerItem: small refactor 2024-07-23 16:07:12 +00:00
dumbmoron
690ae835b4 web/ChangelogEntry: hide focus ring for version 2024-07-23 12:18:18 +00:00
dumbmoron
3218adf5fd web/changelogs: focus on version on page load 2024-07-23 11:42:13 +00:00
wukko
b540703de8 web/UpdateNotification: increase icon size 2024-07-23 16:46:18 +06:00
wukko
8b6775ca86 web/UpdateNotification: reduce right padding 2024-07-23 16:43:29 +06:00
dumbmoron
c32a5301a0 web/updates: make page scrollable on navigation sides on desktop 2024-07-23 10:32:18 +00:00
dumbmoron
61e47b38d1 web/DownloadButton: slight refactor 2024-07-23 10:09:42 +00:00
wukko
2d7d4cf091 web: add an update notification 2024-07-23 16:04:43 +06:00
dumbmoron
89181c6ddc web/settings: make version info optional, wait for load 2024-07-23 09:36:49 +00:00
wukko
23c9eb73aa web: global data-focus-ring-hidden attribute 2024-07-23 14:41:55 +06:00
wukko
19ee8360c4 web/updates: revert div -> main to fix html hierarchy 2024-07-23 14:19:22 +06:00
wukko
0d34bc0ab3 web/updates: focus the main content & fix ghost buttons 2024-07-23 14:13:05 +06:00
wukko
a9e8ea1306 web/Placeholder: focus first on page 2024-07-23 14:08:34 +06:00
wukko
f2de69f153 web/save: focus the page content on navigation 2024-07-23 14:06:44 +06:00
wukko
1234cc1083 web/settings: focus the page after navigation
mobile: focus page header
desktop: focus page content
2024-07-23 14:04:19 +06:00
wukko
c9ca0d51d9 web: add first focus functionality
element with `data-first-focus` will be focused first after navigation. extremely useful for screen readers.
2024-07-23 13:53:43 +06:00
wukko
314d3590ec web/DialogButtons: don't apply hover effect if button is colored 2024-07-23 13:22:05 +06:00
wukko
c12088e297 web/SmallDialog: flex container for header & icon
fixes stranded padding
2024-07-23 13:18:08 +06:00
wukko
836da67f19 web/changelogs: remove 3.3 changelog as it's a duplicate of 3.4 2024-07-23 12:44:13 +06:00
wukko
94853f0b7b web/FilenamePreview: finish the component 2024-07-23 12:34:14 +06:00
wukko
518f634385 web/settings: reduce thickness of back button icon 2024-07-23 12:20:30 +06:00
wukko
5c6ef19132 web/settings: update the back button icon 2024-07-23 12:19:38 +06:00
wukko
48078e7e75 web/updates: replace chevron with arrow 2024-07-23 12:19:12 +06:00
wukko
ee162aa236 web/ClearButton: fix rendering bug in safari & clean up 2024-07-23 12:13:40 +06:00
wukko
0225a7c46c web/settings: simplify sidebar, add version info, flatten page navigation 2024-07-23 11:00:27 +06:00
wukko
8c96ccbc7b web/SmallDialog: make body scrollable on overflow & limit height 2024-07-23 10:01:55 +06:00
wukko
bdd572ea51 web/dialogs: reduce margin on mobile 2024-07-23 09:59:08 +06:00
wukko
7ee99ad30f web/Skeleton: add elevated skeleton and use it for picker item
- fixed bg not being visible when shimmer is not on the element in dark theme
- fixed stuck gradient when motion is reduced
- fixed big skeleton
- skeleton is no longer focusable
2024-07-23 09:55:55 +06:00
wukko
718dc4cf0a web/DownloadButton: darken when disabled 2024-07-22 16:42:37 +06:00
wukko
2fb05d018c web/DownloadButton: show done button state for picker 2024-07-22 16:35:36 +06:00
wukko
bc8e3d4a7c web/Omnibox: simplify link state storage 2024-07-22 16:34:19 +06:00
dumbmoron
44243cc4c2 web/PickerDialog: fix typo 2024-07-22 14:17:33 +00:00
dumbmoron
d170f619d2 web: use conditionals instead of special classes where it makes sense 2024-07-22 10:17:06 +00:00
wukko
b0a69f9944 web/PickerItem: always show type badge, prevent right click on video
- fixed type badge centering in webkit
- increased border radius of type badge to match icons inside it
2024-07-22 16:14:26 +06:00
dumbmoron
c03337fed9 web/skeleton: don't render if hidden 2024-07-22 10:11:23 +00:00
dumbmoron
705fac16a6 web/dialog: internal refactor 2024-07-22 09:24:17 +00:00
wukko
9787a04e19 web/picker: add item type icons and improve accessibility 2024-07-22 15:13:51 +06:00
dumbmoron
7c5b703e37 web/dialog: refactor types and logic 2024-07-22 09:06:11 +00:00
dumbmoron
4e4f7af437 web/settings: types for preparation for future migrations 2024-07-22 08:38:06 +00:00
wukko
66bac03e30 web/dialogs: add picker dialog & clean up small dialog 2024-07-22 14:33:43 +06:00
wukko
24b783e5fb web/Omnibox: remember the link input when switching between tabs 2024-07-22 09:55:04 +06:00
dumbmoron
787fe72340 web/ChangelogEntry: fix warning about unused css selector 2024-07-21 17:40:51 +00:00
dumbmoron
bb446ecf3e web: add Optional type and use it 2024-07-21 17:26:21 +00:00
wukko
f93f3cd558 web/DownloadButton: fallback if status isn't supported 2024-07-21 22:49:26 +06:00
dumbmoron
9b4f593f87 web/changelogs: add more historical changelogs 2024-07-21 15:53:33 +00:00
wukko
4402484a0c web/updates: reduce mobile navigation padding 2024-07-21 17:34:31 +06:00
dumbmoron
4fab0d3fb8 web/ChangelogEntry: expect date to always exist 2024-07-21 11:31:55 +00:00
dumbmoron
534af330ce web/changelogs: make date attribute required 2024-07-21 11:30:06 +00:00
dumbmoron
ebaa209c47 web/changelogs: add dates to all changelogs 2024-07-21 11:29:57 +00:00
wukko
213f2d2c92 web/updates: hide navigation buttons when nowhere to navigate
- removed box shadow on desktop
- centered button vertically with flex
2024-07-21 17:22:22 +06:00
wukko
88fa780f6d web/layout: add dark theme skeleton gradient 2024-07-21 17:06:47 +06:00
wukko
238cd22c8d web/ChangelogSkeleton: fix title skeleton cutting off, reduce rounding 2024-07-21 16:57:42 +06:00
wukko
d8acb5406a web/layout: fix skeleton gradient 2024-07-21 16:49:38 +06:00
dumbmoron
8366a9d9b6 web/changelog: use same stylesheet for skeleton and loaded entry 2024-07-21 10:06:43 +00:00
dumbmoron
20320c1935 web: use svelte-preprocess instead of vitePreprocess
this allows us to use <style src={...}></style> also for scoped styles
(and not just global styles)
2024-07-21 10:06:16 +00:00
dumbmoron
0cea58922d web/changelogs: display skeleton when changelog is loading 2024-07-21 09:42:48 +00:00
wukko
f530624467 web/ResetSettingsButton: update dialog text
erase -> reset
2024-07-21 16:40:39 +06:00
wukko
ec768ebfc2 web/settings/metadata: basic filename preview component 2024-07-21 16:34:37 +06:00
wukko
edd1137228 web/ChangelogEntry: deduplicate padding when banner isn't visible 2024-07-21 14:45:24 +06:00
wukko
dbbd43e002 web/changelog: move components to dedicated folder 2024-07-21 14:42:17 +06:00
wukko
2efaa11670 web/DialogHolder: clean up 2024-07-21 14:37:03 +06:00
wukko
782752fd60 web/OuterLink: accept rel but ignore it 2024-07-21 14:34:29 +06:00
wukko
a7f40d708e web/meowbalt: hide meowbalt from screen readers
presence of an image of a cat on the screen doesn't change anything about the ui for vision impaired people. it's unnecessary and potentially annoying to have the description of it read out loud on every screen it's used.
2024-07-21 13:59:27 +06:00
wukko
f07aac301c web/SmallDialog: focus title first when it's visible 2024-07-21 13:49:22 +06:00
wukko
80300bf766 web/dialogs: moved backdrop to dialog holder, improved animation 2024-07-21 13:41:14 +06:00
dumbmoron
8a080c55f6 web: refactor and deduplicate locale preference logic 2024-07-20 14:37:52 +00:00
wukko
d4d4eded32 web/SmallDialog: make button text white if its bg is red 2024-07-20 21:56:43 +06:00
wukko
d7bf98a80b web: settings reset confirmation, icons for small dialog
- cleaned up dialog i18n
- better red color
- made :active state visible for dialog buttons on mobile
- better body padding in small dialog
- better small dialog typing with optional values
2024-07-20 21:48:17 +06:00
dumbmoron
def6e26b9f web/settings: add "erase all settings" button 2024-07-20 14:01:13 +00:00
wukko
720b3c5f68 web: full SmallDialog component, one flexible meowbalt component
- fully stylized small dialog: header, title, subtext, state without meowbalt
- moved meowbalt into his own adaptive component, no need to import/create new ones for each emotion
- better types for dialog related stuff
- type for meowbalt's emotions
- better padding in small dialog
2024-07-20 20:34:19 +06:00
wukko
e541bdc6d7 web/Switcher: fix ghost hover effect on active button
it used to appear very briefly when you pressed a button and didn't move the cursor off the button
2024-07-20 19:09:44 +06:00
wukko
8193e8c14d web/buttons: add hover state to active button 2024-07-20 18:54:12 +06:00
wukko
205494b367 web/SmallDialog: fix scaling on small screens 2024-07-20 18:49:51 +06:00
wukko
cd41fc9d49 web/SmallDialog: fix rendering & performance issues, new mobile animation 2024-07-18 17:22:29 +06:00
dumbmoron
2c1bd50e70 Revert "web/vite: change build target to esnext"
This reverts commit 842f91ec54.
2024-07-20 12:43:22 +00:00
dumbmoron
c3c7a6b7ba web/version: convert to readable 2024-07-20 12:43:14 +00:00
dumbmoron
0e60ea9582 web/ChangelogEntry: consistent date formatting 2024-07-17 09:07:25 +00:00
dumbmoron
0391ac7230 web/ChangelogEntryWrapper: use OuterLink component for links 2024-07-17 08:59:45 +00:00
dumbmoron
dd16fb65cf web/changelogs: update all links to markdown format 2024-07-17 08:59:10 +00:00
wukko
ce609ad201 web/SmallDialog: allow text selection in body 2024-07-17 14:50:35 +06:00
wukko
204e025656 web/layout: allow text selection in subtext 2024-07-17 14:50:09 +06:00
wukko
ce95135234 web/ChangelogEntry: allow text selection 2024-07-17 14:49:25 +06:00
wukko
691a6acb6c web/ChangelogEntry: slightly reduce font size on mobile 2024-07-17 14:41:44 +06:00
wukko
cf4ee05e0e web/updates: reduce top padding on mobile 2024-07-17 14:38:02 +06:00
wukko
dd7c17efeb web/ChangelogEntry: reduce the size of heading contents 2024-07-17 14:34:03 +06:00
wukko
6a7311874e web/changelog: make main body text easier to read 2024-07-17 14:29:46 +06:00
wukko
6e374fde62 web/updates: make changelogs look nicer
- fixes horizontal scrolling on mobile
- removes text backdrop
- improves readability
2024-07-17 14:04:53 +06:00
wukko
1ec9d92eb2 web/updates: clean up components 2024-07-17 13:32:07 +06:00
dumbmoron
8eee024899 web/updates: don't prevent default action for keyboard inputs 2024-07-17 07:30:22 +00:00
wukko
e6ec8c6734 web/package: fix the svelte icons version & update lock 2024-07-17 13:14:56 +06:00
dumbmoron
5c07afe4ff web/updates: keyboard navigation 2024-07-16 17:27:43 +00:00
dumbmoron
678adfbda4 web/updates: proper navigation buttons, refactor internal nav logic 2024-07-16 17:25:21 +00:00
dumbmoron
3305bba28a web/updates: update hash on navigation, navigate if present on load 2024-07-16 17:21:53 +00:00
dumbmoron
a22b0e5136 web/ChangelogEntry: initial css 2024-07-16 17:19:17 +00:00
dumbmoron
766482c21a frontend: setup initial updates page 2024-06-29 18:23:56 +00:00
dumbmoron
3aa17733d1 frontend: install and configure mdsvex 2024-06-29 17:58:00 +00:00
dumbmoron
a856983810 web: convert changelogs from old format
https://gist.github.com/dumbmoron/3fc6c0c747d791928aba939976fd9304
2024-06-29 17:36:26 +00:00
dumbmoron
e1a898bd58 frontend: move update banners to new frontend 2024-06-27 23:18:52 +00:00
wukko
8ebde39197 web/Omnibox: prevent paste button spamming 2024-07-16 22:17:51 +06:00
wukko
504dfdb995 web/Omnibox: ignore keyboard shortcuts when processing 2024-07-16 22:11:57 +06:00
wukko
d31090c3d5 web/Omnibox: ignore keyboard shortcuts when dialog is visible 2024-07-16 22:03:16 +06:00
wukko
fa835d0010 web/dialog: css for small dialog
- moved backdrop to each dialog
- dialog is now closable by clicking the backdrop
- added meowbalt to dialogs
- added more meowbalt assets & components
- added "main" boolean to indicate the main action button in a list of buttons
2024-07-16 14:00:56 +06:00
wukko
03bd995839 web/Omnibox: disable focus ring on inner input element 2024-07-15 14:29:02 +06:00
wukko
25cfa3e443 web/Omnibox: add extraction of links from page hash and query 2024-07-15 14:21:51 +06:00
wukko
f9dc8096bc web: always show focus ring 2024-07-14 23:21:04 +06:00
wukko
6ff874d5a1 web/i18n/settings: fix a typo in analytics description 2024-07-14 23:05:31 +06:00
wukko
128ab388f3 web: add env variable & plausible functionality 2024-07-14 22:50:18 +06:00
dumbmoron
436b735d2a web/settings: try to migrate settings if new format is not used yet 2024-07-13 20:39:40 +00:00
dumbmoron
5a630c2320 web/migrate: set up migration from old settings format 2024-07-13 20:37:38 +00:00
wukko
9f649ff1db web/settings: update analytics text & add a link to more info 2024-07-14 21:51:56 +06:00
wukko
f582be5d44 web/i18n/save: remove "the" from terms note 2024-07-14 21:27:34 +06:00
dumbmoron
4168998b93 web/settings: add "privacy" page with analytics toggle 2024-07-14 15:26:55 +00:00
dumbmoron
ee9421b831 web/state/settings: add "disable analytics" option 2024-07-14 15:22:42 +00:00
wukko
578150e40e web: add dynamic lang html tag 2024-07-14 21:10:41 +06:00
wukko
ad3703ab73 web/settings: fix header on mobile at certain scales 2024-07-14 20:52:22 +06:00
wukko
1712dc8948 web: switch main body color depending on theme 2024-07-14 20:42:32 +06:00
wukko
36c11556d7 web/i18n/save: fix grammar in terms note 2024-07-14 20:33:49 +06:00
dumbmoron
1f0958a0d1 web/settings: move to state folder 2024-07-13 13:17:03 +00:00
wukko
4232c3437b web: dialog system & basic small dialog 2024-07-13 19:15:43 +06:00
wukko
c5fbff560b web/debug: show all data as json 2024-07-13 19:07:35 +06:00
dumbmoron
15caad7e36 web: adjust gray color to pass WCAG AA guideline 2024-07-13 12:51:31 +00:00
dumbmoron
3f98f5bee8 settings: move schemaVersion definition to updateSetting 2024-07-13 12:32:08 +00:00
dumbmoron
f4aff44004 debug: include settings json on page 2024-07-13 12:25:50 +00:00
dumbmoron
2cce4bd521 settings: expose settings that have only been modified
also reduce unnecessary loads from storage
2024-07-13 12:25:27 +00:00
dumbmoron
2a0366a58d settings: add migrations, include schemaVersion in storage 2024-07-13 12:05:52 +00:00
wukko
6c9d759a3a web: update save page i18n & add link to terms and ethics of use
now also styling <a> properly, with exceptions only when needed
2024-07-13 13:45:53 +06:00
wukko
151fdad047 web/Sidebar: make bottom padding match the corner radius of the page 2024-07-12 20:49:44 +06:00
wukko
ce740770bc web/Sidebar: remove duplicate padding in css 2024-07-12 20:46:46 +06:00
wukko
96be9ffbc3 web/sidebar: redo padding on mobile & desktop
- accommodate space for scaling animation
- replace static padding with variable in calculations
- no more weird padding on mobile
2024-07-12 20:22:12 +06:00
wukko
914be64153 web/settings: make navigation scrollable on overflow 2024-07-12 19:18:47 +06:00
wukko
5ccde7995e web: convert global state classes to data attributes
also cleaned up unnecessary dupe in sidebar component
2024-07-12 19:15:55 +06:00
wukko
b12ad56cc1 web/LanguageAutoToggle: update preferred language variable name 2024-07-12 19:02:23 +06:00
wukko
d27bed7add web: respect reduced motion & transparency preferences
also cleaned up settings & device libs
2024-07-12 18:49:29 +06:00
wukko
1160b90c17 web/SidebarTab: apply will-change only on iphone 2024-07-12 17:16:26 +06:00
wukko
459c746dcc web/SidebarTab: yet another attempt to fix blurriness on small res screens 2024-07-12 17:06:05 +06:00
wukko
27082cd725 web/SidebarTab: go back to neutral transform state at end of animation 2024-07-11 12:26:39 +06:00
dumbmoron
aea7ebb371 LanguageAutoToggle: change language even if it does not exist
if the locfile does not exist, it will just fall back to english
2024-07-10 18:46:43 +00:00
wukko
4759f2037c web/device: add user agent 2024-07-11 00:27:46 +06:00
wukko
02437a686c web/i18n/settings: update language description
added information about translation fallback
2024-07-11 00:21:49 +06:00
wukko
7648c115e0 web/vite: change build target to esnext 2024-07-11 00:05:29 +06:00
wukko
936da1c9ab web/debug: show page content only when debug mode is enabled 2024-07-10 23:52:44 +06:00
wukko
6c7695ca6c web/error: redirect home on 404 2024-07-10 23:50:50 +06:00
dumbmoron
95bcf7bf66 settings: only store settings if changed by user 2024-07-10 17:47:46 +00:00
wukko
a6ddceb643 web/settings: add advanced & debug pages 2024-07-10 23:35:53 +06:00
wukko
49f9057b6b web/SettingsNavSection: make section title optional 2024-07-10 23:35:40 +06:00
wukko
2b907e5684 web/lib/settings: use default settings as base when loading from storage 2024-07-10 23:29:47 +06:00
wukko
bc63b0c6b7 web/lib/device: fix ipad recognition 2024-07-10 23:28:23 +06:00
dumbmoron
d1767c550c version.json: refactor, don't use error(), use cf pages env if available 2024-07-10 16:23:35 +00:00
dumbmoron
a5d87edeca version.json: correct parsing for https clones 2024-07-10 16:14:54 +00:00
dumbmoron
23bcd6076a web: add prerendered version.json endpoint for frontend metadata 2024-07-10 16:04:00 +00:00
wukko
b92579ea2c web/LanguageDropdown: yet another fix for chrome on windows 2024-07-10 21:54:04 +06:00
wukko
3a531713d0 web/SidebarTab: make the button squishy 2024-07-10 21:46:14 +06:00
wukko
f498ea65b0 web/i18n/settings: improve reduce motion description 2024-07-10 20:21:41 +06:00
wukko
6c2d147bc6 web/settings: clean up the mobile header 2024-07-10 20:19:46 +06:00
wukko
e52340f33a web/settings: improve subtext visibility 2024-07-10 20:19:05 +06:00
wukko
ceabce864f web/i18n/settings: remove "preferred" from titles 2024-07-10 19:37:49 +06:00
wukko
c013134b70 web/settings: move switcher description to correct component 2024-07-10 19:35:23 +06:00
wukko
d8420116dc web/LanguageDropdown: fix option style in chrome on windows 2024-07-10 18:42:00 +06:00
wukko
496d440e5b web/settings: refresh the locale state when auto mode is toggled 2024-07-09 21:41:53 +06:00
wukko
82ac838655 web: use credentials for manifest.json 2024-07-09 21:16:40 +06:00
wukko
19a0b00853 web/i18n: add fallback locale 2024-07-09 17:40:45 +06:00
wukko
1bf0e6707b web/settings/appearance: rearrange sections 2024-07-08 19:47:59 +06:00
wukko
cbc1febab2 web/settings: disable the language dropdown when auto 2024-07-08 19:46:20 +06:00
wukko
bd2bdf326f web/Omnibox: handle enter key press 2024-07-08 19:29:30 +06:00
wukko
05044922d5 web/LanguageDropdown: fix current selection string 2024-07-08 19:24:40 +06:00
wukko
6570d163e9 web/SidebarTab: indicate that tab is selected in aria 2024-07-08 12:58:21 +06:00
wukko
862366b5c5 web/LanguageDropdown: fix missing text in firefox & small font size in safari 2024-07-08 12:49:27 +06:00
wukko
bad7e3307d web/LanguageDropdown: proper component style
you can't toggle the "select" element programmatically, so i had to come up with a workaround. it works and looks beautifully!

also fixed buggy overflow in SettingsToggle component.
2024-07-08 00:18:25 +06:00
wukko
35a8628cc1 web/SettingsToggle: change aria role to switch 2024-07-07 22:45:35 +06:00
dumbmoron
da1a11b5ce svelte: don't use relative paths for bundle links in html
this prevents a blank page from showing up when a user
visits a non-existing page on a static build
2024-07-29 10:13:45 +00:00
wukko
d22230b1d5 web/settings: highlight the setting when linked to
- remade the way padding in settings is done to accommodate space for a highlight
- renamed nav components to indicate better what they are
2024-07-07 21:51:46 +06:00
wukko
430bfaca43 web/settings: add section ids 2024-07-07 19:14:49 +06:00
wukko
9b3f289b0e web/lib/api: don't follow redirects away from api 2024-07-07 18:52:06 +06:00
dumbmoron
a6a51b850a web/chore: tabs to spaces
idk how this happened :-3
2024-07-04 22:27:38 +00:00
dumbmoron
9ae0473f80 web/sidebar: simplify settings link logic 2024-07-04 22:25:47 +00:00
dumbmoron
157b687ab5 web/settings: redirect to full page if base page is opened on desktop 2024-07-04 22:25:22 +00:00
dumbmoron
16c76e7e92 web/settings: redirect invalid settings paths to default settings page 2024-07-04 22:18:02 +00:00
dumbmoron
e98f76c8ee web/build: merge i18n chunks for each language into one file 2024-07-04 22:15:15 +00:00
wukko
422b907703 web/i18n/settings: update saving.ask.description 2024-07-04 19:09:02 +06:00
dumbmoron
8fd2c66441 web/i18n: dynamically determine languages from i18n folder contents 2024-07-03 19:28:44 +00:00
wukko
3e9296ac1e web: remove legacy global navigation shortcuts 2024-07-04 00:12:30 +06:00
wukko
8b801bad50 web/save: keyboard shortcut for muted mode 2024-07-04 00:03:46 +06:00
wukko
97d381e993 web: move all strings to i18n & improve a11y
- omnibox is now fully usable with a screen reader
- back button is now interpreted as such
- subtext now accepts line breaks
2024-07-03 23:54:44 +06:00
dumbmoron
70339b7ae9 web: handle global keyboard shortcuts 2024-07-03 17:51:01 +00:00
dumbmoron
743338ea4c web/omnibox: add keyboard shortcuts support
- shift+d to paste
    - ⌘/ctrl+v to paste
    - shift+k for auto mode
    - shift+l for audio mode
    - esc to clear input

todo:
    - shortcut for "muted" mode
2024-07-03 17:42:34 +00:00
dumbmoron
9c4a4fb5a1 web: fix sveltekit warning about body directly in <body> 2024-07-03 17:06:27 +00:00
dumbmoron
d0f78eda53 manifest: fix chrome warnings 2024-07-03 17:05:42 +00:00
wukko
374611553b web: add notch easter egg & optimize for landscape
it took way too much time to optimize the damn logo sticker under notch for all devices & zoom states

also improved device lib api
2024-07-03 19:05:14 +06:00
wukko
901f0a7480 web/settings: more accessibility improvements 2024-07-03 17:10:53 +06:00
wukko
a478993599 web: improve screen reader usability
- switchers now have audible states
- toggles are now interpreted as toggles
- fixed weird spacing introduced in last commit
2024-07-03 14:09:09 +06:00
wukko
5ced7b5388 web/save: move strings to i18n & translate to ru
also fixed line break in switcher for future lengthier translations (german, for example)
2024-07-03 13:52:27 +06:00
wukko
9939f3b172 web: i18n system & navbar translations
dynamic page language and language dropdown!! finally!!
2024-07-03 00:16:03 +06:00
wukko
d11874e57f web/layout: update input border color for light theme 2024-07-02 19:25:37 +06:00
wukko
567cfe05ec web/settings: unfuck tab padding on mobile 2024-06-30 15:58:40 +06:00
wukko
7dd33d1341 web/layout: move main bg coloring to #cobalt 2024-06-29 23:46:28 +06:00
wukko
3527131cd7 web/settings: calculate item padding properly 2024-06-29 23:31:40 +06:00
wukko
a1913988d7 web/settings: adjust padding for switcher & toggle 2024-06-29 23:02:10 +06:00
wukko
0c33ac3a1c web/SettingsToggle: clean up 2024-06-29 22:53:09 +06:00
wukko
ad6539e3bd web/settings: replace checkbox with toggle
- equal font size & padding for all subtexts in settings
- equal padding & border radius for all settings components

it just looks way better now
2024-06-29 22:51:24 +06:00
wukko
c7befcb100 web/Switcher: new style & clean up 2024-06-29 21:19:35 +06:00
wukko
f383f5d94e web/theme: add dynamic status bar color on mobile 2024-06-29 20:24:51 +06:00
wukko
d817888838 web/device: add global constant for device info 2024-06-29 20:24:14 +06:00
wukko
10a9c955d9 web: proper theming 2024-06-29 20:09:17 +06:00
wukko
2a1344f93d web: update meowbalt smile asset 2024-06-28 21:57:57 +06:00
wukko
b2652f29ac web/Omnibox: download right after pasting 2024-06-25 22:52:17 +06:00
wukko
d008bffc08 web/DownloadButton: open share sheet on ios 2024-06-25 22:25:29 +06:00
wukko
98b0a2f10a web/SettingsCheckbox: remove yassing 2024-06-25 21:06:07 +06:00
wukko
635561394c web: add dynamic page titles 2024-06-25 21:01:08 +06:00
wukko
7b289bfb16 web: mobile improvements
- all buttons now reflect that they're pressed or hovered
- settings feel way better on mobile
- settings header has been completely remade
2024-06-25 20:59:25 +06:00
wukko
49e2df425d web: remove future feature placeholders 2024-06-25 19:41:38 +06:00
wukko
1f88a211aa web/SettingsCheckbox: proper checkbox style 2024-06-25 19:34:28 +06:00
wukko
ba2d0bb67f web: fix app height & overscroll 2024-06-25 16:14:54 +06:00
wukko
19661f2f72 web/save: fix overflow 2024-06-25 15:54:33 +06:00
wukko
352b0eae59 web/SettingsTab: fix overflow & chevron scaling 2024-06-25 15:44:06 +06:00
wukko
2512c4c6be web: preload entire code 2024-06-25 15:32:36 +06:00
wukko
44f17e71bc web/settings: update placeholder 2024-06-25 14:54:46 +06:00
wukko
55515f0fb1 web/settings: mobile layout, better padding & borders 2024-06-25 14:50:59 +06:00
wukko
6fdc63a6c2 web/SettingsTab: fix border radius & padding 2024-06-25 13:07:43 +06:00
wukko
5b57c7601d web/Sidebar: don't center the scrollable list 2024-06-25 00:31:16 +06:00
wukko
2c63d431d5 web/Sidebar: dynamic settings tab link based on device type 2024-06-25 00:12:23 +06:00
wukko
dd1f9b512f web/settings: change the layout on mobile screen 2024-06-25 00:11:04 +06:00
wukko
f8ade2bf08 web/Omnibox: don't show focus stroke in link bar 2024-06-24 23:48:37 +06:00
wukko
56081db857 web: move svg icon params to css & clean up 2024-06-24 23:46:37 +06:00
wukko
b153c06294 web/SettingsTab: clean up 2024-06-24 23:22:30 +06:00
wukko
23911cbc92 web: global focus-visible 2024-06-24 23:22:19 +06:00
wukko
042d2e9cc8 web: settings ui & const for settings type options 2024-06-24 23:05:51 +06:00
wukko
0064bda4ed web: proper text styling & semantics 2024-06-24 20:26:45 +06:00
wukko
a226f0635f web: use an alias for components folder 2024-06-24 20:23:55 +06:00
wukko
530edee0b1 web/settings: update main page placeholder 2024-06-24 19:44:06 +06:00
wukko
a12655a834 web/settings: navigation draft
also unified "active" class/state across all components & added more colors
2024-06-24 19:42:31 +06:00
wukko
0372e8df47 web/lock: add engine requirements 2024-06-24 15:47:40 +06:00
wukko
e305c99b94 web/sidebar: highlight the category tab even on subpages 2024-06-24 15:47:20 +06:00
wukko
eb12fa631b web: update favicon to be more rounded 2024-06-24 14:04:24 +06:00
wukko
7e39bd78d7 web/settings: fix setting value name 2024-06-20 19:19:57 +06:00
wukko
b9e7661b6d web: basic settings page needed for testing
typescript cries about types but i don't care at this point
2024-06-20 18:05:17 +06:00
wukko
f2e74b681b web/sidebar: align tabbar to center on mobile 2024-06-20 13:46:01 +06:00
wukko
4564f409aa web/types/settings: add missing 480p video quality 2024-06-19 23:42:52 +06:00
wukko
3b2178fd1a web/api: full api request with user preferences 2024-06-19 23:29:26 +06:00
wukko
00cdb2121d web: data-driven switcher & save mode switcher
also:
- disabled ssr to enable localstorage
- removed the workaround for hover, as it looks bad
2024-06-19 23:04:09 +06:00
wukko
0ce73e03d3 web/package: update required node version to 20.9 2024-06-19 21:30:56 +06:00
wukko
1cac70f795 web/package: lowball engine requirements 2024-06-19 21:26:13 +06:00
wukko
b15b108fa9 web/package: add min engine versions 2024-06-19 21:20:18 +06:00
wukko
009a2cc863 web: implement settings core
this was a torture
2024-06-19 21:12:51 +06:00
wukko
21e03a407c web: add eslint 2024-06-19 17:55:06 +06:00
wukko
068af6a965 web/types/api: add trailing commas 2024-06-19 15:28:36 +06:00
wukko
8ec4a528ef web/save: fix terms note padding on mobile 2024-06-17 19:41:45 +06:00
wukko
838cc508de web/save: reduce meowbalt padding 2024-06-17 19:10:10 +06:00
wukko
ddb52cfef7 web/save: dynamic paste text & component clean up 2024-06-17 19:03:26 +06:00
wukko
9aa2de9bfd web/save: scale terms note on mobile screen 2024-06-17 18:52:18 +06:00
wukko
b97fd24bba web: improve button text legibility 2024-06-17 18:46:52 +06:00
wukko
eaf63fdd45 web: reduced omnibox & button sizes 2024-06-17 18:46:21 +06:00
wukko
f2bacc703a web/omnibox: import only one tabler icon 2024-06-17 01:18:39 +06:00
wukko
5390415aa7 web: use hover effects only when supported 2024-06-17 01:12:59 +06:00
wukko
95aeec3380 web: tab bar pagination effect & smooth scroll 2024-06-17 01:00:18 +06:00
wukko
2ea3ca1a07 web/sidebar: automatically scroll to active tab 2024-06-17 00:31:07 +06:00
wukko
65c14d41fa web: make tab focus blue for better visibility 2024-06-16 23:30:10 +06:00
wukko
ea830974b6 web: fix DownloadButton tab focus glow 2024-06-16 23:06:30 +06:00
wukko
5ba3231a1e web: consistent tab bar style with rounded corners 2024-06-16 22:59:16 +06:00
wukko
7679b84b2e web/sidebar: optimize tab bar for mobile 2024-06-16 22:26:06 +06:00
wukko
3fc7b99d05 web: add manifest, more icons, and some metadata 2024-06-16 22:00:26 +06:00
wukko
66a1e9e953 web/omnibox: prevent password manager autofill 2024-06-16 21:54:02 +06:00
wukko
f8f248f399 web: dark theme & coloring, border, focus fixes 2024-06-16 21:45:24 +06:00
wukko
2080a3e1ae web/sidebar: fix grid on mobile 2024-06-16 20:39:23 +06:00
wukko
72ac4c8f5a web/placeholder: more padding 2024-06-16 20:34:24 +06:00
wukko
382c6e1cd8 web: reusable meowbalt component & page placeholders 2024-06-16 20:32:09 +06:00
wukko
597320cb17 web: fix content padding 2024-06-16 20:15:17 +06:00
wukko
598ffc52b6 web/sidebar: fix scrolling one more time 2024-06-16 20:15:09 +06:00
wukko
1325c3516c web: move border radius into a variable 2024-06-16 19:51:02 +06:00
wukko
3a57c7165f web/sidebar: scroll only in one direction on overflow 2024-06-16 19:50:42 +06:00
wukko
f4485e2af0 web/html: update viewport rules 2024-06-16 19:46:15 +06:00
wukko
2549699a88 web/layout: hide all scrollbars 2024-06-16 19:25:30 +06:00
wukko
1fad4816b2 web: use static svelte adapter instead of auto 2024-06-16 19:21:26 +06:00
wukko
3c1a69063d web/sidebar: disable scrollbars 2024-06-16 19:11:44 +06:00
wukko
1c9d604326 web/sidebar: import individual files for icons 2024-06-16 19:10:58 +06:00
wukko
3554222f42 web: add api response types & clean up DownloadButton 2024-06-16 18:53:45 +06:00
wukko
1f2c28bd02 web: basic api interaction & downloading
download button now acts the way it should with various states
2024-06-16 18:22:44 +06:00
wukko
324729eb21 web: basic switcher component & mute mode button 2024-06-16 15:30:14 +06:00
wukko
bf26988cde web/save: add paste button & dummy mode buttons
tuned default button look, moved custom icons to lib for easy access
2024-06-15 20:39:34 +06:00
wukko
e6ffa4864c web: omnibox base with meowbalt 2024-06-14 21:48:57 +06:00
wukko
7cab37fc30 web: disable tap highlighting & user selection 2024-06-14 17:34:14 +06:00
wukko
92cccd720d web: mobile navigation 2024-06-14 17:33:33 +06:00
wukko
5399ee9a4c web: make sidebar scrollable on vertical overflow 2024-06-14 16:47:13 +06:00
wukko
b831dc8236 web: space out css 2024-06-14 16:38:10 +06:00
wukko
38d7add0a9 web: navigation & sidebar 2024-06-14 16:33:01 +06:00
wukko
fa85a4c75c readme: update license info 2024-07-29 15:29:13 +06:00
wukko
c5c0d44a2e web: add license 2024-07-29 15:26:04 +06:00
wukko
8cc11367ef web: project skeleton 2024-06-13 15:32:17 +06:00
427 changed files with 21157 additions and 8560 deletions

21
.dockerignore Normal file
View File

@@ -0,0 +1,21 @@
# OS directory info files
.DS_Store
desktop.ini
# node
node_modules
# static build
build
# secrets
.env
.env.*
!.env.example
cookies.json
# docker
docker-compose.yml
# ide
.vscode

View File

@@ -7,7 +7,7 @@ body:
value: |
thanks for taking the time to make a feature request!
before you start, please make to read the "adding features or support for services" section of
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/current/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
- type: textarea
id: feat-description
attributes:

View File

@@ -8,7 +8,7 @@ body:
value: |
thanks for taking the time to make a service request!
before you start, please make to read the "adding features or support for services" section of
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/current/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
our [contributor guidelines](https://github.com/imputnet/cobalt/blob/main/CONTRIBUTING.md#adding-features-or-support-for-services) to make sure your request is a good fit for cobalt.
- type: input
id: service-name
attributes:

38
.github/test.sh vendored
View File

@@ -13,19 +13,20 @@ waitport() {
test_api() {
waitport 3000
curl -m 3 http://localhost:3000/api/serverInfo
API_RESPONSE=$(curl -m 3 http://localhost:3000/api/json \
curl -m 3 http://localhost:3000/
API_RESPONSE=$(curl -m 10 http://localhost:3000/ \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{"url":"https://vine.co/v/huwVJIEJW50", "isAudioOnly": true}')
-d '{"url":"https://www.tiktok.com/@fatfatmillycat/video/7195741644585454894"}')
echo "$API_RESPONSE"
echo "API_RESPONSE=$API_RESPONSE"
STATUS=$(echo "$API_RESPONSE" | jq -r .status)
STREAM_URL=$(echo "$API_RESPONSE" | jq -r .url)
[ "$STATUS" = stream ] || exit 1;
[ "$STATUS" = tunnel ] || exit 1;
S=$(curl -I -m 10 "$STREAM_URL")
CONTENT_LENGTH=$(curl -I -m 3 "$STREAM_URL" \
CONTENT_LENGTH=$(echo "$S" \
| grep -i content-length \
| cut -d' ' -f2 \
| tr -d '\r')
@@ -37,37 +38,30 @@ test_api() {
fi
}
test_web() {
waitport 3001
curl -m 3 http://127.0.0.1:3001/onDemand?blockId=0 \
| grep -q '"status":"success"'
}
setup_api() {
export API_PORT=3000
export API_URL=http://localhost:3000
timeout 10 npm run start
timeout 10 pnpm run --prefix api start &
API_PID=$!
}
setup_web() {
export WEB_PORT=3001
export WEB_URL=http://localhost:3001
export API_URL=http://localhost:3000
timeout 5 npm run start
pnpm run --prefix web build
}
cd "$(git rev-parse --show-toplevel)"
npm i
pnpm install --frozen-lockfile
if [ "$1" = "api" ]; then
setup_api &
setup_api
test_api
[ "$API_PID" != "" ] \
&& kill "$API_PID"
elif [ "$1" = "web" ]; then
setup_web &
test_web
setup_web
else
echo "usage: $0 <api/web>" >&2
exit 1
fi
wait || exit $?
wait || exit $?

View File

@@ -32,7 +32,7 @@ jobs:
- name: Get release metadata
id: release-meta
run: |
version=$(cat package.json | jq -r .version)
version=$(cat api/package.json | jq -r .version)
echo "commit_short=$(git rev-parse --short HEAD)" >> $GITHUB_OUTPUT
echo "version=$version" >> $GITHUB_OUTPUT
echo "major_version=$(echo "$version" | cut -d. -f1)" >> $GITHUB_OUTPUT

33
.github/workflows/test-services.yml vendored Normal file
View File

@@ -0,0 +1,33 @@
name: Run service tests
on:
pull_request:
push:
paths:
- api/**
- packages/**
jobs:
check-services:
name: test service functionality
runs-on: ubuntu-latest
outputs:
services: ${{ steps.checkServices.outputs.service_list }}
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- id: checkServices
run: pnpm i --frozen-lockfile && echo "service_list=$(node api/src/util/test-ci get-services)" >> "$GITHUB_OUTPUT"
test-services:
needs: check-services
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: ${{ fromJson(needs.check-services.outputs.services) }}
name: "test service: ${{ matrix.service }}"
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- run: pnpm i --frozen-lockfile && node api/src/util/test-ci run-tests-for ${{ matrix.service }}

View File

@@ -3,60 +3,32 @@ name: Run tests
on:
pull_request:
push:
branches: [ current ]
jobs:
check-lockfile:
name: check lockfile correctness
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- name: Check that lockfile does not need an update
run: |
cp package-lock.json before.json
npm ci
npm i --package-lock-only
diff before.json package-lock.json
run: pnpm install --frozen-lockfile
test-web:
name: web sanity check
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run test script
run: .github/test.sh web
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 'lts/*'
- uses: pnpm/action-setup@v4
- run: .github/test.sh web
test-api:
name: api sanity check
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Run test script
run: .github/test.sh api
check-services:
name: test service functionality
runs-on: ubuntu-latest
outputs:
services: ${{ steps.checkServices.outputs.service_list }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- id: checkServices
run: npm ci && echo "service_list=$(node src/util/test-ci get-services)" >> "$GITHUB_OUTPUT"
test-services:
needs: check-services
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
service: ${{ fromJson(needs.check-services.outputs.services) }}
name: "test service: ${{ matrix.service }}"
steps:
- name: Checkout repository
uses: actions/checkout@v4
- run: npm ci && node src/util/test-ci run-tests-for ${{ matrix.service }}
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- run: .github/test.sh api

18
.gitignore vendored
View File

@@ -1,21 +1,21 @@
# os stuff
# OS directory info files
.DS_Store
desktop.ini
# npm
# node
node_modules
# static build
build
# secrets
.env
.env.*
!.env.example
cookies.json
# docker
docker-compose.yml
# vscode
# ide
.vscode
# cookie file
cookies.json
# page build
build

View File

@@ -1,15 +1,25 @@
FROM node:18-bullseye-slim
FROM node:20-bullseye-slim AS base
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
FROM base AS build
WORKDIR /app
COPY . /app
RUN corepack enable
RUN apt-get update && \
apt-get install -y python3 build-essential
RUN --mount=type=cache,id=pnpm,target=/pnpm/store \
pnpm install --prod --frozen-lockfile
RUN pnpm deploy --filter=@imput/cobalt-api --prod /prod/api
FROM base AS api
WORKDIR /app
COPY package*.json ./
COPY --from=build /prod/api /app
COPY --from=build /app/.git /app/.git
RUN apt-get update && \
apt-get install -y git python3 build-essential && \
npm ci && \
npm cache clean --force && \
apt purge --autoremove -y python3 build-essential && \
rm -rf ~/.cache/ /var/lib/apt/lists/*
COPY . .
EXPOSE 9000
CMD [ "node", "src/cobalt" ]
CMD [ "node", "src/cobalt" ]

122
README.md
View File

@@ -1,41 +1,56 @@
# cobalt
best way to save what you love: [cobalt.tools](https://cobalt.tools/)
<div align="center">
<br/>
<p>
<img src="web/static/favicon.png" title="cobalt" alt="cobalt logo" width="100" />
</p>
<p>
best way to save what you love
<br/>
<a href="https://cobalt.tools">
cobalt.tools
</a>
</p>
<p>
<a href="https://discord.gg/pQPt8HBUPu">
💬 community discord server
</a>
<a href="https://x.com/justusecobalt">
🐦 twitter/x
</a>
</p>
<br/>
</div>
![cobalt logo with repeated logo (double arrow) pattern background](/src/front/icons/pattern.png "cobalt logo with repeated logo (double arrow) pattern background")
[💬 community discord server](https://discord.gg/pQPt8HBUPu)
[🐦 twitter/x](https://x.com/justusecobalt)
## what's cobalt?
cobalt is a media downloader that doesn't piss you off. it's fast, friendly, and doesn't have any bullshit that modern web is filled with: ***no ads, trackers, or invasive analytics***.
cobalt is a media downloader that doesn't piss you off. it's fast, friendly, and doesn't have any bullshit that modern web is filled with: ***no ads, trackers, or paywalls***.
paste the link, get the file, move on. it's that simple. just how it should be.
## supported services
### supported services
this list is not final and keeps expanding over time. if support for a service you want is missing, create an issue (or a pull request 👀).
| service | video + audio | only audio | only video | metadata | rich file names |
| :-------- | :-----------: | :--------: | :--------: | :------: | :-------------: |
| bilibili.com & bilibili.tv | ✅ | ✅ | ✅ | | |
| dailymotion | ✅ | ✅ | ✅ | | |
| instagram posts & reels | ✅ | ✅ | ✅ | | |
| facebook videos | ✅ | | | | |
| loom | ✅ | ❌ | ✅ | | |
| ok video | ✅ | ❌ | ✅ | ✅ | |
| pinterest | | ✅ | ✅ | | |
| reddit | ✅ | ✅ | ✅ | | |
| rutube | ✅ | ✅ | ✅ | | |
| snapchat stories & spotlights | ✅ | ✅ | ✅ | | |
| soundcloud | | ✅ | | ✅ | ✅ |
| streamable | ✅ | | ✅ | | |
| tiktok | ✅ | ✅ | ✅ | | |
| tumblr | ✅ | ✅ | ✅ | | |
| twitch clips | ✅ | ✅ | ✅ | | |
| twitter/x | ✅ | ✅ | ✅ | | |
| vimeo | ✅ | ✅ | ✅ | | |
| vine archive | ✅ | ✅ | ✅ | | |
| vk videos & clips | ✅ | ❌ | ✅ | ✅ | |
| youtube videos, shorts & music | ✅ | | ✅ | ✅ | ✅ |
| service | video + audio | only audio | only video | metadata | rich file names |
| :-------- | :-----------: | :--------: | :--------: | :------: | :-------------: |
| bilibili | ✅ | ✅ | ✅ | | |
| bluesky | ✅ | ✅ | ✅ | | |
| dailymotion | ✅ | ✅ | ✅ | | |
| instagram | ✅ | | | | |
| facebook | ✅ | ❌ | ✅ | | |
| loom | ✅ | ❌ | ✅ | ✅ | |
| ok.ru | ✅ | | ✅ | ✅ | |
| pinterest | ✅ | ✅ | ✅ | | |
| reddit | ✅ | ✅ | ✅ | | |
| rutube | ✅ | ✅ | ✅ | | |
| snapchat | ✅ | | ✅ | | |
| soundcloud | | ✅ | | ✅ | |
| streamable | ✅ | ✅ | ✅ | | |
| tiktok | ✅ | ✅ | ✅ | | |
| tumblr | ✅ | ✅ | ✅ | | |
| twitch clips | ✅ | ✅ | ✅ | | |
| twitter/x | ✅ | ✅ | ✅ | | |
| vimeo | ✅ | ✅ | ✅ | | |
| vine | ✅ | ✅ | ✅ | | |
| vk videos & clips | ✅ | | ✅ | ✅ | ✅ |
| youtube | ✅ | ✅ | ✅ | ✅ | ✅ |
| emoji | meaning |
| :-----: | :---------------------- |
@@ -58,46 +73,17 @@ this list is not final and keeps expanding over time. if support for a service y
| vimeo | audio downloads are only available for dash. |
| youtube | supports videos, music, and shorts. 8K, 4K, HDR, VR, and high FPS videos. rich metadata & dubs. h264/av1/vp9 codecs. |
## cobalt api
cobalt has an open api that you can use in your projects *for free~*. it's easy and straightforward to use, [check out the docs](/docs/api.md) to learn how to use it.
### partners
cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt), all main instances are currently hosted on their network :)
✅ you can use the main api instance ([api.cobalt.tools](https://api.cobalt.tools/)) in your **personal** projects.
❌ you cannot use the free api commercially (anywhere that's gated behind paywalls or ads). host your own instance for this.
we reserve the right to restrict abusive/excessive access to the main instance api.
## how to run your own instance
if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
it's *highly* recommended to use a docker compose method unless you run for developing/debugging purposes.
## partners
cobalt is sponsored by [royalehosting.net](https://royalehosting.net/?partner=cobalt), all main instances are currently hosted on their network :)
## ethics and disclaimer
### ethics and disclaimer
cobalt is a tool for easing content downloads from internet and takes ***zero liability***. you are responsible for what you download, how you use and distribute that content. please be mindful when using content of others and always credit original creators. fair use and credits benefit everyone.
cobalt is ***NOT*** a piracy tool and cannot be used as such. it can only download free, publicly accessible content. such content can be easily downloaded through any browser's dev tools. pressing one button is easier, so i made a convenient, ad-less tool for such repeated actions.
## cobalt license
cobalt code is licensed under [AGPL-3.0](/LICENSE).
cobalt branding, mascots, and other related assets included in the repo are ***copyrighted*** and not covered by the AGPL-3.0 license. you ***cannot*** use them under same terms.
you are allowed to host an ***unmodified*** instance of cobalt with branding, but this ***does not*** give you permission to use it anywhere else, or make derivatives of it in any way.
### notes:
- mascots and other assets are a part of the branding.
- when making an alternative version of the project, please replace or remove all branding (including the name).
- you **must** link the original repo when using any parts of code (such as using separate processing modules in your project) or forking the project.
- if you make a modified version of cobalt, the codebase **must** be published under the same license (according to AGPL-3.0).
## 3rd party licenses
- [Fluent Emoji by Microsoft](https://github.com/microsoft/fluentui-emoji) (used in cobalt) is under [MIT](https://github.com/microsoft/fluentui-emoji/blob/main/LICENSE) license.
- [Noto Sans Mono](https://fonts.google.com/noto/specimen/Noto+Sans+Mono/) fonts (used in cobalt) are licensed under the [OFL](https://fonts.google.com/noto/specimen/Noto+Sans+Mono/about) license.
- many update banners were taken from [tenor.com](https://tenor.com/).
### cobalt license
for relevant licensing information, see the [api](api/README.md) and [web](web/README.md) READMEs.
unless specified otherwise, the remainder of this repository is licensed under [AGPL-3.0](LICENSE).
## acknowledgements
### ffmpeg
@@ -111,7 +97,7 @@ we use [ffmpeg-static](https://github.com/eugeneware/ffmpeg-static) to get binar
you can support the developer via various methods listed on their github page! (linked above)
### youtube.js
cobalt relies on [youtube.js](https://github.com/LuanRT/YouTube.js) for interacting with the innertube api, it wouldn't have been possible without it.
cobalt relies on [youtube.js](https://github.com/LuanRT/YouTube.js) for interacting with the innertube api, it wouldn't have been possible without it.
you can support the developer via various methods listed on their github page! (linked above)

661
api/LICENSE Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
save what you love with cobalt.
Copyright (C) 2024 imput
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

22
api/README.md Normal file
View File

@@ -0,0 +1,22 @@
# cobalt api
## license
cobalt api code is licensed under [AGPL-3.0](LICENSE).
this license allows you to modify, distribute and use the code for any purpose
as long as you:
- give appropriate credit to the original repo when using or modifying any parts of the code,
- provide a link to the license and indicate if changes to the code were made, and
- release the code under the **same license**
## running your own instance
if you want to run your own instance for whatever purpose, [follow this guide](/docs/run-an-instance.md).
it's *highly* recommended to use a docker compose method unless you run for developing/debugging purposes.
## accessing the api
currently, there is no publicly accessible main api. we plan on providing a public api for
cobalt 10 in some form in the future. we recommend deploying your own instance if you wish
to use the latest api. you can access [the documentation](/docs/api.md) for it here.
if you are looking for the documentation for the old (7.x) api, you can find
it [here](https://github.com/imputnet/cobalt/blob/7/docs/api.md)

49
api/package.json Normal file
View File

@@ -0,0 +1,49 @@
{
"name": "@imput/cobalt-api",
"description": "save what you love",
"version": "10.0.0",
"author": "imput",
"exports": "./src/cobalt.js",
"type": "module",
"engines": {
"node": ">=18"
},
"scripts": {
"start": "node src/cobalt",
"setup": "node src/util/setup",
"test": "node src/util/test",
"token:youtube": "node src/util/generate-youtube-tokens"
},
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme",
"dependencies": {
"@imput/version-info": "workspace:^",
"content-disposition-header": "0.6.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"esbuild": "^0.14.51",
"express": "^4.18.1",
"express-rate-limit": "^6.3.0",
"ffmpeg-static": "^5.1.0",
"hls-parser": "^0.10.7",
"ipaddr.js": "2.1.0",
"nanoid": "^4.0.2",
"node-cache": "^5.1.2",
"psl": "1.9.0",
"set-cookie-parser": "2.6.0",
"undici": "^5.19.1",
"url-pattern": "1.0.3",
"youtubei.js": "^10.3.0",
"zod": "^3.23.8"
},
"optionalDependencies": {
"freebind": "^0.2.2"
}
}

27
api/src/cobalt.js Normal file
View File

@@ -0,0 +1,27 @@
import "dotenv/config";
import express from "express";
import path from 'path';
import { fileURLToPath } from 'url';
import { env } from "./config.js"
import { Bright, Green, Red } from "./misc/console-text.js";
const app = express();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4);
app.disable('x-powered-by');
if (env.apiURL) {
const { runAPI } = await import('./core/api.js');
runAPI(express, app, __dirname)
} else {
console.log(
Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
+ Bright(`please run the setup script to fix this: `)
+ Green(`npm run setup`)
)
}

51
api/src/config.js Normal file
View File

@@ -0,0 +1,51 @@
import { getVersion } from "@imput/version-info";
import { services } from "./processing/service-config.js";
const version = await getVersion();
const disabledServices = process.env.DISABLED_SERVICES?.split(',') || [];
const enabledServices = new Set(Object.keys(services).filter(e => {
if (!disabledServices.includes(e)) {
return e;
}
}));
const env = {
apiURL: process.env.API_URL || '',
apiPort: process.env.API_PORT || 9000,
listenAddress: process.env.API_LISTEN_ADDRESS,
freebindCIDR: process.platform === 'linux' && process.env.FREEBIND_CIDR,
corsWildcard: process.env.CORS_WILDCARD !== '0',
corsURL: process.env.CORS_URL,
cookiePath: process.env.COOKIE_PATH,
rateLimitWindow: (process.env.RATELIMIT_WINDOW && parseInt(process.env.RATELIMIT_WINDOW)) || 60,
rateLimitMax: (process.env.RATELIMIT_MAX && parseInt(process.env.RATELIMIT_MAX)) || 20,
durationLimit: (process.env.DURATION_LIMIT && parseInt(process.env.DURATION_LIMIT)) || 10800,
streamLifespan: 90,
processingPriority: process.platform !== 'win32'
&& process.env.PROCESSING_PRIORITY
&& parseInt(process.env.PROCESSING_PRIORITY),
externalProxy: process.env.API_EXTERNAL_PROXY,
turnstileSecret: process.env.TURNSTILE_SECRET,
jwtSecret: process.env.JWT_SECRET,
jwtLifetime: process.env.JWT_EXPIRY || 120,
enabledServices,
}
const genericUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36";
const cobaltUserAgent = `cobalt/${version} (+https://github.com/imputnet/cobalt)`;
export {
env,
genericUserAgent,
cobaltUserAgent,
}

326
api/src/core/api.js Normal file
View File

@@ -0,0 +1,326 @@
import cors from "cors";
import rateLimit from "express-rate-limit";
import { setGlobalDispatcher, ProxyAgent } from "undici";
import { getCommit, getBranch, getRemote, getVersion } from "@imput/version-info";
import jwt from "../security/jwt.js";
import stream from "../stream/stream.js";
import match from "../processing/match.js";
import { env } from "../config.js";
import { extract } from "../processing/url.js";
import { languageCode } from "../misc/utils.js";
import { Bright, Cyan } from "../misc/console-text.js";
import { generateHmac, generateSalt } from "../misc/crypto.js";
import { randomizeCiphers } from "../misc/randomize-ciphers.js";
import { verifyTurnstileToken } from "../security/turnstile.js";
import { friendlyServiceName } from "../processing/service-alias.js";
import { verifyStream, getInternalStream } from "../stream/manage.js";
import { createResponse, normalizeRequest, getIP } from "../processing/request.js";
const git = {
branch: await getBranch(),
commit: await getCommit(),
remote: await getRemote(),
}
const version = await getVersion();
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
const ipSalt = generateSalt();
const corsConfig = env.corsWildcard ? {} : {
origin: env.corsURL,
optionsSuccessStatus: 200
}
const fail = (res, code, context) => {
const { status, body } = createResponse("error", { code, context });
res.status(status).json(body);
}
export const runAPI = (express, app, __dirname) => {
const startTime = new Date();
const startTimestamp = startTime.getTime();
const serverInfo = JSON.stringify({
cobalt: {
version: version,
url: env.apiURL,
startTime: `${startTimestamp}`,
durationLimit: env.durationLimit,
services: [...env.enabledServices].map(e => {
return friendlyServiceName(e);
}),
},
git,
})
const apiLimiter = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => {
if (req.authorized) {
return generateHmac(req.header("Authorization"), ipSalt);
}
return generateHmac(getIP(req), ipSalt);
},
handler: (req, res) => {
const { status, body } = createResponse("error", {
code: "error.api.rate_exceeded",
context: {
limit: env.rateLimitWindow
}
});
return res.status(status).json(body);
}
})
const apiLimiterStream = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.sendStatus(429)
}
})
app.set('trust proxy', ['loopback', 'uniquelocal']);
app.use('/', cors({
methods: ['GET', 'POST'],
exposedHeaders: [
'Ratelimit-Limit',
'Ratelimit-Policy',
'Ratelimit-Remaining',
'Ratelimit-Reset'
],
...corsConfig,
}));
app.post('/', apiLimiter);
app.use('/tunnel', apiLimiterStream);
app.post('/', (req, res, next) => {
if (!env.turnstileSecret || !env.jwtSecret) {
return next();
}
try {
const authorization = req.header("Authorization");
if (!authorization) {
return fail(res, "error.api.auth.jwt.missing");
}
if (!authorization.startsWith("Bearer ") || authorization.length > 256) {
return fail(res, "error.api.auth.jwt.invalid");
}
const verifyJwt = jwt.verify(
authorization.split("Bearer ", 2)[1]
);
if (!verifyJwt) {
return fail(res, "error.api.auth.jwt.invalid");
}
if (!acceptRegex.test(req.header('Accept'))) {
return fail(res, "error.api.header.accept");
}
if (!acceptRegex.test(req.header('Content-Type'))) {
return fail(res, "error.api.header.content_type");
}
req.authorized = true;
} catch {
return fail(res, "error.api.generic");
}
next();
});
app.use('/', express.json({ limit: 1024 }));
app.use('/', (err, _, res, next) => {
if (err) {
const { status, body } = createResponse("error", {
code: "error.api.invalid_body",
});
return res.status(status).json(body);
}
next();
});
app.post("/session", async (req, res) => {
if (!env.turnstileSecret || !env.jwtSecret) {
return fail(res, "error.api.auth.not_configured")
}
const turnstileResponse = req.header("cf-turnstile-response");
if (!turnstileResponse) {
return fail(res, "error.api.auth.turnstile.missing");
}
const turnstileResult = await verifyTurnstileToken(
turnstileResponse,
req.ip
);
if (!turnstileResult) {
return fail(res, "error.api.auth.turnstile.invalid");
}
try {
res.json(jwt.generate());
} catch {
return fail(res, "error.api.generic");
}
});
app.post('/', async (req, res) => {
const request = req.body;
const lang = languageCode(req);
if (!request.url) {
return fail(res, "error.api.link.missing");
}
if (request.youtubeDubBrowserLang) {
request.youtubeDubLang = lang;
}
const { success, data: normalizedRequest } = await normalizeRequest(request);
if (!success) {
return fail(res, "error.api.invalid_body");
}
const parsed = extract(normalizedRequest.url);
if (!parsed) {
return fail(res, "error.api.link.invalid");
}
if ("error" in parsed) {
let context;
if (parsed?.context) {
context = parsed.context;
}
return fail(res, `error.api.${parsed.error}`, context);
}
try {
const result = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: normalizedRequest,
});
res.status(result.status).json(result.body);
} catch {
fail(res, "error.api.generic");
}
})
app.get('/tunnel', (req, res) => {
const id = String(req.query.id);
const exp = String(req.query.exp);
const sig = String(req.query.sig);
const sec = String(req.query.sec);
const iv = String(req.query.iv);
const checkQueries = id && exp && sig && sec && iv;
const checkBaseLength = id.length === 21 && exp.length === 13;
const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
if (!checkQueries || !checkBaseLength || !checkSafeLength) {
return res.status(400).end();
}
if (req.query.p) {
return res.status(200).end();
}
const streamInfo = verifyStream(id, sig, exp, sec, iv);
if (!streamInfo?.service) {
return res.status(streamInfo.status).end();
}
if (streamInfo.type === 'proxy') {
streamInfo.range = req.headers['range'];
}
return stream(res, streamInfo);
})
app.get('/itunnel', (req, res) => {
if (!req.ip.endsWith('127.0.0.1')) {
return res.sendStatus(403);
}
if (String(req.query.id).length !== 21) {
return res.sendStatus(400);
}
const streamInfo = getInternalStream(req.query.id);
if (!streamInfo) {
return res.sendStatus(404);
}
streamInfo.headers = new Map([
...(streamInfo.headers || []),
...Object.entries(req.headers)
]);
return stream(res, { type: 'internal', ...streamInfo });
})
app.get('/', (_, res) => {
res.type('json');
res.status(200).send(serverInfo);
})
app.get('/favicon.ico', (req, res) => {
res.status(404).end();
})
app.get('/*', (req, res) => {
res.redirect('/');
})
// handle all express errors
app.use((_, __, res, ___) => {
return fail(res, "error.api.generic");
})
randomizeCiphers();
setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
if (env.externalProxy) {
if (env.freebindCIDR) {
throw new Error('Freebind is not available when external proxy is enabled')
}
setGlobalDispatcher(new ProxyAgent(env.externalProxy))
}
app.listen(env.apiPort, env.listenAddress, () => {
console.log(`\n` +
Bright(Cyan("cobalt ")) + Bright("API ^ω⁠^") + "\n" +
"~~~~~~\n" +
Bright("version: ") + version + "\n" +
Bright("commit: ") + git.commit + "\n" +
Bright("branch: ") + git.branch + "\n" +
Bright("remote: ") + git.remote + "\n" +
Bright("start time: ") + startTime.toUTCString() + "\n" +
"~~~~~~\n" +
Bright("url: ") + Bright(Cyan(env.apiURL)) + "\n" +
Bright("port: ") + env.apiPort + "\n"
)
})
}

View File

@@ -0,0 +1,20 @@
import * as fs from "fs";
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const root = join(
dirname(fileURLToPath(import.meta.url)),
'../../'
);
export function loadFile(path) {
return fs.readFileSync(join(root, path), 'utf-8')
}
export function loadJSON(path) {
try {
return JSON.parse(loadFile(path))
} catch {
return false
}
}

View File

@@ -1,10 +1,10 @@
import { normalizeRequest } from "../modules/processing/request.js";
import match from "./processing/match.js";
import { extract } from "./processing/url.js";
import { normalizeRequest } from "../processing/request.js";
import match from "../processing/match.js";
import { extract } from "../processing/url.js";
export async function runTest(url, params, expect) {
const normalized = normalizeRequest({ url, ...params });
if (!normalized) {
const { success, data: normalized } = await normalizeRequest({ url, ...params });
if (!success) {
throw "invalid request";
}
@@ -13,9 +13,11 @@ export async function runTest(url, params, expect) {
throw `invalid url: ${normalized.url}`;
}
const result = await match(
parsed.host, parsed.patternMatch, "en", normalized
);
const result = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: normalized,
});
let error = [];
if (expect.status !== result.body.status) {
@@ -36,7 +38,7 @@ export async function runTest(url, params, expect) {
throw error.join('\n');
}
if (result.body.status === 'stream') {
if (result.body.status === 'tunnel') {
// TODO: stream testing
}
}

View File

@@ -1,7 +1,7 @@
import Cookie from './cookie.js';
import { readFile, writeFile } from 'fs/promises';
import { parse as parseSetCookie, splitCookiesString } from 'set-cookie-parser';
import { env } from '../../../modules/config.js'
import { env } from '../../config.js';
const WRITE_INTERVAL = 60000,
cookiePath = env.cookiePath,

View File

@@ -0,0 +1,56 @@
export default (f, style, isAudioOnly, isAudioMuted) => {
let filename = '';
let infoBase = [f.service, f.id];
let classicTags = [...infoBase];
let basicTags = [];
const title = `${f.title} - ${f.author}`;
if (f.resolution) {
classicTags.push(f.resolution);
}
if (f.qualityLabel) {
basicTags.push(f.qualityLabel);
}
if (f.youtubeFormat) {
classicTags.push(f.youtubeFormat);
basicTags.push(f.youtubeFormat);
}
if (isAudioMuted) {
classicTags.push("mute");
basicTags.push("mute");
} else if (f.youtubeDubName) {
classicTags.push(f.youtubeDubName);
basicTags.push(f.youtubeDubName);
}
switch (style) {
default:
case "classic":
if (isAudioOnly) {
if (f.youtubeDubName) {
infoBase.push(f.youtubeDubName);
}
return `${infoBase.join("_")}_audio`;
}
filename = classicTags.join("_");
break;
case "basic":
if (isAudioOnly) return title;
filename = `${title} (${basicTags.join(", ")})`;
break;
case "pretty":
if (isAudioOnly) return `${title} (${infoBase[0]})`;
filename = `${title} (${[...basicTags, infoBase[0]].join(", ")})`;
break;
case "nerdy":
if (isAudioOnly) return `${title} (${infoBase.join(", ")})`;
filename = `${title} (${basicTags.concat(infoBase).join(", ")})`;
break;
}
return `${filename}.${f.extension}`;
}

View File

@@ -1,71 +1,75 @@
import { audioIgnore, services, supportedAudio } from "../config.js";
import { createResponse } from "../processing/request.js";
import loc from "../../localization/manager.js";
import createFilename from "./createFilename.js";
import createFilename from "./create-filename.js";
import { createResponse } from "./request.js";
import { audioIgnore } from "./service-config.js";
import { createStream } from "../stream/manage.js";
export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, disableMetadata, filenamePattern, toGif, requestIP) {
export default function({ r, host, audioFormat, isAudioOnly, isAudioMuted, disableMetadata, filenameStyle, twitterGif, requestIP, audioBitrate, alwaysProxy }) {
let action,
responseType = "stream",
responseType = "tunnel",
defaultParams = {
u: r.urls,
headers: r.headers,
service: host,
filename: r.filenameAttributes ?
createFilename(r.filenameAttributes, filenamePattern, isAudioOnly, isAudioMuted) : r.filename,
createFilename(r.filenameAttributes, filenameStyle, isAudioOnly, isAudioMuted) : r.filename,
fileMetadata: !disableMetadata ? r.fileMetadata : false,
requestIP
},
params = {},
audioFormat = String(userFormat);
params = {};
if (r.isPhoto) action = "photo";
else if (r.picker) action = "picker"
else if (r.isGif && toGif) action = "gif";
else if (isAudioMuted) action = "muteVideo";
else if (r.isGif && twitterGif) action = "gif";
else if (isAudioOnly) action = "audio";
else if (isAudioMuted) action = "muteVideo";
else if (r.isM3U8) action = "m3u8";
else action = "video";
if (action === "picker" || action === "audio") {
if (!r.filenameAttributes) defaultParams.filename = r.audioFilename;
defaultParams.isAudioOnly = true;
defaultParams.audioFormat = audioFormat;
}
if (isAudioMuted && !r.filenameAttributes) {
defaultParams.filename = r.filename.replace('.', '_mute.')
if (action === "muteVideo" && isAudioMuted && !r.filenameAttributes) {
const parts = r.filename.split(".");
const ext = parts.pop();
defaultParams.filename = `${parts.join(".")}_mute.${ext}`;
}
switch (action) {
default:
return createResponse("error", { t: loc(lang, 'ErrorEmptyDownload') });
return createResponse("error", {
code: "error.api.fetch.empty"
});
case "photo":
responseType = "redirect";
break;
case "gif":
params = { type: "gif" }
params = { type: "gif" };
break;
case "m3u8":
params = {
type: Array.isArray(r.urls) ? "render" : "remux"
type: Array.isArray(r.urls) ? "merge" : "remux"
}
break;
case "muteVideo":
let muteType = "mute";
if (Array.isArray(r.urls) && !r.isM3U8) {
muteType = "bridge";
muteType = "proxy";
}
params = {
type: muteType,
u: Array.isArray(r.urls) ? r.urls[0] : r.urls,
mute: true
u: Array.isArray(r.urls) ? r.urls[0] : r.urls
}
if (host === "reddit" && r.typeId === "redirect")
if (host === "reddit" && r.typeId === "redirect") {
responseType = "redirect";
}
break;
case "picker":
@@ -74,13 +78,15 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "instagram":
case "twitter":
case "snapchat":
case "bsky":
params = { picker: r.picker };
break;
case "tiktok":
let audioStreamType = "render";
if (r.bestAudio === "mp3" && (audioFormat === "mp3" || audioFormat === "best")) {
let audioStreamType = "audio";
if (r.bestAudio === "mp3" && audioFormat === "best") {
audioFormat = "mp3";
audioStreamType = "bridge"
audioStreamType = "proxy"
}
params = {
picker: r.picker,
@@ -92,27 +98,30 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
filename: r.audioFilename,
isAudioOnly: true,
audioFormat,
}),
copy: audioFormat === "best"
})
}
break;
}
break;
case "video":
switch (host) {
case "bilibili":
params = { type: "render" };
params = { type: "merge" };
break;
case "youtube":
params = { type: r.type };
break;
case "reddit":
responseType = r.typeId;
params = { type: r.type };
break;
case "vimeo":
if (Array.isArray(r.urls)) {
params = { type: "render" }
params = { type: "merge" }
} else {
responseType = "redirect";
}
@@ -128,7 +137,7 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "vk":
case "tiktok":
params = { type: "bridge" };
params = { type: "proxy" };
break;
case "facebook":
@@ -139,64 +148,63 @@ export default function(r, host, userFormat, isAudioOnly, lang, isAudioMuted, di
case "streamable":
case "snapchat":
case "loom":
case "twitch":
responseType = "redirect";
break;
}
break;
case "audio":
if (audioIgnore.includes(host)
|| (host === "reddit" && r.typeId === "redirect")) {
return createResponse("error", { t: loc(lang, 'ErrorEmptyDownload') })
if (audioIgnore.includes(host) || (host === "reddit" && r.typeId === "redirect")) {
return createResponse("error", {
code: "error.api.fetch.empty"
})
}
let processType = "render",
copy = false;
let processType = "audio";
let copy = false;
if (!supportedAudio.includes(audioFormat)) {
audioFormat = "best"
}
if (audioFormat === "best") {
const serviceBestAudio = r.bestAudio;
const serviceBestAudio = r.bestAudio || services[host]["bestAudio"];
const isBestAudio = audioFormat === "best";
const isBestOrMp3 = isBestAudio || audioFormat === "mp3";
const isBestAudioDefined = isBestAudio && serviceBestAudio;
const isBestHostAudio = serviceBestAudio && (audioFormat === serviceBestAudio);
if (serviceBestAudio) {
audioFormat = serviceBestAudio;
processType = "proxy";
const isTumblrAudio = host === "tumblr" && !r.filename;
const isSoundCloud = host === "soundcloud";
const isTiktok = host === "tiktok";
if (isBestAudioDefined || isBestHostAudio) {
audioFormat = serviceBestAudio;
processType = "bridge";
if (isSoundCloud || (isTiktok && audioFormat === "m4a")) {
processType = "render"
copy = true
if (host === "soundcloud") {
processType = "audio";
copy = true;
}
} else {
audioFormat = "m4a";
copy = true;
}
} else if (isBestAudio && !isSoundCloud) {
audioFormat = "m4a";
copy = true
}
if (isTumblrAudio && isBestOrMp3) {
audioFormat = "mp3";
processType = "bridge"
}
if (r.isM3U8 || host === "vimeo") {
copy = false;
processType = "render"
processType = "audio";
}
params = {
type: processType,
u: Array.isArray(r.urls) ? r.urls[1] : r.urls,
audioFormat: audioFormat,
copy: copy
audioBitrate,
audioCopy: copy,
audioFormat,
}
break;
}
if (defaultParams.filename && (action === "picker" || action === "audio")) {
defaultParams.filename += `.${audioFormat}`;
}
if (alwaysProxy && responseType === "redirect") {
responseType = "tunnel";
params.type = "proxy";
}
return createResponse(responseType, {...defaultParams, ...params})
}

View File

@@ -1,11 +1,12 @@
import { strict as assert } from "node:assert";
import { env } from '../config.js';
import { env } from "../config.js";
import { createResponse } from "../processing/request.js";
import loc from "../../localization/manager.js";
import { testers } from "./servicesPatternTesters.js";
import matchActionDecider from "./matchActionDecider.js";
import { testers } from "./service-patterns.js";
import matchAction from "./match-action.js";
import { friendlyServiceName } from "./service-alias.js";
import bilibili from "./services/bilibili.js";
import reddit from "./services/reddit.js";
@@ -27,11 +28,12 @@ import dailymotion from "./services/dailymotion.js";
import snapchat from "./services/snapchat.js";
import loom from "./services/loom.js";
import facebook from "./services/facebook.js";
import bluesky from "./services/bluesky.js";
let freebind;
export default async function(host, patternMatch, lang, obj) {
const { url } = obj;
export default async function({ host, patternMatch, params }) {
const { url } = params;
assert(url instanceof URL);
let dispatcher, requestIP;
@@ -46,17 +48,20 @@ export default async function(host, patternMatch, lang, obj) {
try {
let r,
isAudioOnly = !!obj.isAudioOnly,
disableMetadata = !!obj.disableMetadata;
isAudioOnly = params.downloadMode === "audio",
isAudioMuted = params.downloadMode === "mute";
if (!testers[host]) {
return createResponse("error", {
t: loc(lang, 'ErrorUnsupported')
code: "error.api.service.unsupported"
});
}
if (!(testers[host](patternMatch))) {
return createResponse("error", {
t: loc(lang, 'ErrorBrokenLink', host)
code: "error.api.link.unsupported",
context: {
service: friendlyServiceName(host),
}
});
}
@@ -65,45 +70,52 @@ export default async function(host, patternMatch, lang, obj) {
r = await twitter({
id: patternMatch.id,
index: patternMatch.index - 1,
toGif: !!obj.twitterGif,
toGif: !!params.twitterGif,
alwaysProxy: params.alwaysProxy,
dispatcher
});
break;
case "vk":
r = await vk({
userId: patternMatch.userId,
videoId: patternMatch.videoId,
quality: obj.vQuality
quality: params.videoQuality
});
break;
case "ok":
r = await ok({
id: patternMatch.id,
quality: obj.vQuality
quality: params.videoQuality
});
break;
case "bilibili":
r = await bilibili(patternMatch);
break;
case "youtube":
let fetchInfo = {
id: patternMatch.id.slice(0, 11),
quality: obj.vQuality,
format: obj.vCodec,
isAudioOnly: isAudioOnly,
isAudioMuted: obj.isAudioMuted,
dubLang: obj.dubLang,
quality: params.videoQuality,
format: params.youtubeVideoCodec,
isAudioOnly,
isAudioMuted,
dubLang: params.youtubeDubLang,
dispatcher
}
if (url.hostname === 'music.youtube.com' || isAudioOnly === true) {
if (url.hostname === "music.youtube.com" || isAudioOnly) {
fetchInfo.quality = "max";
fetchInfo.format = "vp9";
fetchInfo.isAudioOnly = true
fetchInfo.isAudioOnly = true;
fetchInfo.isAudioMuted = false;
}
r = await youtube(fetchInfo);
break;
case "reddit":
r = await reddit({
sub: patternMatch.sub,
@@ -111,15 +123,18 @@ export default async function(host, patternMatch, lang, obj) {
user: patternMatch.user
});
break;
case "tiktok":
r = await tiktok({
postId: patternMatch.postId,
id: patternMatch.id,
fullAudio: obj.isTTFullAudio,
isAudioOnly: isAudioOnly,
h265: obj.tiktokH265
fullAudio: params.tiktokFullAudio,
isAudioOnly,
h265: params.tiktokH265,
alwaysProxy: params.alwaysProxy,
});
break;
case "tumblr":
r = await tumblr({
id: patternMatch.id,
@@ -127,116 +142,169 @@ export default async function(host, patternMatch, lang, obj) {
url
});
break;
case "vimeo":
r = await vimeo({
id: patternMatch.id.slice(0, 11),
password: patternMatch.password,
quality: obj.vQuality,
isAudioOnly: isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "soundcloud":
isAudioOnly = true;
isAudioMuted = false;
r = await soundcloud({
url,
author: patternMatch.author,
song: patternMatch.song,
format: obj.aFormat,
format: params.audioFormat,
shortLink: patternMatch.shortLink || false,
accessKey: patternMatch.accessKey || false
});
break;
case "instagram":
r = await instagram({
...patternMatch,
quality: obj.vQuality,
quality: params.videoQuality,
alwaysProxy: params.alwaysProxy,
dispatcher
})
break;
case "vine":
r = await vine({
id: patternMatch.id
});
break;
case "pinterest":
r = await pinterest({
id: patternMatch.id,
shortLink: patternMatch.shortLink || false
});
break;
case "streamable":
r = await streamable({
id: patternMatch.id,
quality: obj.vQuality,
isAudioOnly: isAudioOnly,
quality: params.videoQuality,
isAudioOnly,
});
break;
case "twitch":
r = await twitch({
clipId: patternMatch.clip || false,
quality: obj.vQuality,
isAudioOnly: obj.isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "rutube":
r = await rutube({
id: patternMatch.id,
yappyId: patternMatch.yappyId,
key: patternMatch.key,
quality: obj.vQuality,
isAudioOnly: isAudioOnly
quality: params.videoQuality,
isAudioOnly,
});
break;
case "dailymotion":
r = await dailymotion(patternMatch);
break;
case "snapchat":
r = await snapchat({
hostname: url.hostname,
...patternMatch
...patternMatch,
alwaysProxy: params.alwaysProxy,
});
break;
case "loom":
r = await loom({
id: patternMatch.id
});
break;
case "facebook":
r = await facebook({
...patternMatch
});
break;
case "bsky":
r = await bluesky({
...patternMatch,
alwaysProxy: params.alwaysProxy
});
break;
default:
return createResponse("error", {
t: loc(lang, 'ErrorUnsupported')
code: "error.api.service.unsupported"
});
}
if (r.isAudioOnly) isAudioOnly = true;
let isAudioMuted = isAudioOnly ? false : obj.isAudioMuted;
if (r.isAudioOnly) {
isAudioOnly = true;
isAudioMuted = false;
}
if (r.error && r.critical) {
return createResponse("critical", {
t: loc(lang, r.error)
})
}
if (r.error) {
return createResponse("error", {
t: Array.isArray(r.error)
? loc(lang, r.error[0], r.error[1])
: loc(lang, r.error)
code: `error.api.${r.error}`,
})
}
return matchActionDecider(
r, host, obj.aFormat, isAudioOnly,
lang, isAudioMuted, disableMetadata,
obj.filenamePattern, obj.twitterGif,
requestIP
)
if (r.error) {
let context;
switch(r.error) {
case "content.too_long":
context = {
limit: env.durationLimit / 60,
}
break;
case "fetch.fail":
case "fetch.rate":
case "fetch.critical":
case "link.unsupported":
case "content.video.unavailable":
context = {
service: friendlyServiceName(host),
}
break;
}
return createResponse("error", {
code: `error.api.${r.error}`,
context,
})
}
return matchAction({
r,
host,
audioFormat: params.audioFormat,
isAudioOnly,
isAudioMuted,
disableMetadata: params.disableMetadata,
filenameStyle: params.filenameStyle,
twitterGif: params.twitterGif,
requestIP,
audioBitrate: params.audioBitrate,
alwaysProxy: params.alwaysProxy,
})
} catch {
return createResponse("error", {
t: loc(lang, 'ErrorBadFetch', host)
code: "error.api.fetch.critical",
context: {
service: friendlyServiceName(host),
}
})
}
}

View File

@@ -0,0 +1,97 @@
import ipaddr from "ipaddr.js";
import { createStream } from "../stream/manage.js";
import { apiSchema } from "./schema.js";
export function createResponse(responseType, responseData) {
const internalError = (code) => {
return {
status: 500,
body: {
status: "error",
error: {
code: code || "error.api.fetch.critical",
},
critical: true
}
}
}
try {
let status = 200,
response = {};
if (responseType === "error") {
status = 400;
}
switch (responseType) {
case "error":
response = {
error: {
code: responseData?.code,
context: responseData?.context,
}
}
break;
case "redirect":
response = {
url: responseData?.u,
filename: responseData?.filename
}
break;
case "tunnel":
response = {
url: createStream(responseData),
filename: responseData?.filename
}
break;
case "picker":
response = {
picker: responseData?.picker,
audio: responseData?.u,
audioFilename: responseData?.filename
}
break;
case "critical":
return internalError(responseData?.code);
default:
throw "unreachable"
}
return {
status,
body: {
status: responseType,
...response
}
}
} catch {
return internalError()
}
}
export function normalizeRequest(request) {
return apiSchema.safeParseAsync(request).catch(() => (
{ success: false }
));
}
export function getIP(req) {
const strippedIP = req.ip.replace(/^::ffff:/, '');
const ip = ipaddr.parse(strippedIP);
if (ip.kind() === 'ipv4') {
return strippedIP;
}
const prefix = 56;
const v6Bytes = ip.toByteArray();
v6Bytes.fill(0, prefix / 8);
return ipaddr.fromByteArray(v6Bytes).toString();
}

View File

@@ -0,0 +1,47 @@
import { z } from "zod";
import { normalizeURL } from "./url.js";
import { verifyLanguageCode } from "../misc/utils.js";
export const apiSchema = z.object({
url: z.string()
.min(1)
.transform(url => normalizeURL(url)),
audioBitrate: z.enum(
["320", "256", "128", "96", "64", "8"]
).default("128"),
audioFormat: z.enum(
["best", "mp3", "ogg", "wav", "opus"]
).default("mp3"),
downloadMode: z.enum(
["auto", "audio", "mute"]
).default("auto"),
filenameStyle: z.enum(
["classic", "pretty", "basic", "nerdy"]
).default("classic"),
youtubeVideoCodec: z.enum(
["h264", "av1", "vp9"]
).default("h264"),
videoQuality: z.enum(
["max", "4320", "2160", "1440", "1080", "720", "480", "360", "240", "144"]
).default("1080"),
youtubeDubLang: z.string()
.length(2)
.transform(verifyLanguageCode)
.optional(),
alwaysProxy: z.boolean().default(false),
disableMetadata: z.boolean().default(false),
tiktokFullAudio: z.boolean().default(false),
tiktokH265: z.boolean().default(false),
twitterGif: z.boolean().default(true),
youtubeDubBrowserLang: z.boolean().default(false),
})
.strict();

View File

@@ -0,0 +1,10 @@
const friendlyNames = {
bsky: "bluesky",
}
export const friendlyServiceName = (service) => {
if (service in friendlyNames) {
return friendlyNames[service];
}
return service;
}

View File

@@ -0,0 +1,182 @@
import UrlPattern from "url-pattern";
export const audioIgnore = ["vk", "ok", "loom"];
export const hlsExceptions = ["dailymotion", "vimeo", "rutube", "bsky"];
export const services = {
bilibili: {
patterns: [
"video/:comId",
"_shortLink/:comShortLink",
"_tv/:lang/video/:tvId",
"_tv/video/:tvId"
],
subdomains: ["m"],
},
bsky: {
patterns: [
"profile/:user/post/:post"
],
tld: "app",
},
dailymotion: {
patterns: ["video/:id"],
},
facebook: {
patterns: [
"_shortLink/:shortLink",
":username/videos/:caption/:id",
":username/videos/:id",
"reel/:id",
"share/:shareType/:id"
],
subdomains: ["web"],
altDomains: ["fb.watch"],
},
instagram: {
patterns: [
"reels/:postId",
":username/reel/:postId",
"reel/:postId",
"p/:postId",
":username/p/:postId",
"tv/:postId",
"stories/:username/:storyId"
],
altDomains: ["ddinstagram.com"],
},
loom: {
patterns: ["share/:id"],
},
ok: {
patterns: [
"video/:id",
"videoembed/:id"
],
tld: "ru",
},
pinterest: {
patterns: [
"pin/:id",
"pin/:id/:garbage",
"url_shortener/:shortLink"
],
},
reddit: {
patterns: [
"r/:sub/comments/:id/:title",
"user/:user/comments/:id/:title"
],
subdomains: "*",
},
rutube: {
patterns: [
"video/:id",
"play/embed/:id",
"shorts/:id",
"yappy/:yappyId",
"video/private/:id?p=:key",
"video/private/:id"
],
tld: "ru",
},
snapchat: {
patterns: [
":shortLink",
"spotlight/:spotlightId",
"add/:username/:storyId",
"u/:username/:storyId",
"add/:username",
"u/:username",
"t/:shortLink",
],
subdomains: ["t", "story"],
},
soundcloud: {
patterns: [
":author/:song/s-:accessKey",
":author/:song",
":shortLink"
],
subdomains: ["on", "m"],
},
streamable: {
patterns: [
":id",
"o/:id",
"e/:id",
"s/:id"
],
},
tiktok: {
patterns: [
":user/video/:postId",
":id",
"t/:id",
":user/photo/:postId",
"v/:id.html"
],
subdomains: ["vt", "vm", "m"],
},
tumblr: {
patterns: [
"post/:id",
"blog/view/:user/:id",
":user/:id",
":user/:id/:trackingId"
],
subdomains: "*",
},
twitch: {
patterns: [":channel/clip/:clip"],
tld: "tv",
},
twitter: {
patterns: [
":user/status/:id",
":user/status/:id/video/:index",
":user/status/:id/photo/:index",
":user/status/:id/mediaviewer",
":user/status/:id/mediaViewer"
],
subdomains: ["mobile"],
altDomains: ["x.com", "vxtwitter.com", "fixvx.com"],
},
vine: {
patterns: ["v/:id"],
tld: "co",
},
vimeo: {
patterns: [
":id",
"video/:id",
":id/:password",
"/channels/:user/:id"
],
subdomains: ["player"],
},
vk: {
patterns: [
"video:userId_:videoId",
"clip:userId_:videoId",
"clips:duplicate?z=clip:userId_:videoId"
],
subdomains: ["m"],
},
youtube: {
patterns: [
"watch?v=:id",
"embed/:id",
"watch/:id"
],
subdomains: ["music", "m"],
}
}
Object.values(services).forEach(service => {
service.patterns = service.patterns.map(
pattern => new UrlPattern(pattern, {
segmentValueCharset: UrlPattern.defaultOptions.segmentValueCharset + '@\\.'
})
)
})

View File

@@ -0,0 +1,76 @@
export const testers = {
"bilibili": pattern =>
pattern.comId?.length <= 12 || pattern.comShortLink?.length <= 16
|| pattern.tvId?.length <= 24,
"dailymotion": pattern => pattern.id?.length <= 32,
"instagram": pattern =>
pattern.postId?.length <= 12
|| (pattern.username?.length <= 30 && pattern.storyId?.length <= 24),
"loom": pattern =>
pattern.id?.length <= 32,
"ok": pattern =>
pattern.id?.length <= 16,
"pinterest": pattern =>
pattern.id?.length <= 128 || pattern.shortLink?.length <= 32,
"reddit": pattern =>
(pattern.sub?.length <= 22 && pattern.id?.length <= 10)
|| (pattern.user?.length <= 22 && pattern.id?.length <= 10),
"rutube": pattern =>
(pattern.id?.length === 32 && pattern.key?.length <= 32) ||
pattern.id?.length === 32 || pattern.yappyId?.length === 32,
"soundcloud": pattern =>
(pattern.author?.length <= 255 && pattern.song?.length <= 255)
|| pattern.shortLink?.length <= 32,
"snapchat": pattern =>
(pattern.username?.length <= 32 && (!pattern.storyId || pattern.storyId?.length <= 255))
|| pattern.spotlightId?.length <= 255
|| pattern.shortLink?.length <= 16,
"streamable": pattern =>
pattern.id?.length === 6,
"tiktok": pattern =>
pattern.postId?.length <= 21 || pattern.id?.length <= 13,
"tumblr": pattern =>
pattern.id?.length < 21
|| (pattern.id?.length < 21 && pattern.user?.length <= 32),
"twitch": pattern =>
pattern.channel && pattern.clip?.length <= 100,
"twitter": pattern =>
pattern.id?.length < 20,
"vimeo": pattern =>
pattern.id?.length <= 11
&& (!pattern.password || pattern.password.length < 16),
"vine": pattern =>
pattern.id?.length <= 12,
"vk": pattern =>
pattern.userId?.length <= 10 && pattern.videoId?.length <= 10,
"youtube": pattern =>
pattern.id?.length <= 11,
"facebook": pattern =>
pattern.shortLink?.length <= 11
|| pattern.username?.length <= 30
|| pattern.caption?.length <= 255
|| pattern.id?.length <= 20 && !pattern.shareType
|| pattern.id?.length <= 20 && pattern.shareType?.length === 1,
"bsky": pattern =>
pattern.user?.length <= 128 && pattern.post?.length <= 128,
}

View File

@@ -30,22 +30,29 @@ function extractBestQuality(dashData) {
async function com_download(id) {
let html = await fetch(`https://bilibili.com/video/${id}`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
headers: {
"user-agent": genericUserAgent
}
})
.then(r => r.text())
.catch(() => {});
if (!html) {
return { error: "fetch.fail" }
}
if (!(html.includes('<script>window.__playinfo__=') && html.includes('"video_codecid"'))) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
let streamData = JSON.parse(html.split('<script>window.__playinfo__=')[1].split('</script>')[0]);
if (streamData.data.timelength > env.durationLimit * 1000) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const [ video, audio ] = extractBestQuality(streamData.data.dash);
if (!video || !audio) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
return {
@@ -66,7 +73,7 @@ async function tv_download(id) {
const { data } = await fetch(url).then(a => a.json());
if (!data?.playurl?.video) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
const [ video, audio ] = extractBestQuality({
@@ -76,11 +83,11 @@ async function tv_download(id) {
});
if (!video || !audio) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
if (video.duration > env.durationLimit * 1000) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
return {
@@ -101,5 +108,5 @@ export default async function({ comId, tvId, comShortLink }) {
return tv_download(tvId);
}
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}

View File

@@ -0,0 +1,93 @@
import HLS from "hls-parser";
import { cobaltUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
const extractVideo = async ({ getPost, filename }) => {
const urlMasterHLS = getPost?.thread?.post?.embed?.playlist;
if (!urlMasterHLS) return { error: "fetch.empty" };
if (!urlMasterHLS.startsWith("https://video.bsky.app/")) return { error: "fetch.empty" };
const masterHLS = await fetch(urlMasterHLS)
.then(r => {
if (r.status !== 200) return;
return r.text();
})
.catch(() => {});
if (!masterHLS) return { error: "fetch.empty" };
const video = HLS.parse(masterHLS)
?.variants
?.reduce((a, b) => a?.bandwidth > b?.bandwidth ? a : b);
const videoURL = new URL(video.uri, urlMasterHLS).toString();
return {
urls: videoURL,
filename: `${filename}.mp4`,
audioFilename: `${filename}_audio`,
isM3U8: true,
}
}
const extractImages = ({ getPost, filename, alwaysProxy }) => {
const images = getPost?.thread?.post?.embed?.images;
if (!images || images.length === 0) {
return { error: "fetch.empty" };
}
if (images.length === 1) return {
urls: images[0].fullsize,
isPhoto: true,
filename: `${filename}.jpg`,
}
const picker = images.map((image, i) => {
let url = image.fullsize;
let proxiedImage = createStream({
service: "bluesky",
type: "proxy",
u: url,
filename: `${filename}_${i + 1}.jpg`,
});
if (alwaysProxy) url = proxiedImage;
return {
type: "photo",
url,
thumb: proxiedImage,
}
});
return { picker };
}
export default async function ({ user, post, alwaysProxy }) {
const apiEndpoint = new URL("https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?depth=0&parentHeight=0");
apiEndpoint.searchParams.set(
"uri",
`at://${user}/app.bsky.feed.post/${post}`
);
const getPost = await fetch(apiEndpoint, {
headers: {
"user-agent": cobaltUserAgent
}
}).then(r => r.json()).catch(() => {});
if (!getPost || getPost?.error) return { error: "fetch.empty" };
const embedType = getPost?.thread?.post?.embed?.$type;
const filename = `bluesky_${user}_${post}`;
if (embedType === "app.bsky.embed.video#view") {
return extractVideo({ getPost, filename });
}
if (embedType === "app.bsky.embed.images#view") {
return extractImages({ getPost, filename, alwaysProxy });
}
return { error: "fetch.empty" };
}

View File

@@ -1,5 +1,5 @@
import HLSParser from 'hls-parser';
import { env } from '../../config.js';
import HLSParser from "hls-parser";
import { env } from "../../config.js";
let _token;
@@ -31,7 +31,7 @@ const getToken = async () => {
export default async function({ id }) {
const token = await getToken();
if (!token) return { error: 'ErrorSomethingWentWrong' };
if (!token) return { error: "fetch.fail" };
const req = await fetch('https://graphql.api.dailymotion.com/',
{
@@ -70,20 +70,20 @@ export default async function({ id }) {
const media = req?.data?.media;
if (media?.__typename !== 'Video' || !media.hlsURL) {
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}
if (media.duration > env.durationLimit) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const manifest = await fetch(media.hlsURL).then(r => r.text()).catch(() => {});
if (!manifest) return { error: 'ErrorSomethingWentWrong' };
if (!manifest) return { error: "fetch.fail" };
const bestQuality = HLSParser.parse(manifest).variants
.filter(v => v.codecs.includes('avc1'))
.reduce((a, b) => a.bandwidth > b.bandwidth ? a : b);
if (!bestQuality) return { error: 'ErrorEmptyDownload' }
if (!bestQuality) return { error: "fetch.empty" }
const fileMetadata = {
title: media.title,

View File

@@ -33,7 +33,8 @@ export default async function({ id, shareType, shortLink }) {
.then(r => r.text())
.catch(() => false);
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html && shortLink) return { error: "fetch.short_link" }
if (!html) return { error: "fetch.fail" };
const urls = [];
const hd = html.match('"browser_native_hd_url":(".*?")');
@@ -43,7 +44,7 @@ export default async function({ id, shareType, shortLink }) {
if (sd?.[1]) urls.push(JSON.parse(sd[1]));
if (!urls.length) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
const baseFilename = `facebook_${id || shortLink}`;

View File

@@ -1,5 +1,5 @@
import { createStream } from "../../stream/manage.js";
import { genericUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
import { getCookie, updateCookie } from "../cookie/manager.js";
const commonHeaders = {
@@ -163,23 +163,34 @@ export default function(obj) {
?.[0];
}
function extractOldPost(data, id) {
function extractOldPost(data, id, alwaysProxy) {
const sidecar = data?.gql_data?.shortcode_media?.edge_sidecar_to_children;
if (sidecar) {
const picker = sidecar.edges.filter(e => e.node?.display_url)
.map(e => {
.map((e, i) => {
const type = e.node?.is_video ? "video" : "photo";
const url = type === "video" ? e.node?.video_url : e.node?.display_url;
let itemExt = type === "video" ? "mp4" : "jpg";
let proxyFile;
if (alwaysProxy) proxyFile = createStream({
service: "instagram",
type: "proxy",
u: url,
filename: `instagram_${id}_${i + 1}.${itemExt}`
});
return {
type, url,
type,
url: proxyFile || url,
/* thumbnails have `Cross-Origin-Resource-Policy`
** set to `same-origin`, so we need to proxy them */
thumb: createStream({
service: "instagram",
type: "default",
type: "proxy",
u: e.node?.display_url,
filename: "image.jpg"
filename: `instagram_${id}_${i + 1}.jpg`
})
}
});
@@ -199,29 +210,40 @@ export default function(obj) {
}
}
function extractNewPost(data, id) {
function extractNewPost(data, id, alwaysProxy) {
const carousel = data.carousel_media;
if (carousel) {
const picker = carousel.filter(e => e?.image_versions2)
.map(e => {
.map((e, i) => {
const type = e.video_versions ? "video" : "photo";
const imageUrl = e.image_versions2.candidates[0].url;
let url = imageUrl;
if (type === 'video') {
let itemExt = type === "video" ? "mp4" : "jpg";
if (type === "video") {
const video = e.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a);
url = video.url;
}
let proxyFile;
if (alwaysProxy) proxyFile = createStream({
service: "instagram",
type: "proxy",
u: url,
filename: `instagram_${id}_${i + 1}.${itemExt}`
});
return {
type, url,
type,
url: proxyFile || url,
/* thumbnails have `Cross-Origin-Resource-Policy`
** set to `same-origin`, so we need to proxy them */
** set to `same-origin`, so we need to always proxy them */
thumb: createStream({
service: "instagram",
type: "default",
type: "proxy",
u: imageUrl,
filename: "image.jpg"
filename: `instagram_${id}_${i + 1}.jpg`
})
}
});
@@ -237,16 +259,17 @@ export default function(obj) {
} else if (data.image_versions2?.candidates) {
return {
urls: data.image_versions2.candidates[0].url,
isPhoto: true
isPhoto: true,
filename: `instagram_${id}.jpg`,
}
}
}
async function getPost(id) {
async function getPost(id, alwaysProxy) {
let data, result;
try {
const cookie = getCookie('instagram');
const bearer = getCookie('instagram_bearer');
const token = bearer?.values()?.token;
@@ -271,16 +294,16 @@ export default function(obj) {
if (!data && cookie) data = await requestGQL(id, cookie);
} catch {}
if (!data) return { error: 'ErrorCouldntFetch' };
if (!data) return { error: "fetch.fail" };
if (data?.gql_data) {
result = extractOldPost(data, id)
result = extractOldPost(data, id, alwaysProxy)
} else {
result = extractNewPost(data, id)
result = extractNewPost(data, id, alwaysProxy)
}
if (result) return result;
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}
async function usernameToId(username, cookie) {
@@ -295,11 +318,11 @@ export default function(obj) {
async function getStory(username, id) {
const cookie = getCookie('instagram');
if (!cookie) return { error: 'ErrorUnsupported' };
if (!cookie) return { error: "link.unsupported" };
const userId = await usernameToId(username, cookie);
if (!userId) return { error: 'ErrorEmptyDownload' };
if (!userId) return { error: "fetch.empty" };
const dtsgId = await findDtsgId(cookie);
const url = new URL('https://www.instagram.com/api/graphql/');
@@ -320,8 +343,8 @@ export default function(obj) {
} catch {}
const item = media.items.find(m => m.pk === id);
if (!item) return { error: 'ErrorEmptyDownload' };
if (!item) return { error: "fetch.empty" };
if (item.video_versions) {
const video = item.video_versions.reduce((a, b) => a.width * a.height < b.width * b.height ? b : a)
return {
@@ -338,12 +361,12 @@ export default function(obj) {
}
}
return { error: 'ErrorUnsupported' };
return { error: "link.unsupported" };
}
const { postId, storyId, username } = obj;
if (postId) return getPost(postId);
const { postId, storyId, username, alwaysProxy } = obj;
if (postId) return getPost(postId, alwaysProxy);
if (username && storyId) return getStory(username, storyId);
return { error: 'ErrorUnsupported' }
return { error: "fetch.empty" }
}

View File

@@ -23,7 +23,7 @@ export default async function({ id }) {
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!gql) return { error: 'ErrorEmptyDownload' };
if (!gql) return { error: "fetch.empty" };
const videoUrl = gql?.url;
@@ -35,5 +35,5 @@ export default async function({ id }) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@@ -1,5 +1,5 @@
import { genericUserAgent, env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
const resolutions = {
"ultra": "2160",
@@ -19,26 +19,26 @@ export default async function(o) {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
let videoData = html.match(/<div data-module="OKVideo" .*? data-options="({.*?})"( .*?)>/)
?.[1]
?.replaceAll("&quot;", '"');
if (!videoData) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
videoData = JSON.parse(JSON.parse(videoData).flashvars.metadata);
if (videoData.provider !== "UPLOADED_ODKL")
return { error: 'ErrorUnsupported' };
return { error: "link.unsupported" };
if (videoData.movie.is_live)
return { error: 'ErrorLiveVideo' };
return { error: "content.video.live" };
if (videoData.movie.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let videos = videoData.videos.filter(v => !v.disallowed);
let bestVideo = videos.find(v => resolutions[v.name] === quality) || videos[videos.length - 1];
@@ -61,5 +61,5 @@ export default async function(o) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@@ -12,15 +12,15 @@ export default async function(o) {
.catch(() => {});
}
if (id.includes("--")) id = id.split("--")[1];
if (!id) return { error: 'ErrorCouldntFetch' };
if (!id) return { error: "fetch.fail" };
let html = await fetch(`https://www.pinterest.com/pin/${id}/`, {
const html = await fetch(`https://www.pinterest.com/pin/${id}/`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
let videoLink = [...html.matchAll(videoRegex)]
const videoLink = [...html.matchAll(videoRegex)]
.map(([, link]) => link)
.find(a => a.endsWith('.mp4') && a.includes('720p'));
@@ -30,14 +30,17 @@ export default async function(o) {
audioFilename: `pinterest_${o.id}_audio`
}
let imageLink = [...html.matchAll(imageRegex)]
const imageLink = [...html.matchAll(imageRegex)]
.map(([, link]) => link)
.find(a => a.endsWith('.jpg') || a.endsWith('.gif'));
const imageType = imageLink.endsWith(".gif") ? "gif" : "jpg"
if (imageLink) return {
urls: imageLink,
isPhoto: true
isPhoto: true,
filename: `pinterest_${o.id}.${imageType}`
}
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}

View File

@@ -9,7 +9,7 @@ async function getAccessToken() {
* you can get these by making a reddit app and
* authenticating an account against reddit's oauth2 api
* see: https://github.com/reddit-archive/reddit/wiki/OAuth2
*
*
* any additional cookie fields are managed by this code and you
* should not touch them unless you know what you're doing. **/
const cookie = await getCookie('reddit');
@@ -67,20 +67,25 @@ export default async function(obj) {
}
).then(r => r.json()).catch(() => {});
if (!data || !Array.isArray(data)) return { error: 'ErrorCouldntFetch' };
if (!data || !Array.isArray(data)) {
return { error: "fetch.fail" }
}
data = data[0]?.data?.children[0]?.data;
const id = `${String(obj.sub).toLowerCase()}_${obj.id}`;
if (data?.url?.endsWith('.gif')) return {
typeId: "redirect",
urls: data.url
urls: data.url,
filename: `reddit_${id}.gif`,
}
if (!data.secure_media?.reddit_video)
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
if (data.secure_media?.reddit_video?.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let audio = false,
video = data.secure_media?.reddit_video?.fallback_url?.split('?')[0],
@@ -107,16 +112,14 @@ export default async function(obj) {
}).catch(() => {})
}
let id = `${String(obj.sub).toLowerCase()}_${obj.id}`;
if (!audio) return {
typeId: "redirect",
urls: video
}
return {
typeId: "stream",
type: "render",
typeId: "tunnel",
type: "merge",
urls: [video, audioFileLink],
audioFilename: `reddit_${id}_audio`,
filename: `reddit_${id}.mp4`

View File

@@ -1,7 +1,7 @@
import HLS from 'hls-parser';
import HLS from "hls-parser";
import { env } from "../../config.js";
import { cleanString } from '../../sub/utils.js';
import { cleanString } from "../../misc/utils.js";
async function requestJSON(url) {
try {
@@ -18,7 +18,7 @@ export default async function(obj) {
`https://rutube.ru/pangolin/api/web/yappy/yappypage/?client=wdp&videoId=${obj.yappyId}&page=1&page_size=15`
)
const yappyURL = yappy?.results?.find(r => r.id === obj.yappyId)?.link;
if (!yappyURL) return { error: 'ErrorEmptyDownload' };
if (!yappyURL) return { error: "fetch.empty" };
return {
urls: yappyURL,
@@ -33,19 +33,19 @@ export default async function(obj) {
if (obj.key) requestURL.searchParams.set('p', obj.key);
const play = await requestJSON(requestURL);
if (!play) return { error: 'ErrorCouldntFetch' };
if (!play) return { error: "fetch.fail" };
if (play.detail || !play.video_balancer) return { error: 'ErrorEmptyDownload' };
if (play.live_streams?.hls) return { error: 'ErrorLiveVideo' };
if (play.detail || !play.video_balancer) return { error: "fetch.empty" };
if (play.live_streams?.hls) return { error: "content.video.live" };
if (play.duration > env.durationLimit * 1000)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
let m3u8 = await fetch(play.video_balancer.m3u8)
.then(r => r.text())
.catch(() => {});
if (!m3u8) return { error: 'ErrorCouldntFetch' };
if (!m3u8) return { error: "fetch.fail" };
m3u8 = HLS.parse(m3u8).variants;

View File

@@ -1,20 +1,23 @@
import { genericUserAgent } from "../../config.js";
import { getRedirectingURL } from "../../sub/utils.js";
import { extract, normalizeURL } from "../url.js";
import { genericUserAgent } from "../../config.js";
import { createStream } from "../../stream/manage.js";
import { getRedirectingURL } from "../../misc/utils.js";
const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="preload" href="(https:\/\/cf-st\.sc-cdn\.net\/d\/[\w.?=]+&amp;uc=\d+)" as="video"\/>/;
const SPOTLIGHT_VIDEO_REGEX = /<link data-react-helmet="true" rel="preload" href="([^"]+)" as="video"\/>/;
const NEXT_DATA_REGEX = /<script id="__NEXT_DATA__" type="application\/json">({.+})<\/script><\/body><\/html>$/;
async function getSpotlight(id) {
const html = await fetch(`https://www.snapchat.com/spotlight/${id}`, {
headers: { 'User-Agent': genericUserAgent }
headers: { 'user-agent': genericUserAgent }
}).then((r) => r.text()).catch(() => null);
if (!html) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
const videoURL = html.match(SPOTLIGHT_VIDEO_REGEX)?.[1];
if (videoURL) {
if (videoURL && new URL(videoURL).hostname.endsWith(".sc-cdn.net")) {
return {
urls: videoURL,
filename: `snapchat_${id}.mp4`,
@@ -23,12 +26,16 @@ async function getSpotlight(id) {
}
}
async function getStory(username, storyId) {
const html = await fetch(`https://www.snapchat.com/add/${username}${storyId ? `/${storyId}` : ''}`, {
headers: { 'User-Agent': genericUserAgent }
}).then((r) => r.text()).catch(() => null);
async function getStory(username, storyId, alwaysProxy) {
const html = await fetch(
`https://www.snapchat.com/add/${username}${storyId ? `/${storyId}` : ''}`,
{ headers: { 'user-agent': genericUserAgent } }
)
.then((r) => r.text())
.catch(() => null);
if (!html) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
const nextDataString = html.match(NEXT_DATA_REGEX)?.[1];
@@ -42,6 +49,7 @@ async function getStory(username, storyId) {
if (story.snapMediaType === 0) {
return {
urls: story.snapUrls.mediaUrl,
filename: `snapchat_${storyId}.jpg`,
isPhoto: true
}
}
@@ -57,11 +65,33 @@ async function getStory(username, storyId) {
const defaultStory = data.props.pageProps.curatedHighlights[0];
if (defaultStory) {
return {
picker: defaultStory.snapList.map((snap) => ({
type: snap.snapMediaType === 0 ? 'photo' : 'video',
url: snap.snapUrls.mediaUrl,
thumb: snap.snapUrls.mediaPreviewUrl.value
}))
picker: defaultStory.snapList.map(snap => {
const snapType = snap.snapMediaType === 0 ? "photo" : "video";
const snapExt = snapType === "video" ? "mp4" : "jpg";
let snapUrl = snap.snapUrls.mediaUrl;
const proxy = createStream({
service: "snapchat",
type: "proxy",
u: snapUrl,
filename: `snapchat_${username}_${snap.timestampInSec.value}.${snapExt}`,
});
let thumbProxy;
if (snapType === "video") thumbProxy = createStream({
service: "snapchat",
type: "proxy",
u: snap.snapUrls.mediaPreviewUrl.value,
});
if (alwaysProxy) snapUrl = proxy;
return {
type: snapType,
url: snapUrl,
thumb: thumbProxy || proxy,
}
})
}
}
}
@@ -69,16 +99,16 @@ async function getStory(username, storyId) {
export default async function (obj) {
let params = obj;
if (obj.hostname === 't.snapchat.com' && obj.shortLink) {
if (obj.shortLink) {
const link = await getRedirectingURL(`https://t.snapchat.com/${obj.shortLink}`);
if (!link?.startsWith('https://www.snapchat.com/')) {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.short_link" };
}
const extractResult = extract(normalizeURL(link));
if (extractResult?.host !== 'snapchat') {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.short_link" };
}
params = extractResult.patternMatch;
@@ -88,9 +118,9 @@ export default async function (obj) {
const result = await getSpotlight(params.spotlightId);
if (result) return result;
} else if (params.username) {
const result = await getStory(params.username, params.storyId);
const result = await getStory(params.username, params.storyId, obj.alwaysProxy);
if (result) return result;
}
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}

View File

@@ -1,5 +1,5 @@
import { env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
const cachedID = {
version: '',
@@ -39,7 +39,7 @@ async function findClientID() {
export default async function(obj) {
let clientId = await findClientID();
if (!clientId) return { error: 'ErrorSoundCloudNoClientId' };
if (!clientId) return { error: "fetch.fail" };
let link;
if (obj.url.hostname === 'on.soundcloud.com' && obj.shortLink) {
@@ -54,15 +54,16 @@ export default async function(obj) {
link = `https://soundcloud.com/${obj.author}/${obj.song}${obj.accessKey ? `/s-${obj.accessKey}` : ''}`
}
if (!link) return { error: 'ErrorCouldntFetch' };
if (!link && obj.shortLink) return { error: "fetch.short_link" };
if (!link) return { error: "link.unsupported" };
let json = await fetch(`https://api-v2.soundcloud.com/resolve?url=${link}&client_id=${clientId}`)
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!json) return { error: 'ErrorCouldntFetch' };
if (!json) return { error: "fetch.fail" };
if (!json.media.transcodings) return { error: 'ErrorEmptyDownload' };
if (!json.media.transcodings) return { error: "fetch.empty" };
let bestAudio = "opus",
selectedStream = json.media.transcodings.find(v => v.preset === "opus_0_0"),
@@ -78,15 +79,16 @@ export default async function(obj) {
let fileUrl = `${fileUrlBase}${fileUrlBase.includes("?") ? "&" : "?"}client_id=${clientId}&track_authorization=${json.track_authorization}`;
if (!fileUrl.startsWith("https://api-v2.soundcloud.com/media/soundcloud:tracks:"))
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
if (json.duration > env.durationLimit * 1000)
return { error: ['ErrorLengthAudioConvert', env.durationLimit / 60] };
if (json.duration > env.durationLimit * 1000) {
return { error: "content.too_long" };
}
let file = await fetch(fileUrl)
.then(async r => (await r.json()).url)
.catch(() => {});
if (!file) return { error: 'ErrorCouldntFetch' };
if (!file) return { error: "fetch.empty" };
let fileMetadata = {
title: cleanString(json.title.trim()),

View File

@@ -3,9 +3,9 @@ export default async function(obj) {
.then(r => r.status === 200 ? r.json() : false)
.catch(() => {});
if (!video) return { error: 'ErrorEmptyDownload' };
if (!video) return { error: "fetch.empty" };
let best = video.files['mp4-mobile'];
let best = video.files["mp4-mobile"];
if (video.files.mp4 && (obj.isAudioOnly || obj.quality === "max" || obj.quality >= 720)) {
best = video.files.mp4;
}
@@ -18,5 +18,5 @@ export default async function(obj) {
title: video.title
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.fail" }
}

View File

@@ -1,7 +1,9 @@
import Cookie from "../cookie/cookie.js";
import { extract } from "../url.js";
import { genericUserAgent } from "../../config.js";
import { updateCookie } from "../cookie/manager.js";
import { extract } from "../url.js";
import Cookie from "../cookie/cookie.js";
import { createStream } from "../../stream/manage.js";
const shortDomain = "https://vt.tiktok.com/";
@@ -17,7 +19,7 @@ export default async function(obj) {
}
}).then(r => r.text()).catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
if (html.startsWith('<a href="https://')) {
const extractedURL = html.split('<a href="')[1].split('?')[0];
@@ -25,7 +27,7 @@ export default async function(obj) {
postId = patternMatch.postId
}
}
if (!postId) return { error: 'ErrorCantGetID' };
if (!postId) return { error: "fetch.short_link" };
// should always be /video/, even for photos
const res = await fetch(`https://tiktok.com/@i/video/${postId}`, {
@@ -46,12 +48,12 @@ export default async function(obj) {
const data = JSON.parse(json)
detail = data["__DEFAULT_SCOPE__"]["webapp.video-detail"]["itemInfo"]["itemStruct"]
} catch {
return { error: 'ErrorCouldntFetch' };
return { error: "fetch.fail" };
}
let video, videoFilename, audioFilename, audio, images,
filenameBase = `tiktok_${detail.author.uniqueId}_${postId}`,
bestAudio = 'm4a';
bestAudio; // will get defaulted to m4a later on in match-action
images = detail.imagePost?.images;
@@ -96,7 +98,19 @@ export default async function(obj) {
if (images) {
let imageLinks = images
.map(i => i.imageURL.urlList.find(p => p.includes(".jpeg?")))
.map(url => ({ url }));
.map((url, i) => {
if (obj.alwaysProxy) url = createStream({
service: "tiktok",
type: "proxy",
u: url,
filename: `${filenameBase}_photo_${i + 1}.jpg`
})
return {
type: "photo",
url
}
});
return {
picker: imageLinks,

View File

@@ -22,7 +22,7 @@ export default async function(input) {
let { subdomain } = psl.parse(input.url.hostname);
if (subdomain?.includes('.')) {
return { error: ['ErrorBrokenLink', 'tumblr'] }
return { error: "link.unsupported" };
} else if (subdomain === 'www' || subdomain === 'at') {
subdomain = undefined
}
@@ -31,7 +31,7 @@ export default async function(input) {
const data = await request(domain, input.id);
const element = data?.response?.timeline?.elements?.[0];
if (!element) return { error: 'ErrorEmptyDownload' };
if (!element) return { error: "fetch.empty" };
const contents = [
...element.content,
@@ -53,7 +53,8 @@ export default async function(input) {
title: fileMetadata.title,
author: fileMetadata.artist
},
isAudioOnly: true
isAudioOnly: true,
bestAudio: "mp3",
}
}
@@ -66,5 +67,5 @@ export default async function(input) {
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "link.unsupported" }
}

View File

@@ -1,11 +1,11 @@
import { env } from "../../config.js";
import { cleanString } from '../../sub/utils.js';
import { cleanString } from '../../misc/utils.js';
const gqlURL = "https://gql.twitch.tv/gql";
const clientIdHead = { "client-id": "kimne78kx3ncx6brgo4mv6wki5h1ko" };
export default async function (obj) {
let req_metadata = await fetch(gqlURL, {
const req_metadata = await fetch(gqlURL, {
method: "POST",
headers: clientIdHead,
body: JSON.stringify({
@@ -30,16 +30,19 @@ export default async function (obj) {
}`
})
}).then(r => r.status === 200 ? r.json() : false).catch(() => {});
if (!req_metadata) return { error: 'ErrorCouldntFetch' };
let clipMetadata = req_metadata.data.clip;
if (!req_metadata) return { error: "fetch.fail" };
if (clipMetadata.durationSeconds > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
if (!clipMetadata.videoQualities || !clipMetadata.broadcaster)
return { error: 'ErrorEmptyDownload' };
const clipMetadata = req_metadata.data.clip;
let req_token = await fetch(gqlURL, {
if (clipMetadata.durationSeconds > env.durationLimit) {
return { error: "content.too_long" };
}
if (!clipMetadata.videoQualities || !clipMetadata.broadcaster) {
return { error: "fetch.empty" };
}
const req_token = await fetch(gqlURL, {
method: "POST",
headers: clientIdHead,
body: JSON.stringify([
@@ -58,13 +61,13 @@ export default async function (obj) {
])
}).then(r => r.status === 200 ? r.json() : false).catch(() => {});
if (!req_token) return { error: 'ErrorCouldntFetch' };
if (!req_token) return { error: "fetch.fail" };
let formats = clipMetadata.videoQualities;
let format = formats.find(f => f.quality === obj.quality) || formats[0];
const formats = clipMetadata.videoQualities;
const format = formats.find(f => f.quality === obj.quality) || formats[0];
return {
type: "bridge",
type: "proxy",
urls: `${format.sourceURL}?${new URLSearchParams({
sig: req_token[0].data.clip.playbackAccessToken.signature,
token: req_token[0].data.clip.playbackAccessToken.value

View File

@@ -101,11 +101,11 @@ const requestTweet = async(dispatcher, tweetId, token, cookie) => {
return result
}
export default async function({ id, index, toGif, dispatcher }) {
export default async function({ id, index, toGif, dispatcher, alwaysProxy }) {
const cookie = await getCookie('twitter');
let guestToken = await getGuestToken(dispatcher);
if (!guestToken) return { error: 'ErrorCouldntFetch' };
if (!guestToken) return { error: "fetch.fail" };
let tweet = await requestTweet(dispatcher, id, guestToken);
@@ -119,22 +119,26 @@ export default async function({ id, index, toGif, dispatcher }) {
let tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
if (!tweetTypename) {
return { error: "fetch.empty" }
}
if (tweetTypename === "TweetUnavailable") {
const reason = tweet?.data?.tweetResult?.result?.reason;
switch(reason) {
case "Protected":
return { error: 'ErrorTweetProtected' }
return { error: "content.post.private" }
case "NsfwLoggedOut":
if (cookie) {
tweet = await requestTweet(dispatcher, id, guestToken, cookie);
tweet = await tweet.json();
tweetTypename = tweet?.data?.tweetResult?.result?.__typename;
} else return { error: 'ErrorTweetNSFW' }
} else return { error: "content.post.age" }
}
}
if (!["Tweet", "TweetWithVisibilityResults"].includes(tweetTypename)) {
return { error: 'ErrorTweetUnavailable' }
return { error: "content.post.unavailable" }
}
let tweetResult = tweet.data.tweetResult.result,
@@ -153,56 +157,77 @@ export default async function({ id, index, toGif, dispatcher }) {
media = [media[index]]
}
const getFileExt = (url) => new URL(url).pathname.split(".", 2)[1];
const proxyMedia = (u, filename) => createStream({
service: "twitter",
type: "proxy",
u, filename,
})
switch (media?.length) {
case undefined:
case 0:
return { error: 'ErrorNoVideosInTweet' };
return {
error: "fetch.empty"
}
case 1:
if (media[0].type === "photo") {
return {
type: "normal",
type: "proxy",
isPhoto: true,
filename: `twitter_${id}.${getFileExt(media[0].media_url_https)}`,
urls: `${media[0].media_url_https}?name=4096x4096`
}
}
return {
type: needsFixing(media[0]) ? "remux" : "normal",
type: needsFixing(media[0]) ? "remux" : "proxy",
urls: bestQuality(media[0].video_info.variants),
filename: `twitter_${id}.mp4`,
audioFilename: `twitter_${id}_audio`,
isGif: media[0].type === "animated_gif"
}
default:
const proxyThumb = (url, i) =>
proxyMedia(url, `twitter_${id}_${i + 1}.${getFileExt(url)}`);
const picker = media.map((content, i) => {
if (content.type === "photo") {
let url = `${content.media_url_https}?name=4096x4096`;
let proxiedImage = proxyThumb(url, i);
if (alwaysProxy) url = proxiedImage;
return {
type: "photo",
url,
thumb: url,
thumb: proxiedImage,
}
}
let url = bestQuality(content.video_info.variants);
const shouldRenderGif = content.type === 'animated_gif' && toGif;
const shouldRenderGif = content.type === "animated_gif" && toGif;
const videoFilename = `twitter_${id}_${i + 1}.mp4`;
let type = "video";
if (shouldRenderGif) type = "gif";
if (needsFixing(content) || shouldRenderGif) {
url = createStream({
service: 'twitter',
type: shouldRenderGif ? 'gif' : 'remux',
service: "twitter",
type: shouldRenderGif ? "gif" : "remux",
u: url,
filename: `twitter_${id}_${i + 1}.mp4`
filename: videoFilename,
})
} else if (alwaysProxy) {
url = proxyMedia(url, videoFilename);
}
return {
type,
url,
thumb: content.media_url_https
thumb: proxyThumb(content.media_url_https, i),
}
});
return { picker };

View File

@@ -1,8 +1,8 @@
import { env } from "../../config.js";
import { cleanString, merge } from '../../sub/utils.js';
import HLS from "hls-parser";
import { env } from "../../config.js";
import { cleanString, merge } from '../../misc/utils.js';
const resolutionMatch = {
"3840": 2160,
"2732": 1440,
@@ -63,7 +63,8 @@ const getDirectLink = (data, quality) => {
resolution: `${match.width}x${match.height}`,
qualityLabel: match.rendition,
extension: "mp4"
}
},
bestAudio: "mp3",
}
}
@@ -73,25 +74,25 @@ const getHLS = async (configURL, obj) => {
const api = await fetch(configURL)
.then(r => r.json())
.catch(() => {});
if (!api) return { error: 'ErrorCouldntFetch' };
if (!api) return { error: "fetch.fail" };
if (api.video?.duration > env.durationLimit) {
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
}
const urlMasterHLS = api.request?.files?.hls?.cdns?.akfire_interconnect_quic?.url;
if (!urlMasterHLS) return { error: 'ErrorCouldntFetch' }
if (!urlMasterHLS) return { error: "fetch.fail" };
const masterHLS = await fetch(urlMasterHLS)
.then(r => r.text())
.catch(() => {});
if (!masterHLS) return { error: 'ErrorCouldntFetch' };
if (!masterHLS) return { error: "fetch.fail" };
const variants = HLS.parse(masterHLS)?.variants?.sort(
(a, b) => Number(b.bandwidth) - Number(a.bandwidth)
);
if (!variants || variants.length === 0) return { error: 'ErrorEmptyDownload' };
if (!variants || variants.length === 0) return { error: "fetch.empty" };
let bestQuality;
@@ -116,7 +117,7 @@ const getHLS = async (configURL, obj) => {
expandLink(audioPath)
]
} else if (obj.isAudioOnly) {
return { error: 'ErrorEmptyDownload' };
return { error: "fetch.empty" };
}
return {
@@ -126,7 +127,8 @@ const getHLS = async (configURL, obj) => {
resolution: `${bestQuality.resolution.width}x${bestQuality.resolution.height}`,
qualityLabel: `${resolutionMatch[bestQuality.resolution.width]}p`,
extension: "mp4"
}
},
bestAudio: "mp3",
}
}
@@ -143,7 +145,7 @@ export default async function(obj) {
}
if (!response) response = getDirectLink(info, quality);
if (!response) response = { error: 'ErrorEmptyDownload' };
if (!response) response = { error: "fetch.empty" };
if (response.error) {
return response;

View File

@@ -3,7 +3,7 @@ export default async function(obj) {
.then(r => r.json())
.catch(() => {});
if (!post) return { error: 'ErrorEmptyDownload' };
if (!post) return { error: "fetch.empty" };
if (post.videoUrl) return {
urls: post.videoUrl.replace("http://", "https://"),
@@ -11,5 +11,5 @@ export default async function(obj) {
audioFilename: `vine_${obj.id}_audio`
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@@ -1,5 +1,5 @@
import { cleanString } from "../../misc/utils.js";
import { genericUserAgent, env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
const resolutions = ["2160", "1440", "1080", "720", "480", "360", "240"];
@@ -7,22 +7,30 @@ export default async function(o) {
let html, url, quality = o.quality === "max" ? 2160 : o.quality;
html = await fetch(`https://vk.com/video${o.userId}_${o.videoId}`, {
headers: { "user-agent": genericUserAgent }
}).then(r => r.arrayBuffer()).catch(() => {});
headers: {
"user-agent": genericUserAgent
}
})
.then(r => r.arrayBuffer())
.catch(() => {});
if (!html) return { error: 'ErrorCouldntFetch' };
if (!html) return { error: "fetch.fail" };
// decode cyrillic from windows-1251 because vk still uses apis from prehistoric times
let decoder = new TextDecoder('windows-1251');
html = decoder.decode(html);
if (!html.includes(`{"lang":`)) return { error: 'ErrorEmptyDownload' };
if (!html.includes(`{"lang":`)) return { error: "fetch.empty" };
let js = JSON.parse('{"lang":' + html.split(`{"lang":`)[1].split(']);')[0]);
if (Number(js.mvData.is_active_live) !== 0) return { error: 'ErrorLiveVideo' };
if (js.mvData.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
if (Number(js.mvData.is_active_live) !== 0) {
return { error: "content.video.live" };
}
if (js.mvData.duration > env.durationLimit) {
return { error: "content.too_long" };
}
for (let i in resolutions) {
if (js.player.params[0][`url${resolutions[i]}`]) {
@@ -51,5 +59,5 @@ export default async function(o) {
extension: "mp4"
}
}
return { error: 'ErrorEmptyDownload' }
return { error: "fetch.empty" }
}

View File

@@ -3,7 +3,7 @@ import { fetch } from "undici";
import { Innertube, Session } from "youtubei.js";
import { env } from "../../config.js";
import { cleanString } from "../../sub/utils.js";
import { cleanString } from "../../misc/utils.js";
import { getCookie, updateCookieValues } from "../cookie/manager.js";
const PLAYER_REFRESH_PERIOD = 1000 * 60 * 15; // ms
@@ -110,7 +110,9 @@ export default async function(o) {
);
} catch(e) {
if (e.message?.endsWith("decipher algorithm")) {
return { error: "ErrorYoutubeDecipher" }
return { error: "youtube.decipher" }
} else if (e.message?.includes("refresh access token")) {
return { error: "youtube.token_expired" }
} else throw e;
}
@@ -130,44 +132,60 @@ export default async function(o) {
try {
info = await yt.getBasicInfo(o.id, yt.session.logged_in ? 'ANDROID' : 'IOS');
} catch(e) {
if (e?.message === 'This video is unavailable') {
return { error: 'ErrorCouldntFetch' };
if (e?.info?.reason === "This video is private") {
return { error: "content.video.private" };
} else if (e?.message === "This video is unavailable") {
return { error: "content.video.unavailable" };
} else {
return { error: 'ErrorCantConnectToServiceAPI' };
return { error: "fetch.fail" };
}
}
if (!info) return { error: 'ErrorCantConnectToServiceAPI' };
if (!info) return { error: "fetch.fail" };
const playability = info.playability_status;
const basicInfo = info.basic_info;
if (playability.status === 'LOGIN_REQUIRED') {
if (playability.reason.endsWith('bot')) {
return { error: 'ErrorYTLogin' }
if (playability.status === "LOGIN_REQUIRED") {
if (playability.reason.endsWith("bot")) {
return { error: "youtube.login" }
}
if (playability.reason.endsWith('age')) {
return { error: 'ErrorYTAgeRestrict' }
if (playability.reason.endsWith("age")) {
return { error: "content.video.age" }
}
if (playability?.error_screen?.reason?.text === "Private video") {
return { error: "content.video.private" }
}
}
if (playability.status === "UNPLAYABLE" && playability.reason.endsWith('request limit.')) {
return { error: 'ErrorYTRateLimit' }
}
if (playability.status !== 'OK') return { error: 'ErrorYTUnavailable' };
if (basicInfo.is_live) return { error: 'ErrorLiveVideo' };
if (playability.status === "UNPLAYABLE") {
if (playability?.reason?.endsWith("request limit.")) {
return { error: "fetch.rate" }
}
if (playability?.error_screen?.subreason?.text?.endsWith("in your country")) {
return { error: "content.video.region" }
}
if (playability?.error_screen?.reason?.text === "Private video") {
return { error: "content.video.private" }
}
}
if (playability.status !== "OK") {
return { error: "content.video.unavailable" };
}
if (basicInfo.is_live) {
return { error: "content.video.live" };
}
// return a critical error if returned video is "Video Not Available"
// or a similar stub by youtube
if (basicInfo.id !== o.id) {
return {
error: 'ErrorCantConnectToServiceAPI',
error: "fetch.fail",
critical: true
}
}
let bestQuality, hasAudio;
const filterByCodec = (formats) =>
formats
.filter(e =>
@@ -183,16 +201,18 @@ export default async function(o) {
adaptive_formats = filterByCodec(info.streaming_data.adaptive_formats)
}
bestQuality = adaptive_formats.find(i => i.has_video && i.content_length);
hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
let bestQuality;
if (bestQuality) bestQuality = qual(bestQuality);
const bestVideo = adaptive_formats.find(i => i.has_video && i.content_length);
const hasAudio = adaptive_formats.find(i => i.has_audio && i.content_length);
if (bestVideo) bestQuality = qual(bestVideo);
if ((!bestQuality && !o.isAudioOnly) || !hasAudio)
return { error: 'ErrorYTTryOtherCodec' };
return { error: "youtube.codec" };
if (basicInfo.duration > env.durationLimit)
return { error: ['ErrorLengthLimit', env.durationLimit / 60] };
return { error: "content.too_long" };
const checkBestAudio = (i) => (i.has_audio && !i.has_video);
@@ -207,7 +227,7 @@ export default async function(o) {
&& i.audio_track
)
if (dubbedAudio) {
if (dubbedAudio && !dubbedAudio?.audio_track?.audio_is_default) {
audio = dubbedAudio;
isDubbed = true;
}
@@ -240,7 +260,7 @@ export default async function(o) {
}
if (audio && o.isAudioOnly) return {
type: "render",
type: "audio",
isAudioOnly: true,
urls: audio.decipher(yt.session.player),
filenameAttributes: filenameAttributes,
@@ -256,9 +276,10 @@ export default async function(o) {
let match, type, urls;
if (!o.isAudioOnly && !o.isAudioMuted && format === 'h264') {
// prefer good premuxed videos if available
if (!o.isAudioOnly && !o.isAudioMuted && format === "h264" && bestVideo.fps <= 30) {
match = info.streaming_data.formats.find(checkSingle);
type = "bridge";
type = "proxy";
urls = match?.decipher(yt.session.player);
}
@@ -266,7 +287,7 @@ export default async function(o) {
if (!match && video && audio) {
match = video;
type = "render";
type = "merge";
urls = [
video.decipher(yt.session.player),
audio.decipher(yt.session.player)
@@ -286,5 +307,5 @@ export default async function(o) {
}
}
return { error: 'ErrorYTTryOtherCodec' }
return { error: "fetch.fail" }
}

View File

@@ -1,6 +1,9 @@
import { services } from "../config.js";
import { strict as assert } from "node:assert";
import psl from "psl";
import { strict as assert } from "node:assert";
import { env } from "../config.js";
import { services } from "./service-config.js";
import { friendlyServiceName } from "./service-alias.js";
function aliasURL(url) {
assert(url instanceof URL);
@@ -54,6 +57,7 @@ function aliasURL(url) {
url = new URL(`https://bilibili.com/_tv${url.pathname}`);
}
break;
case "b23":
if (url.hostname === 'b23.tv' && parts.length === 2) {
url = new URL(`https://bilibili.com/_shortLink/${parts[1]}`)
@@ -64,6 +68,7 @@ function aliasURL(url) {
if (url.hostname === 'dai.ly' && parts.length === 2) {
url = new URL(`https://dailymotion.com/video/${parts[1]}`)
}
break;
case "facebook":
case "fb":
@@ -159,8 +164,12 @@ export function extract(url) {
const host = getHostIfValid(url);
if (!host || !services[host].enabled) {
return null;
if (!host) {
return { error: "link.invalid" };
}
if (!env.enabledServices.has(host)) {
return { error: "service.disabled" };
}
let patternMatch;
@@ -175,8 +184,13 @@ export function extract(url) {
}
if (!patternMatch) {
return null;
return {
error: "link.unsupported",
context: {
service: friendlyServiceName(host),
}
};
}
return { host, patternMatch };
}
}

59
api/src/security/jwt.js Normal file
View File

@@ -0,0 +1,59 @@
import { nanoid } from "nanoid";
import { createHmac } from "crypto";
import { env } from "../config.js";
const toBase64URL = (b) => Buffer.from(b).toString("base64url");
const fromBase64URL = (b) => Buffer.from(b, "base64url").toString();
const makeHmac = (header, payload) =>
createHmac("sha256", env.jwtSecret)
.update(`${header}.${payload}`)
.digest("base64url");
const generate = () => {
const exp = Math.floor(new Date().getTime() / 1000) + env.jwtLifetime;
const header = toBase64URL(JSON.stringify({
alg: "HS256",
typ: "JWT"
}));
const payload = toBase64URL(JSON.stringify({
jti: nanoid(8),
exp,
}));
const signature = makeHmac(header, payload);
return {
token: `${header}.${payload}.${signature}`,
exp: env.jwtLifetime - 2,
};
}
const verify = (jwt) => {
const [header, payload, signature] = jwt.split(".", 3);
const timestamp = Math.floor(new Date().getTime() / 1000);
if ([header, payload, signature].join('.') !== jwt) {
return false;
}
const verifySignature = makeHmac(header, payload);
if (verifySignature !== signature) {
return false;
}
if (timestamp >= JSON.parse(fromBase64URL(payload)).exp) {
return false;
}
return true;
}
export default {
generate,
verify,
}

View File

@@ -0,0 +1,19 @@
import { env } from "../config.js";
export const verifyTurnstileToken = async (turnstileResponse, ip) => {
const result = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
secret: env.turnstileSecret,
response: turnstileResponse,
remoteip: ip,
}),
})
.then(r => r.json())
.catch(() => {});
return !!result?.success;
}

View File

@@ -1,5 +1,5 @@
import { createInternalStream } from './manage.js';
import HLS from 'hls-parser';
import HLS from "hls-parser";
import { createInternalStream } from "./manage.js";
function getURL(url) {
try {

View File

@@ -1,7 +1,7 @@
import { request } from 'undici';
import { Readable } from 'node:stream';
import { closeRequest, getHeaders, pipe } from './shared.js';
import { handleHlsPlaylist, isHlsRequest } from './internal-hls.js';
import { request } from "undici";
import { Readable } from "node:stream";
import { closeRequest, getHeaders, pipe } from "./shared.js";
import { handleHlsPlaylist, isHlsRequest } from "./internal-hls.js";
const CHUNK_SIZE = BigInt(8e6); // 8 MB
const min = (a, b) => a < b ? a : b;
@@ -28,7 +28,7 @@ async function* readChunks(streamInfo, size) {
if (received < expected / 2n) {
closeRequest(streamInfo.controller);
}
for await (const data of chunk.body) {
yield data;
}
@@ -64,7 +64,7 @@ async function handleYoutubeStream(streamInfo, res) {
}
signal.addEventListener('abort', abortGenerator);
const stream = Readable.from(generator);
for (const headerName of ['content-type', 'content-length']) {
@@ -119,4 +119,4 @@ export function internalStream(streamInfo, res) {
}
return handleGenericStream(streamInfo, res);
}
}

View File

@@ -1,12 +1,13 @@
import NodeCache from "node-cache";
import { randomBytes } from "crypto";
import { nanoid } from "nanoid";
import { randomBytes } from "crypto";
import { strict as assert } from "assert";
import { setMaxListeners } from "node:events";
import { decryptStream, encryptStream, generateHmac } from "../sub/crypto.js";
import { env } from "../config.js";
import { strict as assert } from "assert";
import { closeRequest } from "./shared.js";
import { decryptStream, encryptStream, generateHmac } from "../misc/crypto.js";
// optional dependency
const freebind = env.freebindCIDR && await import('freebind').catch(() => {});
@@ -21,7 +22,7 @@ streamCache.on("expired", (key) => {
streamCache.del(key);
})
const internalStreamCache = {};
const internalStreamCache = new Map();
const hmacSalt = randomBytes(64).toString('hex');
export function createStream(obj) {
@@ -36,13 +37,15 @@ export function createStream(obj) {
urls: obj.u,
service: obj.service,
filename: obj.filename,
audioFormat: obj.audioFormat,
isAudioOnly: !!obj.isAudioOnly,
requestIP: obj.requestIP,
headers: obj.headers,
copy: !!obj.copy,
mute: !!obj.mute,
metadata: obj.fileMetadata || false,
requestIP: obj.requestIP
audioBitrate: obj.audioBitrate,
audioCopy: !!obj.audioCopy,
audioFormat: obj.audioFormat,
};
streamCache.set(
@@ -50,7 +53,7 @@ export function createStream(obj) {
encryptStream(streamData, iv, secret)
)
let streamLink = new URL('/api/stream', env.apiURL);
let streamLink = new URL('/tunnel', env.apiURL);
const params = {
'id': streamID,
@@ -68,7 +71,7 @@ export function createStream(obj) {
}
export function getInternalStream(id) {
return internalStreamCache[id];
return internalStreamCache.get(id);
}
export function createInternalStream(url, obj = {}) {
@@ -83,7 +86,7 @@ export function createInternalStream(url, obj = {}) {
let controller = obj.controller;
if (!controller) {
controller = new AbortController();
controller = new AbortController();
setMaxListeners(Infinity, controller.signal);
}
@@ -92,15 +95,15 @@ export function createInternalStream(url, obj = {}) {
headers = new Map(Object.entries(obj.headers));
}
internalStreamCache[streamID] = {
internalStreamCache.set(streamID, {
url,
service: obj.service,
headers,
controller,
dispatcher
};
});
let streamLink = new URL('/api/istream', `http://127.0.0.1:${env.apiPort}`);
let streamLink = new URL('/itunnel', `http://127.0.0.1:${env.apiPort}`);
streamLink.searchParams.set('id', streamID);
const cleanup = () => {
@@ -121,9 +124,9 @@ export function destroyInternalStream(url) {
const id = url.searchParams.get('id');
if (internalStreamCache[id]) {
closeRequest(internalStreamCache[id].controller);
delete internalStreamCache[id];
if (internalStreamCache.has(id)) {
closeRequest(getInternalStream(id)?.controller);
internalStreamCache.delete(id);
}
}

View File

@@ -42,4 +42,4 @@ export function pipe(from, to, done) {
.on('close', done);
from.pipe(to);
}
}

33
api/src/stream/stream.js Normal file
View File

@@ -0,0 +1,33 @@
import stream from "./types.js";
import { closeResponse } from "./shared.js";
import { internalStream } from "./internal.js";
export default async function(res, streamInfo) {
try {
switch (streamInfo.type) {
case "proxy":
return await stream.proxy(streamInfo, res);
case "internal":
return internalStream(streamInfo, res);
case "merge":
return stream.merge(streamInfo, res);
case "remux":
case "mute":
return stream.remux(streamInfo, res);
case "audio":
return stream.convertAudio(streamInfo, res);
case "gif":
return stream.convertGif(streamInfo, res);
}
closeResponse(res);
} catch {
closeResponse(res);
}
}

View File

@@ -3,35 +3,42 @@ import ffmpeg from "ffmpeg-static";
import { spawn } from "child_process";
import { create as contentDisposition } from "content-disposition-header";
import { metadataManager } from "../sub/utils.js";
import { env } from "../config.js";
import { metadataManager } from "../misc/utils.js";
import { destroyInternalStream } from "./manage.js";
import { env, ffmpegArgs, hlsExceptions } from "../config.js";
import { hlsExceptions } from "../processing/service-config.js";
import { getHeaders, closeRequest, closeResponse, pipe } from "./shared.js";
function toRawHeaders(headers) {
const ffmpegArgs = {
webm: ["-c:v", "copy", "-c:a", "copy"],
mp4: ["-c:v", "copy", "-c:a", "copy", "-movflags", "faststart+frag_keyframe+empty_moov"],
m4a: ["-movflags", "frag_keyframe+empty_moov"],
gif: ["-vf", "scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", "-loop", "0"]
}
const toRawHeaders = (headers) => {
return Object.entries(headers)
.map(([key, value]) => `${key}: ${value}\r\n`)
.join('');
}
function killProcess(p) {
// ask the process to terminate itself gracefully
p?.kill('SIGTERM');
const killProcess = (p) => {
p?.kill('SIGTERM'); // ask the process to terminate itself gracefully
setTimeout(() => {
if (p?.exitCode === null)
// brutally murder the process if it didn't quit
p?.kill('SIGKILL');
p?.kill('SIGKILL'); // brutally murder the process if it didn't quit
}, 5000);
}
function getCommand(args) {
const getCommand = (args) => {
if (typeof env.processingPriority === 'number' && !isNaN(env.processingPriority)) {
return ['nice', ['-n', env.processingPriority.toString(), ffmpeg, ...args]]
}
return [ffmpeg, args]
}
export async function streamDefault(streamInfo, res) {
const proxy = async (streamInfo, res) => {
const abortController = new AbortController();
const shutdown = () => (
closeRequest(abortController),
@@ -40,19 +47,21 @@ export async function streamDefault(streamInfo, res) {
);
try {
let filename = streamInfo.filename;
if (streamInfo.isAudioOnly) {
filename = `${streamInfo.filename}.${streamInfo.audioFormat}`
}
res.setHeader('Content-disposition', contentDisposition(filename));
res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
res.setHeader('Content-disposition', contentDisposition(streamInfo.filename));
const { body: stream, headers } = await request(streamInfo.urls, {
headers: getHeaders(streamInfo.service),
const { body: stream, headers, statusCode } = await request(streamInfo.urls, {
headers: {
...getHeaders(streamInfo.service),
Range: streamInfo.range
},
signal: abortController.signal,
maxRedirections: 16
});
for (const headerName of ['content-type', 'content-length']) {
res.status(statusCode);
for (const headerName of ['accept-ranges', 'content-type', 'content-length']) {
if (headers[headerName]) {
res.setHeader(headerName, headers[headerName]);
}
@@ -64,7 +73,7 @@ export async function streamDefault(streamInfo, res) {
}
}
export function streamLiveRender(streamInfo, res) {
const merge = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
@@ -124,61 +133,7 @@ export function streamLiveRender(streamInfo, res) {
}
}
export function streamAudioOnly(streamInfo, res) {
let process;
const shutdown = () => (
killProcess(process),
closeResponse(res),
destroyInternalStream(streamInfo.urls)
);
try {
let args = [
'-loglevel', '-8',
'-headers', toRawHeaders(getHeaders(streamInfo.service)),
]
if (streamInfo.service === "twitter") {
args.push('-seekable', '0');
}
args.push(
'-i', streamInfo.urls,
'-vn'
)
if (streamInfo.metadata) {
args = args.concat(metadataManager(streamInfo.metadata))
}
args = args.concat(ffmpegArgs[streamInfo.copy ? 'copy' : 'audio']);
if (ffmpegArgs[streamInfo.audioFormat]) {
args = args.concat(ffmpegArgs[streamInfo.audioFormat])
}
args.push('-f', streamInfo.audioFormat === "m4a" ? "ipod" : streamInfo.audioFormat, 'pipe:3');
process = spawn(...getCommand(args), {
windowsHide: true,
stdio: [
'inherit', 'inherit', 'inherit',
'pipe'
],
});
const [,,, muxOutput] = process.stdio;
res.setHeader('Connection', 'keep-alive');
res.setHeader('Content-Disposition', contentDisposition(`${streamInfo.filename}.${streamInfo.audioFormat}`));
pipe(muxOutput, res, shutdown);
res.on('finish', shutdown);
} catch {
shutdown();
}
}
export function streamVideoOnly(streamInfo, res) {
const remux = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
@@ -198,15 +153,18 @@ export function streamVideoOnly(streamInfo, res) {
args.push(
'-i', streamInfo.urls,
'-c', 'copy'
'-c:v', 'copy',
)
if (streamInfo.mute) {
args.push('-an')
if (streamInfo.type === "mute") {
args.push('-an');
}
if (hlsExceptions.includes(streamInfo.service)) {
args.push('-bsf:a', 'aac_adtstoasc')
if (streamInfo.type !== "mute") {
args.push('-c:a', 'aac')
}
args.push('-bsf:a', 'aac_adtstoasc');
}
let format = streamInfo.filename.split('.')[streamInfo.filename.split('.').length - 1];
@@ -238,7 +196,74 @@ export function streamVideoOnly(streamInfo, res) {
}
}
export function convertToGif(streamInfo, res) {
const convertAudio = (streamInfo, res) => {
let process;
const shutdown = () => (
killProcess(process),
closeResponse(res),
destroyInternalStream(streamInfo.urls)
);
try {
let args = [
'-loglevel', '-8',
'-headers', toRawHeaders(getHeaders(streamInfo.service)),
]
if (streamInfo.service === "twitter") {
args.push('-seekable', '0');
}
args.push(
'-i', streamInfo.urls,
'-vn'
)
if (streamInfo.audioCopy) {
args.push("-c:a", "copy")
} else {
args.push("-b:a", `${streamInfo.audioBitrate}k`)
}
if (streamInfo.audioFormat === "mp3" && streamInfo.audioBitrate === "8") {
args.push("-ar", "12000");
}
if (streamInfo.audioFormat === "opus") {
args.push("-vbr", "off")
}
if (ffmpegArgs[streamInfo.audioFormat]) {
args = args.concat(ffmpegArgs[streamInfo.audioFormat])
}
if (streamInfo.metadata) {
args = args.concat(metadataManager(streamInfo.metadata))
}
args.push('-f', streamInfo.audioFormat === "m4a" ? "ipod" : streamInfo.audioFormat, 'pipe:3');
process = spawn(...getCommand(args), {
windowsHide: true,
stdio: [
'inherit', 'inherit', 'inherit',
'pipe'
],
});
const [,,, muxOutput] = process.stdio;
res.setHeader('Connection', 'keep-alive');
res.setHeader('Content-Disposition', contentDisposition(streamInfo.filename));
pipe(muxOutput, res, shutdown);
res.on('finish', shutdown);
} catch {
shutdown();
}
}
const convertGif = (streamInfo, res) => {
let process;
const shutdown = () => (killProcess(process), closeResponse(res));
@@ -252,7 +277,7 @@ export function convertToGif(streamInfo, res) {
}
args.push('-i', streamInfo.urls);
args = args.concat(ffmpegArgs["gif"]);
args = args.concat(ffmpegArgs.gif);
args.push('-f', "gif", 'pipe:3');
process = spawn(...getCommand(args), {
@@ -276,3 +301,11 @@ export function convertToGif(streamInfo, res) {
shutdown();
}
}
export default {
proxy,
merge,
remux,
convertAudio,
convertGif,
}

View File

@@ -1,5 +1,5 @@
import { Innertube } from 'youtubei.js';
import { Red } from '../modules/sub/consoleText.js'
import { Red } from '../misc/console-text.js'
const bail = (...msg) => {
console.error(...msg);

View File

@@ -1,7 +1,7 @@
import { existsSync, unlinkSync, appendFileSync } from "fs";
import { createInterface } from "readline";
import { Cyan, Bright } from "./sub/consoleText.js";
import { loadJSON } from "./sub/loadFromFs.js";
import { Cyan, Bright } from "./misc/console-text.js";
import { loadJSON } from "./misc/load-from-fs.js";
import { execSync } from "child_process";
const { version } = loadJSON("./package.json");

View File

@@ -1,20 +1,21 @@
import { env } from "../modules/config.js";
import { runTest } from "../modules/test.js";
import { loadLoc } from "../localization/manager.js";
import { loadJSON } from "../modules/sub/loadFromFs.js";
import { Red, Bright } from "../modules/sub/consoleText.js";
import { env } from "../config.js";
import { runTest } from "../misc/run-test.js";
import { loadJSON } from "../misc/load-from-fs.js";
import { Red, Bright } from "../misc/console-text.js";
import { randomizeCiphers } from "../misc/randomize-ciphers.js";
import { services } from "../processing/service-config.js";
const tests = loadJSON('./src/util/tests.json');
const services = loadJSON('./src/modules/processing/servicesConfig.json');
// services that are known to frequently fail due to external
// factors (e.g. rate limiting)
const finnicky = new Set(['bilibili', 'instagram', 'youtube'])
const finnicky = new Set(['bilibili', 'instagram', 'facebook', 'youtube'])
const action = process.argv[2];
switch (action) {
case "get-services":
const fromConfig = Object.keys(services.config);
const fromConfig = Object.keys(services);
const missingTests = fromConfig.filter(
service => !tests[service] || tests[service].length === 0
@@ -38,9 +39,9 @@ switch (action) {
console.error('no such service:', service);
}
await loadLoc();
env.streamLifespan = 10000;
env.apiURL = 'http://x';
randomizeCiphers();
for (const test of tests[service]) {
const { name, url, params, expected } = test;
@@ -78,4 +79,4 @@ switch (action) {
default:
console.error('invalid action:', action);
process.exitCode = 1;
}
}

View File

@@ -1,12 +1,11 @@
import "dotenv/config";
import "../modules/sub/alias-envs.js";
import { services } from "../modules/config.js";
import { extract } from "../modules/processing/url.js";
import match from "../modules/processing/match.js";
import { loadJSON } from "../modules/sub/loadFromFs.js";
import { normalizeRequest } from "../modules/processing/request.js";
import { env } from "../modules/config.js";
import { services } from "../processing/service-config.js";
import { extract } from "../processing/url.js";
import match from "../processing/match.js";
import { loadJSON } from "../misc/load-from-fs.js";
import { normalizeRequest } from "../processing/request.js";
import { env } from "../config.js";
env.apiURL = 'http://localhost:9000'
let tests = loadJSON('./src/util/tests.json');
@@ -29,20 +28,26 @@ for (let i in services) {
console.log(`\nRunning tests for ${i}...\n`)
for (let k = 0; k < tests[i].length; k++) {
let test = tests[i][k];
console.log(`Running test ${k+1}: ${test.name}`);
console.log('params:');
let params = {...{url: test.url}, ...test.params};
console.log(params);
let chck = normalizeRequest(params);
if (chck) {
let chck = await normalizeRequest(params);
if (chck.success) {
chck = chck.data;
const parsed = extract(chck.url);
if (parsed === null) {
throw `Invalid URL: ${chck.url}`
}
let j = await match(parsed.host, parsed.patternMatch, "en", chck);
let j = await match({
host: parsed.host,
patternMatch: parsed.patternMatch,
params: chck,
});
console.log('\nReceived:');
console.log(j)
if (j.status === test.expected.code && j.body.status === test.expected.status) {

1461
api/src/util/tests.json Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,77 +1,110 @@
# cobalt api documentation
this document provides info about methods and acceptable variables for all cobalt api requests.
this document provides info about methods and acceptable variables for all cobalt api requests.
> if you are looking for the documentation for the old (7.x) api, you can find
> it [here](https://github.com/imputnet/cobalt/blob/7/docs/api.md)
<!-- TODO: authorization -->
## POST: `/`
cobalt's main processing endpoint.
request body type: `application/json`
response body type: `application/json`
```
👍 you can use api.cobalt.tools in your projects for free, just don't be an asshole.
```
## POST: `/api/json`
cobalt's main processing endpoint.
request body type: `application/json`
response body type: `application/json`
```
⚠️ you must include Accept and Content-Type headers with every POST /api/json request.
⚠️ you must include Accept and Content-Type headers with every `POST /` request.
Accept: application/json
Content-Type: application/json
```
### request body variables
| key | type | variables | default | description |
|:------------------|:----------|:-----------------------------------|:----------|:--------------------------------------------------------------------------------|
| `url` | `string` | URL encoded as URI | `null` | **must** be included in every request. |
| `vCodec` | `string` | `h264 / av1 / vp9` | `h264` | applies only to youtube downloads. `h264` is recommended for phones. |
| `vQuality` | `string` | `144 / ... / 2160 / max` | `720` | `720` quality is recommended for phones. |
| `aFormat` | `string` | `best / mp3 / ogg / wav / opus` | `mp3` | |
| `filenamePattern` | `string` | `classic / pretty / basic / nerdy` | `classic` | changes the way files are named. previews can be seen in the web app. |
| `isAudioOnly` | `boolean` | `true / false` | `false` | |
| `isTTFullAudio` | `boolean` | `true / false` | `false` | enables download of original sound used in a tiktok video. |
| `isAudioMuted` | `boolean` | `true / false` | `false` | disables audio track in video downloads. |
| `dubLang` | `boolean` | `true / false` | `false` | backend uses Accept-Language header for youtube video audio tracks when `true`. |
| `disableMetadata` | `boolean` | `true / false` | `false` | disables file metadata when set to `true`. |
| `twitterGif` | `boolean` | `true / false` | `false` | changes whether twitter gifs are converted to .gif |
| `tiktokH265` | `boolean` | `true / false` | `false` | changes whether 1080p h265 videos are preferred or not. |
### request body
| key | type | expected value(s) | default | description |
|:-----------------------------|:----------|:-----------------------------------|:----------|:--------------------------------------------------------------------------------|
| `url` | `string` | URL to download | -- | **must** be included in every request. |
| `videoQuality` | `string` | `144 / ... / 2160 / 4320 / max` | `1080` | `720` quality is recommended for phones. |
| `audioFormat` | `string` | `best / mp3 / ogg / wav / opus` | `mp3` | |
| `audioBitrate` | `string` | `320 / 256 / 128 / 96 / 64 / 8` | `128` | specifies the bitrate to use for the audio. applies only to audio conversion. |
| `filenameStyle` | `string` | `classic / pretty / basic / nerdy` | `classic` | changes the way files are named. previews can be seen in the web app. |
| `downloadMode` | `string` | `auto / audio / mute` | `auto` | `audio` downloads only the audio, `mute` skips the audio track in videos. |
| `youtubeVideoCodec` | `string` | `h264 / av1 / vp9` | `h264` | `h264` is recommended for phones. |
| `youtubeDubLang` | `string` | `en / ru / cs / ja / ...` | -- | specifies the language of audio to download, when the youtube video is dubbed |
| `youtubeDubBrowserLang` | `boolean` | `true / false` | `false` | uses value from the Accept-Language header for `youtubeDubLang`. |
| `alwaysProxy` | `boolean` | `true / false` | `false` | tunnels all downloads through the processing server, even when not necessary. |
| `disableMetadata` | `boolean` | `true / false` | `false` | disables file metadata when set to `true`. |
| `tiktokFullAudio` | `boolean` | `true / false` | `false` | enables download of original sound used in a tiktok video. |
| `tiktokH265` | `boolean` | `true / false` | `false` | changes whether 1080p h265 videos are preferred or not. |
| `twitterGif` | `boolean` | `true / false` | `true` | changes whether twitter gifs are converted to .gif |
### response body variables
| key | type | variables |
### response
the response will always be a JSON object containing the `status` key, which will be one of:
- `error` - something went wrong
- `picker` - we have multiple items to choose from
- `redirect` - you are being redirected to the direct service URL
- `tunnel` - cobalt is proxying the download for you
### tunnel/redirect response
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `status` | `string` | `error / redirect / stream / success / rate-limit / picker` |
| `text` | `string` | various text, mostly used for errors |
| `url` | `string` | direct link to a file or a link to cobalt's live render |
| `pickerType` | `string` | `various / images` |
| `picker` | `array` | array of picker items |
| `audio` | `string` | direct link to a file or a link to cobalt's live render |
| `status` | `string` | `tunnel / redirect` |
| `url` | `string` | url for the cobalt tunnel, or redirect to an external link |
| `filename` | `string` | cobalt-generated filename for the file being downloaded |
### picker item variables
item type: `object`
### picker response
| key | type | values |
|:----------------|:---------|:-------------------------------------------------------------------------------------------------|
| `status` | `string` | `picker` |
| `audio` | `string` | **optional** returned when an image slideshow (such as on tiktok) has a general background audio |
| `audioFilename` | `string` | **optional** cobalt-generated filename, returned if `audio` exists |
| `picker` | `array` | array of objects containing the individual media |
| key | type | variables | description |
|:--------|:---------|:--------------------------------------------------------|:---------------------------------------|
| `type` | `string` | `video / photo / gif` | used only if `pickerType` is `various` |
| `url` | `string` | direct link to a file or a link to cobalt's live render | |
| `thumb` | `string` | item thumbnail that's displayed in the picker | used for `video` and `gif` types |
#### picker object
| key | type | values |
|:-------------|:----------|:------------------------------------------------------------|
| `type` | `string` | `photo` / `video` / `gif` |
| `url` | `string` | |
| `thumb` | `string` | **optional** thumbnail url |
## GET: `/api/stream`
cobalt's live render (or stream) endpoint. usually, you will receive a url to this endpoint
from a successful call to `/api/json`. however, the parameters passed to it are **opaque**
and **unmodifiable** from your (the api client's) perspective, and can change between versions.
### error response
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `status` | `string` | `error` |
| `error` | `object` | contains more context about the error |
therefore you don't need to worry about what they mean - but if you really want to know, you can
[read the source code](/src/modules/stream/manage.js).
#### error object
| key | type | values |
|:-------------|:---------|:------------------------------------------------------------|
| `code` | `string` | machine-readable error code explaining the failure reason |
| `context` | `object` | **optional** container for providing more context |
## GET: `/api/serverInfo`
returns current basic server info.
#### error.context object
| key | type | values |
|:-------------|:---------|:---------------------------------------------------------------------------------------------------------------|
| `service` | `string` | **optional**, stating which service was being downloaded from |
| `limit` | `number` | **optional** number providing the ratelimit maximum number of requests, or maximum downloadable video duration |
## GET: `/`
returns current basic server info.
response body type: `application/json`
### response body variables
### response body
| key | type | variables |
|:------------|:---------|:---------------------------------------------------------|
| `cobalt` | `object` | information about the cobalt instance |
| `git` | `object` | information about the codebase that is currently running |
#### cobalt object
| key | type | description |
|:----------------|:-----------|:-----------------------------------------------|
| `version` | `string` | current version |
| `url` | `string` | server url |
| `startTime` | `string` | server start time in unix milliseconds |
| `durationLimit` | `number` | maximum downloadable video length in seconds |
| `services` | `string[]` | array of services which this instance supports |
#### git object
| key | type | variables |
|:------------|:---------|:------------------|
| `version` | `string` | cobalt version |
| `commit` | `string` | git commit |
| `commit` | `string` | commit hash |
| `branch` | `string` | git branch |
| `name` | `string` | server name |
| `url` | `string` | server url |
| `cors` | `number` | cors status |
| `startTime` | `string` | server start time |
| `remote` | `string` | git remote |

View File

@@ -1,16 +1,11 @@
version: '3.5'
services:
cobalt-api:
image: ghcr.io/imputnet/cobalt:7
image: ghcr.io/imputnet/cobalt:10
restart: unless-stopped
container_name: cobalt-api
init: true
# if container doesn't run detached on your machine, uncomment the next line
#tty: true
ports:
- 9000:9000/tcp
# if you're using a reverse proxy, uncomment the next line and remove the one above (9000:9000/tcp):
@@ -19,8 +14,6 @@ services:
environment:
# replace https://api.cobalt.tools/ with your instance's target url in same format
API_URL: "https://api.cobalt.tools/"
# replace eu-nl with your instance's distinctive name
API_NAME: "eu-nl"
# if you want to use cookies when fetching data from services, uncomment the next line and the lines under volume
# COOKIE_PATH: "/cookies.json"
# see docs/run-an-instance.md for more information
@@ -31,30 +24,6 @@ services:
#volumes:
#- ./cookies.json:/cookies.json
cobalt-web:
image: ghcr.io/imputnet/cobalt:7
restart: unless-stopped
container_name: cobalt-web
init: true
# if container doesn't run detached on your machine, uncomment the next line
#tty: true
ports:
- 9001:9001/tcp
# if you're using a reverse proxy, uncomment the next line and remove the one above (9001:9001/tcp):
#- 127.0.0.1:9001:9001
environment:
# replace https://cobalt.tools/ with your instance's target url in same format
WEB_URL: "https://cobalt.tools/"
# replace https://api.cobalt.tools/ with preferred api instance url
API_URL: "https://api.cobalt.tools/"
labels:
- com.centurylinklabs.watchtower.scope=cobalt
# update the cobalt image automatically with watchtower
watchtower:
image: ghcr.io/containrrr/watchtower

View File

@@ -6,20 +6,20 @@ if you need help with installing docker, follow *only the first step* of these t
- [how to install docker](https://www.digitalocean.com/community/tutorial-collections/how-to-install-and-use-docker)
- [how to install docker compose](https://www.digitalocean.com/community/tutorial-collections/how-to-install-docker-compose)
## how to run a cobalt docker package:
1. create a folder for cobalt config file, something like this:
## how to run a cobalt docker package:
1. create a folder for cobalt config file, something like this:
```sh
mkdir cobalt
```
```
2. go to cobalt folder, and create a docker compose config file:
2. go to cobalt folder, and create a docker compose config file:
```sh
cd cobalt && nano docker-compose.yml
```
i'm using `nano` in this example, it may not be available in your distro. you can use any other text editor.
```
i'm using `nano` in this example, it may not be available in your distro. you can use any other text editor.
3. copy and paste the [sample config from here](examples/docker-compose.example.yml) for either web or api instance (or both, if you wish) and edit it to your needs.
make sure to replace default URLs with your own or cobalt won't work correctly.
3. copy and paste the [sample config from here](examples/docker-compose.example.yml) for either web or api instance (or both, if you wish) and edit it to your needs.
make sure to replace default URLs with your own or cobalt won't work correctly.
4. finally, start the cobalt container (from cobalt directory):
```sh
@@ -72,16 +72,4 @@ sudo service nscd start
setting a `FREEBIND_CIDR` allows cobalt to pick a random IP for every download and use it for all
requests it makes for that particular download. to use freebind in cobalt, you need to follow its [setup instructions](https://github.com/imputnet/freebind.js?tab=readme-ov-file#setup) first. if you configure this option while running cobalt
in a docker container, you also need to set the `API_LISTEN_ADDRESS` env to `127.0.0.1`, and set
`network_mode` for the container to `host`.
### variables for web
| variable name | default | example | description |
|:---------------------|:----------------------------|:----------------------------|:--------------------------------------------------------------------------------------|
| `WEB_PORT` | `9001` | `9001` | changes port from which frontend server is accessible. |
| `WEB_URL` | | `https://cobalt.tools/` | changes url from which frontend server is accessible. <br> ***REQUIRED TO RUN WEB***. |
| `API_URL` | `https://api.cobalt.tools/` | `https://api.cobalt.tools/` | changes url which is used for api requests by frontend clients. |
| `SHOW_SPONSORS` | `0` | `1` | toggles sponsor list in about popup. <br> `0`: disabled. `1`: enabled. |
| `IS_BETA` | `0` | `1` | toggles beta tag next to cobalt logo. <br> `0`: disabled. `1`: enabled. |
| `PLAUSIBLE_HOSTNAME` | | `plausible.io`* | enables plausible analytics with provided hostname as receiver backend. |
\* don't use plausible.io as receiver backend unless you paid for their cloud service. use your own domain when hosting community edition of plausible. refer to their [docs](https://plausible.io/docs) when needed.
`network_mode` for the container to `host`.

1142
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,48 +1,7 @@
{
"name": "cobalt",
"description": "save what you love",
"version": "7.15",
"author": "imput",
"exports": "./src/cobalt.js",
"type": "module",
"packageManager": "pnpm@9.6.0",
"engines": {
"node": ">=18"
},
"scripts": {
"start": "node src/cobalt",
"setup": "node src/modules/setup",
"test": "node src/util/test",
"build": "node src/modules/buildStatic",
"token:youtube": "node src/util/generate-youtube-tokens"
},
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme",
"dependencies": {
"content-disposition-header": "0.6.0",
"cors": "^2.8.5",
"dotenv": "^16.0.1",
"esbuild": "^0.14.51",
"express": "^4.18.1",
"express-rate-limit": "^6.3.0",
"ffmpeg-static": "^5.1.0",
"hls-parser": "^0.10.7",
"ipaddr.js": "2.1.0",
"nanoid": "^4.0.2",
"node-cache": "^5.1.2",
"psl": "1.9.0",
"set-cookie-parser": "2.6.0",
"undici": "^5.19.1",
"url-pattern": "1.0.3",
"youtubei.js": "^10.3.0"
},
"optionalDependencies": {
"freebind": "^0.2.2"
"pnpm": ">=9"
}
}
}

1
packages/api-client/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
dist

View File

@@ -0,0 +1,2 @@
# Ignore artifacts:
dist

View File

@@ -0,0 +1,6 @@
{
"tabWidth": 4,
"singleQuote": true,
"trailingComma": "none",
"arrowParens": "avoid"
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2024 imput
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,43 @@
{
"api.auth.jwt.missing": "couldn't confirm whether you're not a robot because the processing server didn't receive the human access token. try again in a few seconds or reload the page!",
"api.auth.jwt.invalid": "couldn't confirm whether you're not a robot because your human access token expired and wasn't renewed. try again in a few seconds or reload the page!",
"api.auth.turnstile.missing": "couldn't confirm whether you're not a robot because the processing server didn't receive the human access token. try again in a few seconds or reload the page!",
"api.auth.turnstile.invalid": "couldn't confirm whether you're not a robot because your human access token expired and wasn't renewed. try again in a few seconds or reload the page!",
"api.unreachable": "couldn't connect to the processing server. check your internet connection and try again.",
"api.timed_out": "the processing server took way too long to respond. it may be overwhelmed at the moment, try again in a few seconds!",
"api.rate_exceeded": "you're making way too many requests. try again in {{ limit }} seconds!",
"api.capacity": "cobalt is at capacity and can't process your request at the moment. try again in a few seconds. if it still doesn't work, let us know and we'll try to help!",
"api.generic": "something went wrong and i couldn't get anything for you. try again in a few seconds, but if issue sticks, let us know and we'll try to help!",
"api.unknown_response": "couldn't parse the response from the server. this could be caused by a version mismatch. are you sure you're on the latest version of cobalt?",
"api.service.unsupported": "this service is not supported yet. have you pasted the right link?",
"api.service.disabled": "this service is supported by cobalt, but it's disabled on this instance. try a link from another service!",
"api.link.invalid": "your link is invalid or this service is not supported yet. have you pasted the right link?",
"api.link.unsupported": "{{ service }} is supported, but i couldn't recognize your link. have you pasted the right one?",
"api.fetch.fail": "something went wrong when fetching info from {{ service }} and i couldn't find anything for you. are you sure your link works? if it does and you still see this error, let us know and we'll try to help!",
"api.fetch.critical": "the {{ service }} module returned an error that i don't recognize. try again in a few seconds, but if issue sticks, let us know!",
"api.fetch.empty": "couldn't find any media that i could download for you. are you sure you pasted the right link?",
"api.fetch.rate": "the cobalt processing server got rate limited by the {{ service }} api. try again in a few seconds!",
"api.fetch.short_link": "couldn't get link info from the short link. are you sure it works? if it does and you still get this error, let us know, and we'll try to help!",
"api.content.too_long": "the media you requested is too long. current duration limit is {{ limit }} minutes. try something shorter instead!",
"api.content.video.unavailable": "i can't access this video. it may be restricted on {{ service }}'s side. have you pasted the right link?",
"api.content.video.live": "this video is currently live, so i can't download it yet. wait for the livestream to finish, and then try again!",
"api.content.video.private": "this video is private, so i cannot access it. change its visibility or try another one!",
"api.content.video.age": "this video is age-restricted, so i can't access it anonymously. try another one!",
"api.content.video.region": "this video is region locked, and the processing server is in a different location. try another one!",
"api.content.post.unavailable": "couldn't find anything about this post. its visibility may be limited or it may not exist at all. make sure your link works and try again in a few seconds!",
"api.content.post.private": "this post is from a private account, so i can't access it. have you pasted the right link?",
"api.content.post.age": "this post is age-restricted, so i can't access it anonymously. have you pasted the right link?",
"api.youtube.codec": "youtube didn't return anything with your preferred codec & resolution. try another set of settings!",
"api.youtube.decipher": "youtube updated its decipher algorithm and i couldn't extract the info about the video.\n\ntry again in a few seconds, but if issue sticks, contact us for support.",
"api.youtube.login": "couldn't get this video because youtube labeled me as a bot. this is potentially caused by the processing instance not having any active account tokens. try again in a few seconds, but if it still doesn't work, tell the instance owner about this error!",
"api.youtube.token_expired": "couldn't get this video because the youtube token expired and i couldn't refresh it. try again in a few seconds, but if it still doesn't work, tell the instance owner about this error!"
}

View File

@@ -0,0 +1,36 @@
{
"name": "@imput/cobalt-client",
"version": "0.0.1",
"description": "",
"main": "index.js",
"scripts": {
"build": "tsup",
"dev": "tsup --watch"
},
"keywords": [],
"author": "imput <meow@imput.net>",
"license": "MIT",
"devDependencies": {
"prettier": "3.3.3",
"tsup": "^8.2.4",
"turnstile-types": "^1.2.2",
"typescript": "^5.4.5",
"zod": "^3.23.8"
},
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js",
"require": "./dist/index.cjs"
}
},
"tsup": {
"dts": true,
"bundle": false,
"treeshake": true,
"target": "node18",
"format": ["esm", "cjs"],
"entry": ["src/**/*.ts"]
}
}

View File

@@ -0,0 +1,3 @@
export * from "./turnstile-api";
export * from "./unauthenticated-api";
export * from "./types/interface";

View File

@@ -0,0 +1,53 @@
import { CobaltResponseType, type CobaltResponse } from "../types/response";
import { CobaltReachabilityError } from "../types/errors";
import type { CobaltRequest } from "../types/request";
import { CobaltAPIClient } from "../types/interface";
export default class CobaltAPI implements CobaltAPIClient {
#baseURL: string | undefined;
getBaseURL() {
return this.#baseURL;
}
setBaseURL(baseURL: string) {
const url = new URL(baseURL);
if (baseURL !== url.origin && baseURL !== `${url.origin}/`) {
throw new Error('Invalid cobalt instance URL');
}
return this.#baseURL = url.origin;
}
async request(data: CobaltRequest, headers?: Record<string, string>) {
const baseURL = this.getBaseURL();
if (!baseURL) throw "baseURL is undefined";
const response: CobaltResponse = await fetch(baseURL, {
method: 'POST',
redirect: 'manual',
signal: AbortSignal.timeout(10000),
body: JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
...headers
}
})
.then(r => r.json())
.catch((e) => {
const timedOut = e?.message?.includes("timed out");
return {
status: CobaltResponseType.Error,
error: {
code: timedOut
? CobaltReachabilityError.TimedOut
: CobaltReachabilityError.Unreachable
}
};
});
return response;
}
};

View File

@@ -0,0 +1,72 @@
import { CobaltSession, CobaltResponseType, CobaltSessionResponse } from "../types/response";
import { CobaltReachabilityError } from "../types/errors";
import type { TurnstileObject } from "turnstile-types";
import { CobaltAPIClient } from "../types/interface";
const currentTime = () => Math.floor(new Date().getTime() / 1000);
const EXPIRY_THRESHOLD_SECONDS = 2;
export default class CobaltSessionHandler {
#client: CobaltAPIClient;
#turnstile: TurnstileObject;
#session: CobaltSession | undefined;
constructor(client: CobaltAPIClient, turnstile: TurnstileObject) {
this.#client = client;
this.#turnstile = turnstile;
}
async #requestSession(): Promise<CobaltSessionResponse> {
const baseURL = this.#client.getBaseURL();
if (!baseURL) throw "baseURL is undefined";
const endpoint = new URL('/session', baseURL);
const response = await fetch(endpoint, {
method: 'POST',
redirect: 'manual',
signal: AbortSignal.timeout(10000),
headers: {
'cf-turnstile-response': this.#turnstile.getResponse('#turnstile-widget')
}
})
.then(r => r.json())
.catch((e) => {
const timedOut = e?.message?.includes("timed out");
return {
status: CobaltResponseType.Error,
error: {
code: timedOut
? CobaltReachabilityError.TimedOut
: CobaltReachabilityError.Unreachable
}
};
});
if ('token' in response && 'exp' in response) {
this.#session = {
token: response.token,
exp: currentTime() + response.exp
}
}
this.#turnstile.reset('#turnstile-widget');
return response;
}
hasSession() {
return this.#session && this.#session.exp - EXPIRY_THRESHOLD_SECONDS > currentTime();
}
reset() {
this.#session = undefined;
}
async getSession(): Promise<CobaltSessionResponse> {
if (this.hasSession()) {
return this.#session!;
}
return this.#requestSession();
}
};

View File

@@ -0,0 +1,47 @@
import CobaltSessionHandler from "./internal/session";
import CobaltAPI from "./internal/base-api";
import { CobaltRequest } from "./types/request";
import { CobaltAuthError } from "./types/errors";
import type { TurnstileObject } from "turnstile-types";
export class TurnstileCobaltAPI extends CobaltAPI {
#session: CobaltSessionHandler;
#instanceHasTurnstile = true;
constructor(turnstile: TurnstileObject) {
super();
this.#session = new CobaltSessionHandler(this, turnstile);
}
needsSession() {
return this.#instanceHasTurnstile && !this.#session.hasSession();
}
setBaseURL(baseURL: string): string {
if (this.#session && super.getBaseURL() !== super.setBaseURL(baseURL)) {
this.#session.reset();
}
return super.getBaseURL()!;
}
async request(data: CobaltRequest) {
const headers: Record<string, string> = {};
if (this.#instanceHasTurnstile) {
const sessionOrError = await this.#session.getSession();
if ("error" in sessionOrError) {
if (sessionOrError.error.code !== CobaltAuthError.NotConfigured) {
return sessionOrError;
} else {
this.#instanceHasTurnstile = false;
}
} else {
headers['Authorization'] = `Bearer ${sessionOrError.token}`;
}
}
return super.request(data, headers);
}
}

View File

@@ -0,0 +1,67 @@
export enum CobaltAuthError {
NotConfigured = 'error.api.auth.not_configured',
JWTMissing = 'error.api.auth.jwt.missing',
JWTInvalid = 'error.api.auth.jwt.invalid',
TurnstileMissing = 'error.api.auth.turnstile.missing',
TurnstileInvalid = 'api.auth.turnstile.invalid'
};
export enum CobaltReachabilityError {
Unreachable = 'error.api.unreachable',
TimedOut = 'error.api.timed_out',
RateExceeded = 'error.api.rate_exceeded',
AtCapacity = 'error.api.capacity'
};
export enum CobaltGenericError {
Generic = 'error.api.generic',
UnknownResponse = 'error.api.unknown_response'
};
export enum CobaltServiceError {
Unsupported = 'error.api.service.unsupported',
Disabled = 'error.api.service.disabled'
};
export enum CobaltLinkError {
Invalid = 'error.api.link.invalid',
FormatUnsupported = 'error.api.link.unsupported'
};
export enum CobaltProcessingError {
Fail = 'error.api.fetch.fail',
Critical = 'error.api.fetch.critical',
Empty = 'error.api.fetch.empty',
RateLimited = 'error.api.fetch.rate',
ShortLink = 'error.api.fetch.short_link'
};
export enum CobaltContentError {
TooLong = 'error.api.content.too_long',
VideoUnavailable = 'error.api.content.video.unavailable',
VideoIsLive = 'error.api.content.video.live',
VideoIsPrivate = 'error.api.content.video.private',
VideoIsAgeRestricted = 'error.api.content.video.age',
VideoIsRegionRestricted = 'error.api.content.video.region',
PostUnavailable = 'error.api.content.post.unavailable',
PostIsPrivate = 'error.api.content.post.private',
PostIsAgeRestricted = 'error.api.content.post.age',
};
export enum CobaltYouTubeError {
MissingCodec = 'error.api.youtube.codec',
CannotDecipher = 'error.api.youtube.decipher',
MissingLogin = 'error.api.youtube.login',
TokenExpired = 'error.api.youtube.token_expired'
}
export type CobaltAPIErrorCode = CobaltAuthError
| CobaltReachabilityError
| CobaltGenericError
| CobaltServiceError
| CobaltLinkError
| CobaltProcessingError
| CobaltContentError
| CobaltYouTubeError;

View File

@@ -0,0 +1,8 @@
import { CobaltRequest } from "./request";
import { CobaltResponse } from "./response";
export interface CobaltAPIClient {
request(data: CobaltRequest): Promise<CobaltResponse>;
getBaseURL(): string | undefined;
setBaseURL(baseURL: string): string;
}

View File

@@ -0,0 +1,46 @@
import { z } from "zod";
// FIXME: this is duplicated from api/src/processing/schema.js
// (minus defaults) until the api is converted to TS
const apiSchema = z.object({
url: z.string()
.min(1),
audioBitrate: z.enum(
["320", "256", "128", "96", "64", "8"]
).optional(),
audioFormat: z.enum(
["best", "mp3", "ogg", "wav", "opus"]
).optional(),
downloadMode: z.enum(
["auto", "audio", "mute"]
).optional(),
filenameStyle: z.enum(
["classic", "pretty", "basic", "nerdy"]
).optional(),
youtubeVideoCodec: z.enum(
["h264", "av1", "vp9"]
).optional(),
videoQuality: z.enum(
["max", "4320", "2160", "1440", "1080", "720", "480", "360", "240", "144"]
).optional(),
youtubeDubLang: z.string()
.length(2)
.optional(),
alwaysProxy: z.boolean().optional(),
disableMetadata: z.boolean().optional(),
tiktokFullAudio: z.boolean().optional(),
tiktokH265: z.boolean().optional(),
twitterGif: z.boolean().optional(),
youtubeDubBrowserLang: z.boolean().optional()
})
.strict();
export type CobaltRequest = z.infer<typeof apiSchema>;

View File

@@ -0,0 +1,71 @@
import { CobaltAPIErrorCode } from "./errors";
export enum CobaltResponseType {
Error = 'error',
Picker = 'picker',
Redirect = 'redirect',
Tunnel = 'tunnel',
}
export type CobaltErrorResponse = {
status: CobaltResponseType.Error,
error: {
code: CobaltAPIErrorCode,
context?: {
service?: string,
limit?: number,
}
},
};
type CobaltPartialURLResponse = {
url: string,
filename: string,
}
type CobaltPickerResponse = {
status: CobaltResponseType.Picker
picker: {
type: 'photo' | 'video' | 'gif',
url: string,
thumb?: string,
}[];
audio?: string,
audioFilename?: string,
};
type CobaltRedirectResponse = {
status: CobaltResponseType.Redirect,
} & CobaltPartialURLResponse;
type CobaltTunnelResponse = {
status: CobaltResponseType.Tunnel,
} & CobaltPartialURLResponse;
export type CobaltSession = {
token: string,
exp: number,
}
export type CobaltServerInfo = {
cobalt: {
version: string,
url: string,
startTime: string,
durationLimit: number,
services: string[]
},
git: {
branch: string,
commit: string,
remote: string,
}
}
export type CobaltSessionResponse = CobaltSession | CobaltErrorResponse;
export type CobaltServerInfoResponse = CobaltServerInfo | CobaltErrorResponse;
export type CobaltResponse = CobaltErrorResponse
| CobaltPickerResponse
| CobaltRedirectResponse
| CobaltTunnelResponse;

View File

@@ -0,0 +1,9 @@
import CobaltAPI from "./internal/base-api";
import { CobaltRequest } from "./types/request";
import { CobaltAPIClient } from "./types/interface";
export class UnauthenticatedCobaltAPI extends CobaltAPI implements CobaltAPIClient {
async request(data: CobaltRequest) {
return super.request(data, {});
}
}

View File

@@ -0,0 +1,14 @@
{
"include": ["src"],
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"rootDir": "./src",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"outDir": "./dist"
}
}

6
packages/version-info/index.d.ts vendored Normal file
View File

@@ -0,0 +1,6 @@
declare module "@imput/version-info" {
export function getCommit(): Promise<string | undefined>;
export function getBranch(): Promise<string | undefined>;
export function getRemote(): Promise<string>;
export function getVersion(): Promise<string>;
}

View File

@@ -0,0 +1,78 @@
import { existsSync } from 'node:fs';
import { join, parse } from 'node:path';
import { cwd } from 'node:process';
import { readFile } from 'node:fs/promises';
const findFile = (file) => {
let dir = cwd();
while (dir !== parse(dir).root) {
if (existsSync(join(dir, file))) {
return dir;
}
dir = join(dir, '../');
}
}
const root = findFile('.git');
const pack = findFile('package.json');
const readGit = (filename) => {
if (!root) {
throw 'no git repository root found';
}
return readFile(join(root, filename), 'utf8');
}
export const getCommit = async () => {
return (await readGit('.git/logs/HEAD'))
?.split('\n')
?.filter(String)
?.pop()
?.split(' ')[1];
}
export const getBranch = async () => {
if (process.env.CF_PAGES_BRANCH) {
return process.env.CF_PAGES_BRANCH;
}
return (await readGit('.git/HEAD'))
?.replace(/^ref: refs\/heads\//, '')
?.trim();
}
export const getRemote = async () => {
let remote = (await readGit('.git/config'))
?.split('\n')
?.find(line => line.includes('url = '))
?.split('url = ')[1];
if (remote?.startsWith('git@')) {
remote = remote.split(':')[1];
} else if (remote?.startsWith('http')) {
remote = new URL(remote).pathname.substring(1);
}
remote = remote?.replace(/\.git$/, '');
if (!remote) {
throw 'could not parse remote';
}
return remote;
}
export const getVersion = async () => {
if (!pack) {
throw 'no package root found';
}
const { version } = JSON.parse(
await readFile(join(pack, 'package.json'), 'utf8')
);
return version;
}

View File

@@ -0,0 +1,18 @@
{
"name": "@imput/version-info",
"version": "1.0.0",
"description": "helper package for cobalt that provides commit info & version from package file.",
"main": "index.js",
"types": "index.d.ts",
"type": "module",
"repository": {
"type": "git",
"url": "git+https://github.com/imputnet/cobalt.git"
},
"author": "imput",
"license": "AGPL-3.0",
"bugs": {
"url": "https://github.com/imputnet/cobalt/issues"
},
"homepage": "https://github.com/imputnet/cobalt#readme"
}

4201
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

4
pnpm-workspace.yaml Normal file
View File

@@ -0,0 +1,4 @@
packages:
- "api"
- "web"
- "packages/*"

View File

@@ -1,38 +0,0 @@
import "dotenv/config";
import "./modules/sub/alias-envs.js";
import express from "express";
import { Bright, Green, Red } from "./modules/sub/consoleText.js";
import { getCurrentBranch, shortCommit } from "./modules/sub/currentCommit.js";
import { loadLoc } from "./localization/manager.js";
import { mode } from "./modules/config.js"
import path from 'path';
import { fileURLToPath } from 'url';
const app = express();
const gitCommit = shortCommit();
const gitBranch = getCurrentBranch();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename).slice(0, -4);
app.disable('x-powered-by');
await loadLoc();
if (mode === 'API') {
const { runAPI } = await import('./core/api.js');
runAPI(express, app, gitCommit, gitBranch, __dirname)
} else if (mode === 'WEB') {
const { runWeb } = await import('./core/web.js');
await runWeb(express, app, gitCommit, gitBranch, __dirname)
} else {
console.log(
Red(`cobalt wasn't configured yet or configuration is invalid.\n`)
+ Bright(`please run the setup script to fix this: `)
+ Green(`npm run setup`)
)
}

View File

@@ -1,103 +0,0 @@
{
"genericUserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"authorInfo": {
"support": {
"default": {
"email": {
"emoji": "📧",
"url": "mailto:support@cobalt.tools",
"name": "support@cobalt.tools"
},
"twitter": {
"emoji": "🐦",
"url": "https://twitter.com/justusecobalt",
"name": "@justusecobalt"
},
"discord": {
"emoji": "👾",
"url": "https://discord.gg/pQPt8HBUPu",
"name": "cobalt discord server"
}
},
"ru": {
"telegram": {
"emoji": "📬",
"url": "https://t.me/justusecobalt_ru",
"name": "канал в telegram"
},
"email": {
"emoji": "📧",
"url": "mailto:support@cobalt.tools",
"name": "support@cobalt.tools"
}
}
}
},
"donations": {
"crypto": {
"monero": "4B1SNB6s8Pq1hxjNeKPEe8Qa8EP3zdL16Sqsa7QDoJcUecKQzEj9BMxWnEnTGu12doKLJBKRDUqnn6V9qfSdXpXi3Nw5Uod",
"litecoin": "ltc1qvp0xhrk2m7pa6p6z844qcslfyxv4p3vf95rhna",
"ethereum": "0x4B4cF23051c78c7A7E0eA09d39099621c46bc302",
"usdt-erc20": "0x4B4cF23051c78c7A7E0eA09d39099621c46bc302",
"usdt-trc20": "TVbx7YT3rBfu931Gxko6pRfXtedYqbgnBB",
"bitcoin": "bc1qlvcnlnyzfsgnuxyxsv3k0p0q0yln0azjpadyx4",
"bitcoin-alt": "18PKf6N2cHrmSzz9ZzTSvDd2jAkqGC7SxA",
"ton": "UQA3SO-hHZq1oCCT--u6or6ollB8fd2o52aD8mXiLk9iDZd3"
},
"links": {
"boosty": "https://boosty.to/wukko/donate"
}
},
"links": {
"saveToGalleryShortcut": "https://www.icloud.com/shortcuts/14e9aebf04b24156acc34ceccf7e6fcd",
"saveToFilesShortcut": "https://www.icloud.com/shortcuts/2134cd9d4d6b41448b2201f933542b2e",
"statusPage": "https://status.cobalt.tools/",
"troubleshootingGuide": "https://github.com/imputnet/cobalt/blob/current/docs/troubleshooting.md"
},
"celebrations": {
"01-01": "🎄",
"02-17": "😺",
"02-22": "😺",
"03-01": "😺",
"03-08": "💪",
"05-26": "🎂",
"08-08": "😺",
"08-26": "🐶",
"10-29": "😺",
"10-30": "🎃",
"10-31": "🎃",
"11-01": "🕯️",
"11-02": "🕯️",
"12-20": "🎄",
"12-21": "🎄",
"12-22": "🎄",
"12-23": "🎄",
"12-24": "🎄",
"12-25": "🎄",
"12-26": "🎄",
"12-27": "🎄",
"12-28": "🎄",
"12-29": "🎄",
"12-30": "🎄",
"12-31": "🎄"
},
"supportedAudio": ["mp3", "ogg", "wav", "opus"],
"ffmpegArgs": {
"webm": ["-c:v", "copy", "-c:a", "copy"],
"mp4": ["-c:v", "copy", "-c:a", "copy", "-movflags", "faststart+frag_keyframe+empty_moov"],
"copy": ["-c:a", "copy"],
"audio": ["-ar", "48000", "-ac", "2", "-b:a", "320k"],
"m4a": ["-movflags", "frag_keyframe+empty_moov"],
"gif": ["-vf", "scale=-1:-1:flags=lanczos,split[s0][s1];[s0]palettegen[p];[s1][p]paletteuse", "-loop", "0"]
},
"sponsors": [{
"name": "royale",
"fullName": "RoyaleHosting",
"url": "https://royalehosting.net/?partner=cobalt",
"logo": {
"width": 605,
"height": 136,
"scale": 5
}
}]
}

View File

@@ -1,228 +0,0 @@
import cors from "cors";
import rateLimit from "express-rate-limit";
import { setGlobalDispatcher, ProxyAgent } from "undici";
import { env, version } from "../modules/config.js";
import { generateHmac, generateSalt } from "../modules/sub/crypto.js";
import { Bright, Cyan } from "../modules/sub/consoleText.js";
import { languageCode } from "../modules/sub/utils.js";
import loc from "../localization/manager.js";
import { createResponse, normalizeRequest, getIP } from "../modules/processing/request.js";
import { verifyStream, getInternalStream } from "../modules/stream/manage.js";
import { randomizeCiphers } from '../modules/sub/randomize-ciphers.js';
import { extract } from "../modules/processing/url.js";
import match from "../modules/processing/match.js";
import stream from "../modules/stream/stream.js";
const acceptRegex = /^application\/json(; charset=utf-8)?$/;
const ipSalt = generateSalt();
const corsConfig = env.corsWildcard ? {} : {
origin: env.corsURL,
optionsSuccessStatus: 200
}
export function runAPI(express, app, gitCommit, gitBranch, __dirname) {
const startTime = new Date();
const startTimestamp = startTime.getTime();
const serverInfo = {
version: version,
commit: gitCommit,
branch: gitBranch,
name: env.apiName,
url: env.apiURL,
cors: Number(env.corsWildcard),
startTime: `${startTimestamp}`
}
const apiLimiter = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.status(429).json({
"status": "rate-limit",
"text": loc(languageCode(req), 'ErrorRateLimit', env.rateLimitWindow)
});
}
})
const apiLimiterStream = rateLimit({
windowMs: env.rateLimitWindow * 1000,
max: env.rateLimitMax,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: req => generateHmac(getIP(req), ipSalt),
handler: (req, res) => {
return res.sendStatus(429)
}
})
app.set('trust proxy', ['loopback', 'uniquelocal']);
app.use('/api', cors({
methods: ['GET', 'POST'],
exposedHeaders: [
'Ratelimit-Limit',
'Ratelimit-Policy',
'Ratelimit-Remaining',
'Ratelimit-Reset'
],
...corsConfig,
}))
app.use('/api/json', apiLimiter);
app.use('/api/stream', apiLimiterStream);
app.use((req, res, next) => {
try {
decodeURIComponent(req.path)
} catch {
return res.redirect('/')
}
next();
})
app.use('/api/json', express.json({ limit: 1024 }));
app.use('/api/json', (err, _, res, next) => {
if (err) {
return res.status(400).json({
status: "error",
text: "invalid json body"
});
}
next();
});
app.post('/api/json', async (req, res) => {
const request = req.body;
const lang = languageCode(req);
const fail = (t) => {
const { status, body } = createResponse("error", { t: loc(lang, t) });
res.status(status).json(body);
}
if (!acceptRegex.test(req.header('Accept'))) {
return fail('ErrorInvalidAcceptHeader');
}
if (!acceptRegex.test(req.header('Content-Type'))) {
return fail('ErrorInvalidContentType');
}
if (!request.url) {
return fail('ErrorNoLink');
}
request.dubLang = request.dubLang ? lang : false;
const normalizedRequest = normalizeRequest(request);
if (!normalizedRequest) {
return fail('ErrorCantProcess');
}
const parsed = extract(normalizedRequest.url);
if (parsed === null) {
return fail('ErrorUnsupported');
}
try {
const result = await match(
parsed.host, parsed.patternMatch, lang, normalizedRequest
);
res.status(result.status).json(result.body);
} catch {
fail('ErrorSomethingWentWrong');
}
})
app.get('/api/stream', (req, res) => {
const id = String(req.query.id);
const exp = String(req.query.exp);
const sig = String(req.query.sig);
const sec = String(req.query.sec);
const iv = String(req.query.iv);
const checkQueries = id && exp && sig && sec && iv;
const checkBaseLength = id.length === 21 && exp.length === 13;
const checkSafeLength = sig.length === 43 && sec.length === 43 && iv.length === 22;
if (!checkQueries || !checkBaseLength || !checkSafeLength) {
return res.sendStatus(400);
}
// rate limit probe, will not return json after 8.0
if (req.query.p) {
return res.status(200).json({
status: "continue"
})
}
const streamInfo = verifyStream(id, sig, exp, sec, iv);
if (!streamInfo?.service) {
return res.sendStatus(streamInfo.status);
}
return stream(res, streamInfo);
})
app.get('/api/istream', (req, res) => {
if (!req.ip.endsWith('127.0.0.1')) {
return res.sendStatus(403);
}
if (String(req.query.id).length !== 21) {
return res.sendStatus(400);
}
const streamInfo = getInternalStream(req.query.id);
if (!streamInfo) {
return res.sendStatus(404);
}
streamInfo.headers = new Map([
...(streamInfo.headers || []),
...Object.entries(req.headers)
]);
return stream(res, { type: 'internal', ...streamInfo });
})
app.get('/api/serverInfo', (_, res) => {
return res.status(200).json(serverInfo);
})
app.get('/favicon.ico', (req, res) => {
res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
})
app.get('/*', (req, res) => {
res.redirect('/api/serverInfo')
})
randomizeCiphers();
setInterval(randomizeCiphers, 1000 * 60 * 30); // shuffle ciphers every 30 minutes
if (env.externalProxy) {
if (env.freebindCIDR) {
throw new Error('Freebind is not available when external proxy is enabled')
}
setGlobalDispatcher(new ProxyAgent(env.externalProxy))
}
app.listen(env.apiPort, env.listenAddress, () => {
console.log(`\n` +
`${Cyan("cobalt")} API ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${env.apiURL}`)}\n` +
`Port: ${env.apiPort}\n`
)
})
}

View File

@@ -1,97 +0,0 @@
import { Bright, Cyan } from "../modules/sub/consoleText.js";
import { languageCode } from "../modules/sub/utils.js";
import { version, env } from "../modules/config.js";
import { buildFront } from "../modules/build.js";
import findRendered from "../modules/pageRender/findRendered.js";
import { celebrationsEmoji } from "../modules/pageRender/elements.js";
import { changelogHistory } from "../modules/pageRender/onDemand.js";
import { createResponse } from "../modules/processing/request.js";
export async function runWeb(express, app, gitCommit, gitBranch, __dirname) {
const startTime = new Date();
const startTimestamp = Math.floor(startTime.getTime());
await buildFront(gitCommit, gitBranch);
app.use('/', express.static('./build/min'));
app.use('/', express.static('./src/front'));
app.use((req, res, next) => {
try { decodeURIComponent(req.path) } catch (e) { return res.redirect('/') }
next();
})
app.get('/onDemand', (req, res) => {
try {
if (typeof req.query.blockId !== 'string') {
return res.status(400).json({
status: "error",
text: "couldn't render this block, please try again!"
});
}
let blockId = req.query.blockId.slice(0, 3);
let blockData;
switch(blockId) {
// changelog history
case "0":
let history = changelogHistory();
if (history) {
blockData = createResponse("success", { t: history })
} else {
blockData = createResponse("error", {
t: "couldn't render this block, please try again!"
})
}
break;
// celebrations emoji
case "1":
let celebration = celebrationsEmoji();
if (celebration) {
blockData = createResponse("success", { t: celebration })
}
break;
default:
blockData = createResponse("error", {
t: "couldn't find a block with this id"
})
break;
}
if (blockData?.body) {
return res.status(blockData.status).json(blockData.body);
} else {
return res.status(204).end();
}
} catch {
return res.status(400).json({
status: "error",
text: "couldn't render this block, please try again!"
})
}
})
app.get("/", (req, res) => {
return res.sendFile(`${__dirname}/${findRendered(languageCode(req))}`)
})
app.get("/favicon.ico", (req, res) => {
return res.sendFile(`${__dirname}/src/front/icons/favicon.ico`)
})
app.get("/*", (req, res) => {
return res.redirect('/')
})
app.listen(env.webPort, () => {
console.log(`\n` +
`${Cyan("cobalt")} WEB ${Bright(`v.${version}-${gitCommit} (${gitBranch})`)}\n` +
`Start time: ${Bright(`${startTime.toUTCString()} (${startTimestamp})`)}\n\n` +
`URL: ${Cyan(`${env.webURL}`)}\n` +
`Port: ${env.webPort}\n`
)
})
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 21 KiB

File diff suppressed because it is too large Load Diff

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